rasterizer_scene_gles3.cpp 188 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415
  1. /**************************************************************************/
  2. /* rasterizer_scene_gles3.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "rasterizer_scene_gles3.h"
  31. #include "drivers/gles3/effects/copy_effects.h"
  32. #include "drivers/gles3/effects/feed_effects.h"
  33. #include "rasterizer_gles3.h"
  34. #include "storage/config.h"
  35. #include "storage/mesh_storage.h"
  36. #include "storage/particles_storage.h"
  37. #include "storage/texture_storage.h"
  38. #include "core/config/project_settings.h"
  39. #include "core/templates/sort_array.h"
  40. #include "servers/camera/camera_feed.h"
  41. #include "servers/camera_server.h"
  42. #include "servers/rendering/rendering_server_default.h"
  43. #include "servers/rendering/rendering_server_globals.h"
  44. #ifdef GLES3_ENABLED
  45. RasterizerSceneGLES3 *RasterizerSceneGLES3::singleton = nullptr;
  46. RenderGeometryInstance *RasterizerSceneGLES3::geometry_instance_create(RID p_base) {
  47. RS::InstanceType type = RSG::utilities->get_base_type(p_base);
  48. ERR_FAIL_COND_V(!((1 << type) & RS::INSTANCE_GEOMETRY_MASK), nullptr);
  49. GeometryInstanceGLES3 *ginstance = geometry_instance_alloc.alloc();
  50. ginstance->data = memnew(GeometryInstanceGLES3::Data);
  51. ginstance->data->base = p_base;
  52. ginstance->data->base_type = type;
  53. ginstance->data->dependency_tracker.userdata = ginstance;
  54. ginstance->data->dependency_tracker.changed_callback = _geometry_instance_dependency_changed;
  55. ginstance->data->dependency_tracker.deleted_callback = _geometry_instance_dependency_deleted;
  56. ginstance->_mark_dirty();
  57. return ginstance;
  58. }
  59. uint32_t RasterizerSceneGLES3::geometry_instance_get_pair_mask() {
  60. return ((1 << RS::INSTANCE_LIGHT) | (1 << RS::INSTANCE_REFLECTION_PROBE));
  61. }
  62. void RasterizerSceneGLES3::GeometryInstanceGLES3::pair_light_instances(const RID *p_light_instances, uint32_t p_light_instance_count) {
  63. GLES3::Config *config = GLES3::Config::get_singleton();
  64. paired_omni_light_count = 0;
  65. paired_spot_light_count = 0;
  66. paired_omni_lights.clear();
  67. paired_spot_lights.clear();
  68. for (uint32_t i = 0; i < p_light_instance_count; i++) {
  69. RS::LightType type = GLES3::LightStorage::get_singleton()->light_instance_get_type(p_light_instances[i]);
  70. switch (type) {
  71. case RS::LIGHT_OMNI: {
  72. if (paired_omni_light_count < (uint32_t)config->max_lights_per_object) {
  73. paired_omni_lights.push_back(p_light_instances[i]);
  74. paired_omni_light_count++;
  75. }
  76. } break;
  77. case RS::LIGHT_SPOT: {
  78. if (paired_spot_light_count < (uint32_t)config->max_lights_per_object) {
  79. paired_spot_lights.push_back(p_light_instances[i]);
  80. paired_spot_light_count++;
  81. }
  82. } break;
  83. default:
  84. break;
  85. }
  86. }
  87. }
  88. void RasterizerSceneGLES3::GeometryInstanceGLES3::pair_reflection_probe_instances(const RID *p_reflection_probe_instances, uint32_t p_reflection_probe_instance_count) {
  89. paired_reflection_probes.clear();
  90. for (uint32_t i = 0; i < p_reflection_probe_instance_count; i++) {
  91. paired_reflection_probes.push_back(p_reflection_probe_instances[i]);
  92. }
  93. }
  94. void RasterizerSceneGLES3::geometry_instance_free(RenderGeometryInstance *p_geometry_instance) {
  95. GeometryInstanceGLES3 *ginstance = static_cast<GeometryInstanceGLES3 *>(p_geometry_instance);
  96. ERR_FAIL_NULL(ginstance);
  97. GeometryInstanceSurface *surf = ginstance->surface_caches;
  98. while (surf) {
  99. GeometryInstanceSurface *next = surf->next;
  100. geometry_instance_surface_alloc.free(surf);
  101. surf = next;
  102. }
  103. memdelete(ginstance->data);
  104. geometry_instance_alloc.free(ginstance);
  105. }
  106. void RasterizerSceneGLES3::GeometryInstanceGLES3::_mark_dirty() {
  107. if (dirty_list_element.in_list()) {
  108. return;
  109. }
  110. //clear surface caches
  111. GeometryInstanceSurface *surf = surface_caches;
  112. while (surf) {
  113. GeometryInstanceSurface *next = surf->next;
  114. RasterizerSceneGLES3::get_singleton()->geometry_instance_surface_alloc.free(surf);
  115. surf = next;
  116. }
  117. surface_caches = nullptr;
  118. RasterizerSceneGLES3::get_singleton()->geometry_instance_dirty_list.add(&dirty_list_element);
  119. }
  120. void RasterizerSceneGLES3::GeometryInstanceGLES3::set_use_lightmap(RID p_lightmap_instance, const Rect2 &p_lightmap_uv_scale, int p_lightmap_slice_index) {
  121. lightmap_instance = p_lightmap_instance;
  122. lightmap_uv_scale = p_lightmap_uv_scale;
  123. lightmap_slice_index = p_lightmap_slice_index;
  124. _mark_dirty();
  125. }
  126. void RasterizerSceneGLES3::GeometryInstanceGLES3::set_lightmap_capture(const Color *p_sh9) {
  127. if (p_sh9) {
  128. if (lightmap_sh == nullptr) {
  129. lightmap_sh = memnew(GeometryInstanceLightmapSH);
  130. }
  131. memcpy(lightmap_sh->sh, p_sh9, sizeof(Color) * 9);
  132. } else {
  133. if (lightmap_sh != nullptr) {
  134. memdelete(lightmap_sh);
  135. lightmap_sh = nullptr;
  136. }
  137. }
  138. _mark_dirty();
  139. }
  140. void RasterizerSceneGLES3::_update_dirty_geometry_instances() {
  141. while (geometry_instance_dirty_list.first()) {
  142. _geometry_instance_update(geometry_instance_dirty_list.first()->self());
  143. }
  144. }
  145. void RasterizerSceneGLES3::_geometry_instance_dependency_changed(Dependency::DependencyChangedNotification p_notification, DependencyTracker *p_tracker) {
  146. switch (p_notification) {
  147. case Dependency::DEPENDENCY_CHANGED_MATERIAL:
  148. case Dependency::DEPENDENCY_CHANGED_MESH:
  149. case Dependency::DEPENDENCY_CHANGED_PARTICLES:
  150. case Dependency::DEPENDENCY_CHANGED_MULTIMESH:
  151. case Dependency::DEPENDENCY_CHANGED_SKELETON_DATA: {
  152. static_cast<RenderGeometryInstance *>(p_tracker->userdata)->_mark_dirty();
  153. static_cast<GeometryInstanceGLES3 *>(p_tracker->userdata)->data->dirty_dependencies = true;
  154. } break;
  155. case Dependency::DEPENDENCY_CHANGED_MULTIMESH_VISIBLE_INSTANCES: {
  156. GeometryInstanceGLES3 *ginstance = static_cast<GeometryInstanceGLES3 *>(p_tracker->userdata);
  157. if (ginstance->data->base_type == RS::INSTANCE_MULTIMESH) {
  158. ginstance->instance_count = GLES3::MeshStorage::get_singleton()->multimesh_get_instances_to_draw(ginstance->data->base);
  159. }
  160. } break;
  161. default: {
  162. //rest of notifications of no interest
  163. } break;
  164. }
  165. }
  166. void RasterizerSceneGLES3::_geometry_instance_dependency_deleted(const RID &p_dependency, DependencyTracker *p_tracker) {
  167. static_cast<RenderGeometryInstance *>(p_tracker->userdata)->_mark_dirty();
  168. static_cast<GeometryInstanceGLES3 *>(p_tracker->userdata)->data->dirty_dependencies = true;
  169. }
  170. void RasterizerSceneGLES3::_geometry_instance_add_surface_with_material(GeometryInstanceGLES3 *ginstance, uint32_t p_surface, GLES3::SceneMaterialData *p_material, uint32_t p_material_id, uint32_t p_shader_id, RID p_mesh) {
  171. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  172. bool has_read_screen_alpha = p_material->shader_data->uses_screen_texture || p_material->shader_data->uses_depth_texture || p_material->shader_data->uses_normal_texture;
  173. bool has_base_alpha = ((p_material->shader_data->uses_alpha && !p_material->shader_data->uses_alpha_clip) || has_read_screen_alpha);
  174. bool has_blend_alpha = p_material->shader_data->uses_blend_alpha;
  175. bool has_alpha = has_base_alpha || has_blend_alpha;
  176. uint32_t flags = 0;
  177. if (p_material->shader_data->uses_screen_texture) {
  178. flags |= GeometryInstanceSurface::FLAG_USES_SCREEN_TEXTURE;
  179. }
  180. if (p_material->shader_data->uses_depth_texture) {
  181. flags |= GeometryInstanceSurface::FLAG_USES_DEPTH_TEXTURE;
  182. }
  183. if (p_material->shader_data->uses_normal_texture) {
  184. flags |= GeometryInstanceSurface::FLAG_USES_NORMAL_TEXTURE;
  185. }
  186. if (ginstance->data->cast_double_sided_shadows) {
  187. flags |= GeometryInstanceSurface::FLAG_USES_DOUBLE_SIDED_SHADOWS;
  188. }
  189. if (has_alpha || has_read_screen_alpha || p_material->shader_data->depth_draw == GLES3::SceneShaderData::DEPTH_DRAW_DISABLED || p_material->shader_data->depth_test == GLES3::SceneShaderData::DEPTH_TEST_DISABLED) {
  190. //material is only meant for alpha pass
  191. flags |= GeometryInstanceSurface::FLAG_PASS_ALPHA;
  192. if (p_material->shader_data->uses_depth_prepass_alpha && !(p_material->shader_data->depth_draw == GLES3::SceneShaderData::DEPTH_DRAW_DISABLED || p_material->shader_data->depth_test == GLES3::SceneShaderData::DEPTH_TEST_DISABLED)) {
  193. flags |= GeometryInstanceSurface::FLAG_PASS_DEPTH;
  194. flags |= GeometryInstanceSurface::FLAG_PASS_SHADOW;
  195. }
  196. } else {
  197. flags |= GeometryInstanceSurface::FLAG_PASS_OPAQUE;
  198. flags |= GeometryInstanceSurface::FLAG_PASS_DEPTH;
  199. flags |= GeometryInstanceSurface::FLAG_PASS_SHADOW;
  200. }
  201. GLES3::SceneMaterialData *material_shadow = nullptr;
  202. void *surface_shadow = nullptr;
  203. if (!p_material->shader_data->uses_particle_trails && !p_material->shader_data->writes_modelview_or_projection && !p_material->shader_data->uses_vertex && !p_material->shader_data->uses_discard && !p_material->shader_data->uses_depth_prepass_alpha && !p_material->shader_data->uses_alpha_clip && !p_material->shader_data->uses_world_coordinates && !p_material->shader_data->wireframe) {
  204. flags |= GeometryInstanceSurface::FLAG_USES_SHARED_SHADOW_MATERIAL;
  205. material_shadow = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.default_material, RS::SHADER_SPATIAL));
  206. RID shadow_mesh = mesh_storage->mesh_get_shadow_mesh(p_mesh);
  207. if (shadow_mesh.is_valid()) {
  208. surface_shadow = mesh_storage->mesh_get_surface(shadow_mesh, p_surface);
  209. }
  210. } else {
  211. material_shadow = p_material;
  212. }
  213. GeometryInstanceSurface *sdcache = geometry_instance_surface_alloc.alloc();
  214. sdcache->flags = flags;
  215. sdcache->shader = p_material->shader_data;
  216. sdcache->material = p_material;
  217. sdcache->surface = mesh_storage->mesh_get_surface(p_mesh, p_surface);
  218. sdcache->primitive = mesh_storage->mesh_surface_get_primitive(sdcache->surface);
  219. sdcache->surface_index = p_surface;
  220. if (ginstance->data->dirty_dependencies) {
  221. RSG::utilities->base_update_dependency(p_mesh, &ginstance->data->dependency_tracker);
  222. }
  223. //shadow
  224. sdcache->shader_shadow = material_shadow->shader_data;
  225. sdcache->material_shadow = material_shadow;
  226. sdcache->surface_shadow = surface_shadow ? surface_shadow : sdcache->surface;
  227. sdcache->owner = ginstance;
  228. sdcache->next = ginstance->surface_caches;
  229. ginstance->surface_caches = sdcache;
  230. //sortkey
  231. sdcache->sort.sort_key1 = 0;
  232. sdcache->sort.sort_key2 = 0;
  233. sdcache->sort.surface_index = p_surface;
  234. sdcache->sort.material_id_low = p_material_id & 0x0000FFFF;
  235. sdcache->sort.material_id_hi = p_material_id >> 16;
  236. sdcache->sort.shader_id = p_shader_id;
  237. sdcache->sort.geometry_id = p_mesh.get_local_index();
  238. sdcache->sort.priority = p_material->priority;
  239. GLES3::Mesh::Surface *s = reinterpret_cast<GLES3::Mesh::Surface *>(sdcache->surface);
  240. if (p_material->shader_data->uses_tangent && !(s->format & RS::ARRAY_FORMAT_TANGENT)) {
  241. String shader_path = p_material->shader_data->path.is_empty() ? "" : "(" + p_material->shader_data->path + ")";
  242. String mesh_path = mesh_storage->mesh_get_path(p_mesh).is_empty() ? "" : "(" + mesh_storage->mesh_get_path(p_mesh) + ")";
  243. WARN_PRINT_ED(vformat("Attempting to use a shader %s that requires tangents with a mesh %s that doesn't contain tangents. Ensure that meshes are imported with the 'ensure_tangents' option. If creating your own meshes, add an `ARRAY_TANGENT` array (when using ArrayMesh) or call `generate_tangents()` (when using SurfaceTool).", shader_path, mesh_path));
  244. }
  245. }
  246. void RasterizerSceneGLES3::_geometry_instance_add_surface_with_material_chain(GeometryInstanceGLES3 *ginstance, uint32_t p_surface, GLES3::SceneMaterialData *p_material_data, RID p_mat_src, RID p_mesh) {
  247. GLES3::SceneMaterialData *material_data = p_material_data;
  248. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  249. _geometry_instance_add_surface_with_material(ginstance, p_surface, material_data, p_mat_src.get_local_index(), material_storage->material_get_shader_id(p_mat_src), p_mesh);
  250. while (material_data->next_pass.is_valid()) {
  251. RID next_pass = material_data->next_pass;
  252. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(next_pass, RS::SHADER_SPATIAL));
  253. if (!material_data || !material_data->shader_data->valid) {
  254. break;
  255. }
  256. if (ginstance->data->dirty_dependencies) {
  257. material_storage->material_update_dependency(next_pass, &ginstance->data->dependency_tracker);
  258. }
  259. _geometry_instance_add_surface_with_material(ginstance, p_surface, material_data, next_pass.get_local_index(), material_storage->material_get_shader_id(next_pass), p_mesh);
  260. }
  261. }
  262. void RasterizerSceneGLES3::_geometry_instance_add_surface(GeometryInstanceGLES3 *ginstance, uint32_t p_surface, RID p_material, RID p_mesh) {
  263. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  264. RID m_src;
  265. m_src = ginstance->data->material_override.is_valid() ? ginstance->data->material_override : p_material;
  266. GLES3::SceneMaterialData *material_data = nullptr;
  267. if (m_src.is_valid()) {
  268. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(m_src, RS::SHADER_SPATIAL));
  269. if (!material_data || !material_data->shader_data->valid) {
  270. material_data = nullptr;
  271. }
  272. }
  273. if (material_data) {
  274. if (ginstance->data->dirty_dependencies) {
  275. material_storage->material_update_dependency(m_src, &ginstance->data->dependency_tracker);
  276. }
  277. } else {
  278. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(scene_globals.default_material, RS::SHADER_SPATIAL));
  279. m_src = scene_globals.default_material;
  280. }
  281. ERR_FAIL_NULL(material_data);
  282. _geometry_instance_add_surface_with_material_chain(ginstance, p_surface, material_data, m_src, p_mesh);
  283. if (ginstance->data->material_overlay.is_valid()) {
  284. m_src = ginstance->data->material_overlay;
  285. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(m_src, RS::SHADER_SPATIAL));
  286. if (material_data && material_data->shader_data->valid) {
  287. if (ginstance->data->dirty_dependencies) {
  288. material_storage->material_update_dependency(m_src, &ginstance->data->dependency_tracker);
  289. }
  290. _geometry_instance_add_surface_with_material_chain(ginstance, p_surface, material_data, m_src, p_mesh);
  291. }
  292. }
  293. }
  294. void RasterizerSceneGLES3::_geometry_instance_update(RenderGeometryInstance *p_geometry_instance) {
  295. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  296. GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
  297. GeometryInstanceGLES3 *ginstance = static_cast<GeometryInstanceGLES3 *>(p_geometry_instance);
  298. if (ginstance->data->dirty_dependencies) {
  299. ginstance->data->dependency_tracker.update_begin();
  300. }
  301. //add geometry for drawing
  302. switch (ginstance->data->base_type) {
  303. case RS::INSTANCE_MESH: {
  304. const RID *materials = nullptr;
  305. uint32_t surface_count;
  306. RID mesh = ginstance->data->base;
  307. materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count);
  308. if (materials) {
  309. //if no materials, no surfaces.
  310. const RID *inst_materials = ginstance->data->surface_materials.ptr();
  311. uint32_t surf_mat_count = ginstance->data->surface_materials.size();
  312. for (uint32_t j = 0; j < surface_count; j++) {
  313. RID material = (j < surf_mat_count && inst_materials[j].is_valid()) ? inst_materials[j] : materials[j];
  314. _geometry_instance_add_surface(ginstance, j, material, mesh);
  315. }
  316. }
  317. ginstance->instance_count = -1;
  318. } break;
  319. case RS::INSTANCE_MULTIMESH: {
  320. RID mesh = mesh_storage->multimesh_get_mesh(ginstance->data->base);
  321. if (mesh.is_valid()) {
  322. const RID *materials = nullptr;
  323. uint32_t surface_count;
  324. materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count);
  325. if (materials) {
  326. for (uint32_t j = 0; j < surface_count; j++) {
  327. _geometry_instance_add_surface(ginstance, j, materials[j], mesh);
  328. }
  329. }
  330. ginstance->instance_count = mesh_storage->multimesh_get_instances_to_draw(ginstance->data->base);
  331. }
  332. } break;
  333. case RS::INSTANCE_PARTICLES: {
  334. int draw_passes = particles_storage->particles_get_draw_passes(ginstance->data->base);
  335. for (int j = 0; j < draw_passes; j++) {
  336. RID mesh = particles_storage->particles_get_draw_pass_mesh(ginstance->data->base, j);
  337. if (!mesh.is_valid()) {
  338. continue;
  339. }
  340. const RID *materials = nullptr;
  341. uint32_t surface_count;
  342. materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count);
  343. if (materials) {
  344. for (uint32_t k = 0; k < surface_count; k++) {
  345. _geometry_instance_add_surface(ginstance, k, materials[k], mesh);
  346. }
  347. }
  348. }
  349. ginstance->instance_count = particles_storage->particles_get_amount(ginstance->data->base);
  350. } break;
  351. default: {
  352. }
  353. }
  354. bool store_transform = true;
  355. ginstance->base_flags = 0;
  356. if (ginstance->data->base_type == RS::INSTANCE_MULTIMESH) {
  357. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH;
  358. if (mesh_storage->multimesh_get_transform_format(ginstance->data->base) == RS::MULTIMESH_TRANSFORM_2D) {
  359. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D;
  360. }
  361. if (mesh_storage->multimesh_uses_colors(ginstance->data->base)) {
  362. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR;
  363. }
  364. if (mesh_storage->multimesh_uses_custom_data(ginstance->data->base)) {
  365. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA;
  366. }
  367. } else if (ginstance->data->base_type == RS::INSTANCE_PARTICLES) {
  368. ginstance->base_flags |= INSTANCE_DATA_FLAG_PARTICLES;
  369. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH;
  370. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR;
  371. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA;
  372. if (!particles_storage->particles_is_using_local_coords(ginstance->data->base)) {
  373. store_transform = false;
  374. }
  375. } else if (ginstance->data->base_type == RS::INSTANCE_MESH) {
  376. if (mesh_storage->skeleton_is_valid(ginstance->data->skeleton)) {
  377. if (ginstance->data->dirty_dependencies) {
  378. mesh_storage->skeleton_update_dependency(ginstance->data->skeleton, &ginstance->data->dependency_tracker);
  379. }
  380. }
  381. }
  382. ginstance->store_transform_cache = store_transform;
  383. if (ginstance->data->dirty_dependencies) {
  384. ginstance->data->dependency_tracker.update_end();
  385. ginstance->data->dirty_dependencies = false;
  386. }
  387. ginstance->dirty_list_element.remove_from_list();
  388. }
  389. /* SKY API */
  390. void RasterizerSceneGLES3::_free_sky_data(Sky *p_sky) {
  391. if (p_sky->radiance != 0) {
  392. GLES3::Utilities::get_singleton()->texture_free_data(p_sky->radiance);
  393. p_sky->radiance = 0;
  394. GLES3::Utilities::get_singleton()->texture_free_data(p_sky->raw_radiance);
  395. p_sky->raw_radiance = 0;
  396. glDeleteFramebuffers(1, &p_sky->radiance_framebuffer);
  397. p_sky->radiance_framebuffer = 0;
  398. }
  399. }
  400. RID RasterizerSceneGLES3::sky_allocate() {
  401. return sky_owner.allocate_rid();
  402. }
  403. void RasterizerSceneGLES3::sky_initialize(RID p_rid) {
  404. sky_owner.initialize_rid(p_rid);
  405. }
  406. void RasterizerSceneGLES3::sky_set_radiance_size(RID p_sky, int p_radiance_size) {
  407. Sky *sky = sky_owner.get_or_null(p_sky);
  408. ERR_FAIL_NULL(sky);
  409. ERR_FAIL_COND_MSG(p_radiance_size < 32 || p_radiance_size > 2048, "Sky radiance size must be between 32 and 2048");
  410. if (sky->radiance_size == p_radiance_size) {
  411. return; // No need to update
  412. }
  413. sky->radiance_size = p_radiance_size;
  414. _free_sky_data(sky);
  415. _invalidate_sky(sky);
  416. }
  417. void RasterizerSceneGLES3::sky_set_mode(RID p_sky, RS::SkyMode p_mode) {
  418. Sky *sky = sky_owner.get_or_null(p_sky);
  419. ERR_FAIL_NULL(sky);
  420. if (sky->mode == p_mode) {
  421. return;
  422. }
  423. sky->mode = p_mode;
  424. _invalidate_sky(sky);
  425. }
  426. void RasterizerSceneGLES3::sky_set_material(RID p_sky, RID p_material) {
  427. Sky *sky = sky_owner.get_or_null(p_sky);
  428. ERR_FAIL_NULL(sky);
  429. if (sky->material == p_material) {
  430. return;
  431. }
  432. sky->material = p_material;
  433. _invalidate_sky(sky);
  434. }
  435. float RasterizerSceneGLES3::sky_get_baked_exposure(RID p_sky) const {
  436. Sky *sky = sky_owner.get_or_null(p_sky);
  437. ERR_FAIL_NULL_V(sky, 1.0);
  438. return sky->baked_exposure;
  439. }
  440. void RasterizerSceneGLES3::_invalidate_sky(Sky *p_sky) {
  441. if (!p_sky->dirty) {
  442. p_sky->dirty = true;
  443. p_sky->dirty_list = dirty_sky_list;
  444. dirty_sky_list = p_sky;
  445. }
  446. }
  447. GLuint _init_radiance_texture(int p_size, int p_mipmaps, String p_name) {
  448. GLuint radiance_id = 0;
  449. glGenTextures(1, &radiance_id);
  450. glBindTexture(GL_TEXTURE_CUBE_MAP, radiance_id);
  451. #ifdef GL_API_ENABLED
  452. if (RasterizerGLES3::is_gles_over_gl()) {
  453. //TODO, on low-end compare this to allocating each face of each mip individually
  454. // see: https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glTexStorage2D.xhtml
  455. for (int i = 0; i < 6; i++) {
  456. glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB10_A2, p_size, p_size, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, nullptr);
  457. }
  458. glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
  459. }
  460. #endif // GL_API_ENABLED
  461. #ifdef GLES_API_ENABLED
  462. if (!RasterizerGLES3::is_gles_over_gl()) {
  463. glTexStorage2D(GL_TEXTURE_CUBE_MAP, p_mipmaps, GL_RGB10_A2, p_size, p_size);
  464. }
  465. #endif // GLES_API_ENABLED
  466. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  467. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  468. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  469. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  470. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
  471. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, p_mipmaps - 1);
  472. GLES3::Utilities::get_singleton()->texture_allocated_data(radiance_id, Image::get_image_data_size(p_size, p_size, Image::FORMAT_RGBA8, true), p_name);
  473. return radiance_id;
  474. }
  475. void RasterizerSceneGLES3::_update_dirty_skys() {
  476. Sky *sky = dirty_sky_list;
  477. while (sky) {
  478. if (sky->radiance == 0) {
  479. sky->mipmap_count = Image::get_image_required_mipmaps(sky->radiance_size, sky->radiance_size, Image::FORMAT_RGBA8) - 1;
  480. // Left uninitialized, will attach a texture at render time
  481. glGenFramebuffers(1, &sky->radiance_framebuffer);
  482. sky->radiance = _init_radiance_texture(sky->radiance_size, sky->mipmap_count, "Sky radiance texture");
  483. sky->raw_radiance = _init_radiance_texture(sky->radiance_size, sky->mipmap_count, "Sky raw radiance texture");
  484. }
  485. sky->reflection_dirty = true;
  486. sky->processing_layer = 0;
  487. Sky *next = sky->dirty_list;
  488. sky->dirty_list = nullptr;
  489. sky->dirty = false;
  490. sky = next;
  491. }
  492. dirty_sky_list = nullptr;
  493. }
  494. void RasterizerSceneGLES3::_setup_sky(const RenderDataGLES3 *p_render_data, const PagedArray<RID> &p_lights, const Projection &p_projection, const Transform3D &p_transform, const Size2i p_screen_size) {
  495. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  496. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  497. ERR_FAIL_COND(p_render_data->environment.is_null());
  498. GLES3::SkyMaterialData *material = nullptr;
  499. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_render_data->environment));
  500. RID sky_material;
  501. GLES3::SkyShaderData *shader_data = nullptr;
  502. if (sky) {
  503. sky_material = sky->material;
  504. if (sky_material.is_valid()) {
  505. material = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  506. if (!material || !material->shader_data->valid) {
  507. material = nullptr;
  508. }
  509. }
  510. }
  511. if (!material) {
  512. sky_material = sky_globals.default_material;
  513. material = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  514. }
  515. ERR_FAIL_NULL(material);
  516. shader_data = material->shader_data;
  517. ERR_FAIL_NULL(shader_data);
  518. if (sky) {
  519. if (shader_data->uses_time && time - sky->prev_time > 0.00001) {
  520. sky->prev_time = time;
  521. sky->reflection_dirty = true;
  522. RenderingServerDefault::redraw_request();
  523. }
  524. if (material != sky->prev_material) {
  525. sky->prev_material = material;
  526. sky->reflection_dirty = true;
  527. }
  528. if (material->uniform_set_updated) {
  529. material->uniform_set_updated = false;
  530. sky->reflection_dirty = true;
  531. }
  532. if (!p_transform.origin.is_equal_approx(sky->prev_position) && shader_data->uses_position) {
  533. sky->prev_position = p_transform.origin;
  534. sky->reflection_dirty = true;
  535. }
  536. }
  537. glBindBufferBase(GL_UNIFORM_BUFFER, SKY_DIRECTIONAL_LIGHT_UNIFORM_LOCATION, sky_globals.directional_light_buffer);
  538. if (shader_data->uses_light) {
  539. sky_globals.directional_light_count = 0;
  540. for (int i = 0; i < (int)p_lights.size(); i++) {
  541. GLES3::LightInstance *li = GLES3::LightStorage::get_singleton()->get_light_instance(p_lights[i]);
  542. if (!li) {
  543. continue;
  544. }
  545. RID base = li->light;
  546. ERR_CONTINUE(base.is_null());
  547. RS::LightType type = light_storage->light_get_type(base);
  548. if (type == RS::LIGHT_DIRECTIONAL && light_storage->light_directional_get_sky_mode(base) != RS::LIGHT_DIRECTIONAL_SKY_MODE_LIGHT_ONLY) {
  549. DirectionalLightData &sky_light_data = sky_globals.directional_lights[sky_globals.directional_light_count];
  550. Transform3D light_transform = li->transform;
  551. Vector3 world_direction = light_transform.basis.xform(Vector3(0, 0, 1)).normalized();
  552. sky_light_data.direction[0] = world_direction.x;
  553. sky_light_data.direction[1] = world_direction.y;
  554. sky_light_data.direction[2] = world_direction.z;
  555. float sign = light_storage->light_is_negative(base) ? -1 : 1;
  556. sky_light_data.energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY);
  557. if (is_using_physical_light_units()) {
  558. sky_light_data.energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY);
  559. }
  560. if (p_render_data->camera_attributes.is_valid()) {
  561. sky_light_data.energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  562. }
  563. Color linear_col = light_storage->light_get_color(base);
  564. sky_light_data.color[0] = linear_col.r;
  565. sky_light_data.color[1] = linear_col.g;
  566. sky_light_data.color[2] = linear_col.b;
  567. sky_light_data.enabled = true;
  568. float angular_diameter = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  569. sky_light_data.size = Math::deg_to_rad(angular_diameter);
  570. sky_globals.directional_light_count++;
  571. if (sky_globals.directional_light_count >= sky_globals.max_directional_lights) {
  572. break;
  573. }
  574. }
  575. }
  576. // Check whether the directional_light_buffer changes
  577. bool light_data_dirty = false;
  578. // Light buffer is dirty if we have fewer or more lights
  579. // If we have fewer lights, make sure that old lights are disabled
  580. if (sky_globals.directional_light_count != sky_globals.last_frame_directional_light_count) {
  581. light_data_dirty = true;
  582. for (uint32_t i = sky_globals.directional_light_count; i < sky_globals.max_directional_lights; i++) {
  583. sky_globals.directional_lights[i].enabled = false;
  584. sky_globals.last_frame_directional_lights[i].enabled = false;
  585. }
  586. }
  587. if (!light_data_dirty) {
  588. for (uint32_t i = 0; i < sky_globals.directional_light_count; i++) {
  589. if (sky_globals.directional_lights[i].direction[0] != sky_globals.last_frame_directional_lights[i].direction[0] ||
  590. sky_globals.directional_lights[i].direction[1] != sky_globals.last_frame_directional_lights[i].direction[1] ||
  591. sky_globals.directional_lights[i].direction[2] != sky_globals.last_frame_directional_lights[i].direction[2] ||
  592. sky_globals.directional_lights[i].energy != sky_globals.last_frame_directional_lights[i].energy ||
  593. sky_globals.directional_lights[i].color[0] != sky_globals.last_frame_directional_lights[i].color[0] ||
  594. sky_globals.directional_lights[i].color[1] != sky_globals.last_frame_directional_lights[i].color[1] ||
  595. sky_globals.directional_lights[i].color[2] != sky_globals.last_frame_directional_lights[i].color[2] ||
  596. sky_globals.directional_lights[i].enabled != sky_globals.last_frame_directional_lights[i].enabled ||
  597. sky_globals.directional_lights[i].size != sky_globals.last_frame_directional_lights[i].size) {
  598. light_data_dirty = true;
  599. break;
  600. }
  601. }
  602. }
  603. if (light_data_dirty) {
  604. glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalLightData) * sky_globals.max_directional_lights, sky_globals.directional_lights, GL_STREAM_DRAW);
  605. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  606. DirectionalLightData *temp = sky_globals.last_frame_directional_lights;
  607. sky_globals.last_frame_directional_lights = sky_globals.directional_lights;
  608. sky_globals.directional_lights = temp;
  609. sky_globals.last_frame_directional_light_count = sky_globals.directional_light_count;
  610. if (sky) {
  611. sky->reflection_dirty = true;
  612. }
  613. }
  614. }
  615. if (p_render_data->view_count > 1) {
  616. glBindBufferBase(GL_UNIFORM_BUFFER, SKY_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  617. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  618. }
  619. if (sky && !sky->radiance) {
  620. _invalidate_sky(sky);
  621. _update_dirty_skys();
  622. }
  623. }
  624. void RasterizerSceneGLES3::_draw_sky(RID p_env, const Projection &p_projection, const Transform3D &p_transform, float p_sky_energy_multiplier, float p_luminance_multiplier, bool p_use_multiview, bool p_flip_y, bool p_apply_color_adjustments_in_post) {
  625. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  626. ERR_FAIL_COND(p_env.is_null());
  627. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_env));
  628. GLES3::SkyMaterialData *material_data = nullptr;
  629. RID sky_material;
  630. uint64_t spec_constants = p_use_multiview ? SkyShaderGLES3::USE_MULTIVIEW : 0;
  631. if (p_flip_y) {
  632. spec_constants |= SkyShaderGLES3::USE_INVERTED_Y;
  633. }
  634. if (!p_apply_color_adjustments_in_post) {
  635. spec_constants |= SkyShaderGLES3::APPLY_TONEMAPPING;
  636. }
  637. RS::EnvironmentBG background = environment_get_background(p_env);
  638. if (sky) {
  639. sky_material = sky->material;
  640. if (sky_material.is_valid()) {
  641. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  642. if (!material_data || !material_data->shader_data->valid) {
  643. material_data = nullptr;
  644. }
  645. }
  646. if (!material_data) {
  647. sky_material = sky_globals.default_material;
  648. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  649. }
  650. } else if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) {
  651. sky_material = sky_globals.fog_material;
  652. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  653. }
  654. ERR_FAIL_NULL(material_data);
  655. material_data->bind_uniforms();
  656. GLES3::SkyShaderData *shader_data = material_data->shader_data;
  657. ERR_FAIL_NULL(shader_data);
  658. // Camera
  659. Projection camera;
  660. if (environment_get_sky_custom_fov(p_env)) {
  661. float near_plane = p_projection.get_z_near();
  662. float far_plane = p_projection.get_z_far();
  663. float aspect = p_projection.get_aspect();
  664. camera.set_perspective(environment_get_sky_custom_fov(p_env), aspect, near_plane, far_plane);
  665. } else {
  666. camera = p_projection;
  667. }
  668. Projection correction;
  669. correction.set_depth_correction(false, true, false);
  670. camera = correction * camera;
  671. Basis sky_transform = environment_get_sky_orientation(p_env);
  672. sky_transform.invert();
  673. sky_transform = sky_transform * p_transform.basis;
  674. bool success = material_storage->shaders.sky_shader.version_bind_shader(shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  675. if (!success) {
  676. return;
  677. }
  678. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::ORIENTATION, sky_transform, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  679. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::PROJECTION, camera.columns[2][0], camera.columns[0][0], camera.columns[2][1], camera.columns[1][1], shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  680. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::POSITION, p_transform.origin, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  681. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::TIME, time, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  682. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::SKY_ENERGY_MULTIPLIER, p_sky_energy_multiplier, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  683. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::LUMINANCE_MULTIPLIER, p_luminance_multiplier, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  684. Color fog_color = environment_get_fog_light_color(p_env).srgb_to_linear() * environment_get_fog_light_energy(p_env);
  685. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_ENABLED, environment_get_fog_enabled(p_env), shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  686. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_AERIAL_PERSPECTIVE, environment_get_fog_aerial_perspective(p_env), shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  687. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_LIGHT_COLOR, fog_color, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  688. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_SUN_SCATTER, environment_get_fog_sun_scatter(p_env), shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  689. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_DENSITY, environment_get_fog_density(p_env), shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  690. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_SKY_AFFECT, environment_get_fog_sky_affect(p_env), shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  691. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::DIRECTIONAL_LIGHT_COUNT, sky_globals.directional_light_count, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  692. if (p_use_multiview) {
  693. glBindBufferBase(GL_UNIFORM_BUFFER, SKY_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  694. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  695. }
  696. glBindVertexArray(sky_globals.screen_triangle_array);
  697. glDrawArrays(GL_TRIANGLES, 0, 3);
  698. }
  699. void RasterizerSceneGLES3::_update_sky_radiance(RID p_env, const Projection &p_projection, const Transform3D &p_transform, float p_sky_energy_multiplier) {
  700. GLES3::CubemapFilter *cubemap_filter = GLES3::CubemapFilter::get_singleton();
  701. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  702. ERR_FAIL_COND(p_env.is_null());
  703. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_env));
  704. ERR_FAIL_NULL(sky);
  705. GLES3::SkyMaterialData *material_data = nullptr;
  706. RID sky_material;
  707. RS::EnvironmentBG background = environment_get_background(p_env);
  708. if (sky) {
  709. ERR_FAIL_NULL(sky);
  710. sky_material = sky->material;
  711. if (sky_material.is_valid()) {
  712. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  713. if (!material_data || !material_data->shader_data->valid) {
  714. material_data = nullptr;
  715. }
  716. }
  717. if (!material_data) {
  718. sky_material = sky_globals.default_material;
  719. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  720. }
  721. } else if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) {
  722. sky_material = sky_globals.fog_material;
  723. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  724. }
  725. ERR_FAIL_NULL(material_data);
  726. material_data->bind_uniforms();
  727. GLES3::SkyShaderData *shader_data = material_data->shader_data;
  728. ERR_FAIL_NULL(shader_data);
  729. bool update_single_frame = sky->mode == RS::SKY_MODE_REALTIME || sky->mode == RS::SKY_MODE_QUALITY;
  730. RS::SkyMode sky_mode = sky->mode;
  731. if (sky_mode == RS::SKY_MODE_AUTOMATIC) {
  732. if ((shader_data->uses_time || shader_data->uses_position) && sky->radiance_size == 256) {
  733. update_single_frame = true;
  734. sky_mode = RS::SKY_MODE_REALTIME;
  735. } else if (shader_data->uses_light || shader_data->ubo_size > 0) {
  736. update_single_frame = false;
  737. sky_mode = RS::SKY_MODE_INCREMENTAL;
  738. } else {
  739. update_single_frame = true;
  740. sky_mode = RS::SKY_MODE_QUALITY;
  741. }
  742. }
  743. if (sky->processing_layer == 0 && sky_mode == RS::SKY_MODE_INCREMENTAL) {
  744. // On the first frame after creating sky, rebuild in single frame
  745. update_single_frame = true;
  746. sky_mode = RS::SKY_MODE_QUALITY;
  747. }
  748. int max_processing_layer = sky->mipmap_count;
  749. // Update radiance cubemap
  750. if (sky->reflection_dirty && (sky->processing_layer >= max_processing_layer || update_single_frame)) {
  751. static const Vector3 view_normals[6] = {
  752. Vector3(+1, 0, 0),
  753. Vector3(-1, 0, 0),
  754. Vector3(0, +1, 0),
  755. Vector3(0, -1, 0),
  756. Vector3(0, 0, +1),
  757. Vector3(0, 0, -1)
  758. };
  759. static const Vector3 view_up[6] = {
  760. Vector3(0, -1, 0),
  761. Vector3(0, -1, 0),
  762. Vector3(0, 0, +1),
  763. Vector3(0, 0, -1),
  764. Vector3(0, -1, 0),
  765. Vector3(0, -1, 0)
  766. };
  767. Projection cm;
  768. cm.set_perspective(90, 1, 0.01, 10.0);
  769. Projection correction;
  770. correction.set_depth_correction(true, true, false);
  771. cm = correction * cm;
  772. bool success = material_storage->shaders.sky_shader.version_bind_shader(shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  773. if (!success) {
  774. return;
  775. }
  776. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::POSITION, p_transform.origin, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  777. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::TIME, time, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  778. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::PROJECTION, cm.columns[2][0], cm.columns[0][0], cm.columns[2][1], cm.columns[1][1], shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  779. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::SKY_ENERGY_MULTIPLIER, p_sky_energy_multiplier, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  780. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::LUMINANCE_MULTIPLIER, 1.0, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  781. glBindVertexArray(sky_globals.screen_triangle_array);
  782. glViewport(0, 0, sky->radiance_size, sky->radiance_size);
  783. glBindFramebuffer(GL_FRAMEBUFFER, sky->radiance_framebuffer);
  784. scene_state.reset_gl_state();
  785. scene_state.set_gl_cull_mode(RS::CULL_MODE_DISABLED);
  786. scene_state.enable_gl_blend(false);
  787. for (int i = 0; i < 6; i++) {
  788. Basis local_view = Basis::looking_at(view_normals[i], view_up[i]);
  789. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::ORIENTATION, local_view, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  790. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, sky->raw_radiance, 0);
  791. glDrawArrays(GL_TRIANGLES, 0, 3);
  792. }
  793. if (update_single_frame) {
  794. for (int i = 0; i < max_processing_layer; i++) {
  795. cubemap_filter->filter_radiance(sky->raw_radiance, sky->radiance, sky->radiance_framebuffer, sky->radiance_size, sky->mipmap_count, i);
  796. }
  797. } else {
  798. cubemap_filter->filter_radiance(sky->raw_radiance, sky->radiance, sky->radiance_framebuffer, sky->radiance_size, sky->mipmap_count, 0); // Just copy over the first mipmap.
  799. }
  800. sky->processing_layer = 1;
  801. sky->baked_exposure = p_sky_energy_multiplier;
  802. sky->reflection_dirty = false;
  803. } else {
  804. if (sky_mode == RS::SKY_MODE_INCREMENTAL && sky->processing_layer < max_processing_layer) {
  805. scene_state.reset_gl_state();
  806. scene_state.set_gl_cull_mode(RS::CULL_MODE_DISABLED);
  807. scene_state.enable_gl_blend(false);
  808. cubemap_filter->filter_radiance(sky->raw_radiance, sky->radiance, sky->radiance_framebuffer, sky->radiance_size, sky->mipmap_count, sky->processing_layer);
  809. sky->processing_layer++;
  810. }
  811. }
  812. glViewport(0, 0, sky->screen_size.x, sky->screen_size.y);
  813. }
  814. Ref<Image> RasterizerSceneGLES3::sky_bake_panorama(RID p_sky, float p_energy, bool p_bake_irradiance, const Size2i &p_size) {
  815. Sky *sky = sky_owner.get_or_null(p_sky);
  816. ERR_FAIL_NULL_V(sky, Ref<Image>());
  817. _update_dirty_skys();
  818. if (sky->radiance == 0) {
  819. return Ref<Image>();
  820. }
  821. GLES3::CopyEffects *copy_effects = GLES3::CopyEffects::get_singleton();
  822. GLES3::Config *config = GLES3::Config::get_singleton();
  823. GLuint rad_tex = 0;
  824. glGenTextures(1, &rad_tex);
  825. glBindTexture(GL_TEXTURE_2D, rad_tex);
  826. if (config->float_texture_supported) {
  827. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, p_size.width, p_size.height, 0, GL_RGBA, GL_FLOAT, nullptr);
  828. GLES3::Utilities::get_singleton()->texture_allocated_data(rad_tex, p_size.width * p_size.height * 16, "Temp sky panorama");
  829. } else {
  830. // Fallback to RGBA8 on devices that don't support rendering to floating point textures. This will look bad, but we have no choice.
  831. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, p_size.width, p_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  832. GLES3::Utilities::get_singleton()->texture_allocated_data(rad_tex, p_size.width * p_size.height * 4, "Temp sky panorama");
  833. }
  834. GLuint rad_fbo = 0;
  835. glGenFramebuffers(1, &rad_fbo);
  836. glBindFramebuffer(GL_FRAMEBUFFER, rad_fbo);
  837. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rad_tex, 0);
  838. glActiveTexture(GL_TEXTURE0);
  839. glBindTexture(GL_TEXTURE_CUBE_MAP, sky->radiance);
  840. glViewport(0, 0, p_size.width, p_size.height);
  841. glClearColor(0.0, 0.0, 0.0, 1.0);
  842. glClear(GL_COLOR_BUFFER_BIT);
  843. copy_effects->copy_cube_to_panorama(p_bake_irradiance ? float(sky->mipmap_count) : 0.0);
  844. glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
  845. glDeleteFramebuffers(1, &rad_fbo);
  846. // Create a dummy texture so we can use texture_2d_get.
  847. RID tex_rid = GLES3::TextureStorage::get_singleton()->texture_allocate();
  848. GLES3::Texture texture;
  849. texture.width = p_size.width;
  850. texture.height = p_size.height;
  851. texture.alloc_width = p_size.width;
  852. texture.alloc_height = p_size.height;
  853. texture.format = Image::FORMAT_RGBAF;
  854. texture.real_format = Image::FORMAT_RGBAF;
  855. texture.gl_format_cache = GL_RGBA;
  856. texture.gl_type_cache = GL_FLOAT;
  857. texture.type = GLES3::Texture::TYPE_2D;
  858. texture.target = GL_TEXTURE_2D;
  859. texture.active = true;
  860. texture.tex_id = rad_tex;
  861. texture.is_render_target = true;
  862. GLES3::TextureStorage::get_singleton()->texture_2d_initialize_from_texture(tex_rid, texture);
  863. Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid);
  864. GLES3::Utilities::get_singleton()->texture_free_data(rad_tex);
  865. texture.is_render_target = false;
  866. texture.tex_id = 0;
  867. GLES3::TextureStorage::get_singleton()->texture_free(tex_rid);
  868. for (int i = 0; i < p_size.width; i++) {
  869. for (int j = 0; j < p_size.height; j++) {
  870. Color c = img->get_pixel(i, j);
  871. c.r *= p_energy;
  872. c.g *= p_energy;
  873. c.b *= p_energy;
  874. img->set_pixel(i, j, c);
  875. }
  876. }
  877. return img;
  878. }
  879. /* ENVIRONMENT API */
  880. void RasterizerSceneGLES3::environment_glow_set_use_bicubic_upscale(bool p_enable) {
  881. glow_bicubic_upscale = p_enable;
  882. }
  883. void RasterizerSceneGLES3::environment_set_ssr_roughness_quality(RS::EnvironmentSSRRoughnessQuality p_quality) {
  884. }
  885. void RasterizerSceneGLES3::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) {
  886. }
  887. void RasterizerSceneGLES3::environment_set_ssil_quality(RS::EnvironmentSSILQuality p_quality, bool p_half_size, float p_adaptive_target, int p_blur_passes, float p_fadeout_from, float p_fadeout_to) {
  888. }
  889. void RasterizerSceneGLES3::environment_set_sdfgi_ray_count(RS::EnvironmentSDFGIRayCount p_ray_count) {
  890. }
  891. void RasterizerSceneGLES3::environment_set_sdfgi_frames_to_converge(RS::EnvironmentSDFGIFramesToConverge p_frames) {
  892. }
  893. void RasterizerSceneGLES3::environment_set_sdfgi_frames_to_update_light(RS::EnvironmentSDFGIFramesToUpdateLight p_update) {
  894. }
  895. void RasterizerSceneGLES3::environment_set_volumetric_fog_volume_size(int p_size, int p_depth) {
  896. }
  897. void RasterizerSceneGLES3::environment_set_volumetric_fog_filter_active(bool p_enable) {
  898. }
  899. Ref<Image> RasterizerSceneGLES3::environment_bake_panorama(RID p_env, bool p_bake_irradiance, const Size2i &p_size) {
  900. ERR_FAIL_COND_V(p_env.is_null(), Ref<Image>());
  901. RS::EnvironmentBG environment_background = environment_get_background(p_env);
  902. if (environment_background == RS::ENV_BG_CAMERA_FEED || environment_background == RS::ENV_BG_CANVAS || environment_background == RS::ENV_BG_KEEP) {
  903. return Ref<Image>(); // Nothing to bake.
  904. }
  905. RS::EnvironmentAmbientSource ambient_source = environment_get_ambient_source(p_env);
  906. bool use_ambient_light = false;
  907. bool use_cube_map = false;
  908. if (ambient_source == RS::ENV_AMBIENT_SOURCE_BG && (environment_background == RS::ENV_BG_CLEAR_COLOR || environment_background == RS::ENV_BG_COLOR)) {
  909. use_ambient_light = true;
  910. } else {
  911. use_cube_map = (ambient_source == RS::ENV_AMBIENT_SOURCE_BG && environment_background == RS::ENV_BG_SKY) || ambient_source == RS::ENV_AMBIENT_SOURCE_SKY;
  912. use_ambient_light = use_cube_map || ambient_source == RS::ENV_AMBIENT_SOURCE_COLOR;
  913. }
  914. use_cube_map = use_cube_map || (environment_background == RS::ENV_BG_SKY && environment_get_sky(p_env).is_valid());
  915. Color ambient_color;
  916. float ambient_color_sky_mix = 0.0;
  917. if (use_ambient_light) {
  918. ambient_color_sky_mix = environment_get_ambient_sky_contribution(p_env);
  919. const float ambient_energy = environment_get_ambient_light_energy(p_env);
  920. ambient_color = environment_get_ambient_light(p_env);
  921. ambient_color = ambient_color.srgb_to_linear();
  922. ambient_color.r *= ambient_energy;
  923. ambient_color.g *= ambient_energy;
  924. ambient_color.b *= ambient_energy;
  925. }
  926. if (use_cube_map) {
  927. Ref<Image> panorama = sky_bake_panorama(environment_get_sky(p_env), environment_get_bg_energy_multiplier(p_env), p_bake_irradiance, p_size);
  928. if (use_ambient_light) {
  929. for (int x = 0; x < p_size.width; x++) {
  930. for (int y = 0; y < p_size.height; y++) {
  931. panorama->set_pixel(x, y, ambient_color.lerp(panorama->get_pixel(x, y), ambient_color_sky_mix));
  932. }
  933. }
  934. }
  935. return panorama;
  936. } else {
  937. const float bg_energy_multiplier = environment_get_bg_energy_multiplier(p_env);
  938. Color panorama_color = ((environment_background == RS::ENV_BG_CLEAR_COLOR) ? RSG::texture_storage->get_default_clear_color() : environment_get_bg_color(p_env));
  939. panorama_color = panorama_color.srgb_to_linear();
  940. panorama_color.r *= bg_energy_multiplier;
  941. panorama_color.g *= bg_energy_multiplier;
  942. panorama_color.b *= bg_energy_multiplier;
  943. if (use_ambient_light) {
  944. panorama_color = ambient_color.lerp(panorama_color, ambient_color_sky_mix);
  945. }
  946. Ref<Image> panorama = Image::create_empty(p_size.width, p_size.height, false, Image::FORMAT_RGBAF);
  947. panorama->fill(panorama_color);
  948. return panorama;
  949. }
  950. }
  951. void RasterizerSceneGLES3::positional_soft_shadow_filter_set_quality(RS::ShadowQuality p_quality) {
  952. scene_state.positional_shadow_quality = p_quality;
  953. }
  954. void RasterizerSceneGLES3::directional_soft_shadow_filter_set_quality(RS::ShadowQuality p_quality) {
  955. scene_state.directional_shadow_quality = p_quality;
  956. }
  957. RID RasterizerSceneGLES3::fog_volume_instance_create(RID p_fog_volume) {
  958. return RID();
  959. }
  960. void RasterizerSceneGLES3::fog_volume_instance_set_transform(RID p_fog_volume_instance, const Transform3D &p_transform) {
  961. }
  962. void RasterizerSceneGLES3::fog_volume_instance_set_active(RID p_fog_volume_instance, bool p_active) {
  963. }
  964. RID RasterizerSceneGLES3::fog_volume_instance_get_volume(RID p_fog_volume_instance) const {
  965. return RID();
  966. }
  967. Vector3 RasterizerSceneGLES3::fog_volume_instance_get_position(RID p_fog_volume_instance) const {
  968. return Vector3();
  969. }
  970. RID RasterizerSceneGLES3::voxel_gi_instance_create(RID p_voxel_gi) {
  971. return RID();
  972. }
  973. void RasterizerSceneGLES3::voxel_gi_instance_set_transform_to_data(RID p_probe, const Transform3D &p_xform) {
  974. }
  975. bool RasterizerSceneGLES3::voxel_gi_needs_update(RID p_probe) const {
  976. return false;
  977. }
  978. void RasterizerSceneGLES3::voxel_gi_update(RID p_probe, bool p_update_light_instances, const Vector<RID> &p_light_instances, const PagedArray<RenderGeometryInstance *> &p_dynamic_objects) {
  979. }
  980. void RasterizerSceneGLES3::voxel_gi_set_quality(RS::VoxelGIQuality) {
  981. }
  982. _FORCE_INLINE_ static uint32_t _indices_to_primitives(RS::PrimitiveType p_primitive, uint32_t p_indices) {
  983. static const uint32_t divisor[RS::PRIMITIVE_MAX] = { 1, 2, 1, 3, 1 };
  984. static const uint32_t subtractor[RS::PRIMITIVE_MAX] = { 0, 0, 1, 0, 2 };
  985. return (p_indices - subtractor[p_primitive]) / divisor[p_primitive];
  986. }
  987. void RasterizerSceneGLES3::_fill_render_list(RenderListType p_render_list, const RenderDataGLES3 *p_render_data, PassMode p_pass_mode, bool p_append) {
  988. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  989. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  990. if (p_render_list == RENDER_LIST_OPAQUE) {
  991. scene_state.used_screen_texture = false;
  992. scene_state.used_normal_texture = false;
  993. scene_state.used_depth_texture = false;
  994. }
  995. Plane near_plane;
  996. if (p_render_data->cam_orthogonal) {
  997. near_plane = Plane(-p_render_data->cam_transform.basis.get_column(Vector3::AXIS_Z), p_render_data->cam_transform.origin);
  998. near_plane.d += p_render_data->cam_projection.get_z_near();
  999. }
  1000. float z_max = p_render_data->cam_projection.get_z_far() - p_render_data->cam_projection.get_z_near();
  1001. RenderList *rl = &render_list[p_render_list];
  1002. // Parse any updates on our geometry, updates surface caches and such
  1003. _update_dirty_geometry_instances();
  1004. if (!p_append) {
  1005. rl->clear();
  1006. if (p_render_list == RENDER_LIST_OPAQUE) {
  1007. render_list[RENDER_LIST_ALPHA].clear(); //opaque fills alpha too
  1008. }
  1009. }
  1010. //fill list
  1011. for (int i = 0; i < (int)p_render_data->instances->size(); i++) {
  1012. GeometryInstanceGLES3 *inst = static_cast<GeometryInstanceGLES3 *>((*p_render_data->instances)[i]);
  1013. Vector3 center = inst->transform.origin;
  1014. if (p_render_data->cam_orthogonal) {
  1015. if (inst->use_aabb_center) {
  1016. center = inst->transformed_aabb.get_support(-near_plane.normal);
  1017. }
  1018. inst->depth = near_plane.distance_to(center) - inst->sorting_offset;
  1019. } else {
  1020. if (inst->use_aabb_center) {
  1021. center = inst->transformed_aabb.position + (inst->transformed_aabb.size * 0.5);
  1022. }
  1023. inst->depth = p_render_data->cam_transform.origin.distance_to(center) - inst->sorting_offset;
  1024. }
  1025. uint32_t depth_layer = CLAMP(int(inst->depth * 16 / z_max), 0, 15);
  1026. uint32_t flags = inst->base_flags; //fill flags if appropriate
  1027. if (inst->non_uniform_scale) {
  1028. flags |= INSTANCE_DATA_FLAGS_NON_UNIFORM_SCALE;
  1029. }
  1030. // Sets the index values for lookup in the shader
  1031. // This has to be done after _setup_lights was called this frame
  1032. if (p_pass_mode == PASS_MODE_COLOR) {
  1033. inst->light_passes.clear();
  1034. inst->spot_light_gl_cache.clear();
  1035. inst->omni_light_gl_cache.clear();
  1036. inst->reflection_probes_local_transform_cache.clear();
  1037. inst->reflection_probe_rid_cache.clear();
  1038. uint64_t current_frame = RSG::rasterizer->get_frame_number();
  1039. if (inst->paired_omni_light_count) {
  1040. for (uint32_t j = 0; j < inst->paired_omni_light_count; j++) {
  1041. RID light_instance = inst->paired_omni_lights[j];
  1042. if (light_storage->light_instance_get_render_pass(light_instance) != current_frame) {
  1043. continue;
  1044. }
  1045. RID light = light_storage->light_instance_get_base_light(light_instance);
  1046. int32_t shadow_id = light_storage->light_instance_get_shadow_id(light_instance);
  1047. if (light_storage->light_has_shadow(light) && shadow_id >= 0) {
  1048. GeometryInstanceGLES3::LightPass pass;
  1049. pass.light_id = light_storage->light_instance_get_gl_id(light_instance);
  1050. pass.shadow_id = shadow_id;
  1051. pass.light_instance_rid = light_instance;
  1052. pass.is_omni = true;
  1053. inst->light_passes.push_back(pass);
  1054. } else {
  1055. // Lights without shadow can all go in base pass.
  1056. inst->omni_light_gl_cache.push_back((uint32_t)light_storage->light_instance_get_gl_id(light_instance));
  1057. }
  1058. }
  1059. }
  1060. if (inst->paired_spot_light_count) {
  1061. for (uint32_t j = 0; j < inst->paired_spot_light_count; j++) {
  1062. RID light_instance = inst->paired_spot_lights[j];
  1063. if (light_storage->light_instance_get_render_pass(light_instance) != current_frame) {
  1064. continue;
  1065. }
  1066. RID light = light_storage->light_instance_get_base_light(light_instance);
  1067. int32_t shadow_id = light_storage->light_instance_get_shadow_id(light_instance);
  1068. if (light_storage->light_has_shadow(light) && shadow_id >= 0) {
  1069. GeometryInstanceGLES3::LightPass pass;
  1070. pass.light_id = light_storage->light_instance_get_gl_id(light_instance);
  1071. pass.shadow_id = shadow_id;
  1072. pass.light_instance_rid = light_instance;
  1073. inst->light_passes.push_back(pass);
  1074. } else {
  1075. // Lights without shadow can all go in base pass.
  1076. inst->spot_light_gl_cache.push_back((uint32_t)light_storage->light_instance_get_gl_id(light_instance));
  1077. }
  1078. }
  1079. }
  1080. if (p_render_data->reflection_probe.is_null() && inst->paired_reflection_probes.size() > 0) {
  1081. // Do not include if we're rendering reflection probes.
  1082. // We only support two probes for now and we handle them first come, first serve.
  1083. // This should be improved one day, at minimum the list should be sorted by priority.
  1084. for (uint32_t pi = 0; pi < inst->paired_reflection_probes.size(); pi++) {
  1085. RID probe_instance = inst->paired_reflection_probes[pi];
  1086. RID atlas = light_storage->reflection_probe_instance_get_atlas(probe_instance);
  1087. RID probe = light_storage->reflection_probe_instance_get_probe(probe_instance);
  1088. uint32_t reflection_mask = light_storage->reflection_probe_get_reflection_mask(probe);
  1089. if (atlas.is_valid() && (inst->layer_mask & reflection_mask)) {
  1090. Transform3D local_matrix = p_render_data->inv_cam_transform * light_storage->reflection_probe_instance_get_transform(probe_instance);
  1091. inst->reflection_probes_local_transform_cache.push_back(local_matrix.affine_inverse());
  1092. inst->reflection_probe_rid_cache.push_back(probe_instance);
  1093. }
  1094. }
  1095. }
  1096. }
  1097. inst->flags_cache = flags;
  1098. GeometryInstanceSurface *surf = inst->surface_caches;
  1099. float lod_distance = 0.0;
  1100. if (p_render_data->cam_orthogonal) {
  1101. lod_distance = 1.0;
  1102. } else {
  1103. Vector3 aabb_min = inst->transformed_aabb.position;
  1104. Vector3 aabb_max = inst->transformed_aabb.position + inst->transformed_aabb.size;
  1105. Vector3 camera_position = p_render_data->main_cam_transform.origin;
  1106. Vector3 surface_distance = Vector3(0.0, 0.0, 0.0).max(aabb_min - camera_position).max(camera_position - aabb_max);
  1107. lod_distance = surface_distance.length();
  1108. }
  1109. while (surf) {
  1110. // LOD
  1111. if (p_render_data->screen_mesh_lod_threshold > 0.0 && mesh_storage->mesh_surface_has_lod(surf->surface)) {
  1112. uint32_t indices = 0;
  1113. surf->lod_index = mesh_storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, lod_distance * p_render_data->lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, indices);
  1114. surf->index_count = indices;
  1115. if (p_render_data->render_info) {
  1116. indices = _indices_to_primitives(surf->primitive, indices);
  1117. if (p_render_list == RENDER_LIST_OPAQUE) { //opaque
  1118. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += indices;
  1119. } else if (p_render_list == RENDER_LIST_SECONDARY) { //shadow
  1120. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_SHADOW][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += indices;
  1121. }
  1122. }
  1123. } else {
  1124. surf->lod_index = 0;
  1125. if (p_render_data->render_info) {
  1126. uint32_t to_draw = mesh_storage->mesh_surface_get_vertices_drawn_count(surf->surface);
  1127. to_draw = _indices_to_primitives(surf->primitive, to_draw);
  1128. to_draw *= inst->instance_count > 0 ? inst->instance_count : 1;
  1129. if (p_render_list == RENDER_LIST_OPAQUE) { //opaque
  1130. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += to_draw;
  1131. } else if (p_render_list == RENDER_LIST_SECONDARY) { //shadow
  1132. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_SHADOW][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += to_draw;
  1133. }
  1134. }
  1135. }
  1136. // ADD Element
  1137. if (p_pass_mode == PASS_MODE_COLOR) {
  1138. #ifdef DEBUG_ENABLED
  1139. bool force_alpha = unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW);
  1140. #else
  1141. bool force_alpha = false;
  1142. #endif
  1143. if (!force_alpha && (surf->flags & (GeometryInstanceSurface::FLAG_PASS_DEPTH | GeometryInstanceSurface::FLAG_PASS_OPAQUE))) {
  1144. rl->add_element(surf);
  1145. }
  1146. if (force_alpha || (surf->flags & GeometryInstanceSurface::FLAG_PASS_ALPHA)) {
  1147. render_list[RENDER_LIST_ALPHA].add_element(surf);
  1148. }
  1149. if (surf->flags & GeometryInstanceSurface::FLAG_USES_SCREEN_TEXTURE) {
  1150. scene_state.used_screen_texture = true;
  1151. }
  1152. if (surf->flags & GeometryInstanceSurface::FLAG_USES_NORMAL_TEXTURE) {
  1153. scene_state.used_normal_texture = true;
  1154. }
  1155. if (surf->flags & GeometryInstanceSurface::FLAG_USES_DEPTH_TEXTURE) {
  1156. scene_state.used_depth_texture = true;
  1157. }
  1158. } else if (p_pass_mode == PASS_MODE_SHADOW) {
  1159. if (surf->flags & GeometryInstanceSurface::FLAG_PASS_SHADOW) {
  1160. rl->add_element(surf);
  1161. }
  1162. } else if (p_pass_mode == PASS_MODE_MATERIAL) {
  1163. if (surf->flags & (GeometryInstanceSurface::FLAG_PASS_DEPTH | GeometryInstanceSurface::FLAG_PASS_OPAQUE | GeometryInstanceSurface::FLAG_PASS_ALPHA)) {
  1164. rl->add_element(surf);
  1165. }
  1166. } else {
  1167. if (surf->flags & (GeometryInstanceSurface::FLAG_PASS_DEPTH | GeometryInstanceSurface::FLAG_PASS_OPAQUE)) {
  1168. rl->add_element(surf);
  1169. }
  1170. }
  1171. surf->sort.depth_layer = depth_layer;
  1172. surf->finished_base_pass = false;
  1173. surf->light_pass_index = 0;
  1174. surf = surf->next;
  1175. }
  1176. }
  1177. }
  1178. // Needs to be called after _setup_lights so that directional_light_count is accurate.
  1179. void RasterizerSceneGLES3::_setup_environment(const RenderDataGLES3 *p_render_data, bool p_no_fog, const Size2i &p_screen_size, bool p_flip_y, const Color &p_default_bg_color, bool p_pancake_shadows, float p_shadow_bias) {
  1180. Projection correction;
  1181. correction.set_depth_correction(p_flip_y, true, false);
  1182. Projection projection = correction * p_render_data->cam_projection;
  1183. //store camera into ubo
  1184. GLES3::MaterialStorage::store_camera(projection, scene_state.ubo.projection_matrix);
  1185. GLES3::MaterialStorage::store_camera(projection.inverse(), scene_state.ubo.inv_projection_matrix);
  1186. GLES3::MaterialStorage::store_transform(p_render_data->cam_transform, scene_state.ubo.inv_view_matrix);
  1187. GLES3::MaterialStorage::store_transform(p_render_data->inv_cam_transform, scene_state.ubo.view_matrix);
  1188. GLES3::MaterialStorage::store_transform(p_render_data->main_cam_transform, scene_state.ubo.main_cam_inv_view_matrix);
  1189. scene_state.ubo.camera_visible_layers = p_render_data->camera_visible_layers;
  1190. if (p_render_data->view_count > 1) {
  1191. for (uint32_t v = 0; v < p_render_data->view_count; v++) {
  1192. projection = correction * p_render_data->view_projection[v];
  1193. GLES3::MaterialStorage::store_camera(projection, scene_state.multiview_ubo.projection_matrix_view[v]);
  1194. GLES3::MaterialStorage::store_camera(projection.inverse(), scene_state.multiview_ubo.inv_projection_matrix_view[v]);
  1195. scene_state.multiview_ubo.eye_offset[v][0] = p_render_data->view_eye_offset[v].x;
  1196. scene_state.multiview_ubo.eye_offset[v][1] = p_render_data->view_eye_offset[v].y;
  1197. scene_state.multiview_ubo.eye_offset[v][2] = p_render_data->view_eye_offset[v].z;
  1198. scene_state.multiview_ubo.eye_offset[v][3] = 0.0;
  1199. }
  1200. }
  1201. // Only render the lights without shadows in the base pass.
  1202. scene_state.ubo.directional_light_count = p_render_data->directional_light_count - p_render_data->directional_shadow_count;
  1203. scene_state.ubo.z_far = p_render_data->z_far;
  1204. scene_state.ubo.z_near = p_render_data->z_near;
  1205. scene_state.ubo.viewport_size[0] = p_screen_size.x;
  1206. scene_state.ubo.viewport_size[1] = p_screen_size.y;
  1207. Size2 screen_pixel_size = Vector2(1.0, 1.0) / Size2(p_screen_size);
  1208. scene_state.ubo.screen_pixel_size[0] = screen_pixel_size.x;
  1209. scene_state.ubo.screen_pixel_size[1] = screen_pixel_size.y;
  1210. scene_state.ubo.luminance_multiplier = p_render_data->luminance_multiplier;
  1211. scene_state.ubo.shadow_bias = p_shadow_bias;
  1212. scene_state.ubo.pancake_shadows = p_pancake_shadows;
  1213. //time global variables
  1214. scene_state.ubo.time = time;
  1215. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
  1216. scene_state.ubo.use_ambient_light = true;
  1217. scene_state.ubo.ambient_light_color_energy[0] = 1;
  1218. scene_state.ubo.ambient_light_color_energy[1] = 1;
  1219. scene_state.ubo.ambient_light_color_energy[2] = 1;
  1220. scene_state.ubo.ambient_light_color_energy[3] = 1.0;
  1221. scene_state.ubo.use_ambient_cubemap = false;
  1222. scene_state.ubo.use_reflection_cubemap = false;
  1223. } else if (is_environment(p_render_data->environment)) {
  1224. RS::EnvironmentBG env_bg = environment_get_background(p_render_data->environment);
  1225. RS::EnvironmentAmbientSource ambient_src = environment_get_ambient_source(p_render_data->environment);
  1226. float bg_energy_multiplier = environment_get_bg_energy_multiplier(p_render_data->environment);
  1227. scene_state.ubo.ambient_light_color_energy[3] = bg_energy_multiplier;
  1228. scene_state.ubo.ambient_color_sky_mix = environment_get_ambient_sky_contribution(p_render_data->environment);
  1229. //ambient
  1230. if (ambient_src == RS::ENV_AMBIENT_SOURCE_BG && (env_bg == RS::ENV_BG_CLEAR_COLOR || env_bg == RS::ENV_BG_COLOR)) {
  1231. Color color = env_bg == RS::ENV_BG_CLEAR_COLOR ? p_default_bg_color : environment_get_bg_color(p_render_data->environment);
  1232. color = color.srgb_to_linear();
  1233. scene_state.ubo.ambient_light_color_energy[0] = color.r * bg_energy_multiplier;
  1234. scene_state.ubo.ambient_light_color_energy[1] = color.g * bg_energy_multiplier;
  1235. scene_state.ubo.ambient_light_color_energy[2] = color.b * bg_energy_multiplier;
  1236. scene_state.ubo.use_ambient_light = true;
  1237. scene_state.ubo.use_ambient_cubemap = false;
  1238. } else {
  1239. float energy = environment_get_ambient_light_energy(p_render_data->environment);
  1240. Color color = environment_get_ambient_light(p_render_data->environment);
  1241. color = color.srgb_to_linear();
  1242. scene_state.ubo.ambient_light_color_energy[0] = color.r * energy;
  1243. scene_state.ubo.ambient_light_color_energy[1] = color.g * energy;
  1244. scene_state.ubo.ambient_light_color_energy[2] = color.b * energy;
  1245. Basis sky_transform = environment_get_sky_orientation(p_render_data->environment);
  1246. sky_transform = sky_transform.inverse() * p_render_data->cam_transform.basis;
  1247. GLES3::MaterialStorage::store_transform_3x3(sky_transform, scene_state.ubo.radiance_inverse_xform);
  1248. scene_state.ubo.use_ambient_cubemap = (ambient_src == RS::ENV_AMBIENT_SOURCE_BG && env_bg == RS::ENV_BG_SKY) || ambient_src == RS::ENV_AMBIENT_SOURCE_SKY;
  1249. scene_state.ubo.use_ambient_light = scene_state.ubo.use_ambient_cubemap || ambient_src == RS::ENV_AMBIENT_SOURCE_COLOR;
  1250. }
  1251. //specular
  1252. RS::EnvironmentReflectionSource ref_src = environment_get_reflection_source(p_render_data->environment);
  1253. if ((ref_src == RS::ENV_REFLECTION_SOURCE_BG && env_bg == RS::ENV_BG_SKY) || ref_src == RS::ENV_REFLECTION_SOURCE_SKY) {
  1254. scene_state.ubo.use_reflection_cubemap = true;
  1255. } else {
  1256. scene_state.ubo.use_reflection_cubemap = false;
  1257. }
  1258. scene_state.ubo.fog_enabled = environment_get_fog_enabled(p_render_data->environment);
  1259. scene_state.ubo.fog_mode = environment_get_fog_mode(p_render_data->environment);
  1260. scene_state.ubo.fog_density = environment_get_fog_density(p_render_data->environment);
  1261. scene_state.ubo.fog_height = environment_get_fog_height(p_render_data->environment);
  1262. scene_state.ubo.fog_depth_curve = environment_get_fog_depth_curve(p_render_data->environment);
  1263. scene_state.ubo.fog_depth_end = environment_get_fog_depth_end(p_render_data->environment) > 0.0 ? environment_get_fog_depth_end(p_render_data->environment) : scene_state.ubo.z_far;
  1264. scene_state.ubo.fog_depth_begin = MIN(environment_get_fog_depth_begin(p_render_data->environment), scene_state.ubo.fog_depth_end - 0.001);
  1265. scene_state.ubo.fog_height_density = environment_get_fog_height_density(p_render_data->environment);
  1266. scene_state.ubo.fog_aerial_perspective = environment_get_fog_aerial_perspective(p_render_data->environment);
  1267. Color fog_color = environment_get_fog_light_color(p_render_data->environment).srgb_to_linear();
  1268. float fog_energy = environment_get_fog_light_energy(p_render_data->environment);
  1269. scene_state.ubo.fog_light_color[0] = fog_color.r * fog_energy;
  1270. scene_state.ubo.fog_light_color[1] = fog_color.g * fog_energy;
  1271. scene_state.ubo.fog_light_color[2] = fog_color.b * fog_energy;
  1272. scene_state.ubo.fog_sun_scatter = environment_get_fog_sun_scatter(p_render_data->environment);
  1273. } else {
  1274. }
  1275. if (p_render_data->camera_attributes.is_valid()) {
  1276. scene_state.ubo.emissive_exposure_normalization = RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  1277. scene_state.ubo.IBL_exposure_normalization = 1.0;
  1278. if (is_environment(p_render_data->environment)) {
  1279. RID sky_rid = environment_get_sky(p_render_data->environment);
  1280. if (sky_rid.is_valid()) {
  1281. float current_exposure = RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes) * environment_get_bg_intensity(p_render_data->environment);
  1282. scene_state.ubo.IBL_exposure_normalization = current_exposure / MAX(0.001, sky_get_baked_exposure(sky_rid));
  1283. }
  1284. }
  1285. } else if (scene_state.ubo.emissive_exposure_normalization > 0.0) {
  1286. // This branch is triggered when using render_material().
  1287. // Emissive is set outside the function, so don't set it.
  1288. // IBL isn't used don't set it.
  1289. } else {
  1290. scene_state.ubo.emissive_exposure_normalization = 1.0;
  1291. scene_state.ubo.IBL_exposure_normalization = 1.0;
  1292. }
  1293. if (scene_state.ubo_buffer == 0) {
  1294. glGenBuffers(1, &scene_state.ubo_buffer);
  1295. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DATA_UNIFORM_LOCATION, scene_state.ubo_buffer);
  1296. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.ubo_buffer, sizeof(SceneState::UBO), &scene_state.ubo, GL_STREAM_DRAW, "Scene state UBO");
  1297. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1298. } else {
  1299. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DATA_UNIFORM_LOCATION, scene_state.ubo_buffer);
  1300. glBufferData(GL_UNIFORM_BUFFER, sizeof(SceneState::UBO), &scene_state.ubo, GL_STREAM_DRAW);
  1301. }
  1302. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1303. if (p_render_data->view_count > 1) {
  1304. if (scene_state.multiview_buffer == 0) {
  1305. glGenBuffers(1, &scene_state.multiview_buffer);
  1306. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  1307. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.multiview_buffer, sizeof(SceneState::MultiviewUBO), &scene_state.multiview_ubo, GL_STREAM_DRAW, "Multiview UBO");
  1308. } else {
  1309. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  1310. glBufferData(GL_UNIFORM_BUFFER, sizeof(SceneState::MultiviewUBO), &scene_state.multiview_ubo, GL_STREAM_DRAW);
  1311. }
  1312. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1313. }
  1314. }
  1315. // Puts lights into Uniform Buffers. Needs to be called before _fill_list as this caches the index of each light in the Uniform Buffer
  1316. void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, bool p_using_shadows, uint32_t &r_directional_light_count, uint32_t &r_omni_light_count, uint32_t &r_spot_light_count, uint32_t &r_directional_shadow_count) {
  1317. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  1318. GLES3::Config *config = GLES3::Config::get_singleton();
  1319. const Transform3D inverse_transform = p_render_data->inv_cam_transform;
  1320. const PagedArray<RID> &lights = *p_render_data->lights;
  1321. r_directional_light_count = 0;
  1322. r_omni_light_count = 0;
  1323. r_spot_light_count = 0;
  1324. r_directional_shadow_count = 0;
  1325. int num_lights = lights.size();
  1326. for (int i = 0; i < num_lights; i++) {
  1327. GLES3::LightInstance *li = GLES3::LightStorage::get_singleton()->get_light_instance(lights[i]);
  1328. if (!li) {
  1329. continue;
  1330. }
  1331. RID base = li->light;
  1332. ERR_CONTINUE(base.is_null());
  1333. RS::LightType type = light_storage->light_get_type(base);
  1334. switch (type) {
  1335. case RS::LIGHT_DIRECTIONAL: {
  1336. if (r_directional_light_count >= RendererSceneRender::MAX_DIRECTIONAL_LIGHTS || light_storage->light_directional_get_sky_mode(base) == RS::LIGHT_DIRECTIONAL_SKY_MODE_SKY_ONLY) {
  1337. continue;
  1338. }
  1339. // If a DirectionalLight has shadows, we will add it to the end of the array and work in.
  1340. bool has_shadow = light_storage->light_has_shadow(base);
  1341. int index = r_directional_light_count - r_directional_shadow_count;
  1342. if (has_shadow) {
  1343. // Lights with shadow are incremented from the end of the array.
  1344. index = MAX_DIRECTIONAL_LIGHTS - 1 - r_directional_shadow_count;
  1345. }
  1346. DirectionalLightData &light_data = scene_state.directional_lights[index];
  1347. Transform3D light_transform = li->transform;
  1348. Vector3 direction = inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, 1))).normalized();
  1349. light_data.direction[0] = direction.x;
  1350. light_data.direction[1] = direction.y;
  1351. light_data.direction[2] = direction.z;
  1352. light_data.bake_mode = light_storage->light_get_bake_mode(base);
  1353. float sign = light_storage->light_is_negative(base) ? -1 : 1;
  1354. light_data.energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY);
  1355. if (is_using_physical_light_units()) {
  1356. light_data.energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY);
  1357. } else {
  1358. light_data.energy *= Math_PI;
  1359. }
  1360. if (p_render_data->camera_attributes.is_valid()) {
  1361. light_data.energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  1362. }
  1363. Color linear_col = light_storage->light_get_color(base).srgb_to_linear();
  1364. light_data.color[0] = linear_col.r;
  1365. light_data.color[1] = linear_col.g;
  1366. light_data.color[2] = linear_col.b;
  1367. float size = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  1368. light_data.size = 1.0 - Math::cos(Math::deg_to_rad(size)); //angle to cosine offset
  1369. light_data.specular = light_storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR);
  1370. light_data.shadow_opacity = (p_using_shadows && light_storage->light_has_shadow(base))
  1371. ? light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_OPACITY)
  1372. : 0.0;
  1373. if (has_shadow) {
  1374. DirectionalShadowData &shadow_data = scene_state.directional_shadows[MAX_DIRECTIONAL_LIGHTS - 1 - r_directional_shadow_count];
  1375. RS::LightDirectionalShadowMode shadow_mode = light_storage->light_directional_get_shadow_mode(base);
  1376. int limit = shadow_mode == RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL ? 0 : (shadow_mode == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS ? 1 : 3);
  1377. shadow_data.shadow_atlas_pixel_size = 1.0 / light_storage->directional_shadow_get_size();
  1378. shadow_data.blend_splits = uint32_t((shadow_mode != RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL) && light_storage->light_directional_get_blend_splits(base));
  1379. for (int j = 0; j < 4; j++) {
  1380. Rect2 atlas_rect = li->shadow_transform[j].atlas_rect;
  1381. Projection correction;
  1382. correction.set_depth_correction(false, true, false);
  1383. Projection matrix = correction * li->shadow_transform[j].camera;
  1384. float split = li->shadow_transform[MIN(limit, j)].split;
  1385. Projection bias;
  1386. bias.set_light_bias();
  1387. Projection rectm;
  1388. rectm.set_light_atlas_rect(atlas_rect);
  1389. Transform3D modelview = (inverse_transform * li->shadow_transform[j].transform).inverse();
  1390. shadow_data.direction[0] = light_data.direction[0];
  1391. shadow_data.direction[1] = light_data.direction[1];
  1392. shadow_data.direction[2] = light_data.direction[2];
  1393. Projection shadow_mtx = rectm * bias * matrix * modelview;
  1394. shadow_data.shadow_split_offsets[j] = split;
  1395. shadow_data.shadow_normal_bias[j] = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * li->shadow_transform[j].shadow_texel_size;
  1396. GLES3::MaterialStorage::store_camera(shadow_mtx, shadow_data.shadow_matrices[j]);
  1397. }
  1398. float fade_start = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_FADE_START);
  1399. shadow_data.fade_from = -shadow_data.shadow_split_offsets[3] * MIN(fade_start, 0.999);
  1400. shadow_data.fade_to = -shadow_data.shadow_split_offsets[3];
  1401. r_directional_shadow_count++;
  1402. }
  1403. r_directional_light_count++;
  1404. } break;
  1405. case RS::LIGHT_OMNI: {
  1406. if (r_omni_light_count >= (uint32_t)config->max_renderable_lights) {
  1407. continue;
  1408. }
  1409. const real_t distance = p_render_data->cam_transform.origin.distance_to(li->transform.origin);
  1410. if (light_storage->light_is_distance_fade_enabled(li->light)) {
  1411. const float fade_begin = light_storage->light_get_distance_fade_begin(li->light);
  1412. const float fade_length = light_storage->light_get_distance_fade_length(li->light);
  1413. if (distance > fade_begin) {
  1414. if (distance > fade_begin + fade_length) {
  1415. // Out of range, don't draw this light to improve performance.
  1416. continue;
  1417. }
  1418. }
  1419. }
  1420. scene_state.omni_light_sort[r_omni_light_count].instance = li;
  1421. scene_state.omni_light_sort[r_omni_light_count].depth = distance;
  1422. r_omni_light_count++;
  1423. } break;
  1424. case RS::LIGHT_SPOT: {
  1425. if (r_spot_light_count >= (uint32_t)config->max_renderable_lights) {
  1426. continue;
  1427. }
  1428. const real_t distance = p_render_data->cam_transform.origin.distance_to(li->transform.origin);
  1429. if (light_storage->light_is_distance_fade_enabled(li->light)) {
  1430. const float fade_begin = light_storage->light_get_distance_fade_begin(li->light);
  1431. const float fade_length = light_storage->light_get_distance_fade_length(li->light);
  1432. if (distance > fade_begin) {
  1433. if (distance > fade_begin + fade_length) {
  1434. // Out of range, don't draw this light to improve performance.
  1435. continue;
  1436. }
  1437. }
  1438. }
  1439. scene_state.spot_light_sort[r_spot_light_count].instance = li;
  1440. scene_state.spot_light_sort[r_spot_light_count].depth = distance;
  1441. r_spot_light_count++;
  1442. } break;
  1443. }
  1444. li->last_pass = RSG::rasterizer->get_frame_number();
  1445. }
  1446. if (r_omni_light_count) {
  1447. SortArray<InstanceSort<GLES3::LightInstance>> sorter;
  1448. sorter.sort(scene_state.omni_light_sort, r_omni_light_count);
  1449. }
  1450. if (r_spot_light_count) {
  1451. SortArray<InstanceSort<GLES3::LightInstance>> sorter;
  1452. sorter.sort(scene_state.spot_light_sort, r_spot_light_count);
  1453. }
  1454. int num_positional_shadows = 0;
  1455. for (uint32_t i = 0; i < (r_omni_light_count + r_spot_light_count); i++) {
  1456. uint32_t index = (i < r_omni_light_count) ? i : i - (r_omni_light_count);
  1457. LightData &light_data = (i < r_omni_light_count) ? scene_state.omni_lights[index] : scene_state.spot_lights[index];
  1458. RS::LightType type = (i < r_omni_light_count) ? RS::LIGHT_OMNI : RS::LIGHT_SPOT;
  1459. GLES3::LightInstance *li = (i < r_omni_light_count) ? scene_state.omni_light_sort[index].instance : scene_state.spot_light_sort[index].instance;
  1460. real_t distance = (i < r_omni_light_count) ? scene_state.omni_light_sort[index].depth : scene_state.spot_light_sort[index].depth;
  1461. RID base = li->light;
  1462. li->gl_id = index;
  1463. Transform3D light_transform = li->transform;
  1464. Vector3 pos = inverse_transform.xform(light_transform.origin);
  1465. light_data.position[0] = pos.x;
  1466. light_data.position[1] = pos.y;
  1467. light_data.position[2] = pos.z;
  1468. light_data.bake_mode = light_storage->light_get_bake_mode(base);
  1469. float radius = MAX(0.001, light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE));
  1470. light_data.inv_radius = 1.0 / radius;
  1471. Vector3 direction = inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, -1))).normalized();
  1472. light_data.direction[0] = direction.x;
  1473. light_data.direction[1] = direction.y;
  1474. light_data.direction[2] = direction.z;
  1475. float size = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  1476. light_data.size = size;
  1477. float sign = light_storage->light_is_negative(base) ? -1 : 1;
  1478. Color linear_col = light_storage->light_get_color(base).srgb_to_linear();
  1479. // Reuse fade begin, fade length and distance for shadow LOD determination later.
  1480. float fade_begin = 0.0;
  1481. float fade_shadow = 0.0;
  1482. float fade_length = 0.0;
  1483. float fade = 1.0;
  1484. float shadow_opacity_fade = 1.0;
  1485. if (light_storage->light_is_distance_fade_enabled(base)) {
  1486. fade_begin = light_storage->light_get_distance_fade_begin(base);
  1487. fade_shadow = light_storage->light_get_distance_fade_shadow(base);
  1488. fade_length = light_storage->light_get_distance_fade_length(base);
  1489. if (distance > fade_begin) {
  1490. // Use `smoothstep()` to make opacity changes more gradual and less noticeable to the player.
  1491. fade = Math::smoothstep(0.0f, 1.0f, 1.0f - float(distance - fade_begin) / fade_length);
  1492. }
  1493. if (distance > fade_shadow) {
  1494. shadow_opacity_fade = Math::smoothstep(0.0f, 1.0f, 1.0f - float(distance - fade_shadow) / fade_length);
  1495. }
  1496. }
  1497. float energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY) * fade;
  1498. if (is_using_physical_light_units()) {
  1499. energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY);
  1500. // Convert from Luminous Power to Luminous Intensity
  1501. if (type == RS::LIGHT_OMNI) {
  1502. energy *= 1.0 / (Math_PI * 4.0);
  1503. } else {
  1504. // Spot Lights are not physically accurate, Luminous Intensity should change in relation to the cone angle.
  1505. // We make this assumption to keep them easy to control.
  1506. energy *= 1.0 / Math_PI;
  1507. }
  1508. } else {
  1509. energy *= Math_PI;
  1510. }
  1511. if (p_render_data->camera_attributes.is_valid()) {
  1512. energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  1513. }
  1514. light_data.color[0] = linear_col.r * energy;
  1515. light_data.color[1] = linear_col.g * energy;
  1516. light_data.color[2] = linear_col.b * energy;
  1517. light_data.attenuation = light_storage->light_get_param(base, RS::LIGHT_PARAM_ATTENUATION);
  1518. light_data.inv_spot_attenuation = 1.0f / light_storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  1519. float spot_angle = light_storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ANGLE);
  1520. light_data.cos_spot_angle = Math::cos(Math::deg_to_rad(spot_angle));
  1521. light_data.specular_amount = light_storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR) * 2.0;
  1522. // Setup shadows
  1523. const bool needs_shadow =
  1524. p_using_shadows &&
  1525. light_storage->owns_shadow_atlas(p_render_data->shadow_atlas) &&
  1526. light_storage->shadow_atlas_owns_light_instance(p_render_data->shadow_atlas, li->self) &&
  1527. light_storage->light_has_shadow(base);
  1528. bool in_shadow_range = true;
  1529. if (needs_shadow && light_storage->light_is_distance_fade_enabled(base)) {
  1530. if (distance > fade_shadow + fade_length) {
  1531. // Out of range, don't draw shadows to improve performance.
  1532. in_shadow_range = false;
  1533. }
  1534. }
  1535. // Fill in the shadow information.
  1536. if (needs_shadow && in_shadow_range) {
  1537. if (num_positional_shadows >= config->max_renderable_lights) {
  1538. continue;
  1539. }
  1540. ShadowData &shadow_data = scene_state.positional_shadows[num_positional_shadows];
  1541. li->shadow_id = num_positional_shadows;
  1542. num_positional_shadows++;
  1543. light_data.shadow_opacity = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_OPACITY) * shadow_opacity_fade;
  1544. float shadow_texel_size = light_storage->light_instance_get_shadow_texel_size(li->self, p_render_data->shadow_atlas);
  1545. shadow_data.shadow_atlas_pixel_size = shadow_texel_size;
  1546. shadow_data.shadow_normal_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * shadow_texel_size * 10.0;
  1547. shadow_data.light_position[0] = light_data.position[0];
  1548. shadow_data.light_position[1] = light_data.position[1];
  1549. shadow_data.light_position[2] = light_data.position[2];
  1550. if (type == RS::LIGHT_OMNI) {
  1551. Transform3D proj = (inverse_transform * light_transform).inverse();
  1552. GLES3::MaterialStorage::store_transform(proj, shadow_data.shadow_matrix);
  1553. } else if (type == RS::LIGHT_SPOT) {
  1554. Transform3D modelview = (inverse_transform * light_transform).inverse();
  1555. Projection bias;
  1556. bias.set_light_bias();
  1557. Projection correction;
  1558. correction.set_depth_correction(false, true, false);
  1559. Projection cm = correction * li->shadow_transform[0].camera;
  1560. Projection shadow_mtx = bias * cm * modelview;
  1561. GLES3::MaterialStorage::store_camera(shadow_mtx, shadow_data.shadow_matrix);
  1562. }
  1563. }
  1564. }
  1565. // TODO, to avoid stalls, should rotate between 3 buffers based on frame index.
  1566. // TODO, consider mapping the buffer as in 2D
  1567. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_OMNILIGHT_UNIFORM_LOCATION, scene_state.omni_light_buffer);
  1568. if (r_omni_light_count) {
  1569. glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightData) * r_omni_light_count, scene_state.omni_lights);
  1570. }
  1571. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_SPOTLIGHT_UNIFORM_LOCATION, scene_state.spot_light_buffer);
  1572. if (r_spot_light_count) {
  1573. glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightData) * r_spot_light_count, scene_state.spot_lights);
  1574. }
  1575. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DIRECTIONAL_LIGHT_UNIFORM_LOCATION, scene_state.directional_light_buffer);
  1576. if (r_directional_light_count) {
  1577. glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalLightData) * MAX_DIRECTIONAL_LIGHTS, scene_state.directional_lights, GL_STREAM_DRAW);
  1578. }
  1579. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_POSITIONAL_SHADOW_UNIFORM_LOCATION, scene_state.positional_shadow_buffer);
  1580. if (num_positional_shadows) {
  1581. glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(ShadowData) * num_positional_shadows, scene_state.positional_shadows);
  1582. }
  1583. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DIRECTIONAL_SHADOW_UNIFORM_LOCATION, scene_state.directional_shadow_buffer);
  1584. if (r_directional_shadow_count) {
  1585. glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalShadowData) * MAX_DIRECTIONAL_LIGHTS, scene_state.directional_shadows, GL_STREAM_DRAW);
  1586. }
  1587. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1588. }
  1589. // Render shadows
  1590. void RasterizerSceneGLES3::_render_shadows(const RenderDataGLES3 *p_render_data, const Size2i &p_viewport_size) {
  1591. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  1592. LocalVector<int> cube_shadows;
  1593. LocalVector<int> shadows;
  1594. LocalVector<int> directional_shadows;
  1595. float lod_distance_multiplier = p_render_data->cam_projection.get_lod_multiplier();
  1596. // Put lights into buckets for omni (cube shadows), directional, and spot.
  1597. {
  1598. for (int i = 0; i < p_render_data->render_shadow_count; i++) {
  1599. RID li = p_render_data->render_shadows[i].light;
  1600. RID base = light_storage->light_instance_get_base_light(li);
  1601. if (light_storage->light_get_type(base) == RS::LIGHT_DIRECTIONAL) {
  1602. directional_shadows.push_back(i);
  1603. } else if (light_storage->light_get_type(base) == RS::LIGHT_OMNI && light_storage->light_omni_get_shadow_mode(base) == RS::LIGHT_OMNI_SHADOW_CUBE) {
  1604. cube_shadows.push_back(i);
  1605. } else {
  1606. shadows.push_back(i);
  1607. }
  1608. }
  1609. if (directional_shadows.size()) {
  1610. light_storage->update_directional_shadow_atlas();
  1611. }
  1612. }
  1613. bool render_shadows = directional_shadows.size() || shadows.size() || cube_shadows.size();
  1614. if (render_shadows) {
  1615. RENDER_TIMESTAMP("Render Shadows");
  1616. // Render cubemap shadows.
  1617. for (const int &index : cube_shadows) {
  1618. _render_shadow_pass(p_render_data->render_shadows[index].light, p_render_data->shadow_atlas, p_render_data->render_shadows[index].pass, p_render_data->render_shadows[index].instances, lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, p_render_data->render_info, p_viewport_size, p_render_data->cam_transform);
  1619. }
  1620. // Render directional shadows.
  1621. for (uint32_t i = 0; i < directional_shadows.size(); i++) {
  1622. _render_shadow_pass(p_render_data->render_shadows[directional_shadows[i]].light, p_render_data->shadow_atlas, p_render_data->render_shadows[directional_shadows[i]].pass, p_render_data->render_shadows[directional_shadows[i]].instances, lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, p_render_data->render_info, p_viewport_size, p_render_data->cam_transform);
  1623. }
  1624. // Render positional shadows (Spotlight and Omnilight with dual-paraboloid).
  1625. for (uint32_t i = 0; i < shadows.size(); i++) {
  1626. _render_shadow_pass(p_render_data->render_shadows[shadows[i]].light, p_render_data->shadow_atlas, p_render_data->render_shadows[shadows[i]].pass, p_render_data->render_shadows[shadows[i]].instances, lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, p_render_data->render_info, p_viewport_size, p_render_data->cam_transform);
  1627. }
  1628. }
  1629. }
  1630. void RasterizerSceneGLES3::_render_shadow_pass(RID p_light, RID p_shadow_atlas, int p_pass, const PagedArray<RenderGeometryInstance *> &p_instances, float p_lod_distance_multiplier, float p_screen_mesh_lod_threshold, RenderingMethod::RenderInfo *p_render_info, const Size2i &p_viewport_size, const Transform3D &p_main_cam_transform) {
  1631. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  1632. ERR_FAIL_COND(!light_storage->owns_light_instance(p_light));
  1633. RID base = light_storage->light_instance_get_base_light(p_light);
  1634. float zfar = 0.0;
  1635. bool use_pancake = false;
  1636. float shadow_bias = 0.0;
  1637. bool reverse_cull = false;
  1638. bool needs_clear = false;
  1639. Projection light_projection;
  1640. Transform3D light_transform;
  1641. GLuint shadow_fb = 0;
  1642. Rect2i atlas_rect;
  1643. if (light_storage->light_get_type(base) == RS::LIGHT_DIRECTIONAL) {
  1644. // Set pssm stuff.
  1645. uint64_t last_scene_shadow_pass = light_storage->light_instance_get_shadow_pass(p_light);
  1646. if (last_scene_shadow_pass != get_scene_pass()) {
  1647. light_storage->light_instance_set_directional_rect(p_light, light_storage->get_directional_shadow_rect());
  1648. light_storage->directional_shadow_increase_current_light();
  1649. light_storage->light_instance_set_shadow_pass(p_light, get_scene_pass());
  1650. }
  1651. atlas_rect = light_storage->light_instance_get_directional_rect(p_light);
  1652. if (light_storage->light_directional_get_shadow_mode(base) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
  1653. atlas_rect.size.width /= 2;
  1654. atlas_rect.size.height /= 2;
  1655. if (p_pass == 1) {
  1656. atlas_rect.position.x += atlas_rect.size.width;
  1657. } else if (p_pass == 2) {
  1658. atlas_rect.position.y += atlas_rect.size.height;
  1659. } else if (p_pass == 3) {
  1660. atlas_rect.position += atlas_rect.size;
  1661. }
  1662. } else if (light_storage->light_directional_get_shadow_mode(base) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
  1663. atlas_rect.size.height /= 2;
  1664. if (p_pass == 0) {
  1665. } else {
  1666. atlas_rect.position.y += atlas_rect.size.height;
  1667. }
  1668. }
  1669. use_pancake = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE) > 0;
  1670. light_projection = light_storage->light_instance_get_shadow_camera(p_light, p_pass);
  1671. light_transform = light_storage->light_instance_get_shadow_transform(p_light, p_pass);
  1672. float directional_shadow_size = light_storage->directional_shadow_get_size();
  1673. Rect2 atlas_rect_norm = atlas_rect;
  1674. atlas_rect_norm.position /= directional_shadow_size;
  1675. atlas_rect_norm.size /= directional_shadow_size;
  1676. light_storage->light_instance_set_directional_shadow_atlas_rect(p_light, p_pass, atlas_rect_norm);
  1677. zfar = RSG::light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE);
  1678. shadow_fb = light_storage->direction_shadow_get_fb();
  1679. reverse_cull = !light_storage->light_get_reverse_cull_face_mode(base);
  1680. float bias_scale = light_storage->light_instance_get_shadow_bias_scale(p_light, p_pass);
  1681. shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) / 100.0 * bias_scale;
  1682. } else {
  1683. // Set from shadow atlas.
  1684. ERR_FAIL_COND(!light_storage->owns_shadow_atlas(p_shadow_atlas));
  1685. ERR_FAIL_COND(!light_storage->shadow_atlas_owns_light_instance(p_shadow_atlas, p_light));
  1686. uint32_t key = light_storage->shadow_atlas_get_light_instance_key(p_shadow_atlas, p_light);
  1687. uint32_t quadrant = (key >> GLES3::LightStorage::QUADRANT_SHIFT) & 0x3;
  1688. uint32_t shadow = key & GLES3::LightStorage::SHADOW_INDEX_MASK;
  1689. ERR_FAIL_INDEX((int)shadow, light_storage->shadow_atlas_get_quadrant_shadows_length(p_shadow_atlas, quadrant));
  1690. int shadow_size = light_storage->shadow_atlas_get_quadrant_shadow_size(p_shadow_atlas, quadrant);
  1691. shadow_fb = light_storage->shadow_atlas_get_quadrant_shadow_fb(p_shadow_atlas, quadrant, shadow);
  1692. zfar = light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE);
  1693. reverse_cull = !light_storage->light_get_reverse_cull_face_mode(base);
  1694. if (light_storage->light_get_type(base) == RS::LIGHT_OMNI) {
  1695. if (light_storage->light_omni_get_shadow_mode(base) == RS::LIGHT_OMNI_SHADOW_CUBE) {
  1696. GLuint shadow_texture = light_storage->shadow_atlas_get_quadrant_shadow_texture(p_shadow_atlas, quadrant, shadow);
  1697. glBindFramebuffer(GL_FRAMEBUFFER, shadow_fb);
  1698. static GLenum cube_map_faces[6] = {
  1699. GL_TEXTURE_CUBE_MAP_POSITIVE_X,
  1700. GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
  1701. // Flipped order for Y to match what the RD renderer expects
  1702. // (and thus what is given to us by the Rendering Server).
  1703. GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
  1704. GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
  1705. GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
  1706. GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
  1707. };
  1708. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, cube_map_faces[p_pass], shadow_texture, 0);
  1709. light_projection = light_storage->light_instance_get_shadow_camera(p_light, p_pass);
  1710. light_transform = light_storage->light_instance_get_shadow_transform(p_light, p_pass);
  1711. shadow_size = shadow_size / 2;
  1712. } else {
  1713. ERR_FAIL_MSG("Dual paraboloid shadow mode not supported in the Compatibility renderer. Please use CubeMap shadow mode instead.");
  1714. }
  1715. shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS);
  1716. } else if (light_storage->light_get_type(base) == RS::LIGHT_SPOT) {
  1717. light_projection = light_storage->light_instance_get_shadow_camera(p_light, 0);
  1718. light_transform = light_storage->light_instance_get_shadow_transform(p_light, 0);
  1719. shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) / 10.0;
  1720. // Prebake range into bias so we can scale based on distance easily.
  1721. shadow_bias *= light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE);
  1722. }
  1723. atlas_rect.size.x = shadow_size;
  1724. atlas_rect.size.y = shadow_size;
  1725. needs_clear = true;
  1726. }
  1727. RenderDataGLES3 render_data;
  1728. render_data.cam_projection = light_projection;
  1729. render_data.cam_transform = light_transform;
  1730. render_data.inv_cam_transform = light_transform.affine_inverse();
  1731. render_data.z_far = zfar; // Only used by OmniLights.
  1732. render_data.z_near = 0.0;
  1733. render_data.lod_distance_multiplier = p_lod_distance_multiplier;
  1734. render_data.main_cam_transform = p_main_cam_transform;
  1735. render_data.instances = &p_instances;
  1736. render_data.render_info = p_render_info;
  1737. _setup_environment(&render_data, true, p_viewport_size, false, Color(), use_pancake, shadow_bias);
  1738. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_DISABLE_LOD) {
  1739. render_data.screen_mesh_lod_threshold = 0.0;
  1740. } else {
  1741. render_data.screen_mesh_lod_threshold = p_screen_mesh_lod_threshold;
  1742. }
  1743. _fill_render_list(RENDER_LIST_SECONDARY, &render_data, PASS_MODE_SHADOW);
  1744. render_list[RENDER_LIST_SECONDARY].sort_by_key();
  1745. glBindFramebuffer(GL_FRAMEBUFFER, shadow_fb);
  1746. glViewport(atlas_rect.position.x, atlas_rect.position.y, atlas_rect.size.x, atlas_rect.size.y);
  1747. GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer();
  1748. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer);
  1749. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1750. scene_state.reset_gl_state();
  1751. scene_state.enable_gl_depth_test(true);
  1752. scene_state.enable_gl_depth_draw(true);
  1753. glDepthFunc(GL_GREATER);
  1754. glColorMask(0, 0, 0, 0);
  1755. glDrawBuffers(0, nullptr);
  1756. RasterizerGLES3::clear_depth(0.0);
  1757. if (needs_clear) {
  1758. glClear(GL_DEPTH_BUFFER_BIT);
  1759. }
  1760. uint64_t spec_constant_base_flags = SceneShaderGLES3::DISABLE_LIGHTMAP |
  1761. SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL |
  1762. SceneShaderGLES3::DISABLE_LIGHT_OMNI |
  1763. SceneShaderGLES3::DISABLE_LIGHT_SPOT |
  1764. SceneShaderGLES3::DISABLE_FOG |
  1765. SceneShaderGLES3::RENDER_SHADOWS;
  1766. if (light_storage->light_get_type(base) == RS::LIGHT_OMNI) {
  1767. spec_constant_base_flags |= SceneShaderGLES3::RENDER_SHADOWS_LINEAR;
  1768. }
  1769. RenderListParameters render_list_params(render_list[RENDER_LIST_SECONDARY].elements.ptr(), render_list[RENDER_LIST_SECONDARY].elements.size(), reverse_cull, spec_constant_base_flags, false);
  1770. _render_list_template<PASS_MODE_SHADOW>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size());
  1771. glColorMask(1, 1, 1, 1);
  1772. scene_state.enable_gl_depth_test(false);
  1773. scene_state.enable_gl_depth_draw(true);
  1774. glDisable(GL_CULL_FACE);
  1775. scene_state.cull_mode = RS::CULL_MODE_DISABLED;
  1776. glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
  1777. }
  1778. void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_buffers, const CameraData *p_camera_data, const CameraData *p_prev_camera_data, const PagedArray<RenderGeometryInstance *> &p_instances, const PagedArray<RID> &p_lights, const PagedArray<RID> &p_reflection_probes, const PagedArray<RID> &p_voxel_gi_instances, const PagedArray<RID> &p_decals, const PagedArray<RID> &p_lightmaps, const PagedArray<RID> &p_fog_volumes, RID p_environment, RID p_camera_attributes, RID p_compositor, RID p_shadow_atlas, RID p_occluder_debug_tex, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_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, RenderingMethod::RenderInfo *r_render_info) {
  1779. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  1780. GLES3::Config *config = GLES3::Config::get_singleton();
  1781. RENDER_TIMESTAMP("Setup 3D Scene");
  1782. bool apply_color_adjustments_in_post = false;
  1783. bool is_reflection_probe = p_reflection_probe.is_valid();
  1784. Ref<RenderSceneBuffersGLES3> rb = p_render_buffers;
  1785. ERR_FAIL_COND(rb.is_null());
  1786. if (rb->get_scaling_3d_mode() != RS::VIEWPORT_SCALING_3D_MODE_OFF) {
  1787. // If we're scaling, we apply tonemapping etc. in post, so disable it during rendering
  1788. apply_color_adjustments_in_post = true;
  1789. }
  1790. GLES3::RenderTarget *rt = nullptr; // No render target for reflection probe
  1791. if (!is_reflection_probe) {
  1792. rt = texture_storage->get_render_target(rb->render_target);
  1793. ERR_FAIL_NULL(rt);
  1794. }
  1795. bool glow_enabled = false;
  1796. if (p_environment.is_valid()) {
  1797. glow_enabled = environment_get_glow_enabled(p_environment);
  1798. if (glow_enabled) {
  1799. // If glow is enabled, we apply tonemapping etc. in post, so disable it during rendering
  1800. apply_color_adjustments_in_post = true;
  1801. }
  1802. }
  1803. // Assign render data
  1804. // Use the format from rendererRD
  1805. RenderDataGLES3 render_data;
  1806. {
  1807. render_data.render_buffers = rb;
  1808. if (rt) {
  1809. render_data.transparent_bg = rt->is_transparent;
  1810. render_data.render_region = rt->render_region;
  1811. }
  1812. // Our first camera is used by default
  1813. render_data.cam_transform = p_camera_data->main_transform;
  1814. render_data.inv_cam_transform = render_data.cam_transform.affine_inverse();
  1815. render_data.cam_projection = p_camera_data->main_projection;
  1816. render_data.cam_orthogonal = p_camera_data->is_orthogonal;
  1817. render_data.cam_frustum = p_camera_data->is_frustum;
  1818. render_data.camera_visible_layers = p_camera_data->visible_layers;
  1819. render_data.main_cam_transform = p_camera_data->main_transform;
  1820. render_data.view_count = p_camera_data->view_count;
  1821. for (uint32_t v = 0; v < p_camera_data->view_count; v++) {
  1822. render_data.view_eye_offset[v] = p_camera_data->view_offset[v].origin;
  1823. render_data.view_projection[v] = p_camera_data->view_projection[v];
  1824. }
  1825. render_data.z_near = p_camera_data->main_projection.get_z_near();
  1826. render_data.z_far = p_camera_data->main_projection.get_z_far();
  1827. render_data.instances = &p_instances;
  1828. render_data.lights = &p_lights;
  1829. render_data.reflection_probes = &p_reflection_probes;
  1830. render_data.environment = p_environment;
  1831. render_data.camera_attributes = p_camera_attributes;
  1832. render_data.shadow_atlas = p_shadow_atlas;
  1833. render_data.reflection_probe = p_reflection_probe;
  1834. render_data.reflection_probe_pass = p_reflection_probe_pass;
  1835. // this should be the same for all cameras..
  1836. render_data.lod_distance_multiplier = p_camera_data->main_projection.get_lod_multiplier();
  1837. if (rt != nullptr && rt->color_type == GL_UNSIGNED_INT_2_10_10_10_REV && glow_enabled) {
  1838. // As our output is in sRGB and we're using 10bit color space, we can fake a little HDR to do glow...
  1839. render_data.luminance_multiplier = 0.25;
  1840. } else {
  1841. render_data.luminance_multiplier = 1.0;
  1842. }
  1843. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_DISABLE_LOD) {
  1844. render_data.screen_mesh_lod_threshold = 0.0;
  1845. } else {
  1846. render_data.screen_mesh_lod_threshold = p_screen_mesh_lod_threshold;
  1847. }
  1848. render_data.render_info = r_render_info;
  1849. render_data.render_shadows = p_render_shadows;
  1850. render_data.render_shadow_count = p_render_shadow_count;
  1851. }
  1852. PagedArray<RID> empty;
  1853. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
  1854. render_data.lights = &empty;
  1855. render_data.reflection_probes = &empty;
  1856. }
  1857. bool reverse_cull = render_data.cam_transform.basis.determinant() < 0;
  1858. ///////////
  1859. // Fill Light lists here
  1860. //////////
  1861. GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer();
  1862. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer);
  1863. Color clear_color;
  1864. if (!is_reflection_probe && rb->render_target.is_valid()) {
  1865. clear_color = texture_storage->render_target_get_clear_request_color(rb->render_target);
  1866. } else {
  1867. clear_color = texture_storage->get_default_clear_color();
  1868. }
  1869. bool fb_cleared = false;
  1870. Size2i screen_size = rb->internal_size;
  1871. bool use_wireframe = get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME;
  1872. SceneState::TonemapUBO tonemap_ubo;
  1873. if (render_data.environment.is_valid()) {
  1874. bool use_bcs = environment_get_adjustments_enabled(render_data.environment);
  1875. if (use_bcs) {
  1876. apply_color_adjustments_in_post = true;
  1877. }
  1878. tonemap_ubo.exposure = environment_get_exposure(render_data.environment);
  1879. tonemap_ubo.white = environment_get_white(render_data.environment);
  1880. tonemap_ubo.tonemapper = int32_t(environment_get_tone_mapper(render_data.environment));
  1881. tonemap_ubo.brightness = environment_get_adjustments_brightness(render_data.environment);
  1882. tonemap_ubo.contrast = environment_get_adjustments_contrast(render_data.environment);
  1883. tonemap_ubo.saturation = environment_get_adjustments_saturation(render_data.environment);
  1884. }
  1885. if (scene_state.tonemap_buffer == 0) {
  1886. // Only create if using 3D
  1887. glGenBuffers(1, &scene_state.tonemap_buffer);
  1888. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_TONEMAP_UNIFORM_LOCATION, scene_state.tonemap_buffer);
  1889. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.tonemap_buffer, sizeof(SceneState::TonemapUBO), &tonemap_ubo, GL_STREAM_DRAW, "Tonemap UBO");
  1890. } else {
  1891. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_TONEMAP_UNIFORM_LOCATION, scene_state.tonemap_buffer);
  1892. glBufferData(GL_UNIFORM_BUFFER, sizeof(SceneState::TonemapUBO), &tonemap_ubo, GL_STREAM_DRAW);
  1893. }
  1894. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1895. scene_state.ubo.emissive_exposure_normalization = -1.0; // Use default exposure normalization.
  1896. bool flip_y = !is_reflection_probe;
  1897. if (rt && rt->overridden.color.is_valid()) {
  1898. // If we've overridden the render target's color texture, then don't render upside down.
  1899. // We're probably rendering directly to an XR device.
  1900. flip_y = false;
  1901. }
  1902. if (!flip_y) {
  1903. // If we're rendering right-side up, then we need to change the winding order.
  1904. glFrontFace(GL_CW);
  1905. }
  1906. _render_shadows(&render_data, screen_size);
  1907. _setup_lights(&render_data, true, render_data.directional_light_count, render_data.omni_light_count, render_data.spot_light_count, render_data.directional_shadow_count);
  1908. _setup_environment(&render_data, is_reflection_probe, screen_size, flip_y, clear_color, false);
  1909. _fill_render_list(RENDER_LIST_OPAQUE, &render_data, PASS_MODE_COLOR);
  1910. render_list[RENDER_LIST_OPAQUE].sort_by_key();
  1911. render_list[RENDER_LIST_ALPHA].sort_by_reverse_depth_and_priority();
  1912. bool draw_sky = false;
  1913. bool draw_sky_fog_only = false;
  1914. bool keep_color = false;
  1915. bool draw_canvas = false;
  1916. bool draw_feed = false;
  1917. float sky_energy_multiplier = 1.0;
  1918. int camera_feed_id = -1;
  1919. if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW)) {
  1920. clear_color = Color(0, 0, 0, 1); //in overdraw mode, BG should always be black
  1921. } else if (render_data.environment.is_valid()) {
  1922. RS::EnvironmentBG bg_mode = environment_get_background(render_data.environment);
  1923. float bg_energy_multiplier = environment_get_bg_energy_multiplier(render_data.environment);
  1924. bg_energy_multiplier *= environment_get_bg_intensity(render_data.environment);
  1925. RS::EnvironmentReflectionSource reflection_source = environment_get_reflection_source(render_data.environment);
  1926. RS::EnvironmentAmbientSource ambient_source = environment_get_ambient_source(render_data.environment);
  1927. if (render_data.camera_attributes.is_valid()) {
  1928. bg_energy_multiplier *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(render_data.camera_attributes);
  1929. }
  1930. switch (bg_mode) {
  1931. case RS::ENV_BG_CLEAR_COLOR: {
  1932. clear_color.r *= bg_energy_multiplier;
  1933. clear_color.g *= bg_energy_multiplier;
  1934. clear_color.b *= bg_energy_multiplier;
  1935. if (!render_data.transparent_bg && environment_get_fog_enabled(render_data.environment)) {
  1936. draw_sky_fog_only = true;
  1937. GLES3::MaterialStorage::get_singleton()->material_set_param(sky_globals.fog_material, "clear_color", Variant(clear_color));
  1938. }
  1939. } break;
  1940. case RS::ENV_BG_COLOR: {
  1941. clear_color = environment_get_bg_color(render_data.environment);
  1942. clear_color.r *= bg_energy_multiplier;
  1943. clear_color.g *= bg_energy_multiplier;
  1944. clear_color.b *= bg_energy_multiplier;
  1945. if (!render_data.transparent_bg && environment_get_fog_enabled(render_data.environment)) {
  1946. draw_sky_fog_only = true;
  1947. GLES3::MaterialStorage::get_singleton()->material_set_param(sky_globals.fog_material, "clear_color", Variant(clear_color));
  1948. }
  1949. } break;
  1950. case RS::ENV_BG_SKY: {
  1951. draw_sky = !render_data.transparent_bg;
  1952. } break;
  1953. case RS::ENV_BG_CANVAS: {
  1954. draw_canvas = true;
  1955. } break;
  1956. case RS::ENV_BG_KEEP: {
  1957. keep_color = true;
  1958. } break;
  1959. case RS::ENV_BG_CAMERA_FEED: {
  1960. camera_feed_id = environment_get_camera_feed_id(render_data.environment);
  1961. draw_feed = true;
  1962. keep_color = true;
  1963. } break;
  1964. default: {
  1965. }
  1966. }
  1967. bool sky_reflections = reflection_source == RS::ENV_REFLECTION_SOURCE_SKY;
  1968. sky_reflections |= reflection_source == RS::ENV_REFLECTION_SOURCE_BG && bg_mode == RS::ENV_BG_SKY;
  1969. bool sky_ambient = ambient_source == RS::ENV_AMBIENT_SOURCE_SKY;
  1970. sky_ambient |= ambient_source == RS::ENV_AMBIENT_SOURCE_BG && bg_mode == RS::ENV_BG_SKY;
  1971. // setup sky if used for ambient, reflections, or background
  1972. if (draw_sky || draw_sky_fog_only || sky_reflections || sky_ambient) {
  1973. RENDER_TIMESTAMP("Setup Sky");
  1974. Projection projection = render_data.cam_projection;
  1975. if (is_reflection_probe) {
  1976. Projection correction;
  1977. correction.set_depth_correction(true, true, false);
  1978. projection = correction * render_data.cam_projection;
  1979. }
  1980. sky_energy_multiplier *= bg_energy_multiplier;
  1981. _setup_sky(&render_data, *render_data.lights, projection, render_data.cam_transform, screen_size);
  1982. if (environment_get_sky(render_data.environment).is_valid()) {
  1983. if (sky_reflections || sky_ambient) {
  1984. _update_sky_radiance(render_data.environment, projection, render_data.cam_transform, sky_energy_multiplier);
  1985. }
  1986. } else {
  1987. // do not try to draw sky if invalid
  1988. draw_sky = false;
  1989. }
  1990. }
  1991. }
  1992. GLuint fbo = 0;
  1993. if (is_reflection_probe) {
  1994. fbo = GLES3::LightStorage::get_singleton()->reflection_probe_instance_get_framebuffer(render_data.reflection_probe, render_data.reflection_probe_pass);
  1995. } else {
  1996. rb->set_apply_color_adjustments_in_post(apply_color_adjustments_in_post);
  1997. fbo = rb->get_render_fbo();
  1998. }
  1999. glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  2000. glViewport(0, 0, rb->internal_size.x, rb->internal_size.y);
  2001. scene_state.reset_gl_state();
  2002. // Do depth prepass if it's explicitly enabled
  2003. bool use_depth_prepass = config->use_depth_prepass;
  2004. // Don't do depth prepass we are rendering overdraw
  2005. use_depth_prepass = use_depth_prepass && get_debug_draw_mode() != RS::VIEWPORT_DEBUG_DRAW_OVERDRAW;
  2006. if (use_depth_prepass) {
  2007. RENDER_TIMESTAMP("Depth Prepass");
  2008. //pre z pass
  2009. if (render_data.render_region != Rect2i()) {
  2010. glViewport(render_data.render_region.position.x, render_data.render_region.position.y, render_data.render_region.size.width, render_data.render_region.size.height);
  2011. }
  2012. scene_state.enable_gl_depth_test(true);
  2013. scene_state.enable_gl_depth_draw(true);
  2014. scene_state.enable_gl_blend(false);
  2015. glDepthFunc(GL_GEQUAL);
  2016. scene_state.enable_gl_scissor_test(false);
  2017. glColorMask(0, 0, 0, 0);
  2018. RasterizerGLES3::clear_depth(0.0);
  2019. glClear(GL_DEPTH_BUFFER_BIT);
  2020. // Some desktop GL implementations fall apart when using Multiview with GL_NONE.
  2021. GLuint db = p_camera_data->view_count > 1 ? GL_COLOR_ATTACHMENT0 : GL_NONE;
  2022. glDrawBuffers(1, &db);
  2023. uint64_t spec_constant = SceneShaderGLES3::DISABLE_FOG | SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL |
  2024. SceneShaderGLES3::DISABLE_LIGHTMAP | SceneShaderGLES3::DISABLE_LIGHT_OMNI |
  2025. SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  2026. RenderListParameters render_list_params(render_list[RENDER_LIST_OPAQUE].elements.ptr(), render_list[RENDER_LIST_OPAQUE].elements.size(), reverse_cull, spec_constant, use_wireframe);
  2027. _render_list_template<PASS_MODE_DEPTH>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_OPAQUE].elements.size());
  2028. glColorMask(1, 1, 1, 1);
  2029. fb_cleared = true;
  2030. scene_state.used_depth_prepass = true;
  2031. } else {
  2032. scene_state.used_depth_prepass = false;
  2033. }
  2034. glBlendEquation(GL_FUNC_ADD);
  2035. if (render_data.transparent_bg) {
  2036. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  2037. scene_state.enable_gl_blend(true);
  2038. } else {
  2039. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
  2040. scene_state.enable_gl_blend(false);
  2041. }
  2042. scene_state.current_blend_mode = GLES3::SceneShaderData::BLEND_MODE_MIX;
  2043. scene_state.enable_gl_scissor_test(false);
  2044. scene_state.enable_gl_depth_test(true);
  2045. scene_state.enable_gl_depth_draw(true);
  2046. glDepthFunc(GL_GEQUAL);
  2047. {
  2048. GLuint db = GL_COLOR_ATTACHMENT0;
  2049. glDrawBuffers(1, &db);
  2050. }
  2051. if (!fb_cleared) {
  2052. RasterizerGLES3::clear_depth(0.0);
  2053. glClear(GL_DEPTH_BUFFER_BIT);
  2054. }
  2055. // Need to clear framebuffer unless:
  2056. // a) We explicitly request not to (i.e. ENV_BG_KEEP).
  2057. // b) We are rendering to a non-intermediate framebuffer with ENV_BG_CANVAS (shared between 2D and 3D).
  2058. if (!keep_color && (!draw_canvas || fbo != rt->fbo)) {
  2059. clear_color.a = render_data.transparent_bg ? 0.0f : 1.0f;
  2060. glClearBufferfv(GL_COLOR, 0, clear_color.components);
  2061. }
  2062. if ((keep_color || draw_canvas) && fbo != rt->fbo) {
  2063. // Need to copy our current contents to our intermediate/MSAA buffer
  2064. GLES3::CopyEffects *copy_effects = GLES3::CopyEffects::get_singleton();
  2065. scene_state.enable_gl_depth_test(false);
  2066. scene_state.enable_gl_depth_draw(false);
  2067. glActiveTexture(GL_TEXTURE0);
  2068. glBindTexture(rt->view_count > 1 ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D, rt->color);
  2069. copy_effects->copy_screen(render_data.luminance_multiplier);
  2070. scene_state.enable_gl_depth_test(true);
  2071. scene_state.enable_gl_depth_draw(true);
  2072. }
  2073. RENDER_TIMESTAMP("Render Opaque Pass");
  2074. uint64_t spec_constant_base_flags = 0;
  2075. if (render_data.render_region != Rect2i()) {
  2076. glViewport(render_data.render_region.position.x, render_data.render_region.position.y, render_data.render_region.size.width, render_data.render_region.size.height);
  2077. }
  2078. {
  2079. // Specialization Constants that apply for entire rendering pass.
  2080. if (render_data.directional_light_count == 0) {
  2081. spec_constant_base_flags |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  2082. }
  2083. if (render_data.environment.is_null() || (render_data.environment.is_valid() && !environment_get_fog_enabled(render_data.environment))) {
  2084. spec_constant_base_flags |= SceneShaderGLES3::DISABLE_FOG;
  2085. }
  2086. if (render_data.environment.is_valid() && environment_get_fog_mode(render_data.environment) == RS::EnvironmentFogMode::ENV_FOG_MODE_DEPTH) {
  2087. spec_constant_base_flags |= SceneShaderGLES3::USE_DEPTH_FOG;
  2088. }
  2089. if (!apply_color_adjustments_in_post) {
  2090. spec_constant_base_flags |= SceneShaderGLES3::APPLY_TONEMAPPING;
  2091. }
  2092. }
  2093. if (draw_feed && camera_feed_id > -1) {
  2094. RENDER_TIMESTAMP("Render Camera feed");
  2095. scene_state.enable_gl_depth_draw(false);
  2096. scene_state.enable_gl_depth_test(false);
  2097. scene_state.enable_gl_blend(false);
  2098. scene_state.set_gl_cull_mode(RS::CULL_MODE_BACK);
  2099. Ref<CameraFeed> feed = CameraServer::get_singleton()->get_feed_by_id(camera_feed_id);
  2100. if (feed.is_valid()) {
  2101. RID camera_YCBCR = feed->get_texture(CameraServer::FEED_YCBCR_IMAGE);
  2102. GLES3::TextureStorage::get_singleton()->texture_bind(camera_YCBCR, 0);
  2103. GLES3::FeedEffects *feed_effects = GLES3::FeedEffects::get_singleton();
  2104. feed_effects->draw();
  2105. }
  2106. scene_state.enable_gl_depth_draw(true);
  2107. scene_state.enable_gl_depth_test(true);
  2108. scene_state.enable_gl_blend(true);
  2109. }
  2110. // Render Opaque Objects.
  2111. RenderListParameters render_list_params(render_list[RENDER_LIST_OPAQUE].elements.ptr(), render_list[RENDER_LIST_OPAQUE].elements.size(), reverse_cull, spec_constant_base_flags, use_wireframe);
  2112. _render_list_template<PASS_MODE_COLOR>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_OPAQUE].elements.size());
  2113. scene_state.enable_gl_depth_draw(false);
  2114. if (draw_sky || draw_sky_fog_only) {
  2115. RENDER_TIMESTAMP("Render Sky");
  2116. scene_state.enable_gl_depth_test(true);
  2117. scene_state.enable_gl_blend(false);
  2118. scene_state.set_gl_cull_mode(RS::CULL_MODE_BACK);
  2119. Transform3D transform = render_data.cam_transform;
  2120. Projection projection = render_data.cam_projection;
  2121. if (is_reflection_probe) {
  2122. Projection correction;
  2123. correction.columns[1][1] = -1.0;
  2124. projection = correction * render_data.cam_projection;
  2125. } else if (render_data.cam_frustum) {
  2126. // Sky is drawn upside down, the frustum offset doesn't know the image is upside down so needs a flip.
  2127. projection[2].y = -projection[2].y;
  2128. }
  2129. _draw_sky(render_data.environment, projection, transform, sky_energy_multiplier, render_data.luminance_multiplier, p_camera_data->view_count > 1, flip_y, apply_color_adjustments_in_post);
  2130. }
  2131. if (rt && (scene_state.used_screen_texture || scene_state.used_depth_texture)) {
  2132. Size2i size;
  2133. GLuint backbuffer_fbo = 0;
  2134. GLuint backbuffer = 0;
  2135. GLuint backbuffer_depth = 0;
  2136. if (rb->get_scaling_3d_mode() == RS::VIEWPORT_SCALING_3D_MODE_OFF) {
  2137. texture_storage->check_backbuffer(rt, scene_state.used_screen_texture, scene_state.used_depth_texture); // note, badly names, this just allocates!
  2138. size = rt->size;
  2139. backbuffer_fbo = rt->backbuffer_fbo;
  2140. backbuffer = rt->backbuffer;
  2141. backbuffer_depth = rt->backbuffer_depth;
  2142. } else {
  2143. rb->check_backbuffer(scene_state.used_screen_texture, scene_state.used_depth_texture);
  2144. size = rb->get_internal_size();
  2145. backbuffer_fbo = rb->get_backbuffer_fbo();
  2146. backbuffer = rb->get_backbuffer();
  2147. backbuffer_depth = rb->get_backbuffer_depth();
  2148. }
  2149. if (backbuffer_fbo != 0) {
  2150. glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo);
  2151. glReadBuffer(GL_COLOR_ATTACHMENT0);
  2152. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, backbuffer_fbo);
  2153. if (scene_state.used_screen_texture) {
  2154. glBlitFramebuffer(0, 0, size.x, size.y,
  2155. 0, 0, size.x, size.y,
  2156. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  2157. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 6);
  2158. glBindTexture(GL_TEXTURE_2D, backbuffer);
  2159. }
  2160. if (scene_state.used_depth_texture) {
  2161. glBlitFramebuffer(0, 0, size.x, size.y,
  2162. 0, 0, size.x, size.y,
  2163. GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2164. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 7);
  2165. glBindTexture(GL_TEXTURE_2D, backbuffer_depth);
  2166. }
  2167. }
  2168. // Bound framebuffer may have changed, so change it back
  2169. glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  2170. }
  2171. RENDER_TIMESTAMP("Render 3D Transparent Pass");
  2172. scene_state.enable_gl_blend(true);
  2173. //Render transparent pass
  2174. RenderListParameters render_list_params_alpha(render_list[RENDER_LIST_ALPHA].elements.ptr(), render_list[RENDER_LIST_ALPHA].elements.size(), reverse_cull, spec_constant_base_flags, use_wireframe);
  2175. _render_list_template<PASS_MODE_COLOR_TRANSPARENT>(&render_list_params_alpha, &render_data, 0, render_list[RENDER_LIST_ALPHA].elements.size(), true);
  2176. if (!flip_y) {
  2177. // Restore the default winding order.
  2178. glFrontFace(GL_CCW);
  2179. }
  2180. if (!is_reflection_probe && rb.is_valid()) {
  2181. _render_buffers_debug_draw(rb, p_shadow_atlas, fbo);
  2182. }
  2183. // Reset stuff that may trip up the next process.
  2184. scene_state.reset_gl_state();
  2185. glUseProgram(0);
  2186. if (!is_reflection_probe) {
  2187. _render_post_processing(&render_data);
  2188. texture_storage->render_target_disable_clear_request(rb->render_target);
  2189. }
  2190. glActiveTexture(GL_TEXTURE0);
  2191. }
  2192. void RasterizerSceneGLES3::_render_post_processing(const RenderDataGLES3 *p_render_data) {
  2193. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  2194. GLES3::Glow *glow = GLES3::Glow::get_singleton();
  2195. GLES3::PostEffects *post_effects = GLES3::PostEffects::get_singleton();
  2196. Ref<RenderSceneBuffersGLES3> rb = p_render_data->render_buffers;
  2197. ERR_FAIL_COND(rb.is_null());
  2198. RID render_target = rb->get_render_target();
  2199. Size2i internal_size = rb->get_internal_size();
  2200. Size2i target_size = rb->get_target_size();
  2201. uint32_t view_count = rb->get_view_count();
  2202. // bool msaa2d_needs_resolve = texture_storage->render_target_get_msaa(render_target) != RS::VIEWPORT_MSAA_DISABLED && !GLES3::Config::get_singleton()->rt_msaa_supported;
  2203. bool msaa3d_needs_resolve = rb->get_msaa_needs_resolve();
  2204. GLuint fbo_msaa_3d = rb->get_msaa3d_fbo();
  2205. GLuint fbo_int = rb->get_internal_fbo();
  2206. GLuint fbo_rt = texture_storage->render_target_get_fbo(render_target); // TODO if MSAA 2D is enabled and we're not using rt_msaa, get 2D render target here.
  2207. // Check if we have glow enabled and if so, check if our buffers were allocated
  2208. bool glow_enabled = false;
  2209. float glow_intensity = 1.0;
  2210. float glow_bloom = 0.0;
  2211. float glow_hdr_bleed_threshold = 1.0;
  2212. float glow_hdr_bleed_scale = 2.0;
  2213. float glow_hdr_luminance_cap = 12.0;
  2214. if (p_render_data->environment.is_valid()) {
  2215. glow_enabled = environment_get_glow_enabled(p_render_data->environment);
  2216. glow_intensity = environment_get_glow_intensity(p_render_data->environment);
  2217. glow_bloom = environment_get_glow_bloom(p_render_data->environment);
  2218. glow_hdr_bleed_threshold = environment_get_glow_hdr_bleed_threshold(p_render_data->environment);
  2219. glow_hdr_bleed_scale = environment_get_glow_hdr_bleed_scale(p_render_data->environment);
  2220. glow_hdr_luminance_cap = environment_get_glow_hdr_luminance_cap(p_render_data->environment);
  2221. }
  2222. if (glow_enabled) {
  2223. rb->check_glow_buffers();
  2224. }
  2225. uint64_t bcs_spec_constants = 0;
  2226. if (p_render_data->environment.is_valid()) {
  2227. bool use_bcs = environment_get_adjustments_enabled(p_render_data->environment);
  2228. RID color_correction_texture = environment_get_color_correction(p_render_data->environment);
  2229. if (use_bcs) {
  2230. bcs_spec_constants |= PostShaderGLES3::USE_BCS;
  2231. if (color_correction_texture.is_valid()) {
  2232. bcs_spec_constants |= PostShaderGLES3::USE_COLOR_CORRECTION;
  2233. bool use_1d_lut = environment_get_use_1d_color_correction(p_render_data->environment);
  2234. GLenum texture_target = GL_TEXTURE_3D;
  2235. if (use_1d_lut) {
  2236. bcs_spec_constants |= PostShaderGLES3::USE_1D_LUT;
  2237. texture_target = GL_TEXTURE_2D;
  2238. }
  2239. glActiveTexture(GL_TEXTURE2);
  2240. glBindTexture(texture_target, texture_storage->texture_get_texid(color_correction_texture));
  2241. glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  2242. glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  2243. glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  2244. glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  2245. glTexParameteri(texture_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
  2246. }
  2247. }
  2248. }
  2249. if (view_count == 1) {
  2250. // Resolve if needed.
  2251. if (fbo_msaa_3d != 0 && msaa3d_needs_resolve) {
  2252. // We can use blit to copy things over
  2253. glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo_msaa_3d);
  2254. if (fbo_int != 0) {
  2255. // We can't combine resolve and scaling, so resolve into our internal buffer
  2256. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_int);
  2257. } else {
  2258. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_rt);
  2259. }
  2260. glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, internal_size.x, internal_size.y, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2261. }
  2262. // Rendered to intermediate buffer, must copy to our render target
  2263. if (fbo_int != 0) {
  2264. // Apply glow/bloom if requested? then populate our glow buffers
  2265. GLuint color = fbo_int != 0 ? rb->get_internal_color() : texture_storage->render_target_get_color(render_target);
  2266. const GLES3::Glow::GLOWLEVEL *glow_buffers = nullptr;
  2267. if (glow_enabled) {
  2268. glow_buffers = rb->get_glow_buffers();
  2269. glow->set_luminance_multiplier(p_render_data->luminance_multiplier);
  2270. glow->set_intensity(glow_intensity);
  2271. glow->set_glow_bloom(glow_bloom);
  2272. glow->set_glow_hdr_bleed_threshold(glow_hdr_bleed_threshold);
  2273. glow->set_glow_hdr_bleed_scale(glow_hdr_bleed_scale);
  2274. glow->set_glow_hdr_luminance_cap(glow_hdr_luminance_cap);
  2275. glow->process_glow(color, internal_size, glow_buffers);
  2276. }
  2277. // Copy color buffer
  2278. post_effects->post_copy(fbo_rt, target_size, color, internal_size, p_render_data->luminance_multiplier, glow_buffers, glow_intensity, 0, false, bcs_spec_constants);
  2279. // Copy depth buffer
  2280. glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo_int);
  2281. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_rt);
  2282. glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, target_size.x, target_size.y, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2283. }
  2284. glBindFramebuffer(GL_FRAMEBUFFER, fbo_rt);
  2285. } else if ((fbo_msaa_3d != 0 && msaa3d_needs_resolve) || (fbo_int != 0)) {
  2286. // TODO investigate if it's smarter to cache these FBOs
  2287. GLuint fbos[3]; // read, write and post
  2288. glGenFramebuffers(3, fbos);
  2289. // Resolve if needed.
  2290. if (fbo_msaa_3d != 0 && msaa3d_needs_resolve) {
  2291. GLuint read_color = rb->get_msaa3d_color();
  2292. GLuint read_depth = rb->get_msaa3d_depth();
  2293. GLuint write_color = 0;
  2294. GLuint write_depth = 0;
  2295. if (fbo_int != 0) {
  2296. write_color = rb->get_internal_color();
  2297. write_depth = rb->get_internal_depth();
  2298. } else {
  2299. write_color = texture_storage->render_target_get_color(render_target);
  2300. write_depth = texture_storage->render_target_get_depth(render_target);
  2301. }
  2302. glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[0]);
  2303. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]);
  2304. for (uint32_t v = 0; v < view_count; v++) {
  2305. glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, read_color, 0, v);
  2306. glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, read_depth, 0, v);
  2307. glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, write_color, 0, v);
  2308. glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, write_depth, 0, v);
  2309. glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, internal_size.x, internal_size.y, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2310. }
  2311. }
  2312. // Rendered to intermediate buffer, must copy to our render target
  2313. if (fbo_int != 0) {
  2314. // Apply glow/bloom if requested? then populate our glow buffers
  2315. const GLES3::Glow::GLOWLEVEL *glow_buffers = nullptr;
  2316. GLuint source_color = fbo_int != 0 ? rb->get_internal_color() : texture_storage->render_target_get_color(render_target);
  2317. if (glow_enabled) {
  2318. glow_buffers = rb->get_glow_buffers();
  2319. glow->set_luminance_multiplier(p_render_data->luminance_multiplier);
  2320. glow->set_intensity(glow_intensity);
  2321. glow->set_glow_bloom(glow_bloom);
  2322. glow->set_glow_hdr_bleed_threshold(glow_hdr_bleed_threshold);
  2323. glow->set_glow_hdr_bleed_scale(glow_hdr_bleed_scale);
  2324. glow->set_glow_hdr_luminance_cap(glow_hdr_luminance_cap);
  2325. }
  2326. GLuint write_color = texture_storage->render_target_get_color(render_target);
  2327. for (uint32_t v = 0; v < view_count; v++) {
  2328. if (glow_enabled) {
  2329. glow->process_glow(source_color, internal_size, glow_buffers, v, true);
  2330. }
  2331. glBindFramebuffer(GL_FRAMEBUFFER, fbos[2]);
  2332. glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, write_color, 0, v);
  2333. post_effects->post_copy(fbos[2], target_size, source_color, internal_size, p_render_data->luminance_multiplier, glow_buffers, glow_intensity, v, true, bcs_spec_constants);
  2334. }
  2335. // Copy depth
  2336. GLuint read_depth = rb->get_internal_depth();
  2337. GLuint write_depth = texture_storage->render_target_get_depth(render_target);
  2338. glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[0]);
  2339. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]);
  2340. for (uint32_t v = 0; v < view_count; v++) {
  2341. glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, read_depth, 0, v);
  2342. glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, write_depth, 0, v);
  2343. glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, target_size.x, target_size.y, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2344. }
  2345. }
  2346. glBindFramebuffer(GL_FRAMEBUFFER, fbo_rt);
  2347. glDeleteFramebuffers(3, fbos);
  2348. }
  2349. glActiveTexture(GL_TEXTURE2);
  2350. glBindTexture(GL_TEXTURE_2D, 0);
  2351. }
  2352. template <PassMode p_pass_mode>
  2353. void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params, const RenderDataGLES3 *p_render_data, uint32_t p_from_element, uint32_t p_to_element, bool p_alpha_pass) {
  2354. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  2355. GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
  2356. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  2357. GLuint prev_vertex_array_gl = 0;
  2358. GLuint prev_index_array_gl = 0;
  2359. GLES3::SceneMaterialData *prev_material_data = nullptr;
  2360. GLES3::SceneShaderData *prev_shader = nullptr;
  2361. GeometryInstanceGLES3 *prev_inst = nullptr;
  2362. SceneShaderGLES3::ShaderVariant prev_variant = SceneShaderGLES3::ShaderVariant::MODE_COLOR;
  2363. SceneShaderGLES3::ShaderVariant shader_variant = SceneShaderGLES3::MODE_COLOR; // Assigned to silence wrong -Wmaybe-initialized
  2364. uint64_t prev_spec_constants = 0;
  2365. // Specializations constants used by all instances in the scene.
  2366. uint64_t base_spec_constants = p_params->spec_constant_base_flags;
  2367. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2368. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  2369. GLES3::Config *config = GLES3::Config::get_singleton();
  2370. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 2);
  2371. GLuint texture_to_bind = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_CUBEMAP_BLACK))->tex_id;
  2372. if (p_render_data->environment.is_valid()) {
  2373. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_render_data->environment));
  2374. if (sky && sky->radiance != 0) {
  2375. texture_to_bind = sky->radiance;
  2376. base_spec_constants |= SceneShaderGLES3::USE_RADIANCE_MAP;
  2377. }
  2378. glBindTexture(GL_TEXTURE_CUBE_MAP, texture_to_bind);
  2379. }
  2380. } else if constexpr (p_pass_mode == PASS_MODE_DEPTH || p_pass_mode == PASS_MODE_SHADOW) {
  2381. shader_variant = SceneShaderGLES3::MODE_DEPTH;
  2382. }
  2383. if (p_render_data->view_count > 1) {
  2384. base_spec_constants |= SceneShaderGLES3::USE_MULTIVIEW;
  2385. }
  2386. bool should_request_redraw = false;
  2387. if constexpr (p_pass_mode != PASS_MODE_DEPTH) {
  2388. // Don't count elements during depth pre-pass to match the RD renderers.
  2389. if (p_render_data->render_info) {
  2390. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME] += p_to_element - p_from_element;
  2391. }
  2392. }
  2393. for (uint32_t i = p_from_element; i < p_to_element; i++) {
  2394. GeometryInstanceSurface *surf = p_params->elements[i];
  2395. GeometryInstanceGLES3 *inst = surf->owner;
  2396. if (p_pass_mode == PASS_MODE_COLOR && !(surf->flags & GeometryInstanceSurface::FLAG_PASS_OPAQUE)) {
  2397. continue; // Objects with "Depth-prepass" transparency are included in both render lists, but should only be rendered in the transparent pass
  2398. }
  2399. if (inst->instance_count == 0) {
  2400. continue;
  2401. }
  2402. GLES3::SceneShaderData *shader;
  2403. GLES3::SceneMaterialData *material_data;
  2404. void *mesh_surface;
  2405. if constexpr (p_pass_mode == PASS_MODE_SHADOW) {
  2406. shader = surf->shader_shadow;
  2407. material_data = surf->material_shadow;
  2408. mesh_surface = surf->surface_shadow;
  2409. } else {
  2410. if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW)) {
  2411. material_data = overdraw_material_data_ptr;
  2412. shader = material_data->shader_data;
  2413. } else if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_LIGHTING)) {
  2414. material_data = default_material_data_ptr;
  2415. shader = material_data->shader_data;
  2416. } else {
  2417. shader = surf->shader;
  2418. material_data = surf->material;
  2419. }
  2420. mesh_surface = surf->surface;
  2421. }
  2422. if (!mesh_surface) {
  2423. continue;
  2424. }
  2425. //request a redraw if one of the shaders uses TIME
  2426. if (shader->uses_time) {
  2427. should_request_redraw = true;
  2428. }
  2429. if constexpr (p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2430. scene_state.enable_gl_depth_test(shader->depth_test == GLES3::SceneShaderData::DEPTH_TEST_ENABLED);
  2431. }
  2432. if constexpr (p_pass_mode != PASS_MODE_SHADOW) {
  2433. if (shader->depth_draw == GLES3::SceneShaderData::DEPTH_DRAW_OPAQUE) {
  2434. scene_state.enable_gl_depth_draw((p_pass_mode == PASS_MODE_COLOR && !GLES3::Config::get_singleton()->use_depth_prepass) || p_pass_mode == PASS_MODE_DEPTH);
  2435. } else {
  2436. scene_state.enable_gl_depth_draw(shader->depth_draw == GLES3::SceneShaderData::DEPTH_DRAW_ALWAYS);
  2437. }
  2438. }
  2439. bool uses_additive_lighting = (inst->light_passes.size() + p_render_data->directional_shadow_count) > 0;
  2440. uses_additive_lighting = uses_additive_lighting && !shader->unshaded;
  2441. // TODOS
  2442. /*
  2443. * Still a bug when atlas space is limited. Somehow need to evict light when it doesn't have a spot on the atlas, current check isn't enough
  2444. * Disable depth draw
  2445. */
  2446. for (int32_t pass = 0; pass < MAX(1, int32_t(inst->light_passes.size() + p_render_data->directional_shadow_count)); pass++) {
  2447. if constexpr (p_pass_mode == PASS_MODE_DEPTH || p_pass_mode == PASS_MODE_SHADOW) {
  2448. if (pass > 0) {
  2449. // Don't render shadow passes when doing depth or shadow pass.
  2450. break;
  2451. }
  2452. }
  2453. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2454. if (!uses_additive_lighting && pass == 1) {
  2455. // Don't render additive passes if not using additive lighting.
  2456. break;
  2457. }
  2458. if (uses_additive_lighting && pass == 1 && !p_render_data->transparent_bg) {
  2459. // Enable blending if in opaque pass and not already enabled.
  2460. scene_state.enable_gl_blend(true);
  2461. }
  2462. if (pass < int32_t(inst->light_passes.size())) {
  2463. RID light_instance_rid = inst->light_passes[pass].light_instance_rid;
  2464. if (!GLES3::LightStorage::get_singleton()->light_instance_has_shadow_atlas(light_instance_rid, p_render_data->shadow_atlas)) {
  2465. // Shadow wasn't able to get a spot on the atlas. So skip it.
  2466. continue;
  2467. }
  2468. } else if (pass > 0) {
  2469. uint32_t shadow_id = MAX_DIRECTIONAL_LIGHTS - 1 - (pass - int32_t(inst->light_passes.size()));
  2470. if (inst->lightmap_instance.is_valid() && scene_state.directional_lights[shadow_id].bake_mode == RenderingServer::LIGHT_BAKE_STATIC) {
  2471. // Skip shadows for static lights on meshes with a lightmap.
  2472. continue;
  2473. }
  2474. }
  2475. }
  2476. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2477. GLES3::SceneShaderData::BlendMode desired_blend_mode;
  2478. if (pass > 0) {
  2479. desired_blend_mode = GLES3::SceneShaderData::BLEND_MODE_ADD;
  2480. } else {
  2481. desired_blend_mode = shader->blend_mode;
  2482. }
  2483. if (desired_blend_mode != scene_state.current_blend_mode) {
  2484. switch (desired_blend_mode) {
  2485. case GLES3::SceneShaderData::BLEND_MODE_MIX: {
  2486. glBlendEquation(GL_FUNC_ADD);
  2487. if (p_render_data->transparent_bg) {
  2488. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  2489. } else {
  2490. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
  2491. }
  2492. } break;
  2493. case GLES3::SceneShaderData::BLEND_MODE_ADD: {
  2494. glBlendEquation(GL_FUNC_ADD);
  2495. glBlendFunc(p_pass_mode == PASS_MODE_COLOR_TRANSPARENT ? GL_SRC_ALPHA : GL_ONE, GL_ONE);
  2496. } break;
  2497. case GLES3::SceneShaderData::BLEND_MODE_SUB: {
  2498. glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
  2499. glBlendFunc(GL_SRC_ALPHA, GL_ONE);
  2500. } break;
  2501. case GLES3::SceneShaderData::BLEND_MODE_MUL: {
  2502. glBlendEquation(GL_FUNC_ADD);
  2503. if (p_render_data->transparent_bg) {
  2504. glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO);
  2505. } else {
  2506. glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE);
  2507. }
  2508. } break;
  2509. case GLES3::SceneShaderData::BLEND_MODE_PREMULT_ALPHA: {
  2510. glBlendEquation(GL_FUNC_ADD);
  2511. glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  2512. } break;
  2513. case GLES3::SceneShaderData::BLEND_MODE_ALPHA_TO_COVERAGE: {
  2514. // Do nothing for now.
  2515. } break;
  2516. }
  2517. scene_state.current_blend_mode = desired_blend_mode;
  2518. }
  2519. }
  2520. // Find cull variant.
  2521. RS::CullMode cull_mode = shader->cull_mode;
  2522. if (p_pass_mode == PASS_MODE_MATERIAL || (surf->flags & GeometryInstanceSurface::FLAG_USES_DOUBLE_SIDED_SHADOWS)) {
  2523. cull_mode = RS::CULL_MODE_DISABLED;
  2524. } else {
  2525. bool mirror = inst->mirror;
  2526. if (p_params->reverse_cull) {
  2527. mirror = !mirror;
  2528. }
  2529. if (cull_mode == RS::CULL_MODE_FRONT && mirror) {
  2530. cull_mode = RS::CULL_MODE_BACK;
  2531. } else if (cull_mode == RS::CULL_MODE_BACK && mirror) {
  2532. cull_mode = RS::CULL_MODE_FRONT;
  2533. }
  2534. }
  2535. scene_state.set_gl_cull_mode(cull_mode);
  2536. RS::PrimitiveType primitive = surf->primitive;
  2537. if (shader->uses_point_size) {
  2538. primitive = RS::PRIMITIVE_POINTS;
  2539. }
  2540. static const GLenum prim[5] = { GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP };
  2541. GLenum primitive_gl = prim[int(primitive)];
  2542. GLuint vertex_array_gl = 0;
  2543. GLuint index_array_gl = 0;
  2544. uint64_t vertex_input_mask = shader->vertex_input_mask;
  2545. if (inst->lightmap_instance.is_valid() || p_pass_mode == PASS_MODE_MATERIAL) {
  2546. vertex_input_mask |= 1 << RS::ARRAY_TEX_UV2;
  2547. }
  2548. // Skeleton and blend shapes.
  2549. if (surf->owner->mesh_instance.is_valid()) {
  2550. mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(surf->owner->mesh_instance, surf->surface_index, vertex_input_mask, vertex_array_gl);
  2551. } else {
  2552. mesh_storage->mesh_surface_get_vertex_arrays_and_format(mesh_surface, vertex_input_mask, vertex_array_gl);
  2553. }
  2554. index_array_gl = mesh_storage->mesh_surface_get_index_buffer(mesh_surface, surf->lod_index);
  2555. if (prev_vertex_array_gl != vertex_array_gl) {
  2556. if (vertex_array_gl != 0) {
  2557. glBindVertexArray(vertex_array_gl);
  2558. }
  2559. prev_vertex_array_gl = vertex_array_gl;
  2560. // Invalidate the previous index array
  2561. prev_index_array_gl = 0;
  2562. }
  2563. bool use_wireframe = false;
  2564. if (p_params->force_wireframe || shader->wireframe) {
  2565. GLuint wireframe_index_array_gl = mesh_storage->mesh_surface_get_index_buffer_wireframe(mesh_surface);
  2566. if (wireframe_index_array_gl) {
  2567. index_array_gl = wireframe_index_array_gl;
  2568. use_wireframe = true;
  2569. }
  2570. }
  2571. bool use_index_buffer = index_array_gl != 0;
  2572. if (prev_index_array_gl != index_array_gl) {
  2573. if (index_array_gl != 0) {
  2574. // Bind index each time so we can use LODs
  2575. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_array_gl);
  2576. }
  2577. prev_index_array_gl = index_array_gl;
  2578. }
  2579. Transform3D world_transform;
  2580. if (inst->store_transform_cache) {
  2581. world_transform = inst->transform;
  2582. }
  2583. if (prev_material_data != material_data) {
  2584. material_data->bind_uniforms();
  2585. prev_material_data = material_data;
  2586. }
  2587. SceneShaderGLES3::ShaderVariant instance_variant = shader_variant;
  2588. if (inst->instance_count > 0) {
  2589. // Will need to use instancing to draw (either MultiMesh or Particles).
  2590. instance_variant = SceneShaderGLES3::ShaderVariant(1 + int(instance_variant));
  2591. }
  2592. uint64_t spec_constants = base_spec_constants;
  2593. // Set up spec constants for lighting.
  2594. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2595. // Only check during color passes as light shader code is compiled out during depth-only pass anyway.
  2596. if (pass == 0) {
  2597. spec_constants |= SceneShaderGLES3::BASE_PASS;
  2598. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
  2599. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_OMNI;
  2600. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  2601. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  2602. spec_constants |= SceneShaderGLES3::DISABLE_LIGHTMAP;
  2603. } else {
  2604. if (inst->omni_light_gl_cache.is_empty()) {
  2605. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_OMNI;
  2606. }
  2607. if (inst->spot_light_gl_cache.is_empty()) {
  2608. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  2609. }
  2610. if (p_render_data->directional_light_count == p_render_data->directional_shadow_count) {
  2611. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  2612. }
  2613. if (inst->reflection_probe_rid_cache.is_empty()) {
  2614. // We don't have any probes.
  2615. spec_constants |= SceneShaderGLES3::DISABLE_REFLECTION_PROBE;
  2616. } else if (inst->reflection_probe_rid_cache.size() > 1) {
  2617. // We have a second probe.
  2618. spec_constants |= SceneShaderGLES3::SECOND_REFLECTION_PROBE;
  2619. }
  2620. if (inst->lightmap_instance.is_valid()) {
  2621. spec_constants |= SceneShaderGLES3::USE_LIGHTMAP;
  2622. GLES3::LightmapInstance *li = GLES3::LightStorage::get_singleton()->get_lightmap_instance(inst->lightmap_instance);
  2623. GLES3::Lightmap *lm = GLES3::LightStorage::get_singleton()->get_lightmap(li->lightmap);
  2624. if (lm->uses_spherical_harmonics) {
  2625. spec_constants |= SceneShaderGLES3::USE_SH_LIGHTMAP;
  2626. }
  2627. if (lightmap_bicubic_upscale) {
  2628. spec_constants |= SceneShaderGLES3::LIGHTMAP_BICUBIC_FILTER;
  2629. }
  2630. } else if (inst->lightmap_sh) {
  2631. spec_constants |= SceneShaderGLES3::USE_LIGHTMAP_CAPTURE;
  2632. } else {
  2633. spec_constants |= SceneShaderGLES3::DISABLE_LIGHTMAP;
  2634. }
  2635. }
  2636. } else {
  2637. // Only base pass uses the radiance map.
  2638. spec_constants &= ~SceneShaderGLES3::USE_RADIANCE_MAP;
  2639. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_OMNI;
  2640. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  2641. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  2642. spec_constants |= SceneShaderGLES3::DISABLE_REFLECTION_PROBE;
  2643. bool disable_lightmaps = true;
  2644. // Additive directional passes may use shadowmasks, so enable lightmaps for them.
  2645. if (pass >= int32_t(inst->light_passes.size()) && inst->lightmap_instance.is_valid()) {
  2646. GLES3::LightmapInstance *li = GLES3::LightStorage::get_singleton()->get_lightmap_instance(inst->lightmap_instance);
  2647. GLES3::Lightmap *lm = GLES3::LightStorage::get_singleton()->get_lightmap(li->lightmap);
  2648. if (lm->shadowmask_mode != RS::SHADOWMASK_MODE_NONE) {
  2649. spec_constants |= SceneShaderGLES3::USE_LIGHTMAP;
  2650. disable_lightmaps = false;
  2651. if (lightmap_bicubic_upscale) {
  2652. spec_constants |= SceneShaderGLES3::LIGHTMAP_BICUBIC_FILTER;
  2653. }
  2654. }
  2655. }
  2656. if (disable_lightmaps) {
  2657. spec_constants |= SceneShaderGLES3::DISABLE_LIGHTMAP;
  2658. }
  2659. }
  2660. if (uses_additive_lighting) {
  2661. spec_constants |= SceneShaderGLES3::USE_ADDITIVE_LIGHTING;
  2662. if (pass < int32_t(inst->light_passes.size())) {
  2663. // Rendering positional lights.
  2664. if (inst->light_passes[pass].is_omni) {
  2665. spec_constants |= SceneShaderGLES3::ADDITIVE_OMNI;
  2666. } else {
  2667. spec_constants |= SceneShaderGLES3::ADDITIVE_SPOT;
  2668. }
  2669. if (scene_state.positional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_HIGH) {
  2670. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_13;
  2671. } else if (scene_state.positional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_LOW) {
  2672. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_5;
  2673. }
  2674. } else {
  2675. // Render directional lights.
  2676. uint32_t shadow_id = MAX_DIRECTIONAL_LIGHTS - 1 - (pass - int32_t(inst->light_passes.size()));
  2677. if (pass == 0 && inst->lightmap_instance.is_valid() && scene_state.directional_lights[shadow_id].bake_mode == RenderingServer::LIGHT_BAKE_STATIC) {
  2678. // Disable additive lighting with a static light and a lightmap.
  2679. spec_constants &= ~SceneShaderGLES3::USE_ADDITIVE_LIGHTING;
  2680. }
  2681. if (scene_state.directional_shadows[shadow_id].shadow_split_offsets[0] == scene_state.directional_shadows[shadow_id].shadow_split_offsets[1]) {
  2682. // Orthogonal, do nothing.
  2683. } else if (scene_state.directional_shadows[shadow_id].shadow_split_offsets[1] == scene_state.directional_shadows[shadow_id].shadow_split_offsets[2]) {
  2684. spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM2;
  2685. } else {
  2686. spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM4;
  2687. }
  2688. if (scene_state.directional_shadows[shadow_id].blend_splits) {
  2689. spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM_BLEND;
  2690. }
  2691. if (scene_state.directional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_HIGH) {
  2692. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_13;
  2693. } else if (scene_state.directional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_LOW) {
  2694. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_5;
  2695. }
  2696. }
  2697. }
  2698. }
  2699. if (prev_shader != shader || prev_variant != instance_variant || spec_constants != prev_spec_constants) {
  2700. bool success = material_storage->shaders.scene_shader.version_bind_shader(shader->version, instance_variant, spec_constants);
  2701. if (!success) {
  2702. break;
  2703. }
  2704. float opaque_prepass_threshold = 0.0;
  2705. if constexpr (p_pass_mode == PASS_MODE_DEPTH) {
  2706. opaque_prepass_threshold = 0.99;
  2707. } else if constexpr (p_pass_mode == PASS_MODE_SHADOW) {
  2708. opaque_prepass_threshold = 0.1;
  2709. }
  2710. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OPAQUE_PREPASS_THRESHOLD, opaque_prepass_threshold, shader->version, instance_variant, spec_constants);
  2711. }
  2712. // Pass in lighting uniforms.
  2713. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2714. GLES3::Config *config = GLES3::Config::get_singleton();
  2715. // Pass light and shadow index and bind shadow texture.
  2716. if (uses_additive_lighting) {
  2717. if (pass < int32_t(inst->light_passes.size())) {
  2718. int32_t shadow_id = inst->light_passes[pass].shadow_id;
  2719. if (shadow_id >= 0) {
  2720. uint32_t light_id = inst->light_passes[pass].light_id;
  2721. bool is_omni = inst->light_passes[pass].is_omni;
  2722. SceneShaderGLES3::Uniforms uniform_name = is_omni ? SceneShaderGLES3::OMNI_LIGHT_INDEX : SceneShaderGLES3::SPOT_LIGHT_INDEX;
  2723. material_storage->shaders.scene_shader.version_set_uniform(uniform_name, uint32_t(light_id), shader->version, instance_variant, spec_constants);
  2724. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::POSITIONAL_SHADOW_INDEX, uint32_t(shadow_id), shader->version, instance_variant, spec_constants);
  2725. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 3);
  2726. RID light_instance_rid = inst->light_passes[pass].light_instance_rid;
  2727. GLuint tex = GLES3::LightStorage::get_singleton()->light_instance_get_shadow_texture(light_instance_rid, p_render_data->shadow_atlas);
  2728. if (is_omni) {
  2729. glBindTexture(GL_TEXTURE_CUBE_MAP, tex);
  2730. } else {
  2731. glBindTexture(GL_TEXTURE_2D, tex);
  2732. }
  2733. }
  2734. } else {
  2735. uint32_t shadow_id = MAX_DIRECTIONAL_LIGHTS - 1 - (pass - int32_t(inst->light_passes.size()));
  2736. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::DIRECTIONAL_SHADOW_INDEX, shadow_id, shader->version, instance_variant, spec_constants);
  2737. GLuint tex = GLES3::LightStorage::get_singleton()->directional_shadow_get_texture();
  2738. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 3);
  2739. glBindTexture(GL_TEXTURE_2D, tex);
  2740. if (inst->lightmap_instance.is_valid()) {
  2741. // Use shadowmasks for directional light passes.
  2742. GLES3::LightmapInstance *li = GLES3::LightStorage::get_singleton()->get_lightmap_instance(inst->lightmap_instance);
  2743. GLES3::Lightmap *lm = GLES3::LightStorage::get_singleton()->get_lightmap(li->lightmap);
  2744. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_SLICE, inst->lightmap_slice_index, shader->version, instance_variant, spec_constants);
  2745. Vector4 uv_scale(inst->lightmap_uv_scale.position.x, inst->lightmap_uv_scale.position.y, inst->lightmap_uv_scale.size.x, inst->lightmap_uv_scale.size.y);
  2746. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_UV_SCALE, uv_scale, shader->version, instance_variant, spec_constants);
  2747. if (lightmap_bicubic_upscale) {
  2748. Vector2 light_texture_size(lm->light_texture_size.x, lm->light_texture_size.y);
  2749. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_TEXTURE_SIZE, light_texture_size, shader->version, instance_variant, spec_constants);
  2750. }
  2751. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_SHADOWMASK_MODE, (uint32_t)lm->shadowmask_mode, shader->version, instance_variant, spec_constants);
  2752. if (lm->shadow_texture.is_valid()) {
  2753. tex = GLES3::TextureStorage::get_singleton()->texture_get_texid(lm->shadow_texture);
  2754. } else {
  2755. tex = GLES3::TextureStorage::get_singleton()->texture_get_texid(GLES3::TextureStorage::get_singleton()->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_2D_ARRAY_WHITE));
  2756. }
  2757. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 5);
  2758. glBindTexture(GL_TEXTURE_2D_ARRAY, tex);
  2759. }
  2760. }
  2761. }
  2762. // Pass light count and array of light indices for base pass.
  2763. if ((prev_inst != inst || prev_shader != shader || prev_variant != instance_variant || prev_spec_constants != spec_constants) && pass == 0) {
  2764. // Rebind the light indices.
  2765. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT, inst->omni_light_gl_cache.size(), shader->version, instance_variant, spec_constants);
  2766. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT, inst->spot_light_gl_cache.size(), shader->version, instance_variant, spec_constants);
  2767. if (inst->omni_light_gl_cache.size()) {
  2768. glUniform1uiv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::OMNI_LIGHT_INDICES, shader->version, instance_variant, spec_constants), inst->omni_light_gl_cache.size(), inst->omni_light_gl_cache.ptr());
  2769. }
  2770. if (inst->spot_light_gl_cache.size()) {
  2771. glUniform1uiv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::SPOT_LIGHT_INDICES, shader->version, instance_variant, spec_constants), inst->spot_light_gl_cache.size(), inst->spot_light_gl_cache.ptr());
  2772. }
  2773. if (inst->lightmap_instance.is_valid()) {
  2774. GLES3::LightmapInstance *li = GLES3::LightStorage::get_singleton()->get_lightmap_instance(inst->lightmap_instance);
  2775. GLES3::Lightmap *lm = GLES3::LightStorage::get_singleton()->get_lightmap(li->lightmap);
  2776. GLuint tex = GLES3::TextureStorage::get_singleton()->texture_get_texid(lm->light_texture);
  2777. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 4);
  2778. glBindTexture(GL_TEXTURE_2D_ARRAY, tex);
  2779. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_SLICE, inst->lightmap_slice_index, shader->version, instance_variant, spec_constants);
  2780. Vector4 uv_scale(inst->lightmap_uv_scale.position.x, inst->lightmap_uv_scale.position.y, inst->lightmap_uv_scale.size.x, inst->lightmap_uv_scale.size.y);
  2781. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_UV_SCALE, uv_scale, shader->version, instance_variant, spec_constants);
  2782. if (lightmap_bicubic_upscale) {
  2783. Vector2 light_texture_size(lm->light_texture_size.x, lm->light_texture_size.y);
  2784. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_TEXTURE_SIZE, light_texture_size, shader->version, instance_variant, spec_constants);
  2785. }
  2786. float exposure_normalization = 1.0;
  2787. if (p_render_data->camera_attributes.is_valid()) {
  2788. float enf = RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  2789. exposure_normalization = enf / lm->baked_exposure;
  2790. }
  2791. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_EXPOSURE_NORMALIZATION, exposure_normalization, shader->version, instance_variant, spec_constants);
  2792. if (lm->uses_spherical_harmonics) {
  2793. Basis to_lm = li->transform.basis.inverse() * p_render_data->cam_transform.basis;
  2794. to_lm = to_lm.inverse().transposed();
  2795. GLfloat matrix[9] = {
  2796. (GLfloat)to_lm.rows[0][0],
  2797. (GLfloat)to_lm.rows[1][0],
  2798. (GLfloat)to_lm.rows[2][0],
  2799. (GLfloat)to_lm.rows[0][1],
  2800. (GLfloat)to_lm.rows[1][1],
  2801. (GLfloat)to_lm.rows[2][1],
  2802. (GLfloat)to_lm.rows[0][2],
  2803. (GLfloat)to_lm.rows[1][2],
  2804. (GLfloat)to_lm.rows[2][2],
  2805. };
  2806. glUniformMatrix3fv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::LIGHTMAP_NORMAL_XFORM, shader->version, instance_variant, spec_constants), 1, GL_FALSE, matrix);
  2807. }
  2808. } else if (inst->lightmap_sh) {
  2809. glUniform4fv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::LIGHTMAP_CAPTURES, shader->version, instance_variant, spec_constants), 9, reinterpret_cast<const GLfloat *>(inst->lightmap_sh->sh));
  2810. }
  2811. prev_inst = inst;
  2812. }
  2813. }
  2814. prev_shader = shader;
  2815. prev_variant = instance_variant;
  2816. prev_spec_constants = spec_constants;
  2817. // Pass in reflection probe data
  2818. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2819. if (pass == 0 && inst->reflection_probe_rid_cache.size() > 0) {
  2820. GLES3::Config *config = GLES3::Config::get_singleton();
  2821. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  2822. // Setup first probe.
  2823. {
  2824. RID probe_rid = light_storage->reflection_probe_instance_get_probe(inst->reflection_probe_rid_cache[0]);
  2825. GLES3::ReflectionProbe *probe = light_storage->get_reflection_probe(probe_rid);
  2826. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_USE_BOX_PROJECT, probe->box_projection, shader->version, instance_variant, spec_constants);
  2827. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_BOX_EXTENTS, probe->size * 0.5, shader->version, instance_variant, spec_constants);
  2828. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_BOX_OFFSET, probe->origin_offset, shader->version, instance_variant, spec_constants);
  2829. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_EXTERIOR, !probe->interior, shader->version, instance_variant, spec_constants);
  2830. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_INTENSITY, probe->intensity, shader->version, instance_variant, spec_constants);
  2831. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_AMBIENT_MODE, int(probe->ambient_mode), shader->version, instance_variant, spec_constants);
  2832. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_AMBIENT_COLOR, probe->ambient_color * probe->ambient_color_energy, shader->version, instance_variant, spec_constants);
  2833. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_LOCAL_MATRIX, inst->reflection_probes_local_transform_cache[0], shader->version, instance_variant, spec_constants);
  2834. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_BLEND_DISTANCE, probe->blend_distance, shader->version, instance_variant, spec_constants);
  2835. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 8);
  2836. glBindTexture(GL_TEXTURE_CUBE_MAP, light_storage->reflection_probe_instance_get_texture(inst->reflection_probe_rid_cache[0]));
  2837. }
  2838. if (inst->reflection_probe_rid_cache.size() > 1) {
  2839. // Setup second probe.
  2840. RID probe_rid = light_storage->reflection_probe_instance_get_probe(inst->reflection_probe_rid_cache[1]);
  2841. GLES3::ReflectionProbe *probe = light_storage->get_reflection_probe(probe_rid);
  2842. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_USE_BOX_PROJECT, probe->box_projection, shader->version, instance_variant, spec_constants);
  2843. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_BOX_EXTENTS, probe->size * 0.5, shader->version, instance_variant, spec_constants);
  2844. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_BOX_OFFSET, probe->origin_offset, shader->version, instance_variant, spec_constants);
  2845. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_EXTERIOR, !probe->interior, shader->version, instance_variant, spec_constants);
  2846. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_INTENSITY, probe->intensity, shader->version, instance_variant, spec_constants);
  2847. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_AMBIENT_MODE, int(probe->ambient_mode), shader->version, instance_variant, spec_constants);
  2848. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_AMBIENT_COLOR, probe->ambient_color * probe->ambient_color_energy, shader->version, instance_variant, spec_constants);
  2849. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_LOCAL_MATRIX, inst->reflection_probes_local_transform_cache[1], shader->version, instance_variant, spec_constants);
  2850. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_BLEND_DISTANCE, probe->blend_distance, shader->version, instance_variant, spec_constants);
  2851. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 9);
  2852. glBindTexture(GL_TEXTURE_CUBE_MAP, light_storage->reflection_probe_instance_get_texture(inst->reflection_probe_rid_cache[1]));
  2853. spec_constants |= SceneShaderGLES3::SECOND_REFLECTION_PROBE;
  2854. }
  2855. }
  2856. }
  2857. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, world_transform, shader->version, instance_variant, spec_constants);
  2858. {
  2859. GLES3::Mesh::Surface *s = reinterpret_cast<GLES3::Mesh::Surface *>(surf->surface);
  2860. if (s->format & RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES) {
  2861. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_POSITION, s->aabb.position, shader->version, instance_variant, spec_constants);
  2862. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_SIZE, s->aabb.size, shader->version, instance_variant, spec_constants);
  2863. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::UV_SCALE, s->uv_scale, shader->version, instance_variant, spec_constants);
  2864. } else {
  2865. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_POSITION, Vector3(0.0, 0.0, 0.0), shader->version, instance_variant, spec_constants);
  2866. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_SIZE, Vector3(1.0, 1.0, 1.0), shader->version, instance_variant, spec_constants);
  2867. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::UV_SCALE, Vector4(0.0, 0.0, 0.0, 0.0), shader->version, instance_variant, spec_constants);
  2868. }
  2869. }
  2870. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::MODEL_FLAGS, inst->flags_cache, shader->version, instance_variant, spec_constants);
  2871. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::INSTANCE_OFFSET, uint32_t(inst->shader_uniforms_offset), shader->version, instance_variant, spec_constants);
  2872. if (p_pass_mode == PASS_MODE_MATERIAL) {
  2873. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::UV_OFFSET, p_params->uv_offset, shader->version, instance_variant, spec_constants);
  2874. }
  2875. // Can be index count or vertex count
  2876. uint32_t count = 0;
  2877. if (surf->lod_index > 0) {
  2878. count = surf->index_count;
  2879. } else {
  2880. count = mesh_storage->mesh_surface_get_vertices_drawn_count(mesh_surface);
  2881. }
  2882. if (use_wireframe) {
  2883. // In this case we are using index count, and we need double the indices for the wireframe mesh.
  2884. count = count * 2;
  2885. }
  2886. if constexpr (p_pass_mode != PASS_MODE_DEPTH) {
  2887. // Don't count draw calls during depth pre-pass to match the RD renderers.
  2888. if (p_render_data->render_info) {
  2889. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;
  2890. }
  2891. }
  2892. if (inst->instance_count > 0) {
  2893. // Using MultiMesh or Particles.
  2894. // Bind instance buffers.
  2895. GLuint instance_buffer = 0;
  2896. uint32_t stride = 0;
  2897. if (inst->flags_cache & INSTANCE_DATA_FLAG_PARTICLES) {
  2898. instance_buffer = particles_storage->particles_get_gl_buffer(inst->data->base);
  2899. stride = 16; // 12 bytes for instance transform and 4 bytes for packed color and custom.
  2900. } else {
  2901. instance_buffer = mesh_storage->multimesh_get_gl_buffer(inst->data->base);
  2902. stride = mesh_storage->multimesh_get_stride(inst->data->base);
  2903. }
  2904. if (instance_buffer == 0) {
  2905. // Instance buffer not initialized yet. Skip rendering for now.
  2906. break;
  2907. }
  2908. glBindBuffer(GL_ARRAY_BUFFER, instance_buffer);
  2909. glEnableVertexAttribArray(12);
  2910. glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(0));
  2911. glVertexAttribDivisor(12, 1);
  2912. glEnableVertexAttribArray(13);
  2913. glVertexAttribPointer(13, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4));
  2914. glVertexAttribDivisor(13, 1);
  2915. if (!(inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D)) {
  2916. glEnableVertexAttribArray(14);
  2917. glVertexAttribPointer(14, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(sizeof(float) * 8));
  2918. glVertexAttribDivisor(14, 1);
  2919. }
  2920. if ((inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR) || (inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA)) {
  2921. uint32_t color_custom_offset = inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D ? 8 : 12;
  2922. glEnableVertexAttribArray(15);
  2923. glVertexAttribIPointer(15, 4, GL_UNSIGNED_INT, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(color_custom_offset * sizeof(float)));
  2924. glVertexAttribDivisor(15, 1);
  2925. } else {
  2926. // Set all default instance color and custom data values to 1.0 or 0.0 using a compressed format.
  2927. uint16_t zero = Math::make_half_float(0.0f);
  2928. uint16_t one = Math::make_half_float(1.0f);
  2929. GLuint default_color = (uint32_t(one) << 16) | one;
  2930. GLuint default_custom = (uint32_t(zero) << 16) | zero;
  2931. glVertexAttribI4ui(15, default_color, default_color, default_custom, default_custom);
  2932. }
  2933. if (use_wireframe) {
  2934. glDrawElementsInstanced(GL_LINES, count, GL_UNSIGNED_INT, nullptr, inst->instance_count);
  2935. } else {
  2936. if (use_index_buffer) {
  2937. glDrawElementsInstanced(primitive_gl, count, mesh_storage->mesh_surface_get_index_type(mesh_surface), nullptr, inst->instance_count);
  2938. } else {
  2939. glDrawArraysInstanced(primitive_gl, 0, count, inst->instance_count);
  2940. }
  2941. }
  2942. } else {
  2943. // Using regular Mesh.
  2944. if (use_wireframe) {
  2945. glDrawElements(GL_LINES, count, GL_UNSIGNED_INT, nullptr);
  2946. } else {
  2947. if (use_index_buffer) {
  2948. glDrawElements(primitive_gl, count, mesh_storage->mesh_surface_get_index_type(mesh_surface), nullptr);
  2949. } else {
  2950. glDrawArrays(primitive_gl, 0, count);
  2951. }
  2952. }
  2953. }
  2954. if (inst->instance_count > 0) {
  2955. glDisableVertexAttribArray(12);
  2956. glDisableVertexAttribArray(13);
  2957. glDisableVertexAttribArray(14);
  2958. glDisableVertexAttribArray(15);
  2959. }
  2960. }
  2961. if constexpr (p_pass_mode == PASS_MODE_COLOR) {
  2962. if (uses_additive_lighting && !p_render_data->transparent_bg) {
  2963. // Disable additive blending if enabled for additive lights.
  2964. scene_state.enable_gl_blend(false);
  2965. }
  2966. }
  2967. }
  2968. // Make the actual redraw request
  2969. if (should_request_redraw) {
  2970. RenderingServerDefault::redraw_request();
  2971. }
  2972. }
  2973. void RasterizerSceneGLES3::render_material(const Transform3D &p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal, const PagedArray<RenderGeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) {
  2974. }
  2975. void RasterizerSceneGLES3::render_particle_collider_heightfield(RID p_collider, const Transform3D &p_transform, const PagedArray<RenderGeometryInstance *> &p_instances) {
  2976. GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
  2977. ERR_FAIL_COND(!particles_storage->particles_collision_is_heightfield(p_collider));
  2978. Vector3 extents = particles_storage->particles_collision_get_extents(p_collider) * p_transform.basis.get_scale();
  2979. Projection cm;
  2980. cm.set_orthogonal(-extents.x, extents.x, -extents.z, extents.z, 0, extents.y * 2.0);
  2981. Vector3 cam_pos = p_transform.origin;
  2982. cam_pos.y += extents.y;
  2983. Transform3D cam_xform;
  2984. cam_xform.set_look_at(cam_pos, cam_pos - p_transform.basis.get_column(Vector3::AXIS_Y), -p_transform.basis.get_column(Vector3::AXIS_Z).normalized());
  2985. GLuint fb = particles_storage->particles_collision_get_heightfield_framebuffer(p_collider);
  2986. Size2i fb_size = particles_storage->particles_collision_get_heightfield_size(p_collider);
  2987. RENDER_TIMESTAMP("Setup GPUParticlesCollisionHeightField3D");
  2988. RenderDataGLES3 render_data;
  2989. render_data.cam_projection = cm;
  2990. render_data.cam_transform = cam_xform;
  2991. render_data.view_projection[0] = cm;
  2992. render_data.inv_cam_transform = render_data.cam_transform.affine_inverse();
  2993. render_data.cam_orthogonal = true;
  2994. render_data.z_near = 0.0;
  2995. render_data.z_far = cm.get_z_far();
  2996. render_data.main_cam_transform = cam_xform;
  2997. render_data.instances = &p_instances;
  2998. _setup_environment(&render_data, true, Vector2(fb_size), true, Color(), false);
  2999. PassMode pass_mode = PASS_MODE_SHADOW;
  3000. _fill_render_list(RENDER_LIST_SECONDARY, &render_data, pass_mode);
  3001. render_list[RENDER_LIST_SECONDARY].sort_by_key();
  3002. RENDER_TIMESTAMP("Render Collider Heightfield");
  3003. glBindFramebuffer(GL_FRAMEBUFFER, fb);
  3004. glViewport(0, 0, fb_size.width, fb_size.height);
  3005. GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer();
  3006. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer);
  3007. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3008. scene_state.reset_gl_state();
  3009. scene_state.enable_gl_depth_test(true);
  3010. scene_state.enable_gl_depth_draw(true);
  3011. glDepthFunc(GL_GREATER);
  3012. glDrawBuffers(0, nullptr);
  3013. glColorMask(0, 0, 0, 0);
  3014. RasterizerGLES3::clear_depth(0.0);
  3015. glClear(GL_DEPTH_BUFFER_BIT);
  3016. RenderListParameters render_list_params(render_list[RENDER_LIST_SECONDARY].elements.ptr(), render_list[RENDER_LIST_SECONDARY].elements.size(), false, 31, false);
  3017. _render_list_template<PASS_MODE_SHADOW>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size());
  3018. glColorMask(1, 1, 1, 1);
  3019. glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
  3020. }
  3021. void RasterizerSceneGLES3::_render_uv2(const PagedArray<RenderGeometryInstance *> &p_instances, GLuint p_framebuffer, const Rect2i &p_region) {
  3022. RENDER_TIMESTAMP("Setup Rendering UV2");
  3023. RenderDataGLES3 render_data;
  3024. render_data.instances = &p_instances;
  3025. scene_state.ubo.emissive_exposure_normalization = -1.0; // Use default exposure normalization.
  3026. _setup_environment(&render_data, true, Vector2(1, 1), true, Color(), false);
  3027. PassMode pass_mode = PASS_MODE_MATERIAL;
  3028. _fill_render_list(RENDER_LIST_SECONDARY, &render_data, pass_mode);
  3029. render_list[RENDER_LIST_SECONDARY].sort_by_key();
  3030. RENDER_TIMESTAMP("Render 3D Material");
  3031. {
  3032. glBindFramebuffer(GL_FRAMEBUFFER, p_framebuffer);
  3033. glViewport(p_region.position.x, p_region.position.y, p_region.size.x, p_region.size.y);
  3034. GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer();
  3035. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer);
  3036. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3037. scene_state.reset_gl_state();
  3038. scene_state.enable_gl_depth_test(true);
  3039. scene_state.enable_gl_depth_draw(true);
  3040. glDepthFunc(GL_GREATER);
  3041. TightLocalVector<GLenum> draw_buffers;
  3042. draw_buffers.push_back(GL_COLOR_ATTACHMENT0);
  3043. draw_buffers.push_back(GL_COLOR_ATTACHMENT1);
  3044. draw_buffers.push_back(GL_COLOR_ATTACHMENT2);
  3045. draw_buffers.push_back(GL_COLOR_ATTACHMENT3);
  3046. glDrawBuffers(draw_buffers.size(), draw_buffers.ptr());
  3047. glClearColor(0.0, 0.0, 0.0, 0.0);
  3048. RasterizerGLES3::clear_depth(0.0);
  3049. glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
  3050. uint64_t base_spec_constant = 0;
  3051. base_spec_constant |= SceneShaderGLES3::RENDER_MATERIAL;
  3052. base_spec_constant |= SceneShaderGLES3::DISABLE_FOG;
  3053. base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  3054. base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHT_OMNI;
  3055. base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  3056. base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHTMAP;
  3057. RenderListParameters render_list_params(render_list[RENDER_LIST_SECONDARY].elements.ptr(), render_list[RENDER_LIST_SECONDARY].elements.size(), false, base_spec_constant, true, Vector2(0, 0));
  3058. const int uv_offset_count = 9;
  3059. static const Vector2 uv_offsets[uv_offset_count] = {
  3060. Vector2(-1, 1),
  3061. Vector2(1, 1),
  3062. Vector2(1, -1),
  3063. Vector2(-1, -1),
  3064. Vector2(-1, 0),
  3065. Vector2(1, 0),
  3066. Vector2(0, -1),
  3067. Vector2(0, 1),
  3068. Vector2(0, 0),
  3069. };
  3070. for (int i = 0; i < uv_offset_count; i++) {
  3071. Vector2 ofs = uv_offsets[i];
  3072. ofs.x /= p_region.size.width;
  3073. ofs.y /= p_region.size.height;
  3074. render_list_params.uv_offset = ofs;
  3075. _render_list_template<PASS_MODE_MATERIAL>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size());
  3076. }
  3077. render_list_params.uv_offset = Vector2(0, 0);
  3078. render_list_params.force_wireframe = false;
  3079. _render_list_template<PASS_MODE_MATERIAL>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size());
  3080. GLuint db = GL_COLOR_ATTACHMENT0;
  3081. glDrawBuffers(1, &db);
  3082. glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
  3083. }
  3084. }
  3085. void RasterizerSceneGLES3::set_time(double p_time, double p_step) {
  3086. time = p_time;
  3087. time_step = p_step;
  3088. }
  3089. void RasterizerSceneGLES3::set_debug_draw_mode(RS::ViewportDebugDraw p_debug_draw) {
  3090. debug_draw = p_debug_draw;
  3091. }
  3092. Ref<RenderSceneBuffers> RasterizerSceneGLES3::render_buffers_create() {
  3093. Ref<RenderSceneBuffersGLES3> rb;
  3094. rb.instantiate();
  3095. return rb;
  3096. }
  3097. void RasterizerSceneGLES3::_render_buffers_debug_draw(Ref<RenderSceneBuffersGLES3> p_render_buffers, RID p_shadow_atlas, GLuint p_fbo) {
  3098. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  3099. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  3100. GLES3::CopyEffects *copy_effects = GLES3::CopyEffects::get_singleton();
  3101. ERR_FAIL_COND(p_render_buffers.is_null());
  3102. RID render_target = p_render_buffers->render_target;
  3103. GLES3::RenderTarget *rt = texture_storage->get_render_target(render_target);
  3104. ERR_FAIL_NULL(rt);
  3105. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SHADOW_ATLAS) {
  3106. if (p_shadow_atlas.is_valid()) {
  3107. // Get or create debug textures to display shadow maps as an atlas.
  3108. GLuint shadow_atlas_texture = light_storage->shadow_atlas_get_debug_texture(p_shadow_atlas);
  3109. GLuint shadow_atlas_fb = light_storage->shadow_atlas_get_debug_fb(p_shadow_atlas);
  3110. uint32_t shadow_atlas_size = light_storage->shadow_atlas_get_size(p_shadow_atlas);
  3111. uint32_t quadrant_size = shadow_atlas_size >> 1;
  3112. glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas_fb);
  3113. glViewport(0, 0, shadow_atlas_size, shadow_atlas_size);
  3114. glActiveTexture(GL_TEXTURE0);
  3115. scene_state.enable_gl_depth_draw(true);
  3116. glDepthFunc(GL_ALWAYS);
  3117. scene_state.set_gl_cull_mode(RS::CULL_MODE_DISABLED);
  3118. // Loop through quadrants and copy shadows over.
  3119. for (int quadrant = 0; quadrant < 4; quadrant++) {
  3120. uint32_t subdivision = light_storage->shadow_atlas_get_quadrant_subdivision(p_shadow_atlas, quadrant);
  3121. if (subdivision == 0) {
  3122. continue;
  3123. }
  3124. Rect2i atlas_rect;
  3125. Rect2 atlas_uv_rect;
  3126. uint32_t shadow_size = (quadrant_size / subdivision);
  3127. float size = float(shadow_size) / float(shadow_atlas_size);
  3128. uint32_t length = light_storage->shadow_atlas_get_quadrant_shadows_allocated(p_shadow_atlas, quadrant);
  3129. for (uint32_t shadow_idx = 0; shadow_idx < length; shadow_idx++) {
  3130. bool is_omni = light_storage->shadow_atlas_get_quadrant_shadow_is_omni(p_shadow_atlas, quadrant, shadow_idx);
  3131. // Calculate shadow's position in the debug atlas.
  3132. atlas_rect.position.x = (quadrant & 1) * quadrant_size;
  3133. atlas_rect.position.y = (quadrant >> 1) * quadrant_size;
  3134. atlas_rect.position.x += (shadow_idx % subdivision) * shadow_size;
  3135. atlas_rect.position.y += (shadow_idx / subdivision) * shadow_size;
  3136. atlas_uv_rect.position = Vector2(atlas_rect.position) / float(shadow_atlas_size);
  3137. atlas_uv_rect.size = Vector2(size, size);
  3138. GLuint shadow_tex = light_storage->shadow_atlas_get_quadrant_shadow_texture(p_shadow_atlas, quadrant, shadow_idx);
  3139. // Copy from shadowmap to debug atlas.
  3140. if (is_omni) {
  3141. glBindTexture(GL_TEXTURE_CUBE_MAP, shadow_tex);
  3142. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  3143. copy_effects->copy_cube_to_rect(atlas_uv_rect);
  3144. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  3145. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_FUNC, GL_GREATER);
  3146. } else {
  3147. glBindTexture(GL_TEXTURE_2D, shadow_tex);
  3148. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  3149. copy_effects->copy_to_rect(atlas_uv_rect);
  3150. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  3151. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_GREATER);
  3152. }
  3153. }
  3154. }
  3155. // Set back to FBO
  3156. glBindFramebuffer(GL_FRAMEBUFFER, p_fbo);
  3157. Size2i size = p_render_buffers->get_internal_size();
  3158. glViewport(0, 0, size.width, size.height);
  3159. glBindTexture(GL_TEXTURE_2D, shadow_atlas_texture);
  3160. copy_effects->copy_to_rect(Rect2(Vector2(), Vector2(0.5, 0.5)));
  3161. glBindTexture(GL_TEXTURE_2D, 0);
  3162. glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
  3163. }
  3164. }
  3165. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_DIRECTIONAL_SHADOW_ATLAS) {
  3166. if (light_storage->directional_shadow_get_texture() != 0) {
  3167. GLuint shadow_atlas_texture = light_storage->directional_shadow_get_texture();
  3168. glActiveTexture(GL_TEXTURE0);
  3169. glBindTexture(GL_TEXTURE_2D, shadow_atlas_texture);
  3170. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  3171. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED);
  3172. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED);
  3173. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
  3174. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE);
  3175. scene_state.enable_gl_depth_test(false);
  3176. scene_state.enable_gl_depth_draw(false);
  3177. copy_effects->copy_to_rect(Rect2(Vector2(), Vector2(0.5, 0.5)));
  3178. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED);
  3179. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN);
  3180. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE);
  3181. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ALPHA);
  3182. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  3183. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_GREATER);
  3184. glBindTexture(GL_TEXTURE_2D, 0);
  3185. }
  3186. }
  3187. }
  3188. void RasterizerSceneGLES3::gi_set_use_half_resolution(bool p_enable) {
  3189. }
  3190. void RasterizerSceneGLES3::screen_space_roughness_limiter_set_active(bool p_enable, float p_amount, float p_curve) {
  3191. }
  3192. bool RasterizerSceneGLES3::screen_space_roughness_limiter_is_active() const {
  3193. return false;
  3194. }
  3195. void RasterizerSceneGLES3::sub_surface_scattering_set_quality(RS::SubSurfaceScatteringQuality p_quality) {
  3196. }
  3197. void RasterizerSceneGLES3::sub_surface_scattering_set_scale(float p_scale, float p_depth_scale) {
  3198. }
  3199. TypedArray<Image> RasterizerSceneGLES3::bake_render_uv2(RID p_base, const TypedArray<RID> &p_material_overrides, const Size2i &p_image_size) {
  3200. GLES3::Config *config = GLES3::Config::get_singleton();
  3201. ERR_FAIL_COND_V_MSG(p_image_size.width <= 0, TypedArray<Image>(), "Image width must be greater than 0.");
  3202. ERR_FAIL_COND_V_MSG(p_image_size.height <= 0, TypedArray<Image>(), "Image height must be greater than 0.");
  3203. GLuint albedo_alpha_tex = 0;
  3204. GLuint normal_tex = 0;
  3205. GLuint orm_tex = 0;
  3206. GLuint emission_tex = 0;
  3207. GLuint depth_tex = 0;
  3208. glGenTextures(1, &albedo_alpha_tex);
  3209. glGenTextures(1, &normal_tex);
  3210. glGenTextures(1, &orm_tex);
  3211. glGenTextures(1, &emission_tex);
  3212. glGenTextures(1, &depth_tex);
  3213. glBindTexture(GL_TEXTURE_2D, albedo_alpha_tex);
  3214. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  3215. GLES3::Utilities::get_singleton()->texture_allocated_data(albedo_alpha_tex, p_image_size.width * p_image_size.height * 4, "Lightmap albedo texture");
  3216. glBindTexture(GL_TEXTURE_2D, normal_tex);
  3217. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  3218. GLES3::Utilities::get_singleton()->texture_allocated_data(normal_tex, p_image_size.width * p_image_size.height * 4, "Lightmap normal texture");
  3219. glBindTexture(GL_TEXTURE_2D, orm_tex);
  3220. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  3221. GLES3::Utilities::get_singleton()->texture_allocated_data(orm_tex, p_image_size.width * p_image_size.height * 4, "Lightmap ORM texture");
  3222. // Consider rendering to RGBA8 encoded as RGBE, then manually convert to RGBAH on CPU.
  3223. glBindTexture(GL_TEXTURE_2D, emission_tex);
  3224. if (config->float_texture_supported) {
  3225. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_FLOAT, nullptr);
  3226. GLES3::Utilities::get_singleton()->texture_allocated_data(emission_tex, p_image_size.width * p_image_size.height * 16, "Lightmap emission texture");
  3227. } else {
  3228. // Fallback to RGBA8 on devices that don't support rendering to floating point textures. This will look bad, but we have no choice.
  3229. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  3230. GLES3::Utilities::get_singleton()->texture_allocated_data(emission_tex, p_image_size.width * p_image_size.height * 4, "Lightmap emission texture");
  3231. }
  3232. glBindTexture(GL_TEXTURE_2D, depth_tex);
  3233. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, p_image_size.width, p_image_size.height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr);
  3234. GLES3::Utilities::get_singleton()->texture_allocated_data(depth_tex, p_image_size.width * p_image_size.height * 3, "Lightmap depth texture");
  3235. GLuint fbo = 0;
  3236. glGenFramebuffers(1, &fbo);
  3237. glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  3238. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, albedo_alpha_tex, 0);
  3239. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, normal_tex, 0);
  3240. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, orm_tex, 0);
  3241. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, emission_tex, 0);
  3242. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_tex, 0);
  3243. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  3244. if (status != GL_FRAMEBUFFER_COMPLETE) {
  3245. glDeleteFramebuffers(1, &fbo);
  3246. GLES3::Utilities::get_singleton()->texture_free_data(albedo_alpha_tex);
  3247. GLES3::Utilities::get_singleton()->texture_free_data(normal_tex);
  3248. GLES3::Utilities::get_singleton()->texture_free_data(orm_tex);
  3249. GLES3::Utilities::get_singleton()->texture_free_data(emission_tex);
  3250. GLES3::Utilities::get_singleton()->texture_free_data(depth_tex);
  3251. WARN_PRINT("Could not create render target, status: " + GLES3::TextureStorage::get_singleton()->get_framebuffer_error(status));
  3252. return TypedArray<Image>();
  3253. }
  3254. RenderGeometryInstance *gi_inst = geometry_instance_create(p_base);
  3255. ERR_FAIL_NULL_V(gi_inst, TypedArray<Image>());
  3256. uint32_t sc = RSG::mesh_storage->mesh_get_surface_count(p_base);
  3257. Vector<RID> materials;
  3258. materials.resize(sc);
  3259. for (uint32_t i = 0; i < sc; i++) {
  3260. if (i < (uint32_t)p_material_overrides.size()) {
  3261. materials.write[i] = p_material_overrides[i];
  3262. }
  3263. }
  3264. gi_inst->set_surface_materials(materials);
  3265. if (cull_argument.size() == 0) {
  3266. cull_argument.push_back(nullptr);
  3267. }
  3268. cull_argument[0] = gi_inst;
  3269. _render_uv2(cull_argument, fbo, Rect2i(0, 0, p_image_size.width, p_image_size.height));
  3270. geometry_instance_free(gi_inst);
  3271. TypedArray<Image> ret;
  3272. // Create a dummy texture so we can use texture_2d_get.
  3273. RID tex_rid = GLES3::TextureStorage::get_singleton()->texture_allocate();
  3274. GLES3::Texture texture;
  3275. texture.width = p_image_size.width;
  3276. texture.height = p_image_size.height;
  3277. texture.alloc_width = p_image_size.width;
  3278. texture.alloc_height = p_image_size.height;
  3279. texture.format = Image::FORMAT_RGBA8;
  3280. texture.real_format = Image::FORMAT_RGBA8;
  3281. texture.gl_format_cache = GL_RGBA;
  3282. texture.gl_type_cache = GL_UNSIGNED_BYTE;
  3283. texture.type = GLES3::Texture::TYPE_2D;
  3284. texture.target = GL_TEXTURE_2D;
  3285. texture.active = true;
  3286. texture.is_render_target = true; // Enable this so the texture isn't cached in the editor.
  3287. GLES3::TextureStorage::get_singleton()->texture_2d_initialize_from_texture(tex_rid, texture);
  3288. GLES3::Texture *tex = GLES3::TextureStorage::get_singleton()->get_texture(tex_rid);
  3289. {
  3290. tex->tex_id = albedo_alpha_tex;
  3291. Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid);
  3292. GLES3::Utilities::get_singleton()->texture_free_data(albedo_alpha_tex);
  3293. ret.push_back(img);
  3294. }
  3295. {
  3296. tex->tex_id = normal_tex;
  3297. Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid);
  3298. GLES3::Utilities::get_singleton()->texture_free_data(normal_tex);
  3299. ret.push_back(img);
  3300. }
  3301. {
  3302. tex->tex_id = orm_tex;
  3303. Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid);
  3304. GLES3::Utilities::get_singleton()->texture_free_data(orm_tex);
  3305. ret.push_back(img);
  3306. }
  3307. {
  3308. tex->tex_id = emission_tex;
  3309. if (config->float_texture_supported) {
  3310. tex->format = Image::FORMAT_RGBAH;
  3311. tex->real_format = Image::FORMAT_RGBAH;
  3312. tex->gl_type_cache = GL_HALF_FLOAT;
  3313. }
  3314. Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid);
  3315. GLES3::Utilities::get_singleton()->texture_free_data(emission_tex);
  3316. ret.push_back(img);
  3317. }
  3318. tex->is_render_target = false;
  3319. tex->tex_id = 0;
  3320. GLES3::TextureStorage::get_singleton()->texture_free(tex_rid);
  3321. GLES3::Utilities::get_singleton()->texture_free_data(depth_tex);
  3322. glDeleteFramebuffers(1, &fbo);
  3323. return ret;
  3324. }
  3325. bool RasterizerSceneGLES3::free(RID p_rid) {
  3326. if (is_environment(p_rid)) {
  3327. environment_free(p_rid);
  3328. } else if (sky_owner.owns(p_rid)) {
  3329. Sky *sky = sky_owner.get_or_null(p_rid);
  3330. ERR_FAIL_NULL_V(sky, false);
  3331. _free_sky_data(sky);
  3332. sky_owner.free(p_rid);
  3333. } else if (GLES3::LightStorage::get_singleton()->owns_light_instance(p_rid)) {
  3334. GLES3::LightStorage::get_singleton()->light_instance_free(p_rid);
  3335. } else if (RSG::camera_attributes->owns_camera_attributes(p_rid)) {
  3336. //not much to delete, just free it
  3337. RSG::camera_attributes->camera_attributes_free(p_rid);
  3338. } else if (is_compositor(p_rid)) {
  3339. compositor_free(p_rid);
  3340. } else if (is_compositor_effect(p_rid)) {
  3341. compositor_effect_free(p_rid);
  3342. } else {
  3343. return false;
  3344. }
  3345. return true;
  3346. }
  3347. void RasterizerSceneGLES3::update() {
  3348. _update_dirty_skys();
  3349. }
  3350. void RasterizerSceneGLES3::sdfgi_set_debug_probe_select(const Vector3 &p_position, const Vector3 &p_dir) {
  3351. }
  3352. void RasterizerSceneGLES3::decals_set_filter(RS::DecalFilter p_filter) {
  3353. }
  3354. void RasterizerSceneGLES3::light_projectors_set_filter(RS::LightProjectorFilter p_filter) {
  3355. }
  3356. void RasterizerSceneGLES3::lightmaps_set_bicubic_filter(bool p_enable) {
  3357. lightmap_bicubic_upscale = p_enable;
  3358. }
  3359. RasterizerSceneGLES3::RasterizerSceneGLES3() {
  3360. singleton = this;
  3361. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  3362. GLES3::Config *config = GLES3::Config::get_singleton();
  3363. cull_argument.set_page_pool(&cull_argument_pool);
  3364. // Quality settings.
  3365. use_physical_light_units = GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units");
  3366. positional_soft_shadow_filter_set_quality((RS::ShadowQuality)(int)GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/soft_shadow_filter_quality"));
  3367. directional_soft_shadow_filter_set_quality((RS::ShadowQuality)(int)GLOBAL_GET("rendering/lights_and_shadows/directional_shadow/soft_shadow_filter_quality"));
  3368. lightmaps_set_bicubic_filter(GLOBAL_GET("rendering/lightmapping/lightmap_gi/use_bicubic_filter"));
  3369. {
  3370. // Setup Lights
  3371. config->max_renderable_lights = MIN(config->max_renderable_lights, config->max_uniform_buffer_size / (int)sizeof(RasterizerSceneGLES3::LightData));
  3372. config->max_lights_per_object = MIN(config->max_lights_per_object, config->max_renderable_lights);
  3373. uint32_t light_buffer_size = config->max_renderable_lights * sizeof(LightData);
  3374. scene_state.omni_lights = memnew_arr(LightData, config->max_renderable_lights);
  3375. scene_state.omni_light_sort = memnew_arr(InstanceSort<GLES3::LightInstance>, config->max_renderable_lights);
  3376. glGenBuffers(1, &scene_state.omni_light_buffer);
  3377. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.omni_light_buffer);
  3378. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.omni_light_buffer, light_buffer_size, nullptr, GL_STREAM_DRAW, "OmniLight UBO");
  3379. scene_state.spot_lights = memnew_arr(LightData, config->max_renderable_lights);
  3380. scene_state.spot_light_sort = memnew_arr(InstanceSort<GLES3::LightInstance>, config->max_renderable_lights);
  3381. glGenBuffers(1, &scene_state.spot_light_buffer);
  3382. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.spot_light_buffer);
  3383. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.spot_light_buffer, light_buffer_size, nullptr, GL_STREAM_DRAW, "SpotLight UBO");
  3384. uint32_t directional_light_buffer_size = MAX_DIRECTIONAL_LIGHTS * sizeof(DirectionalLightData);
  3385. scene_state.directional_lights = memnew_arr(DirectionalLightData, MAX_DIRECTIONAL_LIGHTS);
  3386. glGenBuffers(1, &scene_state.directional_light_buffer);
  3387. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.directional_light_buffer);
  3388. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.directional_light_buffer, directional_light_buffer_size, nullptr, GL_STREAM_DRAW, "DirectionalLight UBO");
  3389. uint32_t shadow_buffer_size = config->max_renderable_lights * sizeof(ShadowData) * 2;
  3390. scene_state.positional_shadows = memnew_arr(ShadowData, config->max_renderable_lights * 2);
  3391. glGenBuffers(1, &scene_state.positional_shadow_buffer);
  3392. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.positional_shadow_buffer);
  3393. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.positional_shadow_buffer, shadow_buffer_size, nullptr, GL_STREAM_DRAW, "Positional Shadow UBO");
  3394. uint32_t directional_shadow_buffer_size = MAX_DIRECTIONAL_LIGHTS * sizeof(DirectionalShadowData);
  3395. scene_state.directional_shadows = memnew_arr(DirectionalShadowData, MAX_DIRECTIONAL_LIGHTS);
  3396. glGenBuffers(1, &scene_state.directional_shadow_buffer);
  3397. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.directional_shadow_buffer);
  3398. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.directional_shadow_buffer, directional_shadow_buffer_size, nullptr, GL_STREAM_DRAW, "Directional Shadow UBO");
  3399. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3400. }
  3401. {
  3402. sky_globals.max_directional_lights = 4;
  3403. uint32_t directional_light_buffer_size = sky_globals.max_directional_lights * sizeof(DirectionalLightData);
  3404. sky_globals.directional_lights = memnew_arr(DirectionalLightData, sky_globals.max_directional_lights);
  3405. sky_globals.last_frame_directional_lights = memnew_arr(DirectionalLightData, sky_globals.max_directional_lights);
  3406. sky_globals.last_frame_directional_light_count = sky_globals.max_directional_lights + 1;
  3407. glGenBuffers(1, &sky_globals.directional_light_buffer);
  3408. glBindBuffer(GL_UNIFORM_BUFFER, sky_globals.directional_light_buffer);
  3409. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, sky_globals.directional_light_buffer, directional_light_buffer_size, nullptr, GL_STREAM_DRAW, "Sky DirectionalLight UBO");
  3410. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3411. }
  3412. {
  3413. String global_defines;
  3414. global_defines += "#define MAX_GLOBAL_SHADER_UNIFORMS 256\n"; // TODO: this is arbitrary for now
  3415. global_defines += "\n#define MAX_LIGHT_DATA_STRUCTS " + itos(config->max_renderable_lights) + "\n";
  3416. global_defines += "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(MAX_DIRECTIONAL_LIGHTS) + "\n";
  3417. global_defines += "\n#define MAX_FORWARD_LIGHTS " + itos(config->max_lights_per_object) + "u\n";
  3418. global_defines += "\n#define MAX_ROUGHNESS_LOD " + itos(sky_globals.roughness_layers - 1) + ".0\n";
  3419. if (config->force_vertex_shading) {
  3420. global_defines += "\n#define USE_VERTEX_LIGHTING\n";
  3421. }
  3422. material_storage->shaders.scene_shader.initialize(global_defines);
  3423. scene_globals.shader_default_version = material_storage->shaders.scene_shader.version_create();
  3424. material_storage->shaders.scene_shader.version_bind_shader(scene_globals.shader_default_version, SceneShaderGLES3::MODE_COLOR);
  3425. }
  3426. {
  3427. //default material and shader
  3428. scene_globals.default_shader = material_storage->shader_allocate();
  3429. material_storage->shader_initialize(scene_globals.default_shader);
  3430. material_storage->shader_set_code(scene_globals.default_shader, R"(
  3431. // Default 3D material shader (Compatibility).
  3432. shader_type spatial;
  3433. void vertex() {
  3434. ROUGHNESS = 0.8;
  3435. }
  3436. void fragment() {
  3437. ALBEDO = vec3(0.6);
  3438. ROUGHNESS = 0.8;
  3439. METALLIC = 0.2;
  3440. }
  3441. )");
  3442. scene_globals.default_material = material_storage->material_allocate();
  3443. material_storage->material_initialize(scene_globals.default_material);
  3444. material_storage->material_set_shader(scene_globals.default_material, scene_globals.default_shader);
  3445. default_material_data_ptr = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.default_material, RS::SHADER_SPATIAL));
  3446. }
  3447. {
  3448. // Overdraw material and shader.
  3449. scene_globals.overdraw_shader = material_storage->shader_allocate();
  3450. material_storage->shader_initialize(scene_globals.overdraw_shader);
  3451. material_storage->shader_set_code(scene_globals.overdraw_shader, R"(
  3452. // 3D editor Overdraw debug draw mode shader (Compatibility).
  3453. shader_type spatial;
  3454. render_mode blend_add, unshaded, fog_disabled;
  3455. void fragment() {
  3456. ALBEDO = vec3(0.4, 0.8, 0.8);
  3457. ALPHA = 0.2;
  3458. }
  3459. )");
  3460. scene_globals.overdraw_material = material_storage->material_allocate();
  3461. material_storage->material_initialize(scene_globals.overdraw_material);
  3462. material_storage->material_set_shader(scene_globals.overdraw_material, scene_globals.overdraw_shader);
  3463. overdraw_material_data_ptr = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.overdraw_material, RS::SHADER_SPATIAL));
  3464. }
  3465. {
  3466. // Initialize Sky stuff
  3467. sky_globals.roughness_layers = GLOBAL_GET("rendering/reflections/sky_reflections/roughness_layers");
  3468. String global_defines;
  3469. global_defines += "#define MAX_GLOBAL_SHADER_UNIFORMS 256\n"; // TODO: this is arbitrary for now
  3470. global_defines += "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(sky_globals.max_directional_lights) + "\n";
  3471. material_storage->shaders.sky_shader.initialize(global_defines);
  3472. sky_globals.shader_default_version = material_storage->shaders.sky_shader.version_create();
  3473. }
  3474. {
  3475. sky_globals.default_shader = material_storage->shader_allocate();
  3476. material_storage->shader_initialize(sky_globals.default_shader);
  3477. material_storage->shader_set_code(sky_globals.default_shader, R"(
  3478. // Default sky shader.
  3479. shader_type sky;
  3480. void sky() {
  3481. COLOR = vec3(0.0);
  3482. }
  3483. )");
  3484. sky_globals.default_material = material_storage->material_allocate();
  3485. material_storage->material_initialize(sky_globals.default_material);
  3486. material_storage->material_set_shader(sky_globals.default_material, sky_globals.default_shader);
  3487. }
  3488. {
  3489. sky_globals.fog_shader = material_storage->shader_allocate();
  3490. material_storage->shader_initialize(sky_globals.fog_shader);
  3491. material_storage->shader_set_code(sky_globals.fog_shader, R"(
  3492. // Default clear color sky shader.
  3493. shader_type sky;
  3494. uniform vec4 clear_color;
  3495. void sky() {
  3496. COLOR = clear_color.rgb;
  3497. }
  3498. )");
  3499. sky_globals.fog_material = material_storage->material_allocate();
  3500. material_storage->material_initialize(sky_globals.fog_material);
  3501. material_storage->material_set_shader(sky_globals.fog_material, sky_globals.fog_shader);
  3502. }
  3503. {
  3504. glGenVertexArrays(1, &sky_globals.screen_triangle_array);
  3505. glBindVertexArray(sky_globals.screen_triangle_array);
  3506. glGenBuffers(1, &sky_globals.screen_triangle);
  3507. glBindBuffer(GL_ARRAY_BUFFER, sky_globals.screen_triangle);
  3508. const float qv[6] = {
  3509. -1.0f,
  3510. -1.0f,
  3511. 3.0f,
  3512. -1.0f,
  3513. -1.0f,
  3514. 3.0f,
  3515. };
  3516. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, sky_globals.screen_triangle, sizeof(float) * 6, qv, GL_STATIC_DRAW, "Screen triangle vertex buffer");
  3517. glVertexAttribPointer(RS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, nullptr);
  3518. glEnableVertexAttribArray(RS::ARRAY_VERTEX);
  3519. glBindVertexArray(0);
  3520. glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
  3521. }
  3522. #ifdef GL_API_ENABLED
  3523. if (RasterizerGLES3::is_gles_over_gl()) {
  3524. glEnable(_EXT_TEXTURE_CUBE_MAP_SEAMLESS);
  3525. }
  3526. #endif // GL_API_ENABLED
  3527. // MultiMesh may read from color when color is disabled, so make sure that the color defaults to white instead of black;
  3528. glVertexAttrib4f(RS::ARRAY_COLOR, 1.0, 1.0, 1.0, 1.0);
  3529. }
  3530. RasterizerSceneGLES3::~RasterizerSceneGLES3() {
  3531. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.directional_light_buffer);
  3532. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.omni_light_buffer);
  3533. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.spot_light_buffer);
  3534. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.positional_shadow_buffer);
  3535. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.directional_shadow_buffer);
  3536. memdelete_arr(scene_state.directional_lights);
  3537. memdelete_arr(scene_state.omni_lights);
  3538. memdelete_arr(scene_state.spot_lights);
  3539. memdelete_arr(scene_state.omni_light_sort);
  3540. memdelete_arr(scene_state.spot_light_sort);
  3541. memdelete_arr(scene_state.positional_shadows);
  3542. memdelete_arr(scene_state.directional_shadows);
  3543. // Scene Shader
  3544. GLES3::MaterialStorage::get_singleton()->shaders.scene_shader.version_free(scene_globals.shader_default_version);
  3545. RSG::material_storage->material_free(scene_globals.default_material);
  3546. RSG::material_storage->shader_free(scene_globals.default_shader);
  3547. // Overdraw Shader
  3548. RSG::material_storage->material_free(scene_globals.overdraw_material);
  3549. RSG::material_storage->shader_free(scene_globals.overdraw_shader);
  3550. // Sky Shader
  3551. GLES3::MaterialStorage::get_singleton()->shaders.sky_shader.version_free(sky_globals.shader_default_version);
  3552. RSG::material_storage->material_free(sky_globals.default_material);
  3553. RSG::material_storage->shader_free(sky_globals.default_shader);
  3554. RSG::material_storage->material_free(sky_globals.fog_material);
  3555. RSG::material_storage->shader_free(sky_globals.fog_shader);
  3556. GLES3::Utilities::get_singleton()->buffer_free_data(sky_globals.screen_triangle);
  3557. glDeleteVertexArrays(1, &sky_globals.screen_triangle_array);
  3558. GLES3::Utilities::get_singleton()->buffer_free_data(sky_globals.directional_light_buffer);
  3559. memdelete_arr(sky_globals.directional_lights);
  3560. memdelete_arr(sky_globals.last_frame_directional_lights);
  3561. // UBOs
  3562. if (scene_state.ubo_buffer != 0) {
  3563. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.ubo_buffer);
  3564. }
  3565. if (scene_state.multiview_buffer != 0) {
  3566. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.multiview_buffer);
  3567. }
  3568. if (scene_state.tonemap_buffer != 0) {
  3569. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.tonemap_buffer);
  3570. }
  3571. singleton = nullptr;
  3572. }
  3573. #endif // GLES3_ENABLED