renderer_scene_render_rd.cpp 353 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183
  1. /*************************************************************************/
  2. /* renderer_scene_render_rd.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "renderer_scene_render_rd.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/os/os.h"
  33. #include "renderer_compositor_rd.h"
  34. #include "servers/rendering/rendering_server_default.h"
  35. uint64_t RendererSceneRenderRD::auto_exposure_counter = 2;
  36. void get_vogel_disk(float *r_kernel, int p_sample_count) {
  37. const float golden_angle = 2.4;
  38. for (int i = 0; i < p_sample_count; i++) {
  39. float r = Math::sqrt(float(i) + 0.5) / Math::sqrt(float(p_sample_count));
  40. float theta = float(i) * golden_angle;
  41. r_kernel[i * 4] = Math::cos(theta) * r;
  42. r_kernel[i * 4 + 1] = Math::sin(theta) * r;
  43. }
  44. }
  45. void RendererSceneRenderRD::_clear_reflection_data(ReflectionData &rd) {
  46. rd.layers.clear();
  47. rd.radiance_base_cubemap = RID();
  48. if (rd.downsampled_radiance_cubemap.is_valid()) {
  49. RD::get_singleton()->free(rd.downsampled_radiance_cubemap);
  50. }
  51. rd.downsampled_radiance_cubemap = RID();
  52. rd.downsampled_layer.mipmaps.clear();
  53. rd.coefficient_buffer = RID();
  54. }
  55. void RendererSceneRenderRD::_update_reflection_data(ReflectionData &rd, int p_size, int p_mipmaps, bool p_use_array, RID p_base_cube, int p_base_layer, bool p_low_quality) {
  56. //recreate radiance and all data
  57. int mipmaps = p_mipmaps;
  58. uint32_t w = p_size, h = p_size;
  59. if (p_use_array) {
  60. int layers = p_low_quality ? 8 : roughness_layers;
  61. for (int i = 0; i < layers; i++) {
  62. ReflectionData::Layer layer;
  63. uint32_t mmw = w;
  64. uint32_t mmh = h;
  65. layer.mipmaps.resize(mipmaps);
  66. layer.views.resize(mipmaps);
  67. for (int j = 0; j < mipmaps; j++) {
  68. ReflectionData::Layer::Mipmap &mm = layer.mipmaps.write[j];
  69. mm.size.width = mmw;
  70. mm.size.height = mmh;
  71. for (int k = 0; k < 6; k++) {
  72. mm.views[k] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + i * 6 + k, j);
  73. Vector<RID> fbtex;
  74. fbtex.push_back(mm.views[k]);
  75. mm.framebuffers[k] = RD::get_singleton()->framebuffer_create(fbtex);
  76. }
  77. layer.views.write[j] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + i * 6, j, RD::TEXTURE_SLICE_CUBEMAP);
  78. mmw = MAX(1, mmw >> 1);
  79. mmh = MAX(1, mmh >> 1);
  80. }
  81. rd.layers.push_back(layer);
  82. }
  83. } else {
  84. mipmaps = p_low_quality ? 8 : mipmaps;
  85. //regular cubemap, lower quality (aliasing, less memory)
  86. ReflectionData::Layer layer;
  87. uint32_t mmw = w;
  88. uint32_t mmh = h;
  89. layer.mipmaps.resize(mipmaps);
  90. layer.views.resize(mipmaps);
  91. for (int j = 0; j < mipmaps; j++) {
  92. ReflectionData::Layer::Mipmap &mm = layer.mipmaps.write[j];
  93. mm.size.width = mmw;
  94. mm.size.height = mmh;
  95. for (int k = 0; k < 6; k++) {
  96. mm.views[k] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + k, j);
  97. Vector<RID> fbtex;
  98. fbtex.push_back(mm.views[k]);
  99. mm.framebuffers[k] = RD::get_singleton()->framebuffer_create(fbtex);
  100. }
  101. layer.views.write[j] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer, j, RD::TEXTURE_SLICE_CUBEMAP);
  102. mmw = MAX(1, mmw >> 1);
  103. mmh = MAX(1, mmh >> 1);
  104. }
  105. rd.layers.push_back(layer);
  106. }
  107. rd.radiance_base_cubemap = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer, 0, RD::TEXTURE_SLICE_CUBEMAP);
  108. RD::TextureFormat tf;
  109. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  110. tf.width = 64; // Always 64x64
  111. tf.height = 64;
  112. tf.texture_type = RD::TEXTURE_TYPE_CUBE;
  113. tf.array_layers = 6;
  114. tf.mipmaps = 7;
  115. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  116. rd.downsampled_radiance_cubemap = RD::get_singleton()->texture_create(tf, RD::TextureView());
  117. {
  118. uint32_t mmw = 64;
  119. uint32_t mmh = 64;
  120. rd.downsampled_layer.mipmaps.resize(7);
  121. for (int j = 0; j < rd.downsampled_layer.mipmaps.size(); j++) {
  122. ReflectionData::DownsampleLayer::Mipmap &mm = rd.downsampled_layer.mipmaps.write[j];
  123. mm.size.width = mmw;
  124. mm.size.height = mmh;
  125. mm.view = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rd.downsampled_radiance_cubemap, 0, j, RD::TEXTURE_SLICE_CUBEMAP);
  126. mmw = MAX(1, mmw >> 1);
  127. mmh = MAX(1, mmh >> 1);
  128. }
  129. }
  130. }
  131. void RendererSceneRenderRD::_create_reflection_fast_filter(ReflectionData &rd, bool p_use_arrays) {
  132. storage->get_effects()->cubemap_downsample(rd.radiance_base_cubemap, rd.downsampled_layer.mipmaps[0].view, rd.downsampled_layer.mipmaps[0].size);
  133. for (int i = 1; i < rd.downsampled_layer.mipmaps.size(); i++) {
  134. storage->get_effects()->cubemap_downsample(rd.downsampled_layer.mipmaps[i - 1].view, rd.downsampled_layer.mipmaps[i].view, rd.downsampled_layer.mipmaps[i].size);
  135. }
  136. Vector<RID> views;
  137. if (p_use_arrays) {
  138. for (int i = 1; i < rd.layers.size(); i++) {
  139. views.push_back(rd.layers[i].views[0]);
  140. }
  141. } else {
  142. for (int i = 1; i < rd.layers[0].views.size(); i++) {
  143. views.push_back(rd.layers[0].views[i]);
  144. }
  145. }
  146. storage->get_effects()->cubemap_filter(rd.downsampled_radiance_cubemap, views, p_use_arrays);
  147. }
  148. void RendererSceneRenderRD::_create_reflection_importance_sample(ReflectionData &rd, bool p_use_arrays, int p_cube_side, int p_base_layer) {
  149. if (p_use_arrays) {
  150. //render directly to the layers
  151. storage->get_effects()->cubemap_roughness(rd.radiance_base_cubemap, rd.layers[p_base_layer].views[0], p_cube_side, sky_ggx_samples_quality, float(p_base_layer) / (rd.layers.size() - 1.0), rd.layers[p_base_layer].mipmaps[0].size.x);
  152. } else {
  153. storage->get_effects()->cubemap_roughness(rd.layers[0].views[p_base_layer - 1], rd.layers[0].views[p_base_layer], p_cube_side, sky_ggx_samples_quality, float(p_base_layer) / (rd.layers[0].mipmaps.size() - 1.0), rd.layers[0].mipmaps[p_base_layer].size.x);
  154. }
  155. }
  156. void RendererSceneRenderRD::_update_reflection_mipmaps(ReflectionData &rd, int p_start, int p_end) {
  157. for (int i = p_start; i < p_end; i++) {
  158. for (int j = 0; j < rd.layers[i].views.size() - 1; j++) {
  159. RID view = rd.layers[i].views[j];
  160. RID texture = rd.layers[i].views[j + 1];
  161. Size2i size = rd.layers[i].mipmaps[j + 1].size;
  162. storage->get_effects()->cubemap_downsample(view, texture, size);
  163. }
  164. }
  165. }
  166. void RendererSceneRenderRD::_sdfgi_erase(RenderBuffers *rb) {
  167. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  168. const SDFGI::Cascade &c = rb->sdfgi->cascades[i];
  169. RD::get_singleton()->free(c.light_data);
  170. RD::get_singleton()->free(c.light_aniso_0_tex);
  171. RD::get_singleton()->free(c.light_aniso_1_tex);
  172. RD::get_singleton()->free(c.sdf_tex);
  173. RD::get_singleton()->free(c.solid_cell_dispatch_buffer);
  174. RD::get_singleton()->free(c.solid_cell_buffer);
  175. RD::get_singleton()->free(c.lightprobe_history_tex);
  176. RD::get_singleton()->free(c.lightprobe_average_tex);
  177. RD::get_singleton()->free(c.lights_buffer);
  178. }
  179. RD::get_singleton()->free(rb->sdfgi->render_albedo);
  180. RD::get_singleton()->free(rb->sdfgi->render_emission);
  181. RD::get_singleton()->free(rb->sdfgi->render_emission_aniso);
  182. RD::get_singleton()->free(rb->sdfgi->render_sdf[0]);
  183. RD::get_singleton()->free(rb->sdfgi->render_sdf[1]);
  184. RD::get_singleton()->free(rb->sdfgi->render_sdf_half[0]);
  185. RD::get_singleton()->free(rb->sdfgi->render_sdf_half[1]);
  186. for (int i = 0; i < 8; i++) {
  187. RD::get_singleton()->free(rb->sdfgi->render_occlusion[i]);
  188. }
  189. RD::get_singleton()->free(rb->sdfgi->render_geom_facing);
  190. RD::get_singleton()->free(rb->sdfgi->lightprobe_data);
  191. RD::get_singleton()->free(rb->sdfgi->lightprobe_history_scroll);
  192. RD::get_singleton()->free(rb->sdfgi->occlusion_data);
  193. RD::get_singleton()->free(rb->sdfgi->ambient_texture);
  194. RD::get_singleton()->free(rb->sdfgi->cascades_ubo);
  195. memdelete(rb->sdfgi);
  196. rb->sdfgi = nullptr;
  197. }
  198. const Vector3i RendererSceneRenderRD::SDFGI::Cascade::DIRTY_ALL = Vector3i(0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF);
  199. void RendererSceneRenderRD::sdfgi_update(RID p_render_buffers, RID p_environment, const Vector3 &p_world_position) {
  200. Environment *env = environment_owner.getornull(p_environment);
  201. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  202. bool needs_sdfgi = env && env->sdfgi_enabled;
  203. if (!needs_sdfgi) {
  204. if (rb->sdfgi != nullptr) {
  205. //erase it
  206. _sdfgi_erase(rb);
  207. _render_buffers_uniform_set_changed(p_render_buffers);
  208. }
  209. return;
  210. }
  211. static const uint32_t history_frames_to_converge[RS::ENV_SDFGI_CONVERGE_MAX] = { 5, 10, 15, 20, 25, 30 };
  212. uint32_t requested_history_size = history_frames_to_converge[sdfgi_frames_to_converge];
  213. if (rb->sdfgi && (rb->sdfgi->cascade_mode != env->sdfgi_cascades || rb->sdfgi->min_cell_size != env->sdfgi_min_cell_size || requested_history_size != rb->sdfgi->history_size || rb->sdfgi->uses_occlusion != env->sdfgi_use_occlusion || rb->sdfgi->y_scale_mode != env->sdfgi_y_scale)) {
  214. //configuration changed, erase
  215. _sdfgi_erase(rb);
  216. }
  217. SDFGI *sdfgi = rb->sdfgi;
  218. if (sdfgi == nullptr) {
  219. //re-create
  220. rb->sdfgi = memnew(SDFGI);
  221. sdfgi = rb->sdfgi;
  222. sdfgi->cascade_mode = env->sdfgi_cascades;
  223. sdfgi->min_cell_size = env->sdfgi_min_cell_size;
  224. sdfgi->uses_occlusion = env->sdfgi_use_occlusion;
  225. sdfgi->y_scale_mode = env->sdfgi_y_scale;
  226. static const float y_scale[3] = { 1.0, 1.5, 2.0 };
  227. sdfgi->y_mult = y_scale[sdfgi->y_scale_mode];
  228. static const int cascasde_size[3] = { 4, 6, 8 };
  229. sdfgi->cascades.resize(cascasde_size[sdfgi->cascade_mode]);
  230. sdfgi->probe_axis_count = SDFGI::PROBE_DIVISOR + 1;
  231. sdfgi->solid_cell_ratio = sdfgi_solid_cell_ratio;
  232. sdfgi->solid_cell_count = uint32_t(float(sdfgi->cascade_size * sdfgi->cascade_size * sdfgi->cascade_size) * sdfgi->solid_cell_ratio);
  233. float base_cell_size = sdfgi->min_cell_size;
  234. RD::TextureFormat tf_sdf;
  235. tf_sdf.format = RD::DATA_FORMAT_R8_UNORM;
  236. tf_sdf.width = sdfgi->cascade_size; // Always 64x64
  237. tf_sdf.height = sdfgi->cascade_size;
  238. tf_sdf.depth = sdfgi->cascade_size;
  239. tf_sdf.texture_type = RD::TEXTURE_TYPE_3D;
  240. tf_sdf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
  241. {
  242. RD::TextureFormat tf_render = tf_sdf;
  243. tf_render.format = RD::DATA_FORMAT_R16_UINT;
  244. sdfgi->render_albedo = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  245. tf_render.format = RD::DATA_FORMAT_R32_UINT;
  246. sdfgi->render_emission = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  247. sdfgi->render_emission_aniso = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  248. tf_render.format = RD::DATA_FORMAT_R8_UNORM; //at least its easy to visualize
  249. for (int i = 0; i < 8; i++) {
  250. sdfgi->render_occlusion[i] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  251. }
  252. tf_render.format = RD::DATA_FORMAT_R32_UINT;
  253. sdfgi->render_geom_facing = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  254. tf_render.format = RD::DATA_FORMAT_R8G8B8A8_UINT;
  255. sdfgi->render_sdf[0] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  256. sdfgi->render_sdf[1] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  257. tf_render.width /= 2;
  258. tf_render.height /= 2;
  259. tf_render.depth /= 2;
  260. sdfgi->render_sdf_half[0] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  261. sdfgi->render_sdf_half[1] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  262. }
  263. RD::TextureFormat tf_occlusion = tf_sdf;
  264. tf_occlusion.format = RD::DATA_FORMAT_R16_UINT;
  265. tf_occlusion.shareable_formats.push_back(RD::DATA_FORMAT_R16_UINT);
  266. tf_occlusion.shareable_formats.push_back(RD::DATA_FORMAT_R4G4B4A4_UNORM_PACK16);
  267. tf_occlusion.depth *= sdfgi->cascades.size(); //use depth for occlusion slices
  268. tf_occlusion.width *= 2; //use width for the other half
  269. RD::TextureFormat tf_light = tf_sdf;
  270. tf_light.format = RD::DATA_FORMAT_R32_UINT;
  271. tf_light.shareable_formats.push_back(RD::DATA_FORMAT_R32_UINT);
  272. tf_light.shareable_formats.push_back(RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32);
  273. RD::TextureFormat tf_aniso0 = tf_sdf;
  274. tf_aniso0.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  275. RD::TextureFormat tf_aniso1 = tf_sdf;
  276. tf_aniso1.format = RD::DATA_FORMAT_R8G8_UNORM;
  277. int passes = nearest_shift(sdfgi->cascade_size) - 1;
  278. //store lightprobe SH
  279. RD::TextureFormat tf_probes;
  280. tf_probes.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  281. tf_probes.width = sdfgi->probe_axis_count * sdfgi->probe_axis_count;
  282. tf_probes.height = sdfgi->probe_axis_count * SDFGI::SH_SIZE;
  283. tf_probes.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
  284. tf_probes.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
  285. sdfgi->history_size = requested_history_size;
  286. RD::TextureFormat tf_probe_history = tf_probes;
  287. tf_probe_history.format = RD::DATA_FORMAT_R16G16B16A16_SINT; //signed integer because SH are signed
  288. tf_probe_history.array_layers = sdfgi->history_size;
  289. RD::TextureFormat tf_probe_average = tf_probes;
  290. tf_probe_average.format = RD::DATA_FORMAT_R32G32B32A32_SINT; //signed integer because SH are signed
  291. tf_probe_average.texture_type = RD::TEXTURE_TYPE_2D;
  292. sdfgi->lightprobe_history_scroll = RD::get_singleton()->texture_create(tf_probe_history, RD::TextureView());
  293. sdfgi->lightprobe_average_scroll = RD::get_singleton()->texture_create(tf_probe_average, RD::TextureView());
  294. {
  295. //octahedral lightprobes
  296. RD::TextureFormat tf_octprobes = tf_probes;
  297. tf_octprobes.array_layers = sdfgi->cascades.size() * 2;
  298. tf_octprobes.format = RD::DATA_FORMAT_R32_UINT; //pack well with RGBE
  299. tf_octprobes.width = sdfgi->probe_axis_count * sdfgi->probe_axis_count * (SDFGI::LIGHTPROBE_OCT_SIZE + 2);
  300. tf_octprobes.height = sdfgi->probe_axis_count * (SDFGI::LIGHTPROBE_OCT_SIZE + 2);
  301. tf_octprobes.shareable_formats.push_back(RD::DATA_FORMAT_R32_UINT);
  302. tf_octprobes.shareable_formats.push_back(RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32);
  303. //lightprobe texture is an octahedral texture
  304. sdfgi->lightprobe_data = RD::get_singleton()->texture_create(tf_octprobes, RD::TextureView());
  305. RD::TextureView tv;
  306. tv.format_override = RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32;
  307. sdfgi->lightprobe_texture = RD::get_singleton()->texture_create_shared(tv, sdfgi->lightprobe_data);
  308. //texture handling ambient data, to integrate with volumetric foc
  309. RD::TextureFormat tf_ambient = tf_probes;
  310. tf_ambient.array_layers = sdfgi->cascades.size();
  311. tf_ambient.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT; //pack well with RGBE
  312. tf_ambient.width = sdfgi->probe_axis_count * sdfgi->probe_axis_count;
  313. tf_ambient.height = sdfgi->probe_axis_count;
  314. tf_ambient.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
  315. //lightprobe texture is an octahedral texture
  316. sdfgi->ambient_texture = RD::get_singleton()->texture_create(tf_ambient, RD::TextureView());
  317. }
  318. sdfgi->cascades_ubo = RD::get_singleton()->uniform_buffer_create(sizeof(SDFGI::Cascade::UBO) * SDFGI::MAX_CASCADES);
  319. sdfgi->occlusion_data = RD::get_singleton()->texture_create(tf_occlusion, RD::TextureView());
  320. {
  321. RD::TextureView tv;
  322. tv.format_override = RD::DATA_FORMAT_R4G4B4A4_UNORM_PACK16;
  323. sdfgi->occlusion_texture = RD::get_singleton()->texture_create_shared(tv, sdfgi->occlusion_data);
  324. }
  325. for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
  326. SDFGI::Cascade &cascade = sdfgi->cascades[i];
  327. /* 3D Textures */
  328. cascade.sdf_tex = RD::get_singleton()->texture_create(tf_sdf, RD::TextureView());
  329. cascade.light_data = RD::get_singleton()->texture_create(tf_light, RD::TextureView());
  330. cascade.light_aniso_0_tex = RD::get_singleton()->texture_create(tf_aniso0, RD::TextureView());
  331. cascade.light_aniso_1_tex = RD::get_singleton()->texture_create(tf_aniso1, RD::TextureView());
  332. {
  333. RD::TextureView tv;
  334. tv.format_override = RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32;
  335. cascade.light_tex = RD::get_singleton()->texture_create_shared(tv, cascade.light_data);
  336. RD::get_singleton()->texture_clear(cascade.light_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
  337. RD::get_singleton()->texture_clear(cascade.light_aniso_0_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
  338. RD::get_singleton()->texture_clear(cascade.light_aniso_1_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
  339. }
  340. cascade.cell_size = base_cell_size;
  341. Vector3 world_position = p_world_position;
  342. world_position.y *= sdfgi->y_mult;
  343. int32_t probe_cells = sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  344. Vector3 probe_size = Vector3(1, 1, 1) * cascade.cell_size * probe_cells;
  345. Vector3i probe_pos = Vector3i((world_position / probe_size + Vector3(0.5, 0.5, 0.5)).floor());
  346. cascade.position = probe_pos * probe_cells;
  347. cascade.dirty_regions = SDFGI::Cascade::DIRTY_ALL;
  348. base_cell_size *= 2.0;
  349. /* Probe History */
  350. cascade.lightprobe_history_tex = RD::get_singleton()->texture_create(tf_probe_history, RD::TextureView());
  351. RD::get_singleton()->texture_clear(cascade.lightprobe_history_tex, Color(0, 0, 0, 0), 0, 1, 0, tf_probe_history.array_layers); //needs to be cleared for average to work
  352. cascade.lightprobe_average_tex = RD::get_singleton()->texture_create(tf_probe_average, RD::TextureView());
  353. RD::get_singleton()->texture_clear(cascade.lightprobe_average_tex, Color(0, 0, 0, 0), 0, 1, 0, 1); //needs to be cleared for average to work
  354. /* Buffers */
  355. cascade.solid_cell_buffer = RD::get_singleton()->storage_buffer_create(sizeof(SDFGI::Cascade::SolidCell) * sdfgi->solid_cell_count);
  356. cascade.solid_cell_dispatch_buffer = RD::get_singleton()->storage_buffer_create(sizeof(uint32_t) * 4, Vector<uint8_t>(), RD::STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT);
  357. cascade.lights_buffer = RD::get_singleton()->storage_buffer_create(sizeof(SDGIShader::Light) * MAX(SDFGI::MAX_STATIC_LIGHTS, SDFGI::MAX_DYNAMIC_LIGHTS));
  358. {
  359. Vector<RD::Uniform> uniforms;
  360. {
  361. RD::Uniform u;
  362. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  363. u.binding = 1;
  364. u.ids.push_back(sdfgi->render_sdf[(passes & 1) ? 1 : 0]); //if passes are even, we read from buffer 0, else we read from buffer 1
  365. uniforms.push_back(u);
  366. }
  367. {
  368. RD::Uniform u;
  369. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  370. u.binding = 2;
  371. u.ids.push_back(sdfgi->render_albedo);
  372. uniforms.push_back(u);
  373. }
  374. {
  375. RD::Uniform u;
  376. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  377. u.binding = 3;
  378. for (int j = 0; j < 8; j++) {
  379. u.ids.push_back(sdfgi->render_occlusion[j]);
  380. }
  381. uniforms.push_back(u);
  382. }
  383. {
  384. RD::Uniform u;
  385. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  386. u.binding = 4;
  387. u.ids.push_back(sdfgi->render_emission);
  388. uniforms.push_back(u);
  389. }
  390. {
  391. RD::Uniform u;
  392. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  393. u.binding = 5;
  394. u.ids.push_back(sdfgi->render_emission_aniso);
  395. uniforms.push_back(u);
  396. }
  397. {
  398. RD::Uniform u;
  399. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  400. u.binding = 6;
  401. u.ids.push_back(sdfgi->render_geom_facing);
  402. uniforms.push_back(u);
  403. }
  404. {
  405. RD::Uniform u;
  406. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  407. u.binding = 7;
  408. u.ids.push_back(cascade.sdf_tex);
  409. uniforms.push_back(u);
  410. }
  411. {
  412. RD::Uniform u;
  413. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  414. u.binding = 8;
  415. u.ids.push_back(sdfgi->occlusion_data);
  416. uniforms.push_back(u);
  417. }
  418. {
  419. RD::Uniform u;
  420. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  421. u.binding = 10;
  422. u.ids.push_back(cascade.solid_cell_dispatch_buffer);
  423. uniforms.push_back(u);
  424. }
  425. {
  426. RD::Uniform u;
  427. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  428. u.binding = 11;
  429. u.ids.push_back(cascade.solid_cell_buffer);
  430. uniforms.push_back(u);
  431. }
  432. cascade.sdf_store_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_STORE), 0);
  433. }
  434. {
  435. Vector<RD::Uniform> uniforms;
  436. {
  437. RD::Uniform u;
  438. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  439. u.binding = 1;
  440. u.ids.push_back(sdfgi->render_albedo);
  441. uniforms.push_back(u);
  442. }
  443. {
  444. RD::Uniform u;
  445. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  446. u.binding = 2;
  447. u.ids.push_back(sdfgi->render_geom_facing);
  448. uniforms.push_back(u);
  449. }
  450. {
  451. RD::Uniform u;
  452. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  453. u.binding = 3;
  454. u.ids.push_back(sdfgi->render_emission);
  455. uniforms.push_back(u);
  456. }
  457. {
  458. RD::Uniform u;
  459. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  460. u.binding = 4;
  461. u.ids.push_back(sdfgi->render_emission_aniso);
  462. uniforms.push_back(u);
  463. }
  464. {
  465. RD::Uniform u;
  466. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  467. u.binding = 5;
  468. u.ids.push_back(cascade.solid_cell_dispatch_buffer);
  469. uniforms.push_back(u);
  470. }
  471. {
  472. RD::Uniform u;
  473. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  474. u.binding = 6;
  475. u.ids.push_back(cascade.solid_cell_buffer);
  476. uniforms.push_back(u);
  477. }
  478. cascade.scroll_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_SCROLL), 0);
  479. }
  480. {
  481. Vector<RD::Uniform> uniforms;
  482. {
  483. RD::Uniform u;
  484. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  485. u.binding = 1;
  486. for (int j = 0; j < 8; j++) {
  487. u.ids.push_back(sdfgi->render_occlusion[j]);
  488. }
  489. uniforms.push_back(u);
  490. }
  491. {
  492. RD::Uniform u;
  493. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  494. u.binding = 2;
  495. u.ids.push_back(sdfgi->occlusion_data);
  496. uniforms.push_back(u);
  497. }
  498. cascade.scroll_occlusion_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_SCROLL_OCCLUSION), 0);
  499. }
  500. }
  501. //direct light
  502. for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
  503. SDFGI::Cascade &cascade = sdfgi->cascades[i];
  504. Vector<RD::Uniform> uniforms;
  505. {
  506. RD::Uniform u;
  507. u.binding = 1;
  508. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  509. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  510. if (j < rb->sdfgi->cascades.size()) {
  511. u.ids.push_back(rb->sdfgi->cascades[j].sdf_tex);
  512. } else {
  513. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  514. }
  515. }
  516. uniforms.push_back(u);
  517. }
  518. {
  519. RD::Uniform u;
  520. u.binding = 2;
  521. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  522. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  523. uniforms.push_back(u);
  524. }
  525. {
  526. RD::Uniform u;
  527. u.binding = 3;
  528. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  529. u.ids.push_back(cascade.solid_cell_dispatch_buffer);
  530. uniforms.push_back(u);
  531. }
  532. {
  533. RD::Uniform u;
  534. u.binding = 4;
  535. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  536. u.ids.push_back(cascade.solid_cell_buffer);
  537. uniforms.push_back(u);
  538. }
  539. {
  540. RD::Uniform u;
  541. u.binding = 5;
  542. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  543. u.ids.push_back(cascade.light_data);
  544. uniforms.push_back(u);
  545. }
  546. {
  547. RD::Uniform u;
  548. u.binding = 6;
  549. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  550. u.ids.push_back(cascade.light_aniso_0_tex);
  551. uniforms.push_back(u);
  552. }
  553. {
  554. RD::Uniform u;
  555. u.binding = 7;
  556. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  557. u.ids.push_back(cascade.light_aniso_1_tex);
  558. uniforms.push_back(u);
  559. }
  560. {
  561. RD::Uniform u;
  562. u.binding = 8;
  563. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  564. u.ids.push_back(rb->sdfgi->cascades_ubo);
  565. uniforms.push_back(u);
  566. }
  567. {
  568. RD::Uniform u;
  569. u.binding = 9;
  570. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  571. u.ids.push_back(cascade.lights_buffer);
  572. uniforms.push_back(u);
  573. }
  574. {
  575. RD::Uniform u;
  576. u.binding = 10;
  577. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  578. u.ids.push_back(rb->sdfgi->lightprobe_texture);
  579. uniforms.push_back(u);
  580. }
  581. cascade.sdf_direct_light_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.direct_light.version_get_shader(sdfgi_shader.direct_light_shader, 0), 0);
  582. }
  583. //preprocess initialize uniform set
  584. {
  585. Vector<RD::Uniform> uniforms;
  586. {
  587. RD::Uniform u;
  588. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  589. u.binding = 1;
  590. u.ids.push_back(sdfgi->render_albedo);
  591. uniforms.push_back(u);
  592. }
  593. {
  594. RD::Uniform u;
  595. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  596. u.binding = 2;
  597. u.ids.push_back(sdfgi->render_sdf[0]);
  598. uniforms.push_back(u);
  599. }
  600. sdfgi->sdf_initialize_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE), 0);
  601. }
  602. {
  603. Vector<RD::Uniform> uniforms;
  604. {
  605. RD::Uniform u;
  606. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  607. u.binding = 1;
  608. u.ids.push_back(sdfgi->render_albedo);
  609. uniforms.push_back(u);
  610. }
  611. {
  612. RD::Uniform u;
  613. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  614. u.binding = 2;
  615. u.ids.push_back(sdfgi->render_sdf_half[0]);
  616. uniforms.push_back(u);
  617. }
  618. sdfgi->sdf_initialize_half_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE_HALF), 0);
  619. }
  620. //jump flood uniform set
  621. {
  622. Vector<RD::Uniform> uniforms;
  623. {
  624. RD::Uniform u;
  625. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  626. u.binding = 1;
  627. u.ids.push_back(sdfgi->render_sdf[0]);
  628. uniforms.push_back(u);
  629. }
  630. {
  631. RD::Uniform u;
  632. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  633. u.binding = 2;
  634. u.ids.push_back(sdfgi->render_sdf[1]);
  635. uniforms.push_back(u);
  636. }
  637. sdfgi->jump_flood_uniform_set[0] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
  638. SWAP(uniforms.write[0].ids.write[0], uniforms.write[1].ids.write[0]);
  639. sdfgi->jump_flood_uniform_set[1] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
  640. }
  641. //jump flood half uniform set
  642. {
  643. Vector<RD::Uniform> uniforms;
  644. {
  645. RD::Uniform u;
  646. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  647. u.binding = 1;
  648. u.ids.push_back(sdfgi->render_sdf_half[0]);
  649. uniforms.push_back(u);
  650. }
  651. {
  652. RD::Uniform u;
  653. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  654. u.binding = 2;
  655. u.ids.push_back(sdfgi->render_sdf_half[1]);
  656. uniforms.push_back(u);
  657. }
  658. sdfgi->jump_flood_half_uniform_set[0] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
  659. SWAP(uniforms.write[0].ids.write[0], uniforms.write[1].ids.write[0]);
  660. sdfgi->jump_flood_half_uniform_set[1] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
  661. }
  662. //upscale half size sdf
  663. {
  664. Vector<RD::Uniform> uniforms;
  665. {
  666. RD::Uniform u;
  667. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  668. u.binding = 1;
  669. u.ids.push_back(sdfgi->render_albedo);
  670. uniforms.push_back(u);
  671. }
  672. {
  673. RD::Uniform u;
  674. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  675. u.binding = 2;
  676. u.ids.push_back(sdfgi->render_sdf_half[(passes & 1) ? 0 : 1]); //reverse pass order because half size
  677. uniforms.push_back(u);
  678. }
  679. {
  680. RD::Uniform u;
  681. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  682. u.binding = 3;
  683. u.ids.push_back(sdfgi->render_sdf[(passes & 1) ? 0 : 1]); //reverse pass order because it needs an extra JFA pass
  684. uniforms.push_back(u);
  685. }
  686. sdfgi->upscale_jfa_uniform_set_index = (passes & 1) ? 0 : 1;
  687. sdfgi->sdf_upscale_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD_UPSCALE), 0);
  688. }
  689. //occlusion uniform set
  690. {
  691. Vector<RD::Uniform> uniforms;
  692. {
  693. RD::Uniform u;
  694. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  695. u.binding = 1;
  696. u.ids.push_back(sdfgi->render_albedo);
  697. uniforms.push_back(u);
  698. }
  699. {
  700. RD::Uniform u;
  701. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  702. u.binding = 2;
  703. for (int i = 0; i < 8; i++) {
  704. u.ids.push_back(sdfgi->render_occlusion[i]);
  705. }
  706. uniforms.push_back(u);
  707. }
  708. {
  709. RD::Uniform u;
  710. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  711. u.binding = 3;
  712. u.ids.push_back(sdfgi->render_geom_facing);
  713. uniforms.push_back(u);
  714. }
  715. sdfgi->occlusion_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_OCCLUSION), 0);
  716. }
  717. for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
  718. //integrate uniform
  719. Vector<RD::Uniform> uniforms;
  720. {
  721. RD::Uniform u;
  722. u.binding = 1;
  723. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  724. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  725. if (j < sdfgi->cascades.size()) {
  726. u.ids.push_back(sdfgi->cascades[j].sdf_tex);
  727. } else {
  728. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  729. }
  730. }
  731. uniforms.push_back(u);
  732. }
  733. {
  734. RD::Uniform u;
  735. u.binding = 2;
  736. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  737. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  738. if (j < sdfgi->cascades.size()) {
  739. u.ids.push_back(sdfgi->cascades[j].light_tex);
  740. } else {
  741. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  742. }
  743. }
  744. uniforms.push_back(u);
  745. }
  746. {
  747. RD::Uniform u;
  748. u.binding = 3;
  749. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  750. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  751. if (j < sdfgi->cascades.size()) {
  752. u.ids.push_back(sdfgi->cascades[j].light_aniso_0_tex);
  753. } else {
  754. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  755. }
  756. }
  757. uniforms.push_back(u);
  758. }
  759. {
  760. RD::Uniform u;
  761. u.binding = 4;
  762. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  763. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  764. if (j < sdfgi->cascades.size()) {
  765. u.ids.push_back(sdfgi->cascades[j].light_aniso_1_tex);
  766. } else {
  767. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  768. }
  769. }
  770. uniforms.push_back(u);
  771. }
  772. {
  773. RD::Uniform u;
  774. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  775. u.binding = 6;
  776. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  777. uniforms.push_back(u);
  778. }
  779. {
  780. RD::Uniform u;
  781. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  782. u.binding = 7;
  783. u.ids.push_back(sdfgi->cascades_ubo);
  784. uniforms.push_back(u);
  785. }
  786. {
  787. RD::Uniform u;
  788. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  789. u.binding = 8;
  790. u.ids.push_back(sdfgi->lightprobe_data);
  791. uniforms.push_back(u);
  792. }
  793. {
  794. RD::Uniform u;
  795. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  796. u.binding = 9;
  797. u.ids.push_back(sdfgi->cascades[i].lightprobe_history_tex);
  798. uniforms.push_back(u);
  799. }
  800. {
  801. RD::Uniform u;
  802. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  803. u.binding = 10;
  804. u.ids.push_back(sdfgi->cascades[i].lightprobe_average_tex);
  805. uniforms.push_back(u);
  806. }
  807. {
  808. RD::Uniform u;
  809. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  810. u.binding = 11;
  811. u.ids.push_back(sdfgi->lightprobe_history_scroll);
  812. uniforms.push_back(u);
  813. }
  814. {
  815. RD::Uniform u;
  816. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  817. u.binding = 12;
  818. u.ids.push_back(sdfgi->lightprobe_average_scroll);
  819. uniforms.push_back(u);
  820. }
  821. {
  822. RD::Uniform u;
  823. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  824. u.binding = 13;
  825. RID parent_average;
  826. if (i < sdfgi->cascades.size() - 1) {
  827. parent_average = sdfgi->cascades[i + 1].lightprobe_average_tex;
  828. } else {
  829. parent_average = sdfgi->cascades[i - 1].lightprobe_average_tex; //to use something, but it won't be used
  830. }
  831. u.ids.push_back(parent_average);
  832. uniforms.push_back(u);
  833. }
  834. {
  835. RD::Uniform u;
  836. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  837. u.binding = 14;
  838. u.ids.push_back(sdfgi->ambient_texture);
  839. uniforms.push_back(u);
  840. }
  841. sdfgi->cascades[i].integrate_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, 0), 0);
  842. }
  843. sdfgi->uses_multibounce = env->sdfgi_use_multibounce;
  844. sdfgi->energy = env->sdfgi_energy;
  845. sdfgi->normal_bias = env->sdfgi_normal_bias;
  846. sdfgi->probe_bias = env->sdfgi_probe_bias;
  847. sdfgi->reads_sky = env->sdfgi_read_sky_light;
  848. _render_buffers_uniform_set_changed(p_render_buffers);
  849. return; //done. all levels will need to be rendered which its going to take a bit
  850. }
  851. //check for updates
  852. sdfgi->uses_multibounce = env->sdfgi_use_multibounce;
  853. sdfgi->energy = env->sdfgi_energy;
  854. sdfgi->normal_bias = env->sdfgi_normal_bias;
  855. sdfgi->probe_bias = env->sdfgi_probe_bias;
  856. sdfgi->reads_sky = env->sdfgi_read_sky_light;
  857. int32_t drag_margin = (sdfgi->cascade_size / SDFGI::PROBE_DIVISOR) / 2;
  858. for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
  859. SDFGI::Cascade &cascade = sdfgi->cascades[i];
  860. cascade.dirty_regions = Vector3i();
  861. Vector3 probe_half_size = Vector3(1, 1, 1) * cascade.cell_size * float(sdfgi->cascade_size / SDFGI::PROBE_DIVISOR) * 0.5;
  862. probe_half_size = Vector3(0, 0, 0);
  863. Vector3 world_position = p_world_position;
  864. world_position.y *= sdfgi->y_mult;
  865. Vector3i pos_in_cascade = Vector3i((world_position + probe_half_size) / cascade.cell_size);
  866. for (int j = 0; j < 3; j++) {
  867. if (pos_in_cascade[j] < cascade.position[j]) {
  868. while (pos_in_cascade[j] < (cascade.position[j] - drag_margin)) {
  869. cascade.position[j] -= drag_margin * 2;
  870. cascade.dirty_regions[j] += drag_margin * 2;
  871. }
  872. } else if (pos_in_cascade[j] > cascade.position[j]) {
  873. while (pos_in_cascade[j] > (cascade.position[j] + drag_margin)) {
  874. cascade.position[j] += drag_margin * 2;
  875. cascade.dirty_regions[j] -= drag_margin * 2;
  876. }
  877. }
  878. if (cascade.dirty_regions[j] == 0) {
  879. continue; // not dirty
  880. } else if (uint32_t(ABS(cascade.dirty_regions[j])) >= sdfgi->cascade_size) {
  881. //moved too much, just redraw everything (make all dirty)
  882. cascade.dirty_regions = SDFGI::Cascade::DIRTY_ALL;
  883. break;
  884. }
  885. }
  886. if (cascade.dirty_regions != Vector3i() && cascade.dirty_regions != SDFGI::Cascade::DIRTY_ALL) {
  887. //see how much the total dirty volume represents from the total volume
  888. uint32_t total_volume = sdfgi->cascade_size * sdfgi->cascade_size * sdfgi->cascade_size;
  889. uint32_t safe_volume = 1;
  890. for (int j = 0; j < 3; j++) {
  891. safe_volume *= sdfgi->cascade_size - ABS(cascade.dirty_regions[j]);
  892. }
  893. uint32_t dirty_volume = total_volume - safe_volume;
  894. if (dirty_volume > (safe_volume / 2)) {
  895. //more than half the volume is dirty, make all dirty so its only rendered once
  896. cascade.dirty_regions = SDFGI::Cascade::DIRTY_ALL;
  897. }
  898. }
  899. }
  900. }
  901. int RendererSceneRenderRD::sdfgi_get_pending_region_count(RID p_render_buffers) const {
  902. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  903. ERR_FAIL_COND_V(rb == nullptr, 0);
  904. if (rb->sdfgi == nullptr) {
  905. return 0;
  906. }
  907. int dirty_count = 0;
  908. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  909. const SDFGI::Cascade &c = rb->sdfgi->cascades[i];
  910. if (c.dirty_regions == SDFGI::Cascade::DIRTY_ALL) {
  911. dirty_count++;
  912. } else {
  913. for (int j = 0; j < 3; j++) {
  914. if (c.dirty_regions[j] != 0) {
  915. dirty_count++;
  916. }
  917. }
  918. }
  919. }
  920. return dirty_count;
  921. }
  922. int RendererSceneRenderRD::_sdfgi_get_pending_region_data(RID p_render_buffers, int p_region, Vector3i &r_local_offset, Vector3i &r_local_size, AABB &r_bounds) const {
  923. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  924. ERR_FAIL_COND_V(rb == nullptr, -1);
  925. ERR_FAIL_COND_V(rb->sdfgi == nullptr, -1);
  926. int dirty_count = 0;
  927. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  928. const SDFGI::Cascade &c = rb->sdfgi->cascades[i];
  929. if (c.dirty_regions == SDFGI::Cascade::DIRTY_ALL) {
  930. if (dirty_count == p_region) {
  931. r_local_offset = Vector3i();
  932. r_local_size = Vector3i(1, 1, 1) * rb->sdfgi->cascade_size;
  933. r_bounds.position = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + c.position)) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
  934. r_bounds.size = Vector3(r_local_size) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
  935. return i;
  936. }
  937. dirty_count++;
  938. } else {
  939. for (int j = 0; j < 3; j++) {
  940. if (c.dirty_regions[j] != 0) {
  941. if (dirty_count == p_region) {
  942. Vector3i from = Vector3i(0, 0, 0);
  943. Vector3i to = Vector3i(1, 1, 1) * rb->sdfgi->cascade_size;
  944. if (c.dirty_regions[j] > 0) {
  945. //fill from the beginning
  946. to[j] = c.dirty_regions[j];
  947. } else {
  948. //fill from the end
  949. from[j] = to[j] + c.dirty_regions[j];
  950. }
  951. for (int k = 0; k < j; k++) {
  952. // "chip" away previous regions to avoid re-voxelizing the same thing
  953. if (c.dirty_regions[k] > 0) {
  954. from[k] += c.dirty_regions[k];
  955. } else if (c.dirty_regions[k] < 0) {
  956. to[k] += c.dirty_regions[k];
  957. }
  958. }
  959. r_local_offset = from;
  960. r_local_size = to - from;
  961. r_bounds.position = Vector3(from + Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + c.position) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
  962. r_bounds.size = Vector3(r_local_size) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
  963. return i;
  964. }
  965. dirty_count++;
  966. }
  967. }
  968. }
  969. }
  970. return -1;
  971. }
  972. AABB RendererSceneRenderRD::sdfgi_get_pending_region_bounds(RID p_render_buffers, int p_region) const {
  973. AABB bounds;
  974. Vector3i from;
  975. Vector3i size;
  976. int c = _sdfgi_get_pending_region_data(p_render_buffers, p_region, from, size, bounds);
  977. ERR_FAIL_COND_V(c == -1, AABB());
  978. return bounds;
  979. }
  980. uint32_t RendererSceneRenderRD::sdfgi_get_pending_region_cascade(RID p_render_buffers, int p_region) const {
  981. AABB bounds;
  982. Vector3i from;
  983. Vector3i size;
  984. return _sdfgi_get_pending_region_data(p_render_buffers, p_region, from, size, bounds);
  985. }
  986. void RendererSceneRenderRD::_sdfgi_update_cascades(RID p_render_buffers) {
  987. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  988. ERR_FAIL_COND(rb == nullptr);
  989. if (rb->sdfgi == nullptr) {
  990. return;
  991. }
  992. //update cascades
  993. SDFGI::Cascade::UBO cascade_data[SDFGI::MAX_CASCADES];
  994. int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  995. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  996. Vector3 pos = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[i].position)) * rb->sdfgi->cascades[i].cell_size;
  997. cascade_data[i].offset[0] = pos.x;
  998. cascade_data[i].offset[1] = pos.y;
  999. cascade_data[i].offset[2] = pos.z;
  1000. cascade_data[i].to_cell = 1.0 / rb->sdfgi->cascades[i].cell_size;
  1001. cascade_data[i].probe_offset[0] = rb->sdfgi->cascades[i].position.x / probe_divisor;
  1002. cascade_data[i].probe_offset[1] = rb->sdfgi->cascades[i].position.y / probe_divisor;
  1003. cascade_data[i].probe_offset[2] = rb->sdfgi->cascades[i].position.z / probe_divisor;
  1004. cascade_data[i].pad = 0;
  1005. }
  1006. RD::get_singleton()->buffer_update(rb->sdfgi->cascades_ubo, 0, sizeof(SDFGI::Cascade::UBO) * SDFGI::MAX_CASCADES, cascade_data, RD::BARRIER_MASK_COMPUTE);
  1007. }
  1008. void RendererSceneRenderRD::_sdfgi_update_light(RID p_render_buffers, RID p_environment) {
  1009. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  1010. ERR_FAIL_COND(rb == nullptr);
  1011. if (rb->sdfgi == nullptr) {
  1012. return;
  1013. }
  1014. RD::get_singleton()->draw_command_begin_label("SDFGI Update dynamic Light");
  1015. /* Update dynamic light */
  1016. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  1017. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.direct_light_pipeline[SDGIShader::DIRECT_LIGHT_MODE_DYNAMIC]);
  1018. SDGIShader::DirectLightPushConstant push_constant;
  1019. push_constant.grid_size[0] = rb->sdfgi->cascade_size;
  1020. push_constant.grid_size[1] = rb->sdfgi->cascade_size;
  1021. push_constant.grid_size[2] = rb->sdfgi->cascade_size;
  1022. push_constant.max_cascades = rb->sdfgi->cascades.size();
  1023. push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  1024. push_constant.multibounce = rb->sdfgi->uses_multibounce;
  1025. push_constant.y_mult = rb->sdfgi->y_mult;
  1026. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  1027. SDFGI::Cascade &cascade = rb->sdfgi->cascades[i];
  1028. push_constant.light_count = rb->sdfgi->cascade_dynamic_light_count[i];
  1029. push_constant.cascade = i;
  1030. if (rb->sdfgi->cascades[i].all_dynamic_lights_dirty || sdfgi_frames_to_update_light == RS::ENV_SDFGI_UPDATE_LIGHT_IN_1_FRAME) {
  1031. push_constant.process_offset = 0;
  1032. push_constant.process_increment = 1;
  1033. } else {
  1034. static uint32_t frames_to_update_table[RS::ENV_SDFGI_UPDATE_LIGHT_MAX] = {
  1035. 1, 2, 4, 8, 16
  1036. };
  1037. uint32_t frames_to_update = frames_to_update_table[sdfgi_frames_to_update_light];
  1038. push_constant.process_offset = RSG::rasterizer->get_frame_number() % frames_to_update;
  1039. push_constant.process_increment = frames_to_update;
  1040. }
  1041. rb->sdfgi->cascades[i].all_dynamic_lights_dirty = false;
  1042. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, cascade.sdf_direct_light_uniform_set, 0);
  1043. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::DirectLightPushConstant));
  1044. RD::get_singleton()->compute_list_dispatch_indirect(compute_list, cascade.solid_cell_dispatch_buffer, 0);
  1045. }
  1046. RD::get_singleton()->compute_list_end(RD::BARRIER_MASK_COMPUTE);
  1047. RD::get_singleton()->draw_command_end_label();
  1048. }
  1049. void RendererSceneRenderRD::_sdfgi_update_probes(RID p_render_buffers, RID p_environment) {
  1050. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  1051. ERR_FAIL_COND(rb == nullptr);
  1052. if (rb->sdfgi == nullptr) {
  1053. return;
  1054. }
  1055. RD::get_singleton()->draw_command_begin_label("SDFGI Update Probes");
  1056. Environment *env = environment_owner.getornull(p_environment);
  1057. SDGIShader::IntegratePushConstant push_constant;
  1058. push_constant.grid_size[1] = rb->sdfgi->cascade_size;
  1059. push_constant.grid_size[2] = rb->sdfgi->cascade_size;
  1060. push_constant.grid_size[0] = rb->sdfgi->cascade_size;
  1061. push_constant.max_cascades = rb->sdfgi->cascades.size();
  1062. push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  1063. push_constant.history_index = rb->sdfgi->render_pass % rb->sdfgi->history_size;
  1064. push_constant.history_size = rb->sdfgi->history_size;
  1065. static const uint32_t ray_count[RS::ENV_SDFGI_RAY_COUNT_MAX] = { 4, 8, 16, 32, 64, 96, 128 };
  1066. push_constant.ray_count = ray_count[sdfgi_ray_count];
  1067. push_constant.ray_bias = rb->sdfgi->probe_bias;
  1068. push_constant.image_size[0] = rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count;
  1069. push_constant.image_size[1] = rb->sdfgi->probe_axis_count;
  1070. push_constant.store_ambient_texture = env->volumetric_fog_enabled;
  1071. RID sky_uniform_set = sdfgi_shader.integrate_default_sky_uniform_set;
  1072. push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_DISABLED;
  1073. push_constant.y_mult = rb->sdfgi->y_mult;
  1074. if (rb->sdfgi->reads_sky && env) {
  1075. push_constant.sky_energy = env->bg_energy;
  1076. if (env->background == RS::ENV_BG_CLEAR_COLOR) {
  1077. push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_COLOR;
  1078. Color c = storage->get_default_clear_color().to_linear();
  1079. push_constant.sky_color[0] = c.r;
  1080. push_constant.sky_color[1] = c.g;
  1081. push_constant.sky_color[2] = c.b;
  1082. } else if (env->background == RS::ENV_BG_COLOR) {
  1083. push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_COLOR;
  1084. Color c = env->bg_color;
  1085. push_constant.sky_color[0] = c.r;
  1086. push_constant.sky_color[1] = c.g;
  1087. push_constant.sky_color[2] = c.b;
  1088. } else if (env->background == RS::ENV_BG_SKY) {
  1089. Sky *sky = sky_owner.getornull(env->sky);
  1090. if (sky && sky->radiance.is_valid()) {
  1091. if (sky->sdfgi_integrate_sky_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(sky->sdfgi_integrate_sky_uniform_set)) {
  1092. Vector<RD::Uniform> uniforms;
  1093. {
  1094. RD::Uniform u;
  1095. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1096. u.binding = 0;
  1097. u.ids.push_back(sky->radiance);
  1098. uniforms.push_back(u);
  1099. }
  1100. {
  1101. RD::Uniform u;
  1102. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  1103. u.binding = 1;
  1104. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  1105. uniforms.push_back(u);
  1106. }
  1107. sky->sdfgi_integrate_sky_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, 0), 1);
  1108. }
  1109. sky_uniform_set = sky->sdfgi_integrate_sky_uniform_set;
  1110. push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_SKY;
  1111. }
  1112. }
  1113. }
  1114. rb->sdfgi->render_pass++;
  1115. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin(true);
  1116. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_PROCESS]);
  1117. int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  1118. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  1119. push_constant.cascade = i;
  1120. push_constant.world_offset[0] = rb->sdfgi->cascades[i].position.x / probe_divisor;
  1121. push_constant.world_offset[1] = rb->sdfgi->cascades[i].position.y / probe_divisor;
  1122. push_constant.world_offset[2] = rb->sdfgi->cascades[i].position.z / probe_divisor;
  1123. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[i].integrate_uniform_set, 0);
  1124. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sky_uniform_set, 1);
  1125. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::IntegratePushConstant));
  1126. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count, rb->sdfgi->probe_axis_count, 1);
  1127. }
  1128. //end later after raster to avoid barriering on layout changes
  1129. //RD::get_singleton()->compute_list_end(RD::BARRIER_MASK_NO_BARRIER);
  1130. RD::get_singleton()->draw_command_end_label();
  1131. }
  1132. void RendererSceneRenderRD::_sdfgi_store_probes(RID p_render_buffers) {
  1133. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  1134. ERR_FAIL_COND(rb == nullptr);
  1135. if (rb->sdfgi == nullptr) {
  1136. return;
  1137. }
  1138. RD::get_singleton()->barrier(RD::BARRIER_MASK_COMPUTE, RD::BARRIER_MASK_COMPUTE);
  1139. RD::get_singleton()->draw_command_begin_label("SDFGI Store Probes");
  1140. SDGIShader::IntegratePushConstant push_constant;
  1141. push_constant.grid_size[1] = rb->sdfgi->cascade_size;
  1142. push_constant.grid_size[2] = rb->sdfgi->cascade_size;
  1143. push_constant.grid_size[0] = rb->sdfgi->cascade_size;
  1144. push_constant.max_cascades = rb->sdfgi->cascades.size();
  1145. push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  1146. push_constant.history_index = rb->sdfgi->render_pass % rb->sdfgi->history_size;
  1147. push_constant.history_size = rb->sdfgi->history_size;
  1148. static const uint32_t ray_count[RS::ENV_SDFGI_RAY_COUNT_MAX] = { 4, 8, 16, 32, 64, 96, 128 };
  1149. push_constant.ray_count = ray_count[sdfgi_ray_count];
  1150. push_constant.ray_bias = rb->sdfgi->probe_bias;
  1151. push_constant.image_size[0] = rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count;
  1152. push_constant.image_size[1] = rb->sdfgi->probe_axis_count;
  1153. push_constant.store_ambient_texture = false;
  1154. push_constant.sky_mode = 0;
  1155. push_constant.y_mult = rb->sdfgi->y_mult;
  1156. // Then store values into the lightprobe texture. Separating these steps has a small performance hit, but it allows for multiple bounces
  1157. RENDER_TIMESTAMP("Average Probes");
  1158. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  1159. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_STORE]);
  1160. //convert to octahedral to store
  1161. push_constant.image_size[0] *= SDFGI::LIGHTPROBE_OCT_SIZE;
  1162. push_constant.image_size[1] *= SDFGI::LIGHTPROBE_OCT_SIZE;
  1163. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  1164. push_constant.cascade = i;
  1165. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[i].integrate_uniform_set, 0);
  1166. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sdfgi_shader.integrate_default_sky_uniform_set, 1);
  1167. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::IntegratePushConstant));
  1168. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count * SDFGI::LIGHTPROBE_OCT_SIZE, rb->sdfgi->probe_axis_count * SDFGI::LIGHTPROBE_OCT_SIZE, 1);
  1169. }
  1170. RD::get_singleton()->compute_list_end(RD::BARRIER_MASK_COMPUTE);
  1171. RD::get_singleton()->draw_command_end_label();
  1172. }
  1173. void RendererSceneRenderRD::_setup_giprobes(RID p_render_buffers, const Transform &p_transform, const PagedArray<RID> &p_gi_probes, uint32_t &r_gi_probes_used) {
  1174. r_gi_probes_used = 0;
  1175. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  1176. ERR_FAIL_COND(rb == nullptr);
  1177. RD::get_singleton()->draw_command_begin_label("GIProbes Setup");
  1178. RID gi_probe_buffer = render_buffers_get_gi_probe_buffer(p_render_buffers);
  1179. GI::GIProbeData gi_probe_data[RenderBuffers::MAX_GIPROBES];
  1180. bool giprobes_changed = false;
  1181. Transform to_camera;
  1182. to_camera.origin = p_transform.origin; //only translation, make local
  1183. for (int i = 0; i < RenderBuffers::MAX_GIPROBES; i++) {
  1184. RID texture;
  1185. if (i < (int)p_gi_probes.size()) {
  1186. GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_gi_probes[i]);
  1187. if (gipi) {
  1188. texture = gipi->texture;
  1189. GI::GIProbeData &gipd = gi_probe_data[i];
  1190. RID base_probe = gipi->probe;
  1191. Transform to_cell = storage->gi_probe_get_to_cell_xform(gipi->probe) * gipi->transform.affine_inverse() * to_camera;
  1192. gipd.xform[0] = to_cell.basis.elements[0][0];
  1193. gipd.xform[1] = to_cell.basis.elements[1][0];
  1194. gipd.xform[2] = to_cell.basis.elements[2][0];
  1195. gipd.xform[3] = 0;
  1196. gipd.xform[4] = to_cell.basis.elements[0][1];
  1197. gipd.xform[5] = to_cell.basis.elements[1][1];
  1198. gipd.xform[6] = to_cell.basis.elements[2][1];
  1199. gipd.xform[7] = 0;
  1200. gipd.xform[8] = to_cell.basis.elements[0][2];
  1201. gipd.xform[9] = to_cell.basis.elements[1][2];
  1202. gipd.xform[10] = to_cell.basis.elements[2][2];
  1203. gipd.xform[11] = 0;
  1204. gipd.xform[12] = to_cell.origin.x;
  1205. gipd.xform[13] = to_cell.origin.y;
  1206. gipd.xform[14] = to_cell.origin.z;
  1207. gipd.xform[15] = 1;
  1208. Vector3 bounds = storage->gi_probe_get_octree_size(base_probe);
  1209. gipd.bounds[0] = bounds.x;
  1210. gipd.bounds[1] = bounds.y;
  1211. gipd.bounds[2] = bounds.z;
  1212. gipd.dynamic_range = storage->gi_probe_get_dynamic_range(base_probe) * storage->gi_probe_get_energy(base_probe);
  1213. gipd.bias = storage->gi_probe_get_bias(base_probe);
  1214. gipd.normal_bias = storage->gi_probe_get_normal_bias(base_probe);
  1215. gipd.blend_ambient = !storage->gi_probe_is_interior(base_probe);
  1216. gipd.anisotropy_strength = 0;
  1217. gipd.ao = storage->gi_probe_get_ao(base_probe);
  1218. gipd.ao_size = Math::pow(storage->gi_probe_get_ao_size(base_probe), 4.0f);
  1219. gipd.mipmaps = gipi->mipmaps.size();
  1220. }
  1221. r_gi_probes_used++;
  1222. }
  1223. if (texture == RID()) {
  1224. texture = storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE);
  1225. }
  1226. if (texture != rb->giprobe_textures[i]) {
  1227. giprobes_changed = true;
  1228. rb->giprobe_textures[i] = texture;
  1229. }
  1230. }
  1231. if (giprobes_changed) {
  1232. if (RD::get_singleton()->uniform_set_is_valid(rb->gi_uniform_set)) {
  1233. RD::get_singleton()->free(rb->gi_uniform_set);
  1234. }
  1235. rb->gi_uniform_set = RID();
  1236. if (rb->volumetric_fog) {
  1237. if (RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set)) {
  1238. RD::get_singleton()->free(rb->volumetric_fog->uniform_set);
  1239. RD::get_singleton()->free(rb->volumetric_fog->uniform_set2);
  1240. }
  1241. rb->volumetric_fog->uniform_set = RID();
  1242. rb->volumetric_fog->uniform_set2 = RID();
  1243. }
  1244. }
  1245. if (p_gi_probes.size() > 0) {
  1246. RD::get_singleton()->buffer_update(gi_probe_buffer, 0, sizeof(GI::GIProbeData) * MIN((uint64_t)RenderBuffers::MAX_GIPROBES, p_gi_probes.size()), gi_probe_data, RD::BARRIER_MASK_COMPUTE);
  1247. }
  1248. RD::get_singleton()->draw_command_end_label();
  1249. }
  1250. void RendererSceneRenderRD::_pre_process_gi(RID p_render_buffers, const Transform &p_transform) {
  1251. // Do the required buffer transfers and setup before the depth-pre pass, this way GI can
  1252. // run in parallel during depth-pre pass and shadow rendering.
  1253. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  1254. ERR_FAIL_COND(rb == nullptr);
  1255. /* Update Cascades UBO */
  1256. if (rb->sdfgi) {
  1257. /* Update general SDFGI Buffer */
  1258. _sdfgi_update_cascades(p_render_buffers);
  1259. GI::SDFGIData sdfgi_data;
  1260. sdfgi_data.grid_size[0] = rb->sdfgi->cascade_size;
  1261. sdfgi_data.grid_size[1] = rb->sdfgi->cascade_size;
  1262. sdfgi_data.grid_size[2] = rb->sdfgi->cascade_size;
  1263. sdfgi_data.max_cascades = rb->sdfgi->cascades.size();
  1264. sdfgi_data.probe_axis_size = rb->sdfgi->probe_axis_count;
  1265. sdfgi_data.cascade_probe_size[0] = sdfgi_data.probe_axis_size - 1; //float version for performance
  1266. sdfgi_data.cascade_probe_size[1] = sdfgi_data.probe_axis_size - 1;
  1267. sdfgi_data.cascade_probe_size[2] = sdfgi_data.probe_axis_size - 1;
  1268. float csize = rb->sdfgi->cascade_size;
  1269. sdfgi_data.probe_to_uvw = 1.0 / float(sdfgi_data.cascade_probe_size[0]);
  1270. sdfgi_data.use_occlusion = rb->sdfgi->uses_occlusion;
  1271. //sdfgi_data.energy = rb->sdfgi->energy;
  1272. sdfgi_data.y_mult = rb->sdfgi->y_mult;
  1273. float cascade_voxel_size = (csize / sdfgi_data.cascade_probe_size[0]);
  1274. float occlusion_clamp = (cascade_voxel_size - 0.5) / cascade_voxel_size;
  1275. sdfgi_data.occlusion_clamp[0] = occlusion_clamp;
  1276. sdfgi_data.occlusion_clamp[1] = occlusion_clamp;
  1277. sdfgi_data.occlusion_clamp[2] = occlusion_clamp;
  1278. sdfgi_data.normal_bias = (rb->sdfgi->normal_bias / csize) * sdfgi_data.cascade_probe_size[0];
  1279. //vec2 tex_pixel_size = 1.0 / vec2(ivec2( (OCT_SIZE+2) * params.probe_axis_size * params.probe_axis_size, (OCT_SIZE+2) * params.probe_axis_size ) );
  1280. //vec3 probe_uv_offset = (ivec3(OCT_SIZE+2,OCT_SIZE+2,(OCT_SIZE+2) * params.probe_axis_size)) * tex_pixel_size.xyx;
  1281. uint32_t oct_size = SDFGI::LIGHTPROBE_OCT_SIZE;
  1282. sdfgi_data.lightprobe_tex_pixel_size[0] = 1.0 / ((oct_size + 2) * sdfgi_data.probe_axis_size * sdfgi_data.probe_axis_size);
  1283. sdfgi_data.lightprobe_tex_pixel_size[1] = 1.0 / ((oct_size + 2) * sdfgi_data.probe_axis_size);
  1284. sdfgi_data.lightprobe_tex_pixel_size[2] = 1.0;
  1285. sdfgi_data.energy = rb->sdfgi->energy;
  1286. sdfgi_data.lightprobe_uv_offset[0] = float(oct_size + 2) * sdfgi_data.lightprobe_tex_pixel_size[0];
  1287. sdfgi_data.lightprobe_uv_offset[1] = float(oct_size + 2) * sdfgi_data.lightprobe_tex_pixel_size[1];
  1288. sdfgi_data.lightprobe_uv_offset[2] = float((oct_size + 2) * sdfgi_data.probe_axis_size) * sdfgi_data.lightprobe_tex_pixel_size[0];
  1289. sdfgi_data.occlusion_renormalize[0] = 0.5;
  1290. sdfgi_data.occlusion_renormalize[1] = 1.0;
  1291. sdfgi_data.occlusion_renormalize[2] = 1.0 / float(sdfgi_data.max_cascades);
  1292. int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  1293. for (uint32_t i = 0; i < sdfgi_data.max_cascades; i++) {
  1294. GI::SDFGIData::ProbeCascadeData &c = sdfgi_data.cascades[i];
  1295. Vector3 pos = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[i].position)) * rb->sdfgi->cascades[i].cell_size;
  1296. Vector3 cam_origin = p_transform.origin;
  1297. cam_origin.y *= rb->sdfgi->y_mult;
  1298. pos -= cam_origin; //make pos local to camera, to reduce numerical error
  1299. c.position[0] = pos.x;
  1300. c.position[1] = pos.y;
  1301. c.position[2] = pos.z;
  1302. c.to_probe = 1.0 / (float(rb->sdfgi->cascade_size) * rb->sdfgi->cascades[i].cell_size / float(rb->sdfgi->probe_axis_count - 1));
  1303. Vector3i probe_ofs = rb->sdfgi->cascades[i].position / probe_divisor;
  1304. c.probe_world_offset[0] = probe_ofs.x;
  1305. c.probe_world_offset[1] = probe_ofs.y;
  1306. c.probe_world_offset[2] = probe_ofs.z;
  1307. c.to_cell = 1.0 / rb->sdfgi->cascades[i].cell_size;
  1308. }
  1309. RD::get_singleton()->buffer_update(gi.sdfgi_ubo, 0, sizeof(GI::SDFGIData), &sdfgi_data, RD::BARRIER_MASK_COMPUTE);
  1310. /* Update dynamic lights in SDFGI cascades */
  1311. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  1312. SDFGI::Cascade &cascade = rb->sdfgi->cascades[i];
  1313. SDGIShader::Light lights[SDFGI::MAX_DYNAMIC_LIGHTS];
  1314. uint32_t idx = 0;
  1315. for (uint32_t j = 0; j < (uint32_t)render_state.sdfgi_update_data->directional_lights->size(); j++) {
  1316. if (idx == SDFGI::MAX_DYNAMIC_LIGHTS) {
  1317. break;
  1318. }
  1319. LightInstance *li = light_instance_owner.getornull(render_state.sdfgi_update_data->directional_lights->get(j));
  1320. ERR_CONTINUE(!li);
  1321. if (storage->light_directional_is_sky_only(li->light)) {
  1322. continue;
  1323. }
  1324. Vector3 dir = -li->transform.basis.get_axis(Vector3::AXIS_Z);
  1325. dir.y *= rb->sdfgi->y_mult;
  1326. dir.normalize();
  1327. lights[idx].direction[0] = dir.x;
  1328. lights[idx].direction[1] = dir.y;
  1329. lights[idx].direction[2] = dir.z;
  1330. Color color = storage->light_get_color(li->light);
  1331. color = color.to_linear();
  1332. lights[idx].color[0] = color.r;
  1333. lights[idx].color[1] = color.g;
  1334. lights[idx].color[2] = color.b;
  1335. lights[idx].type = RS::LIGHT_DIRECTIONAL;
  1336. lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
  1337. lights[idx].has_shadow = storage->light_has_shadow(li->light);
  1338. idx++;
  1339. }
  1340. AABB cascade_aabb;
  1341. cascade_aabb.position = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + cascade.position)) * cascade.cell_size;
  1342. cascade_aabb.size = Vector3(1, 1, 1) * rb->sdfgi->cascade_size * cascade.cell_size;
  1343. for (uint32_t j = 0; j < render_state.sdfgi_update_data->positional_light_count; j++) {
  1344. if (idx == SDFGI::MAX_DYNAMIC_LIGHTS) {
  1345. break;
  1346. }
  1347. LightInstance *li = light_instance_owner.getornull(render_state.sdfgi_update_data->positional_light_instances[j]);
  1348. ERR_CONTINUE(!li);
  1349. uint32_t max_sdfgi_cascade = storage->light_get_max_sdfgi_cascade(li->light);
  1350. if (i > max_sdfgi_cascade) {
  1351. continue;
  1352. }
  1353. if (!cascade_aabb.intersects(li->aabb)) {
  1354. continue;
  1355. }
  1356. Vector3 dir = -li->transform.basis.get_axis(Vector3::AXIS_Z);
  1357. //faster to not do this here
  1358. //dir.y *= rb->sdfgi->y_mult;
  1359. //dir.normalize();
  1360. lights[idx].direction[0] = dir.x;
  1361. lights[idx].direction[1] = dir.y;
  1362. lights[idx].direction[2] = dir.z;
  1363. Vector3 pos = li->transform.origin;
  1364. pos.y *= rb->sdfgi->y_mult;
  1365. lights[idx].position[0] = pos.x;
  1366. lights[idx].position[1] = pos.y;
  1367. lights[idx].position[2] = pos.z;
  1368. Color color = storage->light_get_color(li->light);
  1369. color = color.to_linear();
  1370. lights[idx].color[0] = color.r;
  1371. lights[idx].color[1] = color.g;
  1372. lights[idx].color[2] = color.b;
  1373. lights[idx].type = storage->light_get_type(li->light);
  1374. lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
  1375. lights[idx].has_shadow = storage->light_has_shadow(li->light);
  1376. lights[idx].attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_ATTENUATION);
  1377. lights[idx].radius = storage->light_get_param(li->light, RS::LIGHT_PARAM_RANGE);
  1378. lights[idx].spot_angle = Math::deg2rad(storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ANGLE));
  1379. lights[idx].spot_attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  1380. idx++;
  1381. }
  1382. if (idx > 0) {
  1383. RD::get_singleton()->buffer_update(cascade.lights_buffer, 0, idx * sizeof(SDGIShader::Light), lights, RD::BARRIER_MASK_COMPUTE);
  1384. }
  1385. rb->sdfgi->cascade_dynamic_light_count[i] = idx;
  1386. }
  1387. }
  1388. }
  1389. void RendererSceneRenderRD::_process_gi(RID p_render_buffers, RID p_normal_roughness_buffer, RID p_gi_probe_buffer, RID p_environment, const CameraMatrix &p_projection, const Transform &p_transform, const PagedArray<RID> &p_gi_probes) {
  1390. RD::get_singleton()->draw_command_begin_label("GI Render");
  1391. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  1392. ERR_FAIL_COND(rb == nullptr);
  1393. Environment *env = environment_owner.getornull(p_environment);
  1394. if (rb->ambient_buffer.is_null() || rb->using_half_size_gi != gi.half_resolution) {
  1395. if (rb->ambient_buffer.is_valid()) {
  1396. RD::get_singleton()->free(rb->ambient_buffer);
  1397. RD::get_singleton()->free(rb->reflection_buffer);
  1398. }
  1399. RD::TextureFormat tf;
  1400. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1401. tf.width = rb->width;
  1402. tf.height = rb->height;
  1403. if (gi.half_resolution) {
  1404. tf.width >>= 1;
  1405. tf.height >>= 1;
  1406. }
  1407. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  1408. rb->reflection_buffer = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1409. rb->ambient_buffer = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1410. rb->using_half_size_gi = gi.half_resolution;
  1411. _render_buffers_uniform_set_changed(p_render_buffers);
  1412. }
  1413. GI::PushConstant push_constant;
  1414. push_constant.screen_size[0] = rb->width;
  1415. push_constant.screen_size[1] = rb->height;
  1416. push_constant.z_near = p_projection.get_z_near();
  1417. push_constant.z_far = p_projection.get_z_far();
  1418. push_constant.orthogonal = p_projection.is_orthogonal();
  1419. push_constant.proj_info[0] = -2.0f / (rb->width * p_projection.matrix[0][0]);
  1420. push_constant.proj_info[1] = -2.0f / (rb->height * p_projection.matrix[1][1]);
  1421. push_constant.proj_info[2] = (1.0f - p_projection.matrix[0][2]) / p_projection.matrix[0][0];
  1422. push_constant.proj_info[3] = (1.0f + p_projection.matrix[1][2]) / p_projection.matrix[1][1];
  1423. push_constant.max_giprobes = MIN((uint64_t)RenderBuffers::MAX_GIPROBES, p_gi_probes.size());
  1424. push_constant.high_quality_vct = gi_probe_quality == RS::GI_PROBE_QUALITY_HIGH;
  1425. bool use_sdfgi = rb->sdfgi != nullptr;
  1426. bool use_giprobes = push_constant.max_giprobes > 0;
  1427. if (env) {
  1428. push_constant.ao_color[0] = env->ao_color.r;
  1429. push_constant.ao_color[1] = env->ao_color.g;
  1430. push_constant.ao_color[2] = env->ao_color.b;
  1431. } else {
  1432. push_constant.ao_color[0] = 0;
  1433. push_constant.ao_color[1] = 0;
  1434. push_constant.ao_color[2] = 0;
  1435. }
  1436. push_constant.cam_rotation[0] = p_transform.basis[0][0];
  1437. push_constant.cam_rotation[1] = p_transform.basis[1][0];
  1438. push_constant.cam_rotation[2] = p_transform.basis[2][0];
  1439. push_constant.cam_rotation[3] = 0;
  1440. push_constant.cam_rotation[4] = p_transform.basis[0][1];
  1441. push_constant.cam_rotation[5] = p_transform.basis[1][1];
  1442. push_constant.cam_rotation[6] = p_transform.basis[2][1];
  1443. push_constant.cam_rotation[7] = 0;
  1444. push_constant.cam_rotation[8] = p_transform.basis[0][2];
  1445. push_constant.cam_rotation[9] = p_transform.basis[1][2];
  1446. push_constant.cam_rotation[10] = p_transform.basis[2][2];
  1447. push_constant.cam_rotation[11] = 0;
  1448. if (rb->gi_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(rb->gi_uniform_set)) {
  1449. Vector<RD::Uniform> uniforms;
  1450. {
  1451. RD::Uniform u;
  1452. u.binding = 1;
  1453. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1454. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  1455. if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
  1456. u.ids.push_back(rb->sdfgi->cascades[j].sdf_tex);
  1457. } else {
  1458. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  1459. }
  1460. }
  1461. uniforms.push_back(u);
  1462. }
  1463. {
  1464. RD::Uniform u;
  1465. u.binding = 2;
  1466. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1467. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  1468. if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
  1469. u.ids.push_back(rb->sdfgi->cascades[j].light_tex);
  1470. } else {
  1471. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  1472. }
  1473. }
  1474. uniforms.push_back(u);
  1475. }
  1476. {
  1477. RD::Uniform u;
  1478. u.binding = 3;
  1479. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1480. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  1481. if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
  1482. u.ids.push_back(rb->sdfgi->cascades[j].light_aniso_0_tex);
  1483. } else {
  1484. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  1485. }
  1486. }
  1487. uniforms.push_back(u);
  1488. }
  1489. {
  1490. RD::Uniform u;
  1491. u.binding = 4;
  1492. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1493. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  1494. if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
  1495. u.ids.push_back(rb->sdfgi->cascades[j].light_aniso_1_tex);
  1496. } else {
  1497. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  1498. }
  1499. }
  1500. uniforms.push_back(u);
  1501. }
  1502. {
  1503. RD::Uniform u;
  1504. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1505. u.binding = 5;
  1506. if (rb->sdfgi) {
  1507. u.ids.push_back(rb->sdfgi->occlusion_texture);
  1508. } else {
  1509. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  1510. }
  1511. uniforms.push_back(u);
  1512. }
  1513. {
  1514. RD::Uniform u;
  1515. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  1516. u.binding = 6;
  1517. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  1518. uniforms.push_back(u);
  1519. }
  1520. {
  1521. RD::Uniform u;
  1522. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  1523. u.binding = 7;
  1524. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  1525. uniforms.push_back(u);
  1526. }
  1527. {
  1528. RD::Uniform u;
  1529. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1530. u.binding = 9;
  1531. u.ids.push_back(rb->ambient_buffer);
  1532. uniforms.push_back(u);
  1533. }
  1534. {
  1535. RD::Uniform u;
  1536. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1537. u.binding = 10;
  1538. u.ids.push_back(rb->reflection_buffer);
  1539. uniforms.push_back(u);
  1540. }
  1541. {
  1542. RD::Uniform u;
  1543. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1544. u.binding = 11;
  1545. if (rb->sdfgi) {
  1546. u.ids.push_back(rb->sdfgi->lightprobe_texture);
  1547. } else {
  1548. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_2D_ARRAY_WHITE));
  1549. }
  1550. uniforms.push_back(u);
  1551. }
  1552. {
  1553. RD::Uniform u;
  1554. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1555. u.binding = 12;
  1556. u.ids.push_back(rb->depth_texture);
  1557. uniforms.push_back(u);
  1558. }
  1559. {
  1560. RD::Uniform u;
  1561. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1562. u.binding = 13;
  1563. u.ids.push_back(p_normal_roughness_buffer);
  1564. uniforms.push_back(u);
  1565. }
  1566. {
  1567. RD::Uniform u;
  1568. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1569. u.binding = 14;
  1570. RID buffer = p_gi_probe_buffer.is_valid() ? p_gi_probe_buffer : storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_BLACK);
  1571. u.ids.push_back(buffer);
  1572. uniforms.push_back(u);
  1573. }
  1574. {
  1575. RD::Uniform u;
  1576. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  1577. u.binding = 15;
  1578. u.ids.push_back(gi.sdfgi_ubo);
  1579. uniforms.push_back(u);
  1580. }
  1581. {
  1582. RD::Uniform u;
  1583. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  1584. u.binding = 16;
  1585. u.ids.push_back(rb->giprobe_buffer);
  1586. uniforms.push_back(u);
  1587. }
  1588. {
  1589. RD::Uniform u;
  1590. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1591. u.binding = 17;
  1592. for (int i = 0; i < RenderBuffers::MAX_GIPROBES; i++) {
  1593. u.ids.push_back(rb->giprobe_textures[i]);
  1594. }
  1595. uniforms.push_back(u);
  1596. }
  1597. rb->gi_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, gi.shader.version_get_shader(gi.shader_version, 0), 0);
  1598. }
  1599. GI::Mode mode;
  1600. if (rb->using_half_size_gi) {
  1601. mode = (use_sdfgi && use_giprobes) ? GI::MODE_HALF_RES_COMBINED : (use_sdfgi ? GI::MODE_HALF_RES_SDFGI : GI::MODE_HALF_RES_GIPROBE);
  1602. } else {
  1603. mode = (use_sdfgi && use_giprobes) ? GI::MODE_COMBINED : (use_sdfgi ? GI::MODE_SDFGI : GI::MODE_GIPROBE);
  1604. }
  1605. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin(true);
  1606. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, gi.pipelines[mode]);
  1607. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->gi_uniform_set, 0);
  1608. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GI::PushConstant));
  1609. if (rb->using_half_size_gi) {
  1610. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->width >> 1, rb->height >> 1, 1);
  1611. } else {
  1612. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->width, rb->height, 1);
  1613. }
  1614. //do barrier later to allow oeverlap
  1615. //RD::get_singleton()->compute_list_end(RD::BARRIER_MASK_NO_BARRIER); //no barriers, let other compute, raster and transfer happen at the same time
  1616. RD::get_singleton()->draw_command_end_label();
  1617. }
  1618. RID RendererSceneRenderRD::sky_create() {
  1619. return sky_owner.make_rid(Sky());
  1620. }
  1621. void RendererSceneRenderRD::_sky_invalidate(Sky *p_sky) {
  1622. if (!p_sky->dirty) {
  1623. p_sky->dirty = true;
  1624. p_sky->dirty_list = dirty_sky_list;
  1625. dirty_sky_list = p_sky;
  1626. }
  1627. }
  1628. void RendererSceneRenderRD::sky_set_radiance_size(RID p_sky, int p_radiance_size) {
  1629. Sky *sky = sky_owner.getornull(p_sky);
  1630. ERR_FAIL_COND(!sky);
  1631. ERR_FAIL_COND(p_radiance_size < 32 || p_radiance_size > 2048);
  1632. if (sky->radiance_size == p_radiance_size) {
  1633. return;
  1634. }
  1635. sky->radiance_size = p_radiance_size;
  1636. if (sky->mode == RS::SKY_MODE_REALTIME && sky->radiance_size != 256) {
  1637. WARN_PRINT("Realtime Skies can only use a radiance size of 256. Radiance size will be set to 256 internally.");
  1638. sky->radiance_size = 256;
  1639. }
  1640. _sky_invalidate(sky);
  1641. if (sky->radiance.is_valid()) {
  1642. RD::get_singleton()->free(sky->radiance);
  1643. sky->radiance = RID();
  1644. }
  1645. _clear_reflection_data(sky->reflection);
  1646. }
  1647. void RendererSceneRenderRD::sky_set_mode(RID p_sky, RS::SkyMode p_mode) {
  1648. Sky *sky = sky_owner.getornull(p_sky);
  1649. ERR_FAIL_COND(!sky);
  1650. if (sky->mode == p_mode) {
  1651. return;
  1652. }
  1653. sky->mode = p_mode;
  1654. if (sky->mode == RS::SKY_MODE_REALTIME && sky->radiance_size != 256) {
  1655. WARN_PRINT("Realtime Skies can only use a radiance size of 256. Radiance size will be set to 256 internally.");
  1656. sky_set_radiance_size(p_sky, 256);
  1657. }
  1658. _sky_invalidate(sky);
  1659. if (sky->radiance.is_valid()) {
  1660. RD::get_singleton()->free(sky->radiance);
  1661. sky->radiance = RID();
  1662. }
  1663. _clear_reflection_data(sky->reflection);
  1664. }
  1665. void RendererSceneRenderRD::sky_set_material(RID p_sky, RID p_material) {
  1666. Sky *sky = sky_owner.getornull(p_sky);
  1667. ERR_FAIL_COND(!sky);
  1668. sky->material = p_material;
  1669. _sky_invalidate(sky);
  1670. }
  1671. Ref<Image> RendererSceneRenderRD::sky_bake_panorama(RID p_sky, float p_energy, bool p_bake_irradiance, const Size2i &p_size) {
  1672. Sky *sky = sky_owner.getornull(p_sky);
  1673. ERR_FAIL_COND_V(!sky, Ref<Image>());
  1674. _update_dirty_skys();
  1675. if (sky->radiance.is_valid()) {
  1676. RD::TextureFormat tf;
  1677. tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  1678. tf.width = p_size.width;
  1679. tf.height = p_size.height;
  1680. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
  1681. RID rad_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1682. storage->get_effects()->copy_cubemap_to_panorama(sky->radiance, rad_tex, p_size, p_bake_irradiance ? roughness_layers : 0, sky->reflection.layers.size() > 1);
  1683. Vector<uint8_t> data = RD::get_singleton()->texture_get_data(rad_tex, 0);
  1684. RD::get_singleton()->free(rad_tex);
  1685. Ref<Image> img;
  1686. img.instance();
  1687. img->create(p_size.width, p_size.height, false, Image::FORMAT_RGBAF, data);
  1688. for (int i = 0; i < p_size.width; i++) {
  1689. for (int j = 0; j < p_size.height; j++) {
  1690. Color c = img->get_pixel(i, j);
  1691. c.r *= p_energy;
  1692. c.g *= p_energy;
  1693. c.b *= p_energy;
  1694. img->set_pixel(i, j, c);
  1695. }
  1696. }
  1697. return img;
  1698. }
  1699. return Ref<Image>();
  1700. }
  1701. void RendererSceneRenderRD::_update_dirty_skys() {
  1702. Sky *sky = dirty_sky_list;
  1703. while (sky) {
  1704. bool texture_set_dirty = false;
  1705. //update sky configuration if texture is missing
  1706. if (sky->radiance.is_null()) {
  1707. int mipmaps = Image::get_image_required_mipmaps(sky->radiance_size, sky->radiance_size, Image::FORMAT_RGBAH) + 1;
  1708. uint32_t w = sky->radiance_size, h = sky->radiance_size;
  1709. int layers = roughness_layers;
  1710. if (sky->mode == RS::SKY_MODE_REALTIME) {
  1711. layers = 8;
  1712. if (roughness_layers != 8) {
  1713. WARN_PRINT("When using REALTIME skies, roughness_layers should be set to 8 in the project settings for best quality reflections");
  1714. }
  1715. }
  1716. if (sky_use_cubemap_array) {
  1717. //array (higher quality, 6 times more memory)
  1718. RD::TextureFormat tf;
  1719. tf.array_layers = layers * 6;
  1720. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1721. tf.texture_type = RD::TEXTURE_TYPE_CUBE_ARRAY;
  1722. tf.mipmaps = mipmaps;
  1723. tf.width = w;
  1724. tf.height = h;
  1725. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  1726. sky->radiance = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1727. _update_reflection_data(sky->reflection, sky->radiance_size, mipmaps, true, sky->radiance, 0, sky->mode == RS::SKY_MODE_REALTIME);
  1728. } else {
  1729. //regular cubemap, lower quality (aliasing, less memory)
  1730. RD::TextureFormat tf;
  1731. tf.array_layers = 6;
  1732. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1733. tf.texture_type = RD::TEXTURE_TYPE_CUBE;
  1734. tf.mipmaps = MIN(mipmaps, layers);
  1735. tf.width = w;
  1736. tf.height = h;
  1737. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  1738. sky->radiance = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1739. _update_reflection_data(sky->reflection, sky->radiance_size, MIN(mipmaps, layers), false, sky->radiance, 0, sky->mode == RS::SKY_MODE_REALTIME);
  1740. }
  1741. texture_set_dirty = true;
  1742. }
  1743. // Create subpass buffers if they haven't been created already
  1744. if (sky->half_res_pass.is_null() && !RD::get_singleton()->texture_is_valid(sky->half_res_pass) && sky->screen_size.x >= 4 && sky->screen_size.y >= 4) {
  1745. RD::TextureFormat tformat;
  1746. tformat.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1747. tformat.width = sky->screen_size.x / 2;
  1748. tformat.height = sky->screen_size.y / 2;
  1749. tformat.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  1750. tformat.texture_type = RD::TEXTURE_TYPE_2D;
  1751. sky->half_res_pass = RD::get_singleton()->texture_create(tformat, RD::TextureView());
  1752. Vector<RID> texs;
  1753. texs.push_back(sky->half_res_pass);
  1754. sky->half_res_framebuffer = RD::get_singleton()->framebuffer_create(texs);
  1755. texture_set_dirty = true;
  1756. }
  1757. if (sky->quarter_res_pass.is_null() && !RD::get_singleton()->texture_is_valid(sky->quarter_res_pass) && sky->screen_size.x >= 4 && sky->screen_size.y >= 4) {
  1758. RD::TextureFormat tformat;
  1759. tformat.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1760. tformat.width = sky->screen_size.x / 4;
  1761. tformat.height = sky->screen_size.y / 4;
  1762. tformat.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  1763. tformat.texture_type = RD::TEXTURE_TYPE_2D;
  1764. sky->quarter_res_pass = RD::get_singleton()->texture_create(tformat, RD::TextureView());
  1765. Vector<RID> texs;
  1766. texs.push_back(sky->quarter_res_pass);
  1767. sky->quarter_res_framebuffer = RD::get_singleton()->framebuffer_create(texs);
  1768. texture_set_dirty = true;
  1769. }
  1770. if (texture_set_dirty) {
  1771. for (int i = 0; i < SKY_TEXTURE_SET_MAX; i++) {
  1772. if (sky->texture_uniform_sets[i].is_valid() && RD::get_singleton()->uniform_set_is_valid(sky->texture_uniform_sets[i])) {
  1773. RD::get_singleton()->free(sky->texture_uniform_sets[i]);
  1774. sky->texture_uniform_sets[i] = RID();
  1775. }
  1776. }
  1777. }
  1778. sky->reflection.dirty = true;
  1779. sky->processing_layer = 0;
  1780. Sky *next = sky->dirty_list;
  1781. sky->dirty_list = nullptr;
  1782. sky->dirty = false;
  1783. sky = next;
  1784. }
  1785. dirty_sky_list = nullptr;
  1786. }
  1787. RID RendererSceneRenderRD::sky_get_radiance_texture_rd(RID p_sky) const {
  1788. Sky *sky = sky_owner.getornull(p_sky);
  1789. ERR_FAIL_COND_V(!sky, RID());
  1790. return sky->radiance;
  1791. }
  1792. RID RendererSceneRenderRD::sky_get_radiance_uniform_set_rd(RID p_sky, RID p_shader, int p_set) const {
  1793. Sky *sky = sky_owner.getornull(p_sky);
  1794. ERR_FAIL_COND_V(!sky, RID());
  1795. if (sky->uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(sky->uniform_set)) {
  1796. sky->uniform_set = RID();
  1797. if (sky->radiance.is_valid()) {
  1798. Vector<RD::Uniform> uniforms;
  1799. {
  1800. RD::Uniform u;
  1801. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1802. u.binding = 0;
  1803. u.ids.push_back(sky->radiance);
  1804. uniforms.push_back(u);
  1805. }
  1806. sky->uniform_set = RD::get_singleton()->uniform_set_create(uniforms, p_shader, p_set);
  1807. }
  1808. }
  1809. return sky->uniform_set;
  1810. }
  1811. RID RendererSceneRenderRD::_get_sky_textures(Sky *p_sky, SkyTextureSetVersion p_version) {
  1812. if (p_sky->texture_uniform_sets[p_version].is_valid() && RD::get_singleton()->uniform_set_is_valid(p_sky->texture_uniform_sets[p_version])) {
  1813. return p_sky->texture_uniform_sets[p_version];
  1814. }
  1815. Vector<RD::Uniform> uniforms;
  1816. {
  1817. RD::Uniform u;
  1818. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1819. u.binding = 0;
  1820. if (p_sky->radiance.is_valid() && p_version <= SKY_TEXTURE_SET_QUARTER_RES) {
  1821. u.ids.push_back(p_sky->radiance);
  1822. } else {
  1823. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
  1824. }
  1825. uniforms.push_back(u);
  1826. }
  1827. {
  1828. RD::Uniform u;
  1829. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1830. u.binding = 1; // half res
  1831. if (p_sky->half_res_pass.is_valid() && p_version != SKY_TEXTURE_SET_HALF_RES && p_version != SKY_TEXTURE_SET_CUBEMAP_HALF_RES) {
  1832. if (p_version >= SKY_TEXTURE_SET_CUBEMAP) {
  1833. u.ids.push_back(p_sky->reflection.layers[0].views[1]);
  1834. } else {
  1835. u.ids.push_back(p_sky->half_res_pass);
  1836. }
  1837. } else {
  1838. if (p_version < SKY_TEXTURE_SET_CUBEMAP) {
  1839. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_WHITE));
  1840. } else {
  1841. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
  1842. }
  1843. }
  1844. uniforms.push_back(u);
  1845. }
  1846. {
  1847. RD::Uniform u;
  1848. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1849. u.binding = 2; // quarter res
  1850. if (p_sky->quarter_res_pass.is_valid() && p_version != SKY_TEXTURE_SET_QUARTER_RES && p_version != SKY_TEXTURE_SET_CUBEMAP_QUARTER_RES) {
  1851. if (p_version >= SKY_TEXTURE_SET_CUBEMAP) {
  1852. u.ids.push_back(p_sky->reflection.layers[0].views[2]);
  1853. } else {
  1854. u.ids.push_back(p_sky->quarter_res_pass);
  1855. }
  1856. } else {
  1857. if (p_version < SKY_TEXTURE_SET_CUBEMAP) {
  1858. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_WHITE));
  1859. } else {
  1860. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
  1861. }
  1862. }
  1863. uniforms.push_back(u);
  1864. }
  1865. p_sky->texture_uniform_sets[p_version] = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_TEXTURES);
  1866. return p_sky->texture_uniform_sets[p_version];
  1867. }
  1868. RID RendererSceneRenderRD::sky_get_material(RID p_sky) const {
  1869. Sky *sky = sky_owner.getornull(p_sky);
  1870. ERR_FAIL_COND_V(!sky, RID());
  1871. return sky->material;
  1872. }
  1873. void RendererSceneRenderRD::_draw_sky(bool p_can_continue_color, bool p_can_continue_depth, RID p_fb, RID p_environment, const CameraMatrix &p_projection, const Transform &p_transform) {
  1874. ERR_FAIL_COND(!is_environment(p_environment));
  1875. SkyMaterialData *material = nullptr;
  1876. Sky *sky = sky_owner.getornull(environment_get_sky(p_environment));
  1877. RID sky_material;
  1878. RS::EnvironmentBG background = environment_get_background(p_environment);
  1879. if (!(background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) || sky) {
  1880. ERR_FAIL_COND(!sky);
  1881. sky_material = sky_get_material(environment_get_sky(p_environment));
  1882. if (sky_material.is_valid()) {
  1883. material = (SkyMaterialData *)storage->material_get_data(sky_material, RendererStorageRD::SHADER_TYPE_SKY);
  1884. if (!material || !material->shader_data->valid) {
  1885. material = nullptr;
  1886. }
  1887. }
  1888. if (!material) {
  1889. sky_material = sky_shader.default_material;
  1890. material = (SkyMaterialData *)storage->material_get_data(sky_material, RendererStorageRD::SHADER_TYPE_SKY);
  1891. }
  1892. }
  1893. if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) {
  1894. sky_material = sky_scene_state.fog_material;
  1895. material = (SkyMaterialData *)storage->material_get_data(sky_material, RendererStorageRD::SHADER_TYPE_SKY);
  1896. }
  1897. ERR_FAIL_COND(!material);
  1898. SkyShaderData *shader_data = material->shader_data;
  1899. ERR_FAIL_COND(!shader_data);
  1900. Basis sky_transform = environment_get_sky_orientation(p_environment);
  1901. sky_transform.invert();
  1902. float multiplier = environment_get_bg_energy(p_environment);
  1903. float custom_fov = environment_get_sky_custom_fov(p_environment);
  1904. // Camera
  1905. CameraMatrix camera;
  1906. if (custom_fov) {
  1907. float near_plane = p_projection.get_z_near();
  1908. float far_plane = p_projection.get_z_far();
  1909. float aspect = p_projection.get_aspect();
  1910. camera.set_perspective(custom_fov, aspect, near_plane, far_plane);
  1911. } else {
  1912. camera = p_projection;
  1913. }
  1914. sky_transform = p_transform.basis * sky_transform;
  1915. if (shader_data->uses_quarter_res) {
  1916. PipelineCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_QUARTER_RES];
  1917. RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_QUARTER_RES);
  1918. Vector<Color> clear_colors;
  1919. clear_colors.push_back(Color(0.0, 0.0, 0.0));
  1920. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(sky->quarter_res_framebuffer, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
  1921. storage->get_effects()->render_sky(draw_list, time, sky->quarter_res_framebuffer, sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, camera, sky_transform, multiplier, p_transform.origin);
  1922. RD::get_singleton()->draw_list_end();
  1923. }
  1924. if (shader_data->uses_half_res) {
  1925. PipelineCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_HALF_RES];
  1926. RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_HALF_RES);
  1927. Vector<Color> clear_colors;
  1928. clear_colors.push_back(Color(0.0, 0.0, 0.0));
  1929. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(sky->half_res_framebuffer, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
  1930. storage->get_effects()->render_sky(draw_list, time, sky->half_res_framebuffer, sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, camera, sky_transform, multiplier, p_transform.origin);
  1931. RD::get_singleton()->draw_list_end();
  1932. }
  1933. PipelineCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_BACKGROUND];
  1934. RID texture_uniform_set;
  1935. if (sky) {
  1936. texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_BACKGROUND);
  1937. } else {
  1938. texture_uniform_set = sky_scene_state.fog_only_texture_uniform_set;
  1939. }
  1940. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(p_fb, RD::INITIAL_ACTION_CONTINUE, p_can_continue_color ? RD::FINAL_ACTION_CONTINUE : RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CONTINUE, p_can_continue_depth ? RD::FINAL_ACTION_CONTINUE : RD::FINAL_ACTION_READ);
  1941. storage->get_effects()->render_sky(draw_list, time, p_fb, sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, camera, sky_transform, multiplier, p_transform.origin);
  1942. RD::get_singleton()->draw_list_end();
  1943. }
  1944. void RendererSceneRenderRD::_setup_sky(RID p_environment, RID p_render_buffers, const CameraMatrix &p_projection, const Transform &p_transform, const Size2i p_screen_size) {
  1945. ERR_FAIL_COND(!is_environment(p_environment));
  1946. SkyMaterialData *material = nullptr;
  1947. Sky *sky = sky_owner.getornull(environment_get_sky(p_environment));
  1948. RID sky_material;
  1949. SkyShaderData *shader_data = nullptr;
  1950. RS::EnvironmentBG background = environment_get_background(p_environment);
  1951. if (!(background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) || sky) {
  1952. ERR_FAIL_COND(!sky);
  1953. sky_material = sky_get_material(environment_get_sky(p_environment));
  1954. if (sky_material.is_valid()) {
  1955. material = (SkyMaterialData *)storage->material_get_data(sky_material, RendererStorageRD::SHADER_TYPE_SKY);
  1956. if (!material || !material->shader_data->valid) {
  1957. material = nullptr;
  1958. }
  1959. }
  1960. if (!material) {
  1961. sky_material = sky_shader.default_material;
  1962. material = (SkyMaterialData *)storage->material_get_data(sky_material, RendererStorageRD::SHADER_TYPE_SKY);
  1963. }
  1964. ERR_FAIL_COND(!material);
  1965. shader_data = material->shader_data;
  1966. ERR_FAIL_COND(!shader_data);
  1967. }
  1968. if (sky) {
  1969. // Invalidate supbass buffers if screen size changes
  1970. if (sky->screen_size != p_screen_size) {
  1971. sky->screen_size = p_screen_size;
  1972. sky->screen_size.x = sky->screen_size.x < 4 ? 4 : sky->screen_size.x;
  1973. sky->screen_size.y = sky->screen_size.y < 4 ? 4 : sky->screen_size.y;
  1974. if (shader_data->uses_half_res) {
  1975. if (sky->half_res_pass.is_valid()) {
  1976. RD::get_singleton()->free(sky->half_res_pass);
  1977. sky->half_res_pass = RID();
  1978. }
  1979. _sky_invalidate(sky);
  1980. }
  1981. if (shader_data->uses_quarter_res) {
  1982. if (sky->quarter_res_pass.is_valid()) {
  1983. RD::get_singleton()->free(sky->quarter_res_pass);
  1984. sky->quarter_res_pass = RID();
  1985. }
  1986. _sky_invalidate(sky);
  1987. }
  1988. }
  1989. // Create new subpass buffers if necessary
  1990. if ((shader_data->uses_half_res && sky->half_res_pass.is_null()) ||
  1991. (shader_data->uses_quarter_res && sky->quarter_res_pass.is_null()) ||
  1992. sky->radiance.is_null()) {
  1993. _sky_invalidate(sky);
  1994. _update_dirty_skys();
  1995. }
  1996. if (shader_data->uses_time && time - sky->prev_time > 0.00001) {
  1997. sky->prev_time = time;
  1998. sky->reflection.dirty = true;
  1999. RenderingServerDefault::redraw_request();
  2000. }
  2001. if (material != sky->prev_material) {
  2002. sky->prev_material = material;
  2003. sky->reflection.dirty = true;
  2004. }
  2005. if (material->uniform_set_updated) {
  2006. material->uniform_set_updated = false;
  2007. sky->reflection.dirty = true;
  2008. }
  2009. if (!p_transform.origin.is_equal_approx(sky->prev_position) && shader_data->uses_position) {
  2010. sky->prev_position = p_transform.origin;
  2011. sky->reflection.dirty = true;
  2012. }
  2013. if (shader_data->uses_light) {
  2014. // Check whether the directional_light_buffer changes
  2015. bool light_data_dirty = false;
  2016. if (sky_scene_state.ubo.directional_light_count != sky_scene_state.last_frame_directional_light_count) {
  2017. light_data_dirty = true;
  2018. for (uint32_t i = sky_scene_state.ubo.directional_light_count; i < sky_scene_state.max_directional_lights; i++) {
  2019. sky_scene_state.directional_lights[i].enabled = false;
  2020. }
  2021. }
  2022. if (!light_data_dirty) {
  2023. for (uint32_t i = 0; i < sky_scene_state.ubo.directional_light_count; i++) {
  2024. if (sky_scene_state.directional_lights[i].direction[0] != sky_scene_state.last_frame_directional_lights[i].direction[0] ||
  2025. sky_scene_state.directional_lights[i].direction[1] != sky_scene_state.last_frame_directional_lights[i].direction[1] ||
  2026. sky_scene_state.directional_lights[i].direction[2] != sky_scene_state.last_frame_directional_lights[i].direction[2] ||
  2027. sky_scene_state.directional_lights[i].energy != sky_scene_state.last_frame_directional_lights[i].energy ||
  2028. sky_scene_state.directional_lights[i].color[0] != sky_scene_state.last_frame_directional_lights[i].color[0] ||
  2029. sky_scene_state.directional_lights[i].color[1] != sky_scene_state.last_frame_directional_lights[i].color[1] ||
  2030. sky_scene_state.directional_lights[i].color[2] != sky_scene_state.last_frame_directional_lights[i].color[2] ||
  2031. sky_scene_state.directional_lights[i].enabled != sky_scene_state.last_frame_directional_lights[i].enabled ||
  2032. sky_scene_state.directional_lights[i].size != sky_scene_state.last_frame_directional_lights[i].size) {
  2033. light_data_dirty = true;
  2034. break;
  2035. }
  2036. }
  2037. }
  2038. if (light_data_dirty) {
  2039. RD::get_singleton()->buffer_update(sky_scene_state.directional_light_buffer, 0, sizeof(SkyDirectionalLightData) * sky_scene_state.max_directional_lights, sky_scene_state.directional_lights);
  2040. RendererSceneRenderRD::SkyDirectionalLightData *temp = sky_scene_state.last_frame_directional_lights;
  2041. sky_scene_state.last_frame_directional_lights = sky_scene_state.directional_lights;
  2042. sky_scene_state.directional_lights = temp;
  2043. sky_scene_state.last_frame_directional_light_count = sky_scene_state.ubo.directional_light_count;
  2044. sky->reflection.dirty = true;
  2045. }
  2046. }
  2047. }
  2048. //setup fog variables
  2049. sky_scene_state.ubo.volumetric_fog_enabled = false;
  2050. if (p_render_buffers.is_valid()) {
  2051. if (render_buffers_has_volumetric_fog(p_render_buffers)) {
  2052. sky_scene_state.ubo.volumetric_fog_enabled = true;
  2053. float fog_end = render_buffers_get_volumetric_fog_end(p_render_buffers);
  2054. if (fog_end > 0.0) {
  2055. sky_scene_state.ubo.volumetric_fog_inv_length = 1.0 / fog_end;
  2056. } else {
  2057. sky_scene_state.ubo.volumetric_fog_inv_length = 1.0;
  2058. }
  2059. float fog_detail_spread = render_buffers_get_volumetric_fog_detail_spread(p_render_buffers); //reverse lookup
  2060. if (fog_detail_spread > 0.0) {
  2061. sky_scene_state.ubo.volumetric_fog_detail_spread = 1.0 / fog_detail_spread;
  2062. } else {
  2063. sky_scene_state.ubo.volumetric_fog_detail_spread = 1.0;
  2064. }
  2065. }
  2066. RID fog_uniform_set = render_buffers_get_volumetric_fog_sky_uniform_set(p_render_buffers);
  2067. if (fog_uniform_set != RID()) {
  2068. sky_scene_state.fog_uniform_set = fog_uniform_set;
  2069. } else {
  2070. sky_scene_state.fog_uniform_set = sky_scene_state.default_fog_uniform_set;
  2071. }
  2072. }
  2073. sky_scene_state.ubo.z_far = p_projection.get_z_far();
  2074. sky_scene_state.ubo.fog_enabled = environment_is_fog_enabled(p_environment);
  2075. sky_scene_state.ubo.fog_density = environment_get_fog_density(p_environment);
  2076. sky_scene_state.ubo.fog_aerial_perspective = environment_get_fog_aerial_perspective(p_environment);
  2077. Color fog_color = environment_get_fog_light_color(p_environment).to_linear();
  2078. float fog_energy = environment_get_fog_light_energy(p_environment);
  2079. sky_scene_state.ubo.fog_light_color[0] = fog_color.r * fog_energy;
  2080. sky_scene_state.ubo.fog_light_color[1] = fog_color.g * fog_energy;
  2081. sky_scene_state.ubo.fog_light_color[2] = fog_color.b * fog_energy;
  2082. sky_scene_state.ubo.fog_sun_scatter = environment_get_fog_sun_scatter(p_environment);
  2083. RD::get_singleton()->buffer_update(sky_scene_state.uniform_buffer, 0, sizeof(SkySceneState::UBO), &sky_scene_state.ubo);
  2084. }
  2085. void RendererSceneRenderRD::_update_sky(RID p_environment, const CameraMatrix &p_projection, const Transform &p_transform) {
  2086. ERR_FAIL_COND(!is_environment(p_environment));
  2087. Sky *sky = sky_owner.getornull(environment_get_sky(p_environment));
  2088. ERR_FAIL_COND(!sky);
  2089. RID sky_material = sky_get_material(environment_get_sky(p_environment));
  2090. SkyMaterialData *material = nullptr;
  2091. if (sky_material.is_valid()) {
  2092. material = (SkyMaterialData *)storage->material_get_data(sky_material, RendererStorageRD::SHADER_TYPE_SKY);
  2093. if (!material || !material->shader_data->valid) {
  2094. material = nullptr;
  2095. }
  2096. }
  2097. if (!material) {
  2098. sky_material = sky_shader.default_material;
  2099. material = (SkyMaterialData *)storage->material_get_data(sky_material, RendererStorageRD::SHADER_TYPE_SKY);
  2100. }
  2101. ERR_FAIL_COND(!material);
  2102. SkyShaderData *shader_data = material->shader_data;
  2103. ERR_FAIL_COND(!shader_data);
  2104. float multiplier = environment_get_bg_energy(p_environment);
  2105. bool update_single_frame = sky->mode == RS::SKY_MODE_REALTIME || sky->mode == RS::SKY_MODE_QUALITY;
  2106. RS::SkyMode sky_mode = sky->mode;
  2107. if (sky_mode == RS::SKY_MODE_AUTOMATIC) {
  2108. if (shader_data->uses_time || shader_data->uses_position) {
  2109. update_single_frame = true;
  2110. sky_mode = RS::SKY_MODE_REALTIME;
  2111. } else if (shader_data->uses_light || shader_data->ubo_size > 0) {
  2112. update_single_frame = false;
  2113. sky_mode = RS::SKY_MODE_INCREMENTAL;
  2114. } else {
  2115. update_single_frame = true;
  2116. sky_mode = RS::SKY_MODE_QUALITY;
  2117. }
  2118. }
  2119. if (sky->processing_layer == 0 && sky_mode == RS::SKY_MODE_INCREMENTAL) {
  2120. // On the first frame after creating sky, rebuild in single frame
  2121. update_single_frame = true;
  2122. sky_mode = RS::SKY_MODE_QUALITY;
  2123. }
  2124. int max_processing_layer = sky_use_cubemap_array ? sky->reflection.layers.size() : sky->reflection.layers[0].mipmaps.size();
  2125. // Update radiance cubemap
  2126. if (sky->reflection.dirty && (sky->processing_layer >= max_processing_layer || update_single_frame)) {
  2127. static const Vector3 view_normals[6] = {
  2128. Vector3(+1, 0, 0),
  2129. Vector3(-1, 0, 0),
  2130. Vector3(0, +1, 0),
  2131. Vector3(0, -1, 0),
  2132. Vector3(0, 0, +1),
  2133. Vector3(0, 0, -1)
  2134. };
  2135. static const Vector3 view_up[6] = {
  2136. Vector3(0, -1, 0),
  2137. Vector3(0, -1, 0),
  2138. Vector3(0, 0, +1),
  2139. Vector3(0, 0, -1),
  2140. Vector3(0, -1, 0),
  2141. Vector3(0, -1, 0)
  2142. };
  2143. CameraMatrix cm;
  2144. cm.set_perspective(90, 1, 0.01, 10.0);
  2145. CameraMatrix correction;
  2146. correction.set_depth_correction(true);
  2147. cm = correction * cm;
  2148. if (shader_data->uses_quarter_res) {
  2149. PipelineCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP_QUARTER_RES];
  2150. Vector<Color> clear_colors;
  2151. clear_colors.push_back(Color(0.0, 0.0, 0.0));
  2152. RD::DrawListID cubemap_draw_list;
  2153. for (int i = 0; i < 6; i++) {
  2154. Transform local_view;
  2155. local_view.set_look_at(Vector3(0, 0, 0), view_normals[i], view_up[i]);
  2156. RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_CUBEMAP_QUARTER_RES);
  2157. cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[2].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
  2158. storage->get_effects()->render_sky(cubemap_draw_list, time, sky->reflection.layers[0].mipmaps[2].framebuffers[i], sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, cm, local_view.basis, multiplier, p_transform.origin);
  2159. RD::get_singleton()->draw_list_end();
  2160. }
  2161. }
  2162. if (shader_data->uses_half_res) {
  2163. PipelineCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP_HALF_RES];
  2164. Vector<Color> clear_colors;
  2165. clear_colors.push_back(Color(0.0, 0.0, 0.0));
  2166. RD::DrawListID cubemap_draw_list;
  2167. for (int i = 0; i < 6; i++) {
  2168. Transform local_view;
  2169. local_view.set_look_at(Vector3(0, 0, 0), view_normals[i], view_up[i]);
  2170. RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_CUBEMAP_HALF_RES);
  2171. cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[1].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
  2172. storage->get_effects()->render_sky(cubemap_draw_list, time, sky->reflection.layers[0].mipmaps[1].framebuffers[i], sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, cm, local_view.basis, multiplier, p_transform.origin);
  2173. RD::get_singleton()->draw_list_end();
  2174. }
  2175. }
  2176. RD::DrawListID cubemap_draw_list;
  2177. PipelineCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP];
  2178. for (int i = 0; i < 6; i++) {
  2179. Transform local_view;
  2180. local_view.set_look_at(Vector3(0, 0, 0), view_normals[i], view_up[i]);
  2181. RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_CUBEMAP);
  2182. cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[0].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
  2183. storage->get_effects()->render_sky(cubemap_draw_list, time, sky->reflection.layers[0].mipmaps[0].framebuffers[i], sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, cm, local_view.basis, multiplier, p_transform.origin);
  2184. RD::get_singleton()->draw_list_end();
  2185. }
  2186. if (sky_mode == RS::SKY_MODE_REALTIME) {
  2187. _create_reflection_fast_filter(sky->reflection, sky_use_cubemap_array);
  2188. if (sky_use_cubemap_array) {
  2189. _update_reflection_mipmaps(sky->reflection, 0, sky->reflection.layers.size());
  2190. }
  2191. } else {
  2192. if (update_single_frame) {
  2193. for (int i = 1; i < max_processing_layer; i++) {
  2194. _create_reflection_importance_sample(sky->reflection, sky_use_cubemap_array, 10, i);
  2195. }
  2196. if (sky_use_cubemap_array) {
  2197. _update_reflection_mipmaps(sky->reflection, 0, sky->reflection.layers.size());
  2198. }
  2199. } else {
  2200. if (sky_use_cubemap_array) {
  2201. // Multi-Frame so just update the first array level
  2202. _update_reflection_mipmaps(sky->reflection, 0, 1);
  2203. }
  2204. }
  2205. sky->processing_layer = 1;
  2206. }
  2207. sky->reflection.dirty = false;
  2208. } else {
  2209. if (sky_mode == RS::SKY_MODE_INCREMENTAL && sky->processing_layer < max_processing_layer) {
  2210. _create_reflection_importance_sample(sky->reflection, sky_use_cubemap_array, 10, sky->processing_layer);
  2211. if (sky_use_cubemap_array) {
  2212. _update_reflection_mipmaps(sky->reflection, sky->processing_layer, sky->processing_layer + 1);
  2213. }
  2214. sky->processing_layer++;
  2215. }
  2216. }
  2217. }
  2218. /* SKY SHADER */
  2219. void RendererSceneRenderRD::SkyShaderData::set_code(const String &p_code) {
  2220. //compile
  2221. code = p_code;
  2222. valid = false;
  2223. ubo_size = 0;
  2224. uniforms.clear();
  2225. if (code == String()) {
  2226. return; //just invalid, but no error
  2227. }
  2228. ShaderCompilerRD::GeneratedCode gen_code;
  2229. ShaderCompilerRD::IdentifierActions actions;
  2230. uses_time = false;
  2231. uses_half_res = false;
  2232. uses_quarter_res = false;
  2233. uses_position = false;
  2234. uses_light = false;
  2235. actions.render_mode_flags["use_half_res_pass"] = &uses_half_res;
  2236. actions.render_mode_flags["use_quarter_res_pass"] = &uses_quarter_res;
  2237. actions.usage_flag_pointers["TIME"] = &uses_time;
  2238. actions.usage_flag_pointers["POSITION"] = &uses_position;
  2239. actions.usage_flag_pointers["LIGHT0_ENABLED"] = &uses_light;
  2240. actions.usage_flag_pointers["LIGHT0_ENERGY"] = &uses_light;
  2241. actions.usage_flag_pointers["LIGHT0_DIRECTION"] = &uses_light;
  2242. actions.usage_flag_pointers["LIGHT0_COLOR"] = &uses_light;
  2243. actions.usage_flag_pointers["LIGHT0_SIZE"] = &uses_light;
  2244. actions.usage_flag_pointers["LIGHT1_ENABLED"] = &uses_light;
  2245. actions.usage_flag_pointers["LIGHT1_ENERGY"] = &uses_light;
  2246. actions.usage_flag_pointers["LIGHT1_DIRECTION"] = &uses_light;
  2247. actions.usage_flag_pointers["LIGHT1_COLOR"] = &uses_light;
  2248. actions.usage_flag_pointers["LIGHT1_SIZE"] = &uses_light;
  2249. actions.usage_flag_pointers["LIGHT2_ENABLED"] = &uses_light;
  2250. actions.usage_flag_pointers["LIGHT2_ENERGY"] = &uses_light;
  2251. actions.usage_flag_pointers["LIGHT2_DIRECTION"] = &uses_light;
  2252. actions.usage_flag_pointers["LIGHT2_COLOR"] = &uses_light;
  2253. actions.usage_flag_pointers["LIGHT2_SIZE"] = &uses_light;
  2254. actions.usage_flag_pointers["LIGHT3_ENABLED"] = &uses_light;
  2255. actions.usage_flag_pointers["LIGHT3_ENERGY"] = &uses_light;
  2256. actions.usage_flag_pointers["LIGHT3_DIRECTION"] = &uses_light;
  2257. actions.usage_flag_pointers["LIGHT3_COLOR"] = &uses_light;
  2258. actions.usage_flag_pointers["LIGHT3_SIZE"] = &uses_light;
  2259. actions.uniforms = &uniforms;
  2260. RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton;
  2261. Error err = scene_singleton->sky_shader.compiler.compile(RS::SHADER_SKY, code, &actions, path, gen_code);
  2262. ERR_FAIL_COND(err != OK);
  2263. if (version.is_null()) {
  2264. version = scene_singleton->sky_shader.shader.version_create();
  2265. }
  2266. #if 0
  2267. print_line("**compiling shader:");
  2268. print_line("**defines:\n");
  2269. for (int i = 0; i < gen_code.defines.size(); i++) {
  2270. print_line(gen_code.defines[i]);
  2271. }
  2272. print_line("\n**uniforms:\n" + gen_code.uniforms);
  2273. // print_line("\n**vertex_globals:\n" + gen_code.vertex_global);
  2274. // print_line("\n**vertex_code:\n" + gen_code.vertex);
  2275. print_line("\n**fragment_globals:\n" + gen_code.fragment_global);
  2276. print_line("\n**fragment_code:\n" + gen_code.fragment);
  2277. print_line("\n**light_code:\n" + gen_code.light);
  2278. #endif
  2279. scene_singleton->sky_shader.shader.version_set_code(version, gen_code.uniforms, gen_code.vertex_global, gen_code.vertex, gen_code.fragment_global, gen_code.light, gen_code.fragment, gen_code.defines);
  2280. ERR_FAIL_COND(!scene_singleton->sky_shader.shader.version_is_valid(version));
  2281. ubo_size = gen_code.uniform_total_size;
  2282. ubo_offsets = gen_code.uniform_offsets;
  2283. texture_uniforms = gen_code.texture_uniforms;
  2284. //update pipelines
  2285. for (int i = 0; i < SKY_VERSION_MAX; i++) {
  2286. RD::PipelineDepthStencilState depth_stencil_state;
  2287. depth_stencil_state.enable_depth_test = true;
  2288. depth_stencil_state.depth_compare_operator = RD::COMPARE_OP_LESS_OR_EQUAL;
  2289. RID shader_variant = scene_singleton->sky_shader.shader.version_get_shader(version, i);
  2290. pipelines[i].setup(shader_variant, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), depth_stencil_state, RD::PipelineColorBlendState::create_disabled(), 0);
  2291. }
  2292. valid = true;
  2293. }
  2294. void RendererSceneRenderRD::SkyShaderData::set_default_texture_param(const StringName &p_name, RID p_texture) {
  2295. if (!p_texture.is_valid()) {
  2296. default_texture_params.erase(p_name);
  2297. } else {
  2298. default_texture_params[p_name] = p_texture;
  2299. }
  2300. }
  2301. void RendererSceneRenderRD::SkyShaderData::get_param_list(List<PropertyInfo> *p_param_list) const {
  2302. Map<int, StringName> order;
  2303. for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = uniforms.front(); E; E = E->next()) {
  2304. if (E->get().scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL || E->get().scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
  2305. continue;
  2306. }
  2307. if (E->get().texture_order >= 0) {
  2308. order[E->get().texture_order + 100000] = E->key();
  2309. } else {
  2310. order[E->get().order] = E->key();
  2311. }
  2312. }
  2313. for (Map<int, StringName>::Element *E = order.front(); E; E = E->next()) {
  2314. PropertyInfo pi = ShaderLanguage::uniform_to_property_info(uniforms[E->get()]);
  2315. pi.name = E->get();
  2316. p_param_list->push_back(pi);
  2317. }
  2318. }
  2319. void RendererSceneRenderRD::SkyShaderData::get_instance_param_list(List<RendererStorage::InstanceShaderParam> *p_param_list) const {
  2320. for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = uniforms.front(); E; E = E->next()) {
  2321. if (E->get().scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
  2322. continue;
  2323. }
  2324. RendererStorage::InstanceShaderParam p;
  2325. p.info = ShaderLanguage::uniform_to_property_info(E->get());
  2326. p.info.name = E->key(); //supply name
  2327. p.index = E->get().instance_index;
  2328. p.default_value = ShaderLanguage::constant_value_to_variant(E->get().default_value, E->get().type, E->get().hint);
  2329. p_param_list->push_back(p);
  2330. }
  2331. }
  2332. bool RendererSceneRenderRD::SkyShaderData::is_param_texture(const StringName &p_param) const {
  2333. if (!uniforms.has(p_param)) {
  2334. return false;
  2335. }
  2336. return uniforms[p_param].texture_order >= 0;
  2337. }
  2338. bool RendererSceneRenderRD::SkyShaderData::is_animated() const {
  2339. return false;
  2340. }
  2341. bool RendererSceneRenderRD::SkyShaderData::casts_shadows() const {
  2342. return false;
  2343. }
  2344. Variant RendererSceneRenderRD::SkyShaderData::get_default_parameter(const StringName &p_parameter) const {
  2345. if (uniforms.has(p_parameter)) {
  2346. ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter];
  2347. Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value;
  2348. return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint);
  2349. }
  2350. return Variant();
  2351. }
  2352. RS::ShaderNativeSourceCode RendererSceneRenderRD::SkyShaderData::get_native_source_code() const {
  2353. RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton;
  2354. return scene_singleton->sky_shader.shader.version_get_native_source_code(version);
  2355. }
  2356. RendererSceneRenderRD::SkyShaderData::SkyShaderData() {
  2357. valid = false;
  2358. }
  2359. RendererSceneRenderRD::SkyShaderData::~SkyShaderData() {
  2360. RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton;
  2361. ERR_FAIL_COND(!scene_singleton);
  2362. //pipeline variants will clear themselves if shader is gone
  2363. if (version.is_valid()) {
  2364. scene_singleton->sky_shader.shader.version_free(version);
  2365. }
  2366. }
  2367. RendererStorageRD::ShaderData *RendererSceneRenderRD::_create_sky_shader_func() {
  2368. SkyShaderData *shader_data = memnew(SkyShaderData);
  2369. return shader_data;
  2370. }
  2371. void RendererSceneRenderRD::SkyMaterialData::update_parameters(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
  2372. RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton;
  2373. uniform_set_updated = true;
  2374. if ((uint32_t)ubo_data.size() != shader_data->ubo_size) {
  2375. p_uniform_dirty = true;
  2376. if (uniform_buffer.is_valid()) {
  2377. RD::get_singleton()->free(uniform_buffer);
  2378. uniform_buffer = RID();
  2379. }
  2380. ubo_data.resize(shader_data->ubo_size);
  2381. if (ubo_data.size()) {
  2382. uniform_buffer = RD::get_singleton()->uniform_buffer_create(ubo_data.size());
  2383. memset(ubo_data.ptrw(), 0, ubo_data.size()); //clear
  2384. }
  2385. //clear previous uniform set
  2386. if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  2387. RD::get_singleton()->free(uniform_set);
  2388. uniform_set = RID();
  2389. }
  2390. }
  2391. //check whether buffer changed
  2392. if (p_uniform_dirty && ubo_data.size()) {
  2393. update_uniform_buffer(shader_data->uniforms, shader_data->ubo_offsets.ptr(), p_parameters, ubo_data.ptrw(), ubo_data.size(), false);
  2394. RD::get_singleton()->buffer_update(uniform_buffer, 0, ubo_data.size(), ubo_data.ptrw());
  2395. }
  2396. uint32_t tex_uniform_count = shader_data->texture_uniforms.size();
  2397. if ((uint32_t)texture_cache.size() != tex_uniform_count) {
  2398. texture_cache.resize(tex_uniform_count);
  2399. p_textures_dirty = true;
  2400. //clear previous uniform set
  2401. if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  2402. RD::get_singleton()->free(uniform_set);
  2403. uniform_set = RID();
  2404. }
  2405. }
  2406. if (p_textures_dirty && tex_uniform_count) {
  2407. update_textures(p_parameters, shader_data->default_texture_params, shader_data->texture_uniforms, texture_cache.ptrw(), true);
  2408. }
  2409. if (shader_data->ubo_size == 0 && shader_data->texture_uniforms.size() == 0) {
  2410. // This material does not require an uniform set, so don't create it.
  2411. return;
  2412. }
  2413. if (!p_textures_dirty && uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  2414. //no reason to update uniform set, only UBO (or nothing) was needed to update
  2415. return;
  2416. }
  2417. Vector<RD::Uniform> uniforms;
  2418. {
  2419. if (shader_data->ubo_size) {
  2420. RD::Uniform u;
  2421. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  2422. u.binding = 0;
  2423. u.ids.push_back(uniform_buffer);
  2424. uniforms.push_back(u);
  2425. }
  2426. const RID *textures = texture_cache.ptrw();
  2427. for (uint32_t i = 0; i < tex_uniform_count; i++) {
  2428. RD::Uniform u;
  2429. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  2430. u.binding = 1 + i;
  2431. u.ids.push_back(textures[i]);
  2432. uniforms.push_back(u);
  2433. }
  2434. }
  2435. uniform_set = RD::get_singleton()->uniform_set_create(uniforms, scene_singleton->sky_shader.shader.version_get_shader(shader_data->version, 0), SKY_SET_MATERIAL);
  2436. }
  2437. RendererSceneRenderRD::SkyMaterialData::~SkyMaterialData() {
  2438. if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  2439. RD::get_singleton()->free(uniform_set);
  2440. }
  2441. if (uniform_buffer.is_valid()) {
  2442. RD::get_singleton()->free(uniform_buffer);
  2443. }
  2444. }
  2445. RendererStorageRD::MaterialData *RendererSceneRenderRD::_create_sky_material_func(SkyShaderData *p_shader) {
  2446. SkyMaterialData *material_data = memnew(SkyMaterialData);
  2447. material_data->shader_data = p_shader;
  2448. material_data->last_frame = false;
  2449. //update will happen later anyway so do nothing.
  2450. return material_data;
  2451. }
  2452. RID RendererSceneRenderRD::environment_create() {
  2453. return environment_owner.make_rid(Environment());
  2454. }
  2455. void RendererSceneRenderRD::environment_set_background(RID p_env, RS::EnvironmentBG p_bg) {
  2456. Environment *env = environment_owner.getornull(p_env);
  2457. ERR_FAIL_COND(!env);
  2458. env->background = p_bg;
  2459. }
  2460. void RendererSceneRenderRD::environment_set_sky(RID p_env, RID p_sky) {
  2461. Environment *env = environment_owner.getornull(p_env);
  2462. ERR_FAIL_COND(!env);
  2463. env->sky = p_sky;
  2464. }
  2465. void RendererSceneRenderRD::environment_set_sky_custom_fov(RID p_env, float p_scale) {
  2466. Environment *env = environment_owner.getornull(p_env);
  2467. ERR_FAIL_COND(!env);
  2468. env->sky_custom_fov = p_scale;
  2469. }
  2470. void RendererSceneRenderRD::environment_set_sky_orientation(RID p_env, const Basis &p_orientation) {
  2471. Environment *env = environment_owner.getornull(p_env);
  2472. ERR_FAIL_COND(!env);
  2473. env->sky_orientation = p_orientation;
  2474. }
  2475. void RendererSceneRenderRD::environment_set_bg_color(RID p_env, const Color &p_color) {
  2476. Environment *env = environment_owner.getornull(p_env);
  2477. ERR_FAIL_COND(!env);
  2478. env->bg_color = p_color;
  2479. }
  2480. void RendererSceneRenderRD::environment_set_bg_energy(RID p_env, float p_energy) {
  2481. Environment *env = environment_owner.getornull(p_env);
  2482. ERR_FAIL_COND(!env);
  2483. env->bg_energy = p_energy;
  2484. }
  2485. void RendererSceneRenderRD::environment_set_canvas_max_layer(RID p_env, int p_max_layer) {
  2486. Environment *env = environment_owner.getornull(p_env);
  2487. ERR_FAIL_COND(!env);
  2488. env->canvas_max_layer = p_max_layer;
  2489. }
  2490. void RendererSceneRenderRD::environment_set_ambient_light(RID p_env, const Color &p_color, RS::EnvironmentAmbientSource p_ambient, float p_energy, float p_sky_contribution, RS::EnvironmentReflectionSource p_reflection_source, const Color &p_ao_color) {
  2491. Environment *env = environment_owner.getornull(p_env);
  2492. ERR_FAIL_COND(!env);
  2493. env->ambient_light = p_color;
  2494. env->ambient_source = p_ambient;
  2495. env->ambient_light_energy = p_energy;
  2496. env->ambient_sky_contribution = p_sky_contribution;
  2497. env->reflection_source = p_reflection_source;
  2498. env->ao_color = p_ao_color;
  2499. }
  2500. RS::EnvironmentBG RendererSceneRenderRD::environment_get_background(RID p_env) const {
  2501. Environment *env = environment_owner.getornull(p_env);
  2502. ERR_FAIL_COND_V(!env, RS::ENV_BG_MAX);
  2503. return env->background;
  2504. }
  2505. RID RendererSceneRenderRD::environment_get_sky(RID p_env) const {
  2506. Environment *env = environment_owner.getornull(p_env);
  2507. ERR_FAIL_COND_V(!env, RID());
  2508. return env->sky;
  2509. }
  2510. float RendererSceneRenderRD::environment_get_sky_custom_fov(RID p_env) const {
  2511. Environment *env = environment_owner.getornull(p_env);
  2512. ERR_FAIL_COND_V(!env, 0);
  2513. return env->sky_custom_fov;
  2514. }
  2515. Basis RendererSceneRenderRD::environment_get_sky_orientation(RID p_env) const {
  2516. Environment *env = environment_owner.getornull(p_env);
  2517. ERR_FAIL_COND_V(!env, Basis());
  2518. return env->sky_orientation;
  2519. }
  2520. Color RendererSceneRenderRD::environment_get_bg_color(RID p_env) const {
  2521. Environment *env = environment_owner.getornull(p_env);
  2522. ERR_FAIL_COND_V(!env, Color());
  2523. return env->bg_color;
  2524. }
  2525. float RendererSceneRenderRD::environment_get_bg_energy(RID p_env) const {
  2526. Environment *env = environment_owner.getornull(p_env);
  2527. ERR_FAIL_COND_V(!env, 0);
  2528. return env->bg_energy;
  2529. }
  2530. int RendererSceneRenderRD::environment_get_canvas_max_layer(RID p_env) const {
  2531. Environment *env = environment_owner.getornull(p_env);
  2532. ERR_FAIL_COND_V(!env, 0);
  2533. return env->canvas_max_layer;
  2534. }
  2535. Color RendererSceneRenderRD::environment_get_ambient_light_color(RID p_env) const {
  2536. Environment *env = environment_owner.getornull(p_env);
  2537. ERR_FAIL_COND_V(!env, Color());
  2538. return env->ambient_light;
  2539. }
  2540. RS::EnvironmentAmbientSource RendererSceneRenderRD::environment_get_ambient_source(RID p_env) const {
  2541. Environment *env = environment_owner.getornull(p_env);
  2542. ERR_FAIL_COND_V(!env, RS::ENV_AMBIENT_SOURCE_BG);
  2543. return env->ambient_source;
  2544. }
  2545. float RendererSceneRenderRD::environment_get_ambient_light_energy(RID p_env) const {
  2546. Environment *env = environment_owner.getornull(p_env);
  2547. ERR_FAIL_COND_V(!env, 0);
  2548. return env->ambient_light_energy;
  2549. }
  2550. float RendererSceneRenderRD::environment_get_ambient_sky_contribution(RID p_env) const {
  2551. Environment *env = environment_owner.getornull(p_env);
  2552. ERR_FAIL_COND_V(!env, 0);
  2553. return env->ambient_sky_contribution;
  2554. }
  2555. RS::EnvironmentReflectionSource RendererSceneRenderRD::environment_get_reflection_source(RID p_env) const {
  2556. Environment *env = environment_owner.getornull(p_env);
  2557. ERR_FAIL_COND_V(!env, RS::ENV_REFLECTION_SOURCE_DISABLED);
  2558. return env->reflection_source;
  2559. }
  2560. Color RendererSceneRenderRD::environment_get_ao_color(RID p_env) const {
  2561. Environment *env = environment_owner.getornull(p_env);
  2562. ERR_FAIL_COND_V(!env, Color());
  2563. return env->ao_color;
  2564. }
  2565. void RendererSceneRenderRD::environment_set_tonemap(RID p_env, RS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale) {
  2566. Environment *env = environment_owner.getornull(p_env);
  2567. ERR_FAIL_COND(!env);
  2568. env->exposure = p_exposure;
  2569. env->tone_mapper = p_tone_mapper;
  2570. if (!env->auto_exposure && p_auto_exposure) {
  2571. env->auto_exposure_version = ++auto_exposure_counter;
  2572. }
  2573. env->auto_exposure = p_auto_exposure;
  2574. env->white = p_white;
  2575. env->min_luminance = p_min_luminance;
  2576. env->max_luminance = p_max_luminance;
  2577. env->auto_exp_speed = p_auto_exp_speed;
  2578. env->auto_exp_scale = p_auto_exp_scale;
  2579. }
  2580. void RendererSceneRenderRD::environment_set_glow(RID p_env, bool p_enable, Vector<float> p_levels, float p_intensity, float p_strength, float p_mix, float p_bloom_threshold, RS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_threshold, float p_hdr_bleed_scale, float p_hdr_luminance_cap) {
  2581. Environment *env = environment_owner.getornull(p_env);
  2582. ERR_FAIL_COND(!env);
  2583. ERR_FAIL_COND_MSG(p_levels.size() != 7, "Size of array of glow levels must be 7");
  2584. env->glow_enabled = p_enable;
  2585. env->glow_levels = p_levels;
  2586. env->glow_intensity = p_intensity;
  2587. env->glow_strength = p_strength;
  2588. env->glow_mix = p_mix;
  2589. env->glow_bloom = p_bloom_threshold;
  2590. env->glow_blend_mode = p_blend_mode;
  2591. env->glow_hdr_bleed_threshold = p_hdr_bleed_threshold;
  2592. env->glow_hdr_bleed_scale = p_hdr_bleed_scale;
  2593. env->glow_hdr_luminance_cap = p_hdr_luminance_cap;
  2594. }
  2595. void RendererSceneRenderRD::environment_glow_set_use_bicubic_upscale(bool p_enable) {
  2596. glow_bicubic_upscale = p_enable;
  2597. }
  2598. void RendererSceneRenderRD::environment_glow_set_use_high_quality(bool p_enable) {
  2599. glow_high_quality = p_enable;
  2600. }
  2601. void RendererSceneRenderRD::environment_set_sdfgi(RID p_env, bool p_enable, RS::EnvironmentSDFGICascades p_cascades, float p_min_cell_size, RS::EnvironmentSDFGIYScale p_y_scale, bool p_use_occlusion, bool p_use_multibounce, bool p_read_sky, float p_energy, float p_normal_bias, float p_probe_bias) {
  2602. Environment *env = environment_owner.getornull(p_env);
  2603. ERR_FAIL_COND(!env);
  2604. if (low_end) {
  2605. return;
  2606. }
  2607. env->sdfgi_enabled = p_enable;
  2608. env->sdfgi_cascades = p_cascades;
  2609. env->sdfgi_min_cell_size = p_min_cell_size;
  2610. env->sdfgi_use_occlusion = p_use_occlusion;
  2611. env->sdfgi_use_multibounce = p_use_multibounce;
  2612. env->sdfgi_read_sky_light = p_read_sky;
  2613. env->sdfgi_energy = p_energy;
  2614. env->sdfgi_normal_bias = p_normal_bias;
  2615. env->sdfgi_probe_bias = p_probe_bias;
  2616. env->sdfgi_y_scale = p_y_scale;
  2617. }
  2618. void RendererSceneRenderRD::environment_set_fog(RID p_env, bool p_enable, const Color &p_light_color, float p_light_energy, float p_sun_scatter, float p_density, float p_height, float p_height_density, float p_fog_aerial_perspective) {
  2619. Environment *env = environment_owner.getornull(p_env);
  2620. ERR_FAIL_COND(!env);
  2621. env->fog_enabled = p_enable;
  2622. env->fog_light_color = p_light_color;
  2623. env->fog_light_energy = p_light_energy;
  2624. env->fog_sun_scatter = p_sun_scatter;
  2625. env->fog_density = p_density;
  2626. env->fog_height = p_height;
  2627. env->fog_height_density = p_height_density;
  2628. env->fog_aerial_perspective = p_fog_aerial_perspective;
  2629. }
  2630. bool RendererSceneRenderRD::environment_is_fog_enabled(RID p_env) const {
  2631. const Environment *env = environment_owner.getornull(p_env);
  2632. ERR_FAIL_COND_V(!env, false);
  2633. return env->fog_enabled;
  2634. }
  2635. Color RendererSceneRenderRD::environment_get_fog_light_color(RID p_env) const {
  2636. const Environment *env = environment_owner.getornull(p_env);
  2637. ERR_FAIL_COND_V(!env, Color());
  2638. return env->fog_light_color;
  2639. }
  2640. float RendererSceneRenderRD::environment_get_fog_light_energy(RID p_env) const {
  2641. const Environment *env = environment_owner.getornull(p_env);
  2642. ERR_FAIL_COND_V(!env, 0);
  2643. return env->fog_light_energy;
  2644. }
  2645. float RendererSceneRenderRD::environment_get_fog_sun_scatter(RID p_env) const {
  2646. const Environment *env = environment_owner.getornull(p_env);
  2647. ERR_FAIL_COND_V(!env, 0);
  2648. return env->fog_sun_scatter;
  2649. }
  2650. float RendererSceneRenderRD::environment_get_fog_density(RID p_env) const {
  2651. const Environment *env = environment_owner.getornull(p_env);
  2652. ERR_FAIL_COND_V(!env, 0);
  2653. return env->fog_density;
  2654. }
  2655. float RendererSceneRenderRD::environment_get_fog_height(RID p_env) const {
  2656. const Environment *env = environment_owner.getornull(p_env);
  2657. ERR_FAIL_COND_V(!env, 0);
  2658. return env->fog_height;
  2659. }
  2660. float RendererSceneRenderRD::environment_get_fog_height_density(RID p_env) const {
  2661. const Environment *env = environment_owner.getornull(p_env);
  2662. ERR_FAIL_COND_V(!env, 0);
  2663. return env->fog_height_density;
  2664. }
  2665. float RendererSceneRenderRD::environment_get_fog_aerial_perspective(RID p_env) const {
  2666. const Environment *env = environment_owner.getornull(p_env);
  2667. ERR_FAIL_COND_V(!env, 0);
  2668. return env->fog_aerial_perspective;
  2669. }
  2670. void RendererSceneRenderRD::environment_set_volumetric_fog(RID p_env, bool p_enable, float p_density, const Color &p_light, float p_light_energy, float p_length, float p_detail_spread, float p_gi_inject, RenderingServer::EnvVolumetricFogShadowFilter p_shadow_filter) {
  2671. Environment *env = environment_owner.getornull(p_env);
  2672. ERR_FAIL_COND(!env);
  2673. if (low_end) {
  2674. return;
  2675. }
  2676. env->volumetric_fog_enabled = p_enable;
  2677. env->volumetric_fog_density = p_density;
  2678. env->volumetric_fog_light = p_light;
  2679. env->volumetric_fog_light_energy = p_light_energy;
  2680. env->volumetric_fog_length = p_length;
  2681. env->volumetric_fog_detail_spread = p_detail_spread;
  2682. env->volumetric_fog_shadow_filter = p_shadow_filter;
  2683. env->volumetric_fog_gi_inject = p_gi_inject;
  2684. }
  2685. void RendererSceneRenderRD::environment_set_volumetric_fog_volume_size(int p_size, int p_depth) {
  2686. volumetric_fog_size = p_size;
  2687. volumetric_fog_depth = p_depth;
  2688. }
  2689. void RendererSceneRenderRD::environment_set_volumetric_fog_filter_active(bool p_enable) {
  2690. volumetric_fog_filter_active = p_enable;
  2691. }
  2692. void RendererSceneRenderRD::environment_set_volumetric_fog_directional_shadow_shrink_size(int p_shrink_size) {
  2693. p_shrink_size = nearest_power_of_2_templated(p_shrink_size);
  2694. if (volumetric_fog_directional_shadow_shrink == (uint32_t)p_shrink_size) {
  2695. return;
  2696. }
  2697. _clear_shadow_shrink_stages(directional_shadow.shrink_stages);
  2698. }
  2699. void RendererSceneRenderRD::environment_set_volumetric_fog_positional_shadow_shrink_size(int p_shrink_size) {
  2700. p_shrink_size = nearest_power_of_2_templated(p_shrink_size);
  2701. if (volumetric_fog_positional_shadow_shrink == (uint32_t)p_shrink_size) {
  2702. return;
  2703. }
  2704. for (uint32_t i = 0; i < shadow_atlas_owner.get_rid_count(); i++) {
  2705. ShadowAtlas *sa = shadow_atlas_owner.get_ptr_by_index(i);
  2706. _clear_shadow_shrink_stages(sa->shrink_stages);
  2707. }
  2708. }
  2709. void RendererSceneRenderRD::environment_set_sdfgi_ray_count(RS::EnvironmentSDFGIRayCount p_ray_count) {
  2710. sdfgi_ray_count = p_ray_count;
  2711. }
  2712. void RendererSceneRenderRD::environment_set_sdfgi_frames_to_converge(RS::EnvironmentSDFGIFramesToConverge p_frames) {
  2713. sdfgi_frames_to_converge = p_frames;
  2714. }
  2715. void RendererSceneRenderRD::environment_set_sdfgi_frames_to_update_light(RS::EnvironmentSDFGIFramesToUpdateLight p_update) {
  2716. sdfgi_frames_to_update_light = p_update;
  2717. }
  2718. void RendererSceneRenderRD::environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_fade_int, float p_fade_out, float p_depth_tolerance) {
  2719. Environment *env = environment_owner.getornull(p_env);
  2720. ERR_FAIL_COND(!env);
  2721. if (low_end) {
  2722. return;
  2723. }
  2724. env->ssr_enabled = p_enable;
  2725. env->ssr_max_steps = p_max_steps;
  2726. env->ssr_fade_in = p_fade_int;
  2727. env->ssr_fade_out = p_fade_out;
  2728. env->ssr_depth_tolerance = p_depth_tolerance;
  2729. }
  2730. void RendererSceneRenderRD::environment_set_ssr_roughness_quality(RS::EnvironmentSSRRoughnessQuality p_quality) {
  2731. ssr_roughness_quality = p_quality;
  2732. }
  2733. RS::EnvironmentSSRRoughnessQuality RendererSceneRenderRD::environment_get_ssr_roughness_quality() const {
  2734. return ssr_roughness_quality;
  2735. }
  2736. void RendererSceneRenderRD::environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_power, float p_detail, float p_horizon, float p_sharpness, float p_light_affect, float p_ao_channel_affect) {
  2737. Environment *env = environment_owner.getornull(p_env);
  2738. ERR_FAIL_COND(!env);
  2739. if (low_end) {
  2740. return;
  2741. }
  2742. env->ssao_enabled = p_enable;
  2743. env->ssao_radius = p_radius;
  2744. env->ssao_intensity = p_intensity;
  2745. env->ssao_power = p_power;
  2746. env->ssao_detail = p_detail;
  2747. env->ssao_horizon = p_horizon;
  2748. env->ssao_sharpness = p_sharpness;
  2749. env->ssao_direct_light_affect = p_light_affect;
  2750. env->ssao_ao_channel_affect = p_ao_channel_affect;
  2751. }
  2752. void RendererSceneRenderRD::environment_set_ssao_quality(RS::EnvironmentSSAOQuality p_quality, bool p_half_size, float p_adaptive_target, int p_blur_passes, float p_fadeout_from, float p_fadeout_to) {
  2753. ssao_quality = p_quality;
  2754. ssao_half_size = p_half_size;
  2755. ssao_adaptive_target = p_adaptive_target;
  2756. ssao_blur_passes = p_blur_passes;
  2757. ssao_fadeout_from = p_fadeout_from;
  2758. ssao_fadeout_to = p_fadeout_to;
  2759. }
  2760. bool RendererSceneRenderRD::environment_is_ssao_enabled(RID p_env) const {
  2761. Environment *env = environment_owner.getornull(p_env);
  2762. ERR_FAIL_COND_V(!env, false);
  2763. return env->ssao_enabled;
  2764. }
  2765. float RendererSceneRenderRD::environment_get_ssao_ao_affect(RID p_env) const {
  2766. Environment *env = environment_owner.getornull(p_env);
  2767. ERR_FAIL_COND_V(!env, 0.0);
  2768. return env->ssao_ao_channel_affect;
  2769. }
  2770. float RendererSceneRenderRD::environment_get_ssao_light_affect(RID p_env) const {
  2771. Environment *env = environment_owner.getornull(p_env);
  2772. ERR_FAIL_COND_V(!env, 0.0);
  2773. return env->ssao_direct_light_affect;
  2774. }
  2775. bool RendererSceneRenderRD::environment_is_ssr_enabled(RID p_env) const {
  2776. Environment *env = environment_owner.getornull(p_env);
  2777. ERR_FAIL_COND_V(!env, false);
  2778. return env->ssr_enabled;
  2779. }
  2780. bool RendererSceneRenderRD::environment_is_sdfgi_enabled(RID p_env) const {
  2781. Environment *env = environment_owner.getornull(p_env);
  2782. ERR_FAIL_COND_V(!env, false);
  2783. return env->sdfgi_enabled;
  2784. }
  2785. bool RendererSceneRenderRD::is_environment(RID p_env) const {
  2786. return environment_owner.owns(p_env);
  2787. }
  2788. Ref<Image> RendererSceneRenderRD::environment_bake_panorama(RID p_env, bool p_bake_irradiance, const Size2i &p_size) {
  2789. Environment *env = environment_owner.getornull(p_env);
  2790. ERR_FAIL_COND_V(!env, Ref<Image>());
  2791. if (env->background == RS::ENV_BG_CAMERA_FEED || env->background == RS::ENV_BG_CANVAS || env->background == RS::ENV_BG_KEEP) {
  2792. return Ref<Image>(); //nothing to bake
  2793. }
  2794. if (env->background == RS::ENV_BG_CLEAR_COLOR || env->background == RS::ENV_BG_COLOR) {
  2795. Color color;
  2796. if (env->background == RS::ENV_BG_CLEAR_COLOR) {
  2797. color = storage->get_default_clear_color();
  2798. } else {
  2799. color = env->bg_color;
  2800. }
  2801. color.r *= env->bg_energy;
  2802. color.g *= env->bg_energy;
  2803. color.b *= env->bg_energy;
  2804. Ref<Image> ret;
  2805. ret.instance();
  2806. ret->create(p_size.width, p_size.height, false, Image::FORMAT_RGBAF);
  2807. for (int i = 0; i < p_size.width; i++) {
  2808. for (int j = 0; j < p_size.height; j++) {
  2809. ret->set_pixel(i, j, color);
  2810. }
  2811. }
  2812. return ret;
  2813. }
  2814. if (env->background == RS::ENV_BG_SKY && env->sky.is_valid()) {
  2815. return sky_bake_panorama(env->sky, env->bg_energy, p_bake_irradiance, p_size);
  2816. }
  2817. return Ref<Image>();
  2818. }
  2819. ////////////////////////////////////////////////////////////
  2820. RID RendererSceneRenderRD::reflection_atlas_create() {
  2821. ReflectionAtlas ra;
  2822. ra.count = GLOBAL_GET("rendering/quality/reflection_atlas/reflection_count");
  2823. ra.size = GLOBAL_GET("rendering/quality/reflection_atlas/reflection_size");
  2824. ra.cluster_builder = memnew(ClusterBuilderRD);
  2825. ra.cluster_builder->set_shared(&cluster_builder_shared);
  2826. ra.cluster_builder->setup(Size2i(ra.size, ra.size), max_cluster_elements, RID(), RID(), RID());
  2827. return reflection_atlas_owner.make_rid(ra);
  2828. }
  2829. void RendererSceneRenderRD::reflection_atlas_set_size(RID p_ref_atlas, int p_reflection_size, int p_reflection_count) {
  2830. ReflectionAtlas *ra = reflection_atlas_owner.getornull(p_ref_atlas);
  2831. ERR_FAIL_COND(!ra);
  2832. if (ra->size == p_reflection_size && ra->count == p_reflection_count) {
  2833. return; //no changes
  2834. }
  2835. ra->cluster_builder->setup(Size2i(ra->size, ra->size), max_cluster_elements, RID(), RID(), RID());
  2836. ra->size = p_reflection_size;
  2837. ra->count = p_reflection_count;
  2838. if (ra->reflection.is_valid()) {
  2839. //clear and invalidate everything
  2840. RD::get_singleton()->free(ra->reflection);
  2841. ra->reflection = RID();
  2842. RD::get_singleton()->free(ra->depth_buffer);
  2843. ra->depth_buffer = RID();
  2844. for (int i = 0; i < ra->reflections.size(); i++) {
  2845. _clear_reflection_data(ra->reflections.write[i].data);
  2846. if (ra->reflections[i].owner.is_null()) {
  2847. continue;
  2848. }
  2849. reflection_probe_release_atlas_index(ra->reflections[i].owner);
  2850. //rp->atlasindex clear
  2851. }
  2852. ra->reflections.clear();
  2853. }
  2854. }
  2855. int RendererSceneRenderRD::reflection_atlas_get_size(RID p_ref_atlas) const {
  2856. ReflectionAtlas *ra = reflection_atlas_owner.getornull(p_ref_atlas);
  2857. ERR_FAIL_COND_V(!ra, 0);
  2858. return ra->size;
  2859. }
  2860. ////////////////////////
  2861. RID RendererSceneRenderRD::reflection_probe_instance_create(RID p_probe) {
  2862. ReflectionProbeInstance rpi;
  2863. rpi.probe = p_probe;
  2864. return reflection_probe_instance_owner.make_rid(rpi);
  2865. }
  2866. void RendererSceneRenderRD::reflection_probe_instance_set_transform(RID p_instance, const Transform &p_transform) {
  2867. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2868. ERR_FAIL_COND(!rpi);
  2869. rpi->transform = p_transform;
  2870. rpi->dirty = true;
  2871. }
  2872. void RendererSceneRenderRD::reflection_probe_release_atlas_index(RID p_instance) {
  2873. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2874. ERR_FAIL_COND(!rpi);
  2875. if (rpi->atlas.is_null()) {
  2876. return; //nothing to release
  2877. }
  2878. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
  2879. ERR_FAIL_COND(!atlas);
  2880. ERR_FAIL_INDEX(rpi->atlas_index, atlas->reflections.size());
  2881. atlas->reflections.write[rpi->atlas_index].owner = RID();
  2882. rpi->atlas_index = -1;
  2883. rpi->atlas = RID();
  2884. }
  2885. bool RendererSceneRenderRD::reflection_probe_instance_needs_redraw(RID p_instance) {
  2886. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2887. ERR_FAIL_COND_V(!rpi, false);
  2888. if (rpi->rendering) {
  2889. return false;
  2890. }
  2891. if (rpi->dirty) {
  2892. return true;
  2893. }
  2894. if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS) {
  2895. return true;
  2896. }
  2897. return rpi->atlas_index == -1;
  2898. }
  2899. bool RendererSceneRenderRD::reflection_probe_instance_has_reflection(RID p_instance) {
  2900. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2901. ERR_FAIL_COND_V(!rpi, false);
  2902. return rpi->atlas.is_valid();
  2903. }
  2904. bool RendererSceneRenderRD::reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas) {
  2905. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(p_reflection_atlas);
  2906. ERR_FAIL_COND_V(!atlas, false);
  2907. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2908. ERR_FAIL_COND_V(!rpi, false);
  2909. if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS && atlas->reflection.is_valid() && atlas->size != 256) {
  2910. WARN_PRINT("ReflectionProbes set to UPDATE_ALWAYS must have an atlas size of 256. Please update the atlas size in the ProjectSettings.");
  2911. reflection_atlas_set_size(p_reflection_atlas, 256, atlas->count);
  2912. }
  2913. if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS && atlas->reflection.is_valid() && atlas->reflections[0].data.layers[0].mipmaps.size() != 8) {
  2914. // Invalidate reflection atlas, need to regenerate
  2915. RD::get_singleton()->free(atlas->reflection);
  2916. atlas->reflection = RID();
  2917. for (int i = 0; i < atlas->reflections.size(); i++) {
  2918. if (atlas->reflections[i].owner.is_null()) {
  2919. continue;
  2920. }
  2921. reflection_probe_release_atlas_index(atlas->reflections[i].owner);
  2922. }
  2923. atlas->reflections.clear();
  2924. }
  2925. if (atlas->reflection.is_null()) {
  2926. int mipmaps = MIN(roughness_layers, Image::get_image_required_mipmaps(atlas->size, atlas->size, Image::FORMAT_RGBAH) + 1);
  2927. mipmaps = storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS ? 8 : mipmaps; // always use 8 mipmaps with real time filtering
  2928. {
  2929. //reflection atlas was unused, create:
  2930. RD::TextureFormat tf;
  2931. tf.array_layers = 6 * atlas->count;
  2932. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  2933. tf.texture_type = RD::TEXTURE_TYPE_CUBE_ARRAY;
  2934. tf.mipmaps = mipmaps;
  2935. tf.width = atlas->size;
  2936. tf.height = atlas->size;
  2937. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  2938. atlas->reflection = RD::get_singleton()->texture_create(tf, RD::TextureView());
  2939. }
  2940. {
  2941. RD::TextureFormat tf;
  2942. tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
  2943. tf.width = atlas->size;
  2944. tf.height = atlas->size;
  2945. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
  2946. atlas->depth_buffer = RD::get_singleton()->texture_create(tf, RD::TextureView());
  2947. }
  2948. atlas->reflections.resize(atlas->count);
  2949. for (int i = 0; i < atlas->count; i++) {
  2950. _update_reflection_data(atlas->reflections.write[i].data, atlas->size, mipmaps, false, atlas->reflection, i * 6, storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS);
  2951. for (int j = 0; j < 6; j++) {
  2952. Vector<RID> fb;
  2953. fb.push_back(atlas->reflections.write[i].data.layers[0].mipmaps[0].views[j]);
  2954. fb.push_back(atlas->depth_buffer);
  2955. atlas->reflections.write[i].fbs[j] = RD::get_singleton()->framebuffer_create(fb);
  2956. }
  2957. }
  2958. Vector<RID> fb;
  2959. fb.push_back(atlas->depth_buffer);
  2960. atlas->depth_fb = RD::get_singleton()->framebuffer_create(fb);
  2961. }
  2962. if (rpi->atlas_index == -1) {
  2963. for (int i = 0; i < atlas->reflections.size(); i++) {
  2964. if (atlas->reflections[i].owner.is_null()) {
  2965. rpi->atlas_index = i;
  2966. break;
  2967. }
  2968. }
  2969. //find the one used last
  2970. if (rpi->atlas_index == -1) {
  2971. //everything is in use, find the one least used via LRU
  2972. uint64_t pass_min = 0;
  2973. for (int i = 0; i < atlas->reflections.size(); i++) {
  2974. ReflectionProbeInstance *rpi2 = reflection_probe_instance_owner.getornull(atlas->reflections[i].owner);
  2975. if (rpi2->last_pass < pass_min) {
  2976. pass_min = rpi2->last_pass;
  2977. rpi->atlas_index = i;
  2978. }
  2979. }
  2980. }
  2981. }
  2982. rpi->atlas = p_reflection_atlas;
  2983. rpi->rendering = true;
  2984. rpi->dirty = false;
  2985. rpi->processing_layer = 1;
  2986. rpi->processing_side = 0;
  2987. return true;
  2988. }
  2989. bool RendererSceneRenderRD::reflection_probe_instance_postprocess_step(RID p_instance) {
  2990. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2991. ERR_FAIL_COND_V(!rpi, false);
  2992. ERR_FAIL_COND_V(!rpi->rendering, false);
  2993. ERR_FAIL_COND_V(rpi->atlas.is_null(), false);
  2994. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
  2995. if (!atlas || rpi->atlas_index == -1) {
  2996. //does not belong to an atlas anymore, cancel (was removed from atlas or atlas changed while rendering)
  2997. rpi->rendering = false;
  2998. return false;
  2999. }
  3000. if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS) {
  3001. // Using real time reflections, all roughness is done in one step
  3002. _create_reflection_fast_filter(atlas->reflections.write[rpi->atlas_index].data, false);
  3003. rpi->rendering = false;
  3004. rpi->processing_side = 0;
  3005. rpi->processing_layer = 1;
  3006. return true;
  3007. }
  3008. if (rpi->processing_layer > 1) {
  3009. _create_reflection_importance_sample(atlas->reflections.write[rpi->atlas_index].data, false, 10, rpi->processing_layer);
  3010. rpi->processing_layer++;
  3011. if (rpi->processing_layer == atlas->reflections[rpi->atlas_index].data.layers[0].mipmaps.size()) {
  3012. rpi->rendering = false;
  3013. rpi->processing_side = 0;
  3014. rpi->processing_layer = 1;
  3015. return true;
  3016. }
  3017. return false;
  3018. } else {
  3019. _create_reflection_importance_sample(atlas->reflections.write[rpi->atlas_index].data, false, rpi->processing_side, rpi->processing_layer);
  3020. }
  3021. rpi->processing_side++;
  3022. if (rpi->processing_side == 6) {
  3023. rpi->processing_side = 0;
  3024. rpi->processing_layer++;
  3025. }
  3026. return false;
  3027. }
  3028. uint32_t RendererSceneRenderRD::reflection_probe_instance_get_resolution(RID p_instance) {
  3029. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  3030. ERR_FAIL_COND_V(!rpi, 0);
  3031. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
  3032. ERR_FAIL_COND_V(!atlas, 0);
  3033. return atlas->size;
  3034. }
  3035. RID RendererSceneRenderRD::reflection_probe_instance_get_framebuffer(RID p_instance, int p_index) {
  3036. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  3037. ERR_FAIL_COND_V(!rpi, RID());
  3038. ERR_FAIL_INDEX_V(p_index, 6, RID());
  3039. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
  3040. ERR_FAIL_COND_V(!atlas, RID());
  3041. return atlas->reflections[rpi->atlas_index].fbs[p_index];
  3042. }
  3043. RID RendererSceneRenderRD::reflection_probe_instance_get_depth_framebuffer(RID p_instance, int p_index) {
  3044. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  3045. ERR_FAIL_COND_V(!rpi, RID());
  3046. ERR_FAIL_INDEX_V(p_index, 6, RID());
  3047. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
  3048. ERR_FAIL_COND_V(!atlas, RID());
  3049. return atlas->depth_fb;
  3050. }
  3051. ///////////////////////////////////////////////////////////
  3052. RID RendererSceneRenderRD::shadow_atlas_create() {
  3053. return shadow_atlas_owner.make_rid(ShadowAtlas());
  3054. }
  3055. void RendererSceneRenderRD::_update_shadow_atlas(ShadowAtlas *shadow_atlas) {
  3056. if (shadow_atlas->size > 0 && shadow_atlas->depth.is_null()) {
  3057. RD::TextureFormat tf;
  3058. tf.format = shadow_atlas->use_16_bits ? RD::DATA_FORMAT_D16_UNORM : RD::DATA_FORMAT_D32_SFLOAT;
  3059. tf.width = shadow_atlas->size;
  3060. tf.height = shadow_atlas->size;
  3061. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  3062. shadow_atlas->depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
  3063. Vector<RID> fb_tex;
  3064. fb_tex.push_back(shadow_atlas->depth);
  3065. shadow_atlas->fb = RD::get_singleton()->framebuffer_create(fb_tex);
  3066. }
  3067. }
  3068. void RendererSceneRenderRD::shadow_atlas_set_size(RID p_atlas, int p_size, bool p_16_bits) {
  3069. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
  3070. ERR_FAIL_COND(!shadow_atlas);
  3071. ERR_FAIL_COND(p_size < 0);
  3072. p_size = next_power_of_2(p_size);
  3073. if (p_size == shadow_atlas->size && p_16_bits == shadow_atlas->use_16_bits) {
  3074. return;
  3075. }
  3076. // erasing atlas
  3077. if (shadow_atlas->depth.is_valid()) {
  3078. RD::get_singleton()->free(shadow_atlas->depth);
  3079. shadow_atlas->depth = RID();
  3080. _clear_shadow_shrink_stages(shadow_atlas->shrink_stages);
  3081. }
  3082. for (int i = 0; i < 4; i++) {
  3083. //clear subdivisions
  3084. shadow_atlas->quadrants[i].shadows.resize(0);
  3085. shadow_atlas->quadrants[i].shadows.resize(1 << shadow_atlas->quadrants[i].subdivision);
  3086. }
  3087. //erase shadow atlas reference from lights
  3088. for (Map<RID, uint32_t>::Element *E = shadow_atlas->shadow_owners.front(); E; E = E->next()) {
  3089. LightInstance *li = light_instance_owner.getornull(E->key());
  3090. ERR_CONTINUE(!li);
  3091. li->shadow_atlases.erase(p_atlas);
  3092. }
  3093. //clear owners
  3094. shadow_atlas->shadow_owners.clear();
  3095. shadow_atlas->size = p_size;
  3096. shadow_atlas->use_16_bits = p_size;
  3097. }
  3098. void RendererSceneRenderRD::shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision) {
  3099. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
  3100. ERR_FAIL_COND(!shadow_atlas);
  3101. ERR_FAIL_INDEX(p_quadrant, 4);
  3102. ERR_FAIL_INDEX(p_subdivision, 16384);
  3103. uint32_t subdiv = next_power_of_2(p_subdivision);
  3104. if (subdiv & 0xaaaaaaaa) { //sqrt(subdiv) must be integer
  3105. subdiv <<= 1;
  3106. }
  3107. subdiv = int(Math::sqrt((float)subdiv));
  3108. //obtain the number that will be x*x
  3109. if (shadow_atlas->quadrants[p_quadrant].subdivision == subdiv) {
  3110. return;
  3111. }
  3112. //erase all data from quadrant
  3113. for (int i = 0; i < shadow_atlas->quadrants[p_quadrant].shadows.size(); i++) {
  3114. if (shadow_atlas->quadrants[p_quadrant].shadows[i].owner.is_valid()) {
  3115. shadow_atlas->shadow_owners.erase(shadow_atlas->quadrants[p_quadrant].shadows[i].owner);
  3116. LightInstance *li = light_instance_owner.getornull(shadow_atlas->quadrants[p_quadrant].shadows[i].owner);
  3117. ERR_CONTINUE(!li);
  3118. li->shadow_atlases.erase(p_atlas);
  3119. }
  3120. }
  3121. shadow_atlas->quadrants[p_quadrant].shadows.resize(0);
  3122. shadow_atlas->quadrants[p_quadrant].shadows.resize(subdiv * subdiv);
  3123. shadow_atlas->quadrants[p_quadrant].subdivision = subdiv;
  3124. //cache the smallest subdiv (for faster allocation in light update)
  3125. shadow_atlas->smallest_subdiv = 1 << 30;
  3126. for (int i = 0; i < 4; i++) {
  3127. if (shadow_atlas->quadrants[i].subdivision) {
  3128. shadow_atlas->smallest_subdiv = MIN(shadow_atlas->smallest_subdiv, shadow_atlas->quadrants[i].subdivision);
  3129. }
  3130. }
  3131. if (shadow_atlas->smallest_subdiv == 1 << 30) {
  3132. shadow_atlas->smallest_subdiv = 0;
  3133. }
  3134. //resort the size orders, simple bublesort for 4 elements..
  3135. int swaps = 0;
  3136. do {
  3137. swaps = 0;
  3138. for (int i = 0; i < 3; i++) {
  3139. if (shadow_atlas->quadrants[shadow_atlas->size_order[i]].subdivision < shadow_atlas->quadrants[shadow_atlas->size_order[i + 1]].subdivision) {
  3140. SWAP(shadow_atlas->size_order[i], shadow_atlas->size_order[i + 1]);
  3141. swaps++;
  3142. }
  3143. }
  3144. } while (swaps > 0);
  3145. }
  3146. bool RendererSceneRenderRD::_shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas, int *p_in_quadrants, int p_quadrant_count, int p_current_subdiv, uint64_t p_tick, int &r_quadrant, int &r_shadow) {
  3147. for (int i = p_quadrant_count - 1; i >= 0; i--) {
  3148. int qidx = p_in_quadrants[i];
  3149. if (shadow_atlas->quadrants[qidx].subdivision == (uint32_t)p_current_subdiv) {
  3150. return false;
  3151. }
  3152. //look for an empty space
  3153. int sc = shadow_atlas->quadrants[qidx].shadows.size();
  3154. ShadowAtlas::Quadrant::Shadow *sarr = shadow_atlas->quadrants[qidx].shadows.ptrw();
  3155. int found_free_idx = -1; //found a free one
  3156. int found_used_idx = -1; //found existing one, must steal it
  3157. uint64_t min_pass = 0; // pass of the existing one, try to use the least recently used one (LRU fashion)
  3158. for (int j = 0; j < sc; j++) {
  3159. if (!sarr[j].owner.is_valid()) {
  3160. found_free_idx = j;
  3161. break;
  3162. }
  3163. LightInstance *sli = light_instance_owner.getornull(sarr[j].owner);
  3164. ERR_CONTINUE(!sli);
  3165. if (sli->last_scene_pass != scene_pass) {
  3166. //was just allocated, don't kill it so soon, wait a bit..
  3167. if (p_tick - sarr[j].alloc_tick < shadow_atlas_realloc_tolerance_msec) {
  3168. continue;
  3169. }
  3170. if (found_used_idx == -1 || sli->last_scene_pass < min_pass) {
  3171. found_used_idx = j;
  3172. min_pass = sli->last_scene_pass;
  3173. }
  3174. }
  3175. }
  3176. if (found_free_idx == -1 && found_used_idx == -1) {
  3177. continue; //nothing found
  3178. }
  3179. if (found_free_idx == -1 && found_used_idx != -1) {
  3180. found_free_idx = found_used_idx;
  3181. }
  3182. r_quadrant = qidx;
  3183. r_shadow = found_free_idx;
  3184. return true;
  3185. }
  3186. return false;
  3187. }
  3188. bool RendererSceneRenderRD::shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version) {
  3189. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
  3190. ERR_FAIL_COND_V(!shadow_atlas, false);
  3191. LightInstance *li = light_instance_owner.getornull(p_light_intance);
  3192. ERR_FAIL_COND_V(!li, false);
  3193. if (shadow_atlas->size == 0 || shadow_atlas->smallest_subdiv == 0) {
  3194. return false;
  3195. }
  3196. uint32_t quad_size = shadow_atlas->size >> 1;
  3197. int desired_fit = MIN(quad_size / shadow_atlas->smallest_subdiv, next_power_of_2(quad_size * p_coverage));
  3198. int valid_quadrants[4];
  3199. int valid_quadrant_count = 0;
  3200. int best_size = -1; //best size found
  3201. int best_subdiv = -1; //subdiv for the best size
  3202. //find the quadrants this fits into, and the best possible size it can fit into
  3203. for (int i = 0; i < 4; i++) {
  3204. int q = shadow_atlas->size_order[i];
  3205. int sd = shadow_atlas->quadrants[q].subdivision;
  3206. if (sd == 0) {
  3207. continue; //unused
  3208. }
  3209. int max_fit = quad_size / sd;
  3210. if (best_size != -1 && max_fit > best_size) {
  3211. break; //too large
  3212. }
  3213. valid_quadrants[valid_quadrant_count++] = q;
  3214. best_subdiv = sd;
  3215. if (max_fit >= desired_fit) {
  3216. best_size = max_fit;
  3217. }
  3218. }
  3219. ERR_FAIL_COND_V(valid_quadrant_count == 0, false);
  3220. uint64_t tick = OS::get_singleton()->get_ticks_msec();
  3221. //see if it already exists
  3222. if (shadow_atlas->shadow_owners.has(p_light_intance)) {
  3223. //it does!
  3224. uint32_t key = shadow_atlas->shadow_owners[p_light_intance];
  3225. uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  3226. uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK;
  3227. bool should_realloc = shadow_atlas->quadrants[q].subdivision != (uint32_t)best_subdiv && (shadow_atlas->quadrants[q].shadows[s].alloc_tick - tick > shadow_atlas_realloc_tolerance_msec);
  3228. bool should_redraw = shadow_atlas->quadrants[q].shadows[s].version != p_light_version;
  3229. if (!should_realloc) {
  3230. shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version;
  3231. //already existing, see if it should redraw or it's just OK
  3232. return should_redraw;
  3233. }
  3234. int new_quadrant, new_shadow;
  3235. //find a better place
  3236. if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, shadow_atlas->quadrants[q].subdivision, tick, new_quadrant, new_shadow)) {
  3237. //found a better place!
  3238. ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow];
  3239. if (sh->owner.is_valid()) {
  3240. //is taken, but is invalid, erasing it
  3241. shadow_atlas->shadow_owners.erase(sh->owner);
  3242. LightInstance *sli = light_instance_owner.getornull(sh->owner);
  3243. sli->shadow_atlases.erase(p_atlas);
  3244. }
  3245. //erase previous
  3246. shadow_atlas->quadrants[q].shadows.write[s].version = 0;
  3247. shadow_atlas->quadrants[q].shadows.write[s].owner = RID();
  3248. sh->owner = p_light_intance;
  3249. sh->alloc_tick = tick;
  3250. sh->version = p_light_version;
  3251. li->shadow_atlases.insert(p_atlas);
  3252. //make new key
  3253. key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT;
  3254. key |= new_shadow;
  3255. //update it in map
  3256. shadow_atlas->shadow_owners[p_light_intance] = key;
  3257. //make it dirty, as it should redraw anyway
  3258. return true;
  3259. }
  3260. //no better place for this shadow found, keep current
  3261. //already existing, see if it should redraw or it's just OK
  3262. shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version;
  3263. return should_redraw;
  3264. }
  3265. int new_quadrant, new_shadow;
  3266. //find a better place
  3267. if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, -1, tick, new_quadrant, new_shadow)) {
  3268. //found a better place!
  3269. ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow];
  3270. if (sh->owner.is_valid()) {
  3271. //is taken, but is invalid, erasing it
  3272. shadow_atlas->shadow_owners.erase(sh->owner);
  3273. LightInstance *sli = light_instance_owner.getornull(sh->owner);
  3274. sli->shadow_atlases.erase(p_atlas);
  3275. }
  3276. sh->owner = p_light_intance;
  3277. sh->alloc_tick = tick;
  3278. sh->version = p_light_version;
  3279. li->shadow_atlases.insert(p_atlas);
  3280. //make new key
  3281. uint32_t key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT;
  3282. key |= new_shadow;
  3283. //update it in map
  3284. shadow_atlas->shadow_owners[p_light_intance] = key;
  3285. //make it dirty, as it should redraw anyway
  3286. return true;
  3287. }
  3288. //no place to allocate this light, apologies
  3289. return false;
  3290. }
  3291. void RendererSceneRenderRD::_update_directional_shadow_atlas() {
  3292. if (directional_shadow.depth.is_null() && directional_shadow.size > 0) {
  3293. RD::TextureFormat tf;
  3294. tf.format = directional_shadow.use_16_bits ? RD::DATA_FORMAT_D16_UNORM : RD::DATA_FORMAT_D32_SFLOAT;
  3295. tf.width = directional_shadow.size;
  3296. tf.height = directional_shadow.size;
  3297. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  3298. directional_shadow.depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
  3299. Vector<RID> fb_tex;
  3300. fb_tex.push_back(directional_shadow.depth);
  3301. directional_shadow.fb = RD::get_singleton()->framebuffer_create(fb_tex);
  3302. }
  3303. }
  3304. void RendererSceneRenderRD::directional_shadow_atlas_set_size(int p_size, bool p_16_bits) {
  3305. p_size = nearest_power_of_2_templated(p_size);
  3306. if (directional_shadow.size == p_size && directional_shadow.use_16_bits == p_16_bits) {
  3307. return;
  3308. }
  3309. directional_shadow.size = p_size;
  3310. if (directional_shadow.depth.is_valid()) {
  3311. RD::get_singleton()->free(directional_shadow.depth);
  3312. _clear_shadow_shrink_stages(directional_shadow.shrink_stages);
  3313. directional_shadow.depth = RID();
  3314. _base_uniforms_changed();
  3315. }
  3316. }
  3317. void RendererSceneRenderRD::set_directional_shadow_count(int p_count) {
  3318. directional_shadow.light_count = p_count;
  3319. directional_shadow.current_light = 0;
  3320. }
  3321. static Rect2i _get_directional_shadow_rect(int p_size, int p_shadow_count, int p_shadow_index) {
  3322. int split_h = 1;
  3323. int split_v = 1;
  3324. while (split_h * split_v < p_shadow_count) {
  3325. if (split_h == split_v) {
  3326. split_h <<= 1;
  3327. } else {
  3328. split_v <<= 1;
  3329. }
  3330. }
  3331. Rect2i rect(0, 0, p_size, p_size);
  3332. rect.size.width /= split_h;
  3333. rect.size.height /= split_v;
  3334. rect.position.x = rect.size.width * (p_shadow_index % split_h);
  3335. rect.position.y = rect.size.height * (p_shadow_index / split_h);
  3336. return rect;
  3337. }
  3338. int RendererSceneRenderRD::get_directional_light_shadow_size(RID p_light_intance) {
  3339. ERR_FAIL_COND_V(directional_shadow.light_count == 0, 0);
  3340. Rect2i r = _get_directional_shadow_rect(directional_shadow.size, directional_shadow.light_count, 0);
  3341. LightInstance *light_instance = light_instance_owner.getornull(p_light_intance);
  3342. ERR_FAIL_COND_V(!light_instance, 0);
  3343. switch (storage->light_directional_get_shadow_mode(light_instance->light)) {
  3344. case RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
  3345. break; //none
  3346. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
  3347. r.size.height /= 2;
  3348. break;
  3349. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
  3350. r.size /= 2;
  3351. break;
  3352. }
  3353. return MAX(r.size.width, r.size.height);
  3354. }
  3355. //////////////////////////////////////////////////
  3356. RID RendererSceneRenderRD::camera_effects_create() {
  3357. return camera_effects_owner.make_rid(CameraEffects());
  3358. }
  3359. void RendererSceneRenderRD::camera_effects_set_dof_blur_quality(RS::DOFBlurQuality p_quality, bool p_use_jitter) {
  3360. dof_blur_quality = p_quality;
  3361. dof_blur_use_jitter = p_use_jitter;
  3362. }
  3363. void RendererSceneRenderRD::camera_effects_set_dof_blur_bokeh_shape(RS::DOFBokehShape p_shape) {
  3364. dof_blur_bokeh_shape = p_shape;
  3365. }
  3366. void RendererSceneRenderRD::camera_effects_set_dof_blur(RID p_camera_effects, bool p_far_enable, float p_far_distance, float p_far_transition, bool p_near_enable, float p_near_distance, float p_near_transition, float p_amount) {
  3367. CameraEffects *camfx = camera_effects_owner.getornull(p_camera_effects);
  3368. ERR_FAIL_COND(!camfx);
  3369. camfx->dof_blur_far_enabled = p_far_enable;
  3370. camfx->dof_blur_far_distance = p_far_distance;
  3371. camfx->dof_blur_far_transition = p_far_transition;
  3372. camfx->dof_blur_near_enabled = p_near_enable;
  3373. camfx->dof_blur_near_distance = p_near_distance;
  3374. camfx->dof_blur_near_transition = p_near_transition;
  3375. camfx->dof_blur_amount = p_amount;
  3376. }
  3377. void RendererSceneRenderRD::camera_effects_set_custom_exposure(RID p_camera_effects, bool p_enable, float p_exposure) {
  3378. CameraEffects *camfx = camera_effects_owner.getornull(p_camera_effects);
  3379. ERR_FAIL_COND(!camfx);
  3380. camfx->override_exposure_enabled = p_enable;
  3381. camfx->override_exposure = p_exposure;
  3382. }
  3383. RID RendererSceneRenderRD::light_instance_create(RID p_light) {
  3384. RID li = light_instance_owner.make_rid(LightInstance());
  3385. LightInstance *light_instance = light_instance_owner.getornull(li);
  3386. light_instance->self = li;
  3387. light_instance->light = p_light;
  3388. light_instance->light_type = storage->light_get_type(p_light);
  3389. return li;
  3390. }
  3391. void RendererSceneRenderRD::light_instance_set_transform(RID p_light_instance, const Transform &p_transform) {
  3392. LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
  3393. ERR_FAIL_COND(!light_instance);
  3394. light_instance->transform = p_transform;
  3395. }
  3396. void RendererSceneRenderRD::light_instance_set_aabb(RID p_light_instance, const AABB &p_aabb) {
  3397. LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
  3398. ERR_FAIL_COND(!light_instance);
  3399. light_instance->aabb = p_aabb;
  3400. }
  3401. void RendererSceneRenderRD::light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform &p_transform, float p_far, float p_split, int p_pass, float p_shadow_texel_size, float p_bias_scale, float p_range_begin, const Vector2 &p_uv_scale) {
  3402. LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
  3403. ERR_FAIL_COND(!light_instance);
  3404. ERR_FAIL_INDEX(p_pass, 6);
  3405. light_instance->shadow_transform[p_pass].camera = p_projection;
  3406. light_instance->shadow_transform[p_pass].transform = p_transform;
  3407. light_instance->shadow_transform[p_pass].farplane = p_far;
  3408. light_instance->shadow_transform[p_pass].split = p_split;
  3409. light_instance->shadow_transform[p_pass].bias_scale = p_bias_scale;
  3410. light_instance->shadow_transform[p_pass].range_begin = p_range_begin;
  3411. light_instance->shadow_transform[p_pass].shadow_texel_size = p_shadow_texel_size;
  3412. light_instance->shadow_transform[p_pass].uv_scale = p_uv_scale;
  3413. }
  3414. void RendererSceneRenderRD::light_instance_mark_visible(RID p_light_instance) {
  3415. LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
  3416. ERR_FAIL_COND(!light_instance);
  3417. light_instance->last_scene_pass = scene_pass;
  3418. }
  3419. RendererSceneRenderRD::ShadowCubemap *RendererSceneRenderRD::_get_shadow_cubemap(int p_size) {
  3420. if (!shadow_cubemaps.has(p_size)) {
  3421. ShadowCubemap sc;
  3422. {
  3423. RD::TextureFormat tf;
  3424. tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
  3425. tf.width = p_size;
  3426. tf.height = p_size;
  3427. tf.texture_type = RD::TEXTURE_TYPE_CUBE;
  3428. tf.array_layers = 6;
  3429. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
  3430. sc.cubemap = RD::get_singleton()->texture_create(tf, RD::TextureView());
  3431. }
  3432. for (int i = 0; i < 6; i++) {
  3433. RID side_texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), sc.cubemap, i, 0);
  3434. Vector<RID> fbtex;
  3435. fbtex.push_back(side_texture);
  3436. sc.side_fb[i] = RD::get_singleton()->framebuffer_create(fbtex);
  3437. }
  3438. shadow_cubemaps[p_size] = sc;
  3439. }
  3440. return &shadow_cubemaps[p_size];
  3441. }
  3442. //////////////////////////
  3443. RID RendererSceneRenderRD::decal_instance_create(RID p_decal) {
  3444. DecalInstance di;
  3445. di.decal = p_decal;
  3446. return decal_instance_owner.make_rid(di);
  3447. }
  3448. void RendererSceneRenderRD::decal_instance_set_transform(RID p_decal, const Transform &p_transform) {
  3449. DecalInstance *di = decal_instance_owner.getornull(p_decal);
  3450. ERR_FAIL_COND(!di);
  3451. di->transform = p_transform;
  3452. }
  3453. /////////////////////////////////
  3454. RID RendererSceneRenderRD::lightmap_instance_create(RID p_lightmap) {
  3455. LightmapInstance li;
  3456. li.lightmap = p_lightmap;
  3457. return lightmap_instance_owner.make_rid(li);
  3458. }
  3459. void RendererSceneRenderRD::lightmap_instance_set_transform(RID p_lightmap, const Transform &p_transform) {
  3460. LightmapInstance *li = lightmap_instance_owner.getornull(p_lightmap);
  3461. ERR_FAIL_COND(!li);
  3462. li->transform = p_transform;
  3463. }
  3464. /////////////////////////////////
  3465. RID RendererSceneRenderRD::gi_probe_instance_create(RID p_base) {
  3466. GIProbeInstance gi_probe;
  3467. gi_probe.probe = p_base;
  3468. RID rid = gi_probe_instance_owner.make_rid(gi_probe);
  3469. return rid;
  3470. }
  3471. void RendererSceneRenderRD::gi_probe_instance_set_transform_to_data(RID p_probe, const Transform &p_xform) {
  3472. GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_probe);
  3473. ERR_FAIL_COND(!gi_probe);
  3474. gi_probe->transform = p_xform;
  3475. }
  3476. bool RendererSceneRenderRD::gi_probe_needs_update(RID p_probe) const {
  3477. GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_probe);
  3478. ERR_FAIL_COND_V(!gi_probe, false);
  3479. if (low_end) {
  3480. return false;
  3481. }
  3482. //return true;
  3483. return gi_probe->last_probe_version != storage->gi_probe_get_version(gi_probe->probe);
  3484. }
  3485. void RendererSceneRenderRD::gi_probe_update(RID p_probe, bool p_update_light_instances, const Vector<RID> &p_light_instances, const PagedArray<GeometryInstance *> &p_dynamic_objects) {
  3486. GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_probe);
  3487. ERR_FAIL_COND(!gi_probe);
  3488. if (low_end) {
  3489. return;
  3490. }
  3491. uint32_t data_version = storage->gi_probe_get_data_version(gi_probe->probe);
  3492. // (RE)CREATE IF NEEDED
  3493. if (gi_probe->last_probe_data_version != data_version) {
  3494. //need to re-create everything
  3495. if (gi_probe->texture.is_valid()) {
  3496. RD::get_singleton()->free(gi_probe->texture);
  3497. RD::get_singleton()->free(gi_probe->write_buffer);
  3498. gi_probe->mipmaps.clear();
  3499. }
  3500. for (int i = 0; i < gi_probe->dynamic_maps.size(); i++) {
  3501. RD::get_singleton()->free(gi_probe->dynamic_maps[i].texture);
  3502. RD::get_singleton()->free(gi_probe->dynamic_maps[i].depth);
  3503. }
  3504. gi_probe->dynamic_maps.clear();
  3505. Vector3i octree_size = storage->gi_probe_get_octree_size(gi_probe->probe);
  3506. if (octree_size != Vector3i()) {
  3507. //can create a 3D texture
  3508. Vector<int> levels = storage->gi_probe_get_level_counts(gi_probe->probe);
  3509. RD::TextureFormat tf;
  3510. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  3511. tf.width = octree_size.x;
  3512. tf.height = octree_size.y;
  3513. tf.depth = octree_size.z;
  3514. tf.texture_type = RD::TEXTURE_TYPE_3D;
  3515. tf.mipmaps = levels.size();
  3516. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT;
  3517. gi_probe->texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  3518. RD::get_singleton()->texture_clear(gi_probe->texture, Color(0, 0, 0, 0), 0, levels.size(), 0, 1);
  3519. {
  3520. int total_elements = 0;
  3521. for (int i = 0; i < levels.size(); i++) {
  3522. total_elements += levels[i];
  3523. }
  3524. gi_probe->write_buffer = RD::get_singleton()->storage_buffer_create(total_elements * 16);
  3525. }
  3526. for (int i = 0; i < levels.size(); i++) {
  3527. GIProbeInstance::Mipmap mipmap;
  3528. mipmap.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), gi_probe->texture, 0, i, RD::TEXTURE_SLICE_3D);
  3529. mipmap.level = levels.size() - i - 1;
  3530. mipmap.cell_offset = 0;
  3531. for (uint32_t j = 0; j < mipmap.level; j++) {
  3532. mipmap.cell_offset += levels[j];
  3533. }
  3534. mipmap.cell_count = levels[mipmap.level];
  3535. Vector<RD::Uniform> uniforms;
  3536. {
  3537. RD::Uniform u;
  3538. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  3539. u.binding = 1;
  3540. u.ids.push_back(storage->gi_probe_get_octree_buffer(gi_probe->probe));
  3541. uniforms.push_back(u);
  3542. }
  3543. {
  3544. RD::Uniform u;
  3545. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  3546. u.binding = 2;
  3547. u.ids.push_back(storage->gi_probe_get_data_buffer(gi_probe->probe));
  3548. uniforms.push_back(u);
  3549. }
  3550. {
  3551. RD::Uniform u;
  3552. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  3553. u.binding = 4;
  3554. u.ids.push_back(gi_probe->write_buffer);
  3555. uniforms.push_back(u);
  3556. }
  3557. {
  3558. RD::Uniform u;
  3559. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  3560. u.binding = 9;
  3561. u.ids.push_back(storage->gi_probe_get_sdf_texture(gi_probe->probe));
  3562. uniforms.push_back(u);
  3563. }
  3564. {
  3565. RD::Uniform u;
  3566. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  3567. u.binding = 10;
  3568. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  3569. uniforms.push_back(u);
  3570. }
  3571. {
  3572. Vector<RD::Uniform> copy_uniforms = uniforms;
  3573. if (i == 0) {
  3574. {
  3575. RD::Uniform u;
  3576. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  3577. u.binding = 3;
  3578. u.ids.push_back(gi_probe_lights_uniform);
  3579. copy_uniforms.push_back(u);
  3580. }
  3581. mipmap.uniform_set = RD::get_singleton()->uniform_set_create(copy_uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_COMPUTE_LIGHT], 0);
  3582. copy_uniforms = uniforms; //restore
  3583. {
  3584. RD::Uniform u;
  3585. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  3586. u.binding = 5;
  3587. u.ids.push_back(gi_probe->texture);
  3588. copy_uniforms.push_back(u);
  3589. }
  3590. mipmap.second_bounce_uniform_set = RD::get_singleton()->uniform_set_create(copy_uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_COMPUTE_SECOND_BOUNCE], 0);
  3591. } else {
  3592. mipmap.uniform_set = RD::get_singleton()->uniform_set_create(copy_uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_COMPUTE_MIPMAP], 0);
  3593. }
  3594. }
  3595. {
  3596. RD::Uniform u;
  3597. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  3598. u.binding = 5;
  3599. u.ids.push_back(mipmap.texture);
  3600. uniforms.push_back(u);
  3601. }
  3602. mipmap.write_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_WRITE_TEXTURE], 0);
  3603. gi_probe->mipmaps.push_back(mipmap);
  3604. }
  3605. {
  3606. uint32_t dynamic_map_size = MAX(MAX(octree_size.x, octree_size.y), octree_size.z);
  3607. uint32_t oversample = nearest_power_of_2_templated(4);
  3608. int mipmap_index = 0;
  3609. while (mipmap_index < gi_probe->mipmaps.size()) {
  3610. GIProbeInstance::DynamicMap dmap;
  3611. if (oversample > 0) {
  3612. dmap.size = dynamic_map_size * (1 << oversample);
  3613. dmap.mipmap = -1;
  3614. oversample--;
  3615. } else {
  3616. dmap.size = dynamic_map_size >> mipmap_index;
  3617. dmap.mipmap = mipmap_index;
  3618. mipmap_index++;
  3619. }
  3620. RD::TextureFormat dtf;
  3621. dtf.width = dmap.size;
  3622. dtf.height = dmap.size;
  3623. dtf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  3624. dtf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
  3625. if (gi_probe->dynamic_maps.size() == 0) {
  3626. dtf.usage_bits |= RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  3627. }
  3628. dmap.texture = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3629. if (gi_probe->dynamic_maps.size() == 0) {
  3630. //render depth for first one
  3631. dtf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
  3632. dtf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  3633. dmap.fb_depth = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3634. }
  3635. //just use depth as-is
  3636. dtf.format = RD::DATA_FORMAT_R32_SFLOAT;
  3637. dtf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  3638. dmap.depth = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3639. if (gi_probe->dynamic_maps.size() == 0) {
  3640. dtf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  3641. dtf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  3642. dmap.albedo = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3643. dmap.normal = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3644. dmap.orm = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3645. Vector<RID> fb;
  3646. fb.push_back(dmap.albedo);
  3647. fb.push_back(dmap.normal);
  3648. fb.push_back(dmap.orm);
  3649. fb.push_back(dmap.texture); //emission
  3650. fb.push_back(dmap.depth);
  3651. fb.push_back(dmap.fb_depth);
  3652. dmap.fb = RD::get_singleton()->framebuffer_create(fb);
  3653. {
  3654. Vector<RD::Uniform> uniforms;
  3655. {
  3656. RD::Uniform u;
  3657. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  3658. u.binding = 3;
  3659. u.ids.push_back(gi_probe_lights_uniform);
  3660. uniforms.push_back(u);
  3661. }
  3662. {
  3663. RD::Uniform u;
  3664. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  3665. u.binding = 5;
  3666. u.ids.push_back(dmap.albedo);
  3667. uniforms.push_back(u);
  3668. }
  3669. {
  3670. RD::Uniform u;
  3671. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  3672. u.binding = 6;
  3673. u.ids.push_back(dmap.normal);
  3674. uniforms.push_back(u);
  3675. }
  3676. {
  3677. RD::Uniform u;
  3678. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  3679. u.binding = 7;
  3680. u.ids.push_back(dmap.orm);
  3681. uniforms.push_back(u);
  3682. }
  3683. {
  3684. RD::Uniform u;
  3685. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  3686. u.binding = 8;
  3687. u.ids.push_back(dmap.fb_depth);
  3688. uniforms.push_back(u);
  3689. }
  3690. {
  3691. RD::Uniform u;
  3692. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  3693. u.binding = 9;
  3694. u.ids.push_back(storage->gi_probe_get_sdf_texture(gi_probe->probe));
  3695. uniforms.push_back(u);
  3696. }
  3697. {
  3698. RD::Uniform u;
  3699. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  3700. u.binding = 10;
  3701. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  3702. uniforms.push_back(u);
  3703. }
  3704. {
  3705. RD::Uniform u;
  3706. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  3707. u.binding = 11;
  3708. u.ids.push_back(dmap.texture);
  3709. uniforms.push_back(u);
  3710. }
  3711. {
  3712. RD::Uniform u;
  3713. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  3714. u.binding = 12;
  3715. u.ids.push_back(dmap.depth);
  3716. uniforms.push_back(u);
  3717. }
  3718. dmap.uniform_set = RD::get_singleton()->uniform_set_create(uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_DYNAMIC_OBJECT_LIGHTING], 0);
  3719. }
  3720. } else {
  3721. bool plot = dmap.mipmap >= 0;
  3722. bool write = dmap.mipmap < (gi_probe->mipmaps.size() - 1);
  3723. Vector<RD::Uniform> uniforms;
  3724. {
  3725. RD::Uniform u;
  3726. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  3727. u.binding = 5;
  3728. u.ids.push_back(gi_probe->dynamic_maps[gi_probe->dynamic_maps.size() - 1].texture);
  3729. uniforms.push_back(u);
  3730. }
  3731. {
  3732. RD::Uniform u;
  3733. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  3734. u.binding = 6;
  3735. u.ids.push_back(gi_probe->dynamic_maps[gi_probe->dynamic_maps.size() - 1].depth);
  3736. uniforms.push_back(u);
  3737. }
  3738. if (write) {
  3739. {
  3740. RD::Uniform u;
  3741. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  3742. u.binding = 7;
  3743. u.ids.push_back(dmap.texture);
  3744. uniforms.push_back(u);
  3745. }
  3746. {
  3747. RD::Uniform u;
  3748. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  3749. u.binding = 8;
  3750. u.ids.push_back(dmap.depth);
  3751. uniforms.push_back(u);
  3752. }
  3753. }
  3754. {
  3755. RD::Uniform u;
  3756. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  3757. u.binding = 9;
  3758. u.ids.push_back(storage->gi_probe_get_sdf_texture(gi_probe->probe));
  3759. uniforms.push_back(u);
  3760. }
  3761. {
  3762. RD::Uniform u;
  3763. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  3764. u.binding = 10;
  3765. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  3766. uniforms.push_back(u);
  3767. }
  3768. if (plot) {
  3769. {
  3770. RD::Uniform u;
  3771. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  3772. u.binding = 11;
  3773. u.ids.push_back(gi_probe->mipmaps[dmap.mipmap].texture);
  3774. uniforms.push_back(u);
  3775. }
  3776. }
  3777. dmap.uniform_set = RD::get_singleton()->uniform_set_create(
  3778. uniforms,
  3779. giprobe_lighting_shader_version_shaders[(write && plot) ? GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE_PLOT : (write ? GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE : GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_PLOT)],
  3780. 0);
  3781. }
  3782. gi_probe->dynamic_maps.push_back(dmap);
  3783. }
  3784. }
  3785. }
  3786. gi_probe->last_probe_data_version = data_version;
  3787. p_update_light_instances = true; //just in case
  3788. _base_uniforms_changed();
  3789. }
  3790. // UDPDATE TIME
  3791. if (gi_probe->has_dynamic_object_data) {
  3792. //if it has dynamic object data, it needs to be cleared
  3793. RD::get_singleton()->texture_clear(gi_probe->texture, Color(0, 0, 0, 0), 0, gi_probe->mipmaps.size(), 0, 1);
  3794. }
  3795. uint32_t light_count = 0;
  3796. if (p_update_light_instances || p_dynamic_objects.size() > 0) {
  3797. light_count = MIN(gi_probe_max_lights, (uint32_t)p_light_instances.size());
  3798. {
  3799. Transform to_cell = storage->gi_probe_get_to_cell_xform(gi_probe->probe);
  3800. Transform to_probe_xform = (gi_probe->transform * to_cell.affine_inverse()).affine_inverse();
  3801. //update lights
  3802. for (uint32_t i = 0; i < light_count; i++) {
  3803. GIProbeLight &l = gi_probe_lights[i];
  3804. RID light_instance = p_light_instances[i];
  3805. RID light = light_instance_get_base_light(light_instance);
  3806. l.type = storage->light_get_type(light);
  3807. if (l.type == RS::LIGHT_DIRECTIONAL && storage->light_directional_is_sky_only(light)) {
  3808. light_count--;
  3809. continue;
  3810. }
  3811. l.attenuation = storage->light_get_param(light, RS::LIGHT_PARAM_ATTENUATION);
  3812. l.energy = storage->light_get_param(light, RS::LIGHT_PARAM_ENERGY) * storage->light_get_param(light, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  3813. l.radius = to_cell.basis.xform(Vector3(storage->light_get_param(light, RS::LIGHT_PARAM_RANGE), 0, 0)).length();
  3814. Color color = storage->light_get_color(light).to_linear();
  3815. l.color[0] = color.r;
  3816. l.color[1] = color.g;
  3817. l.color[2] = color.b;
  3818. l.spot_angle_radians = Math::deg2rad(storage->light_get_param(light, RS::LIGHT_PARAM_SPOT_ANGLE));
  3819. l.spot_attenuation = storage->light_get_param(light, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  3820. Transform xform = light_instance_get_base_transform(light_instance);
  3821. Vector3 pos = to_probe_xform.xform(xform.origin);
  3822. Vector3 dir = to_probe_xform.basis.xform(-xform.basis.get_axis(2)).normalized();
  3823. l.position[0] = pos.x;
  3824. l.position[1] = pos.y;
  3825. l.position[2] = pos.z;
  3826. l.direction[0] = dir.x;
  3827. l.direction[1] = dir.y;
  3828. l.direction[2] = dir.z;
  3829. l.has_shadow = storage->light_has_shadow(light);
  3830. }
  3831. RD::get_singleton()->buffer_update(gi_probe_lights_uniform, 0, sizeof(GIProbeLight) * light_count, gi_probe_lights);
  3832. }
  3833. }
  3834. if (gi_probe->has_dynamic_object_data || p_update_light_instances || p_dynamic_objects.size()) {
  3835. // PROCESS MIPMAPS
  3836. if (gi_probe->mipmaps.size()) {
  3837. //can update mipmaps
  3838. Vector3i probe_size = storage->gi_probe_get_octree_size(gi_probe->probe);
  3839. GIProbePushConstant push_constant;
  3840. push_constant.limits[0] = probe_size.x;
  3841. push_constant.limits[1] = probe_size.y;
  3842. push_constant.limits[2] = probe_size.z;
  3843. push_constant.stack_size = gi_probe->mipmaps.size();
  3844. push_constant.emission_scale = 1.0;
  3845. push_constant.propagation = storage->gi_probe_get_propagation(gi_probe->probe);
  3846. push_constant.dynamic_range = storage->gi_probe_get_dynamic_range(gi_probe->probe);
  3847. push_constant.light_count = light_count;
  3848. push_constant.aniso_strength = 0;
  3849. /* print_line("probe update to version " + itos(gi_probe->last_probe_version));
  3850. print_line("propagation " + rtos(push_constant.propagation));
  3851. print_line("dynrange " + rtos(push_constant.dynamic_range));
  3852. */
  3853. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  3854. int passes;
  3855. if (p_update_light_instances) {
  3856. passes = storage->gi_probe_is_using_two_bounces(gi_probe->probe) ? 2 : 1;
  3857. } else {
  3858. passes = 1; //only re-blitting is necessary
  3859. }
  3860. int wg_size = 64;
  3861. int wg_limit_x = RD::get_singleton()->limit_get(RD::LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X);
  3862. for (int pass = 0; pass < passes; pass++) {
  3863. if (p_update_light_instances) {
  3864. for (int i = 0; i < gi_probe->mipmaps.size(); i++) {
  3865. if (i == 0) {
  3866. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[pass == 0 ? GI_PROBE_SHADER_VERSION_COMPUTE_LIGHT : GI_PROBE_SHADER_VERSION_COMPUTE_SECOND_BOUNCE]);
  3867. } else if (i == 1) {
  3868. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_COMPUTE_MIPMAP]);
  3869. }
  3870. if (pass == 1 || i > 0) {
  3871. RD::get_singleton()->compute_list_add_barrier(compute_list); //wait til previous step is done
  3872. }
  3873. if (pass == 0 || i > 0) {
  3874. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->mipmaps[i].uniform_set, 0);
  3875. } else {
  3876. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->mipmaps[i].second_bounce_uniform_set, 0);
  3877. }
  3878. push_constant.cell_offset = gi_probe->mipmaps[i].cell_offset;
  3879. push_constant.cell_count = gi_probe->mipmaps[i].cell_count;
  3880. int wg_todo = (gi_probe->mipmaps[i].cell_count - 1) / wg_size + 1;
  3881. while (wg_todo) {
  3882. int wg_count = MIN(wg_todo, wg_limit_x);
  3883. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbePushConstant));
  3884. RD::get_singleton()->compute_list_dispatch(compute_list, wg_count, 1, 1);
  3885. wg_todo -= wg_count;
  3886. push_constant.cell_offset += wg_count * wg_size;
  3887. }
  3888. }
  3889. RD::get_singleton()->compute_list_add_barrier(compute_list); //wait til previous step is done
  3890. }
  3891. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_WRITE_TEXTURE]);
  3892. for (int i = 0; i < gi_probe->mipmaps.size(); i++) {
  3893. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->mipmaps[i].write_uniform_set, 0);
  3894. push_constant.cell_offset = gi_probe->mipmaps[i].cell_offset;
  3895. push_constant.cell_count = gi_probe->mipmaps[i].cell_count;
  3896. int wg_todo = (gi_probe->mipmaps[i].cell_count - 1) / wg_size + 1;
  3897. while (wg_todo) {
  3898. int wg_count = MIN(wg_todo, wg_limit_x);
  3899. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbePushConstant));
  3900. RD::get_singleton()->compute_list_dispatch(compute_list, wg_count, 1, 1);
  3901. wg_todo -= wg_count;
  3902. push_constant.cell_offset += wg_count * wg_size;
  3903. }
  3904. }
  3905. }
  3906. RD::get_singleton()->compute_list_end();
  3907. }
  3908. }
  3909. gi_probe->has_dynamic_object_data = false; //clear until dynamic object data is used again
  3910. if (p_dynamic_objects.size() && gi_probe->dynamic_maps.size()) {
  3911. Vector3i octree_size = storage->gi_probe_get_octree_size(gi_probe->probe);
  3912. int multiplier = gi_probe->dynamic_maps[0].size / MAX(MAX(octree_size.x, octree_size.y), octree_size.z);
  3913. Transform oversample_scale;
  3914. oversample_scale.basis.scale(Vector3(multiplier, multiplier, multiplier));
  3915. Transform to_cell = oversample_scale * storage->gi_probe_get_to_cell_xform(gi_probe->probe);
  3916. Transform to_world_xform = gi_probe->transform * to_cell.affine_inverse();
  3917. Transform to_probe_xform = to_world_xform.affine_inverse();
  3918. AABB probe_aabb(Vector3(), octree_size);
  3919. //this could probably be better parallelized in compute..
  3920. for (int i = 0; i < (int)p_dynamic_objects.size(); i++) {
  3921. GeometryInstance *instance = p_dynamic_objects[i];
  3922. //transform aabb to giprobe
  3923. AABB aabb = (to_probe_xform * geometry_instance_get_transform(instance)).xform(geometry_instance_get_aabb(instance));
  3924. //this needs to wrap to grid resolution to avoid jitter
  3925. //also extend margin a bit just in case
  3926. Vector3i begin = aabb.position - Vector3i(1, 1, 1);
  3927. Vector3i end = aabb.position + aabb.size + Vector3i(1, 1, 1);
  3928. for (int j = 0; j < 3; j++) {
  3929. if ((end[j] - begin[j]) & 1) {
  3930. end[j]++; //for half extents split, it needs to be even
  3931. }
  3932. begin[j] = MAX(begin[j], 0);
  3933. end[j] = MIN(end[j], octree_size[j] * multiplier);
  3934. }
  3935. //aabb = aabb.intersection(probe_aabb); //intersect
  3936. aabb.position = begin;
  3937. aabb.size = end - begin;
  3938. //print_line("aabb: " + aabb);
  3939. for (int j = 0; j < 6; j++) {
  3940. //if (j != 0 && j != 3) {
  3941. // continue;
  3942. //}
  3943. static const Vector3 render_z[6] = {
  3944. Vector3(1, 0, 0),
  3945. Vector3(0, 1, 0),
  3946. Vector3(0, 0, 1),
  3947. Vector3(-1, 0, 0),
  3948. Vector3(0, -1, 0),
  3949. Vector3(0, 0, -1),
  3950. };
  3951. static const Vector3 render_up[6] = {
  3952. Vector3(0, 1, 0),
  3953. Vector3(0, 0, 1),
  3954. Vector3(0, 1, 0),
  3955. Vector3(0, 1, 0),
  3956. Vector3(0, 0, 1),
  3957. Vector3(0, 1, 0),
  3958. };
  3959. Vector3 render_dir = render_z[j];
  3960. Vector3 up_dir = render_up[j];
  3961. Vector3 center = aabb.position + aabb.size * 0.5;
  3962. Transform xform;
  3963. xform.set_look_at(center - aabb.size * 0.5 * render_dir, center, up_dir);
  3964. Vector3 x_dir = xform.basis.get_axis(0).abs();
  3965. int x_axis = int(Vector3(0, 1, 2).dot(x_dir));
  3966. Vector3 y_dir = xform.basis.get_axis(1).abs();
  3967. int y_axis = int(Vector3(0, 1, 2).dot(y_dir));
  3968. Vector3 z_dir = -xform.basis.get_axis(2);
  3969. int z_axis = int(Vector3(0, 1, 2).dot(z_dir.abs()));
  3970. Rect2i rect(aabb.position[x_axis], aabb.position[y_axis], aabb.size[x_axis], aabb.size[y_axis]);
  3971. bool x_flip = bool(Vector3(1, 1, 1).dot(xform.basis.get_axis(0)) < 0);
  3972. bool y_flip = bool(Vector3(1, 1, 1).dot(xform.basis.get_axis(1)) < 0);
  3973. bool z_flip = bool(Vector3(1, 1, 1).dot(xform.basis.get_axis(2)) > 0);
  3974. CameraMatrix cm;
  3975. cm.set_orthogonal(-rect.size.width / 2, rect.size.width / 2, -rect.size.height / 2, rect.size.height / 2, 0.0001, aabb.size[z_axis]);
  3976. if (cull_argument.size() == 0) {
  3977. cull_argument.push_back(nullptr);
  3978. }
  3979. cull_argument[0] = instance;
  3980. _render_material(to_world_xform * xform, cm, true, cull_argument, gi_probe->dynamic_maps[0].fb, Rect2i(Vector2i(), rect.size));
  3981. GIProbeDynamicPushConstant push_constant;
  3982. zeromem(&push_constant, sizeof(GIProbeDynamicPushConstant));
  3983. push_constant.limits[0] = octree_size.x;
  3984. push_constant.limits[1] = octree_size.y;
  3985. push_constant.limits[2] = octree_size.z;
  3986. push_constant.light_count = p_light_instances.size();
  3987. push_constant.x_dir[0] = x_dir[0];
  3988. push_constant.x_dir[1] = x_dir[1];
  3989. push_constant.x_dir[2] = x_dir[2];
  3990. push_constant.y_dir[0] = y_dir[0];
  3991. push_constant.y_dir[1] = y_dir[1];
  3992. push_constant.y_dir[2] = y_dir[2];
  3993. push_constant.z_dir[0] = z_dir[0];
  3994. push_constant.z_dir[1] = z_dir[1];
  3995. push_constant.z_dir[2] = z_dir[2];
  3996. push_constant.z_base = xform.origin[z_axis];
  3997. push_constant.z_sign = (z_flip ? -1.0 : 1.0);
  3998. push_constant.pos_multiplier = float(1.0) / multiplier;
  3999. push_constant.dynamic_range = storage->gi_probe_get_dynamic_range(gi_probe->probe);
  4000. push_constant.flip_x = x_flip;
  4001. push_constant.flip_y = y_flip;
  4002. push_constant.rect_pos[0] = rect.position[0];
  4003. push_constant.rect_pos[1] = rect.position[1];
  4004. push_constant.rect_size[0] = rect.size[0];
  4005. push_constant.rect_size[1] = rect.size[1];
  4006. push_constant.prev_rect_ofs[0] = 0;
  4007. push_constant.prev_rect_ofs[1] = 0;
  4008. push_constant.prev_rect_size[0] = 0;
  4009. push_constant.prev_rect_size[1] = 0;
  4010. push_constant.on_mipmap = false;
  4011. push_constant.propagation = storage->gi_probe_get_propagation(gi_probe->probe);
  4012. push_constant.pad[0] = 0;
  4013. push_constant.pad[1] = 0;
  4014. push_constant.pad[2] = 0;
  4015. //process lighting
  4016. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  4017. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_OBJECT_LIGHTING]);
  4018. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->dynamic_maps[0].uniform_set, 0);
  4019. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbeDynamicPushConstant));
  4020. RD::get_singleton()->compute_list_dispatch(compute_list, (rect.size.x - 1) / 8 + 1, (rect.size.y - 1) / 8 + 1, 1);
  4021. //print_line("rect: " + itos(i) + ": " + rect);
  4022. for (int k = 1; k < gi_probe->dynamic_maps.size(); k++) {
  4023. // enlarge the rect if needed so all pixels fit when downscaled,
  4024. // this ensures downsampling is smooth and optimal because no pixels are left behind
  4025. //x
  4026. if (rect.position.x & 1) {
  4027. rect.size.x++;
  4028. push_constant.prev_rect_ofs[0] = 1; //this is used to ensure reading is also optimal
  4029. } else {
  4030. push_constant.prev_rect_ofs[0] = 0;
  4031. }
  4032. if (rect.size.x & 1) {
  4033. rect.size.x++;
  4034. }
  4035. rect.position.x >>= 1;
  4036. rect.size.x = MAX(1, rect.size.x >> 1);
  4037. //y
  4038. if (rect.position.y & 1) {
  4039. rect.size.y++;
  4040. push_constant.prev_rect_ofs[1] = 1;
  4041. } else {
  4042. push_constant.prev_rect_ofs[1] = 0;
  4043. }
  4044. if (rect.size.y & 1) {
  4045. rect.size.y++;
  4046. }
  4047. rect.position.y >>= 1;
  4048. rect.size.y = MAX(1, rect.size.y >> 1);
  4049. //shrink limits to ensure plot does not go outside map
  4050. if (gi_probe->dynamic_maps[k].mipmap > 0) {
  4051. for (int l = 0; l < 3; l++) {
  4052. push_constant.limits[l] = MAX(1, push_constant.limits[l] >> 1);
  4053. }
  4054. }
  4055. //print_line("rect: " + itos(i) + ": " + rect);
  4056. push_constant.rect_pos[0] = rect.position[0];
  4057. push_constant.rect_pos[1] = rect.position[1];
  4058. push_constant.prev_rect_size[0] = push_constant.rect_size[0];
  4059. push_constant.prev_rect_size[1] = push_constant.rect_size[1];
  4060. push_constant.rect_size[0] = rect.size[0];
  4061. push_constant.rect_size[1] = rect.size[1];
  4062. push_constant.on_mipmap = gi_probe->dynamic_maps[k].mipmap > 0;
  4063. RD::get_singleton()->compute_list_add_barrier(compute_list);
  4064. if (gi_probe->dynamic_maps[k].mipmap < 0) {
  4065. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE]);
  4066. } else if (k < gi_probe->dynamic_maps.size() - 1) {
  4067. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE_PLOT]);
  4068. } else {
  4069. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_PLOT]);
  4070. }
  4071. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->dynamic_maps[k].uniform_set, 0);
  4072. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbeDynamicPushConstant));
  4073. RD::get_singleton()->compute_list_dispatch(compute_list, (rect.size.x - 1) / 8 + 1, (rect.size.y - 1) / 8 + 1, 1);
  4074. }
  4075. RD::get_singleton()->compute_list_end();
  4076. }
  4077. }
  4078. gi_probe->has_dynamic_object_data = true; //clear until dynamic object data is used again
  4079. }
  4080. gi_probe->last_probe_version = storage->gi_probe_get_version(gi_probe->probe);
  4081. }
  4082. void RendererSceneRenderRD::_debug_giprobe(RID p_gi_probe, RD::DrawListID p_draw_list, RID p_framebuffer, const CameraMatrix &p_camera_with_transform, bool p_lighting, bool p_emission, float p_alpha) {
  4083. GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_gi_probe);
  4084. ERR_FAIL_COND(!gi_probe);
  4085. if (gi_probe->mipmaps.size() == 0) {
  4086. return;
  4087. }
  4088. CameraMatrix transform = (p_camera_with_transform * CameraMatrix(gi_probe->transform)) * CameraMatrix(storage->gi_probe_get_to_cell_xform(gi_probe->probe).affine_inverse());
  4089. int level = 0;
  4090. Vector3i octree_size = storage->gi_probe_get_octree_size(gi_probe->probe);
  4091. GIProbeDebugPushConstant push_constant;
  4092. push_constant.alpha = p_alpha;
  4093. push_constant.dynamic_range = storage->gi_probe_get_dynamic_range(gi_probe->probe);
  4094. push_constant.cell_offset = gi_probe->mipmaps[level].cell_offset;
  4095. push_constant.level = level;
  4096. push_constant.bounds[0] = octree_size.x >> level;
  4097. push_constant.bounds[1] = octree_size.y >> level;
  4098. push_constant.bounds[2] = octree_size.z >> level;
  4099. push_constant.pad = 0;
  4100. for (int i = 0; i < 4; i++) {
  4101. for (int j = 0; j < 4; j++) {
  4102. push_constant.projection[i * 4 + j] = transform.matrix[i][j];
  4103. }
  4104. }
  4105. if (giprobe_debug_uniform_set.is_valid()) {
  4106. RD::get_singleton()->free(giprobe_debug_uniform_set);
  4107. }
  4108. Vector<RD::Uniform> uniforms;
  4109. {
  4110. RD::Uniform u;
  4111. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  4112. u.binding = 1;
  4113. u.ids.push_back(storage->gi_probe_get_data_buffer(gi_probe->probe));
  4114. uniforms.push_back(u);
  4115. }
  4116. {
  4117. RD::Uniform u;
  4118. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  4119. u.binding = 2;
  4120. u.ids.push_back(gi_probe->texture);
  4121. uniforms.push_back(u);
  4122. }
  4123. {
  4124. RD::Uniform u;
  4125. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  4126. u.binding = 3;
  4127. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  4128. uniforms.push_back(u);
  4129. }
  4130. int cell_count;
  4131. if (!p_emission && p_lighting && gi_probe->has_dynamic_object_data) {
  4132. cell_count = push_constant.bounds[0] * push_constant.bounds[1] * push_constant.bounds[2];
  4133. } else {
  4134. cell_count = gi_probe->mipmaps[level].cell_count;
  4135. }
  4136. giprobe_debug_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, giprobe_debug_shader_version_shaders[0], 0);
  4137. int giprobe_debug_pipeline = GI_PROBE_DEBUG_COLOR;
  4138. if (p_emission) {
  4139. giprobe_debug_pipeline = GI_PROBE_DEBUG_EMISSION;
  4140. } else if (p_lighting) {
  4141. giprobe_debug_pipeline = gi_probe->has_dynamic_object_data ? GI_PROBE_DEBUG_LIGHT_FULL : GI_PROBE_DEBUG_LIGHT;
  4142. }
  4143. RD::get_singleton()->draw_list_bind_render_pipeline(
  4144. p_draw_list,
  4145. giprobe_debug_shader_version_pipelines[giprobe_debug_pipeline].get_render_pipeline(RD::INVALID_ID, RD::get_singleton()->framebuffer_get_format(p_framebuffer)));
  4146. RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, giprobe_debug_uniform_set, 0);
  4147. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(GIProbeDebugPushConstant));
  4148. RD::get_singleton()->draw_list_draw(p_draw_list, false, cell_count, 36);
  4149. }
  4150. void RendererSceneRenderRD::_debug_sdfgi_probes(RID p_render_buffers, RD::DrawListID p_draw_list, RID p_framebuffer, const CameraMatrix &p_camera_with_transform) {
  4151. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4152. ERR_FAIL_COND(!rb);
  4153. if (!rb->sdfgi) {
  4154. return; //nothing to debug
  4155. }
  4156. SDGIShader::DebugProbesPushConstant push_constant;
  4157. for (int i = 0; i < 4; i++) {
  4158. for (int j = 0; j < 4; j++) {
  4159. push_constant.projection[i * 4 + j] = p_camera_with_transform.matrix[i][j];
  4160. }
  4161. }
  4162. //gen spheres from strips
  4163. uint32_t band_points = 16;
  4164. push_constant.band_power = 4;
  4165. push_constant.sections_in_band = ((band_points / 2) - 1);
  4166. push_constant.band_mask = band_points - 2;
  4167. push_constant.section_arc = Math_TAU / float(push_constant.sections_in_band);
  4168. push_constant.y_mult = rb->sdfgi->y_mult;
  4169. uint32_t total_points = push_constant.sections_in_band * band_points;
  4170. uint32_t total_probes = rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count;
  4171. push_constant.grid_size[0] = rb->sdfgi->cascade_size;
  4172. push_constant.grid_size[1] = rb->sdfgi->cascade_size;
  4173. push_constant.grid_size[2] = rb->sdfgi->cascade_size;
  4174. push_constant.cascade = 0;
  4175. push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  4176. if (!rb->sdfgi->debug_probes_uniform_set.is_valid() || !RD::get_singleton()->uniform_set_is_valid(rb->sdfgi->debug_probes_uniform_set)) {
  4177. Vector<RD::Uniform> uniforms;
  4178. {
  4179. RD::Uniform u;
  4180. u.binding = 1;
  4181. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  4182. u.ids.push_back(rb->sdfgi->cascades_ubo);
  4183. uniforms.push_back(u);
  4184. }
  4185. {
  4186. RD::Uniform u;
  4187. u.binding = 2;
  4188. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  4189. u.ids.push_back(rb->sdfgi->lightprobe_texture);
  4190. uniforms.push_back(u);
  4191. }
  4192. {
  4193. RD::Uniform u;
  4194. u.binding = 3;
  4195. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  4196. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  4197. uniforms.push_back(u);
  4198. }
  4199. {
  4200. RD::Uniform u;
  4201. u.binding = 4;
  4202. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  4203. u.ids.push_back(rb->sdfgi->occlusion_texture);
  4204. uniforms.push_back(u);
  4205. }
  4206. rb->sdfgi->debug_probes_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.debug_probes.version_get_shader(sdfgi_shader.debug_probes_shader, 0), 0);
  4207. }
  4208. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, sdfgi_shader.debug_probes_pipeline[SDGIShader::PROBE_DEBUG_PROBES].get_render_pipeline(RD::INVALID_FORMAT_ID, RD::get_singleton()->framebuffer_get_format(p_framebuffer)));
  4209. RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, rb->sdfgi->debug_probes_uniform_set, 0);
  4210. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(SDGIShader::DebugProbesPushConstant));
  4211. RD::get_singleton()->draw_list_draw(p_draw_list, false, total_probes, total_points);
  4212. if (sdfgi_debug_probe_dir != Vector3()) {
  4213. print_line("CLICK DEBUG ME?");
  4214. uint32_t cascade = 0;
  4215. Vector3 offset = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[cascade].position)) * rb->sdfgi->cascades[cascade].cell_size * Vector3(1.0, 1.0 / rb->sdfgi->y_mult, 1.0);
  4216. Vector3 probe_size = rb->sdfgi->cascades[cascade].cell_size * (rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR) * Vector3(1.0, 1.0 / rb->sdfgi->y_mult, 1.0);
  4217. Vector3 ray_from = sdfgi_debug_probe_pos;
  4218. Vector3 ray_to = sdfgi_debug_probe_pos + sdfgi_debug_probe_dir * rb->sdfgi->cascades[cascade].cell_size * Math::sqrt(3.0) * rb->sdfgi->cascade_size;
  4219. float sphere_radius = 0.2;
  4220. float closest_dist = 1e20;
  4221. sdfgi_debug_probe_enabled = false;
  4222. Vector3i probe_from = rb->sdfgi->cascades[cascade].position / (rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR);
  4223. for (int i = 0; i < (SDFGI::PROBE_DIVISOR + 1); i++) {
  4224. for (int j = 0; j < (SDFGI::PROBE_DIVISOR + 1); j++) {
  4225. for (int k = 0; k < (SDFGI::PROBE_DIVISOR + 1); k++) {
  4226. Vector3 pos = offset + probe_size * Vector3(i, j, k);
  4227. Vector3 res;
  4228. if (Geometry3D::segment_intersects_sphere(ray_from, ray_to, pos, sphere_radius, &res)) {
  4229. float d = ray_from.distance_to(res);
  4230. if (d < closest_dist) {
  4231. closest_dist = d;
  4232. sdfgi_debug_probe_enabled = true;
  4233. sdfgi_debug_probe_index = probe_from + Vector3i(i, j, k);
  4234. }
  4235. }
  4236. }
  4237. }
  4238. }
  4239. if (sdfgi_debug_probe_enabled) {
  4240. print_line("found: " + sdfgi_debug_probe_index);
  4241. } else {
  4242. print_line("no found");
  4243. }
  4244. sdfgi_debug_probe_dir = Vector3();
  4245. }
  4246. if (sdfgi_debug_probe_enabled) {
  4247. uint32_t cascade = 0;
  4248. uint32_t probe_cells = (rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR);
  4249. Vector3i probe_from = rb->sdfgi->cascades[cascade].position / probe_cells;
  4250. Vector3i ofs = sdfgi_debug_probe_index - probe_from;
  4251. if (ofs.x < 0 || ofs.y < 0 || ofs.z < 0) {
  4252. return;
  4253. }
  4254. if (ofs.x > SDFGI::PROBE_DIVISOR || ofs.y > SDFGI::PROBE_DIVISOR || ofs.z > SDFGI::PROBE_DIVISOR) {
  4255. return;
  4256. }
  4257. uint32_t mult = (SDFGI::PROBE_DIVISOR + 1);
  4258. uint32_t index = ofs.z * mult * mult + ofs.y * mult + ofs.x;
  4259. push_constant.probe_debug_index = index;
  4260. uint32_t cell_count = probe_cells * 2 * probe_cells * 2 * probe_cells * 2;
  4261. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, sdfgi_shader.debug_probes_pipeline[SDGIShader::PROBE_DEBUG_VISIBILITY].get_render_pipeline(RD::INVALID_FORMAT_ID, RD::get_singleton()->framebuffer_get_format(p_framebuffer)));
  4262. RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, rb->sdfgi->debug_probes_uniform_set, 0);
  4263. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(SDGIShader::DebugProbesPushConstant));
  4264. RD::get_singleton()->draw_list_draw(p_draw_list, false, cell_count, total_points);
  4265. }
  4266. }
  4267. ////////////////////////////////
  4268. RID RendererSceneRenderRD::render_buffers_create() {
  4269. RenderBuffers rb;
  4270. rb.data = _create_render_buffer_data();
  4271. return render_buffers_owner.make_rid(rb);
  4272. }
  4273. void RendererSceneRenderRD::_allocate_blur_textures(RenderBuffers *rb) {
  4274. ERR_FAIL_COND(!rb->blur[0].texture.is_null());
  4275. uint32_t mipmaps_required = Image::get_image_required_mipmaps(rb->width, rb->height, Image::FORMAT_RGBAH);
  4276. RD::TextureFormat tf;
  4277. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  4278. tf.width = rb->width;
  4279. tf.height = rb->height;
  4280. tf.texture_type = RD::TEXTURE_TYPE_2D;
  4281. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT;
  4282. tf.mipmaps = mipmaps_required;
  4283. rb->blur[0].texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4284. //the second one is smaller (only used for separatable part of blur)
  4285. tf.width >>= 1;
  4286. tf.height >>= 1;
  4287. tf.mipmaps--;
  4288. rb->blur[1].texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4289. int base_width = rb->width;
  4290. int base_height = rb->height;
  4291. for (uint32_t i = 0; i < mipmaps_required; i++) {
  4292. RenderBuffers::Blur::Mipmap mm;
  4293. mm.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->blur[0].texture, 0, i);
  4294. mm.width = base_width;
  4295. mm.height = base_height;
  4296. rb->blur[0].mipmaps.push_back(mm);
  4297. if (i > 0) {
  4298. mm.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->blur[1].texture, 0, i - 1);
  4299. rb->blur[1].mipmaps.push_back(mm);
  4300. }
  4301. base_width = MAX(1, base_width >> 1);
  4302. base_height = MAX(1, base_height >> 1);
  4303. }
  4304. }
  4305. void RendererSceneRenderRD::_allocate_luminance_textures(RenderBuffers *rb) {
  4306. ERR_FAIL_COND(!rb->luminance.current.is_null());
  4307. int w = rb->width;
  4308. int h = rb->height;
  4309. while (true) {
  4310. w = MAX(w / 8, 1);
  4311. h = MAX(h / 8, 1);
  4312. RD::TextureFormat tf;
  4313. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  4314. tf.width = w;
  4315. tf.height = h;
  4316. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
  4317. bool final = w == 1 && h == 1;
  4318. if (final) {
  4319. tf.usage_bits |= RD::TEXTURE_USAGE_SAMPLING_BIT;
  4320. }
  4321. RID texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4322. rb->luminance.reduce.push_back(texture);
  4323. if (final) {
  4324. rb->luminance.current = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4325. break;
  4326. }
  4327. }
  4328. }
  4329. void RendererSceneRenderRD::_free_render_buffer_data(RenderBuffers *rb) {
  4330. if (rb->texture.is_valid()) {
  4331. RD::get_singleton()->free(rb->texture);
  4332. rb->texture = RID();
  4333. }
  4334. if (rb->depth_texture.is_valid()) {
  4335. RD::get_singleton()->free(rb->depth_texture);
  4336. rb->depth_texture = RID();
  4337. }
  4338. for (int i = 0; i < 2; i++) {
  4339. if (rb->blur[i].texture.is_valid()) {
  4340. RD::get_singleton()->free(rb->blur[i].texture);
  4341. rb->blur[i].texture = RID();
  4342. rb->blur[i].mipmaps.clear();
  4343. }
  4344. }
  4345. for (int i = 0; i < rb->luminance.reduce.size(); i++) {
  4346. RD::get_singleton()->free(rb->luminance.reduce[i]);
  4347. }
  4348. rb->luminance.reduce.clear();
  4349. if (rb->luminance.current.is_valid()) {
  4350. RD::get_singleton()->free(rb->luminance.current);
  4351. rb->luminance.current = RID();
  4352. }
  4353. if (rb->ssao.depth.is_valid()) {
  4354. RD::get_singleton()->free(rb->ssao.depth);
  4355. RD::get_singleton()->free(rb->ssao.ao_deinterleaved);
  4356. RD::get_singleton()->free(rb->ssao.ao_pong);
  4357. RD::get_singleton()->free(rb->ssao.ao_final);
  4358. RD::get_singleton()->free(rb->ssao.importance_map[0]);
  4359. RD::get_singleton()->free(rb->ssao.importance_map[1]);
  4360. rb->ssao.depth = RID();
  4361. rb->ssao.ao_deinterleaved = RID();
  4362. rb->ssao.ao_pong = RID();
  4363. rb->ssao.ao_final = RID();
  4364. rb->ssao.importance_map[0] = RID();
  4365. rb->ssao.importance_map[1] = RID();
  4366. rb->ssao.depth_slices.clear();
  4367. rb->ssao.ao_deinterleaved_slices.clear();
  4368. rb->ssao.ao_pong_slices.clear();
  4369. }
  4370. if (rb->ssr.blur_radius[0].is_valid()) {
  4371. RD::get_singleton()->free(rb->ssr.blur_radius[0]);
  4372. RD::get_singleton()->free(rb->ssr.blur_radius[1]);
  4373. rb->ssr.blur_radius[0] = RID();
  4374. rb->ssr.blur_radius[1] = RID();
  4375. }
  4376. if (rb->ssr.depth_scaled.is_valid()) {
  4377. RD::get_singleton()->free(rb->ssr.depth_scaled);
  4378. rb->ssr.depth_scaled = RID();
  4379. RD::get_singleton()->free(rb->ssr.normal_scaled);
  4380. rb->ssr.normal_scaled = RID();
  4381. }
  4382. if (rb->ambient_buffer.is_valid()) {
  4383. RD::get_singleton()->free(rb->ambient_buffer);
  4384. RD::get_singleton()->free(rb->reflection_buffer);
  4385. rb->ambient_buffer = RID();
  4386. rb->reflection_buffer = RID();
  4387. }
  4388. }
  4389. void RendererSceneRenderRD::_process_sss(RID p_render_buffers, const CameraMatrix &p_camera) {
  4390. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4391. ERR_FAIL_COND(!rb);
  4392. bool can_use_effects = rb->width >= 8 && rb->height >= 8;
  4393. if (!can_use_effects) {
  4394. //just copy
  4395. return;
  4396. }
  4397. if (rb->blur[0].texture.is_null()) {
  4398. _allocate_blur_textures(rb);
  4399. _render_buffers_uniform_set_changed(p_render_buffers);
  4400. }
  4401. storage->get_effects()->sub_surface_scattering(rb->texture, rb->blur[0].mipmaps[0].texture, rb->depth_texture, p_camera, Size2i(rb->width, rb->height), sss_scale, sss_depth_scale, sss_quality);
  4402. }
  4403. void RendererSceneRenderRD::_process_ssr(RID p_render_buffers, RID p_dest_framebuffer, RID p_normal_buffer, RID p_specular_buffer, RID p_metallic, const Color &p_metallic_mask, RID p_environment, const CameraMatrix &p_projection, bool p_use_additive) {
  4404. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4405. ERR_FAIL_COND(!rb);
  4406. bool can_use_effects = rb->width >= 8 && rb->height >= 8;
  4407. if (!can_use_effects) {
  4408. //just copy
  4409. storage->get_effects()->merge_specular(p_dest_framebuffer, p_specular_buffer, p_use_additive ? RID() : rb->texture, RID());
  4410. return;
  4411. }
  4412. Environment *env = environment_owner.getornull(p_environment);
  4413. ERR_FAIL_COND(!env);
  4414. ERR_FAIL_COND(!env->ssr_enabled);
  4415. if (rb->ssr.depth_scaled.is_null()) {
  4416. RD::TextureFormat tf;
  4417. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  4418. tf.width = rb->width / 2;
  4419. tf.height = rb->height / 2;
  4420. tf.texture_type = RD::TEXTURE_TYPE_2D;
  4421. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
  4422. rb->ssr.depth_scaled = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4423. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  4424. rb->ssr.normal_scaled = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4425. }
  4426. if (ssr_roughness_quality != RS::ENV_SSR_ROUGNESS_QUALITY_DISABLED && !rb->ssr.blur_radius[0].is_valid()) {
  4427. RD::TextureFormat tf;
  4428. tf.format = RD::DATA_FORMAT_R8_UNORM;
  4429. tf.width = rb->width / 2;
  4430. tf.height = rb->height / 2;
  4431. tf.texture_type = RD::TEXTURE_TYPE_2D;
  4432. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
  4433. rb->ssr.blur_radius[0] = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4434. rb->ssr.blur_radius[1] = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4435. }
  4436. if (rb->blur[0].texture.is_null()) {
  4437. _allocate_blur_textures(rb);
  4438. _render_buffers_uniform_set_changed(p_render_buffers);
  4439. }
  4440. storage->get_effects()->screen_space_reflection(rb->texture, p_normal_buffer, ssr_roughness_quality, rb->ssr.blur_radius[0], rb->ssr.blur_radius[1], p_metallic, p_metallic_mask, rb->depth_texture, rb->ssr.depth_scaled, rb->ssr.normal_scaled, rb->blur[0].mipmaps[1].texture, rb->blur[1].mipmaps[0].texture, Size2i(rb->width / 2, rb->height / 2), env->ssr_max_steps, env->ssr_fade_in, env->ssr_fade_out, env->ssr_depth_tolerance, p_projection);
  4441. storage->get_effects()->merge_specular(p_dest_framebuffer, p_specular_buffer, p_use_additive ? RID() : rb->texture, rb->blur[0].mipmaps[1].texture);
  4442. }
  4443. void RendererSceneRenderRD::_process_ssao(RID p_render_buffers, RID p_environment, RID p_normal_buffer, const CameraMatrix &p_projection) {
  4444. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4445. ERR_FAIL_COND(!rb);
  4446. Environment *env = environment_owner.getornull(p_environment);
  4447. ERR_FAIL_COND(!env);
  4448. RENDER_TIMESTAMP("Process SSAO");
  4449. if (rb->ssao.ao_final.is_valid() && ssao_using_half_size != ssao_half_size) {
  4450. RD::get_singleton()->free(rb->ssao.depth);
  4451. RD::get_singleton()->free(rb->ssao.ao_deinterleaved);
  4452. RD::get_singleton()->free(rb->ssao.ao_pong);
  4453. RD::get_singleton()->free(rb->ssao.ao_final);
  4454. RD::get_singleton()->free(rb->ssao.importance_map[0]);
  4455. RD::get_singleton()->free(rb->ssao.importance_map[1]);
  4456. rb->ssao.depth = RID();
  4457. rb->ssao.ao_deinterleaved = RID();
  4458. rb->ssao.ao_pong = RID();
  4459. rb->ssao.ao_final = RID();
  4460. rb->ssao.importance_map[0] = RID();
  4461. rb->ssao.importance_map[1] = RID();
  4462. rb->ssao.depth_slices.clear();
  4463. rb->ssao.ao_deinterleaved_slices.clear();
  4464. rb->ssao.ao_pong_slices.clear();
  4465. }
  4466. int buffer_width;
  4467. int buffer_height;
  4468. int half_width;
  4469. int half_height;
  4470. if (ssao_half_size) {
  4471. buffer_width = (rb->width + 3) / 4;
  4472. buffer_height = (rb->height + 3) / 4;
  4473. half_width = (rb->width + 7) / 8;
  4474. half_height = (rb->height + 7) / 8;
  4475. } else {
  4476. buffer_width = (rb->width + 1) / 2;
  4477. buffer_height = (rb->height + 1) / 2;
  4478. half_width = (rb->width + 3) / 4;
  4479. half_height = (rb->height + 3) / 4;
  4480. }
  4481. bool uniform_sets_are_invalid = false;
  4482. if (rb->ssao.depth.is_null()) {
  4483. //allocate depth slices
  4484. {
  4485. RD::TextureFormat tf;
  4486. tf.format = RD::DATA_FORMAT_R16_SFLOAT;
  4487. tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
  4488. tf.width = buffer_width;
  4489. tf.height = buffer_height;
  4490. tf.mipmaps = 4;
  4491. tf.array_layers = 4;
  4492. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  4493. rb->ssao.depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4494. RD::get_singleton()->set_resource_name(rb->ssao.depth, "SSAO Depth");
  4495. for (uint32_t i = 0; i < tf.mipmaps; i++) {
  4496. RID slice = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->ssao.depth, 0, i, RD::TEXTURE_SLICE_2D_ARRAY);
  4497. rb->ssao.depth_slices.push_back(slice);
  4498. RD::get_singleton()->set_resource_name(rb->ssao.depth_slices[i], "SSAO Depth Mip " + itos(i) + " ");
  4499. }
  4500. }
  4501. {
  4502. RD::TextureFormat tf;
  4503. tf.format = RD::DATA_FORMAT_R8G8_UNORM;
  4504. tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
  4505. tf.width = buffer_width;
  4506. tf.height = buffer_height;
  4507. tf.array_layers = 4;
  4508. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  4509. rb->ssao.ao_deinterleaved = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4510. RD::get_singleton()->set_resource_name(rb->ssao.ao_deinterleaved, "SSAO De-interleaved Array");
  4511. for (uint32_t i = 0; i < 4; i++) {
  4512. RID slice = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->ssao.ao_deinterleaved, i, 0);
  4513. rb->ssao.ao_deinterleaved_slices.push_back(slice);
  4514. RD::get_singleton()->set_resource_name(rb->ssao.ao_deinterleaved_slices[i], "SSAO De-interleaved Array Layer " + itos(i) + " ");
  4515. }
  4516. }
  4517. {
  4518. RD::TextureFormat tf;
  4519. tf.format = RD::DATA_FORMAT_R8G8_UNORM;
  4520. tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
  4521. tf.width = buffer_width;
  4522. tf.height = buffer_height;
  4523. tf.array_layers = 4;
  4524. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  4525. rb->ssao.ao_pong = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4526. RD::get_singleton()->set_resource_name(rb->ssao.ao_pong, "SSAO De-interleaved Array Pong");
  4527. for (uint32_t i = 0; i < 4; i++) {
  4528. RID slice = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->ssao.ao_pong, i, 0);
  4529. rb->ssao.ao_pong_slices.push_back(slice);
  4530. RD::get_singleton()->set_resource_name(rb->ssao.ao_deinterleaved_slices[i], "SSAO De-interleaved Array Layer " + itos(i) + " Pong");
  4531. }
  4532. }
  4533. {
  4534. RD::TextureFormat tf;
  4535. tf.format = RD::DATA_FORMAT_R8_UNORM;
  4536. tf.width = half_width;
  4537. tf.height = half_height;
  4538. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  4539. rb->ssao.importance_map[0] = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4540. RD::get_singleton()->set_resource_name(rb->ssao.importance_map[0], "SSAO Importance Map");
  4541. rb->ssao.importance_map[1] = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4542. RD::get_singleton()->set_resource_name(rb->ssao.importance_map[1], "SSAO Importance Map Pong");
  4543. }
  4544. {
  4545. RD::TextureFormat tf;
  4546. tf.format = RD::DATA_FORMAT_R8_UNORM;
  4547. tf.width = rb->width;
  4548. tf.height = rb->height;
  4549. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  4550. rb->ssao.ao_final = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4551. RD::get_singleton()->set_resource_name(rb->ssao.ao_final, "SSAO Final");
  4552. _render_buffers_uniform_set_changed(p_render_buffers);
  4553. }
  4554. ssao_using_half_size = ssao_half_size;
  4555. uniform_sets_are_invalid = true;
  4556. }
  4557. EffectsRD::SSAOSettings settings;
  4558. settings.radius = env->ssao_radius;
  4559. settings.intensity = env->ssao_intensity;
  4560. settings.power = env->ssao_power;
  4561. settings.detail = env->ssao_detail;
  4562. settings.horizon = env->ssao_horizon;
  4563. settings.sharpness = env->ssao_sharpness;
  4564. settings.quality = ssao_quality;
  4565. settings.half_size = ssao_half_size;
  4566. settings.adaptive_target = ssao_adaptive_target;
  4567. settings.blur_passes = ssao_blur_passes;
  4568. settings.fadeout_from = ssao_fadeout_from;
  4569. settings.fadeout_to = ssao_fadeout_to;
  4570. settings.full_screen_size = Size2i(rb->width, rb->height);
  4571. settings.half_screen_size = Size2i(buffer_width, buffer_height);
  4572. settings.quarter_screen_size = Size2i(half_width, half_height);
  4573. storage->get_effects()->generate_ssao(rb->depth_texture, p_normal_buffer, rb->ssao.depth, rb->ssao.depth_slices, rb->ssao.ao_deinterleaved, rb->ssao.ao_deinterleaved_slices, rb->ssao.ao_pong, rb->ssao.ao_pong_slices, rb->ssao.ao_final, rb->ssao.importance_map[0], rb->ssao.importance_map[1], p_projection, settings, uniform_sets_are_invalid);
  4574. }
  4575. void RendererSceneRenderRD::_render_buffers_post_process_and_tonemap(RID p_render_buffers, RID p_environment, RID p_camera_effects, const CameraMatrix &p_projection) {
  4576. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4577. ERR_FAIL_COND(!rb);
  4578. Environment *env = environment_owner.getornull(p_environment);
  4579. //glow (if enabled)
  4580. CameraEffects *camfx = camera_effects_owner.getornull(p_camera_effects);
  4581. bool can_use_effects = rb->width >= 8 && rb->height >= 8;
  4582. if (can_use_effects && camfx && (camfx->dof_blur_near_enabled || camfx->dof_blur_far_enabled) && camfx->dof_blur_amount > 0.0) {
  4583. if (rb->blur[0].texture.is_null()) {
  4584. _allocate_blur_textures(rb);
  4585. _render_buffers_uniform_set_changed(p_render_buffers);
  4586. }
  4587. float bokeh_size = camfx->dof_blur_amount * 64.0;
  4588. storage->get_effects()->bokeh_dof(rb->texture, rb->depth_texture, Size2i(rb->width, rb->height), rb->blur[0].mipmaps[0].texture, rb->blur[1].mipmaps[0].texture, rb->blur[0].mipmaps[1].texture, camfx->dof_blur_far_enabled, camfx->dof_blur_far_distance, camfx->dof_blur_far_transition, camfx->dof_blur_near_enabled, camfx->dof_blur_near_distance, camfx->dof_blur_near_transition, bokeh_size, dof_blur_bokeh_shape, dof_blur_quality, dof_blur_use_jitter, p_projection.get_z_near(), p_projection.get_z_far(), p_projection.is_orthogonal());
  4589. }
  4590. if (can_use_effects && env && env->auto_exposure) {
  4591. if (rb->luminance.current.is_null()) {
  4592. _allocate_luminance_textures(rb);
  4593. _render_buffers_uniform_set_changed(p_render_buffers);
  4594. }
  4595. bool set_immediate = env->auto_exposure_version != rb->auto_exposure_version;
  4596. rb->auto_exposure_version = env->auto_exposure_version;
  4597. double step = env->auto_exp_speed * time_step;
  4598. storage->get_effects()->luminance_reduction(rb->texture, Size2i(rb->width, rb->height), rb->luminance.reduce, rb->luminance.current, env->min_luminance, env->max_luminance, step, set_immediate);
  4599. //swap final reduce with prev luminance
  4600. SWAP(rb->luminance.current, rb->luminance.reduce.write[rb->luminance.reduce.size() - 1]);
  4601. RenderingServerDefault::redraw_request(); //redraw all the time if auto exposure rendering is on
  4602. }
  4603. int max_glow_level = -1;
  4604. if (can_use_effects && env && env->glow_enabled) {
  4605. /* see that blur textures are allocated */
  4606. if (rb->blur[1].texture.is_null()) {
  4607. _allocate_blur_textures(rb);
  4608. _render_buffers_uniform_set_changed(p_render_buffers);
  4609. }
  4610. for (int i = 0; i < RS::MAX_GLOW_LEVELS; i++) {
  4611. if (env->glow_levels[i] > 0.0) {
  4612. if (i >= rb->blur[1].mipmaps.size()) {
  4613. max_glow_level = rb->blur[1].mipmaps.size() - 1;
  4614. } else {
  4615. max_glow_level = i;
  4616. }
  4617. }
  4618. }
  4619. for (int i = 0; i < (max_glow_level + 1); i++) {
  4620. int vp_w = rb->blur[1].mipmaps[i].width;
  4621. int vp_h = rb->blur[1].mipmaps[i].height;
  4622. if (i == 0) {
  4623. RID luminance_texture;
  4624. if (env->auto_exposure && rb->luminance.current.is_valid()) {
  4625. luminance_texture = rb->luminance.current;
  4626. }
  4627. storage->get_effects()->gaussian_glow(rb->texture, rb->blur[1].mipmaps[i].texture, Size2i(vp_w, vp_h), env->glow_strength, glow_high_quality, true, env->glow_hdr_luminance_cap, env->exposure, env->glow_bloom, env->glow_hdr_bleed_threshold, env->glow_hdr_bleed_scale, luminance_texture, env->auto_exp_scale);
  4628. } else {
  4629. storage->get_effects()->gaussian_glow(rb->blur[1].mipmaps[i - 1].texture, rb->blur[1].mipmaps[i].texture, Size2i(vp_w, vp_h), env->glow_strength, glow_high_quality);
  4630. }
  4631. }
  4632. }
  4633. {
  4634. //tonemap
  4635. EffectsRD::TonemapSettings tonemap;
  4636. if (can_use_effects && env && env->auto_exposure && rb->luminance.current.is_valid()) {
  4637. tonemap.use_auto_exposure = true;
  4638. tonemap.exposure_texture = rb->luminance.current;
  4639. tonemap.auto_exposure_grey = env->auto_exp_scale;
  4640. } else {
  4641. tonemap.exposure_texture = storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_WHITE);
  4642. }
  4643. if (can_use_effects && env && env->glow_enabled) {
  4644. tonemap.use_glow = true;
  4645. tonemap.glow_mode = EffectsRD::TonemapSettings::GlowMode(env->glow_blend_mode);
  4646. tonemap.glow_intensity = env->glow_blend_mode == RS::ENV_GLOW_BLEND_MODE_MIX ? env->glow_mix : env->glow_intensity;
  4647. for (int i = 0; i < RS::MAX_GLOW_LEVELS; i++) {
  4648. tonemap.glow_levels[i] = env->glow_levels[i];
  4649. }
  4650. tonemap.glow_texture_size.x = rb->blur[1].mipmaps[0].width;
  4651. tonemap.glow_texture_size.y = rb->blur[1].mipmaps[0].height;
  4652. tonemap.glow_use_bicubic_upscale = glow_bicubic_upscale;
  4653. tonemap.glow_texture = rb->blur[1].texture;
  4654. } else {
  4655. tonemap.glow_texture = storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_BLACK);
  4656. }
  4657. if (rb->screen_space_aa == RS::VIEWPORT_SCREEN_SPACE_AA_FXAA) {
  4658. tonemap.use_fxaa = true;
  4659. }
  4660. tonemap.use_debanding = rb->use_debanding;
  4661. tonemap.texture_size = Vector2i(rb->width, rb->height);
  4662. if (env) {
  4663. tonemap.tonemap_mode = env->tone_mapper;
  4664. tonemap.white = env->white;
  4665. tonemap.exposure = env->exposure;
  4666. }
  4667. tonemap.use_color_correction = false;
  4668. tonemap.use_1d_color_correction = false;
  4669. tonemap.color_correction_texture = storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE);
  4670. if (can_use_effects && env) {
  4671. tonemap.use_bcs = env->adjustments_enabled;
  4672. tonemap.brightness = env->adjustments_brightness;
  4673. tonemap.contrast = env->adjustments_contrast;
  4674. tonemap.saturation = env->adjustments_saturation;
  4675. if (env->adjustments_enabled && env->color_correction.is_valid()) {
  4676. tonemap.use_color_correction = true;
  4677. tonemap.use_1d_color_correction = env->use_1d_color_correction;
  4678. tonemap.color_correction_texture = storage->texture_get_rd_texture(env->color_correction);
  4679. }
  4680. }
  4681. storage->get_effects()->tonemapper(rb->texture, storage->render_target_get_rd_framebuffer(rb->render_target), tonemap);
  4682. }
  4683. storage->render_target_disable_clear_request(rb->render_target);
  4684. }
  4685. void RendererSceneRenderRD::_render_buffers_debug_draw(RID p_render_buffers, RID p_shadow_atlas) {
  4686. EffectsRD *effects = storage->get_effects();
  4687. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4688. ERR_FAIL_COND(!rb);
  4689. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SHADOW_ATLAS) {
  4690. if (p_shadow_atlas.is_valid()) {
  4691. RID shadow_atlas_texture = shadow_atlas_get_texture(p_shadow_atlas);
  4692. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4693. effects->copy_to_fb_rect(shadow_atlas_texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2i(Vector2(), rtsize / 2), false, true);
  4694. }
  4695. }
  4696. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_DIRECTIONAL_SHADOW_ATLAS) {
  4697. if (directional_shadow_get_texture().is_valid()) {
  4698. RID shadow_atlas_texture = directional_shadow_get_texture();
  4699. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4700. effects->copy_to_fb_rect(shadow_atlas_texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2i(Vector2(), rtsize / 2), false, true);
  4701. }
  4702. }
  4703. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_DECAL_ATLAS) {
  4704. RID decal_atlas = storage->decal_atlas_get_texture();
  4705. if (decal_atlas.is_valid()) {
  4706. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4707. effects->copy_to_fb_rect(decal_atlas, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2i(Vector2(), rtsize / 2), false, false, true);
  4708. }
  4709. }
  4710. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SCENE_LUMINANCE) {
  4711. if (rb->luminance.current.is_valid()) {
  4712. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4713. effects->copy_to_fb_rect(rb->luminance.current, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize / 8), false, true);
  4714. }
  4715. }
  4716. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SSAO && rb->ssao.ao_final.is_valid()) {
  4717. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4718. RID ao_buf = rb->ssao.ao_final;
  4719. effects->copy_to_fb_rect(ao_buf, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), false, true);
  4720. }
  4721. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_NORMAL_BUFFER && _render_buffers_get_normal_texture(p_render_buffers).is_valid()) {
  4722. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4723. effects->copy_to_fb_rect(_render_buffers_get_normal_texture(p_render_buffers), storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), false, false);
  4724. }
  4725. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_GI_BUFFER && rb->ambient_buffer.is_valid()) {
  4726. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4727. RID ambient_texture = rb->ambient_buffer;
  4728. RID reflection_texture = rb->reflection_buffer;
  4729. effects->copy_to_fb_rect(ambient_texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), false, false, false, true, reflection_texture);
  4730. }
  4731. }
  4732. void RendererSceneRenderRD::environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, bool p_use_1d_color_correction, RID p_color_correction) {
  4733. Environment *env = environment_owner.getornull(p_env);
  4734. ERR_FAIL_COND(!env);
  4735. env->adjustments_enabled = p_enable;
  4736. env->adjustments_brightness = p_brightness;
  4737. env->adjustments_contrast = p_contrast;
  4738. env->adjustments_saturation = p_saturation;
  4739. env->use_1d_color_correction = p_use_1d_color_correction;
  4740. env->color_correction = p_color_correction;
  4741. }
  4742. void RendererSceneRenderRD::_sdfgi_debug_draw(RID p_render_buffers, const CameraMatrix &p_projection, const Transform &p_transform) {
  4743. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4744. ERR_FAIL_COND(!rb);
  4745. if (!rb->sdfgi) {
  4746. return; //eh
  4747. }
  4748. if (!rb->sdfgi->debug_uniform_set.is_valid() || !RD::get_singleton()->uniform_set_is_valid(rb->sdfgi->debug_uniform_set)) {
  4749. Vector<RD::Uniform> uniforms;
  4750. {
  4751. RD::Uniform u;
  4752. u.binding = 1;
  4753. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  4754. for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
  4755. if (i < rb->sdfgi->cascades.size()) {
  4756. u.ids.push_back(rb->sdfgi->cascades[i].sdf_tex);
  4757. } else {
  4758. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  4759. }
  4760. }
  4761. uniforms.push_back(u);
  4762. }
  4763. {
  4764. RD::Uniform u;
  4765. u.binding = 2;
  4766. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  4767. for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
  4768. if (i < rb->sdfgi->cascades.size()) {
  4769. u.ids.push_back(rb->sdfgi->cascades[i].light_tex);
  4770. } else {
  4771. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  4772. }
  4773. }
  4774. uniforms.push_back(u);
  4775. }
  4776. {
  4777. RD::Uniform u;
  4778. u.binding = 3;
  4779. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  4780. for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
  4781. if (i < rb->sdfgi->cascades.size()) {
  4782. u.ids.push_back(rb->sdfgi->cascades[i].light_aniso_0_tex);
  4783. } else {
  4784. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  4785. }
  4786. }
  4787. uniforms.push_back(u);
  4788. }
  4789. {
  4790. RD::Uniform u;
  4791. u.binding = 4;
  4792. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  4793. for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
  4794. if (i < rb->sdfgi->cascades.size()) {
  4795. u.ids.push_back(rb->sdfgi->cascades[i].light_aniso_1_tex);
  4796. } else {
  4797. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  4798. }
  4799. }
  4800. uniforms.push_back(u);
  4801. }
  4802. {
  4803. RD::Uniform u;
  4804. u.binding = 5;
  4805. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  4806. u.ids.push_back(rb->sdfgi->occlusion_texture);
  4807. uniforms.push_back(u);
  4808. }
  4809. {
  4810. RD::Uniform u;
  4811. u.binding = 8;
  4812. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  4813. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  4814. uniforms.push_back(u);
  4815. }
  4816. {
  4817. RD::Uniform u;
  4818. u.binding = 9;
  4819. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  4820. u.ids.push_back(rb->sdfgi->cascades_ubo);
  4821. uniforms.push_back(u);
  4822. }
  4823. {
  4824. RD::Uniform u;
  4825. u.binding = 10;
  4826. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  4827. u.ids.push_back(rb->texture);
  4828. uniforms.push_back(u);
  4829. }
  4830. {
  4831. RD::Uniform u;
  4832. u.binding = 11;
  4833. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  4834. u.ids.push_back(rb->sdfgi->lightprobe_texture);
  4835. uniforms.push_back(u);
  4836. }
  4837. rb->sdfgi->debug_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.debug_shader_version, 0);
  4838. }
  4839. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  4840. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.debug_pipeline);
  4841. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->debug_uniform_set, 0);
  4842. SDGIShader::DebugPushConstant push_constant;
  4843. push_constant.grid_size[0] = rb->sdfgi->cascade_size;
  4844. push_constant.grid_size[1] = rb->sdfgi->cascade_size;
  4845. push_constant.grid_size[2] = rb->sdfgi->cascade_size;
  4846. push_constant.max_cascades = rb->sdfgi->cascades.size();
  4847. push_constant.screen_size[0] = rb->width;
  4848. push_constant.screen_size[1] = rb->height;
  4849. push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  4850. push_constant.use_occlusion = rb->sdfgi->uses_occlusion;
  4851. push_constant.y_mult = rb->sdfgi->y_mult;
  4852. Vector2 vp_half = p_projection.get_viewport_half_extents();
  4853. push_constant.cam_extent[0] = vp_half.x;
  4854. push_constant.cam_extent[1] = vp_half.y;
  4855. push_constant.cam_extent[2] = -p_projection.get_z_near();
  4856. push_constant.cam_transform[0] = p_transform.basis.elements[0][0];
  4857. push_constant.cam_transform[1] = p_transform.basis.elements[1][0];
  4858. push_constant.cam_transform[2] = p_transform.basis.elements[2][0];
  4859. push_constant.cam_transform[3] = 0;
  4860. push_constant.cam_transform[4] = p_transform.basis.elements[0][1];
  4861. push_constant.cam_transform[5] = p_transform.basis.elements[1][1];
  4862. push_constant.cam_transform[6] = p_transform.basis.elements[2][1];
  4863. push_constant.cam_transform[7] = 0;
  4864. push_constant.cam_transform[8] = p_transform.basis.elements[0][2];
  4865. push_constant.cam_transform[9] = p_transform.basis.elements[1][2];
  4866. push_constant.cam_transform[10] = p_transform.basis.elements[2][2];
  4867. push_constant.cam_transform[11] = 0;
  4868. push_constant.cam_transform[12] = p_transform.origin.x;
  4869. push_constant.cam_transform[13] = p_transform.origin.y;
  4870. push_constant.cam_transform[14] = p_transform.origin.z;
  4871. push_constant.cam_transform[15] = 1;
  4872. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::DebugPushConstant));
  4873. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->width, rb->height, 1);
  4874. RD::get_singleton()->compute_list_end();
  4875. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4876. storage->get_effects()->copy_to_fb_rect(rb->texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), true);
  4877. }
  4878. RID RendererSceneRenderRD::render_buffers_get_back_buffer_texture(RID p_render_buffers) {
  4879. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4880. ERR_FAIL_COND_V(!rb, RID());
  4881. if (!rb->blur[0].texture.is_valid()) {
  4882. return RID(); //not valid at the moment
  4883. }
  4884. return rb->blur[0].texture;
  4885. }
  4886. RID RendererSceneRenderRD::render_buffers_get_ao_texture(RID p_render_buffers) {
  4887. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4888. ERR_FAIL_COND_V(!rb, RID());
  4889. return rb->ssao.ao_final;
  4890. }
  4891. RID RendererSceneRenderRD::render_buffers_get_gi_probe_buffer(RID p_render_buffers) {
  4892. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4893. ERR_FAIL_COND_V(!rb, RID());
  4894. if (rb->giprobe_buffer.is_null()) {
  4895. rb->giprobe_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(GI::GIProbeData) * RenderBuffers::MAX_GIPROBES);
  4896. }
  4897. return rb->giprobe_buffer;
  4898. }
  4899. RID RendererSceneRenderRD::render_buffers_get_default_gi_probe_buffer() {
  4900. return default_giprobe_buffer;
  4901. }
  4902. RID RendererSceneRenderRD::render_buffers_get_gi_ambient_texture(RID p_render_buffers) {
  4903. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4904. ERR_FAIL_COND_V(!rb, RID());
  4905. return rb->ambient_buffer;
  4906. }
  4907. RID RendererSceneRenderRD::render_buffers_get_gi_reflection_texture(RID p_render_buffers) {
  4908. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4909. ERR_FAIL_COND_V(!rb, RID());
  4910. return rb->reflection_buffer;
  4911. }
  4912. uint32_t RendererSceneRenderRD::render_buffers_get_sdfgi_cascade_count(RID p_render_buffers) const {
  4913. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4914. ERR_FAIL_COND_V(!rb, 0);
  4915. ERR_FAIL_COND_V(!rb->sdfgi, 0);
  4916. return rb->sdfgi->cascades.size();
  4917. }
  4918. bool RendererSceneRenderRD::render_buffers_is_sdfgi_enabled(RID p_render_buffers) const {
  4919. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4920. ERR_FAIL_COND_V(!rb, false);
  4921. return rb->sdfgi != nullptr;
  4922. }
  4923. RID RendererSceneRenderRD::render_buffers_get_sdfgi_irradiance_probes(RID p_render_buffers) const {
  4924. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4925. ERR_FAIL_COND_V(!rb, RID());
  4926. ERR_FAIL_COND_V(!rb->sdfgi, RID());
  4927. return rb->sdfgi->lightprobe_texture;
  4928. }
  4929. Vector3 RendererSceneRenderRD::render_buffers_get_sdfgi_cascade_offset(RID p_render_buffers, uint32_t p_cascade) const {
  4930. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4931. ERR_FAIL_COND_V(!rb, Vector3());
  4932. ERR_FAIL_COND_V(!rb->sdfgi, Vector3());
  4933. ERR_FAIL_UNSIGNED_INDEX_V(p_cascade, rb->sdfgi->cascades.size(), Vector3());
  4934. return Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[p_cascade].position)) * rb->sdfgi->cascades[p_cascade].cell_size;
  4935. }
  4936. Vector3i RendererSceneRenderRD::render_buffers_get_sdfgi_cascade_probe_offset(RID p_render_buffers, uint32_t p_cascade) const {
  4937. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4938. ERR_FAIL_COND_V(!rb, Vector3i());
  4939. ERR_FAIL_COND_V(!rb->sdfgi, Vector3i());
  4940. ERR_FAIL_UNSIGNED_INDEX_V(p_cascade, rb->sdfgi->cascades.size(), Vector3i());
  4941. int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  4942. return rb->sdfgi->cascades[p_cascade].position / probe_divisor;
  4943. }
  4944. float RendererSceneRenderRD::render_buffers_get_sdfgi_normal_bias(RID p_render_buffers) const {
  4945. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4946. ERR_FAIL_COND_V(!rb, 0);
  4947. ERR_FAIL_COND_V(!rb->sdfgi, 0);
  4948. return rb->sdfgi->normal_bias;
  4949. }
  4950. float RendererSceneRenderRD::render_buffers_get_sdfgi_cascade_probe_size(RID p_render_buffers, uint32_t p_cascade) const {
  4951. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4952. ERR_FAIL_COND_V(!rb, 0);
  4953. ERR_FAIL_COND_V(!rb->sdfgi, 0);
  4954. ERR_FAIL_UNSIGNED_INDEX_V(p_cascade, rb->sdfgi->cascades.size(), 0);
  4955. return float(rb->sdfgi->cascade_size) * rb->sdfgi->cascades[p_cascade].cell_size / float(rb->sdfgi->probe_axis_count - 1);
  4956. }
  4957. uint32_t RendererSceneRenderRD::render_buffers_get_sdfgi_cascade_probe_count(RID p_render_buffers) const {
  4958. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4959. ERR_FAIL_COND_V(!rb, 0);
  4960. ERR_FAIL_COND_V(!rb->sdfgi, 0);
  4961. return rb->sdfgi->probe_axis_count;
  4962. }
  4963. uint32_t RendererSceneRenderRD::render_buffers_get_sdfgi_cascade_size(RID p_render_buffers) const {
  4964. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4965. ERR_FAIL_COND_V(!rb, 0);
  4966. ERR_FAIL_COND_V(!rb->sdfgi, 0);
  4967. return rb->sdfgi->cascade_size;
  4968. }
  4969. bool RendererSceneRenderRD::render_buffers_is_sdfgi_using_occlusion(RID p_render_buffers) const {
  4970. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4971. ERR_FAIL_COND_V(!rb, false);
  4972. ERR_FAIL_COND_V(!rb->sdfgi, false);
  4973. return rb->sdfgi->uses_occlusion;
  4974. }
  4975. float RendererSceneRenderRD::render_buffers_get_sdfgi_energy(RID p_render_buffers) const {
  4976. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4977. ERR_FAIL_COND_V(!rb, 0.0);
  4978. ERR_FAIL_COND_V(!rb->sdfgi, 0.0);
  4979. return rb->sdfgi->energy;
  4980. }
  4981. RID RendererSceneRenderRD::render_buffers_get_sdfgi_occlusion_texture(RID p_render_buffers) const {
  4982. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4983. ERR_FAIL_COND_V(!rb, RID());
  4984. ERR_FAIL_COND_V(!rb->sdfgi, RID());
  4985. return rb->sdfgi->occlusion_texture;
  4986. }
  4987. bool RendererSceneRenderRD::render_buffers_has_volumetric_fog(RID p_render_buffers) const {
  4988. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4989. ERR_FAIL_COND_V(!rb, false);
  4990. return rb->volumetric_fog != nullptr;
  4991. }
  4992. RID RendererSceneRenderRD::render_buffers_get_volumetric_fog_texture(RID p_render_buffers) {
  4993. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4994. ERR_FAIL_COND_V(!rb || !rb->volumetric_fog, RID());
  4995. return rb->volumetric_fog->fog_map;
  4996. }
  4997. RID RendererSceneRenderRD::render_buffers_get_volumetric_fog_sky_uniform_set(RID p_render_buffers) {
  4998. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4999. ERR_FAIL_COND_V(!rb, RID());
  5000. if (!rb->volumetric_fog) {
  5001. return RID();
  5002. }
  5003. return rb->volumetric_fog->sky_uniform_set;
  5004. }
  5005. float RendererSceneRenderRD::render_buffers_get_volumetric_fog_end(RID p_render_buffers) {
  5006. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  5007. ERR_FAIL_COND_V(!rb || !rb->volumetric_fog, 0);
  5008. return rb->volumetric_fog->length;
  5009. }
  5010. float RendererSceneRenderRD::render_buffers_get_volumetric_fog_detail_spread(RID p_render_buffers) {
  5011. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  5012. ERR_FAIL_COND_V(!rb || !rb->volumetric_fog, 0);
  5013. return rb->volumetric_fog->spread;
  5014. }
  5015. void RendererSceneRenderRD::render_buffers_configure(RID p_render_buffers, RID p_render_target, int p_width, int p_height, RS::ViewportMSAA p_msaa, RenderingServer::ViewportScreenSpaceAA p_screen_space_aa, bool p_use_debanding) {
  5016. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  5017. rb->width = p_width;
  5018. rb->height = p_height;
  5019. rb->render_target = p_render_target;
  5020. rb->msaa = p_msaa;
  5021. rb->screen_space_aa = p_screen_space_aa;
  5022. rb->use_debanding = p_use_debanding;
  5023. if (rb->cluster_builder == nullptr) {
  5024. rb->cluster_builder = memnew(ClusterBuilderRD);
  5025. }
  5026. rb->cluster_builder->set_shared(&cluster_builder_shared);
  5027. _free_render_buffer_data(rb);
  5028. {
  5029. RD::TextureFormat tf;
  5030. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  5031. tf.width = rb->width;
  5032. tf.height = rb->height;
  5033. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  5034. if (rb->msaa != RS::VIEWPORT_MSAA_DISABLED) {
  5035. tf.usage_bits |= RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  5036. } else {
  5037. tf.usage_bits |= RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  5038. }
  5039. rb->texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5040. }
  5041. {
  5042. RD::TextureFormat tf;
  5043. if (rb->msaa == RS::VIEWPORT_MSAA_DISABLED) {
  5044. tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D24_UNORM_S8_UINT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D24_UNORM_S8_UINT : RD::DATA_FORMAT_D32_SFLOAT_S8_UINT;
  5045. } else {
  5046. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  5047. }
  5048. tf.width = p_width;
  5049. tf.height = p_height;
  5050. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT;
  5051. if (rb->msaa != RS::VIEWPORT_MSAA_DISABLED) {
  5052. tf.usage_bits |= RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  5053. } else {
  5054. tf.usage_bits |= RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  5055. }
  5056. rb->depth_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5057. }
  5058. rb->data->configure(rb->texture, rb->depth_texture, p_width, p_height, p_msaa);
  5059. _render_buffers_uniform_set_changed(p_render_buffers);
  5060. rb->cluster_builder->setup(Size2i(p_width, p_height), max_cluster_elements, rb->depth_texture, storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED), rb->texture);
  5061. }
  5062. void RendererSceneRenderRD::gi_set_use_half_resolution(bool p_enable) {
  5063. gi.half_resolution = p_enable;
  5064. }
  5065. void RendererSceneRenderRD::sub_surface_scattering_set_quality(RS::SubSurfaceScatteringQuality p_quality) {
  5066. sss_quality = p_quality;
  5067. }
  5068. RS::SubSurfaceScatteringQuality RendererSceneRenderRD::sub_surface_scattering_get_quality() const {
  5069. return sss_quality;
  5070. }
  5071. void RendererSceneRenderRD::sub_surface_scattering_set_scale(float p_scale, float p_depth_scale) {
  5072. sss_scale = p_scale;
  5073. sss_depth_scale = p_depth_scale;
  5074. }
  5075. void RendererSceneRenderRD::shadows_quality_set(RS::ShadowQuality p_quality) {
  5076. ERR_FAIL_INDEX_MSG(p_quality, RS::SHADOW_QUALITY_MAX, "Shadow quality too high, please see RenderingServer's ShadowQuality enum");
  5077. if (shadows_quality != p_quality) {
  5078. shadows_quality = p_quality;
  5079. switch (shadows_quality) {
  5080. case RS::SHADOW_QUALITY_HARD: {
  5081. penumbra_shadow_samples = 4;
  5082. soft_shadow_samples = 1;
  5083. shadows_quality_radius = 1.0;
  5084. } break;
  5085. case RS::SHADOW_QUALITY_SOFT_LOW: {
  5086. penumbra_shadow_samples = 8;
  5087. soft_shadow_samples = 4;
  5088. shadows_quality_radius = 2.0;
  5089. } break;
  5090. case RS::SHADOW_QUALITY_SOFT_MEDIUM: {
  5091. penumbra_shadow_samples = 12;
  5092. soft_shadow_samples = 8;
  5093. shadows_quality_radius = 2.0;
  5094. } break;
  5095. case RS::SHADOW_QUALITY_SOFT_HIGH: {
  5096. penumbra_shadow_samples = 24;
  5097. soft_shadow_samples = 16;
  5098. shadows_quality_radius = 3.0;
  5099. } break;
  5100. case RS::SHADOW_QUALITY_SOFT_ULTRA: {
  5101. penumbra_shadow_samples = 32;
  5102. soft_shadow_samples = 32;
  5103. shadows_quality_radius = 4.0;
  5104. } break;
  5105. case RS::SHADOW_QUALITY_MAX:
  5106. break;
  5107. }
  5108. get_vogel_disk(penumbra_shadow_kernel, penumbra_shadow_samples);
  5109. get_vogel_disk(soft_shadow_kernel, soft_shadow_samples);
  5110. }
  5111. }
  5112. void RendererSceneRenderRD::directional_shadow_quality_set(RS::ShadowQuality p_quality) {
  5113. ERR_FAIL_INDEX_MSG(p_quality, RS::SHADOW_QUALITY_MAX, "Shadow quality too high, please see RenderingServer's ShadowQuality enum");
  5114. if (directional_shadow_quality != p_quality) {
  5115. directional_shadow_quality = p_quality;
  5116. switch (directional_shadow_quality) {
  5117. case RS::SHADOW_QUALITY_HARD: {
  5118. directional_penumbra_shadow_samples = 4;
  5119. directional_soft_shadow_samples = 1;
  5120. directional_shadow_quality_radius = 1.0;
  5121. } break;
  5122. case RS::SHADOW_QUALITY_SOFT_LOW: {
  5123. directional_penumbra_shadow_samples = 8;
  5124. directional_soft_shadow_samples = 4;
  5125. directional_shadow_quality_radius = 2.0;
  5126. } break;
  5127. case RS::SHADOW_QUALITY_SOFT_MEDIUM: {
  5128. directional_penumbra_shadow_samples = 12;
  5129. directional_soft_shadow_samples = 8;
  5130. directional_shadow_quality_radius = 2.0;
  5131. } break;
  5132. case RS::SHADOW_QUALITY_SOFT_HIGH: {
  5133. directional_penumbra_shadow_samples = 24;
  5134. directional_soft_shadow_samples = 16;
  5135. directional_shadow_quality_radius = 3.0;
  5136. } break;
  5137. case RS::SHADOW_QUALITY_SOFT_ULTRA: {
  5138. directional_penumbra_shadow_samples = 32;
  5139. directional_soft_shadow_samples = 32;
  5140. directional_shadow_quality_radius = 4.0;
  5141. } break;
  5142. case RS::SHADOW_QUALITY_MAX:
  5143. break;
  5144. }
  5145. get_vogel_disk(directional_penumbra_shadow_kernel, directional_penumbra_shadow_samples);
  5146. get_vogel_disk(directional_soft_shadow_kernel, directional_soft_shadow_samples);
  5147. }
  5148. }
  5149. int RendererSceneRenderRD::get_roughness_layers() const {
  5150. return roughness_layers;
  5151. }
  5152. bool RendererSceneRenderRD::is_using_radiance_cubemap_array() const {
  5153. return sky_use_cubemap_array;
  5154. }
  5155. RendererSceneRenderRD::RenderBufferData *RendererSceneRenderRD::render_buffers_get_data(RID p_render_buffers) {
  5156. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  5157. ERR_FAIL_COND_V(!rb, nullptr);
  5158. return rb->data;
  5159. }
  5160. void RendererSceneRenderRD::_setup_reflections(const PagedArray<RID> &p_reflections, const Transform &p_camera_inverse_transform, RID p_environment) {
  5161. cluster.reflection_count = 0;
  5162. for (uint32_t i = 0; i < (uint32_t)p_reflections.size(); i++) {
  5163. if (cluster.reflection_count == cluster.max_reflections) {
  5164. break;
  5165. }
  5166. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_reflections[i]);
  5167. if (!rpi) {
  5168. continue;
  5169. }
  5170. cluster.reflection_sort[cluster.reflection_count].instance = rpi;
  5171. cluster.reflection_sort[cluster.reflection_count].depth = -p_camera_inverse_transform.xform(rpi->transform.origin).z;
  5172. cluster.reflection_count++;
  5173. }
  5174. if (cluster.reflection_count > 0) {
  5175. SortArray<Cluster::InstanceSort<ReflectionProbeInstance>> sort_array;
  5176. sort_array.sort(cluster.reflection_sort, cluster.reflection_count);
  5177. }
  5178. for (uint32_t i = 0; i < cluster.reflection_count; i++) {
  5179. ReflectionProbeInstance *rpi = cluster.reflection_sort[i].instance;
  5180. rpi->render_index = i;
  5181. RID base_probe = rpi->probe;
  5182. Cluster::ReflectionData &reflection_ubo = cluster.reflections[i];
  5183. Vector3 extents = storage->reflection_probe_get_extents(base_probe);
  5184. reflection_ubo.box_extents[0] = extents.x;
  5185. reflection_ubo.box_extents[1] = extents.y;
  5186. reflection_ubo.box_extents[2] = extents.z;
  5187. reflection_ubo.index = rpi->atlas_index;
  5188. Vector3 origin_offset = storage->reflection_probe_get_origin_offset(base_probe);
  5189. reflection_ubo.box_offset[0] = origin_offset.x;
  5190. reflection_ubo.box_offset[1] = origin_offset.y;
  5191. reflection_ubo.box_offset[2] = origin_offset.z;
  5192. reflection_ubo.mask = storage->reflection_probe_get_cull_mask(base_probe);
  5193. reflection_ubo.intensity = storage->reflection_probe_get_intensity(base_probe);
  5194. reflection_ubo.ambient_mode = storage->reflection_probe_get_ambient_mode(base_probe);
  5195. reflection_ubo.exterior = !storage->reflection_probe_is_interior(base_probe);
  5196. reflection_ubo.box_project = storage->reflection_probe_is_box_projection(base_probe);
  5197. Color ambient_linear = storage->reflection_probe_get_ambient_color(base_probe).to_linear();
  5198. float interior_ambient_energy = storage->reflection_probe_get_ambient_color_energy(base_probe);
  5199. reflection_ubo.ambient[0] = ambient_linear.r * interior_ambient_energy;
  5200. reflection_ubo.ambient[1] = ambient_linear.g * interior_ambient_energy;
  5201. reflection_ubo.ambient[2] = ambient_linear.b * interior_ambient_energy;
  5202. Transform transform = rpi->transform;
  5203. Transform proj = (p_camera_inverse_transform * transform).inverse();
  5204. RendererStorageRD::store_transform(proj, reflection_ubo.local_matrix);
  5205. current_cluster_builder->add_box(ClusterBuilderRD::BOX_TYPE_REFLECTION_PROBE, transform, extents);
  5206. rpi->last_pass = RSG::rasterizer->get_frame_number();
  5207. }
  5208. if (cluster.reflection_count) {
  5209. RD::get_singleton()->buffer_update(cluster.reflection_buffer, 0, cluster.reflection_count * sizeof(ReflectionData), cluster.reflections, RD::BARRIER_MASK_RASTER | RD::BARRIER_MASK_COMPUTE);
  5210. }
  5211. }
  5212. void RendererSceneRenderRD::_setup_lights(const PagedArray<RID> &p_lights, const Transform &p_camera_transform, RID p_shadow_atlas, bool p_using_shadows, uint32_t &r_directional_light_count, uint32_t &r_positional_light_count) {
  5213. Transform inverse_transform = p_camera_transform.affine_inverse();
  5214. r_directional_light_count = 0;
  5215. r_positional_light_count = 0;
  5216. sky_scene_state.ubo.directional_light_count = 0;
  5217. Plane camera_plane(p_camera_transform.origin, -p_camera_transform.basis.get_axis(Vector3::AXIS_Z).normalized());
  5218. cluster.omni_light_count = 0;
  5219. cluster.spot_light_count = 0;
  5220. for (int i = 0; i < (int)p_lights.size(); i++) {
  5221. LightInstance *li = light_instance_owner.getornull(p_lights[i]);
  5222. if (!li) {
  5223. continue;
  5224. }
  5225. RID base = li->light;
  5226. ERR_CONTINUE(base.is_null());
  5227. RS::LightType type = storage->light_get_type(base);
  5228. switch (type) {
  5229. case RS::LIGHT_DIRECTIONAL: {
  5230. // Copy to SkyDirectionalLightData
  5231. if (r_directional_light_count < sky_scene_state.max_directional_lights) {
  5232. SkyDirectionalLightData &sky_light_data = sky_scene_state.directional_lights[r_directional_light_count];
  5233. Transform light_transform = li->transform;
  5234. Vector3 world_direction = light_transform.basis.xform(Vector3(0, 0, 1)).normalized();
  5235. sky_light_data.direction[0] = world_direction.x;
  5236. sky_light_data.direction[1] = world_direction.y;
  5237. sky_light_data.direction[2] = -world_direction.z;
  5238. float sign = storage->light_is_negative(base) ? -1 : 1;
  5239. sky_light_data.energy = sign * storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY);
  5240. Color linear_col = storage->light_get_color(base).to_linear();
  5241. sky_light_data.color[0] = linear_col.r;
  5242. sky_light_data.color[1] = linear_col.g;
  5243. sky_light_data.color[2] = linear_col.b;
  5244. sky_light_data.enabled = true;
  5245. float angular_diameter = storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  5246. if (angular_diameter > 0.0) {
  5247. // I know tan(0) is 0, but let's not risk it with numerical precision.
  5248. // technically this will keep expanding until reaching the sun, but all we care
  5249. // is expand until we reach the radius of the near plane (there can't be more occluders than that)
  5250. angular_diameter = Math::tan(Math::deg2rad(angular_diameter));
  5251. } else {
  5252. angular_diameter = 0.0;
  5253. }
  5254. sky_light_data.size = angular_diameter;
  5255. sky_scene_state.ubo.directional_light_count++;
  5256. }
  5257. if (r_directional_light_count >= cluster.max_directional_lights || storage->light_directional_is_sky_only(base)) {
  5258. continue;
  5259. }
  5260. Cluster::DirectionalLightData &light_data = cluster.directional_lights[r_directional_light_count];
  5261. Transform light_transform = li->transform;
  5262. Vector3 direction = inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, 1))).normalized();
  5263. light_data.direction[0] = direction.x;
  5264. light_data.direction[1] = direction.y;
  5265. light_data.direction[2] = direction.z;
  5266. float sign = storage->light_is_negative(base) ? -1 : 1;
  5267. light_data.energy = sign * storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY) * Math_PI;
  5268. Color linear_col = storage->light_get_color(base).to_linear();
  5269. light_data.color[0] = linear_col.r;
  5270. light_data.color[1] = linear_col.g;
  5271. light_data.color[2] = linear_col.b;
  5272. light_data.specular = storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR);
  5273. light_data.mask = storage->light_get_cull_mask(base);
  5274. float size = storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  5275. light_data.size = 1.0 - Math::cos(Math::deg2rad(size)); //angle to cosine offset
  5276. Color shadow_col = storage->light_get_shadow_color(base).to_linear();
  5277. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_PSSM_SPLITS) {
  5278. light_data.shadow_color1[0] = 1.0;
  5279. light_data.shadow_color1[1] = 0.0;
  5280. light_data.shadow_color1[2] = 0.0;
  5281. light_data.shadow_color1[3] = 1.0;
  5282. light_data.shadow_color2[0] = 0.0;
  5283. light_data.shadow_color2[1] = 1.0;
  5284. light_data.shadow_color2[2] = 0.0;
  5285. light_data.shadow_color2[3] = 1.0;
  5286. light_data.shadow_color3[0] = 0.0;
  5287. light_data.shadow_color3[1] = 0.0;
  5288. light_data.shadow_color3[2] = 1.0;
  5289. light_data.shadow_color3[3] = 1.0;
  5290. light_data.shadow_color4[0] = 1.0;
  5291. light_data.shadow_color4[1] = 1.0;
  5292. light_data.shadow_color4[2] = 0.0;
  5293. light_data.shadow_color4[3] = 1.0;
  5294. } else {
  5295. light_data.shadow_color1[0] = shadow_col.r;
  5296. light_data.shadow_color1[1] = shadow_col.g;
  5297. light_data.shadow_color1[2] = shadow_col.b;
  5298. light_data.shadow_color1[3] = 1.0;
  5299. light_data.shadow_color2[0] = shadow_col.r;
  5300. light_data.shadow_color2[1] = shadow_col.g;
  5301. light_data.shadow_color2[2] = shadow_col.b;
  5302. light_data.shadow_color2[3] = 1.0;
  5303. light_data.shadow_color3[0] = shadow_col.r;
  5304. light_data.shadow_color3[1] = shadow_col.g;
  5305. light_data.shadow_color3[2] = shadow_col.b;
  5306. light_data.shadow_color3[3] = 1.0;
  5307. light_data.shadow_color4[0] = shadow_col.r;
  5308. light_data.shadow_color4[1] = shadow_col.g;
  5309. light_data.shadow_color4[2] = shadow_col.b;
  5310. light_data.shadow_color4[3] = 1.0;
  5311. }
  5312. light_data.shadow_enabled = p_using_shadows && storage->light_has_shadow(base);
  5313. float angular_diameter = storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  5314. if (angular_diameter > 0.0) {
  5315. // I know tan(0) is 0, but let's not risk it with numerical precision.
  5316. // technically this will keep expanding until reaching the sun, but all we care
  5317. // is expand until we reach the radius of the near plane (there can't be more occluders than that)
  5318. angular_diameter = Math::tan(Math::deg2rad(angular_diameter));
  5319. } else {
  5320. angular_diameter = 0.0;
  5321. }
  5322. if (light_data.shadow_enabled) {
  5323. RS::LightDirectionalShadowMode smode = storage->light_directional_get_shadow_mode(base);
  5324. int limit = smode == RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL ? 0 : (smode == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS ? 1 : 3);
  5325. light_data.blend_splits = storage->light_directional_get_blend_splits(base);
  5326. for (int j = 0; j < 4; j++) {
  5327. Rect2 atlas_rect = li->shadow_transform[j].atlas_rect;
  5328. CameraMatrix matrix = li->shadow_transform[j].camera;
  5329. float split = li->shadow_transform[MIN(limit, j)].split;
  5330. CameraMatrix bias;
  5331. bias.set_light_bias();
  5332. CameraMatrix rectm;
  5333. rectm.set_light_atlas_rect(atlas_rect);
  5334. Transform modelview = (inverse_transform * li->shadow_transform[j].transform).inverse();
  5335. CameraMatrix shadow_mtx = rectm * bias * matrix * modelview;
  5336. light_data.shadow_split_offsets[j] = split;
  5337. float bias_scale = li->shadow_transform[j].bias_scale;
  5338. light_data.shadow_bias[j] = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) * bias_scale;
  5339. light_data.shadow_normal_bias[j] = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * li->shadow_transform[j].shadow_texel_size;
  5340. light_data.shadow_transmittance_bias[j] = storage->light_get_transmittance_bias(base) * bias_scale;
  5341. light_data.shadow_z_range[j] = li->shadow_transform[j].farplane;
  5342. light_data.shadow_range_begin[j] = li->shadow_transform[j].range_begin;
  5343. RendererStorageRD::store_camera(shadow_mtx, light_data.shadow_matrices[j]);
  5344. Vector2 uv_scale = li->shadow_transform[j].uv_scale;
  5345. uv_scale *= atlas_rect.size; //adapt to atlas size
  5346. switch (j) {
  5347. case 0: {
  5348. light_data.uv_scale1[0] = uv_scale.x;
  5349. light_data.uv_scale1[1] = uv_scale.y;
  5350. } break;
  5351. case 1: {
  5352. light_data.uv_scale2[0] = uv_scale.x;
  5353. light_data.uv_scale2[1] = uv_scale.y;
  5354. } break;
  5355. case 2: {
  5356. light_data.uv_scale3[0] = uv_scale.x;
  5357. light_data.uv_scale3[1] = uv_scale.y;
  5358. } break;
  5359. case 3: {
  5360. light_data.uv_scale4[0] = uv_scale.x;
  5361. light_data.uv_scale4[1] = uv_scale.y;
  5362. } break;
  5363. }
  5364. }
  5365. float fade_start = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_FADE_START);
  5366. light_data.fade_from = -light_data.shadow_split_offsets[3] * MIN(fade_start, 0.999); //using 1.0 would break smoothstep
  5367. light_data.fade_to = -light_data.shadow_split_offsets[3];
  5368. light_data.shadow_volumetric_fog_fade = 1.0 / storage->light_get_shadow_volumetric_fog_fade(base);
  5369. light_data.soft_shadow_scale = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BLUR);
  5370. light_data.softshadow_angle = angular_diameter;
  5371. if (angular_diameter <= 0.0) {
  5372. light_data.soft_shadow_scale *= directional_shadow_quality_radius_get(); // Only use quality radius for PCF
  5373. }
  5374. }
  5375. r_directional_light_count++;
  5376. } break;
  5377. case RS::LIGHT_OMNI: {
  5378. if (cluster.omni_light_count >= cluster.max_lights) {
  5379. continue;
  5380. }
  5381. cluster.omni_light_sort[cluster.omni_light_count].instance = li;
  5382. cluster.omni_light_sort[cluster.omni_light_count].depth = camera_plane.distance_to(li->transform.origin);
  5383. cluster.omni_light_count++;
  5384. } break;
  5385. case RS::LIGHT_SPOT: {
  5386. if (cluster.spot_light_count >= cluster.max_lights) {
  5387. continue;
  5388. }
  5389. cluster.spot_light_sort[cluster.spot_light_count].instance = li;
  5390. cluster.spot_light_sort[cluster.spot_light_count].depth = camera_plane.distance_to(li->transform.origin);
  5391. cluster.spot_light_count++;
  5392. } break;
  5393. }
  5394. li->last_pass = RSG::rasterizer->get_frame_number();
  5395. }
  5396. if (cluster.omni_light_count) {
  5397. SortArray<Cluster::InstanceSort<LightInstance>> sorter;
  5398. sorter.sort(cluster.omni_light_sort, cluster.omni_light_count);
  5399. }
  5400. if (cluster.spot_light_count) {
  5401. SortArray<Cluster::InstanceSort<LightInstance>> sorter;
  5402. sorter.sort(cluster.spot_light_sort, cluster.spot_light_count);
  5403. }
  5404. ShadowAtlas *shadow_atlas = nullptr;
  5405. if (p_shadow_atlas.is_valid() && p_using_shadows) {
  5406. shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
  5407. }
  5408. for (uint32_t i = 0; i < (cluster.omni_light_count + cluster.spot_light_count); i++) {
  5409. uint32_t index = (i < cluster.omni_light_count) ? i : i - (cluster.omni_light_count);
  5410. Cluster::LightData &light_data = (i < cluster.omni_light_count) ? cluster.omni_lights[index] : cluster.spot_lights[index];
  5411. RS::LightType type = (i < cluster.omni_light_count) ? RS::LIGHT_OMNI : RS::LIGHT_SPOT;
  5412. LightInstance *li = (i < cluster.omni_light_count) ? cluster.omni_light_sort[index].instance : cluster.spot_light_sort[index].instance;
  5413. RID base = li->light;
  5414. cluster.lights_instances[i] = li->self;
  5415. Transform light_transform = li->transform;
  5416. float sign = storage->light_is_negative(base) ? -1 : 1;
  5417. Color linear_col = storage->light_get_color(base).to_linear();
  5418. light_data.attenuation = storage->light_get_param(base, RS::LIGHT_PARAM_ATTENUATION);
  5419. float energy = sign * storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY) * Math_PI;
  5420. light_data.color[0] = linear_col.r * energy;
  5421. light_data.color[1] = linear_col.g * energy;
  5422. light_data.color[2] = linear_col.b * energy;
  5423. light_data.specular_amount = storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR) * 2.0;
  5424. float radius = MAX(0.001, storage->light_get_param(base, RS::LIGHT_PARAM_RANGE));
  5425. light_data.inv_radius = 1.0 / radius;
  5426. Vector3 pos = inverse_transform.xform(light_transform.origin);
  5427. light_data.position[0] = pos.x;
  5428. light_data.position[1] = pos.y;
  5429. light_data.position[2] = pos.z;
  5430. Vector3 direction = inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, -1))).normalized();
  5431. light_data.direction[0] = direction.x;
  5432. light_data.direction[1] = direction.y;
  5433. light_data.direction[2] = direction.z;
  5434. float size = storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  5435. light_data.size = size;
  5436. light_data.cone_attenuation = storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  5437. float spot_angle = storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ANGLE);
  5438. light_data.cone_angle = Math::cos(Math::deg2rad(spot_angle));
  5439. light_data.mask = storage->light_get_cull_mask(base);
  5440. light_data.atlas_rect[0] = 0;
  5441. light_data.atlas_rect[1] = 0;
  5442. light_data.atlas_rect[2] = 0;
  5443. light_data.atlas_rect[3] = 0;
  5444. RID projector = storage->light_get_projector(base);
  5445. if (projector.is_valid()) {
  5446. Rect2 rect = storage->decal_atlas_get_texture_rect(projector);
  5447. if (type == RS::LIGHT_SPOT) {
  5448. light_data.projector_rect[0] = rect.position.x;
  5449. light_data.projector_rect[1] = rect.position.y + rect.size.height; //flip because shadow is flipped
  5450. light_data.projector_rect[2] = rect.size.width;
  5451. light_data.projector_rect[3] = -rect.size.height;
  5452. } else {
  5453. light_data.projector_rect[0] = rect.position.x;
  5454. light_data.projector_rect[1] = rect.position.y;
  5455. light_data.projector_rect[2] = rect.size.width;
  5456. light_data.projector_rect[3] = rect.size.height * 0.5; //used by dp, so needs to be half
  5457. }
  5458. } else {
  5459. light_data.projector_rect[0] = 0;
  5460. light_data.projector_rect[1] = 0;
  5461. light_data.projector_rect[2] = 0;
  5462. light_data.projector_rect[3] = 0;
  5463. }
  5464. if (shadow_atlas && shadow_atlas->shadow_owners.has(li->self)) {
  5465. // fill in the shadow information
  5466. light_data.shadow_enabled = true;
  5467. if (type == RS::LIGHT_SPOT) {
  5468. light_data.shadow_bias = (storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) * radius / 10.0);
  5469. float shadow_texel_size = Math::tan(Math::deg2rad(spot_angle)) * radius * 2.0;
  5470. shadow_texel_size *= light_instance_get_shadow_texel_size(li->self, p_shadow_atlas);
  5471. light_data.shadow_normal_bias = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * shadow_texel_size;
  5472. } else { //omni
  5473. light_data.shadow_bias = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) * radius / 10.0;
  5474. float shadow_texel_size = light_instance_get_shadow_texel_size(li->self, p_shadow_atlas);
  5475. light_data.shadow_normal_bias = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * shadow_texel_size * 2.0; // applied in -1 .. 1 space
  5476. }
  5477. light_data.transmittance_bias = storage->light_get_transmittance_bias(base);
  5478. Rect2 rect = light_instance_get_shadow_atlas_rect(li->self, p_shadow_atlas);
  5479. light_data.atlas_rect[0] = rect.position.x;
  5480. light_data.atlas_rect[1] = rect.position.y;
  5481. light_data.atlas_rect[2] = rect.size.width;
  5482. light_data.atlas_rect[3] = rect.size.height;
  5483. light_data.soft_shadow_scale = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BLUR);
  5484. light_data.shadow_volumetric_fog_fade = 1.0 / storage->light_get_shadow_volumetric_fog_fade(base);
  5485. if (type == RS::LIGHT_OMNI) {
  5486. light_data.atlas_rect[3] *= 0.5; //one paraboloid on top of another
  5487. Transform proj = (inverse_transform * light_transform).inverse();
  5488. RendererStorageRD::store_transform(proj, light_data.shadow_matrix);
  5489. if (size > 0.0) {
  5490. light_data.soft_shadow_size = size;
  5491. } else {
  5492. light_data.soft_shadow_size = 0.0;
  5493. light_data.soft_shadow_scale *= shadows_quality_radius_get(); // Only use quality radius for PCF
  5494. }
  5495. } else if (type == RS::LIGHT_SPOT) {
  5496. Transform modelview = (inverse_transform * light_transform).inverse();
  5497. CameraMatrix bias;
  5498. bias.set_light_bias();
  5499. CameraMatrix shadow_mtx = bias * li->shadow_transform[0].camera * modelview;
  5500. RendererStorageRD::store_camera(shadow_mtx, light_data.shadow_matrix);
  5501. if (size > 0.0) {
  5502. CameraMatrix cm = li->shadow_transform[0].camera;
  5503. float half_np = cm.get_z_near() * Math::tan(Math::deg2rad(spot_angle));
  5504. light_data.soft_shadow_size = (size * 0.5 / radius) / (half_np / cm.get_z_near()) * rect.size.width;
  5505. } else {
  5506. light_data.soft_shadow_size = 0.0;
  5507. light_data.soft_shadow_scale *= shadows_quality_radius_get(); // Only use quality radius for PCF
  5508. }
  5509. }
  5510. } else {
  5511. light_data.shadow_enabled = false;
  5512. }
  5513. li->light_index = index;
  5514. current_cluster_builder->add_light(type == RS::LIGHT_SPOT ? ClusterBuilderRD::LIGHT_TYPE_SPOT : ClusterBuilderRD::LIGHT_TYPE_OMNI, light_transform, radius, spot_angle);
  5515. r_positional_light_count++;
  5516. }
  5517. //update without barriers
  5518. if (cluster.omni_light_count) {
  5519. RD::get_singleton()->buffer_update(cluster.omni_light_buffer, 0, sizeof(Cluster::LightData) * cluster.omni_light_count, cluster.omni_lights, RD::BARRIER_MASK_RASTER | RD::BARRIER_MASK_COMPUTE);
  5520. }
  5521. if (cluster.spot_light_count) {
  5522. RD::get_singleton()->buffer_update(cluster.spot_light_buffer, 0, sizeof(Cluster::LightData) * cluster.spot_light_count, cluster.spot_lights, RD::BARRIER_MASK_RASTER | RD::BARRIER_MASK_COMPUTE);
  5523. }
  5524. if (r_directional_light_count) {
  5525. RD::get_singleton()->buffer_update(cluster.directional_light_buffer, 0, sizeof(Cluster::DirectionalLightData) * r_directional_light_count, cluster.directional_lights, RD::BARRIER_MASK_RASTER | RD::BARRIER_MASK_COMPUTE);
  5526. }
  5527. }
  5528. void RendererSceneRenderRD::_setup_decals(const PagedArray<RID> &p_decals, const Transform &p_camera_inverse_xform) {
  5529. Transform uv_xform;
  5530. uv_xform.basis.scale(Vector3(2.0, 1.0, 2.0));
  5531. uv_xform.origin = Vector3(-1.0, 0.0, -1.0);
  5532. uint32_t decal_count = p_decals.size();
  5533. cluster.decal_count = 0;
  5534. for (uint32_t i = 0; i < decal_count; i++) {
  5535. if (cluster.decal_count == cluster.max_decals) {
  5536. break;
  5537. }
  5538. DecalInstance *di = decal_instance_owner.getornull(p_decals[i]);
  5539. if (!di) {
  5540. continue;
  5541. }
  5542. RID decal = di->decal;
  5543. Transform xform = di->transform;
  5544. real_t distance = -p_camera_inverse_xform.xform(xform.origin).z;
  5545. if (storage->decal_is_distance_fade_enabled(decal)) {
  5546. float fade_begin = storage->decal_get_distance_fade_begin(decal);
  5547. float fade_length = storage->decal_get_distance_fade_length(decal);
  5548. if (distance > fade_begin) {
  5549. if (distance > fade_begin + fade_length) {
  5550. continue; // do not use this decal, its invisible
  5551. }
  5552. }
  5553. }
  5554. cluster.decal_sort[cluster.decal_count].instance = di;
  5555. cluster.decal_sort[cluster.decal_count].depth = distance;
  5556. cluster.decal_count++;
  5557. }
  5558. if (cluster.decal_count > 0) {
  5559. SortArray<Cluster::InstanceSort<DecalInstance>> sort_array;
  5560. sort_array.sort(cluster.decal_sort, cluster.decal_count);
  5561. }
  5562. for (uint32_t i = 0; i < cluster.decal_count; i++) {
  5563. DecalInstance *di = cluster.decal_sort[i].instance;
  5564. RID decal = di->decal;
  5565. Transform xform = di->transform;
  5566. float fade = 1.0;
  5567. if (storage->decal_is_distance_fade_enabled(decal)) {
  5568. real_t distance = -p_camera_inverse_xform.xform(xform.origin).z;
  5569. float fade_begin = storage->decal_get_distance_fade_begin(decal);
  5570. float fade_length = storage->decal_get_distance_fade_length(decal);
  5571. if (distance > fade_begin) {
  5572. fade = 1.0 - (distance - fade_begin) / fade_length;
  5573. }
  5574. }
  5575. Cluster::DecalData &dd = cluster.decals[i];
  5576. Vector3 decal_extents = storage->decal_get_extents(decal);
  5577. Transform scale_xform;
  5578. scale_xform.basis.scale(Vector3(decal_extents.x, decal_extents.y, decal_extents.z));
  5579. Transform to_decal_xform = (p_camera_inverse_xform * di->transform * scale_xform * uv_xform).affine_inverse();
  5580. RendererStorageRD::store_transform(to_decal_xform, dd.xform);
  5581. Vector3 normal = xform.basis.get_axis(Vector3::AXIS_Y).normalized();
  5582. normal = p_camera_inverse_xform.basis.xform(normal); //camera is normalized, so fine
  5583. dd.normal[0] = normal.x;
  5584. dd.normal[1] = normal.y;
  5585. dd.normal[2] = normal.z;
  5586. dd.normal_fade = storage->decal_get_normal_fade(decal);
  5587. RID albedo_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_ALBEDO);
  5588. RID emission_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_EMISSION);
  5589. if (albedo_tex.is_valid()) {
  5590. Rect2 rect = storage->decal_atlas_get_texture_rect(albedo_tex);
  5591. dd.albedo_rect[0] = rect.position.x;
  5592. dd.albedo_rect[1] = rect.position.y;
  5593. dd.albedo_rect[2] = rect.size.x;
  5594. dd.albedo_rect[3] = rect.size.y;
  5595. } else {
  5596. if (!emission_tex.is_valid()) {
  5597. continue; //no albedo, no emission, no decal.
  5598. }
  5599. dd.albedo_rect[0] = 0;
  5600. dd.albedo_rect[1] = 0;
  5601. dd.albedo_rect[2] = 0;
  5602. dd.albedo_rect[3] = 0;
  5603. }
  5604. RID normal_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_NORMAL);
  5605. if (normal_tex.is_valid()) {
  5606. Rect2 rect = storage->decal_atlas_get_texture_rect(normal_tex);
  5607. dd.normal_rect[0] = rect.position.x;
  5608. dd.normal_rect[1] = rect.position.y;
  5609. dd.normal_rect[2] = rect.size.x;
  5610. dd.normal_rect[3] = rect.size.y;
  5611. Basis normal_xform = p_camera_inverse_xform.basis * xform.basis.orthonormalized();
  5612. RendererStorageRD::store_basis_3x4(normal_xform, dd.normal_xform);
  5613. } else {
  5614. dd.normal_rect[0] = 0;
  5615. dd.normal_rect[1] = 0;
  5616. dd.normal_rect[2] = 0;
  5617. dd.normal_rect[3] = 0;
  5618. }
  5619. RID orm_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_ORM);
  5620. if (orm_tex.is_valid()) {
  5621. Rect2 rect = storage->decal_atlas_get_texture_rect(orm_tex);
  5622. dd.orm_rect[0] = rect.position.x;
  5623. dd.orm_rect[1] = rect.position.y;
  5624. dd.orm_rect[2] = rect.size.x;
  5625. dd.orm_rect[3] = rect.size.y;
  5626. } else {
  5627. dd.orm_rect[0] = 0;
  5628. dd.orm_rect[1] = 0;
  5629. dd.orm_rect[2] = 0;
  5630. dd.orm_rect[3] = 0;
  5631. }
  5632. if (emission_tex.is_valid()) {
  5633. Rect2 rect = storage->decal_atlas_get_texture_rect(emission_tex);
  5634. dd.emission_rect[0] = rect.position.x;
  5635. dd.emission_rect[1] = rect.position.y;
  5636. dd.emission_rect[2] = rect.size.x;
  5637. dd.emission_rect[3] = rect.size.y;
  5638. } else {
  5639. dd.emission_rect[0] = 0;
  5640. dd.emission_rect[1] = 0;
  5641. dd.emission_rect[2] = 0;
  5642. dd.emission_rect[3] = 0;
  5643. }
  5644. Color modulate = storage->decal_get_modulate(decal);
  5645. dd.modulate[0] = modulate.r;
  5646. dd.modulate[1] = modulate.g;
  5647. dd.modulate[2] = modulate.b;
  5648. dd.modulate[3] = modulate.a * fade;
  5649. dd.emission_energy = storage->decal_get_emission_energy(decal) * fade;
  5650. dd.albedo_mix = storage->decal_get_albedo_mix(decal);
  5651. dd.mask = storage->decal_get_cull_mask(decal);
  5652. dd.upper_fade = storage->decal_get_upper_fade(decal);
  5653. dd.lower_fade = storage->decal_get_lower_fade(decal);
  5654. current_cluster_builder->add_box(ClusterBuilderRD::BOX_TYPE_DECAL, xform, decal_extents);
  5655. }
  5656. if (cluster.decal_count > 0) {
  5657. RD::get_singleton()->buffer_update(cluster.decal_buffer, 0, sizeof(Cluster::DecalData) * cluster.decal_count, cluster.decals, RD::BARRIER_MASK_RASTER | RD::BARRIER_MASK_COMPUTE);
  5658. }
  5659. }
  5660. void RendererSceneRenderRD::_volumetric_fog_erase(RenderBuffers *rb) {
  5661. ERR_FAIL_COND(!rb->volumetric_fog);
  5662. RD::get_singleton()->free(rb->volumetric_fog->light_density_map);
  5663. RD::get_singleton()->free(rb->volumetric_fog->fog_map);
  5664. if (rb->volumetric_fog->uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set)) {
  5665. RD::get_singleton()->free(rb->volumetric_fog->uniform_set);
  5666. }
  5667. if (rb->volumetric_fog->uniform_set2.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set2)) {
  5668. RD::get_singleton()->free(rb->volumetric_fog->uniform_set2);
  5669. }
  5670. if (rb->volumetric_fog->sdfgi_uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->sdfgi_uniform_set)) {
  5671. RD::get_singleton()->free(rb->volumetric_fog->sdfgi_uniform_set);
  5672. }
  5673. if (rb->volumetric_fog->sky_uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->sky_uniform_set)) {
  5674. RD::get_singleton()->free(rb->volumetric_fog->sky_uniform_set);
  5675. }
  5676. memdelete(rb->volumetric_fog);
  5677. rb->volumetric_fog = nullptr;
  5678. }
  5679. void RendererSceneRenderRD::_allocate_shadow_shrink_stages(RID p_base, int p_base_size, Vector<ShadowShrinkStage> &shrink_stages, uint32_t p_target_size) {
  5680. //create fog mipmaps
  5681. uint32_t fog_texture_size = p_target_size;
  5682. uint32_t base_texture_size = p_base_size;
  5683. ShadowShrinkStage first;
  5684. first.size = base_texture_size;
  5685. first.texture = p_base;
  5686. shrink_stages.push_back(first); //put depth first in case we dont find smaller ones
  5687. while (fog_texture_size < base_texture_size) {
  5688. base_texture_size = MAX(base_texture_size / 8, fog_texture_size);
  5689. ShadowShrinkStage s;
  5690. s.size = base_texture_size;
  5691. RD::TextureFormat tf;
  5692. tf.format = RD::DATA_FORMAT_R16_UNORM;
  5693. tf.width = base_texture_size;
  5694. tf.height = base_texture_size;
  5695. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
  5696. if (base_texture_size == fog_texture_size) {
  5697. s.filter_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5698. tf.usage_bits |= RD::TEXTURE_USAGE_SAMPLING_BIT;
  5699. }
  5700. s.texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5701. shrink_stages.push_back(s);
  5702. }
  5703. }
  5704. void RendererSceneRenderRD::_clear_shadow_shrink_stages(Vector<ShadowShrinkStage> &shrink_stages) {
  5705. for (int i = 1; i < shrink_stages.size(); i++) {
  5706. RD::get_singleton()->free(shrink_stages[i].texture);
  5707. if (shrink_stages[i].filter_texture.is_valid()) {
  5708. RD::get_singleton()->free(shrink_stages[i].filter_texture);
  5709. }
  5710. }
  5711. shrink_stages.clear();
  5712. }
  5713. void RendererSceneRenderRD::_update_volumetric_fog(RID p_render_buffers, RID p_environment, const CameraMatrix &p_cam_projection, const Transform &p_cam_transform, RID p_shadow_atlas, int p_directional_light_count, bool p_use_directional_shadows, int p_positional_light_count, int p_gi_probe_count) {
  5714. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  5715. ERR_FAIL_COND(!rb);
  5716. Environment *env = environment_owner.getornull(p_environment);
  5717. float ratio = float(rb->width) / float((rb->width + rb->height) / 2);
  5718. uint32_t target_width = uint32_t(float(volumetric_fog_size) * ratio);
  5719. uint32_t target_height = uint32_t(float(volumetric_fog_size) / ratio);
  5720. if (rb->volumetric_fog) {
  5721. //validate
  5722. if (!env || !env->volumetric_fog_enabled || rb->volumetric_fog->width != target_width || rb->volumetric_fog->height != target_height || rb->volumetric_fog->depth != volumetric_fog_depth) {
  5723. _volumetric_fog_erase(rb);
  5724. _render_buffers_uniform_set_changed(p_render_buffers);
  5725. }
  5726. }
  5727. if (!env || !env->volumetric_fog_enabled) {
  5728. //no reason to enable or update, bye
  5729. return;
  5730. }
  5731. RENDER_TIMESTAMP(">Volumetric Fog");
  5732. if (env && env->volumetric_fog_enabled && !rb->volumetric_fog) {
  5733. //required volumetric fog but not existing, create
  5734. rb->volumetric_fog = memnew(VolumetricFog);
  5735. rb->volumetric_fog->width = target_width;
  5736. rb->volumetric_fog->height = target_height;
  5737. rb->volumetric_fog->depth = volumetric_fog_depth;
  5738. RD::TextureFormat tf;
  5739. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  5740. tf.width = target_width;
  5741. tf.height = target_height;
  5742. tf.depth = volumetric_fog_depth;
  5743. tf.texture_type = RD::TEXTURE_TYPE_3D;
  5744. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
  5745. rb->volumetric_fog->light_density_map = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5746. tf.usage_bits |= RD::TEXTURE_USAGE_SAMPLING_BIT;
  5747. rb->volumetric_fog->fog_map = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5748. _render_buffers_uniform_set_changed(p_render_buffers);
  5749. Vector<RD::Uniform> uniforms;
  5750. {
  5751. RD::Uniform u;
  5752. u.binding = 0;
  5753. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  5754. u.ids.push_back(rb->volumetric_fog->fog_map);
  5755. uniforms.push_back(u);
  5756. }
  5757. rb->volumetric_fog->sky_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_FOG);
  5758. }
  5759. //update directional shadow
  5760. RENDER_TIMESTAMP("Downsample Shadows");
  5761. if (p_use_directional_shadows) {
  5762. RD::get_singleton()->draw_command_begin_label("Downsample Directional Shadows");
  5763. if (directional_shadow.shrink_stages.is_empty()) {
  5764. if (rb->volumetric_fog->uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set)) {
  5765. //invalidate uniform set, we will need a new one
  5766. RD::get_singleton()->free(rb->volumetric_fog->uniform_set);
  5767. rb->volumetric_fog->uniform_set = RID();
  5768. }
  5769. _allocate_shadow_shrink_stages(directional_shadow.depth, directional_shadow.size, directional_shadow.shrink_stages, volumetric_fog_directional_shadow_shrink);
  5770. }
  5771. if (directional_shadow.shrink_stages.size() > 1) {
  5772. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  5773. for (int i = 1; i < directional_shadow.shrink_stages.size(); i++) {
  5774. int32_t src_size = directional_shadow.shrink_stages[i - 1].size;
  5775. int32_t dst_size = directional_shadow.shrink_stages[i].size;
  5776. Rect2i r(0, 0, src_size, src_size);
  5777. int32_t shrink_limit = 8 / (src_size / dst_size);
  5778. storage->get_effects()->reduce_shadow(directional_shadow.shrink_stages[i - 1].texture, directional_shadow.shrink_stages[i].texture, Size2i(src_size, src_size), r, shrink_limit, compute_list);
  5779. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5780. if (env->volumetric_fog_shadow_filter != RS::ENV_VOLUMETRIC_FOG_SHADOW_FILTER_DISABLED && directional_shadow.shrink_stages[i].filter_texture.is_valid()) {
  5781. Rect2i rf(0, 0, dst_size, dst_size);
  5782. storage->get_effects()->filter_shadow(directional_shadow.shrink_stages[i].texture, directional_shadow.shrink_stages[i].filter_texture, Size2i(dst_size, dst_size), rf, env->volumetric_fog_shadow_filter, compute_list);
  5783. }
  5784. }
  5785. RD::get_singleton()->compute_list_end();
  5786. }
  5787. RD::get_singleton()->draw_command_end_label();
  5788. }
  5789. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
  5790. if (shadow_atlas) {
  5791. //shrink shadows that need to be shrunk
  5792. RD::get_singleton()->draw_command_begin_label("Downsample Positional Shadows");
  5793. bool force_shrink_shadows = false;
  5794. if (shadow_atlas->shrink_stages.is_empty()) {
  5795. if (rb->volumetric_fog->uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set)) {
  5796. //invalidate uniform set, we will need a new one
  5797. RD::get_singleton()->free(rb->volumetric_fog->uniform_set);
  5798. rb->volumetric_fog->uniform_set = RID();
  5799. }
  5800. _allocate_shadow_shrink_stages(shadow_atlas->depth, shadow_atlas->size, shadow_atlas->shrink_stages, volumetric_fog_positional_shadow_shrink);
  5801. force_shrink_shadows = true;
  5802. }
  5803. if (rb->volumetric_fog->last_shadow_filter != env->volumetric_fog_shadow_filter) {
  5804. //if shadow filter changed, invalidate caches
  5805. rb->volumetric_fog->last_shadow_filter = env->volumetric_fog_shadow_filter;
  5806. force_shrink_shadows = true;
  5807. }
  5808. cluster.lights_shadow_rect_cache_count = 0;
  5809. for (uint32_t i = 0; i < cluster.omni_light_count + cluster.spot_light_count; i++) {
  5810. Cluster::LightData &ld = i < cluster.omni_light_count ? cluster.omni_lights[i] : cluster.spot_lights[i - cluster.omni_light_count];
  5811. if (ld.shadow_enabled != 0) {
  5812. RID li = cluster.lights_instances[i];
  5813. ERR_CONTINUE(!shadow_atlas->shadow_owners.has(li));
  5814. uint32_t key = shadow_atlas->shadow_owners[li];
  5815. uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  5816. uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK;
  5817. ERR_CONTINUE((int)shadow >= shadow_atlas->quadrants[quadrant].shadows.size());
  5818. ShadowAtlas::Quadrant::Shadow &s = shadow_atlas->quadrants[quadrant].shadows.write[shadow];
  5819. if (!force_shrink_shadows && s.fog_version == s.version) {
  5820. continue; //do not update, no need
  5821. }
  5822. s.fog_version = s.version;
  5823. uint32_t quadrant_size = shadow_atlas->size >> 1;
  5824. Rect2i atlas_rect;
  5825. atlas_rect.position.x = (quadrant & 1) * quadrant_size;
  5826. atlas_rect.position.y = (quadrant >> 1) * quadrant_size;
  5827. uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision);
  5828. atlas_rect.position.x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  5829. atlas_rect.position.y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  5830. atlas_rect.size.x = shadow_size;
  5831. atlas_rect.size.y = shadow_size;
  5832. cluster.lights_shadow_rect_cache[cluster.lights_shadow_rect_cache_count] = atlas_rect;
  5833. cluster.lights_shadow_rect_cache_count++;
  5834. if (cluster.lights_shadow_rect_cache_count == cluster.max_lights * 2) {
  5835. break; //light limit reached
  5836. }
  5837. }
  5838. }
  5839. if (cluster.lights_shadow_rect_cache_count > 0) {
  5840. //there are shadows to be shrunk, try to do them in parallel
  5841. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  5842. for (int i = 1; i < shadow_atlas->shrink_stages.size(); i++) {
  5843. int32_t base_size = shadow_atlas->shrink_stages[0].size;
  5844. int32_t src_size = shadow_atlas->shrink_stages[i - 1].size;
  5845. int32_t dst_size = shadow_atlas->shrink_stages[i].size;
  5846. uint32_t rect_divisor = base_size / src_size;
  5847. int32_t shrink_limit = 8 / (src_size / dst_size);
  5848. //shrink in parallel for more performance
  5849. for (uint32_t j = 0; j < cluster.lights_shadow_rect_cache_count; j++) {
  5850. Rect2i src_rect = cluster.lights_shadow_rect_cache[j];
  5851. src_rect.position /= rect_divisor;
  5852. src_rect.size /= rect_divisor;
  5853. storage->get_effects()->reduce_shadow(shadow_atlas->shrink_stages[i - 1].texture, shadow_atlas->shrink_stages[i].texture, Size2i(src_size, src_size), src_rect, shrink_limit, compute_list);
  5854. }
  5855. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5856. if (env->volumetric_fog_shadow_filter != RS::ENV_VOLUMETRIC_FOG_SHADOW_FILTER_DISABLED && shadow_atlas->shrink_stages[i].filter_texture.is_valid()) {
  5857. uint32_t filter_divisor = base_size / dst_size;
  5858. //filter in parallel for more performance
  5859. for (uint32_t j = 0; j < cluster.lights_shadow_rect_cache_count; j++) {
  5860. Rect2i dst_rect = cluster.lights_shadow_rect_cache[j];
  5861. dst_rect.position /= filter_divisor;
  5862. dst_rect.size /= filter_divisor;
  5863. storage->get_effects()->filter_shadow(shadow_atlas->shrink_stages[i].texture, shadow_atlas->shrink_stages[i].filter_texture, Size2i(dst_size, dst_size), dst_rect, env->volumetric_fog_shadow_filter, compute_list, true, false);
  5864. }
  5865. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5866. for (uint32_t j = 0; j < cluster.lights_shadow_rect_cache_count; j++) {
  5867. Rect2i dst_rect = cluster.lights_shadow_rect_cache[j];
  5868. dst_rect.position /= filter_divisor;
  5869. dst_rect.size /= filter_divisor;
  5870. storage->get_effects()->filter_shadow(shadow_atlas->shrink_stages[i].texture, shadow_atlas->shrink_stages[i].filter_texture, Size2i(dst_size, dst_size), dst_rect, env->volumetric_fog_shadow_filter, compute_list, false, true);
  5871. }
  5872. }
  5873. }
  5874. RD::get_singleton()->compute_list_end(RD::BARRIER_MASK_COMPUTE);
  5875. }
  5876. RD::get_singleton()->draw_command_end_label();
  5877. }
  5878. //update volumetric fog
  5879. if (rb->volumetric_fog->uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set)) {
  5880. //re create uniform set if needed
  5881. Vector<RD::Uniform> uniforms;
  5882. {
  5883. RD::Uniform u;
  5884. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  5885. u.binding = 1;
  5886. if (shadow_atlas == nullptr || shadow_atlas->shrink_stages.size() == 0) {
  5887. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_BLACK));
  5888. } else {
  5889. u.ids.push_back(shadow_atlas->shrink_stages[shadow_atlas->shrink_stages.size() - 1].texture);
  5890. }
  5891. uniforms.push_back(u);
  5892. }
  5893. {
  5894. RD::Uniform u;
  5895. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  5896. u.binding = 2;
  5897. if (directional_shadow.shrink_stages.size() == 0) {
  5898. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_BLACK));
  5899. } else {
  5900. u.ids.push_back(directional_shadow.shrink_stages[directional_shadow.shrink_stages.size() - 1].texture);
  5901. }
  5902. uniforms.push_back(u);
  5903. }
  5904. {
  5905. RD::Uniform u;
  5906. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  5907. u.binding = 3;
  5908. u.ids.push_back(get_omni_light_buffer());
  5909. uniforms.push_back(u);
  5910. }
  5911. {
  5912. RD::Uniform u;
  5913. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  5914. u.binding = 4;
  5915. u.ids.push_back(get_spot_light_buffer());
  5916. uniforms.push_back(u);
  5917. }
  5918. {
  5919. RD::Uniform u;
  5920. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  5921. u.binding = 5;
  5922. u.ids.push_back(get_directional_light_buffer());
  5923. uniforms.push_back(u);
  5924. }
  5925. {
  5926. RD::Uniform u;
  5927. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  5928. u.binding = 6;
  5929. u.ids.push_back(rb->cluster_builder->get_cluster_buffer());
  5930. uniforms.push_back(u);
  5931. }
  5932. {
  5933. RD::Uniform u;
  5934. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  5935. u.binding = 7;
  5936. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  5937. uniforms.push_back(u);
  5938. }
  5939. {
  5940. RD::Uniform u;
  5941. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  5942. u.binding = 8;
  5943. u.ids.push_back(rb->volumetric_fog->light_density_map);
  5944. uniforms.push_back(u);
  5945. }
  5946. {
  5947. RD::Uniform u;
  5948. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  5949. u.binding = 9;
  5950. u.ids.push_back(rb->volumetric_fog->fog_map);
  5951. uniforms.push_back(u);
  5952. }
  5953. {
  5954. RD::Uniform u;
  5955. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  5956. u.binding = 10;
  5957. u.ids.push_back(shadow_sampler);
  5958. uniforms.push_back(u);
  5959. }
  5960. {
  5961. RD::Uniform u;
  5962. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  5963. u.binding = 11;
  5964. u.ids.push_back(render_buffers_get_gi_probe_buffer(p_render_buffers));
  5965. uniforms.push_back(u);
  5966. }
  5967. {
  5968. RD::Uniform u;
  5969. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  5970. u.binding = 12;
  5971. for (int i = 0; i < RenderBuffers::MAX_GIPROBES; i++) {
  5972. u.ids.push_back(rb->giprobe_textures[i]);
  5973. }
  5974. uniforms.push_back(u);
  5975. }
  5976. {
  5977. RD::Uniform u;
  5978. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  5979. u.binding = 13;
  5980. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  5981. uniforms.push_back(u);
  5982. }
  5983. {
  5984. RD::Uniform u;
  5985. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  5986. u.binding = 14;
  5987. u.ids.push_back(volumetric_fog.params_ubo);
  5988. uniforms.push_back(u);
  5989. }
  5990. rb->volumetric_fog->uniform_set = RD::get_singleton()->uniform_set_create(uniforms, volumetric_fog.shader.version_get_shader(volumetric_fog.shader_version, 0), 0);
  5991. SWAP(uniforms.write[7].ids.write[0], uniforms.write[8].ids.write[0]);
  5992. rb->volumetric_fog->uniform_set2 = RD::get_singleton()->uniform_set_create(uniforms, volumetric_fog.shader.version_get_shader(volumetric_fog.shader_version, 0), 0);
  5993. }
  5994. bool using_sdfgi = env->volumetric_fog_gi_inject > 0.0001 && env->sdfgi_enabled && (rb->sdfgi != nullptr);
  5995. if (using_sdfgi) {
  5996. if (rb->volumetric_fog->sdfgi_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->sdfgi_uniform_set)) {
  5997. Vector<RD::Uniform> uniforms;
  5998. {
  5999. RD::Uniform u;
  6000. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  6001. u.binding = 0;
  6002. u.ids.push_back(gi.sdfgi_ubo);
  6003. uniforms.push_back(u);
  6004. }
  6005. {
  6006. RD::Uniform u;
  6007. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  6008. u.binding = 1;
  6009. u.ids.push_back(rb->sdfgi->ambient_texture);
  6010. uniforms.push_back(u);
  6011. }
  6012. {
  6013. RD::Uniform u;
  6014. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  6015. u.binding = 2;
  6016. u.ids.push_back(rb->sdfgi->occlusion_texture);
  6017. uniforms.push_back(u);
  6018. }
  6019. rb->volumetric_fog->sdfgi_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, volumetric_fog.shader.version_get_shader(volumetric_fog.shader_version, VOLUMETRIC_FOG_SHADER_DENSITY_WITH_SDFGI), 1);
  6020. }
  6021. }
  6022. rb->volumetric_fog->length = env->volumetric_fog_length;
  6023. rb->volumetric_fog->spread = env->volumetric_fog_detail_spread;
  6024. VolumetricFogShader::ParamsUBO params;
  6025. Vector2 frustum_near_size = p_cam_projection.get_viewport_half_extents();
  6026. Vector2 frustum_far_size = p_cam_projection.get_far_plane_half_extents();
  6027. float z_near = p_cam_projection.get_z_near();
  6028. float z_far = p_cam_projection.get_z_far();
  6029. float fog_end = env->volumetric_fog_length;
  6030. Vector2 fog_far_size = frustum_near_size.lerp(frustum_far_size, (fog_end - z_near) / (z_far - z_near));
  6031. Vector2 fog_near_size;
  6032. if (p_cam_projection.is_orthogonal()) {
  6033. fog_near_size = fog_far_size;
  6034. } else {
  6035. fog_near_size = Vector2();
  6036. }
  6037. params.fog_frustum_size_begin[0] = fog_near_size.x;
  6038. params.fog_frustum_size_begin[1] = fog_near_size.y;
  6039. params.fog_frustum_size_end[0] = fog_far_size.x;
  6040. params.fog_frustum_size_end[1] = fog_far_size.y;
  6041. params.z_near = z_near;
  6042. params.z_far = z_far;
  6043. params.fog_frustum_end = fog_end;
  6044. params.fog_volume_size[0] = rb->volumetric_fog->width;
  6045. params.fog_volume_size[1] = rb->volumetric_fog->height;
  6046. params.fog_volume_size[2] = rb->volumetric_fog->depth;
  6047. params.directional_light_count = p_directional_light_count;
  6048. Color light = env->volumetric_fog_light.to_linear();
  6049. params.light_energy[0] = light.r * env->volumetric_fog_light_energy;
  6050. params.light_energy[1] = light.g * env->volumetric_fog_light_energy;
  6051. params.light_energy[2] = light.b * env->volumetric_fog_light_energy;
  6052. params.base_density = env->volumetric_fog_density;
  6053. params.detail_spread = env->volumetric_fog_detail_spread;
  6054. params.gi_inject = env->volumetric_fog_gi_inject;
  6055. params.cam_rotation[0] = p_cam_transform.basis[0][0];
  6056. params.cam_rotation[1] = p_cam_transform.basis[1][0];
  6057. params.cam_rotation[2] = p_cam_transform.basis[2][0];
  6058. params.cam_rotation[3] = 0;
  6059. params.cam_rotation[4] = p_cam_transform.basis[0][1];
  6060. params.cam_rotation[5] = p_cam_transform.basis[1][1];
  6061. params.cam_rotation[6] = p_cam_transform.basis[2][1];
  6062. params.cam_rotation[7] = 0;
  6063. params.cam_rotation[8] = p_cam_transform.basis[0][2];
  6064. params.cam_rotation[9] = p_cam_transform.basis[1][2];
  6065. params.cam_rotation[10] = p_cam_transform.basis[2][2];
  6066. params.cam_rotation[11] = 0;
  6067. params.filter_axis = 0;
  6068. params.max_gi_probes = env->volumetric_fog_gi_inject > 0.001 ? p_gi_probe_count : 0;
  6069. {
  6070. uint32_t cluster_size = rb->cluster_builder->get_cluster_size();
  6071. params.cluster_shift = get_shift_from_power_of_2(cluster_size);
  6072. uint32_t cluster_screen_width = (rb->width - 1) / cluster_size + 1;
  6073. uint32_t cluster_screen_height = (rb->height - 1) / cluster_size + 1;
  6074. params.cluster_type_size = cluster_screen_width * cluster_screen_height * (32 + 32);
  6075. params.cluster_width = cluster_screen_width;
  6076. params.max_cluster_element_count_div_32 = max_cluster_elements / 32;
  6077. params.screen_size[0] = rb->width;
  6078. params.screen_size[1] = rb->height;
  6079. }
  6080. /* Vector2 dssize = directional_shadow_get_size();
  6081. push_constant.directional_shadow_pixel_size[0] = 1.0 / dssize.x;
  6082. push_constant.directional_shadow_pixel_size[1] = 1.0 / dssize.y;
  6083. */
  6084. RD::get_singleton()->draw_command_begin_label("Render Volumetric Fog");
  6085. RENDER_TIMESTAMP("Render Fog");
  6086. RD::get_singleton()->buffer_update(volumetric_fog.params_ubo, 0, sizeof(VolumetricFogShader::ParamsUBO), &params, RD::BARRIER_MASK_COMPUTE);
  6087. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  6088. bool use_filter = volumetric_fog_filter_active;
  6089. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, volumetric_fog.pipelines[using_sdfgi ? VOLUMETRIC_FOG_SHADER_DENSITY_WITH_SDFGI : VOLUMETRIC_FOG_SHADER_DENSITY]);
  6090. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->volumetric_fog->uniform_set, 0);
  6091. if (using_sdfgi) {
  6092. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->volumetric_fog->sdfgi_uniform_set, 1);
  6093. }
  6094. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->volumetric_fog->width, rb->volumetric_fog->height, rb->volumetric_fog->depth);
  6095. RD::get_singleton()->draw_command_end_label();
  6096. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6097. if (use_filter) {
  6098. RD::get_singleton()->draw_command_begin_label("Filter Fog");
  6099. RENDER_TIMESTAMP("Filter Fog");
  6100. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, volumetric_fog.pipelines[VOLUMETRIC_FOG_SHADER_FILTER]);
  6101. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->volumetric_fog->uniform_set, 0);
  6102. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->volumetric_fog->width, rb->volumetric_fog->height, rb->volumetric_fog->depth);
  6103. RD::get_singleton()->compute_list_end();
  6104. //need restart for buffer update
  6105. params.filter_axis = 1;
  6106. RD::get_singleton()->buffer_update(volumetric_fog.params_ubo, 0, sizeof(VolumetricFogShader::ParamsUBO), &params);
  6107. compute_list = RD::get_singleton()->compute_list_begin();
  6108. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, volumetric_fog.pipelines[VOLUMETRIC_FOG_SHADER_FILTER]);
  6109. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->volumetric_fog->uniform_set2, 0);
  6110. if (using_sdfgi) {
  6111. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->volumetric_fog->sdfgi_uniform_set, 1);
  6112. }
  6113. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->volumetric_fog->width, rb->volumetric_fog->height, rb->volumetric_fog->depth);
  6114. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6115. RD::get_singleton()->draw_command_end_label();
  6116. }
  6117. RENDER_TIMESTAMP("Integrate Fog");
  6118. RD::get_singleton()->draw_command_begin_label("Integrate Fog");
  6119. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, volumetric_fog.pipelines[VOLUMETRIC_FOG_SHADER_FOG]);
  6120. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->volumetric_fog->uniform_set, 0);
  6121. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->volumetric_fog->width, rb->volumetric_fog->height, 1);
  6122. RD::get_singleton()->compute_list_end(RD::BARRIER_MASK_RASTER);
  6123. RENDER_TIMESTAMP("<Volumetric Fog");
  6124. RD::get_singleton()->draw_command_end_label();
  6125. }
  6126. uint32_t RendererSceneRenderRD::_get_render_state_directional_light_count() const {
  6127. return render_state.directional_light_count;
  6128. }
  6129. bool RendererSceneRenderRD::_needs_post_prepass_render(bool p_use_gi) {
  6130. if (render_state.render_buffers.is_valid()) {
  6131. RenderBuffers *rb = render_buffers_owner.getornull(render_state.render_buffers);
  6132. if (rb->sdfgi != nullptr) {
  6133. return true;
  6134. }
  6135. }
  6136. return false;
  6137. }
  6138. void RendererSceneRenderRD::_post_prepass_render(bool p_use_gi) {
  6139. if (render_state.render_buffers.is_valid()) {
  6140. if (p_use_gi) {
  6141. _sdfgi_update_probes(render_state.render_buffers, render_state.environment);
  6142. }
  6143. }
  6144. }
  6145. void RendererSceneRenderRD::_pre_resolve_render(bool p_use_gi) {
  6146. if (render_state.render_buffers.is_valid()) {
  6147. if (p_use_gi) {
  6148. RD::get_singleton()->compute_list_end();
  6149. }
  6150. }
  6151. }
  6152. void RendererSceneRenderRD::_pre_opaque_render(bool p_use_ssao, bool p_use_gi, RID p_normal_roughness_buffer, RID p_gi_probe_buffer) {
  6153. // Render shadows while GI is rendering, due to how barriers are handled, this should happen at the same time
  6154. if (render_state.render_buffers.is_valid() && p_use_gi) {
  6155. _sdfgi_store_probes(render_state.render_buffers);
  6156. }
  6157. render_state.cube_shadows.clear();
  6158. render_state.shadows.clear();
  6159. render_state.directional_shadows.clear();
  6160. Plane camera_plane(render_state.cam_transform.origin, -render_state.cam_transform.basis.get_axis(Vector3::AXIS_Z));
  6161. float lod_distance_multiplier = render_state.cam_projection.get_lod_multiplier();
  6162. {
  6163. for (int i = 0; i < render_state.render_shadow_count; i++) {
  6164. LightInstance *li = light_instance_owner.getornull(render_state.render_shadows[i].light);
  6165. if (storage->light_get_type(li->light) == RS::LIGHT_DIRECTIONAL) {
  6166. render_state.directional_shadows.push_back(i);
  6167. } else if (storage->light_get_type(li->light) == RS::LIGHT_OMNI && storage->light_omni_get_shadow_mode(li->light) == RS::LIGHT_OMNI_SHADOW_CUBE) {
  6168. render_state.cube_shadows.push_back(i);
  6169. } else {
  6170. render_state.shadows.push_back(i);
  6171. }
  6172. }
  6173. //cube shadows are rendered in their own way
  6174. for (uint32_t i = 0; i < render_state.cube_shadows.size(); i++) {
  6175. _render_shadow_pass(render_state.render_shadows[render_state.cube_shadows[i]].light, render_state.shadow_atlas, render_state.render_shadows[render_state.cube_shadows[i]].pass, render_state.render_shadows[render_state.cube_shadows[i]].instances, camera_plane, lod_distance_multiplier, render_state.screen_lod_threshold, true, true, true);
  6176. }
  6177. if (render_state.directional_shadows.size()) {
  6178. //open the pass for directional shadows
  6179. _update_directional_shadow_atlas();
  6180. RD::get_singleton()->draw_list_begin(directional_shadow.fb, RD::INITIAL_ACTION_DROP, RD::FINAL_ACTION_DISCARD, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_CONTINUE);
  6181. RD::get_singleton()->draw_list_end();
  6182. }
  6183. }
  6184. // Render GI
  6185. bool render_shadows = render_state.directional_shadows.size() || render_state.shadows.size();
  6186. bool render_gi = render_state.render_buffers.is_valid() && p_use_gi;
  6187. if (render_shadows && render_gi) {
  6188. RENDER_TIMESTAMP("Render GI + Render Shadows (parallel)");
  6189. } else if (render_shadows) {
  6190. RENDER_TIMESTAMP("Render Shadows");
  6191. } else if (render_gi) {
  6192. RENDER_TIMESTAMP("Render GI");
  6193. }
  6194. //prepare shadow rendering
  6195. if (render_shadows) {
  6196. _render_shadow_begin();
  6197. //render directional shadows
  6198. for (uint32_t i = 0; i < render_state.directional_shadows.size(); i++) {
  6199. _render_shadow_pass(render_state.render_shadows[render_state.directional_shadows[i]].light, render_state.shadow_atlas, render_state.render_shadows[render_state.directional_shadows[i]].pass, render_state.render_shadows[render_state.directional_shadows[i]].instances, camera_plane, lod_distance_multiplier, render_state.screen_lod_threshold, false, i == render_state.directional_shadows.size() - 1, false);
  6200. }
  6201. //render positional shadows
  6202. for (uint32_t i = 0; i < render_state.shadows.size(); i++) {
  6203. _render_shadow_pass(render_state.render_shadows[render_state.shadows[i]].light, render_state.shadow_atlas, render_state.render_shadows[render_state.shadows[i]].pass, render_state.render_shadows[render_state.shadows[i]].instances, camera_plane, lod_distance_multiplier, render_state.screen_lod_threshold, i == 0, i == render_state.shadows.size() - 1, true);
  6204. }
  6205. _render_shadow_process();
  6206. }
  6207. //start GI
  6208. if (render_gi) {
  6209. _process_gi(render_state.render_buffers, p_normal_roughness_buffer, p_gi_probe_buffer, render_state.environment, render_state.cam_projection, render_state.cam_transform, *render_state.gi_probes);
  6210. }
  6211. //Do shadow rendering (in parallel with GI)
  6212. if (render_shadows) {
  6213. _render_shadow_end(RD::BARRIER_MASK_NO_BARRIER);
  6214. }
  6215. if (render_gi) {
  6216. RD::get_singleton()->compute_list_end(RD::BARRIER_MASK_NO_BARRIER); //use a later barrier
  6217. }
  6218. if (render_state.render_buffers.is_valid()) {
  6219. if (p_use_ssao) {
  6220. _process_ssao(render_state.render_buffers, render_state.environment, p_normal_roughness_buffer, render_state.cam_projection);
  6221. }
  6222. }
  6223. //full barrier here, we need raster, transfer and compute and it depends from the previous work
  6224. RD::get_singleton()->barrier(RD::BARRIER_MASK_ALL, RD::BARRIER_MASK_ALL);
  6225. if (current_cluster_builder) {
  6226. current_cluster_builder->begin(render_state.cam_transform, render_state.cam_projection, !render_state.reflection_probe.is_valid());
  6227. }
  6228. bool using_shadows = true;
  6229. if (render_state.reflection_probe.is_valid()) {
  6230. if (!storage->reflection_probe_renders_shadows(reflection_probe_instance_get_probe(render_state.reflection_probe))) {
  6231. using_shadows = false;
  6232. }
  6233. } else {
  6234. //do not render reflections when rendering a reflection probe
  6235. _setup_reflections(*render_state.reflection_probes, render_state.cam_transform.affine_inverse(), render_state.environment);
  6236. }
  6237. uint32_t directional_light_count = 0;
  6238. uint32_t positional_light_count = 0;
  6239. _setup_lights(*render_state.lights, render_state.cam_transform, render_state.shadow_atlas, using_shadows, directional_light_count, positional_light_count);
  6240. _setup_decals(*render_state.decals, render_state.cam_transform.affine_inverse());
  6241. render_state.directional_light_count = directional_light_count;
  6242. if (current_cluster_builder) {
  6243. current_cluster_builder->bake_cluster();
  6244. }
  6245. if (render_state.render_buffers.is_valid()) {
  6246. bool directional_shadows = false;
  6247. for (uint32_t i = 0; i < directional_light_count; i++) {
  6248. if (cluster.directional_lights[i].shadow_enabled) {
  6249. directional_shadows = true;
  6250. break;
  6251. }
  6252. }
  6253. _update_volumetric_fog(render_state.render_buffers, render_state.environment, render_state.cam_projection, render_state.cam_transform, render_state.shadow_atlas, directional_light_count, directional_shadows, positional_light_count, render_state.gi_probe_count);
  6254. }
  6255. }
  6256. void RendererSceneRenderRD::render_scene(RID p_render_buffers, const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, const PagedArray<RID> &p_lights, const PagedArray<RID> &p_reflection_probes, const PagedArray<RID> &p_gi_probes, const PagedArray<RID> &p_decals, const PagedArray<RID> &p_lightmaps, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_lod_threshold, const RenderShadowData *p_render_shadows, int p_render_shadow_count, const RenderSDFGIData *p_render_sdfgi_regions, int p_render_sdfgi_region_count, const RenderSDFGIUpdateData *p_sdfgi_update_data) {
  6257. //assign render data
  6258. {
  6259. render_state.render_buffers = p_render_buffers;
  6260. render_state.cam_transform = p_cam_transform;
  6261. render_state.cam_projection = p_cam_projection;
  6262. render_state.cam_ortogonal = p_cam_projection.is_orthogonal();
  6263. render_state.instances = &p_instances;
  6264. render_state.lights = &p_lights;
  6265. render_state.reflection_probes = &p_reflection_probes;
  6266. render_state.gi_probes = &p_gi_probes;
  6267. render_state.decals = &p_decals;
  6268. render_state.lightmaps = &p_lightmaps;
  6269. render_state.environment = p_environment;
  6270. render_state.camera_effects = p_camera_effects;
  6271. render_state.shadow_atlas = p_shadow_atlas;
  6272. render_state.reflection_atlas = p_reflection_atlas;
  6273. render_state.reflection_probe = p_reflection_probe;
  6274. render_state.reflection_probe_pass = p_reflection_probe_pass;
  6275. render_state.screen_lod_threshold = p_screen_lod_threshold;
  6276. render_state.render_shadows = p_render_shadows;
  6277. render_state.render_shadow_count = p_render_shadow_count;
  6278. render_state.render_sdfgi_regions = p_render_sdfgi_regions;
  6279. render_state.render_sdfgi_region_count = p_render_sdfgi_region_count;
  6280. render_state.sdfgi_update_data = p_sdfgi_update_data;
  6281. }
  6282. PagedArray<RID> empty;
  6283. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
  6284. render_state.lights = &empty;
  6285. render_state.reflection_probes = &empty;
  6286. render_state.gi_probes = &empty;
  6287. }
  6288. //sdfgi first
  6289. if (p_render_buffers.is_valid()) {
  6290. for (int i = 0; i < render_state.render_sdfgi_region_count; i++) {
  6291. _render_sdfgi_region(p_render_buffers, render_state.render_sdfgi_regions[i].region, render_state.render_sdfgi_regions[i].instances);
  6292. }
  6293. if (render_state.sdfgi_update_data->update_static) {
  6294. _render_sdfgi_static_lights(p_render_buffers, render_state.sdfgi_update_data->static_cascade_count, p_sdfgi_update_data->static_cascade_indices, render_state.sdfgi_update_data->static_positional_lights);
  6295. }
  6296. }
  6297. Color clear_color;
  6298. if (p_render_buffers.is_valid()) {
  6299. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  6300. ERR_FAIL_COND(!rb);
  6301. clear_color = storage->render_target_get_clear_request_color(rb->render_target);
  6302. } else {
  6303. clear_color = storage->get_default_clear_color();
  6304. }
  6305. //assign render indices to giprobes
  6306. for (uint32_t i = 0; i < (uint32_t)p_gi_probes.size(); i++) {
  6307. GIProbeInstance *giprobe_inst = gi_probe_instance_owner.getornull(p_gi_probes[i]);
  6308. if (giprobe_inst) {
  6309. giprobe_inst->render_index = i;
  6310. }
  6311. }
  6312. if (render_buffers_owner.owns(render_state.render_buffers)) {
  6313. RenderBuffers *rb = render_buffers_owner.getornull(render_state.render_buffers);
  6314. current_cluster_builder = rb->cluster_builder;
  6315. } else if (reflection_probe_instance_owner.owns(render_state.reflection_probe)) {
  6316. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(render_state.reflection_probe);
  6317. ReflectionAtlas *ra = reflection_atlas_owner.getornull(rpi->atlas);
  6318. if (!ra) {
  6319. ERR_PRINT("reflection probe has no reflection atlas! Bug?");
  6320. current_cluster_builder = nullptr;
  6321. } else {
  6322. current_cluster_builder = ra->cluster_builder;
  6323. }
  6324. } else {
  6325. ERR_PRINT("No cluster builder, bug"); //should never happen, will crash
  6326. current_cluster_builder = nullptr;
  6327. }
  6328. if (p_render_buffers.is_valid()) {
  6329. _pre_process_gi(p_render_buffers, p_cam_transform);
  6330. }
  6331. render_state.gi_probe_count = 0;
  6332. if (render_state.render_buffers.is_valid()) {
  6333. _setup_giprobes(render_state.render_buffers, render_state.cam_transform, *render_state.gi_probes, render_state.gi_probe_count);
  6334. _sdfgi_update_light(render_state.render_buffers, render_state.environment);
  6335. }
  6336. render_state.depth_prepass_used = false;
  6337. //calls _pre_opaque_render between depth pre-pass and opaque pass
  6338. _render_scene(p_render_buffers, p_cam_transform, p_cam_projection, p_cam_ortogonal, p_instances, *render_state.gi_probes, p_lightmaps, p_environment, current_cluster_builder->get_cluster_buffer(), current_cluster_builder->get_cluster_size(), current_cluster_builder->get_max_cluster_elements(), p_camera_effects, p_shadow_atlas, p_reflection_atlas, p_reflection_probe, p_reflection_probe_pass, clear_color, p_screen_lod_threshold);
  6339. if (p_render_buffers.is_valid()) {
  6340. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_CLUSTER_OMNI_LIGHTS || debug_draw == RS::VIEWPORT_DEBUG_DRAW_CLUSTER_SPOT_LIGHTS || debug_draw == RS::VIEWPORT_DEBUG_DRAW_CLUSTER_DECALS || debug_draw == RS::VIEWPORT_DEBUG_DRAW_CLUSTER_REFLECTION_PROBES) {
  6341. ClusterBuilderRD::ElementType elem_type = ClusterBuilderRD::ELEMENT_TYPE_MAX;
  6342. switch (debug_draw) {
  6343. case RS::VIEWPORT_DEBUG_DRAW_CLUSTER_OMNI_LIGHTS:
  6344. elem_type = ClusterBuilderRD::ELEMENT_TYPE_OMNI_LIGHT;
  6345. break;
  6346. case RS::VIEWPORT_DEBUG_DRAW_CLUSTER_SPOT_LIGHTS:
  6347. elem_type = ClusterBuilderRD::ELEMENT_TYPE_SPOT_LIGHT;
  6348. break;
  6349. case RS::VIEWPORT_DEBUG_DRAW_CLUSTER_DECALS:
  6350. elem_type = ClusterBuilderRD::ELEMENT_TYPE_DECAL;
  6351. break;
  6352. case RS::VIEWPORT_DEBUG_DRAW_CLUSTER_REFLECTION_PROBES:
  6353. elem_type = ClusterBuilderRD::ELEMENT_TYPE_REFLECTION_PROBE;
  6354. break;
  6355. default: {
  6356. }
  6357. }
  6358. current_cluster_builder->debug(elem_type);
  6359. }
  6360. RENDER_TIMESTAMP("Tonemap");
  6361. _render_buffers_post_process_and_tonemap(p_render_buffers, p_environment, p_camera_effects, p_cam_projection);
  6362. _render_buffers_debug_draw(p_render_buffers, p_shadow_atlas);
  6363. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SDFGI) {
  6364. _sdfgi_debug_draw(p_render_buffers, p_cam_projection, p_cam_transform);
  6365. }
  6366. }
  6367. }
  6368. void RendererSceneRenderRD::_render_shadow_pass(RID p_light, RID p_shadow_atlas, int p_pass, const PagedArray<GeometryInstance *> &p_instances, const Plane &p_camera_plane, float p_lod_distance_multiplier, float p_screen_lod_threshold, bool p_open_pass, bool p_close_pass, bool p_clear_region) {
  6369. LightInstance *light_instance = light_instance_owner.getornull(p_light);
  6370. ERR_FAIL_COND(!light_instance);
  6371. Rect2i atlas_rect;
  6372. uint32_t atlas_size;
  6373. RID atlas_fb;
  6374. bool using_dual_paraboloid = false;
  6375. bool using_dual_paraboloid_flip = false;
  6376. RID render_fb;
  6377. RID render_texture;
  6378. float zfar;
  6379. bool use_pancake = false;
  6380. bool render_cubemap = false;
  6381. bool finalize_cubemap = false;
  6382. bool flip_y = false;
  6383. CameraMatrix light_projection;
  6384. Transform light_transform;
  6385. if (storage->light_get_type(light_instance->light) == RS::LIGHT_DIRECTIONAL) {
  6386. //set pssm stuff
  6387. if (light_instance->last_scene_shadow_pass != scene_pass) {
  6388. light_instance->directional_rect = _get_directional_shadow_rect(directional_shadow.size, directional_shadow.light_count, directional_shadow.current_light);
  6389. directional_shadow.current_light++;
  6390. light_instance->last_scene_shadow_pass = scene_pass;
  6391. }
  6392. use_pancake = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE) > 0;
  6393. light_projection = light_instance->shadow_transform[p_pass].camera;
  6394. light_transform = light_instance->shadow_transform[p_pass].transform;
  6395. atlas_rect.position.x = light_instance->directional_rect.position.x;
  6396. atlas_rect.position.y = light_instance->directional_rect.position.y;
  6397. atlas_rect.size.width = light_instance->directional_rect.size.x;
  6398. atlas_rect.size.height = light_instance->directional_rect.size.y;
  6399. if (storage->light_directional_get_shadow_mode(light_instance->light) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
  6400. atlas_rect.size.width /= 2;
  6401. atlas_rect.size.height /= 2;
  6402. if (p_pass == 1) {
  6403. atlas_rect.position.x += atlas_rect.size.width;
  6404. } else if (p_pass == 2) {
  6405. atlas_rect.position.y += atlas_rect.size.height;
  6406. } else if (p_pass == 3) {
  6407. atlas_rect.position.x += atlas_rect.size.width;
  6408. atlas_rect.position.y += atlas_rect.size.height;
  6409. }
  6410. } else if (storage->light_directional_get_shadow_mode(light_instance->light) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
  6411. atlas_rect.size.height /= 2;
  6412. if (p_pass == 0) {
  6413. } else {
  6414. atlas_rect.position.y += atlas_rect.size.height;
  6415. }
  6416. }
  6417. light_instance->shadow_transform[p_pass].atlas_rect = atlas_rect;
  6418. light_instance->shadow_transform[p_pass].atlas_rect.position /= directional_shadow.size;
  6419. light_instance->shadow_transform[p_pass].atlas_rect.size /= directional_shadow.size;
  6420. zfar = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_RANGE);
  6421. render_fb = directional_shadow.fb;
  6422. render_texture = RID();
  6423. flip_y = true;
  6424. } else {
  6425. //set from shadow atlas
  6426. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
  6427. ERR_FAIL_COND(!shadow_atlas);
  6428. ERR_FAIL_COND(!shadow_atlas->shadow_owners.has(p_light));
  6429. _update_shadow_atlas(shadow_atlas);
  6430. uint32_t key = shadow_atlas->shadow_owners[p_light];
  6431. uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  6432. uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK;
  6433. ERR_FAIL_INDEX((int)shadow, shadow_atlas->quadrants[quadrant].shadows.size());
  6434. uint32_t quadrant_size = shadow_atlas->size >> 1;
  6435. atlas_rect.position.x = (quadrant & 1) * quadrant_size;
  6436. atlas_rect.position.y = (quadrant >> 1) * quadrant_size;
  6437. uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision);
  6438. atlas_rect.position.x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  6439. atlas_rect.position.y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  6440. atlas_rect.size.width = shadow_size;
  6441. atlas_rect.size.height = shadow_size;
  6442. zfar = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_RANGE);
  6443. if (storage->light_get_type(light_instance->light) == RS::LIGHT_OMNI) {
  6444. if (storage->light_omni_get_shadow_mode(light_instance->light) == RS::LIGHT_OMNI_SHADOW_CUBE) {
  6445. ShadowCubemap *cubemap = _get_shadow_cubemap(shadow_size / 2);
  6446. render_fb = cubemap->side_fb[p_pass];
  6447. render_texture = cubemap->cubemap;
  6448. light_projection = light_instance->shadow_transform[p_pass].camera;
  6449. light_transform = light_instance->shadow_transform[p_pass].transform;
  6450. render_cubemap = true;
  6451. finalize_cubemap = p_pass == 5;
  6452. atlas_fb = shadow_atlas->fb;
  6453. atlas_size = shadow_atlas->size;
  6454. if (p_pass == 0) {
  6455. _render_shadow_begin();
  6456. }
  6457. } else {
  6458. light_projection = light_instance->shadow_transform[0].camera;
  6459. light_transform = light_instance->shadow_transform[0].transform;
  6460. atlas_rect.size.height /= 2;
  6461. atlas_rect.position.y += p_pass * atlas_rect.size.height;
  6462. using_dual_paraboloid = true;
  6463. using_dual_paraboloid_flip = p_pass == 1;
  6464. render_fb = shadow_atlas->fb;
  6465. flip_y = true;
  6466. }
  6467. } else if (storage->light_get_type(light_instance->light) == RS::LIGHT_SPOT) {
  6468. light_projection = light_instance->shadow_transform[0].camera;
  6469. light_transform = light_instance->shadow_transform[0].transform;
  6470. render_fb = shadow_atlas->fb;
  6471. flip_y = true;
  6472. }
  6473. }
  6474. if (render_cubemap) {
  6475. //rendering to cubemap
  6476. _render_shadow_append(render_fb, p_instances, light_projection, light_transform, zfar, 0, 0, false, false, use_pancake, p_camera_plane, p_lod_distance_multiplier, p_screen_lod_threshold, Rect2(), false, true, true, true);
  6477. if (finalize_cubemap) {
  6478. _render_shadow_process();
  6479. _render_shadow_end();
  6480. //reblit
  6481. Rect2 atlas_rect_norm = atlas_rect;
  6482. atlas_rect_norm.position.x /= float(atlas_size);
  6483. atlas_rect_norm.position.y /= float(atlas_size);
  6484. atlas_rect_norm.size.x /= float(atlas_size);
  6485. atlas_rect_norm.size.y /= float(atlas_size);
  6486. atlas_rect_norm.size.height /= 2;
  6487. storage->get_effects()->copy_cubemap_to_dp(render_texture, atlas_fb, atlas_rect_norm, light_projection.get_z_near(), light_projection.get_z_far(), false);
  6488. atlas_rect_norm.position.y += atlas_rect_norm.size.height;
  6489. storage->get_effects()->copy_cubemap_to_dp(render_texture, atlas_fb, atlas_rect_norm, light_projection.get_z_near(), light_projection.get_z_far(), true);
  6490. //restore transform so it can be properly used
  6491. light_instance_set_shadow_transform(p_light, CameraMatrix(), light_instance->transform, zfar, 0, 0, 0);
  6492. }
  6493. } else {
  6494. //render shadow
  6495. _render_shadow_append(render_fb, p_instances, light_projection, light_transform, zfar, 0, 0, using_dual_paraboloid, using_dual_paraboloid_flip, use_pancake, p_camera_plane, p_lod_distance_multiplier, p_screen_lod_threshold, atlas_rect, flip_y, p_clear_region, p_open_pass, p_close_pass);
  6496. }
  6497. }
  6498. void RendererSceneRenderRD::render_material(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) {
  6499. _render_material(p_cam_transform, p_cam_projection, p_cam_ortogonal, p_instances, p_framebuffer, p_region);
  6500. }
  6501. void RendererSceneRenderRD::_render_sdfgi_region(RID p_render_buffers, int p_region, const PagedArray<GeometryInstance *> &p_instances) {
  6502. //print_line("rendering region " + itos(p_region));
  6503. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  6504. ERR_FAIL_COND(!rb);
  6505. ERR_FAIL_COND(!rb->sdfgi);
  6506. AABB bounds;
  6507. Vector3i from;
  6508. Vector3i size;
  6509. int cascade_prev = _sdfgi_get_pending_region_data(p_render_buffers, p_region - 1, from, size, bounds);
  6510. int cascade_next = _sdfgi_get_pending_region_data(p_render_buffers, p_region + 1, from, size, bounds);
  6511. int cascade = _sdfgi_get_pending_region_data(p_render_buffers, p_region, from, size, bounds);
  6512. ERR_FAIL_COND(cascade < 0);
  6513. if (cascade_prev != cascade) {
  6514. //initialize render
  6515. RD::get_singleton()->texture_clear(rb->sdfgi->render_albedo, Color(0, 0, 0, 0), 0, 1, 0, 1);
  6516. RD::get_singleton()->texture_clear(rb->sdfgi->render_emission, Color(0, 0, 0, 0), 0, 1, 0, 1);
  6517. RD::get_singleton()->texture_clear(rb->sdfgi->render_emission_aniso, Color(0, 0, 0, 0), 0, 1, 0, 1);
  6518. RD::get_singleton()->texture_clear(rb->sdfgi->render_geom_facing, Color(0, 0, 0, 0), 0, 1, 0, 1);
  6519. }
  6520. //print_line("rendering cascade " + itos(p_region) + " objects: " + itos(p_cull_count) + " bounds: " + bounds + " from: " + from + " size: " + size + " cell size: " + rtos(rb->sdfgi->cascades[cascade].cell_size));
  6521. _render_sdfgi(p_render_buffers, from, size, bounds, p_instances, rb->sdfgi->render_albedo, rb->sdfgi->render_emission, rb->sdfgi->render_emission_aniso, rb->sdfgi->render_geom_facing);
  6522. if (cascade_next != cascade) {
  6523. RD::get_singleton()->draw_command_begin_label("SDFGI Pre-Process Cascade");
  6524. RENDER_TIMESTAMP(">SDFGI Update SDF");
  6525. //done rendering! must update SDF
  6526. //clear dispatch indirect data
  6527. SDGIShader::PreprocessPushConstant push_constant;
  6528. zeromem(&push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6529. RENDER_TIMESTAMP("Scroll SDF");
  6530. //scroll
  6531. if (rb->sdfgi->cascades[cascade].dirty_regions != SDFGI::Cascade::DIRTY_ALL) {
  6532. //for scroll
  6533. Vector3i dirty = rb->sdfgi->cascades[cascade].dirty_regions;
  6534. push_constant.scroll[0] = dirty.x;
  6535. push_constant.scroll[1] = dirty.y;
  6536. push_constant.scroll[2] = dirty.z;
  6537. } else {
  6538. //for no scroll
  6539. push_constant.scroll[0] = 0;
  6540. push_constant.scroll[1] = 0;
  6541. push_constant.scroll[2] = 0;
  6542. }
  6543. rb->sdfgi->cascades[cascade].all_dynamic_lights_dirty = true;
  6544. push_constant.grid_size = rb->sdfgi->cascade_size;
  6545. push_constant.cascade = cascade;
  6546. if (rb->sdfgi->cascades[cascade].dirty_regions != SDFGI::Cascade::DIRTY_ALL) {
  6547. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  6548. //must pre scroll existing data because not all is dirty
  6549. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_SCROLL]);
  6550. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].scroll_uniform_set, 0);
  6551. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6552. RD::get_singleton()->compute_list_dispatch_indirect(compute_list, rb->sdfgi->cascades[cascade].solid_cell_dispatch_buffer, 0);
  6553. // no barrier do all together
  6554. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_SCROLL_OCCLUSION]);
  6555. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].scroll_occlusion_uniform_set, 0);
  6556. Vector3i dirty = rb->sdfgi->cascades[cascade].dirty_regions;
  6557. Vector3i groups;
  6558. groups.x = rb->sdfgi->cascade_size - ABS(dirty.x);
  6559. groups.y = rb->sdfgi->cascade_size - ABS(dirty.y);
  6560. groups.z = rb->sdfgi->cascade_size - ABS(dirty.z);
  6561. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6562. RD::get_singleton()->compute_list_dispatch_threads(compute_list, groups.x, groups.y, groups.z);
  6563. //no barrier, continue together
  6564. {
  6565. //scroll probes and their history also
  6566. SDGIShader::IntegratePushConstant ipush_constant;
  6567. ipush_constant.grid_size[1] = rb->sdfgi->cascade_size;
  6568. ipush_constant.grid_size[2] = rb->sdfgi->cascade_size;
  6569. ipush_constant.grid_size[0] = rb->sdfgi->cascade_size;
  6570. ipush_constant.max_cascades = rb->sdfgi->cascades.size();
  6571. ipush_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  6572. ipush_constant.history_index = 0;
  6573. ipush_constant.history_size = rb->sdfgi->history_size;
  6574. ipush_constant.ray_count = 0;
  6575. ipush_constant.ray_bias = 0;
  6576. ipush_constant.sky_mode = 0;
  6577. ipush_constant.sky_energy = 0;
  6578. ipush_constant.sky_color[0] = 0;
  6579. ipush_constant.sky_color[1] = 0;
  6580. ipush_constant.sky_color[2] = 0;
  6581. ipush_constant.y_mult = rb->sdfgi->y_mult;
  6582. ipush_constant.store_ambient_texture = false;
  6583. ipush_constant.image_size[0] = rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count;
  6584. ipush_constant.image_size[1] = rb->sdfgi->probe_axis_count;
  6585. int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  6586. ipush_constant.cascade = cascade;
  6587. ipush_constant.world_offset[0] = rb->sdfgi->cascades[cascade].position.x / probe_divisor;
  6588. ipush_constant.world_offset[1] = rb->sdfgi->cascades[cascade].position.y / probe_divisor;
  6589. ipush_constant.world_offset[2] = rb->sdfgi->cascades[cascade].position.z / probe_divisor;
  6590. ipush_constant.scroll[0] = dirty.x / probe_divisor;
  6591. ipush_constant.scroll[1] = dirty.y / probe_divisor;
  6592. ipush_constant.scroll[2] = dirty.z / probe_divisor;
  6593. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_SCROLL]);
  6594. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].integrate_uniform_set, 0);
  6595. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sdfgi_shader.integrate_default_sky_uniform_set, 1);
  6596. RD::get_singleton()->compute_list_set_push_constant(compute_list, &ipush_constant, sizeof(SDGIShader::IntegratePushConstant));
  6597. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count, rb->sdfgi->probe_axis_count, 1);
  6598. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6599. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_SCROLL_STORE]);
  6600. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].integrate_uniform_set, 0);
  6601. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sdfgi_shader.integrate_default_sky_uniform_set, 1);
  6602. RD::get_singleton()->compute_list_set_push_constant(compute_list, &ipush_constant, sizeof(SDGIShader::IntegratePushConstant));
  6603. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count, rb->sdfgi->probe_axis_count, 1);
  6604. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6605. if (rb->sdfgi->uses_multibounce) {
  6606. //multibounce requires this to be stored so direct light can read from it
  6607. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_STORE]);
  6608. //convert to octahedral to store
  6609. ipush_constant.image_size[0] *= SDFGI::LIGHTPROBE_OCT_SIZE;
  6610. ipush_constant.image_size[1] *= SDFGI::LIGHTPROBE_OCT_SIZE;
  6611. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].integrate_uniform_set, 0);
  6612. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sdfgi_shader.integrate_default_sky_uniform_set, 1);
  6613. RD::get_singleton()->compute_list_set_push_constant(compute_list, &ipush_constant, sizeof(SDGIShader::IntegratePushConstant));
  6614. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count * SDFGI::LIGHTPROBE_OCT_SIZE, rb->sdfgi->probe_axis_count * SDFGI::LIGHTPROBE_OCT_SIZE, 1);
  6615. }
  6616. }
  6617. //ok finally barrier
  6618. RD::get_singleton()->compute_list_end();
  6619. }
  6620. //clear dispatch indirect data
  6621. uint32_t dispatch_indirct_data[4] = { 0, 0, 0, 0 };
  6622. RD::get_singleton()->buffer_update(rb->sdfgi->cascades[cascade].solid_cell_dispatch_buffer, 0, sizeof(uint32_t) * 4, dispatch_indirct_data);
  6623. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  6624. bool half_size = true; //much faster, very little difference
  6625. static const int optimized_jf_group_size = 8;
  6626. if (half_size) {
  6627. push_constant.grid_size >>= 1;
  6628. uint32_t cascade_half_size = rb->sdfgi->cascade_size >> 1;
  6629. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE_HALF]);
  6630. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->sdf_initialize_half_uniform_set, 0);
  6631. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6632. RD::get_singleton()->compute_list_dispatch_threads(compute_list, cascade_half_size, cascade_half_size, cascade_half_size);
  6633. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6634. //must start with regular jumpflood
  6635. push_constant.half_size = true;
  6636. {
  6637. RENDER_TIMESTAMP("SDFGI Jump Flood (Half Size)");
  6638. uint32_t s = cascade_half_size;
  6639. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD]);
  6640. int jf_us = 0;
  6641. //start with regular jump flood for very coarse reads, as this is impossible to optimize
  6642. while (s > 1) {
  6643. s /= 2;
  6644. push_constant.step_size = s;
  6645. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_half_uniform_set[jf_us], 0);
  6646. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6647. RD::get_singleton()->compute_list_dispatch_threads(compute_list, cascade_half_size, cascade_half_size, cascade_half_size);
  6648. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6649. jf_us = jf_us == 0 ? 1 : 0;
  6650. if (cascade_half_size / (s / 2) >= optimized_jf_group_size) {
  6651. break;
  6652. }
  6653. }
  6654. RENDER_TIMESTAMP("SDFGI Jump Flood Optimized (Half Size)");
  6655. //continue with optimized jump flood for smaller reads
  6656. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_OPTIMIZED]);
  6657. while (s > 1) {
  6658. s /= 2;
  6659. push_constant.step_size = s;
  6660. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_half_uniform_set[jf_us], 0);
  6661. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6662. RD::get_singleton()->compute_list_dispatch_threads(compute_list, cascade_half_size, cascade_half_size, cascade_half_size);
  6663. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6664. jf_us = jf_us == 0 ? 1 : 0;
  6665. }
  6666. }
  6667. // restore grid size for last passes
  6668. push_constant.grid_size = rb->sdfgi->cascade_size;
  6669. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_UPSCALE]);
  6670. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->sdf_upscale_uniform_set, 0);
  6671. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6672. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size);
  6673. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6674. //run one pass of fullsize jumpflood to fix up half size arctifacts
  6675. push_constant.half_size = false;
  6676. push_constant.step_size = 1;
  6677. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_OPTIMIZED]);
  6678. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_uniform_set[rb->sdfgi->upscale_jfa_uniform_set_index], 0);
  6679. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6680. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size);
  6681. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6682. } else {
  6683. //full size jumpflood
  6684. RENDER_TIMESTAMP("SDFGI Jump Flood");
  6685. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE]);
  6686. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->sdf_initialize_uniform_set, 0);
  6687. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6688. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size);
  6689. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6690. push_constant.half_size = false;
  6691. {
  6692. uint32_t s = rb->sdfgi->cascade_size;
  6693. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD]);
  6694. int jf_us = 0;
  6695. //start with regular jump flood for very coarse reads, as this is impossible to optimize
  6696. while (s > 1) {
  6697. s /= 2;
  6698. push_constant.step_size = s;
  6699. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_uniform_set[jf_us], 0);
  6700. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6701. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size);
  6702. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6703. jf_us = jf_us == 0 ? 1 : 0;
  6704. if (rb->sdfgi->cascade_size / (s / 2) >= optimized_jf_group_size) {
  6705. break;
  6706. }
  6707. }
  6708. RENDER_TIMESTAMP("SDFGI Jump Flood Optimized");
  6709. //continue with optimized jump flood for smaller reads
  6710. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_OPTIMIZED]);
  6711. while (s > 1) {
  6712. s /= 2;
  6713. push_constant.step_size = s;
  6714. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_uniform_set[jf_us], 0);
  6715. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6716. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size);
  6717. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6718. jf_us = jf_us == 0 ? 1 : 0;
  6719. }
  6720. }
  6721. }
  6722. RENDER_TIMESTAMP("SDFGI Occlusion");
  6723. // occlusion
  6724. {
  6725. uint32_t probe_size = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  6726. Vector3i probe_global_pos = rb->sdfgi->cascades[cascade].position / probe_size;
  6727. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_OCCLUSION]);
  6728. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->occlusion_uniform_set, 0);
  6729. for (int i = 0; i < 8; i++) {
  6730. //dispatch all at once for performance
  6731. Vector3i offset(i & 1, (i >> 1) & 1, (i >> 2) & 1);
  6732. if ((probe_global_pos.x & 1) != 0) {
  6733. offset.x = (offset.x + 1) & 1;
  6734. }
  6735. if ((probe_global_pos.y & 1) != 0) {
  6736. offset.y = (offset.y + 1) & 1;
  6737. }
  6738. if ((probe_global_pos.z & 1) != 0) {
  6739. offset.z = (offset.z + 1) & 1;
  6740. }
  6741. push_constant.probe_offset[0] = offset.x;
  6742. push_constant.probe_offset[1] = offset.y;
  6743. push_constant.probe_offset[2] = offset.z;
  6744. push_constant.occlusion_index = i;
  6745. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6746. Vector3i groups = Vector3i(probe_size + 1, probe_size + 1, probe_size + 1) - offset; //if offset, it's one less probe per axis to compute
  6747. RD::get_singleton()->compute_list_dispatch(compute_list, groups.x, groups.y, groups.z);
  6748. }
  6749. RD::get_singleton()->compute_list_add_barrier(compute_list);
  6750. }
  6751. RENDER_TIMESTAMP("SDFGI Store");
  6752. // store
  6753. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_STORE]);
  6754. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].sdf_store_uniform_set, 0);
  6755. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  6756. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size);
  6757. RD::get_singleton()->compute_list_end();
  6758. //clear these textures, as they will have previous garbage on next draw
  6759. RD::get_singleton()->texture_clear(rb->sdfgi->cascades[cascade].light_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
  6760. RD::get_singleton()->texture_clear(rb->sdfgi->cascades[cascade].light_aniso_0_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
  6761. RD::get_singleton()->texture_clear(rb->sdfgi->cascades[cascade].light_aniso_1_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
  6762. #if 0
  6763. Vector<uint8_t> data = RD::get_singleton()->texture_get_data(rb->sdfgi->cascades[cascade].sdf, 0);
  6764. Ref<Image> img;
  6765. img.instance();
  6766. for (uint32_t i = 0; i < rb->sdfgi->cascade_size; i++) {
  6767. Vector<uint8_t> subarr = data.subarray(128 * 128 * i, 128 * 128 * (i + 1) - 1);
  6768. img->create(rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, false, Image::FORMAT_L8, subarr);
  6769. img->save_png("res://cascade_sdf_" + itos(cascade) + "_" + itos(i) + ".png");
  6770. }
  6771. //finalize render and update sdf
  6772. #endif
  6773. #if 0
  6774. Vector<uint8_t> data = RD::get_singleton()->texture_get_data(rb->sdfgi->render_albedo, 0);
  6775. Ref<Image> img;
  6776. img.instance();
  6777. for (uint32_t i = 0; i < rb->sdfgi->cascade_size; i++) {
  6778. Vector<uint8_t> subarr = data.subarray(128 * 128 * i * 2, 128 * 128 * (i + 1) * 2 - 1);
  6779. img->create(rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, false, Image::FORMAT_RGB565, subarr);
  6780. img->convert(Image::FORMAT_RGBA8);
  6781. img->save_png("res://cascade_" + itos(cascade) + "_" + itos(i) + ".png");
  6782. }
  6783. //finalize render and update sdf
  6784. #endif
  6785. RENDER_TIMESTAMP("<SDFGI Update SDF");
  6786. RD::get_singleton()->draw_command_end_label();
  6787. }
  6788. }
  6789. void RendererSceneRenderRD::render_particle_collider_heightfield(RID p_collider, const Transform &p_transform, const PagedArray<GeometryInstance *> &p_instances) {
  6790. ERR_FAIL_COND(!storage->particles_collision_is_heightfield(p_collider));
  6791. Vector3 extents = storage->particles_collision_get_extents(p_collider) * p_transform.basis.get_scale();
  6792. CameraMatrix cm;
  6793. cm.set_orthogonal(-extents.x, extents.x, -extents.z, extents.z, 0, extents.y * 2.0);
  6794. Vector3 cam_pos = p_transform.origin;
  6795. cam_pos.y += extents.y;
  6796. Transform cam_xform;
  6797. cam_xform.set_look_at(cam_pos, cam_pos - p_transform.basis.get_axis(Vector3::AXIS_Y), -p_transform.basis.get_axis(Vector3::AXIS_Z).normalized());
  6798. RID fb = storage->particles_collision_get_heightfield_framebuffer(p_collider);
  6799. _render_particle_collider_heightfield(fb, cam_xform, cm, p_instances);
  6800. }
  6801. void RendererSceneRenderRD::_render_sdfgi_static_lights(RID p_render_buffers, uint32_t p_cascade_count, const uint32_t *p_cascade_indices, const PagedArray<RID> *p_positional_light_cull_result) {
  6802. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  6803. ERR_FAIL_COND(!rb);
  6804. ERR_FAIL_COND(!rb->sdfgi);
  6805. RD::get_singleton()->draw_command_begin_label("SDFGI Render Static Lighs");
  6806. _sdfgi_update_cascades(p_render_buffers); //need cascades updated for this
  6807. SDGIShader::Light lights[SDFGI::MAX_STATIC_LIGHTS];
  6808. uint32_t light_count[SDFGI::MAX_STATIC_LIGHTS];
  6809. for (uint32_t i = 0; i < p_cascade_count; i++) {
  6810. ERR_CONTINUE(p_cascade_indices[i] >= rb->sdfgi->cascades.size());
  6811. SDFGI::Cascade &cc = rb->sdfgi->cascades[p_cascade_indices[i]];
  6812. { //fill light buffer
  6813. AABB cascade_aabb;
  6814. cascade_aabb.position = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + cc.position)) * cc.cell_size;
  6815. cascade_aabb.size = Vector3(1, 1, 1) * rb->sdfgi->cascade_size * cc.cell_size;
  6816. int idx = 0;
  6817. for (uint32_t j = 0; j < (uint32_t)p_positional_light_cull_result[i].size(); j++) {
  6818. if (idx == SDFGI::MAX_STATIC_LIGHTS) {
  6819. break;
  6820. }
  6821. LightInstance *li = light_instance_owner.getornull(p_positional_light_cull_result[i][j]);
  6822. ERR_CONTINUE(!li);
  6823. uint32_t max_sdfgi_cascade = storage->light_get_max_sdfgi_cascade(li->light);
  6824. if (p_cascade_indices[i] > max_sdfgi_cascade) {
  6825. continue;
  6826. }
  6827. if (!cascade_aabb.intersects(li->aabb)) {
  6828. continue;
  6829. }
  6830. lights[idx].type = storage->light_get_type(li->light);
  6831. Vector3 dir = -li->transform.basis.get_axis(Vector3::AXIS_Z);
  6832. if (lights[idx].type == RS::LIGHT_DIRECTIONAL) {
  6833. dir.y *= rb->sdfgi->y_mult; //only makes sense for directional
  6834. dir.normalize();
  6835. }
  6836. lights[idx].direction[0] = dir.x;
  6837. lights[idx].direction[1] = dir.y;
  6838. lights[idx].direction[2] = dir.z;
  6839. Vector3 pos = li->transform.origin;
  6840. pos.y *= rb->sdfgi->y_mult;
  6841. lights[idx].position[0] = pos.x;
  6842. lights[idx].position[1] = pos.y;
  6843. lights[idx].position[2] = pos.z;
  6844. Color color = storage->light_get_color(li->light);
  6845. color = color.to_linear();
  6846. lights[idx].color[0] = color.r;
  6847. lights[idx].color[1] = color.g;
  6848. lights[idx].color[2] = color.b;
  6849. lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
  6850. lights[idx].has_shadow = storage->light_has_shadow(li->light);
  6851. lights[idx].attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_ATTENUATION);
  6852. lights[idx].radius = storage->light_get_param(li->light, RS::LIGHT_PARAM_RANGE);
  6853. lights[idx].spot_angle = Math::deg2rad(storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ANGLE));
  6854. lights[idx].spot_attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  6855. idx++;
  6856. }
  6857. if (idx > 0) {
  6858. RD::get_singleton()->buffer_update(cc.lights_buffer, 0, idx * sizeof(SDGIShader::Light), lights);
  6859. }
  6860. light_count[i] = idx;
  6861. }
  6862. }
  6863. /* Static Lights */
  6864. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  6865. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.direct_light_pipeline[SDGIShader::DIRECT_LIGHT_MODE_STATIC]);
  6866. SDGIShader::DirectLightPushConstant dl_push_constant;
  6867. dl_push_constant.grid_size[0] = rb->sdfgi->cascade_size;
  6868. dl_push_constant.grid_size[1] = rb->sdfgi->cascade_size;
  6869. dl_push_constant.grid_size[2] = rb->sdfgi->cascade_size;
  6870. dl_push_constant.max_cascades = rb->sdfgi->cascades.size();
  6871. dl_push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  6872. dl_push_constant.multibounce = false; // this is static light, do not multibounce yet
  6873. dl_push_constant.y_mult = rb->sdfgi->y_mult;
  6874. //all must be processed
  6875. dl_push_constant.process_offset = 0;
  6876. dl_push_constant.process_increment = 1;
  6877. for (uint32_t i = 0; i < p_cascade_count; i++) {
  6878. ERR_CONTINUE(p_cascade_indices[i] >= rb->sdfgi->cascades.size());
  6879. SDFGI::Cascade &cc = rb->sdfgi->cascades[p_cascade_indices[i]];
  6880. dl_push_constant.light_count = light_count[i];
  6881. dl_push_constant.cascade = p_cascade_indices[i];
  6882. if (dl_push_constant.light_count > 0) {
  6883. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, cc.sdf_direct_light_uniform_set, 0);
  6884. RD::get_singleton()->compute_list_set_push_constant(compute_list, &dl_push_constant, sizeof(SDGIShader::DirectLightPushConstant));
  6885. RD::get_singleton()->compute_list_dispatch_indirect(compute_list, cc.solid_cell_dispatch_buffer, 0);
  6886. }
  6887. }
  6888. RD::get_singleton()->compute_list_end();
  6889. RD::get_singleton()->draw_command_end_label();
  6890. }
  6891. bool RendererSceneRenderRD::free(RID p_rid) {
  6892. if (render_buffers_owner.owns(p_rid)) {
  6893. RenderBuffers *rb = render_buffers_owner.getornull(p_rid);
  6894. _free_render_buffer_data(rb);
  6895. memdelete(rb->data);
  6896. if (rb->sdfgi) {
  6897. _sdfgi_erase(rb);
  6898. }
  6899. if (rb->volumetric_fog) {
  6900. _volumetric_fog_erase(rb);
  6901. }
  6902. if (rb->cluster_builder) {
  6903. memdelete(rb->cluster_builder);
  6904. }
  6905. render_buffers_owner.free(p_rid);
  6906. } else if (environment_owner.owns(p_rid)) {
  6907. //not much to delete, just free it
  6908. environment_owner.free(p_rid);
  6909. } else if (camera_effects_owner.owns(p_rid)) {
  6910. //not much to delete, just free it
  6911. camera_effects_owner.free(p_rid);
  6912. } else if (reflection_atlas_owner.owns(p_rid)) {
  6913. reflection_atlas_set_size(p_rid, 0, 0);
  6914. ReflectionAtlas *ra = reflection_atlas_owner.getornull(p_rid);
  6915. if (ra->cluster_builder) {
  6916. memdelete(ra->cluster_builder);
  6917. }
  6918. reflection_atlas_owner.free(p_rid);
  6919. } else if (reflection_probe_instance_owner.owns(p_rid)) {
  6920. //not much to delete, just free it
  6921. //ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_rid);
  6922. reflection_probe_release_atlas_index(p_rid);
  6923. reflection_probe_instance_owner.free(p_rid);
  6924. } else if (decal_instance_owner.owns(p_rid)) {
  6925. decal_instance_owner.free(p_rid);
  6926. } else if (lightmap_instance_owner.owns(p_rid)) {
  6927. lightmap_instance_owner.free(p_rid);
  6928. } else if (gi_probe_instance_owner.owns(p_rid)) {
  6929. GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_rid);
  6930. if (gi_probe->texture.is_valid()) {
  6931. RD::get_singleton()->free(gi_probe->texture);
  6932. RD::get_singleton()->free(gi_probe->write_buffer);
  6933. }
  6934. for (int i = 0; i < gi_probe->dynamic_maps.size(); i++) {
  6935. RD::get_singleton()->free(gi_probe->dynamic_maps[i].texture);
  6936. RD::get_singleton()->free(gi_probe->dynamic_maps[i].depth);
  6937. }
  6938. gi_probe_instance_owner.free(p_rid);
  6939. } else if (sky_owner.owns(p_rid)) {
  6940. _update_dirty_skys();
  6941. Sky *sky = sky_owner.getornull(p_rid);
  6942. if (sky->radiance.is_valid()) {
  6943. RD::get_singleton()->free(sky->radiance);
  6944. sky->radiance = RID();
  6945. }
  6946. _clear_reflection_data(sky->reflection);
  6947. if (sky->uniform_buffer.is_valid()) {
  6948. RD::get_singleton()->free(sky->uniform_buffer);
  6949. sky->uniform_buffer = RID();
  6950. }
  6951. if (sky->half_res_pass.is_valid()) {
  6952. RD::get_singleton()->free(sky->half_res_pass);
  6953. sky->half_res_pass = RID();
  6954. }
  6955. if (sky->quarter_res_pass.is_valid()) {
  6956. RD::get_singleton()->free(sky->quarter_res_pass);
  6957. sky->quarter_res_pass = RID();
  6958. }
  6959. if (sky->material.is_valid()) {
  6960. storage->free(sky->material);
  6961. }
  6962. sky_owner.free(p_rid);
  6963. } else if (light_instance_owner.owns(p_rid)) {
  6964. LightInstance *light_instance = light_instance_owner.getornull(p_rid);
  6965. //remove from shadow atlases..
  6966. for (Set<RID>::Element *E = light_instance->shadow_atlases.front(); E; E = E->next()) {
  6967. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(E->get());
  6968. ERR_CONTINUE(!shadow_atlas->shadow_owners.has(p_rid));
  6969. uint32_t key = shadow_atlas->shadow_owners[p_rid];
  6970. uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  6971. uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK;
  6972. shadow_atlas->quadrants[q].shadows.write[s].owner = RID();
  6973. shadow_atlas->shadow_owners.erase(p_rid);
  6974. }
  6975. light_instance_owner.free(p_rid);
  6976. } else if (shadow_atlas_owner.owns(p_rid)) {
  6977. shadow_atlas_set_size(p_rid, 0);
  6978. shadow_atlas_owner.free(p_rid);
  6979. } else {
  6980. return false;
  6981. }
  6982. return true;
  6983. }
  6984. void RendererSceneRenderRD::set_debug_draw_mode(RS::ViewportDebugDraw p_debug_draw) {
  6985. debug_draw = p_debug_draw;
  6986. }
  6987. void RendererSceneRenderRD::update() {
  6988. _update_dirty_skys();
  6989. }
  6990. void RendererSceneRenderRD::set_time(double p_time, double p_step) {
  6991. time = p_time;
  6992. time_step = p_step;
  6993. }
  6994. void RendererSceneRenderRD::screen_space_roughness_limiter_set_active(bool p_enable, float p_amount, float p_limit) {
  6995. screen_space_roughness_limiter = p_enable;
  6996. screen_space_roughness_limiter_amount = p_amount;
  6997. screen_space_roughness_limiter_limit = p_limit;
  6998. }
  6999. bool RendererSceneRenderRD::screen_space_roughness_limiter_is_active() const {
  7000. return screen_space_roughness_limiter;
  7001. }
  7002. float RendererSceneRenderRD::screen_space_roughness_limiter_get_amount() const {
  7003. return screen_space_roughness_limiter_amount;
  7004. }
  7005. float RendererSceneRenderRD::screen_space_roughness_limiter_get_limit() const {
  7006. return screen_space_roughness_limiter_limit;
  7007. }
  7008. TypedArray<Image> RendererSceneRenderRD::bake_render_uv2(RID p_base, const Vector<RID> &p_material_overrides, const Size2i &p_image_size) {
  7009. RD::TextureFormat tf;
  7010. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  7011. tf.width = p_image_size.width; // Always 64x64
  7012. tf.height = p_image_size.height;
  7013. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
  7014. RID albedo_alpha_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  7015. RID normal_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  7016. RID orm_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  7017. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  7018. RID emission_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  7019. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  7020. RID depth_write_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  7021. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
  7022. tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
  7023. RID depth_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  7024. Vector<RID> fb_tex;
  7025. fb_tex.push_back(albedo_alpha_tex);
  7026. fb_tex.push_back(normal_tex);
  7027. fb_tex.push_back(orm_tex);
  7028. fb_tex.push_back(emission_tex);
  7029. fb_tex.push_back(depth_write_tex);
  7030. fb_tex.push_back(depth_tex);
  7031. RID fb = RD::get_singleton()->framebuffer_create(fb_tex);
  7032. //RID sampled_light;
  7033. GeometryInstance *gi = geometry_instance_create(p_base);
  7034. uint32_t sc = RSG::storage->mesh_get_surface_count(p_base);
  7035. Vector<RID> materials;
  7036. materials.resize(sc);
  7037. for (uint32_t i = 0; i < sc; i++) {
  7038. if (i < (uint32_t)p_material_overrides.size()) {
  7039. materials.write[i] = p_material_overrides[i];
  7040. }
  7041. }
  7042. geometry_instance_set_surface_materials(gi, materials);
  7043. if (cull_argument.size() == 0) {
  7044. cull_argument.push_back(nullptr);
  7045. }
  7046. cull_argument[0] = gi;
  7047. _render_uv2(cull_argument, fb, Rect2i(0, 0, p_image_size.width, p_image_size.height));
  7048. geometry_instance_free(gi);
  7049. TypedArray<Image> ret;
  7050. {
  7051. PackedByteArray data = RD::get_singleton()->texture_get_data(albedo_alpha_tex, 0);
  7052. Ref<Image> img;
  7053. img.instance();
  7054. img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
  7055. RD::get_singleton()->free(albedo_alpha_tex);
  7056. ret.push_back(img);
  7057. }
  7058. {
  7059. PackedByteArray data = RD::get_singleton()->texture_get_data(normal_tex, 0);
  7060. Ref<Image> img;
  7061. img.instance();
  7062. img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
  7063. RD::get_singleton()->free(normal_tex);
  7064. ret.push_back(img);
  7065. }
  7066. {
  7067. PackedByteArray data = RD::get_singleton()->texture_get_data(orm_tex, 0);
  7068. Ref<Image> img;
  7069. img.instance();
  7070. img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
  7071. RD::get_singleton()->free(orm_tex);
  7072. ret.push_back(img);
  7073. }
  7074. {
  7075. PackedByteArray data = RD::get_singleton()->texture_get_data(emission_tex, 0);
  7076. Ref<Image> img;
  7077. img.instance();
  7078. img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBAH, data);
  7079. RD::get_singleton()->free(emission_tex);
  7080. ret.push_back(img);
  7081. }
  7082. RD::get_singleton()->free(depth_write_tex);
  7083. RD::get_singleton()->free(depth_tex);
  7084. return ret;
  7085. }
  7086. void RendererSceneRenderRD::sdfgi_set_debug_probe_select(const Vector3 &p_position, const Vector3 &p_dir) {
  7087. sdfgi_debug_probe_pos = p_position;
  7088. sdfgi_debug_probe_dir = p_dir;
  7089. }
  7090. RendererSceneRenderRD *RendererSceneRenderRD::singleton = nullptr;
  7091. RID RendererSceneRenderRD::get_reflection_probe_buffer() {
  7092. return cluster.reflection_buffer;
  7093. }
  7094. RID RendererSceneRenderRD::get_omni_light_buffer() {
  7095. return cluster.omni_light_buffer;
  7096. }
  7097. RID RendererSceneRenderRD::get_spot_light_buffer() {
  7098. return cluster.spot_light_buffer;
  7099. }
  7100. RID RendererSceneRenderRD::get_directional_light_buffer() {
  7101. return cluster.directional_light_buffer;
  7102. }
  7103. RID RendererSceneRenderRD::get_decal_buffer() {
  7104. return cluster.decal_buffer;
  7105. }
  7106. int RendererSceneRenderRD::get_max_directional_lights() const {
  7107. return cluster.max_directional_lights;
  7108. }
  7109. bool RendererSceneRenderRD::is_low_end() const {
  7110. return low_end;
  7111. }
  7112. RendererSceneRenderRD::RendererSceneRenderRD(RendererStorageRD *p_storage) {
  7113. max_cluster_elements = GLOBAL_GET("rendering/cluster_builder/max_clustered_elements");
  7114. storage = p_storage;
  7115. singleton = this;
  7116. roughness_layers = GLOBAL_GET("rendering/quality/reflections/roughness_layers");
  7117. sky_ggx_samples_quality = GLOBAL_GET("rendering/quality/reflections/ggx_samples");
  7118. sky_use_cubemap_array = GLOBAL_GET("rendering/quality/reflections/texture_array_reflections");
  7119. sdfgi_ray_count = RS::EnvironmentSDFGIRayCount(CLAMP(int32_t(GLOBAL_GET("rendering/sdfgi/probe_ray_count")), 0, int32_t(RS::ENV_SDFGI_RAY_COUNT_MAX - 1)));
  7120. sdfgi_frames_to_converge = RS::EnvironmentSDFGIFramesToConverge(CLAMP(int32_t(GLOBAL_GET("rendering/sdfgi/frames_to_converge")), 0, int32_t(RS::ENV_SDFGI_CONVERGE_MAX - 1)));
  7121. sdfgi_frames_to_update_light = RS::EnvironmentSDFGIFramesToUpdateLight(CLAMP(int32_t(GLOBAL_GET("rendering/sdfgi/frames_to_update_lights")), 0, int32_t(RS::ENV_SDFGI_UPDATE_LIGHT_MAX - 1)));
  7122. directional_shadow.size = GLOBAL_GET("rendering/quality/directional_shadow/size");
  7123. directional_shadow.use_16_bits = GLOBAL_GET("rendering/quality/directional_shadow/16_bits");
  7124. uint32_t textures_per_stage = RD::get_singleton()->limit_get(RD::LIMIT_MAX_TEXTURES_PER_SHADER_STAGE);
  7125. low_end = GLOBAL_GET("rendering/quality/rd_renderer/use_low_end_renderer");
  7126. if (textures_per_stage < 48) {
  7127. low_end = true;
  7128. }
  7129. if (!low_end) {
  7130. //kinda complicated to compute the amount of slots, we try to use as many as we can
  7131. gi_probe_max_lights = 32;
  7132. gi_probe_lights = memnew_arr(GIProbeLight, gi_probe_max_lights);
  7133. gi_probe_lights_uniform = RD::get_singleton()->uniform_buffer_create(gi_probe_max_lights * sizeof(GIProbeLight));
  7134. gi_probe_quality = RS::GIProbeQuality(CLAMP(int(GLOBAL_GET("rendering/quality/gi_probes/quality")), 0, 1));
  7135. String defines = "\n#define MAX_LIGHTS " + itos(gi_probe_max_lights) + "\n";
  7136. Vector<String> versions;
  7137. versions.push_back("\n#define MODE_COMPUTE_LIGHT\n");
  7138. versions.push_back("\n#define MODE_SECOND_BOUNCE\n");
  7139. versions.push_back("\n#define MODE_UPDATE_MIPMAPS\n");
  7140. versions.push_back("\n#define MODE_WRITE_TEXTURE\n");
  7141. versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_LIGHTING\n");
  7142. versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_SHRINK\n#define MODE_DYNAMIC_SHRINK_WRITE\n");
  7143. versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_SHRINK\n#define MODE_DYNAMIC_SHRINK_PLOT\n");
  7144. versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_SHRINK\n#define MODE_DYNAMIC_SHRINK_PLOT\n#define MODE_DYNAMIC_SHRINK_WRITE\n");
  7145. giprobe_shader.initialize(versions, defines);
  7146. giprobe_lighting_shader_version = giprobe_shader.version_create();
  7147. for (int i = 0; i < GI_PROBE_SHADER_VERSION_MAX; i++) {
  7148. giprobe_lighting_shader_version_shaders[i] = giprobe_shader.version_get_shader(giprobe_lighting_shader_version, i);
  7149. giprobe_lighting_shader_version_pipelines[i] = RD::get_singleton()->compute_pipeline_create(giprobe_lighting_shader_version_shaders[i]);
  7150. }
  7151. }
  7152. if (!low_end) {
  7153. String defines;
  7154. Vector<String> versions;
  7155. versions.push_back("\n#define MODE_DEBUG_COLOR\n");
  7156. versions.push_back("\n#define MODE_DEBUG_LIGHT\n");
  7157. versions.push_back("\n#define MODE_DEBUG_EMISSION\n");
  7158. versions.push_back("\n#define MODE_DEBUG_LIGHT\n#define MODE_DEBUG_LIGHT_FULL\n");
  7159. giprobe_debug_shader.initialize(versions, defines);
  7160. giprobe_debug_shader_version = giprobe_debug_shader.version_create();
  7161. for (int i = 0; i < GI_PROBE_DEBUG_MAX; i++) {
  7162. giprobe_debug_shader_version_shaders[i] = giprobe_debug_shader.version_get_shader(giprobe_debug_shader_version, i);
  7163. RD::PipelineRasterizationState rs;
  7164. rs.cull_mode = RD::POLYGON_CULL_FRONT;
  7165. RD::PipelineDepthStencilState ds;
  7166. ds.enable_depth_test = true;
  7167. ds.enable_depth_write = true;
  7168. ds.depth_compare_operator = RD::COMPARE_OP_LESS_OR_EQUAL;
  7169. giprobe_debug_shader_version_pipelines[i].setup(giprobe_debug_shader_version_shaders[i], RD::RENDER_PRIMITIVE_TRIANGLES, rs, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(), 0);
  7170. }
  7171. }
  7172. /* SKY SHADER */
  7173. {
  7174. // Start with the directional lights for the sky
  7175. sky_scene_state.max_directional_lights = 4;
  7176. uint32_t directional_light_buffer_size = sky_scene_state.max_directional_lights * sizeof(SkyDirectionalLightData);
  7177. sky_scene_state.directional_lights = memnew_arr(SkyDirectionalLightData, sky_scene_state.max_directional_lights);
  7178. sky_scene_state.last_frame_directional_lights = memnew_arr(SkyDirectionalLightData, sky_scene_state.max_directional_lights);
  7179. sky_scene_state.last_frame_directional_light_count = sky_scene_state.max_directional_lights + 1;
  7180. sky_scene_state.directional_light_buffer = RD::get_singleton()->uniform_buffer_create(directional_light_buffer_size);
  7181. String defines = "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(sky_scene_state.max_directional_lights) + "\n";
  7182. // Initialize sky
  7183. Vector<String> sky_modes;
  7184. sky_modes.push_back(""); // Full size
  7185. sky_modes.push_back("\n#define USE_HALF_RES_PASS\n"); // Half Res
  7186. sky_modes.push_back("\n#define USE_QUARTER_RES_PASS\n"); // Quarter res
  7187. sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n"); // Cubemap
  7188. sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n#define USE_HALF_RES_PASS\n"); // Half Res Cubemap
  7189. sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n#define USE_QUARTER_RES_PASS\n"); // Quarter res Cubemap
  7190. sky_shader.shader.initialize(sky_modes, defines);
  7191. }
  7192. // register our shader funds
  7193. storage->shader_set_data_request_function(RendererStorageRD::SHADER_TYPE_SKY, _create_sky_shader_funcs);
  7194. storage->material_set_data_request_function(RendererStorageRD::SHADER_TYPE_SKY, _create_sky_material_funcs);
  7195. {
  7196. ShaderCompilerRD::DefaultIdentifierActions actions;
  7197. actions.renames["COLOR"] = "color";
  7198. actions.renames["ALPHA"] = "alpha";
  7199. actions.renames["EYEDIR"] = "cube_normal";
  7200. actions.renames["POSITION"] = "params.position_multiplier.xyz";
  7201. actions.renames["SKY_COORDS"] = "panorama_coords";
  7202. actions.renames["SCREEN_UV"] = "uv";
  7203. actions.renames["TIME"] = "params.time";
  7204. actions.renames["HALF_RES_COLOR"] = "half_res_color";
  7205. actions.renames["QUARTER_RES_COLOR"] = "quarter_res_color";
  7206. actions.renames["RADIANCE"] = "radiance";
  7207. actions.renames["FOG"] = "custom_fog";
  7208. actions.renames["LIGHT0_ENABLED"] = "directional_lights.data[0].enabled";
  7209. actions.renames["LIGHT0_DIRECTION"] = "directional_lights.data[0].direction_energy.xyz";
  7210. actions.renames["LIGHT0_ENERGY"] = "directional_lights.data[0].direction_energy.w";
  7211. actions.renames["LIGHT0_COLOR"] = "directional_lights.data[0].color_size.xyz";
  7212. actions.renames["LIGHT0_SIZE"] = "directional_lights.data[0].color_size.w";
  7213. actions.renames["LIGHT1_ENABLED"] = "directional_lights.data[1].enabled";
  7214. actions.renames["LIGHT1_DIRECTION"] = "directional_lights.data[1].direction_energy.xyz";
  7215. actions.renames["LIGHT1_ENERGY"] = "directional_lights.data[1].direction_energy.w";
  7216. actions.renames["LIGHT1_COLOR"] = "directional_lights.data[1].color_size.xyz";
  7217. actions.renames["LIGHT1_SIZE"] = "directional_lights.data[1].color_size.w";
  7218. actions.renames["LIGHT2_ENABLED"] = "directional_lights.data[2].enabled";
  7219. actions.renames["LIGHT2_DIRECTION"] = "directional_lights.data[2].direction_energy.xyz";
  7220. actions.renames["LIGHT2_ENERGY"] = "directional_lights.data[2].direction_energy.w";
  7221. actions.renames["LIGHT2_COLOR"] = "directional_lights.data[2].color_size.xyz";
  7222. actions.renames["LIGHT2_SIZE"] = "directional_lights.data[2].color_size.w";
  7223. actions.renames["LIGHT3_ENABLED"] = "directional_lights.data[3].enabled";
  7224. actions.renames["LIGHT3_DIRECTION"] = "directional_lights.data[3].direction_energy.xyz";
  7225. actions.renames["LIGHT3_ENERGY"] = "directional_lights.data[3].direction_energy.w";
  7226. actions.renames["LIGHT3_COLOR"] = "directional_lights.data[3].color_size.xyz";
  7227. actions.renames["LIGHT3_SIZE"] = "directional_lights.data[3].color_size.w";
  7228. actions.renames["AT_CUBEMAP_PASS"] = "AT_CUBEMAP_PASS";
  7229. actions.renames["AT_HALF_RES_PASS"] = "AT_HALF_RES_PASS";
  7230. actions.renames["AT_QUARTER_RES_PASS"] = "AT_QUARTER_RES_PASS";
  7231. actions.custom_samplers["RADIANCE"] = "material_samplers[3]";
  7232. actions.usage_defines["HALF_RES_COLOR"] = "\n#define USES_HALF_RES_COLOR\n";
  7233. actions.usage_defines["QUARTER_RES_COLOR"] = "\n#define USES_QUARTER_RES_COLOR\n";
  7234. actions.render_mode_defines["disable_fog"] = "#define DISABLE_FOG\n";
  7235. actions.sampler_array_name = "material_samplers";
  7236. actions.base_texture_binding_index = 1;
  7237. actions.texture_layout_set = 1;
  7238. actions.base_uniform_string = "material.";
  7239. actions.base_varying_index = 10;
  7240. actions.default_filter = ShaderLanguage::FILTER_LINEAR_MIPMAP;
  7241. actions.default_repeat = ShaderLanguage::REPEAT_ENABLE;
  7242. actions.global_buffer_array_variable = "global_variables.data";
  7243. sky_shader.compiler.initialize(actions);
  7244. }
  7245. {
  7246. // default material and shader for sky shader
  7247. sky_shader.default_shader = storage->shader_create();
  7248. storage->shader_set_code(sky_shader.default_shader, "shader_type sky; void fragment() { COLOR = vec3(0.0); } \n");
  7249. sky_shader.default_material = storage->material_create();
  7250. storage->material_set_shader(sky_shader.default_material, sky_shader.default_shader);
  7251. SkyMaterialData *md = (SkyMaterialData *)storage->material_get_data(sky_shader.default_material, RendererStorageRD::SHADER_TYPE_SKY);
  7252. sky_shader.default_shader_rd = sky_shader.shader.version_get_shader(md->shader_data->version, SKY_VERSION_BACKGROUND);
  7253. sky_scene_state.uniform_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(SkySceneState::UBO));
  7254. Vector<RD::Uniform> uniforms;
  7255. {
  7256. RD::Uniform u;
  7257. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  7258. u.binding = 0;
  7259. u.ids.resize(12);
  7260. RID *ids_ptr = u.ids.ptrw();
  7261. ids_ptr[0] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  7262. ids_ptr[1] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  7263. ids_ptr[2] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  7264. ids_ptr[3] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  7265. ids_ptr[4] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  7266. ids_ptr[5] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  7267. ids_ptr[6] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  7268. ids_ptr[7] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  7269. ids_ptr[8] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  7270. ids_ptr[9] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  7271. ids_ptr[10] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  7272. ids_ptr[11] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  7273. uniforms.push_back(u);
  7274. }
  7275. {
  7276. RD::Uniform u;
  7277. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  7278. u.binding = 1;
  7279. u.ids.push_back(storage->global_variables_get_storage_buffer());
  7280. uniforms.push_back(u);
  7281. }
  7282. {
  7283. RD::Uniform u;
  7284. u.binding = 2;
  7285. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  7286. u.ids.push_back(sky_scene_state.uniform_buffer);
  7287. uniforms.push_back(u);
  7288. }
  7289. {
  7290. RD::Uniform u;
  7291. u.binding = 3;
  7292. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  7293. u.ids.push_back(sky_scene_state.directional_light_buffer);
  7294. uniforms.push_back(u);
  7295. }
  7296. sky_scene_state.uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_UNIFORMS);
  7297. }
  7298. {
  7299. Vector<RD::Uniform> uniforms;
  7300. {
  7301. RD::Uniform u;
  7302. u.binding = 0;
  7303. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  7304. RID vfog = storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE);
  7305. u.ids.push_back(vfog);
  7306. uniforms.push_back(u);
  7307. }
  7308. sky_scene_state.default_fog_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_FOG);
  7309. }
  7310. {
  7311. // Need defaults for using fog with clear color
  7312. sky_scene_state.fog_shader = storage->shader_create();
  7313. storage->shader_set_code(sky_scene_state.fog_shader, "shader_type sky; uniform vec4 clear_color; void fragment() { COLOR = clear_color.rgb; } \n");
  7314. sky_scene_state.fog_material = storage->material_create();
  7315. storage->material_set_shader(sky_scene_state.fog_material, sky_scene_state.fog_shader);
  7316. Vector<RD::Uniform> uniforms;
  7317. {
  7318. RD::Uniform u;
  7319. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  7320. u.binding = 0;
  7321. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
  7322. uniforms.push_back(u);
  7323. }
  7324. {
  7325. RD::Uniform u;
  7326. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  7327. u.binding = 1;
  7328. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_WHITE));
  7329. uniforms.push_back(u);
  7330. }
  7331. {
  7332. RD::Uniform u;
  7333. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  7334. u.binding = 2;
  7335. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_WHITE));
  7336. uniforms.push_back(u);
  7337. }
  7338. sky_scene_state.fog_only_texture_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_TEXTURES);
  7339. }
  7340. if (!low_end) {
  7341. //SDFGI
  7342. {
  7343. Vector<String> preprocess_modes;
  7344. preprocess_modes.push_back("\n#define MODE_SCROLL\n");
  7345. preprocess_modes.push_back("\n#define MODE_SCROLL_OCCLUSION\n");
  7346. preprocess_modes.push_back("\n#define MODE_INITIALIZE_JUMP_FLOOD\n");
  7347. preprocess_modes.push_back("\n#define MODE_INITIALIZE_JUMP_FLOOD_HALF\n");
  7348. preprocess_modes.push_back("\n#define MODE_JUMPFLOOD\n");
  7349. preprocess_modes.push_back("\n#define MODE_JUMPFLOOD_OPTIMIZED\n");
  7350. preprocess_modes.push_back("\n#define MODE_UPSCALE_JUMP_FLOOD\n");
  7351. preprocess_modes.push_back("\n#define MODE_OCCLUSION\n");
  7352. preprocess_modes.push_back("\n#define MODE_STORE\n");
  7353. String defines = "\n#define OCCLUSION_SIZE " + itos(SDFGI::CASCADE_SIZE / SDFGI::PROBE_DIVISOR) + "\n";
  7354. sdfgi_shader.preprocess.initialize(preprocess_modes, defines);
  7355. sdfgi_shader.preprocess_shader = sdfgi_shader.preprocess.version_create();
  7356. for (int i = 0; i < SDGIShader::PRE_PROCESS_MAX; i++) {
  7357. sdfgi_shader.preprocess_pipeline[i] = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, i));
  7358. }
  7359. }
  7360. {
  7361. //calculate tables
  7362. String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
  7363. Vector<String> direct_light_modes;
  7364. direct_light_modes.push_back("\n#define MODE_PROCESS_STATIC\n");
  7365. direct_light_modes.push_back("\n#define MODE_PROCESS_DYNAMIC\n");
  7366. sdfgi_shader.direct_light.initialize(direct_light_modes, defines);
  7367. sdfgi_shader.direct_light_shader = sdfgi_shader.direct_light.version_create();
  7368. for (int i = 0; i < SDGIShader::DIRECT_LIGHT_MODE_MAX; i++) {
  7369. sdfgi_shader.direct_light_pipeline[i] = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.direct_light.version_get_shader(sdfgi_shader.direct_light_shader, i));
  7370. }
  7371. }
  7372. {
  7373. //calculate tables
  7374. String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
  7375. defines += "\n#define SH_SIZE " + itos(SDFGI::SH_SIZE) + "\n";
  7376. if (sky_use_cubemap_array) {
  7377. defines += "\n#define USE_CUBEMAP_ARRAY\n";
  7378. }
  7379. Vector<String> integrate_modes;
  7380. integrate_modes.push_back("\n#define MODE_PROCESS\n");
  7381. integrate_modes.push_back("\n#define MODE_STORE\n");
  7382. integrate_modes.push_back("\n#define MODE_SCROLL\n");
  7383. integrate_modes.push_back("\n#define MODE_SCROLL_STORE\n");
  7384. sdfgi_shader.integrate.initialize(integrate_modes, defines);
  7385. sdfgi_shader.integrate_shader = sdfgi_shader.integrate.version_create();
  7386. for (int i = 0; i < SDGIShader::INTEGRATE_MODE_MAX; i++) {
  7387. sdfgi_shader.integrate_pipeline[i] = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, i));
  7388. }
  7389. {
  7390. Vector<RD::Uniform> uniforms;
  7391. {
  7392. RD::Uniform u;
  7393. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  7394. u.binding = 0;
  7395. u.ids.push_back(storage->texture_rd_get_default(RendererStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_WHITE));
  7396. uniforms.push_back(u);
  7397. }
  7398. {
  7399. RD::Uniform u;
  7400. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  7401. u.binding = 1;
  7402. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  7403. uniforms.push_back(u);
  7404. }
  7405. sdfgi_shader.integrate_default_sky_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, 0), 1);
  7406. }
  7407. }
  7408. //GK
  7409. {
  7410. //calculate tables
  7411. String defines = "\n#define SDFGI_OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
  7412. Vector<String> gi_modes;
  7413. gi_modes.push_back("\n#define USE_GIPROBES\n");
  7414. gi_modes.push_back("\n#define USE_SDFGI\n");
  7415. gi_modes.push_back("\n#define USE_SDFGI\n\n#define USE_GIPROBES\n");
  7416. gi_modes.push_back("\n#define MODE_HALF_RES\n#define USE_GIPROBES\n");
  7417. gi_modes.push_back("\n#define MODE_HALF_RES\n#define USE_SDFGI\n");
  7418. gi_modes.push_back("\n#define MODE_HALF_RES\n#define USE_SDFGI\n\n#define USE_GIPROBES\n");
  7419. gi.shader.initialize(gi_modes, defines);
  7420. gi.shader_version = gi.shader.version_create();
  7421. for (int i = 0; i < GI::MODE_MAX; i++) {
  7422. gi.pipelines[i] = RD::get_singleton()->compute_pipeline_create(gi.shader.version_get_shader(gi.shader_version, i));
  7423. }
  7424. gi.sdfgi_ubo = RD::get_singleton()->uniform_buffer_create(sizeof(GI::SDFGIData));
  7425. }
  7426. {
  7427. String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
  7428. Vector<String> debug_modes;
  7429. debug_modes.push_back("");
  7430. sdfgi_shader.debug.initialize(debug_modes, defines);
  7431. sdfgi_shader.debug_shader = sdfgi_shader.debug.version_create();
  7432. sdfgi_shader.debug_shader_version = sdfgi_shader.debug.version_get_shader(sdfgi_shader.debug_shader, 0);
  7433. sdfgi_shader.debug_pipeline = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.debug_shader_version);
  7434. }
  7435. {
  7436. String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
  7437. Vector<String> versions;
  7438. versions.push_back("\n#define MODE_PROBES\n");
  7439. versions.push_back("\n#define MODE_VISIBILITY\n");
  7440. sdfgi_shader.debug_probes.initialize(versions, defines);
  7441. sdfgi_shader.debug_probes_shader = sdfgi_shader.debug_probes.version_create();
  7442. {
  7443. RD::PipelineRasterizationState rs;
  7444. rs.cull_mode = RD::POLYGON_CULL_DISABLED;
  7445. RD::PipelineDepthStencilState ds;
  7446. ds.enable_depth_test = true;
  7447. ds.enable_depth_write = true;
  7448. ds.depth_compare_operator = RD::COMPARE_OP_LESS_OR_EQUAL;
  7449. for (int i = 0; i < SDGIShader::PROBE_DEBUG_MAX; i++) {
  7450. RID debug_probes_shader_version = sdfgi_shader.debug_probes.version_get_shader(sdfgi_shader.debug_probes_shader, i);
  7451. sdfgi_shader.debug_probes_pipeline[i].setup(debug_probes_shader_version, RD::RENDER_PRIMITIVE_TRIANGLE_STRIPS, rs, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(), 0);
  7452. }
  7453. }
  7454. }
  7455. default_giprobe_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(GI::GIProbeData) * RenderBuffers::MAX_GIPROBES);
  7456. }
  7457. { //decals
  7458. cluster.max_decals = max_cluster_elements;
  7459. uint32_t decal_buffer_size = cluster.max_decals * sizeof(Cluster::DecalData);
  7460. cluster.decals = memnew_arr(Cluster::DecalData, cluster.max_decals);
  7461. cluster.decal_sort = memnew_arr(Cluster::InstanceSort<DecalInstance>, cluster.max_decals);
  7462. cluster.decal_buffer = RD::get_singleton()->storage_buffer_create(decal_buffer_size);
  7463. }
  7464. { //reflections
  7465. cluster.max_reflections = max_cluster_elements;
  7466. cluster.reflections = memnew_arr(Cluster::ReflectionData, cluster.max_reflections);
  7467. cluster.reflection_sort = memnew_arr(Cluster::InstanceSort<ReflectionProbeInstance>, cluster.max_reflections);
  7468. cluster.reflection_buffer = RD::get_singleton()->storage_buffer_create(sizeof(Cluster::ReflectionData) * cluster.max_reflections);
  7469. }
  7470. { //lights
  7471. cluster.max_lights = max_cluster_elements;
  7472. uint32_t light_buffer_size = cluster.max_lights * sizeof(Cluster::LightData);
  7473. cluster.omni_lights = memnew_arr(Cluster::LightData, cluster.max_lights);
  7474. cluster.omni_light_buffer = RD::get_singleton()->storage_buffer_create(light_buffer_size);
  7475. cluster.omni_light_sort = memnew_arr(Cluster::InstanceSort<LightInstance>, cluster.max_lights);
  7476. cluster.spot_lights = memnew_arr(Cluster::LightData, cluster.max_lights);
  7477. cluster.spot_light_buffer = RD::get_singleton()->storage_buffer_create(light_buffer_size);
  7478. cluster.spot_light_sort = memnew_arr(Cluster::InstanceSort<LightInstance>, cluster.max_lights);
  7479. //defines += "\n#define MAX_LIGHT_DATA_STRUCTS " + itos(cluster.max_lights) + "\n";
  7480. //used for volumetric fog shrinking
  7481. cluster.lights_instances = memnew_arr(RID, cluster.max_lights * 2);
  7482. cluster.lights_shadow_rect_cache = memnew_arr(Rect2i, cluster.max_lights * 2);
  7483. cluster.max_directional_lights = MAX_DIRECTIONAL_LIGHTS;
  7484. uint32_t directional_light_buffer_size = cluster.max_directional_lights * sizeof(Cluster::DirectionalLightData);
  7485. cluster.directional_lights = memnew_arr(Cluster::DirectionalLightData, cluster.max_directional_lights);
  7486. cluster.directional_light_buffer = RD::get_singleton()->uniform_buffer_create(directional_light_buffer_size);
  7487. }
  7488. if (!low_end) {
  7489. String defines = "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(cluster.max_directional_lights) + "\n";
  7490. Vector<String> volumetric_fog_modes;
  7491. volumetric_fog_modes.push_back("\n#define MODE_DENSITY\n");
  7492. volumetric_fog_modes.push_back("\n#define MODE_DENSITY\n#define ENABLE_SDFGI\n");
  7493. volumetric_fog_modes.push_back("\n#define MODE_FILTER\n");
  7494. volumetric_fog_modes.push_back("\n#define MODE_FOG\n");
  7495. volumetric_fog.shader.initialize(volumetric_fog_modes, defines);
  7496. volumetric_fog.shader_version = volumetric_fog.shader.version_create();
  7497. for (int i = 0; i < VOLUMETRIC_FOG_SHADER_MAX; i++) {
  7498. volumetric_fog.pipelines[i] = RD::get_singleton()->compute_pipeline_create(volumetric_fog.shader.version_get_shader(volumetric_fog.shader_version, i));
  7499. }
  7500. volumetric_fog.params_ubo = RD::get_singleton()->uniform_buffer_create(sizeof(VolumetricFogShader::ParamsUBO));
  7501. }
  7502. {
  7503. RD::SamplerState sampler;
  7504. sampler.mag_filter = RD::SAMPLER_FILTER_NEAREST;
  7505. sampler.min_filter = RD::SAMPLER_FILTER_NEAREST;
  7506. sampler.enable_compare = true;
  7507. sampler.compare_op = RD::COMPARE_OP_LESS;
  7508. shadow_sampler = RD::get_singleton()->sampler_create(sampler);
  7509. }
  7510. camera_effects_set_dof_blur_bokeh_shape(RS::DOFBokehShape(int(GLOBAL_GET("rendering/quality/depth_of_field/depth_of_field_bokeh_shape"))));
  7511. camera_effects_set_dof_blur_quality(RS::DOFBlurQuality(int(GLOBAL_GET("rendering/quality/depth_of_field/depth_of_field_bokeh_quality"))), GLOBAL_GET("rendering/quality/depth_of_field/depth_of_field_use_jitter"));
  7512. environment_set_ssao_quality(RS::EnvironmentSSAOQuality(int(GLOBAL_GET("rendering/quality/ssao/quality"))), GLOBAL_GET("rendering/quality/ssao/half_size"), GLOBAL_GET("rendering/quality/ssao/adaptive_target"), GLOBAL_GET("rendering/quality/ssao/blur_passes"), GLOBAL_GET("rendering/quality/ssao/fadeout_from"), GLOBAL_GET("rendering/quality/ssao/fadeout_to"));
  7513. screen_space_roughness_limiter = GLOBAL_GET("rendering/quality/screen_filters/screen_space_roughness_limiter_enabled");
  7514. screen_space_roughness_limiter_amount = GLOBAL_GET("rendering/quality/screen_filters/screen_space_roughness_limiter_amount");
  7515. screen_space_roughness_limiter_limit = GLOBAL_GET("rendering/quality/screen_filters/screen_space_roughness_limiter_limit");
  7516. glow_bicubic_upscale = int(GLOBAL_GET("rendering/quality/glow/upscale_mode")) > 0;
  7517. glow_high_quality = GLOBAL_GET("rendering/quality/glow/use_high_quality");
  7518. ssr_roughness_quality = RS::EnvironmentSSRRoughnessQuality(int(GLOBAL_GET("rendering/quality/screen_space_reflection/roughness_quality")));
  7519. sss_quality = RS::SubSurfaceScatteringQuality(int(GLOBAL_GET("rendering/quality/subsurface_scattering/subsurface_scattering_quality")));
  7520. sss_scale = GLOBAL_GET("rendering/quality/subsurface_scattering/subsurface_scattering_scale");
  7521. sss_depth_scale = GLOBAL_GET("rendering/quality/subsurface_scattering/subsurface_scattering_depth_scale");
  7522. directional_penumbra_shadow_kernel = memnew_arr(float, 128);
  7523. directional_soft_shadow_kernel = memnew_arr(float, 128);
  7524. penumbra_shadow_kernel = memnew_arr(float, 128);
  7525. soft_shadow_kernel = memnew_arr(float, 128);
  7526. shadows_quality_set(RS::ShadowQuality(int(GLOBAL_GET("rendering/quality/shadows/soft_shadow_quality"))));
  7527. directional_shadow_quality_set(RS::ShadowQuality(int(GLOBAL_GET("rendering/quality/directional_shadow/soft_shadow_quality"))));
  7528. environment_set_volumetric_fog_volume_size(GLOBAL_GET("rendering/volumetric_fog/volume_size"), GLOBAL_GET("rendering/volumetric_fog/volume_depth"));
  7529. environment_set_volumetric_fog_filter_active(GLOBAL_GET("rendering/volumetric_fog/use_filter"));
  7530. environment_set_volumetric_fog_directional_shadow_shrink_size(GLOBAL_GET("rendering/volumetric_fog/directional_shadow_shrink"));
  7531. environment_set_volumetric_fog_positional_shadow_shrink_size(GLOBAL_GET("rendering/volumetric_fog/positional_shadow_shrink"));
  7532. cull_argument.set_page_pool(&cull_argument_pool);
  7533. gi.half_resolution = GLOBAL_GET("rendering/quality/gi/use_half_resolution");
  7534. }
  7535. RendererSceneRenderRD::~RendererSceneRenderRD() {
  7536. for (Map<int, ShadowCubemap>::Element *E = shadow_cubemaps.front(); E; E = E->next()) {
  7537. RD::get_singleton()->free(E->get().cubemap);
  7538. }
  7539. if (sky_scene_state.uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(sky_scene_state.uniform_set)) {
  7540. RD::get_singleton()->free(sky_scene_state.uniform_set);
  7541. }
  7542. if (!low_end) {
  7543. RD::get_singleton()->free(default_giprobe_buffer);
  7544. RD::get_singleton()->free(gi_probe_lights_uniform);
  7545. RD::get_singleton()->free(gi.sdfgi_ubo);
  7546. giprobe_debug_shader.version_free(giprobe_debug_shader_version);
  7547. giprobe_shader.version_free(giprobe_lighting_shader_version);
  7548. gi.shader.version_free(gi.shader_version);
  7549. sdfgi_shader.debug_probes.version_free(sdfgi_shader.debug_probes_shader);
  7550. sdfgi_shader.debug.version_free(sdfgi_shader.debug_shader);
  7551. sdfgi_shader.direct_light.version_free(sdfgi_shader.direct_light_shader);
  7552. sdfgi_shader.integrate.version_free(sdfgi_shader.integrate_shader);
  7553. sdfgi_shader.preprocess.version_free(sdfgi_shader.preprocess_shader);
  7554. volumetric_fog.shader.version_free(volumetric_fog.shader_version);
  7555. RD::get_singleton()->free(volumetric_fog.params_ubo);
  7556. memdelete_arr(gi_probe_lights);
  7557. }
  7558. SkyMaterialData *md = (SkyMaterialData *)storage->material_get_data(sky_shader.default_material, RendererStorageRD::SHADER_TYPE_SKY);
  7559. sky_shader.shader.version_free(md->shader_data->version);
  7560. RD::get_singleton()->free(sky_scene_state.directional_light_buffer);
  7561. RD::get_singleton()->free(sky_scene_state.uniform_buffer);
  7562. memdelete_arr(sky_scene_state.directional_lights);
  7563. memdelete_arr(sky_scene_state.last_frame_directional_lights);
  7564. storage->free(sky_shader.default_shader);
  7565. storage->free(sky_shader.default_material);
  7566. storage->free(sky_scene_state.fog_shader);
  7567. storage->free(sky_scene_state.fog_material);
  7568. memdelete_arr(directional_penumbra_shadow_kernel);
  7569. memdelete_arr(directional_soft_shadow_kernel);
  7570. memdelete_arr(penumbra_shadow_kernel);
  7571. memdelete_arr(soft_shadow_kernel);
  7572. {
  7573. RD::get_singleton()->free(cluster.directional_light_buffer);
  7574. RD::get_singleton()->free(cluster.omni_light_buffer);
  7575. RD::get_singleton()->free(cluster.spot_light_buffer);
  7576. RD::get_singleton()->free(cluster.reflection_buffer);
  7577. RD::get_singleton()->free(cluster.decal_buffer);
  7578. memdelete_arr(cluster.directional_lights);
  7579. memdelete_arr(cluster.omni_lights);
  7580. memdelete_arr(cluster.spot_lights);
  7581. memdelete_arr(cluster.omni_light_sort);
  7582. memdelete_arr(cluster.spot_light_sort);
  7583. memdelete_arr(cluster.lights_shadow_rect_cache);
  7584. memdelete_arr(cluster.lights_instances);
  7585. memdelete_arr(cluster.reflections);
  7586. memdelete_arr(cluster.reflection_sort);
  7587. memdelete_arr(cluster.decals);
  7588. memdelete_arr(cluster.decal_sort);
  7589. }
  7590. RD::get_singleton()->free(shadow_sampler);
  7591. directional_shadow_atlas_set_size(0);
  7592. cull_argument.reset(); //avoid exit error
  7593. }