rasterizer_scene_gles3.cpp 185 KB

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