renderer_scene_cull.cpp 158 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105
  1. /*************************************************************************/
  2. /* renderer_scene_cull.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "renderer_scene_cull.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/os/os.h"
  33. #include "rendering_server_default.h"
  34. #include "rendering_server_globals.h"
  35. #include <new>
  36. /* CAMERA API */
  37. RID RendererSceneCull::camera_allocate() {
  38. return camera_owner.allocate_rid();
  39. }
  40. void RendererSceneCull::camera_initialize(RID p_rid) {
  41. camera_owner.initialize_rid(p_rid);
  42. }
  43. void RendererSceneCull::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {
  44. Camera *camera = camera_owner.get_or_null(p_camera);
  45. ERR_FAIL_COND(!camera);
  46. camera->type = Camera::PERSPECTIVE;
  47. camera->fov = p_fovy_degrees;
  48. camera->znear = p_z_near;
  49. camera->zfar = p_z_far;
  50. }
  51. void RendererSceneCull::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
  52. Camera *camera = camera_owner.get_or_null(p_camera);
  53. ERR_FAIL_COND(!camera);
  54. camera->type = Camera::ORTHOGONAL;
  55. camera->size = p_size;
  56. camera->znear = p_z_near;
  57. camera->zfar = p_z_far;
  58. }
  59. void RendererSceneCull::camera_set_frustum(RID p_camera, float p_size, Vector2 p_offset, float p_z_near, float p_z_far) {
  60. Camera *camera = camera_owner.get_or_null(p_camera);
  61. ERR_FAIL_COND(!camera);
  62. camera->type = Camera::FRUSTUM;
  63. camera->size = p_size;
  64. camera->offset = p_offset;
  65. camera->znear = p_z_near;
  66. camera->zfar = p_z_far;
  67. }
  68. void RendererSceneCull::camera_set_transform(RID p_camera, const Transform3D &p_transform) {
  69. Camera *camera = camera_owner.get_or_null(p_camera);
  70. ERR_FAIL_COND(!camera);
  71. camera->transform = p_transform.orthonormalized();
  72. }
  73. void RendererSceneCull::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {
  74. Camera *camera = camera_owner.get_or_null(p_camera);
  75. ERR_FAIL_COND(!camera);
  76. camera->visible_layers = p_layers;
  77. }
  78. void RendererSceneCull::camera_set_environment(RID p_camera, RID p_env) {
  79. Camera *camera = camera_owner.get_or_null(p_camera);
  80. ERR_FAIL_COND(!camera);
  81. camera->env = p_env;
  82. }
  83. void RendererSceneCull::camera_set_camera_effects(RID p_camera, RID p_fx) {
  84. Camera *camera = camera_owner.get_or_null(p_camera);
  85. ERR_FAIL_COND(!camera);
  86. camera->effects = p_fx;
  87. }
  88. void RendererSceneCull::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {
  89. Camera *camera = camera_owner.get_or_null(p_camera);
  90. ERR_FAIL_COND(!camera);
  91. camera->vaspect = p_enable;
  92. }
  93. bool RendererSceneCull::is_camera(RID p_camera) const {
  94. return camera_owner.owns(p_camera);
  95. }
  96. /* OCCLUDER API */
  97. RID RendererSceneCull::occluder_allocate() {
  98. return RendererSceneOcclusionCull::get_singleton()->occluder_allocate();
  99. }
  100. void RendererSceneCull::occluder_initialize(RID p_rid) {
  101. RendererSceneOcclusionCull::get_singleton()->occluder_initialize(p_rid);
  102. }
  103. void RendererSceneCull::occluder_set_mesh(RID p_occluder, const PackedVector3Array &p_vertices, const PackedInt32Array &p_indices) {
  104. RendererSceneOcclusionCull::get_singleton()->occluder_set_mesh(p_occluder, p_vertices, p_indices);
  105. }
  106. /* SCENARIO API */
  107. void RendererSceneCull::_instance_pair(Instance *p_A, Instance *p_B) {
  108. RendererSceneCull *self = (RendererSceneCull *)singleton;
  109. Instance *A = p_A;
  110. Instance *B = p_B;
  111. //instance indices are designed so greater always contains lesser
  112. if (A->base_type > B->base_type) {
  113. SWAP(A, B); //lesser always first
  114. }
  115. if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  116. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  117. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  118. geom->lights.insert(B);
  119. light->geometries.insert(A);
  120. if (geom->can_cast_shadows) {
  121. light->shadow_dirty = true;
  122. }
  123. if (A->scenario && A->array_index >= 0) {
  124. InstanceData &idata = A->scenario->instance_data[A->array_index];
  125. idata.flags |= InstanceData::FLAG_GEOM_LIGHTING_DIRTY;
  126. }
  127. if (light->uses_projector) {
  128. geom->projector_count++;
  129. if (geom->projector_count == 1) {
  130. InstanceData &idata = A->scenario->instance_data[A->array_index];
  131. idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
  132. }
  133. }
  134. if (light->uses_softshadow) {
  135. geom->softshadow_count++;
  136. if (geom->softshadow_count == 1) {
  137. InstanceData &idata = A->scenario->instance_data[A->array_index];
  138. idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
  139. }
  140. }
  141. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  142. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  143. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  144. geom->reflection_probes.insert(B);
  145. reflection_probe->geometries.insert(A);
  146. if (A->scenario && A->array_index >= 0) {
  147. InstanceData &idata = A->scenario->instance_data[A->array_index];
  148. idata.flags |= InstanceData::FLAG_GEOM_REFLECTION_DIRTY;
  149. }
  150. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  151. InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
  152. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  153. geom->decals.insert(B);
  154. decal->geometries.insert(A);
  155. if (A->scenario && A->array_index >= 0) {
  156. InstanceData &idata = A->scenario->instance_data[A->array_index];
  157. idata.flags |= InstanceData::FLAG_GEOM_DECAL_DIRTY;
  158. }
  159. } else if (B->base_type == RS::INSTANCE_LIGHTMAP && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  160. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(B->base_data);
  161. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  162. if (A->dynamic_gi) {
  163. geom->lightmap_captures.insert(A);
  164. lightmap_data->geometries.insert(B);
  165. if (A->scenario && A->array_index >= 0) {
  166. InstanceData &idata = A->scenario->instance_data[A->array_index];
  167. idata.flags |= InstanceData::FLAG_LIGHTMAP_CAPTURE;
  168. }
  169. ((RendererSceneCull *)self)->_instance_queue_update(A, false, false); //need to update capture
  170. }
  171. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_VOXEL_GI) && B->base_type == RS::INSTANCE_VOXEL_GI && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  172. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
  173. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  174. geom->voxel_gi_instances.insert(B);
  175. if (A->dynamic_gi) {
  176. voxel_gi->dynamic_geometries.insert(A);
  177. } else {
  178. voxel_gi->geometries.insert(A);
  179. }
  180. if (A->scenario && A->array_index >= 0) {
  181. InstanceData &idata = A->scenario->instance_data[A->array_index];
  182. idata.flags |= InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY;
  183. }
  184. } else if (B->base_type == RS::INSTANCE_VOXEL_GI && A->base_type == RS::INSTANCE_LIGHT) {
  185. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
  186. voxel_gi->lights.insert(A);
  187. } else if (B->base_type == RS::INSTANCE_PARTICLES_COLLISION && A->base_type == RS::INSTANCE_PARTICLES) {
  188. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(B->base_data);
  189. RSG::particles_storage->particles_add_collision(A->base, collision->instance);
  190. }
  191. }
  192. void RendererSceneCull::_instance_unpair(Instance *p_A, Instance *p_B) {
  193. RendererSceneCull *self = (RendererSceneCull *)singleton;
  194. Instance *A = p_A;
  195. Instance *B = p_B;
  196. //instance indices are designed so greater always contains lesser
  197. if (A->base_type > B->base_type) {
  198. SWAP(A, B); //lesser always first
  199. }
  200. if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  201. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  202. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  203. geom->lights.erase(B);
  204. light->geometries.erase(A);
  205. if (geom->can_cast_shadows) {
  206. light->shadow_dirty = true;
  207. }
  208. if (A->scenario && A->array_index >= 0) {
  209. InstanceData &idata = A->scenario->instance_data[A->array_index];
  210. idata.flags |= InstanceData::FLAG_GEOM_LIGHTING_DIRTY;
  211. }
  212. if (light->uses_projector) {
  213. #ifdef DEBUG_ENABLED
  214. if (geom->projector_count == 0) {
  215. ERR_PRINT("geom->projector_count==0 - BUG!");
  216. }
  217. #endif
  218. geom->projector_count--;
  219. if (geom->projector_count == 0) {
  220. InstanceData &idata = A->scenario->instance_data[A->array_index];
  221. idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
  222. }
  223. }
  224. if (light->uses_softshadow) {
  225. #ifdef DEBUG_ENABLED
  226. if (geom->softshadow_count == 0) {
  227. ERR_PRINT("geom->softshadow_count==0 - BUG!");
  228. }
  229. #endif
  230. geom->softshadow_count--;
  231. if (geom->softshadow_count == 0) {
  232. InstanceData &idata = A->scenario->instance_data[A->array_index];
  233. idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
  234. }
  235. }
  236. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  237. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  238. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  239. geom->reflection_probes.erase(B);
  240. reflection_probe->geometries.erase(A);
  241. if (A->scenario && A->array_index >= 0) {
  242. InstanceData &idata = A->scenario->instance_data[A->array_index];
  243. idata.flags |= InstanceData::FLAG_GEOM_REFLECTION_DIRTY;
  244. }
  245. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  246. InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
  247. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  248. geom->decals.erase(B);
  249. decal->geometries.erase(A);
  250. if (A->scenario && A->array_index >= 0) {
  251. InstanceData &idata = A->scenario->instance_data[A->array_index];
  252. idata.flags |= InstanceData::FLAG_GEOM_DECAL_DIRTY;
  253. }
  254. } else if (B->base_type == RS::INSTANCE_LIGHTMAP && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  255. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(B->base_data);
  256. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  257. if (A->dynamic_gi) {
  258. geom->lightmap_captures.erase(B);
  259. if (geom->lightmap_captures.is_empty() && A->scenario && A->array_index >= 0) {
  260. InstanceData &idata = A->scenario->instance_data[A->array_index];
  261. idata.flags &= ~uint32_t(InstanceData::FLAG_LIGHTMAP_CAPTURE);
  262. }
  263. lightmap_data->geometries.erase(A);
  264. ((RendererSceneCull *)self)->_instance_queue_update(A, false, false); //need to update capture
  265. }
  266. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_VOXEL_GI) && B->base_type == RS::INSTANCE_VOXEL_GI && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  267. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
  268. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  269. geom->voxel_gi_instances.erase(B);
  270. if (A->dynamic_gi) {
  271. voxel_gi->dynamic_geometries.erase(A);
  272. } else {
  273. voxel_gi->geometries.erase(A);
  274. }
  275. if (A->scenario && A->array_index >= 0) {
  276. InstanceData &idata = A->scenario->instance_data[A->array_index];
  277. idata.flags |= InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY;
  278. }
  279. } else if (B->base_type == RS::INSTANCE_VOXEL_GI && A->base_type == RS::INSTANCE_LIGHT) {
  280. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
  281. voxel_gi->lights.erase(A);
  282. } else if (B->base_type == RS::INSTANCE_PARTICLES_COLLISION && A->base_type == RS::INSTANCE_PARTICLES) {
  283. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(B->base_data);
  284. RSG::particles_storage->particles_remove_collision(A->base, collision->instance);
  285. }
  286. }
  287. RID RendererSceneCull::scenario_allocate() {
  288. return scenario_owner.allocate_rid();
  289. }
  290. void RendererSceneCull::scenario_initialize(RID p_rid) {
  291. scenario_owner.initialize_rid(p_rid);
  292. Scenario *scenario = scenario_owner.get_or_null(p_rid);
  293. scenario->self = p_rid;
  294. scenario->reflection_probe_shadow_atlas = scene_render->shadow_atlas_create();
  295. scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
  296. scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
  297. scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
  298. scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
  299. scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
  300. scenario->reflection_atlas = scene_render->reflection_atlas_create();
  301. scenario->instance_aabbs.set_page_pool(&instance_aabb_page_pool);
  302. scenario->instance_data.set_page_pool(&instance_data_page_pool);
  303. scenario->instance_visibility.set_page_pool(&instance_visibility_data_page_pool);
  304. RendererSceneOcclusionCull::get_singleton()->add_scenario(p_rid);
  305. }
  306. void RendererSceneCull::scenario_set_environment(RID p_scenario, RID p_environment) {
  307. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  308. ERR_FAIL_COND(!scenario);
  309. scenario->environment = p_environment;
  310. }
  311. void RendererSceneCull::scenario_set_camera_effects(RID p_scenario, RID p_camera_effects) {
  312. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  313. ERR_FAIL_COND(!scenario);
  314. scenario->camera_effects = p_camera_effects;
  315. }
  316. void RendererSceneCull::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {
  317. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  318. ERR_FAIL_COND(!scenario);
  319. scenario->fallback_environment = p_environment;
  320. }
  321. void RendererSceneCull::scenario_set_reflection_atlas_size(RID p_scenario, int p_reflection_size, int p_reflection_count) {
  322. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  323. ERR_FAIL_COND(!scenario);
  324. scene_render->reflection_atlas_set_size(scenario->reflection_atlas, p_reflection_size, p_reflection_count);
  325. }
  326. bool RendererSceneCull::is_scenario(RID p_scenario) const {
  327. return scenario_owner.owns(p_scenario);
  328. }
  329. RID RendererSceneCull::scenario_get_environment(RID p_scenario) {
  330. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  331. ERR_FAIL_COND_V(!scenario, RID());
  332. return scenario->environment;
  333. }
  334. void RendererSceneCull::scenario_remove_viewport_visibility_mask(RID p_scenario, RID p_viewport) {
  335. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  336. ERR_FAIL_COND(!scenario);
  337. if (!scenario->viewport_visibility_masks.has(p_viewport)) {
  338. return;
  339. }
  340. uint64_t mask = scenario->viewport_visibility_masks[p_viewport];
  341. scenario->used_viewport_visibility_bits &= ~mask;
  342. scenario->viewport_visibility_masks.erase(p_viewport);
  343. }
  344. void RendererSceneCull::scenario_add_viewport_visibility_mask(RID p_scenario, RID p_viewport) {
  345. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  346. ERR_FAIL_COND(!scenario);
  347. ERR_FAIL_COND(scenario->viewport_visibility_masks.has(p_viewport));
  348. uint64_t new_mask = 1;
  349. while (new_mask & scenario->used_viewport_visibility_bits) {
  350. new_mask <<= 1;
  351. }
  352. if (new_mask == 0) {
  353. ERR_PRINT("Only 64 viewports per scenario allowed when using visibility ranges.");
  354. new_mask = ((uint64_t)1) << 63;
  355. }
  356. scenario->viewport_visibility_masks[p_viewport] = new_mask;
  357. scenario->used_viewport_visibility_bits |= new_mask;
  358. }
  359. /* INSTANCING API */
  360. void RendererSceneCull::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_dependencies) {
  361. if (p_update_aabb) {
  362. p_instance->update_aabb = true;
  363. }
  364. if (p_update_dependencies) {
  365. p_instance->update_dependencies = true;
  366. }
  367. if (p_instance->update_item.in_list()) {
  368. return;
  369. }
  370. _instance_update_list.add(&p_instance->update_item);
  371. }
  372. RID RendererSceneCull::instance_allocate() {
  373. return instance_owner.allocate_rid();
  374. }
  375. void RendererSceneCull::instance_initialize(RID p_rid) {
  376. instance_owner.initialize_rid(p_rid);
  377. Instance *instance = instance_owner.get_or_null(p_rid);
  378. instance->self = p_rid;
  379. }
  380. void RendererSceneCull::_instance_update_mesh_instance(Instance *p_instance) {
  381. bool needs_instance = RSG::mesh_storage->mesh_needs_instance(p_instance->base, p_instance->skeleton.is_valid());
  382. if (needs_instance != p_instance->mesh_instance.is_valid()) {
  383. if (needs_instance) {
  384. p_instance->mesh_instance = RSG::mesh_storage->mesh_instance_create(p_instance->base);
  385. } else {
  386. RSG::mesh_storage->mesh_instance_free(p_instance->mesh_instance);
  387. p_instance->mesh_instance = RID();
  388. }
  389. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  390. geom->geometry_instance->set_mesh_instance(p_instance->mesh_instance);
  391. if (p_instance->scenario && p_instance->array_index >= 0) {
  392. InstanceData &idata = p_instance->scenario->instance_data[p_instance->array_index];
  393. if (p_instance->mesh_instance.is_valid()) {
  394. idata.flags |= InstanceData::FLAG_USES_MESH_INSTANCE;
  395. } else {
  396. idata.flags &= ~uint32_t(InstanceData::FLAG_USES_MESH_INSTANCE);
  397. }
  398. }
  399. }
  400. if (p_instance->mesh_instance.is_valid()) {
  401. RSG::mesh_storage->mesh_instance_set_skeleton(p_instance->mesh_instance, p_instance->skeleton);
  402. }
  403. }
  404. void RendererSceneCull::instance_set_base(RID p_instance, RID p_base) {
  405. Instance *instance = instance_owner.get_or_null(p_instance);
  406. ERR_FAIL_COND(!instance);
  407. Scenario *scenario = instance->scenario;
  408. if (instance->base_type != RS::INSTANCE_NONE) {
  409. //free anything related to that base
  410. if (scenario && instance->indexer_id.is_valid()) {
  411. _unpair_instance(instance);
  412. }
  413. if (instance->mesh_instance.is_valid()) {
  414. RSG::mesh_storage->mesh_instance_free(instance->mesh_instance);
  415. instance->mesh_instance = RID();
  416. // no need to set instance data flag here, as it was freed above
  417. }
  418. switch (instance->base_type) {
  419. case RS::INSTANCE_MESH:
  420. case RS::INSTANCE_MULTIMESH:
  421. case RS::INSTANCE_PARTICLES: {
  422. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  423. scene_render->geometry_instance_free(geom->geometry_instance);
  424. } break;
  425. case RS::INSTANCE_LIGHT: {
  426. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  427. if (scenario && instance->visible && RSG::light_storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  428. scenario->dynamic_lights.erase(light->instance);
  429. }
  430. #ifdef DEBUG_ENABLED
  431. if (light->geometries.size()) {
  432. ERR_PRINT("BUG, indexing did not unpair geometries from light.");
  433. }
  434. #endif
  435. if (scenario && light->D) {
  436. scenario->directional_lights.erase(light->D);
  437. light->D = nullptr;
  438. }
  439. scene_render->free(light->instance);
  440. } break;
  441. case RS::INSTANCE_PARTICLES_COLLISION: {
  442. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(instance->base_data);
  443. RSG::utilities->free(collision->instance);
  444. } break;
  445. case RS::INSTANCE_FOG_VOLUME: {
  446. InstanceFogVolumeData *volume = static_cast<InstanceFogVolumeData *>(instance->base_data);
  447. scene_render->free(volume->instance);
  448. } break;
  449. case RS::INSTANCE_VISIBLITY_NOTIFIER: {
  450. //none
  451. } break;
  452. case RS::INSTANCE_REFLECTION_PROBE: {
  453. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  454. scene_render->free(reflection_probe->instance);
  455. if (reflection_probe->update_list.in_list()) {
  456. reflection_probe_render_list.remove(&reflection_probe->update_list);
  457. }
  458. } break;
  459. case RS::INSTANCE_DECAL: {
  460. InstanceDecalData *decal = static_cast<InstanceDecalData *>(instance->base_data);
  461. scene_render->free(decal->instance);
  462. } break;
  463. case RS::INSTANCE_LIGHTMAP: {
  464. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(instance->base_data);
  465. //erase dependencies, since no longer a lightmap
  466. while (lightmap_data->users.begin()) {
  467. instance_geometry_set_lightmap((*lightmap_data->users.begin())->self, RID(), Rect2(), 0);
  468. }
  469. scene_render->free(lightmap_data->instance);
  470. } break;
  471. case RS::INSTANCE_VOXEL_GI: {
  472. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(instance->base_data);
  473. #ifdef DEBUG_ENABLED
  474. if (voxel_gi->geometries.size()) {
  475. ERR_PRINT("BUG, indexing did not unpair geometries from VoxelGI.");
  476. }
  477. #endif
  478. #ifdef DEBUG_ENABLED
  479. if (voxel_gi->lights.size()) {
  480. ERR_PRINT("BUG, indexing did not unpair lights from VoxelGI.");
  481. }
  482. #endif
  483. if (voxel_gi->update_element.in_list()) {
  484. voxel_gi_update_list.remove(&voxel_gi->update_element);
  485. }
  486. scene_render->free(voxel_gi->probe_instance);
  487. } break;
  488. case RS::INSTANCE_OCCLUDER: {
  489. if (scenario && instance->visible) {
  490. RendererSceneOcclusionCull::get_singleton()->scenario_remove_instance(instance->scenario->self, p_instance);
  491. }
  492. } break;
  493. default: {
  494. }
  495. }
  496. if (instance->base_data) {
  497. memdelete(instance->base_data);
  498. instance->base_data = nullptr;
  499. }
  500. instance->materials.clear();
  501. }
  502. instance->base_type = RS::INSTANCE_NONE;
  503. instance->base = RID();
  504. if (p_base.is_valid()) {
  505. instance->base_type = RSG::utilities->get_base_type(p_base);
  506. // fix up a specific malfunctioning case before the switch, so it can be handled
  507. if (instance->base_type == RS::INSTANCE_NONE && RendererSceneOcclusionCull::get_singleton()->is_occluder(p_base)) {
  508. instance->base_type = RS::INSTANCE_OCCLUDER;
  509. }
  510. switch (instance->base_type) {
  511. case RS::INSTANCE_NONE: {
  512. ERR_PRINT_ONCE("unimplemented base type encountered in renderer scene cull");
  513. return;
  514. }
  515. case RS::INSTANCE_LIGHT: {
  516. InstanceLightData *light = memnew(InstanceLightData);
  517. if (scenario && RSG::light_storage->light_get_type(p_base) == RS::LIGHT_DIRECTIONAL) {
  518. light->D = scenario->directional_lights.push_back(instance);
  519. }
  520. light->instance = scene_render->light_instance_create(p_base);
  521. instance->base_data = light;
  522. } break;
  523. case RS::INSTANCE_MESH:
  524. case RS::INSTANCE_MULTIMESH:
  525. case RS::INSTANCE_PARTICLES: {
  526. InstanceGeometryData *geom = memnew(InstanceGeometryData);
  527. instance->base_data = geom;
  528. geom->geometry_instance = scene_render->geometry_instance_create(p_base);
  529. ERR_FAIL_NULL(geom->geometry_instance);
  530. geom->geometry_instance->set_skeleton(instance->skeleton);
  531. geom->geometry_instance->set_material_override(instance->material_override);
  532. geom->geometry_instance->set_material_overlay(instance->material_overlay);
  533. geom->geometry_instance->set_surface_materials(instance->materials);
  534. geom->geometry_instance->set_transform(instance->transform, instance->aabb, instance->transformed_aabb);
  535. geom->geometry_instance->set_layer_mask(instance->layer_mask);
  536. geom->geometry_instance->set_lod_bias(instance->lod_bias);
  537. geom->geometry_instance->set_transparency(instance->transparency);
  538. geom->geometry_instance->set_use_baked_light(instance->baked_light);
  539. geom->geometry_instance->set_use_dynamic_gi(instance->dynamic_gi);
  540. geom->geometry_instance->set_use_lightmap(RID(), instance->lightmap_uv_scale, instance->lightmap_slice_index);
  541. geom->geometry_instance->set_cast_double_sided_shadows(instance->cast_shadows == RS::SHADOW_CASTING_SETTING_DOUBLE_SIDED);
  542. if (instance->lightmap_sh.size() == 9) {
  543. geom->geometry_instance->set_lightmap_capture(instance->lightmap_sh.ptr());
  544. }
  545. for (Instance *E : instance->visibility_dependencies) {
  546. Instance *dep_instance = E;
  547. ERR_CONTINUE(dep_instance->array_index == -1);
  548. ERR_CONTINUE(dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index != -1);
  549. dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = instance->array_index;
  550. }
  551. } break;
  552. case RS::INSTANCE_PARTICLES_COLLISION: {
  553. InstanceParticlesCollisionData *collision = memnew(InstanceParticlesCollisionData);
  554. collision->instance = RSG::particles_storage->particles_collision_instance_create(p_base);
  555. RSG::particles_storage->particles_collision_instance_set_active(collision->instance, instance->visible);
  556. instance->base_data = collision;
  557. } break;
  558. case RS::INSTANCE_FOG_VOLUME: {
  559. InstanceFogVolumeData *volume = memnew(InstanceFogVolumeData);
  560. volume->instance = scene_render->fog_volume_instance_create(p_base);
  561. scene_render->fog_volume_instance_set_active(volume->instance, instance->visible);
  562. instance->base_data = volume;
  563. } break;
  564. case RS::INSTANCE_VISIBLITY_NOTIFIER: {
  565. InstanceVisibilityNotifierData *vnd = memnew(InstanceVisibilityNotifierData);
  566. vnd->base = p_base;
  567. instance->base_data = vnd;
  568. } break;
  569. case RS::INSTANCE_REFLECTION_PROBE: {
  570. InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
  571. reflection_probe->owner = instance;
  572. instance->base_data = reflection_probe;
  573. reflection_probe->instance = scene_render->reflection_probe_instance_create(p_base);
  574. } break;
  575. case RS::INSTANCE_DECAL: {
  576. InstanceDecalData *decal = memnew(InstanceDecalData);
  577. decal->owner = instance;
  578. instance->base_data = decal;
  579. decal->instance = scene_render->decal_instance_create(p_base);
  580. } break;
  581. case RS::INSTANCE_LIGHTMAP: {
  582. InstanceLightmapData *lightmap_data = memnew(InstanceLightmapData);
  583. instance->base_data = lightmap_data;
  584. lightmap_data->instance = scene_render->lightmap_instance_create(p_base);
  585. } break;
  586. case RS::INSTANCE_VOXEL_GI: {
  587. InstanceVoxelGIData *voxel_gi = memnew(InstanceVoxelGIData);
  588. instance->base_data = voxel_gi;
  589. voxel_gi->owner = instance;
  590. if (scenario && !voxel_gi->update_element.in_list()) {
  591. voxel_gi_update_list.add(&voxel_gi->update_element);
  592. }
  593. voxel_gi->probe_instance = scene_render->voxel_gi_instance_create(p_base);
  594. } break;
  595. case RS::INSTANCE_OCCLUDER: {
  596. if (scenario) {
  597. RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(scenario->self, p_instance, p_base, instance->transform, instance->visible);
  598. }
  599. } break;
  600. default: {
  601. }
  602. }
  603. instance->base = p_base;
  604. if (instance->base_type == RS::INSTANCE_MESH) {
  605. _instance_update_mesh_instance(instance);
  606. }
  607. //forcefully update the dependency now, so if for some reason it gets removed, we can immediately clear it
  608. RSG::utilities->base_update_dependency(p_base, &instance->dependency_tracker);
  609. }
  610. _instance_queue_update(instance, true, true);
  611. }
  612. void RendererSceneCull::instance_set_scenario(RID p_instance, RID p_scenario) {
  613. Instance *instance = instance_owner.get_or_null(p_instance);
  614. ERR_FAIL_COND(!instance);
  615. if (instance->scenario) {
  616. instance->scenario->instances.remove(&instance->scenario_item);
  617. if (instance->indexer_id.is_valid()) {
  618. _unpair_instance(instance);
  619. }
  620. switch (instance->base_type) {
  621. case RS::INSTANCE_LIGHT: {
  622. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  623. #ifdef DEBUG_ENABLED
  624. if (light->geometries.size()) {
  625. ERR_PRINT("BUG, indexing did not unpair geometries from light.");
  626. }
  627. #endif
  628. if (light->D) {
  629. instance->scenario->directional_lights.erase(light->D);
  630. light->D = nullptr;
  631. }
  632. } break;
  633. case RS::INSTANCE_REFLECTION_PROBE: {
  634. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  635. scene_render->reflection_probe_release_atlas_index(reflection_probe->instance);
  636. } break;
  637. case RS::INSTANCE_PARTICLES_COLLISION: {
  638. heightfield_particle_colliders_update_list.erase(instance);
  639. } break;
  640. case RS::INSTANCE_VOXEL_GI: {
  641. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(instance->base_data);
  642. #ifdef DEBUG_ENABLED
  643. if (voxel_gi->geometries.size()) {
  644. ERR_PRINT("BUG, indexing did not unpair geometries from VoxelGI.");
  645. }
  646. #endif
  647. #ifdef DEBUG_ENABLED
  648. if (voxel_gi->lights.size()) {
  649. ERR_PRINT("BUG, indexing did not unpair lights from VoxelGI.");
  650. }
  651. #endif
  652. if (voxel_gi->update_element.in_list()) {
  653. voxel_gi_update_list.remove(&voxel_gi->update_element);
  654. }
  655. } break;
  656. case RS::INSTANCE_OCCLUDER: {
  657. if (instance->visible) {
  658. RendererSceneOcclusionCull::get_singleton()->scenario_remove_instance(instance->scenario->self, p_instance);
  659. }
  660. } break;
  661. default: {
  662. }
  663. }
  664. instance->scenario = nullptr;
  665. }
  666. if (p_scenario.is_valid()) {
  667. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  668. ERR_FAIL_COND(!scenario);
  669. instance->scenario = scenario;
  670. scenario->instances.add(&instance->scenario_item);
  671. switch (instance->base_type) {
  672. case RS::INSTANCE_LIGHT: {
  673. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  674. if (RSG::light_storage->light_get_type(instance->base) == RS::LIGHT_DIRECTIONAL) {
  675. light->D = scenario->directional_lights.push_back(instance);
  676. }
  677. } break;
  678. case RS::INSTANCE_VOXEL_GI: {
  679. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(instance->base_data);
  680. if (!voxel_gi->update_element.in_list()) {
  681. voxel_gi_update_list.add(&voxel_gi->update_element);
  682. }
  683. } break;
  684. case RS::INSTANCE_OCCLUDER: {
  685. RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(scenario->self, p_instance, instance->base, instance->transform, instance->visible);
  686. } break;
  687. default: {
  688. }
  689. }
  690. _instance_queue_update(instance, true, true);
  691. }
  692. }
  693. void RendererSceneCull::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {
  694. Instance *instance = instance_owner.get_or_null(p_instance);
  695. ERR_FAIL_COND(!instance);
  696. instance->layer_mask = p_mask;
  697. if (instance->scenario && instance->array_index >= 0) {
  698. instance->scenario->instance_data[instance->array_index].layer_mask = p_mask;
  699. }
  700. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  701. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  702. ERR_FAIL_NULL(geom->geometry_instance);
  703. geom->geometry_instance->set_layer_mask(p_mask);
  704. }
  705. }
  706. void RendererSceneCull::instance_geometry_set_transparency(RID p_instance, float p_transparency) {
  707. Instance *instance = instance_owner.get_or_null(p_instance);
  708. ERR_FAIL_COND(!instance);
  709. instance->transparency = p_transparency;
  710. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  711. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  712. ERR_FAIL_NULL(geom->geometry_instance);
  713. geom->geometry_instance->set_transparency(p_transparency);
  714. }
  715. }
  716. void RendererSceneCull::instance_set_transform(RID p_instance, const Transform3D &p_transform) {
  717. Instance *instance = instance_owner.get_or_null(p_instance);
  718. ERR_FAIL_COND(!instance);
  719. if (instance->transform == p_transform) {
  720. return; //must be checked to avoid worst evil
  721. }
  722. #ifdef DEBUG_ENABLED
  723. for (int i = 0; i < 4; i++) {
  724. const Vector3 &v = i < 3 ? p_transform.basis.rows[i] : p_transform.origin;
  725. ERR_FAIL_COND(Math::is_inf(v.x));
  726. ERR_FAIL_COND(Math::is_nan(v.x));
  727. ERR_FAIL_COND(Math::is_inf(v.y));
  728. ERR_FAIL_COND(Math::is_nan(v.y));
  729. ERR_FAIL_COND(Math::is_inf(v.z));
  730. ERR_FAIL_COND(Math::is_nan(v.z));
  731. }
  732. #endif
  733. instance->transform = p_transform;
  734. _instance_queue_update(instance, true);
  735. }
  736. void RendererSceneCull::instance_attach_object_instance_id(RID p_instance, ObjectID p_id) {
  737. Instance *instance = instance_owner.get_or_null(p_instance);
  738. ERR_FAIL_COND(!instance);
  739. instance->object_id = p_id;
  740. }
  741. void RendererSceneCull::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {
  742. Instance *instance = instance_owner.get_or_null(p_instance);
  743. ERR_FAIL_COND(!instance);
  744. if (instance->update_item.in_list()) {
  745. _update_dirty_instance(instance);
  746. }
  747. if (instance->mesh_instance.is_valid()) {
  748. RSG::mesh_storage->mesh_instance_set_blend_shape_weight(instance->mesh_instance, p_shape, p_weight);
  749. }
  750. }
  751. void RendererSceneCull::instance_set_surface_override_material(RID p_instance, int p_surface, RID p_material) {
  752. Instance *instance = instance_owner.get_or_null(p_instance);
  753. ERR_FAIL_COND(!instance);
  754. if (instance->base_type == RS::INSTANCE_MESH) {
  755. //may not have been updated yet, may also have not been set yet. When updated will be correcte, worst case
  756. instance->materials.resize(MAX(p_surface + 1, RSG::mesh_storage->mesh_get_surface_count(instance->base)));
  757. }
  758. ERR_FAIL_INDEX(p_surface, instance->materials.size());
  759. instance->materials.write[p_surface] = p_material;
  760. _instance_queue_update(instance, false, true);
  761. }
  762. void RendererSceneCull::instance_set_visible(RID p_instance, bool p_visible) {
  763. Instance *instance = instance_owner.get_or_null(p_instance);
  764. ERR_FAIL_COND(!instance);
  765. if (instance->visible == p_visible) {
  766. return;
  767. }
  768. instance->visible = p_visible;
  769. if (p_visible) {
  770. if (instance->scenario != nullptr) {
  771. _instance_queue_update(instance, true, false);
  772. }
  773. } else if (instance->indexer_id.is_valid()) {
  774. _unpair_instance(instance);
  775. }
  776. if (instance->base_type == RS::INSTANCE_LIGHT) {
  777. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  778. if (instance->scenario && RSG::light_storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  779. if (p_visible) {
  780. instance->scenario->dynamic_lights.push_back(light->instance);
  781. } else {
  782. instance->scenario->dynamic_lights.erase(light->instance);
  783. }
  784. }
  785. }
  786. if (instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
  787. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(instance->base_data);
  788. RSG::particles_storage->particles_collision_instance_set_active(collision->instance, p_visible);
  789. }
  790. if (instance->base_type == RS::INSTANCE_FOG_VOLUME) {
  791. InstanceFogVolumeData *volume = static_cast<InstanceFogVolumeData *>(instance->base_data);
  792. scene_render->fog_volume_instance_set_active(volume->instance, p_visible);
  793. }
  794. if (instance->base_type == RS::INSTANCE_OCCLUDER) {
  795. if (instance->scenario) {
  796. RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(instance->scenario->self, p_instance, instance->base, instance->transform, p_visible);
  797. }
  798. }
  799. }
  800. inline bool is_geometry_instance(RenderingServer::InstanceType p_type) {
  801. return p_type == RS::INSTANCE_MESH || p_type == RS::INSTANCE_MULTIMESH || p_type == RS::INSTANCE_PARTICLES;
  802. }
  803. void RendererSceneCull::instance_set_custom_aabb(RID p_instance, AABB p_aabb) {
  804. Instance *instance = instance_owner.get_or_null(p_instance);
  805. ERR_FAIL_COND(!instance);
  806. ERR_FAIL_COND(!is_geometry_instance(instance->base_type));
  807. if (p_aabb != AABB()) {
  808. // Set custom AABB
  809. if (instance->custom_aabb == nullptr) {
  810. instance->custom_aabb = memnew(AABB);
  811. }
  812. *instance->custom_aabb = p_aabb;
  813. } else {
  814. // Clear custom AABB
  815. if (instance->custom_aabb != nullptr) {
  816. memdelete(instance->custom_aabb);
  817. instance->custom_aabb = nullptr;
  818. }
  819. }
  820. if (instance->scenario) {
  821. _instance_queue_update(instance, true, false);
  822. }
  823. }
  824. void RendererSceneCull::instance_attach_skeleton(RID p_instance, RID p_skeleton) {
  825. Instance *instance = instance_owner.get_or_null(p_instance);
  826. ERR_FAIL_COND(!instance);
  827. if (instance->skeleton == p_skeleton) {
  828. return;
  829. }
  830. instance->skeleton = p_skeleton;
  831. if (p_skeleton.is_valid()) {
  832. //update the dependency now, so if cleared, we remove it
  833. RSG::mesh_storage->skeleton_update_dependency(p_skeleton, &instance->dependency_tracker);
  834. }
  835. _instance_queue_update(instance, true, true);
  836. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  837. _instance_update_mesh_instance(instance);
  838. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  839. ERR_FAIL_NULL(geom->geometry_instance);
  840. geom->geometry_instance->set_skeleton(p_skeleton);
  841. }
  842. }
  843. void RendererSceneCull::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
  844. Instance *instance = instance_owner.get_or_null(p_instance);
  845. ERR_FAIL_COND(!instance);
  846. instance->extra_margin = p_margin;
  847. _instance_queue_update(instance, true, false);
  848. }
  849. void RendererSceneCull::instance_set_ignore_culling(RID p_instance, bool p_enabled) {
  850. Instance *instance = instance_owner.get_or_null(p_instance);
  851. ERR_FAIL_COND(!instance);
  852. instance->ignore_all_culling = p_enabled;
  853. if (instance->scenario && instance->array_index >= 0) {
  854. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  855. if (instance->ignore_all_culling) {
  856. idata.flags |= InstanceData::FLAG_IGNORE_ALL_CULLING;
  857. } else {
  858. idata.flags &= ~uint32_t(InstanceData::FLAG_IGNORE_ALL_CULLING);
  859. }
  860. }
  861. }
  862. Vector<ObjectID> RendererSceneCull::instances_cull_aabb(const AABB &p_aabb, RID p_scenario) const {
  863. Vector<ObjectID> instances;
  864. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  865. ERR_FAIL_COND_V(!scenario, instances);
  866. const_cast<RendererSceneCull *>(this)->update_dirty_instances(); // check dirty instances before culling
  867. struct CullAABB {
  868. Vector<ObjectID> instances;
  869. _FORCE_INLINE_ bool operator()(void *p_data) {
  870. Instance *p_instance = (Instance *)p_data;
  871. if (!p_instance->object_id.is_null()) {
  872. instances.push_back(p_instance->object_id);
  873. }
  874. return false;
  875. }
  876. };
  877. CullAABB cull_aabb;
  878. scenario->indexers[Scenario::INDEXER_GEOMETRY].aabb_query(p_aabb, cull_aabb);
  879. scenario->indexers[Scenario::INDEXER_VOLUMES].aabb_query(p_aabb, cull_aabb);
  880. return cull_aabb.instances;
  881. }
  882. Vector<ObjectID> RendererSceneCull::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
  883. Vector<ObjectID> instances;
  884. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  885. ERR_FAIL_COND_V(!scenario, instances);
  886. const_cast<RendererSceneCull *>(this)->update_dirty_instances(); // check dirty instances before culling
  887. struct CullRay {
  888. Vector<ObjectID> instances;
  889. _FORCE_INLINE_ bool operator()(void *p_data) {
  890. Instance *p_instance = (Instance *)p_data;
  891. if (!p_instance->object_id.is_null()) {
  892. instances.push_back(p_instance->object_id);
  893. }
  894. return false;
  895. }
  896. };
  897. CullRay cull_ray;
  898. scenario->indexers[Scenario::INDEXER_GEOMETRY].ray_query(p_from, p_to, cull_ray);
  899. scenario->indexers[Scenario::INDEXER_VOLUMES].ray_query(p_from, p_to, cull_ray);
  900. return cull_ray.instances;
  901. }
  902. Vector<ObjectID> RendererSceneCull::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {
  903. Vector<ObjectID> instances;
  904. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  905. ERR_FAIL_COND_V(!scenario, instances);
  906. const_cast<RendererSceneCull *>(this)->update_dirty_instances(); // check dirty instances before culling
  907. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&p_convex[0], p_convex.size());
  908. struct CullConvex {
  909. Vector<ObjectID> instances;
  910. _FORCE_INLINE_ bool operator()(void *p_data) {
  911. Instance *p_instance = (Instance *)p_data;
  912. if (!p_instance->object_id.is_null()) {
  913. instances.push_back(p_instance->object_id);
  914. }
  915. return false;
  916. }
  917. };
  918. CullConvex cull_convex;
  919. scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(p_convex.ptr(), p_convex.size(), points.ptr(), points.size(), cull_convex);
  920. scenario->indexers[Scenario::INDEXER_VOLUMES].convex_query(p_convex.ptr(), p_convex.size(), points.ptr(), points.size(), cull_convex);
  921. return cull_convex.instances;
  922. }
  923. void RendererSceneCull::instance_geometry_set_flag(RID p_instance, RS::InstanceFlags p_flags, bool p_enabled) {
  924. Instance *instance = instance_owner.get_or_null(p_instance);
  925. ERR_FAIL_COND(!instance);
  926. //ERR_FAIL_COND(((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK));
  927. switch (p_flags) {
  928. case RS::INSTANCE_FLAG_USE_BAKED_LIGHT: {
  929. instance->baked_light = p_enabled;
  930. if (instance->scenario && instance->array_index >= 0) {
  931. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  932. if (instance->baked_light) {
  933. idata.flags |= InstanceData::FLAG_USES_BAKED_LIGHT;
  934. } else {
  935. idata.flags &= ~uint32_t(InstanceData::FLAG_USES_BAKED_LIGHT);
  936. }
  937. }
  938. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  939. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  940. ERR_FAIL_NULL(geom->geometry_instance);
  941. geom->geometry_instance->set_use_baked_light(p_enabled);
  942. }
  943. } break;
  944. case RS::INSTANCE_FLAG_USE_DYNAMIC_GI: {
  945. if (p_enabled == instance->dynamic_gi) {
  946. //bye, redundant
  947. return;
  948. }
  949. if (instance->indexer_id.is_valid()) {
  950. _unpair_instance(instance);
  951. _instance_queue_update(instance, true, true);
  952. }
  953. //once out of octree, can be changed
  954. instance->dynamic_gi = p_enabled;
  955. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  956. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  957. ERR_FAIL_NULL(geom->geometry_instance);
  958. geom->geometry_instance->set_use_dynamic_gi(p_enabled);
  959. }
  960. } break;
  961. case RS::INSTANCE_FLAG_DRAW_NEXT_FRAME_IF_VISIBLE: {
  962. instance->redraw_if_visible = p_enabled;
  963. if (instance->scenario && instance->array_index >= 0) {
  964. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  965. if (instance->redraw_if_visible) {
  966. idata.flags |= InstanceData::FLAG_REDRAW_IF_VISIBLE;
  967. } else {
  968. idata.flags &= ~uint32_t(InstanceData::FLAG_REDRAW_IF_VISIBLE);
  969. }
  970. }
  971. } break;
  972. case RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING: {
  973. instance->ignore_occlusion_culling = p_enabled;
  974. if (instance->scenario && instance->array_index >= 0) {
  975. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  976. if (instance->ignore_occlusion_culling) {
  977. idata.flags |= InstanceData::FLAG_IGNORE_OCCLUSION_CULLING;
  978. } else {
  979. idata.flags &= ~uint32_t(InstanceData::FLAG_IGNORE_OCCLUSION_CULLING);
  980. }
  981. }
  982. } break;
  983. default: {
  984. }
  985. }
  986. }
  987. void RendererSceneCull::instance_geometry_set_cast_shadows_setting(RID p_instance, RS::ShadowCastingSetting p_shadow_casting_setting) {
  988. Instance *instance = instance_owner.get_or_null(p_instance);
  989. ERR_FAIL_COND(!instance);
  990. instance->cast_shadows = p_shadow_casting_setting;
  991. if (instance->scenario && instance->array_index >= 0) {
  992. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  993. if (instance->cast_shadows != RS::SHADOW_CASTING_SETTING_OFF) {
  994. idata.flags |= InstanceData::FLAG_CAST_SHADOWS;
  995. } else {
  996. idata.flags &= ~uint32_t(InstanceData::FLAG_CAST_SHADOWS);
  997. }
  998. if (instance->cast_shadows == RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  999. idata.flags |= InstanceData::FLAG_CAST_SHADOWS_ONLY;
  1000. } else {
  1001. idata.flags &= ~uint32_t(InstanceData::FLAG_CAST_SHADOWS_ONLY);
  1002. }
  1003. }
  1004. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1005. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1006. ERR_FAIL_NULL(geom->geometry_instance);
  1007. geom->geometry_instance->set_cast_double_sided_shadows(instance->cast_shadows == RS::SHADOW_CASTING_SETTING_DOUBLE_SIDED);
  1008. }
  1009. _instance_queue_update(instance, false, true);
  1010. }
  1011. void RendererSceneCull::instance_geometry_set_material_override(RID p_instance, RID p_material) {
  1012. Instance *instance = instance_owner.get_or_null(p_instance);
  1013. ERR_FAIL_COND(!instance);
  1014. instance->material_override = p_material;
  1015. _instance_queue_update(instance, false, true);
  1016. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1017. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1018. ERR_FAIL_NULL(geom->geometry_instance);
  1019. geom->geometry_instance->set_material_override(p_material);
  1020. }
  1021. }
  1022. void RendererSceneCull::instance_geometry_set_material_overlay(RID p_instance, RID p_material) {
  1023. Instance *instance = instance_owner.get_or_null(p_instance);
  1024. ERR_FAIL_COND(!instance);
  1025. instance->material_overlay = p_material;
  1026. _instance_queue_update(instance, false, true);
  1027. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1028. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1029. ERR_FAIL_NULL(geom->geometry_instance);
  1030. geom->geometry_instance->set_material_overlay(p_material);
  1031. }
  1032. }
  1033. void RendererSceneCull::instance_geometry_set_visibility_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin, RS::VisibilityRangeFadeMode p_fade_mode) {
  1034. Instance *instance = instance_owner.get_or_null(p_instance);
  1035. ERR_FAIL_COND(!instance);
  1036. instance->visibility_range_begin = p_min;
  1037. instance->visibility_range_end = p_max;
  1038. instance->visibility_range_begin_margin = p_min_margin;
  1039. instance->visibility_range_end_margin = p_max_margin;
  1040. instance->visibility_range_fade_mode = p_fade_mode;
  1041. _update_instance_visibility_dependencies(instance);
  1042. if (instance->scenario && instance->visibility_index != -1) {
  1043. InstanceVisibilityData &vd = instance->scenario->instance_visibility[instance->visibility_index];
  1044. vd.range_begin = instance->visibility_range_begin;
  1045. vd.range_end = instance->visibility_range_end;
  1046. vd.range_begin_margin = instance->visibility_range_begin_margin;
  1047. vd.range_end_margin = instance->visibility_range_end_margin;
  1048. vd.fade_mode = p_fade_mode;
  1049. }
  1050. }
  1051. void RendererSceneCull::instance_set_visibility_parent(RID p_instance, RID p_parent_instance) {
  1052. Instance *instance = instance_owner.get_or_null(p_instance);
  1053. ERR_FAIL_COND(!instance);
  1054. Instance *old_parent = instance->visibility_parent;
  1055. if (old_parent) {
  1056. old_parent->visibility_dependencies.erase(instance);
  1057. instance->visibility_parent = nullptr;
  1058. _update_instance_visibility_depth(old_parent);
  1059. }
  1060. Instance *parent = instance_owner.get_or_null(p_parent_instance);
  1061. ERR_FAIL_COND(p_parent_instance.is_valid() && !parent);
  1062. if (parent) {
  1063. parent->visibility_dependencies.insert(instance);
  1064. instance->visibility_parent = parent;
  1065. bool cycle_detected = _update_instance_visibility_depth(parent);
  1066. if (cycle_detected) {
  1067. ERR_PRINT("Cycle detected in the visibility dependencies tree. The latest change to visibility_parent will have no effect.");
  1068. parent->visibility_dependencies.erase(instance);
  1069. instance->visibility_parent = nullptr;
  1070. }
  1071. }
  1072. _update_instance_visibility_dependencies(instance);
  1073. }
  1074. bool RendererSceneCull::_update_instance_visibility_depth(Instance *p_instance) {
  1075. bool cycle_detected = false;
  1076. HashSet<Instance *> traversed_nodes;
  1077. {
  1078. Instance *instance = p_instance;
  1079. while (instance) {
  1080. if (!instance->visibility_dependencies.is_empty()) {
  1081. uint32_t depth = 0;
  1082. for (const Instance *E : instance->visibility_dependencies) {
  1083. depth = MAX(depth, E->visibility_dependencies_depth);
  1084. }
  1085. instance->visibility_dependencies_depth = depth + 1;
  1086. } else {
  1087. instance->visibility_dependencies_depth = 0;
  1088. }
  1089. if (instance->scenario && instance->visibility_index != -1) {
  1090. instance->scenario->instance_visibility.move(instance->visibility_index, instance->visibility_dependencies_depth);
  1091. }
  1092. traversed_nodes.insert(instance);
  1093. instance = instance->visibility_parent;
  1094. if (traversed_nodes.has(instance)) {
  1095. cycle_detected = true;
  1096. break;
  1097. }
  1098. }
  1099. }
  1100. return cycle_detected;
  1101. }
  1102. void RendererSceneCull::_update_instance_visibility_dependencies(Instance *p_instance) {
  1103. bool is_geometry_instance = ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) && p_instance->base_data;
  1104. bool has_visibility_range = p_instance->visibility_range_begin > 0.0 || p_instance->visibility_range_end > 0.0;
  1105. bool needs_visibility_cull = has_visibility_range && is_geometry_instance && p_instance->array_index != -1;
  1106. if (!needs_visibility_cull && p_instance->visibility_index != -1) {
  1107. p_instance->scenario->instance_visibility.remove_at(p_instance->visibility_index);
  1108. p_instance->visibility_index = -1;
  1109. } else if (needs_visibility_cull && p_instance->visibility_index == -1) {
  1110. InstanceVisibilityData vd;
  1111. vd.instance = p_instance;
  1112. vd.range_begin = p_instance->visibility_range_begin;
  1113. vd.range_end = p_instance->visibility_range_end;
  1114. vd.range_begin_margin = p_instance->visibility_range_begin_margin;
  1115. vd.range_end_margin = p_instance->visibility_range_end_margin;
  1116. vd.position = p_instance->transformed_aabb.get_center();
  1117. vd.array_index = p_instance->array_index;
  1118. vd.fade_mode = p_instance->visibility_range_fade_mode;
  1119. p_instance->scenario->instance_visibility.insert(vd, p_instance->visibility_dependencies_depth);
  1120. }
  1121. if (p_instance->scenario && p_instance->array_index != -1) {
  1122. InstanceData &idata = p_instance->scenario->instance_data[p_instance->array_index];
  1123. idata.visibility_index = p_instance->visibility_index;
  1124. if (is_geometry_instance) {
  1125. if (has_visibility_range && p_instance->visibility_range_fade_mode == RS::VISIBILITY_RANGE_FADE_SELF) {
  1126. bool begin_enabled = p_instance->visibility_range_begin > 0.0f;
  1127. float begin_min = p_instance->visibility_range_begin - p_instance->visibility_range_begin_margin;
  1128. float begin_max = p_instance->visibility_range_begin + p_instance->visibility_range_begin_margin;
  1129. bool end_enabled = p_instance->visibility_range_end > 0.0f;
  1130. float end_min = p_instance->visibility_range_end - p_instance->visibility_range_end_margin;
  1131. float end_max = p_instance->visibility_range_end + p_instance->visibility_range_end_margin;
  1132. idata.instance_geometry->set_fade_range(begin_enabled, begin_min, begin_max, end_enabled, end_min, end_max);
  1133. } else {
  1134. idata.instance_geometry->set_fade_range(false, 0.0f, 0.0f, false, 0.0f, 0.0f);
  1135. }
  1136. }
  1137. if ((has_visibility_range || p_instance->visibility_parent) && (p_instance->visibility_index == -1 || p_instance->visibility_dependencies_depth == 0)) {
  1138. idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK;
  1139. } else {
  1140. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK;
  1141. }
  1142. if (p_instance->visibility_parent) {
  1143. idata.parent_array_index = p_instance->visibility_parent->array_index;
  1144. } else {
  1145. idata.parent_array_index = -1;
  1146. if (is_geometry_instance) {
  1147. idata.instance_geometry->set_parent_fade_alpha(1.0f);
  1148. }
  1149. }
  1150. }
  1151. }
  1152. void RendererSceneCull::instance_geometry_set_lightmap(RID p_instance, RID p_lightmap, const Rect2 &p_lightmap_uv_scale, int p_slice_index) {
  1153. Instance *instance = instance_owner.get_or_null(p_instance);
  1154. ERR_FAIL_COND(!instance);
  1155. if (instance->lightmap) {
  1156. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(((Instance *)instance->lightmap)->base_data);
  1157. lightmap_data->users.erase(instance);
  1158. instance->lightmap = nullptr;
  1159. }
  1160. Instance *lightmap_instance = instance_owner.get_or_null(p_lightmap);
  1161. instance->lightmap = lightmap_instance;
  1162. instance->lightmap_uv_scale = p_lightmap_uv_scale;
  1163. instance->lightmap_slice_index = p_slice_index;
  1164. RID lightmap_instance_rid;
  1165. if (lightmap_instance) {
  1166. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(lightmap_instance->base_data);
  1167. lightmap_data->users.insert(instance);
  1168. lightmap_instance_rid = lightmap_data->instance;
  1169. }
  1170. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1171. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1172. ERR_FAIL_NULL(geom->geometry_instance);
  1173. geom->geometry_instance->set_use_lightmap(lightmap_instance_rid, p_lightmap_uv_scale, p_slice_index);
  1174. }
  1175. }
  1176. void RendererSceneCull::instance_geometry_set_lod_bias(RID p_instance, float p_lod_bias) {
  1177. Instance *instance = instance_owner.get_or_null(p_instance);
  1178. ERR_FAIL_COND(!instance);
  1179. instance->lod_bias = p_lod_bias;
  1180. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1181. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1182. ERR_FAIL_NULL(geom->geometry_instance);
  1183. geom->geometry_instance->set_lod_bias(p_lod_bias);
  1184. }
  1185. }
  1186. void RendererSceneCull::instance_geometry_set_shader_uniform(RID p_instance, const StringName &p_parameter, const Variant &p_value) {
  1187. Instance *instance = instance_owner.get_or_null(p_instance);
  1188. ERR_FAIL_COND(!instance);
  1189. ERR_FAIL_COND(p_value.get_type() == Variant::OBJECT);
  1190. HashMap<StringName, Instance::InstanceShaderParameter>::Iterator E = instance->instance_shader_uniforms.find(p_parameter);
  1191. if (!E) {
  1192. Instance::InstanceShaderParameter isp;
  1193. isp.index = -1;
  1194. isp.info = PropertyInfo();
  1195. isp.value = p_value;
  1196. instance->instance_shader_uniforms[p_parameter] = isp;
  1197. } else {
  1198. E->value.value = p_value;
  1199. if (E->value.index >= 0 && instance->instance_allocated_shader_uniforms) {
  1200. //update directly
  1201. RSG::material_storage->global_shader_uniforms_instance_update(p_instance, E->value.index, p_value);
  1202. }
  1203. }
  1204. }
  1205. Variant RendererSceneCull::instance_geometry_get_shader_uniform(RID p_instance, const StringName &p_parameter) const {
  1206. const Instance *instance = const_cast<RendererSceneCull *>(this)->instance_owner.get_or_null(p_instance);
  1207. ERR_FAIL_COND_V(!instance, Variant());
  1208. if (instance->instance_shader_uniforms.has(p_parameter)) {
  1209. return instance->instance_shader_uniforms[p_parameter].value;
  1210. }
  1211. return Variant();
  1212. }
  1213. Variant RendererSceneCull::instance_geometry_get_shader_uniform_default_value(RID p_instance, const StringName &p_parameter) const {
  1214. const Instance *instance = const_cast<RendererSceneCull *>(this)->instance_owner.get_or_null(p_instance);
  1215. ERR_FAIL_COND_V(!instance, Variant());
  1216. if (instance->instance_shader_uniforms.has(p_parameter)) {
  1217. return instance->instance_shader_uniforms[p_parameter].default_value;
  1218. }
  1219. return Variant();
  1220. }
  1221. void RendererSceneCull::instance_geometry_get_shader_uniform_list(RID p_instance, List<PropertyInfo> *p_parameters) const {
  1222. const Instance *instance = const_cast<RendererSceneCull *>(this)->instance_owner.get_or_null(p_instance);
  1223. ERR_FAIL_COND(!instance);
  1224. const_cast<RendererSceneCull *>(this)->update_dirty_instances();
  1225. Vector<StringName> names;
  1226. for (const KeyValue<StringName, Instance::InstanceShaderParameter> &E : instance->instance_shader_uniforms) {
  1227. names.push_back(E.key);
  1228. }
  1229. names.sort_custom<StringName::AlphCompare>();
  1230. for (int i = 0; i < names.size(); i++) {
  1231. PropertyInfo pinfo = instance->instance_shader_uniforms[names[i]].info;
  1232. p_parameters->push_back(pinfo);
  1233. }
  1234. }
  1235. void RendererSceneCull::_update_instance(Instance *p_instance) {
  1236. p_instance->version++;
  1237. if (p_instance->base_type == RS::INSTANCE_LIGHT) {
  1238. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1239. scene_render->light_instance_set_transform(light->instance, p_instance->transform);
  1240. scene_render->light_instance_set_aabb(light->instance, p_instance->transform.xform(p_instance->aabb));
  1241. light->shadow_dirty = true;
  1242. RS::LightBakeMode bake_mode = RSG::light_storage->light_get_bake_mode(p_instance->base);
  1243. if (RSG::light_storage->light_get_type(p_instance->base) != RS::LIGHT_DIRECTIONAL && bake_mode != light->bake_mode) {
  1244. if (p_instance->visible && p_instance->scenario && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  1245. p_instance->scenario->dynamic_lights.erase(light->instance);
  1246. }
  1247. light->bake_mode = bake_mode;
  1248. if (p_instance->visible && p_instance->scenario && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  1249. p_instance->scenario->dynamic_lights.push_back(light->instance);
  1250. }
  1251. }
  1252. uint32_t max_sdfgi_cascade = RSG::light_storage->light_get_max_sdfgi_cascade(p_instance->base);
  1253. if (light->max_sdfgi_cascade != max_sdfgi_cascade) {
  1254. light->max_sdfgi_cascade = max_sdfgi_cascade; //should most likely make sdfgi dirty in scenario
  1255. }
  1256. } else if (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE) {
  1257. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  1258. scene_render->reflection_probe_instance_set_transform(reflection_probe->instance, p_instance->transform);
  1259. if (p_instance->scenario && p_instance->array_index >= 0) {
  1260. InstanceData &idata = p_instance->scenario->instance_data[p_instance->array_index];
  1261. idata.flags |= InstanceData::FLAG_REFLECTION_PROBE_DIRTY;
  1262. }
  1263. } else if (p_instance->base_type == RS::INSTANCE_DECAL) {
  1264. InstanceDecalData *decal = static_cast<InstanceDecalData *>(p_instance->base_data);
  1265. scene_render->decal_instance_set_transform(decal->instance, p_instance->transform);
  1266. } else if (p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
  1267. InstanceLightmapData *lightmap = static_cast<InstanceLightmapData *>(p_instance->base_data);
  1268. scene_render->lightmap_instance_set_transform(lightmap->instance, p_instance->transform);
  1269. } else if (p_instance->base_type == RS::INSTANCE_VOXEL_GI) {
  1270. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(p_instance->base_data);
  1271. scene_render->voxel_gi_instance_set_transform_to_data(voxel_gi->probe_instance, p_instance->transform);
  1272. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  1273. RSG::particles_storage->particles_set_emission_transform(p_instance->base, p_instance->transform);
  1274. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
  1275. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(p_instance->base_data);
  1276. //remove materials no longer used and un-own them
  1277. if (RSG::particles_storage->particles_collision_is_heightfield(p_instance->base)) {
  1278. heightfield_particle_colliders_update_list.insert(p_instance);
  1279. }
  1280. RSG::particles_storage->particles_collision_instance_set_transform(collision->instance, p_instance->transform);
  1281. } else if (p_instance->base_type == RS::INSTANCE_FOG_VOLUME) {
  1282. InstanceFogVolumeData *volume = static_cast<InstanceFogVolumeData *>(p_instance->base_data);
  1283. scene_render->fog_volume_instance_set_transform(volume->instance, p_instance->transform);
  1284. } else if (p_instance->base_type == RS::INSTANCE_OCCLUDER) {
  1285. if (p_instance->scenario) {
  1286. RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(p_instance->scenario->self, p_instance->self, p_instance->base, p_instance->transform, p_instance->visible);
  1287. }
  1288. }
  1289. if (p_instance->aabb.has_no_surface()) {
  1290. return;
  1291. }
  1292. if (p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
  1293. //if this moved, update the captured objects
  1294. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(p_instance->base_data);
  1295. //erase dependencies, since no longer a lightmap
  1296. for (Instance *E : lightmap_data->geometries) {
  1297. Instance *geom = E;
  1298. _instance_queue_update(geom, true, false);
  1299. }
  1300. }
  1301. AABB new_aabb;
  1302. new_aabb = p_instance->transform.xform(p_instance->aabb);
  1303. p_instance->transformed_aabb = new_aabb;
  1304. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1305. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1306. //make sure lights are updated if it casts shadow
  1307. if (geom->can_cast_shadows) {
  1308. for (const Instance *E : geom->lights) {
  1309. InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
  1310. light->shadow_dirty = true;
  1311. }
  1312. }
  1313. if (!p_instance->lightmap && geom->lightmap_captures.size()) {
  1314. //affected by lightmap captures, must update capture info!
  1315. _update_instance_lightmap_captures(p_instance);
  1316. } else {
  1317. if (!p_instance->lightmap_sh.is_empty()) {
  1318. p_instance->lightmap_sh.clear(); //don't need SH
  1319. p_instance->lightmap_target_sh.clear(); //don't need SH
  1320. ERR_FAIL_NULL(geom->geometry_instance);
  1321. geom->geometry_instance->set_lightmap_capture(nullptr);
  1322. }
  1323. }
  1324. ERR_FAIL_NULL(geom->geometry_instance);
  1325. geom->geometry_instance->set_transform(p_instance->transform, p_instance->aabb, p_instance->transformed_aabb);
  1326. }
  1327. // note: we had to remove is equal approx check here, it meant that det == 0.000004 won't work, which is the case for some of our scenes.
  1328. if (p_instance->scenario == nullptr || !p_instance->visible || p_instance->transform.basis.determinant() == 0) {
  1329. p_instance->prev_transformed_aabb = p_instance->transformed_aabb;
  1330. return;
  1331. }
  1332. //quantize to improve moving object performance
  1333. AABB bvh_aabb = p_instance->transformed_aabb;
  1334. if (p_instance->indexer_id.is_valid() && bvh_aabb != p_instance->prev_transformed_aabb) {
  1335. //assume motion, see if bounds need to be quantized
  1336. AABB motion_aabb = bvh_aabb.merge(p_instance->prev_transformed_aabb);
  1337. float motion_longest_axis = motion_aabb.get_longest_axis_size();
  1338. float longest_axis = p_instance->transformed_aabb.get_longest_axis_size();
  1339. if (motion_longest_axis < longest_axis * 2) {
  1340. //moved but not a lot, use motion aabb quantizing
  1341. float quantize_size = Math::pow(2.0, Math::ceil(Math::log(motion_longest_axis) / Math::log(2.0))) * 0.5; //one fifth
  1342. bvh_aabb.quantize(quantize_size);
  1343. }
  1344. }
  1345. if (!p_instance->indexer_id.is_valid()) {
  1346. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1347. p_instance->indexer_id = p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].insert(bvh_aabb, p_instance);
  1348. } else {
  1349. p_instance->indexer_id = p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].insert(bvh_aabb, p_instance);
  1350. }
  1351. p_instance->array_index = p_instance->scenario->instance_data.size();
  1352. InstanceData idata;
  1353. idata.instance = p_instance;
  1354. idata.layer_mask = p_instance->layer_mask;
  1355. idata.flags = p_instance->base_type; //changing it means de-indexing, so this never needs to be changed later
  1356. idata.base_rid = p_instance->base;
  1357. idata.parent_array_index = p_instance->visibility_parent ? p_instance->visibility_parent->array_index : -1;
  1358. idata.visibility_index = p_instance->visibility_index;
  1359. for (Instance *E : p_instance->visibility_dependencies) {
  1360. Instance *dep_instance = E;
  1361. if (dep_instance->array_index != -1) {
  1362. dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = p_instance->array_index;
  1363. }
  1364. }
  1365. switch (p_instance->base_type) {
  1366. case RS::INSTANCE_MESH:
  1367. case RS::INSTANCE_MULTIMESH:
  1368. case RS::INSTANCE_PARTICLES: {
  1369. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1370. idata.instance_geometry = geom->geometry_instance;
  1371. } break;
  1372. case RS::INSTANCE_LIGHT: {
  1373. InstanceLightData *light_data = static_cast<InstanceLightData *>(p_instance->base_data);
  1374. idata.instance_data_rid = light_data->instance.get_id();
  1375. light_data->uses_projector = RSG::light_storage->light_has_projector(p_instance->base);
  1376. light_data->uses_softshadow = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SIZE) > CMP_EPSILON;
  1377. } break;
  1378. case RS::INSTANCE_REFLECTION_PROBE: {
  1379. idata.instance_data_rid = static_cast<InstanceReflectionProbeData *>(p_instance->base_data)->instance.get_id();
  1380. } break;
  1381. case RS::INSTANCE_DECAL: {
  1382. idata.instance_data_rid = static_cast<InstanceDecalData *>(p_instance->base_data)->instance.get_id();
  1383. } break;
  1384. case RS::INSTANCE_LIGHTMAP: {
  1385. idata.instance_data_rid = static_cast<InstanceLightmapData *>(p_instance->base_data)->instance.get_id();
  1386. } break;
  1387. case RS::INSTANCE_VOXEL_GI: {
  1388. idata.instance_data_rid = static_cast<InstanceVoxelGIData *>(p_instance->base_data)->probe_instance.get_id();
  1389. } break;
  1390. case RS::INSTANCE_FOG_VOLUME: {
  1391. idata.instance_data_rid = static_cast<InstanceFogVolumeData *>(p_instance->base_data)->instance.get_id();
  1392. } break;
  1393. case RS::INSTANCE_VISIBLITY_NOTIFIER: {
  1394. idata.visibility_notifier = static_cast<InstanceVisibilityNotifierData *>(p_instance->base_data);
  1395. } break;
  1396. default: {
  1397. }
  1398. }
  1399. if (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE) {
  1400. //always dirty when added
  1401. idata.flags |= InstanceData::FLAG_REFLECTION_PROBE_DIRTY;
  1402. }
  1403. if (p_instance->cast_shadows != RS::SHADOW_CASTING_SETTING_OFF) {
  1404. idata.flags |= InstanceData::FLAG_CAST_SHADOWS;
  1405. }
  1406. if (p_instance->cast_shadows == RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  1407. idata.flags |= InstanceData::FLAG_CAST_SHADOWS_ONLY;
  1408. }
  1409. if (p_instance->redraw_if_visible) {
  1410. idata.flags |= InstanceData::FLAG_REDRAW_IF_VISIBLE;
  1411. }
  1412. // dirty flags should not be set here, since no pairing has happened
  1413. if (p_instance->baked_light) {
  1414. idata.flags |= InstanceData::FLAG_USES_BAKED_LIGHT;
  1415. }
  1416. if (p_instance->mesh_instance.is_valid()) {
  1417. idata.flags |= InstanceData::FLAG_USES_MESH_INSTANCE;
  1418. }
  1419. if (p_instance->ignore_occlusion_culling) {
  1420. idata.flags |= InstanceData::FLAG_IGNORE_OCCLUSION_CULLING;
  1421. }
  1422. if (p_instance->ignore_all_culling) {
  1423. idata.flags |= InstanceData::FLAG_IGNORE_ALL_CULLING;
  1424. }
  1425. p_instance->scenario->instance_data.push_back(idata);
  1426. p_instance->scenario->instance_aabbs.push_back(InstanceBounds(p_instance->transformed_aabb));
  1427. _update_instance_visibility_dependencies(p_instance);
  1428. } else {
  1429. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1430. p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].update(p_instance->indexer_id, bvh_aabb);
  1431. } else {
  1432. p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].update(p_instance->indexer_id, bvh_aabb);
  1433. }
  1434. p_instance->scenario->instance_aabbs[p_instance->array_index] = InstanceBounds(p_instance->transformed_aabb);
  1435. }
  1436. if (p_instance->visibility_index != -1) {
  1437. p_instance->scenario->instance_visibility[p_instance->visibility_index].position = p_instance->transformed_aabb.get_center();
  1438. }
  1439. //move instance and repair
  1440. pair_pass++;
  1441. PairInstances pair;
  1442. pair.instance = p_instance;
  1443. pair.pair_allocator = &pair_allocator;
  1444. pair.pair_pass = pair_pass;
  1445. pair.pair_mask = 0;
  1446. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1447. pair.pair_mask |= 1 << RS::INSTANCE_LIGHT;
  1448. pair.pair_mask |= 1 << RS::INSTANCE_VOXEL_GI;
  1449. pair.pair_mask |= 1 << RS::INSTANCE_LIGHTMAP;
  1450. if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  1451. pair.pair_mask |= 1 << RS::INSTANCE_PARTICLES_COLLISION;
  1452. }
  1453. pair.pair_mask |= geometry_instance_pair_mask;
  1454. pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
  1455. } else if (p_instance->base_type == RS::INSTANCE_LIGHT) {
  1456. pair.pair_mask |= RS::INSTANCE_GEOMETRY_MASK;
  1457. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1458. if (RSG::light_storage->light_get_bake_mode(p_instance->base) == RS::LIGHT_BAKE_DYNAMIC) {
  1459. pair.pair_mask |= (1 << RS::INSTANCE_VOXEL_GI);
  1460. pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
  1461. }
  1462. } else if (geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE)) {
  1463. pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK;
  1464. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1465. } else if (geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && (p_instance->base_type == RS::INSTANCE_DECAL)) {
  1466. pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK;
  1467. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1468. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
  1469. pair.pair_mask = (1 << RS::INSTANCE_PARTICLES);
  1470. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1471. } else if (p_instance->base_type == RS::INSTANCE_VOXEL_GI) {
  1472. //lights and geometries
  1473. pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK | (1 << RS::INSTANCE_LIGHT);
  1474. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1475. pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
  1476. }
  1477. pair.pair();
  1478. p_instance->prev_transformed_aabb = p_instance->transformed_aabb;
  1479. }
  1480. void RendererSceneCull::_unpair_instance(Instance *p_instance) {
  1481. if (!p_instance->indexer_id.is_valid()) {
  1482. return; //nothing to do
  1483. }
  1484. while (p_instance->pairs.first()) {
  1485. InstancePair *pair = p_instance->pairs.first()->self();
  1486. Instance *other_instance = p_instance == pair->a ? pair->b : pair->a;
  1487. _instance_unpair(p_instance, other_instance);
  1488. pair_allocator.free(pair);
  1489. }
  1490. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1491. p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].remove(p_instance->indexer_id);
  1492. } else {
  1493. p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].remove(p_instance->indexer_id);
  1494. }
  1495. p_instance->indexer_id = DynamicBVH::ID();
  1496. //replace this by last
  1497. int32_t swap_with_index = p_instance->scenario->instance_data.size() - 1;
  1498. if (swap_with_index != p_instance->array_index) {
  1499. Instance *swapped_instance = p_instance->scenario->instance_data[swap_with_index].instance;
  1500. swapped_instance->array_index = p_instance->array_index; //swap
  1501. p_instance->scenario->instance_data[p_instance->array_index] = p_instance->scenario->instance_data[swap_with_index];
  1502. p_instance->scenario->instance_aabbs[p_instance->array_index] = p_instance->scenario->instance_aabbs[swap_with_index];
  1503. if (swapped_instance->visibility_index != -1) {
  1504. swapped_instance->scenario->instance_visibility[swapped_instance->visibility_index].array_index = swapped_instance->array_index;
  1505. }
  1506. for (Instance *E : swapped_instance->visibility_dependencies) {
  1507. Instance *dep_instance = E;
  1508. if (dep_instance != p_instance && dep_instance->array_index != -1) {
  1509. dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = swapped_instance->array_index;
  1510. }
  1511. }
  1512. }
  1513. // pop last
  1514. p_instance->scenario->instance_data.pop_back();
  1515. p_instance->scenario->instance_aabbs.pop_back();
  1516. //uninitialize
  1517. p_instance->array_index = -1;
  1518. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1519. // Clear these now because the InstanceData containing the dirty flags is gone
  1520. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1521. ERR_FAIL_NULL(geom->geometry_instance);
  1522. geom->geometry_instance->pair_light_instances(nullptr, 0);
  1523. geom->geometry_instance->pair_reflection_probe_instances(nullptr, 0);
  1524. geom->geometry_instance->pair_decal_instances(nullptr, 0);
  1525. geom->geometry_instance->pair_voxel_gi_instances(nullptr, 0);
  1526. }
  1527. for (Instance *E : p_instance->visibility_dependencies) {
  1528. Instance *dep_instance = E;
  1529. if (dep_instance->array_index != -1) {
  1530. dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = -1;
  1531. if ((1 << dep_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1532. dep_instance->scenario->instance_data[dep_instance->array_index].instance_geometry->set_parent_fade_alpha(1.0f);
  1533. }
  1534. }
  1535. }
  1536. _update_instance_visibility_dependencies(p_instance);
  1537. }
  1538. void RendererSceneCull::_update_instance_aabb(Instance *p_instance) {
  1539. AABB new_aabb;
  1540. ERR_FAIL_COND(p_instance->base_type != RS::INSTANCE_NONE && !p_instance->base.is_valid());
  1541. switch (p_instance->base_type) {
  1542. case RenderingServer::INSTANCE_NONE: {
  1543. // do nothing
  1544. } break;
  1545. case RenderingServer::INSTANCE_MESH: {
  1546. if (p_instance->custom_aabb) {
  1547. new_aabb = *p_instance->custom_aabb;
  1548. } else {
  1549. new_aabb = RSG::mesh_storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);
  1550. }
  1551. } break;
  1552. case RenderingServer::INSTANCE_MULTIMESH: {
  1553. if (p_instance->custom_aabb) {
  1554. new_aabb = *p_instance->custom_aabb;
  1555. } else {
  1556. new_aabb = RSG::mesh_storage->multimesh_get_aabb(p_instance->base);
  1557. }
  1558. } break;
  1559. case RenderingServer::INSTANCE_PARTICLES: {
  1560. if (p_instance->custom_aabb) {
  1561. new_aabb = *p_instance->custom_aabb;
  1562. } else {
  1563. new_aabb = RSG::particles_storage->particles_get_aabb(p_instance->base);
  1564. }
  1565. } break;
  1566. case RenderingServer::INSTANCE_PARTICLES_COLLISION: {
  1567. new_aabb = RSG::particles_storage->particles_collision_get_aabb(p_instance->base);
  1568. } break;
  1569. case RenderingServer::INSTANCE_FOG_VOLUME: {
  1570. new_aabb = RSG::fog->fog_volume_get_aabb(p_instance->base);
  1571. } break;
  1572. case RenderingServer::INSTANCE_VISIBLITY_NOTIFIER: {
  1573. new_aabb = RSG::utilities->visibility_notifier_get_aabb(p_instance->base);
  1574. } break;
  1575. case RenderingServer::INSTANCE_LIGHT: {
  1576. new_aabb = RSG::light_storage->light_get_aabb(p_instance->base);
  1577. } break;
  1578. case RenderingServer::INSTANCE_REFLECTION_PROBE: {
  1579. new_aabb = RSG::light_storage->reflection_probe_get_aabb(p_instance->base);
  1580. } break;
  1581. case RenderingServer::INSTANCE_DECAL: {
  1582. new_aabb = RSG::texture_storage->decal_get_aabb(p_instance->base);
  1583. } break;
  1584. case RenderingServer::INSTANCE_VOXEL_GI: {
  1585. new_aabb = RSG::gi->voxel_gi_get_bounds(p_instance->base);
  1586. } break;
  1587. case RenderingServer::INSTANCE_LIGHTMAP: {
  1588. new_aabb = RSG::light_storage->lightmap_get_aabb(p_instance->base);
  1589. } break;
  1590. default: {
  1591. }
  1592. }
  1593. // <Zylann> This is why I didn't re-use Instance::aabb to implement custom AABBs
  1594. if (p_instance->extra_margin) {
  1595. new_aabb.grow_by(p_instance->extra_margin);
  1596. }
  1597. p_instance->aabb = new_aabb;
  1598. }
  1599. void RendererSceneCull::_update_instance_lightmap_captures(Instance *p_instance) {
  1600. bool first_set = p_instance->lightmap_sh.size() == 0;
  1601. p_instance->lightmap_sh.resize(9); //using SH
  1602. p_instance->lightmap_target_sh.resize(9); //using SH
  1603. Color *instance_sh = p_instance->lightmap_target_sh.ptrw();
  1604. bool inside = false;
  1605. Color accum_sh[9];
  1606. float accum_blend = 0.0;
  1607. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1608. for (Instance *E : geom->lightmap_captures) {
  1609. Instance *lightmap = E;
  1610. bool interior = RSG::light_storage->lightmap_is_interior(lightmap->base);
  1611. if (inside && !interior) {
  1612. continue; //we are inside, ignore exteriors
  1613. }
  1614. Transform3D to_bounds = lightmap->transform.affine_inverse();
  1615. Vector3 center = p_instance->transform.xform(p_instance->aabb.get_center()); //use aabb center
  1616. Vector3 lm_pos = to_bounds.xform(center);
  1617. AABB bounds = RSG::light_storage->lightmap_get_aabb(lightmap->base);
  1618. if (!bounds.has_point(lm_pos)) {
  1619. continue; //not in this lightmap
  1620. }
  1621. Color sh[9];
  1622. RSG::light_storage->lightmap_tap_sh_light(lightmap->base, lm_pos, sh);
  1623. //rotate it
  1624. Basis rot = lightmap->transform.basis.orthonormalized();
  1625. for (int i = 0; i < 3; i++) {
  1626. real_t csh[9];
  1627. for (int j = 0; j < 9; j++) {
  1628. csh[j] = sh[j][i];
  1629. }
  1630. rot.rotate_sh(csh);
  1631. for (int j = 0; j < 9; j++) {
  1632. sh[j][i] = csh[j];
  1633. }
  1634. }
  1635. Vector3 inner_pos = ((lm_pos - bounds.position) / bounds.size) * 2.0 - Vector3(1.0, 1.0, 1.0);
  1636. real_t blend = MAX(inner_pos.x, MAX(inner_pos.y, inner_pos.z));
  1637. //make blend more rounded
  1638. blend = Math::lerp(inner_pos.length(), blend, blend);
  1639. blend *= blend;
  1640. blend = MAX(0.0, 1.0 - blend);
  1641. if (interior && !inside) {
  1642. //do not blend, just replace
  1643. for (int j = 0; j < 9; j++) {
  1644. accum_sh[j] = sh[j] * blend;
  1645. }
  1646. accum_blend = blend;
  1647. inside = true;
  1648. } else {
  1649. for (int j = 0; j < 9; j++) {
  1650. accum_sh[j] += sh[j] * blend;
  1651. }
  1652. accum_blend += blend;
  1653. }
  1654. }
  1655. if (accum_blend > 0.0) {
  1656. for (int j = 0; j < 9; j++) {
  1657. instance_sh[j] = accum_sh[j] / accum_blend;
  1658. if (first_set) {
  1659. p_instance->lightmap_sh.write[j] = instance_sh[j];
  1660. }
  1661. }
  1662. }
  1663. ERR_FAIL_NULL(geom->geometry_instance);
  1664. geom->geometry_instance->set_lightmap_capture(p_instance->lightmap_sh.ptr());
  1665. }
  1666. void RendererSceneCull::_light_instance_setup_directional_shadow(int p_shadow_index, Instance *p_instance, const Transform3D p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect) {
  1667. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1668. Transform3D light_transform = p_instance->transform;
  1669. light_transform.orthonormalize(); //scale does not count on lights
  1670. real_t max_distance = p_cam_projection.get_z_far();
  1671. real_t shadow_max = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
  1672. if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera
  1673. max_distance = MIN(shadow_max, max_distance);
  1674. }
  1675. max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
  1676. real_t min_distance = MIN(p_cam_projection.get_z_near(), max_distance);
  1677. real_t pancake_size = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE);
  1678. real_t range = max_distance - min_distance;
  1679. int splits = 0;
  1680. switch (RSG::light_storage->light_directional_get_shadow_mode(p_instance->base)) {
  1681. case RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
  1682. splits = 1;
  1683. break;
  1684. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
  1685. splits = 2;
  1686. break;
  1687. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
  1688. splits = 4;
  1689. break;
  1690. }
  1691. real_t distances[5];
  1692. distances[0] = min_distance;
  1693. for (int i = 0; i < splits; i++) {
  1694. distances[i + 1] = min_distance + RSG::light_storage->light_get_param(p_instance->base, RS::LightParam(RS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
  1695. };
  1696. distances[splits] = max_distance;
  1697. real_t texture_size = scene_render->get_directional_light_shadow_size(light->instance);
  1698. bool overlap = RSG::light_storage->light_directional_get_blend_splits(p_instance->base);
  1699. cull.shadow_count = p_shadow_index + 1;
  1700. cull.shadows[p_shadow_index].cascade_count = splits;
  1701. cull.shadows[p_shadow_index].light_instance = light->instance;
  1702. for (int i = 0; i < splits; i++) {
  1703. RENDER_TIMESTAMP("Cull DirectionalLight3D, Split " + itos(i));
  1704. // setup a camera matrix for that range!
  1705. Projection camera_matrix;
  1706. real_t aspect = p_cam_projection.get_aspect();
  1707. if (p_cam_orthogonal) {
  1708. Vector2 vp_he = p_cam_projection.get_viewport_half_extents();
  1709. camera_matrix.set_orthogonal(vp_he.y * 2.0, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  1710. } else {
  1711. real_t fov = p_cam_projection.get_fov(); //this is actually yfov, because set aspect tries to keep it
  1712. camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
  1713. }
  1714. //obtain the frustum endpoints
  1715. Vector3 endpoints[8]; // frustum plane endpoints
  1716. bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
  1717. ERR_CONTINUE(!res);
  1718. // obtain the light frustum ranges (given endpoints)
  1719. Transform3D transform = light_transform; //discard scale and stabilize light
  1720. Vector3 x_vec = transform.basis.get_column(Vector3::AXIS_X).normalized();
  1721. Vector3 y_vec = transform.basis.get_column(Vector3::AXIS_Y).normalized();
  1722. Vector3 z_vec = transform.basis.get_column(Vector3::AXIS_Z).normalized();
  1723. //z_vec points against the camera, like in default opengl
  1724. real_t x_min = 0.f, x_max = 0.f;
  1725. real_t y_min = 0.f, y_max = 0.f;
  1726. real_t z_min = 0.f, z_max = 0.f;
  1727. // FIXME: z_max_cam is defined, computed, but not used below when setting up
  1728. // ortho_camera. Commented out for now to fix warnings but should be investigated.
  1729. real_t x_min_cam = 0.f, x_max_cam = 0.f;
  1730. real_t y_min_cam = 0.f, y_max_cam = 0.f;
  1731. real_t z_min_cam = 0.f;
  1732. //real_t z_max_cam = 0.f;
  1733. //real_t bias_scale = 1.0;
  1734. //real_t aspect_bias_scale = 1.0;
  1735. //used for culling
  1736. for (int j = 0; j < 8; j++) {
  1737. real_t d_x = x_vec.dot(endpoints[j]);
  1738. real_t d_y = y_vec.dot(endpoints[j]);
  1739. real_t d_z = z_vec.dot(endpoints[j]);
  1740. if (j == 0 || d_x < x_min) {
  1741. x_min = d_x;
  1742. }
  1743. if (j == 0 || d_x > x_max) {
  1744. x_max = d_x;
  1745. }
  1746. if (j == 0 || d_y < y_min) {
  1747. y_min = d_y;
  1748. }
  1749. if (j == 0 || d_y > y_max) {
  1750. y_max = d_y;
  1751. }
  1752. if (j == 0 || d_z < z_min) {
  1753. z_min = d_z;
  1754. }
  1755. if (j == 0 || d_z > z_max) {
  1756. z_max = d_z;
  1757. }
  1758. }
  1759. real_t radius = 0;
  1760. real_t soft_shadow_expand = 0;
  1761. Vector3 center;
  1762. {
  1763. //camera viewport stuff
  1764. for (int j = 0; j < 8; j++) {
  1765. center += endpoints[j];
  1766. }
  1767. center /= 8.0;
  1768. //center=x_vec*(x_max-x_min)*0.5 + y_vec*(y_max-y_min)*0.5 + z_vec*(z_max-z_min)*0.5;
  1769. for (int j = 0; j < 8; j++) {
  1770. real_t d = center.distance_to(endpoints[j]);
  1771. if (d > radius) {
  1772. radius = d;
  1773. }
  1774. }
  1775. radius *= texture_size / (texture_size - 2.0); //add a texel by each side
  1776. z_min_cam = z_vec.dot(center) - radius;
  1777. {
  1778. float soft_shadow_angle = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SIZE);
  1779. if (soft_shadow_angle > 0.0) {
  1780. float z_range = (z_vec.dot(center) + radius + pancake_size) - z_min_cam;
  1781. soft_shadow_expand = Math::tan(Math::deg_to_rad(soft_shadow_angle)) * z_range;
  1782. x_max += soft_shadow_expand;
  1783. y_max += soft_shadow_expand;
  1784. x_min -= soft_shadow_expand;
  1785. y_min -= soft_shadow_expand;
  1786. }
  1787. }
  1788. // This trick here is what stabilizes the shadow (make potential jaggies to not move)
  1789. // at the cost of some wasted resolution. Still, the quality increase is very well worth it.
  1790. const real_t unit = (radius + soft_shadow_expand) * 2.0 / texture_size;
  1791. x_max_cam = Math::snapped(x_vec.dot(center) + radius + soft_shadow_expand, unit);
  1792. x_min_cam = Math::snapped(x_vec.dot(center) - radius - soft_shadow_expand, unit);
  1793. y_max_cam = Math::snapped(y_vec.dot(center) + radius + soft_shadow_expand, unit);
  1794. y_min_cam = Math::snapped(y_vec.dot(center) - radius - soft_shadow_expand, unit);
  1795. }
  1796. //now that we know all ranges, we can proceed to make the light frustum planes, for culling octree
  1797. Vector<Plane> light_frustum_planes;
  1798. light_frustum_planes.resize(6);
  1799. //right/left
  1800. light_frustum_planes.write[0] = Plane(x_vec, x_max);
  1801. light_frustum_planes.write[1] = Plane(-x_vec, -x_min);
  1802. //top/bottom
  1803. light_frustum_planes.write[2] = Plane(y_vec, y_max);
  1804. light_frustum_planes.write[3] = Plane(-y_vec, -y_min);
  1805. //near/far
  1806. light_frustum_planes.write[4] = Plane(z_vec, z_max + 1e6);
  1807. light_frustum_planes.write[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed
  1808. // a pre pass will need to be needed to determine the actual z-near to be used
  1809. z_max = z_vec.dot(center) + radius + pancake_size;
  1810. {
  1811. Projection ortho_camera;
  1812. real_t half_x = (x_max_cam - x_min_cam) * 0.5;
  1813. real_t half_y = (y_max_cam - y_min_cam) * 0.5;
  1814. ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));
  1815. Vector2 uv_scale(1.0 / (x_max_cam - x_min_cam), 1.0 / (y_max_cam - y_min_cam));
  1816. Transform3D ortho_transform;
  1817. ortho_transform.basis = transform.basis;
  1818. ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;
  1819. cull.shadows[p_shadow_index].cascades[i].frustum = Frustum(light_frustum_planes);
  1820. cull.shadows[p_shadow_index].cascades[i].projection = ortho_camera;
  1821. cull.shadows[p_shadow_index].cascades[i].transform = ortho_transform;
  1822. cull.shadows[p_shadow_index].cascades[i].zfar = z_max - z_min_cam;
  1823. cull.shadows[p_shadow_index].cascades[i].split = distances[i + 1];
  1824. cull.shadows[p_shadow_index].cascades[i].shadow_texel_size = radius * 2.0 / texture_size;
  1825. cull.shadows[p_shadow_index].cascades[i].bias_scale = (z_max - z_min_cam);
  1826. cull.shadows[p_shadow_index].cascades[i].range_begin = z_max;
  1827. cull.shadows[p_shadow_index].cascades[i].uv_scale = uv_scale;
  1828. }
  1829. }
  1830. }
  1831. bool RendererSceneCull::_light_instance_update_shadow(Instance *p_instance, const Transform3D p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect, RID p_shadow_atlas, Scenario *p_scenario, float p_screen_mesh_lod_threshold) {
  1832. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1833. Transform3D light_transform = p_instance->transform;
  1834. light_transform.orthonormalize(); //scale does not count on lights
  1835. bool animated_material_found = false;
  1836. switch (RSG::light_storage->light_get_type(p_instance->base)) {
  1837. case RS::LIGHT_DIRECTIONAL: {
  1838. } break;
  1839. case RS::LIGHT_OMNI: {
  1840. RS::LightOmniShadowMode shadow_mode = RSG::light_storage->light_omni_get_shadow_mode(p_instance->base);
  1841. if (shadow_mode == RS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID || !scene_render->light_instances_can_render_shadow_cube()) {
  1842. if (max_shadows_used + 2 > MAX_UPDATE_SHADOWS) {
  1843. return true;
  1844. }
  1845. for (int i = 0; i < 2; i++) {
  1846. //using this one ensures that raster deferred will have it
  1847. RENDER_TIMESTAMP("Cull OmniLight3D Shadow Paraboloid, Half " + itos(i));
  1848. real_t radius = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1849. real_t z = i == 0 ? -1 : 1;
  1850. Vector<Plane> planes;
  1851. planes.resize(6);
  1852. planes.write[0] = light_transform.xform(Plane(Vector3(0, 0, z), radius));
  1853. planes.write[1] = light_transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
  1854. planes.write[2] = light_transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
  1855. planes.write[3] = light_transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
  1856. planes.write[4] = light_transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));
  1857. planes.write[5] = light_transform.xform(Plane(Vector3(0, 0, -z), 0));
  1858. instance_shadow_cull_result.clear();
  1859. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
  1860. struct CullConvex {
  1861. PagedArray<Instance *> *result;
  1862. _FORCE_INLINE_ bool operator()(void *p_data) {
  1863. Instance *p_instance = (Instance *)p_data;
  1864. result->push_back(p_instance);
  1865. return false;
  1866. }
  1867. };
  1868. CullConvex cull_convex;
  1869. cull_convex.result = &instance_shadow_cull_result;
  1870. p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
  1871. RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
  1872. for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
  1873. Instance *instance = instance_shadow_cull_result[j];
  1874. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1875. continue;
  1876. } else {
  1877. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1878. animated_material_found = true;
  1879. }
  1880. if (instance->mesh_instance.is_valid()) {
  1881. RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance);
  1882. }
  1883. }
  1884. shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
  1885. }
  1886. RSG::mesh_storage->update_mesh_instances();
  1887. scene_render->light_instance_set_shadow_transform(light->instance, Projection(), light_transform, radius, 0, i, 0);
  1888. shadow_data.light = light->instance;
  1889. shadow_data.pass = i;
  1890. }
  1891. } else { //shadow cube
  1892. if (max_shadows_used + 6 > MAX_UPDATE_SHADOWS) {
  1893. return true;
  1894. }
  1895. real_t radius = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1896. Projection cm;
  1897. cm.set_perspective(90, 1, radius * 0.005f, radius);
  1898. for (int i = 0; i < 6; i++) {
  1899. RENDER_TIMESTAMP("Cull OmniLight3D Shadow Cube, Side " + itos(i));
  1900. //using this one ensures that raster deferred will have it
  1901. static const Vector3 view_normals[6] = {
  1902. Vector3(+1, 0, 0),
  1903. Vector3(-1, 0, 0),
  1904. Vector3(0, -1, 0),
  1905. Vector3(0, +1, 0),
  1906. Vector3(0, 0, +1),
  1907. Vector3(0, 0, -1)
  1908. };
  1909. static const Vector3 view_up[6] = {
  1910. Vector3(0, -1, 0),
  1911. Vector3(0, -1, 0),
  1912. Vector3(0, 0, -1),
  1913. Vector3(0, 0, +1),
  1914. Vector3(0, -1, 0),
  1915. Vector3(0, -1, 0)
  1916. };
  1917. Transform3D xform = light_transform * Transform3D().looking_at(view_normals[i], view_up[i]);
  1918. Vector<Plane> planes = cm.get_projection_planes(xform);
  1919. instance_shadow_cull_result.clear();
  1920. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
  1921. struct CullConvex {
  1922. PagedArray<Instance *> *result;
  1923. _FORCE_INLINE_ bool operator()(void *p_data) {
  1924. Instance *p_instance = (Instance *)p_data;
  1925. result->push_back(p_instance);
  1926. return false;
  1927. }
  1928. };
  1929. CullConvex cull_convex;
  1930. cull_convex.result = &instance_shadow_cull_result;
  1931. p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
  1932. RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
  1933. for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
  1934. Instance *instance = instance_shadow_cull_result[j];
  1935. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1936. continue;
  1937. } else {
  1938. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1939. animated_material_found = true;
  1940. }
  1941. if (instance->mesh_instance.is_valid()) {
  1942. RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance);
  1943. }
  1944. }
  1945. shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
  1946. }
  1947. RSG::mesh_storage->update_mesh_instances();
  1948. scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i, 0);
  1949. shadow_data.light = light->instance;
  1950. shadow_data.pass = i;
  1951. }
  1952. //restore the regular DP matrix
  1953. //scene_render->light_instance_set_shadow_transform(light->instance, Projection(), light_transform, radius, 0, 0, 0);
  1954. }
  1955. } break;
  1956. case RS::LIGHT_SPOT: {
  1957. RENDER_TIMESTAMP("Cull SpotLight3D Shadow");
  1958. if (max_shadows_used + 1 > MAX_UPDATE_SHADOWS) {
  1959. return true;
  1960. }
  1961. real_t radius = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1962. real_t angle = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  1963. Projection cm;
  1964. cm.set_perspective(angle * 2.0, 1.0, 0.005f * radius, radius);
  1965. Vector<Plane> planes = cm.get_projection_planes(light_transform);
  1966. instance_shadow_cull_result.clear();
  1967. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
  1968. struct CullConvex {
  1969. PagedArray<Instance *> *result;
  1970. _FORCE_INLINE_ bool operator()(void *p_data) {
  1971. Instance *p_instance = (Instance *)p_data;
  1972. result->push_back(p_instance);
  1973. return false;
  1974. }
  1975. };
  1976. CullConvex cull_convex;
  1977. cull_convex.result = &instance_shadow_cull_result;
  1978. p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
  1979. RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
  1980. for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
  1981. Instance *instance = instance_shadow_cull_result[j];
  1982. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1983. continue;
  1984. } else {
  1985. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1986. animated_material_found = true;
  1987. }
  1988. if (instance->mesh_instance.is_valid()) {
  1989. RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance);
  1990. }
  1991. }
  1992. shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
  1993. }
  1994. RSG::mesh_storage->update_mesh_instances();
  1995. scene_render->light_instance_set_shadow_transform(light->instance, cm, light_transform, radius, 0, 0, 0);
  1996. shadow_data.light = light->instance;
  1997. shadow_data.pass = 0;
  1998. } break;
  1999. }
  2000. return animated_material_found;
  2001. }
  2002. void RendererSceneCull::render_camera(RID p_render_buffers, RID p_camera, RID p_scenario, RID p_viewport, Size2 p_viewport_size, bool p_use_taa, float p_screen_mesh_lod_threshold, RID p_shadow_atlas, Ref<XRInterface> &p_xr_interface, RenderInfo *r_render_info) {
  2003. #ifndef _3D_DISABLED
  2004. Camera *camera = camera_owner.get_or_null(p_camera);
  2005. ERR_FAIL_COND(!camera);
  2006. Vector2 jitter;
  2007. if (p_use_taa) {
  2008. jitter = taa_jitter_array[RSG::rasterizer->get_frame_number() % TAA_JITTER_COUNT] / p_viewport_size;
  2009. }
  2010. RendererSceneRender::CameraData camera_data;
  2011. // Setup Camera(s)
  2012. if (p_xr_interface.is_null()) {
  2013. // Normal camera
  2014. Transform3D transform = camera->transform;
  2015. Projection projection;
  2016. bool vaspect = camera->vaspect;
  2017. bool is_orthogonal = false;
  2018. switch (camera->type) {
  2019. case Camera::ORTHOGONAL: {
  2020. projection.set_orthogonal(
  2021. camera->size,
  2022. p_viewport_size.width / (float)p_viewport_size.height,
  2023. camera->znear,
  2024. camera->zfar,
  2025. camera->vaspect);
  2026. is_orthogonal = true;
  2027. } break;
  2028. case Camera::PERSPECTIVE: {
  2029. projection.set_perspective(
  2030. camera->fov,
  2031. p_viewport_size.width / (float)p_viewport_size.height,
  2032. camera->znear,
  2033. camera->zfar,
  2034. camera->vaspect);
  2035. } break;
  2036. case Camera::FRUSTUM: {
  2037. projection.set_frustum(
  2038. camera->size,
  2039. p_viewport_size.width / (float)p_viewport_size.height,
  2040. camera->offset,
  2041. camera->znear,
  2042. camera->zfar,
  2043. camera->vaspect);
  2044. } break;
  2045. }
  2046. camera_data.set_camera(transform, projection, is_orthogonal, vaspect, jitter);
  2047. } else {
  2048. // Setup our camera for our XR interface.
  2049. // We can support multiple views here each with their own camera
  2050. Transform3D transforms[RendererSceneRender::MAX_RENDER_VIEWS];
  2051. Projection projections[RendererSceneRender::MAX_RENDER_VIEWS];
  2052. uint32_t view_count = p_xr_interface->get_view_count();
  2053. ERR_FAIL_COND_MSG(view_count > RendererSceneRender::MAX_RENDER_VIEWS, "Requested view count is not supported");
  2054. float aspect = p_viewport_size.width / (float)p_viewport_size.height;
  2055. Transform3D world_origin = XRServer::get_singleton()->get_world_origin();
  2056. // We ignore our camera position, it will have been positioned with a slightly old tracking position.
  2057. // Instead we take our origin point and have our XR interface add fresh tracking data! Whoohoo!
  2058. for (uint32_t v = 0; v < view_count; v++) {
  2059. transforms[v] = p_xr_interface->get_transform_for_view(v, world_origin);
  2060. projections[v] = p_xr_interface->get_projection_for_view(v, aspect, camera->znear, camera->zfar);
  2061. }
  2062. if (view_count == 1) {
  2063. camera_data.set_camera(transforms[0], projections[0], false, camera->vaspect, jitter);
  2064. } else if (view_count == 2) {
  2065. camera_data.set_multiview_camera(view_count, transforms, projections, false, camera->vaspect);
  2066. } else {
  2067. // this won't be called (see fail check above) but keeping this comment to indicate we may support more then 2 views in the future...
  2068. }
  2069. }
  2070. RID environment = _render_get_environment(p_camera, p_scenario);
  2071. RENDER_TIMESTAMP("Update Occlusion Buffer")
  2072. // For now just cull on the first camera
  2073. RendererSceneOcclusionCull::get_singleton()->buffer_update(p_viewport, camera_data.main_transform, camera_data.main_projection, camera_data.is_orthogonal);
  2074. _render_scene(&camera_data, p_render_buffers, environment, camera->effects, camera->visible_layers, p_scenario, p_viewport, p_shadow_atlas, RID(), -1, p_screen_mesh_lod_threshold, true, r_render_info);
  2075. #endif
  2076. }
  2077. void RendererSceneCull::_visibility_cull_threaded(uint32_t p_thread, VisibilityCullData *cull_data) {
  2078. uint32_t total_threads = WorkerThreadPool::get_singleton()->get_thread_count();
  2079. uint32_t bin_from = p_thread * cull_data->cull_count / total_threads;
  2080. uint32_t bin_to = (p_thread + 1 == total_threads) ? cull_data->cull_count : ((p_thread + 1) * cull_data->cull_count / total_threads);
  2081. _visibility_cull(*cull_data, cull_data->cull_offset + bin_from, cull_data->cull_offset + bin_to);
  2082. }
  2083. void RendererSceneCull::_visibility_cull(const VisibilityCullData &cull_data, uint64_t p_from, uint64_t p_to) {
  2084. Scenario *scenario = cull_data.scenario;
  2085. for (unsigned int i = p_from; i < p_to; i++) {
  2086. InstanceVisibilityData &vd = scenario->instance_visibility[i];
  2087. InstanceData &idata = scenario->instance_data[vd.array_index];
  2088. if (idata.parent_array_index >= 0) {
  2089. uint32_t parent_flags = scenario->instance_data[idata.parent_array_index].flags;
  2090. if ((parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN) || !(parent_flags & (InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE | InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN))) {
  2091. idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
  2092. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
  2093. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
  2094. continue;
  2095. }
  2096. }
  2097. int range_check = _visibility_range_check<true>(vd, cull_data.camera_position, cull_data.viewport_mask);
  2098. if (range_check == -1) {
  2099. idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
  2100. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
  2101. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
  2102. } else if (range_check == 1) {
  2103. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
  2104. idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
  2105. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
  2106. } else {
  2107. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
  2108. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
  2109. if (range_check == 2) {
  2110. idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
  2111. } else {
  2112. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
  2113. }
  2114. }
  2115. }
  2116. }
  2117. template <bool p_fade_check>
  2118. int RendererSceneCull::_visibility_range_check(InstanceVisibilityData &r_vis_data, const Vector3 &p_camera_pos, uint64_t p_viewport_mask) {
  2119. float dist = p_camera_pos.distance_to(r_vis_data.position);
  2120. const RS::VisibilityRangeFadeMode &fade_mode = r_vis_data.fade_mode;
  2121. float begin_offset = -r_vis_data.range_begin_margin;
  2122. float end_offset = r_vis_data.range_end_margin;
  2123. if (fade_mode == RS::VISIBILITY_RANGE_FADE_DISABLED && !(p_viewport_mask & r_vis_data.viewport_state)) {
  2124. begin_offset = -begin_offset;
  2125. end_offset = -end_offset;
  2126. }
  2127. if (r_vis_data.range_end > 0.0f && dist > r_vis_data.range_end + end_offset) {
  2128. r_vis_data.viewport_state &= ~p_viewport_mask;
  2129. return -1;
  2130. } else if (r_vis_data.range_begin > 0.0f && dist < r_vis_data.range_begin + begin_offset) {
  2131. r_vis_data.viewport_state &= ~p_viewport_mask;
  2132. return 1;
  2133. } else {
  2134. r_vis_data.viewport_state |= p_viewport_mask;
  2135. if (p_fade_check) {
  2136. if (fade_mode != RS::VISIBILITY_RANGE_FADE_DISABLED) {
  2137. r_vis_data.children_fade_alpha = 1.0f;
  2138. if (r_vis_data.range_end > 0.0f && dist > r_vis_data.range_end - end_offset) {
  2139. if (fade_mode == RS::VISIBILITY_RANGE_FADE_DEPENDENCIES) {
  2140. r_vis_data.children_fade_alpha = MIN(1.0f, (dist - (r_vis_data.range_end - end_offset)) / (2.0f * r_vis_data.range_end_margin));
  2141. }
  2142. return 2;
  2143. } else if (r_vis_data.range_begin > 0.0f && dist < r_vis_data.range_begin - begin_offset) {
  2144. if (fade_mode == RS::VISIBILITY_RANGE_FADE_DEPENDENCIES) {
  2145. r_vis_data.children_fade_alpha = MIN(1.0f, 1.0 - (dist - (r_vis_data.range_begin + begin_offset)) / (2.0f * r_vis_data.range_begin_margin));
  2146. }
  2147. return 2;
  2148. }
  2149. }
  2150. }
  2151. return 0;
  2152. }
  2153. }
  2154. bool RendererSceneCull::_visibility_parent_check(const CullData &p_cull_data, const InstanceData &p_instance_data) {
  2155. if (p_instance_data.parent_array_index == -1) {
  2156. return true;
  2157. }
  2158. const uint32_t &parent_flags = p_cull_data.scenario->instance_data[p_instance_data.parent_array_index].flags;
  2159. return ((parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK) == InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE) || (parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN);
  2160. }
  2161. void RendererSceneCull::_scene_cull_threaded(uint32_t p_thread, CullData *cull_data) {
  2162. uint32_t cull_total = cull_data->scenario->instance_data.size();
  2163. uint32_t total_threads = WorkerThreadPool::get_singleton()->get_thread_count();
  2164. uint32_t cull_from = p_thread * cull_total / total_threads;
  2165. uint32_t cull_to = (p_thread + 1 == total_threads) ? cull_total : ((p_thread + 1) * cull_total / total_threads);
  2166. _scene_cull(*cull_data, scene_cull_result_threads[p_thread], cull_from, cull_to);
  2167. }
  2168. void RendererSceneCull::_scene_cull(CullData &cull_data, InstanceCullResult &cull_result, uint64_t p_from, uint64_t p_to) {
  2169. uint64_t frame_number = RSG::rasterizer->get_frame_number();
  2170. float lightmap_probe_update_speed = RSG::light_storage->lightmap_get_probe_capture_update_speed() * RSG::rasterizer->get_frame_delta_time();
  2171. uint32_t sdfgi_last_light_index = 0xFFFFFFFF;
  2172. uint32_t sdfgi_last_light_cascade = 0xFFFFFFFF;
  2173. RID instance_pair_buffer[MAX_INSTANCE_PAIRS];
  2174. Transform3D inv_cam_transform = cull_data.cam_transform.inverse();
  2175. float z_near = cull_data.camera_matrix->get_z_near();
  2176. for (uint64_t i = p_from; i < p_to; i++) {
  2177. bool mesh_visible = false;
  2178. InstanceData &idata = cull_data.scenario->instance_data[i];
  2179. uint32_t visibility_flags = idata.flags & (InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE | InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN | InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN);
  2180. int32_t visibility_check = -1;
  2181. #define HIDDEN_BY_VISIBILITY_CHECKS (visibility_flags == InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE || visibility_flags == InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN)
  2182. #define LAYER_CHECK (cull_data.visible_layers & idata.layer_mask)
  2183. #define IN_FRUSTUM(f) (cull_data.scenario->instance_aabbs[i].in_frustum(f))
  2184. #define VIS_RANGE_CHECK ((idata.visibility_index == -1) || _visibility_range_check<false>(cull_data.scenario->instance_visibility[idata.visibility_index], cull_data.cam_transform.origin, cull_data.visibility_viewport_mask) == 0)
  2185. #define VIS_PARENT_CHECK (_visibility_parent_check(cull_data, idata))
  2186. #define VIS_CHECK (visibility_check < 0 ? (visibility_check = (visibility_flags != InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK || (VIS_RANGE_CHECK && VIS_PARENT_CHECK))) : visibility_check)
  2187. #define OCCLUSION_CULLED (cull_data.occlusion_buffer != nullptr && (cull_data.scenario->instance_data[i].flags & InstanceData::FLAG_IGNORE_OCCLUSION_CULLING) == 0 && cull_data.occlusion_buffer->is_occluded(cull_data.scenario->instance_aabbs[i].bounds, cull_data.cam_transform.origin, inv_cam_transform, *cull_data.camera_matrix, z_near))
  2188. if (!HIDDEN_BY_VISIBILITY_CHECKS) {
  2189. if ((LAYER_CHECK && IN_FRUSTUM(cull_data.cull->frustum) && VIS_CHECK && !OCCLUSION_CULLED) || (cull_data.scenario->instance_data[i].flags & InstanceData::FLAG_IGNORE_ALL_CULLING)) {
  2190. uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
  2191. if (base_type == RS::INSTANCE_LIGHT) {
  2192. cull_result.lights.push_back(idata.instance);
  2193. cull_result.light_instances.push_back(RID::from_uint64(idata.instance_data_rid));
  2194. if (cull_data.shadow_atlas.is_valid() && RSG::light_storage->light_has_shadow(idata.base_rid)) {
  2195. scene_render->light_instance_mark_visible(RID::from_uint64(idata.instance_data_rid)); //mark it visible for shadow allocation later
  2196. }
  2197. } else if (base_type == RS::INSTANCE_REFLECTION_PROBE) {
  2198. if (cull_data.render_reflection_probe != idata.instance) {
  2199. //avoid entering The Matrix
  2200. if ((idata.flags & InstanceData::FLAG_REFLECTION_PROBE_DIRTY) || scene_render->reflection_probe_instance_needs_redraw(RID::from_uint64(idata.instance_data_rid))) {
  2201. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(idata.instance->base_data);
  2202. cull_data.cull->lock.lock();
  2203. if (!reflection_probe->update_list.in_list()) {
  2204. reflection_probe->render_step = 0;
  2205. reflection_probe_render_list.add_last(&reflection_probe->update_list);
  2206. }
  2207. cull_data.cull->lock.unlock();
  2208. idata.flags &= ~uint32_t(InstanceData::FLAG_REFLECTION_PROBE_DIRTY);
  2209. }
  2210. if (scene_render->reflection_probe_instance_has_reflection(RID::from_uint64(idata.instance_data_rid))) {
  2211. cull_result.reflections.push_back(RID::from_uint64(idata.instance_data_rid));
  2212. }
  2213. }
  2214. } else if (base_type == RS::INSTANCE_DECAL) {
  2215. cull_result.decals.push_back(RID::from_uint64(idata.instance_data_rid));
  2216. } else if (base_type == RS::INSTANCE_VOXEL_GI) {
  2217. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(idata.instance->base_data);
  2218. cull_data.cull->lock.lock();
  2219. if (!voxel_gi->update_element.in_list()) {
  2220. voxel_gi_update_list.add(&voxel_gi->update_element);
  2221. }
  2222. cull_data.cull->lock.unlock();
  2223. cull_result.voxel_gi_instances.push_back(RID::from_uint64(idata.instance_data_rid));
  2224. } else if (base_type == RS::INSTANCE_LIGHTMAP) {
  2225. cull_result.lightmaps.push_back(RID::from_uint64(idata.instance_data_rid));
  2226. } else if (base_type == RS::INSTANCE_FOG_VOLUME) {
  2227. cull_result.fog_volumes.push_back(RID::from_uint64(idata.instance_data_rid));
  2228. } else if (base_type == RS::INSTANCE_VISIBLITY_NOTIFIER) {
  2229. InstanceVisibilityNotifierData *vnd = idata.visibility_notifier;
  2230. if (!vnd->list_element.in_list()) {
  2231. visible_notifier_list_lock.lock();
  2232. visible_notifier_list.add(&vnd->list_element);
  2233. visible_notifier_list_lock.unlock();
  2234. vnd->just_visible = true;
  2235. }
  2236. vnd->visible_in_frame = RSG::rasterizer->get_frame_number();
  2237. } else if (((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) && !(idata.flags & InstanceData::FLAG_CAST_SHADOWS_ONLY)) {
  2238. bool keep = true;
  2239. if (idata.flags & InstanceData::FLAG_REDRAW_IF_VISIBLE) {
  2240. RenderingServerDefault::redraw_request();
  2241. }
  2242. if (base_type == RS::INSTANCE_MESH) {
  2243. mesh_visible = true;
  2244. } else if (base_type == RS::INSTANCE_PARTICLES) {
  2245. //particles visible? process them
  2246. if (RSG::particles_storage->particles_is_inactive(idata.base_rid)) {
  2247. //but if nothing is going on, don't do it.
  2248. keep = false;
  2249. } else {
  2250. cull_data.cull->lock.lock();
  2251. RSG::particles_storage->particles_request_process(idata.base_rid);
  2252. cull_data.cull->lock.unlock();
  2253. RSG::particles_storage->particles_set_view_axis(idata.base_rid, -cull_data.cam_transform.basis.get_column(2).normalized(), cull_data.cam_transform.basis.get_column(1).normalized());
  2254. //particles visible? request redraw
  2255. RenderingServerDefault::redraw_request();
  2256. }
  2257. }
  2258. if (idata.parent_array_index != -1) {
  2259. float fade = 1.0f;
  2260. const uint32_t &parent_flags = cull_data.scenario->instance_data[idata.parent_array_index].flags;
  2261. if (parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN) {
  2262. const int32_t &parent_idx = cull_data.scenario->instance_data[idata.parent_array_index].visibility_index;
  2263. fade = cull_data.scenario->instance_visibility[parent_idx].children_fade_alpha;
  2264. }
  2265. idata.instance_geometry->set_parent_fade_alpha(fade);
  2266. }
  2267. if (geometry_instance_pair_mask & (1 << RS::INSTANCE_LIGHT) && (idata.flags & InstanceData::FLAG_GEOM_LIGHTING_DIRTY)) {
  2268. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2269. uint32_t idx = 0;
  2270. for (const Instance *E : geom->lights) {
  2271. InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
  2272. instance_pair_buffer[idx++] = light->instance;
  2273. if (idx == MAX_INSTANCE_PAIRS) {
  2274. break;
  2275. }
  2276. }
  2277. ERR_FAIL_NULL(geom->geometry_instance);
  2278. geom->geometry_instance->pair_light_instances(instance_pair_buffer, idx);
  2279. idata.flags &= ~uint32_t(InstanceData::FLAG_GEOM_LIGHTING_DIRTY);
  2280. }
  2281. if (idata.flags & InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY) {
  2282. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2283. ERR_FAIL_NULL(geom->geometry_instance);
  2284. geom->geometry_instance->set_softshadow_projector_pairing(geom->softshadow_count > 0, geom->projector_count > 0);
  2285. idata.flags &= ~uint32_t(InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY);
  2286. }
  2287. if (geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && (idata.flags & InstanceData::FLAG_GEOM_REFLECTION_DIRTY)) {
  2288. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2289. uint32_t idx = 0;
  2290. for (const Instance *E : geom->reflection_probes) {
  2291. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->base_data);
  2292. instance_pair_buffer[idx++] = reflection_probe->instance;
  2293. if (idx == MAX_INSTANCE_PAIRS) {
  2294. break;
  2295. }
  2296. }
  2297. ERR_FAIL_NULL(geom->geometry_instance);
  2298. geom->geometry_instance->pair_reflection_probe_instances(instance_pair_buffer, idx);
  2299. idata.flags &= ~uint32_t(InstanceData::FLAG_GEOM_REFLECTION_DIRTY);
  2300. }
  2301. if (geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && (idata.flags & InstanceData::FLAG_GEOM_DECAL_DIRTY)) {
  2302. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2303. uint32_t idx = 0;
  2304. for (const Instance *E : geom->decals) {
  2305. InstanceDecalData *decal = static_cast<InstanceDecalData *>(E->base_data);
  2306. instance_pair_buffer[idx++] = decal->instance;
  2307. if (idx == MAX_INSTANCE_PAIRS) {
  2308. break;
  2309. }
  2310. }
  2311. ERR_FAIL_NULL(geom->geometry_instance);
  2312. geom->geometry_instance->pair_decal_instances(instance_pair_buffer, idx);
  2313. idata.flags &= ~uint32_t(InstanceData::FLAG_GEOM_DECAL_DIRTY);
  2314. }
  2315. if (idata.flags & InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY) {
  2316. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2317. uint32_t idx = 0;
  2318. for (const Instance *E : geom->voxel_gi_instances) {
  2319. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(E->base_data);
  2320. instance_pair_buffer[idx++] = voxel_gi->probe_instance;
  2321. if (idx == MAX_INSTANCE_PAIRS) {
  2322. break;
  2323. }
  2324. }
  2325. ERR_FAIL_NULL(geom->geometry_instance);
  2326. geom->geometry_instance->pair_voxel_gi_instances(instance_pair_buffer, idx);
  2327. idata.flags &= ~uint32_t(InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY);
  2328. }
  2329. if ((idata.flags & InstanceData::FLAG_LIGHTMAP_CAPTURE) && idata.instance->last_frame_pass != frame_number && !idata.instance->lightmap_target_sh.is_empty() && !idata.instance->lightmap_sh.is_empty()) {
  2330. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2331. Color *sh = idata.instance->lightmap_sh.ptrw();
  2332. const Color *target_sh = idata.instance->lightmap_target_sh.ptr();
  2333. for (uint32_t j = 0; j < 9; j++) {
  2334. sh[j] = sh[j].lerp(target_sh[j], MIN(1.0, lightmap_probe_update_speed));
  2335. }
  2336. ERR_FAIL_NULL(geom->geometry_instance);
  2337. geom->geometry_instance->set_lightmap_capture(sh);
  2338. idata.instance->last_frame_pass = frame_number;
  2339. }
  2340. if (keep) {
  2341. cull_result.geometry_instances.push_back(idata.instance_geometry);
  2342. }
  2343. }
  2344. }
  2345. for (uint32_t j = 0; j < cull_data.cull->shadow_count; j++) {
  2346. for (uint32_t k = 0; k < cull_data.cull->shadows[j].cascade_count; k++) {
  2347. if (IN_FRUSTUM(cull_data.cull->shadows[j].cascades[k].frustum) && VIS_CHECK) {
  2348. uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
  2349. if (((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) && idata.flags & InstanceData::FLAG_CAST_SHADOWS) {
  2350. cull_result.directional_shadows[j].cascade_geometry_instances[k].push_back(idata.instance_geometry);
  2351. mesh_visible = true;
  2352. }
  2353. }
  2354. }
  2355. }
  2356. }
  2357. #undef HIDDEN_BY_VISIBILITY_CHECKS
  2358. #undef LAYER_CHECK
  2359. #undef IN_FRUSTUM
  2360. #undef VIS_RANGE_CHECK
  2361. #undef VIS_PARENT_CHECK
  2362. #undef VIS_CHECK
  2363. #undef OCCLUSION_CULLED
  2364. for (uint32_t j = 0; j < cull_data.cull->sdfgi.region_count; j++) {
  2365. if (cull_data.scenario->instance_aabbs[i].in_aabb(cull_data.cull->sdfgi.region_aabb[j])) {
  2366. uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
  2367. if (base_type == RS::INSTANCE_LIGHT) {
  2368. InstanceLightData *instance_light = (InstanceLightData *)idata.instance->base_data;
  2369. if (instance_light->bake_mode == RS::LIGHT_BAKE_STATIC && cull_data.cull->sdfgi.region_cascade[j] <= instance_light->max_sdfgi_cascade) {
  2370. if (sdfgi_last_light_index != i || sdfgi_last_light_cascade != cull_data.cull->sdfgi.region_cascade[j]) {
  2371. sdfgi_last_light_index = i;
  2372. sdfgi_last_light_cascade = cull_data.cull->sdfgi.region_cascade[j];
  2373. cull_result.sdfgi_cascade_lights[sdfgi_last_light_cascade].push_back(instance_light->instance);
  2374. }
  2375. }
  2376. } else if ((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  2377. if (idata.flags & InstanceData::FLAG_USES_BAKED_LIGHT) {
  2378. cull_result.sdfgi_region_geometry_instances[j].push_back(idata.instance_geometry);
  2379. mesh_visible = true;
  2380. }
  2381. }
  2382. }
  2383. }
  2384. if (mesh_visible && cull_data.scenario->instance_data[i].flags & InstanceData::FLAG_USES_MESH_INSTANCE) {
  2385. cull_result.mesh_instances.push_back(cull_data.scenario->instance_data[i].instance->mesh_instance);
  2386. }
  2387. }
  2388. }
  2389. void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_camera_data, RID p_render_buffers, RID p_environment, RID p_force_camera_effects, uint32_t p_visible_layers, RID p_scenario, RID p_viewport, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_lod_threshold, bool p_using_shadows, RendererScene::RenderInfo *r_render_info) {
  2390. Instance *render_reflection_probe = instance_owner.get_or_null(p_reflection_probe); //if null, not rendering to it
  2391. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  2392. render_pass++;
  2393. scene_render->set_scene_pass(render_pass);
  2394. if (p_render_buffers.is_valid()) {
  2395. //no rendering code here, this is only to set up what needs to be done, request regions, etc.
  2396. scene_render->sdfgi_update(p_render_buffers, p_environment, p_camera_data->main_transform.origin); //update conditions for SDFGI (whether its used or not)
  2397. }
  2398. RENDER_TIMESTAMP("Update Visibility Dependencies");
  2399. if (scenario->instance_visibility.get_bin_count() > 0) {
  2400. if (!scenario->viewport_visibility_masks.has(p_viewport)) {
  2401. scenario_add_viewport_visibility_mask(scenario->self, p_viewport);
  2402. }
  2403. VisibilityCullData visibility_cull_data;
  2404. visibility_cull_data.scenario = scenario;
  2405. visibility_cull_data.viewport_mask = scenario->viewport_visibility_masks[p_viewport];
  2406. visibility_cull_data.camera_position = p_camera_data->main_transform.origin;
  2407. for (int i = scenario->instance_visibility.get_bin_count() - 1; i > 0; i--) { // We skip bin 0
  2408. visibility_cull_data.cull_offset = scenario->instance_visibility.get_bin_start(i);
  2409. visibility_cull_data.cull_count = scenario->instance_visibility.get_bin_size(i);
  2410. if (visibility_cull_data.cull_count == 0) {
  2411. continue;
  2412. }
  2413. if (visibility_cull_data.cull_count > thread_cull_threshold) {
  2414. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &RendererSceneCull::_visibility_cull_threaded, &visibility_cull_data, WorkerThreadPool::get_singleton()->get_thread_count(), -1, true, SNAME("VisibilityCullInstances"));
  2415. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  2416. } else {
  2417. _visibility_cull(visibility_cull_data, visibility_cull_data.cull_offset, visibility_cull_data.cull_offset + visibility_cull_data.cull_count);
  2418. }
  2419. }
  2420. }
  2421. RENDER_TIMESTAMP("Cull 3D Scene");
  2422. //rasterizer->set_camera(p_camera_data->main_transform, p_camera_data.main_projection, p_camera_data.is_orthogonal);
  2423. /* STEP 2 - CULL */
  2424. Vector<Plane> planes = p_camera_data->main_projection.get_projection_planes(p_camera_data->main_transform);
  2425. cull.frustum = Frustum(planes);
  2426. Vector<RID> directional_lights;
  2427. // directional lights
  2428. {
  2429. cull.shadow_count = 0;
  2430. Vector<Instance *> lights_with_shadow;
  2431. for (Instance *E : scenario->directional_lights) {
  2432. if (!E->visible) {
  2433. continue;
  2434. }
  2435. if (directional_lights.size() > RendererSceneRender::MAX_DIRECTIONAL_LIGHTS) {
  2436. break;
  2437. }
  2438. InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
  2439. //check shadow..
  2440. if (light) {
  2441. if (p_using_shadows && p_shadow_atlas.is_valid() && RSG::light_storage->light_has_shadow(E->base) && !(RSG::light_storage->light_get_type(E->base) == RS::LIGHT_DIRECTIONAL && RSG::light_storage->light_directional_get_sky_mode(E->base) == RS::LIGHT_DIRECTIONAL_SKY_MODE_SKY_ONLY)) {
  2442. lights_with_shadow.push_back(E);
  2443. }
  2444. //add to list
  2445. directional_lights.push_back(light->instance);
  2446. }
  2447. }
  2448. scene_render->set_directional_shadow_count(lights_with_shadow.size());
  2449. for (int i = 0; i < lights_with_shadow.size(); i++) {
  2450. _light_instance_setup_directional_shadow(i, lights_with_shadow[i], p_camera_data->main_transform, p_camera_data->main_projection, p_camera_data->is_orthogonal, p_camera_data->vaspect);
  2451. }
  2452. }
  2453. { //sdfgi
  2454. cull.sdfgi.region_count = 0;
  2455. if (p_render_buffers.is_valid()) {
  2456. cull.sdfgi.cascade_light_count = 0;
  2457. uint32_t prev_cascade = 0xFFFFFFFF;
  2458. uint32_t pending_region_count = scene_render->sdfgi_get_pending_region_count(p_render_buffers);
  2459. for (uint32_t i = 0; i < pending_region_count; i++) {
  2460. cull.sdfgi.region_aabb[i] = scene_render->sdfgi_get_pending_region_bounds(p_render_buffers, i);
  2461. uint32_t region_cascade = scene_render->sdfgi_get_pending_region_cascade(p_render_buffers, i);
  2462. cull.sdfgi.region_cascade[i] = region_cascade;
  2463. if (region_cascade != prev_cascade) {
  2464. cull.sdfgi.cascade_light_index[cull.sdfgi.cascade_light_count] = region_cascade;
  2465. cull.sdfgi.cascade_light_count++;
  2466. prev_cascade = region_cascade;
  2467. }
  2468. }
  2469. cull.sdfgi.region_count = pending_region_count;
  2470. }
  2471. }
  2472. scene_cull_result.clear();
  2473. {
  2474. uint64_t cull_from = 0;
  2475. uint64_t cull_to = scenario->instance_data.size();
  2476. CullData cull_data;
  2477. //prepare for eventual thread usage
  2478. cull_data.cull = &cull;
  2479. cull_data.scenario = scenario;
  2480. cull_data.shadow_atlas = p_shadow_atlas;
  2481. cull_data.cam_transform = p_camera_data->main_transform;
  2482. cull_data.visible_layers = p_visible_layers;
  2483. cull_data.render_reflection_probe = render_reflection_probe;
  2484. cull_data.occlusion_buffer = RendererSceneOcclusionCull::get_singleton()->buffer_get_ptr(p_viewport);
  2485. cull_data.camera_matrix = &p_camera_data->main_projection;
  2486. cull_data.visibility_viewport_mask = scenario->viewport_visibility_masks.has(p_viewport) ? scenario->viewport_visibility_masks[p_viewport] : 0;
  2487. //#define DEBUG_CULL_TIME
  2488. #ifdef DEBUG_CULL_TIME
  2489. uint64_t time_from = OS::get_singleton()->get_ticks_usec();
  2490. #endif
  2491. if (cull_to > thread_cull_threshold) {
  2492. //multiple threads
  2493. for (uint32_t i = 0; i < scene_cull_result_threads.size(); i++) {
  2494. scene_cull_result_threads[i].clear();
  2495. }
  2496. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &RendererSceneCull::_scene_cull_threaded, &cull_data, scene_cull_result_threads.size(), -1, true, SNAME("RenderCullInstances"));
  2497. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  2498. for (uint32_t i = 0; i < scene_cull_result_threads.size(); i++) {
  2499. scene_cull_result.append_from(scene_cull_result_threads[i]);
  2500. }
  2501. } else {
  2502. //single threaded
  2503. _scene_cull(cull_data, scene_cull_result, cull_from, cull_to);
  2504. }
  2505. #ifdef DEBUG_CULL_TIME
  2506. static float time_avg = 0;
  2507. static uint32_t time_count = 0;
  2508. time_avg += double(OS::get_singleton()->get_ticks_usec() - time_from) / 1000.0;
  2509. time_count++;
  2510. print_line("time taken: " + rtos(time_avg / time_count));
  2511. #endif
  2512. if (scene_cull_result.mesh_instances.size()) {
  2513. for (uint64_t i = 0; i < scene_cull_result.mesh_instances.size(); i++) {
  2514. RSG::mesh_storage->mesh_instance_check_for_update(scene_cull_result.mesh_instances[i]);
  2515. }
  2516. RSG::mesh_storage->update_mesh_instances();
  2517. }
  2518. }
  2519. //render shadows
  2520. max_shadows_used = 0;
  2521. if (p_using_shadows) { //setup shadow maps
  2522. // Directional Shadows
  2523. for (uint32_t i = 0; i < cull.shadow_count; i++) {
  2524. for (uint32_t j = 0; j < cull.shadows[i].cascade_count; j++) {
  2525. const Cull::Shadow::Cascade &c = cull.shadows[i].cascades[j];
  2526. // print_line("shadow " + itos(i) + " cascade " + itos(j) + " elements: " + itos(c.cull_result.size()));
  2527. scene_render->light_instance_set_shadow_transform(cull.shadows[i].light_instance, c.projection, c.transform, c.zfar, c.split, j, c.shadow_texel_size, c.bias_scale, c.range_begin, c.uv_scale);
  2528. if (max_shadows_used == MAX_UPDATE_SHADOWS) {
  2529. continue;
  2530. }
  2531. render_shadow_data[max_shadows_used].light = cull.shadows[i].light_instance;
  2532. render_shadow_data[max_shadows_used].pass = j;
  2533. render_shadow_data[max_shadows_used].instances.merge_unordered(scene_cull_result.directional_shadows[i].cascade_geometry_instances[j]);
  2534. max_shadows_used++;
  2535. }
  2536. }
  2537. // Positional Shadowss
  2538. for (uint32_t i = 0; i < (uint32_t)scene_cull_result.lights.size(); i++) {
  2539. Instance *ins = scene_cull_result.lights[i];
  2540. if (!p_shadow_atlas.is_valid() || !RSG::light_storage->light_has_shadow(ins->base)) {
  2541. continue;
  2542. }
  2543. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  2544. float coverage = 0.f;
  2545. { //compute coverage
  2546. Transform3D cam_xf = p_camera_data->main_transform;
  2547. float zn = p_camera_data->main_projection.get_z_near();
  2548. Plane p(-cam_xf.basis.get_column(2), cam_xf.origin + cam_xf.basis.get_column(2) * -zn); //camera near plane
  2549. // near plane half width and height
  2550. Vector2 vp_half_extents = p_camera_data->main_projection.get_viewport_half_extents();
  2551. switch (RSG::light_storage->light_get_type(ins->base)) {
  2552. case RS::LIGHT_OMNI: {
  2553. float radius = RSG::light_storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
  2554. //get two points parallel to near plane
  2555. Vector3 points[2] = {
  2556. ins->transform.origin,
  2557. ins->transform.origin + cam_xf.basis.get_column(0) * radius
  2558. };
  2559. if (!p_camera_data->is_orthogonal) {
  2560. //if using perspetive, map them to near plane
  2561. for (int j = 0; j < 2; j++) {
  2562. if (p.distance_to(points[j]) < 0) {
  2563. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  2564. }
  2565. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  2566. }
  2567. }
  2568. float screen_diameter = points[0].distance_to(points[1]) * 2;
  2569. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  2570. } break;
  2571. case RS::LIGHT_SPOT: {
  2572. float radius = RSG::light_storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
  2573. float angle = RSG::light_storage->light_get_param(ins->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2574. float w = radius * Math::sin(Math::deg_to_rad(angle));
  2575. float d = radius * Math::cos(Math::deg_to_rad(angle));
  2576. Vector3 base = ins->transform.origin - ins->transform.basis.get_column(2).normalized() * d;
  2577. Vector3 points[2] = {
  2578. base,
  2579. base + cam_xf.basis.get_column(0) * w
  2580. };
  2581. if (!p_camera_data->is_orthogonal) {
  2582. //if using perspetive, map them to near plane
  2583. for (int j = 0; j < 2; j++) {
  2584. if (p.distance_to(points[j]) < 0) {
  2585. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  2586. }
  2587. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  2588. }
  2589. }
  2590. float screen_diameter = points[0].distance_to(points[1]) * 2;
  2591. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  2592. } break;
  2593. default: {
  2594. ERR_PRINT("Invalid Light Type");
  2595. }
  2596. }
  2597. }
  2598. if (light->shadow_dirty) {
  2599. light->last_version++;
  2600. light->shadow_dirty = false;
  2601. }
  2602. bool redraw = scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
  2603. if (redraw && max_shadows_used < MAX_UPDATE_SHADOWS) {
  2604. //must redraw!
  2605. RENDER_TIMESTAMP("> Render Light3D " + itos(i));
  2606. light->shadow_dirty = _light_instance_update_shadow(ins, p_camera_data->main_transform, p_camera_data->main_projection, p_camera_data->is_orthogonal, p_camera_data->vaspect, p_shadow_atlas, scenario, p_screen_mesh_lod_threshold);
  2607. RENDER_TIMESTAMP("< Render Light3D " + itos(i));
  2608. } else {
  2609. light->shadow_dirty = redraw;
  2610. }
  2611. }
  2612. }
  2613. //render SDFGI
  2614. {
  2615. sdfgi_update_data.update_static = false;
  2616. if (cull.sdfgi.region_count > 0) {
  2617. //update regions
  2618. for (uint32_t i = 0; i < cull.sdfgi.region_count; i++) {
  2619. render_sdfgi_data[i].instances.merge_unordered(scene_cull_result.sdfgi_region_geometry_instances[i]);
  2620. render_sdfgi_data[i].region = i;
  2621. }
  2622. //check if static lights were culled
  2623. bool static_lights_culled = false;
  2624. for (uint32_t i = 0; i < cull.sdfgi.cascade_light_count; i++) {
  2625. if (scene_cull_result.sdfgi_cascade_lights[i].size()) {
  2626. static_lights_culled = true;
  2627. break;
  2628. }
  2629. }
  2630. if (static_lights_culled) {
  2631. sdfgi_update_data.static_cascade_count = cull.sdfgi.cascade_light_count;
  2632. sdfgi_update_data.static_cascade_indices = cull.sdfgi.cascade_light_index;
  2633. sdfgi_update_data.static_positional_lights = scene_cull_result.sdfgi_cascade_lights;
  2634. sdfgi_update_data.update_static = true;
  2635. }
  2636. }
  2637. if (p_render_buffers.is_valid()) {
  2638. sdfgi_update_data.directional_lights = &directional_lights;
  2639. sdfgi_update_data.positional_light_instances = scenario->dynamic_lights.ptr();
  2640. sdfgi_update_data.positional_light_count = scenario->dynamic_lights.size();
  2641. }
  2642. }
  2643. //append the directional lights to the lights culled
  2644. for (int i = 0; i < directional_lights.size(); i++) {
  2645. scene_cull_result.light_instances.push_back(directional_lights[i]);
  2646. }
  2647. RID camera_effects;
  2648. if (p_force_camera_effects.is_valid()) {
  2649. camera_effects = p_force_camera_effects;
  2650. } else {
  2651. camera_effects = scenario->camera_effects;
  2652. }
  2653. /* PROCESS GEOMETRY AND DRAW SCENE */
  2654. RID occluders_tex;
  2655. const RendererSceneRender::CameraData *prev_camera_data = p_camera_data;
  2656. if (p_viewport.is_valid()) {
  2657. occluders_tex = RSG::viewport->viewport_get_occluder_debug_texture(p_viewport);
  2658. prev_camera_data = RSG::viewport->viewport_get_prev_camera_data(p_viewport);
  2659. }
  2660. RENDER_TIMESTAMP("Render 3D Scene");
  2661. scene_render->render_scene(p_render_buffers, p_camera_data, prev_camera_data, scene_cull_result.geometry_instances, scene_cull_result.light_instances, scene_cull_result.reflections, scene_cull_result.voxel_gi_instances, scene_cull_result.decals, scene_cull_result.lightmaps, scene_cull_result.fog_volumes, p_environment, camera_effects, p_shadow_atlas, occluders_tex, p_reflection_probe.is_valid() ? RID() : scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass, p_screen_mesh_lod_threshold, render_shadow_data, max_shadows_used, render_sdfgi_data, cull.sdfgi.region_count, &sdfgi_update_data, r_render_info);
  2662. if (p_viewport.is_valid()) {
  2663. RSG::viewport->viewport_set_prev_camera_data(p_viewport, p_camera_data);
  2664. }
  2665. for (uint32_t i = 0; i < max_shadows_used; i++) {
  2666. render_shadow_data[i].instances.clear();
  2667. }
  2668. max_shadows_used = 0;
  2669. for (uint32_t i = 0; i < cull.sdfgi.region_count; i++) {
  2670. render_sdfgi_data[i].instances.clear();
  2671. }
  2672. // virtual void render_scene(RID p_render_buffers, const Transform3D &p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal, 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, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_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 RenderSDFGIStaticLightData *p_render_sdfgi_static_lights=nullptr) = 0;
  2673. }
  2674. RID RendererSceneCull::_render_get_environment(RID p_camera, RID p_scenario) {
  2675. Camera *camera = camera_owner.get_or_null(p_camera);
  2676. if (camera && scene_render->is_environment(camera->env)) {
  2677. return camera->env;
  2678. }
  2679. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  2680. if (!scenario) {
  2681. return RID();
  2682. }
  2683. if (scene_render->is_environment(scenario->environment)) {
  2684. return scenario->environment;
  2685. }
  2686. if (scene_render->is_environment(scenario->fallback_environment)) {
  2687. return scenario->fallback_environment;
  2688. }
  2689. return RID();
  2690. }
  2691. void RendererSceneCull::render_empty_scene(RID p_render_buffers, RID p_scenario, RID p_shadow_atlas) {
  2692. #ifndef _3D_DISABLED
  2693. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  2694. RID environment;
  2695. if (scenario->environment.is_valid()) {
  2696. environment = scenario->environment;
  2697. } else {
  2698. environment = scenario->fallback_environment;
  2699. }
  2700. RENDER_TIMESTAMP("Render Empty 3D Scene");
  2701. RendererSceneRender::CameraData camera_data;
  2702. camera_data.set_camera(Transform3D(), Projection(), true, false);
  2703. scene_render->render_scene(p_render_buffers, &camera_data, &camera_data, PagedArray<RenderGeometryInstance *>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), RID(), RID(), p_shadow_atlas, RID(), scenario->reflection_atlas, RID(), 0, 0, nullptr, 0, nullptr, 0, nullptr);
  2704. #endif
  2705. }
  2706. bool RendererSceneCull::_render_reflection_probe_step(Instance *p_instance, int p_step) {
  2707. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  2708. Scenario *scenario = p_instance->scenario;
  2709. ERR_FAIL_COND_V(!scenario, true);
  2710. RenderingServerDefault::redraw_request(); //update, so it updates in editor
  2711. if (p_step == 0) {
  2712. if (!scene_render->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
  2713. return true; //all full
  2714. }
  2715. }
  2716. if (p_step >= 0 && p_step < 6) {
  2717. static const Vector3 view_normals[6] = {
  2718. Vector3(+1, 0, 0),
  2719. Vector3(-1, 0, 0),
  2720. Vector3(0, +1, 0),
  2721. Vector3(0, -1, 0),
  2722. Vector3(0, 0, +1),
  2723. Vector3(0, 0, -1)
  2724. };
  2725. static const Vector3 view_up[6] = {
  2726. Vector3(0, -1, 0),
  2727. Vector3(0, -1, 0),
  2728. Vector3(0, 0, +1),
  2729. Vector3(0, 0, -1),
  2730. Vector3(0, -1, 0),
  2731. Vector3(0, -1, 0)
  2732. };
  2733. Vector3 extents = RSG::light_storage->reflection_probe_get_extents(p_instance->base);
  2734. Vector3 origin_offset = RSG::light_storage->reflection_probe_get_origin_offset(p_instance->base);
  2735. float max_distance = RSG::light_storage->reflection_probe_get_origin_max_distance(p_instance->base);
  2736. float size = scene_render->reflection_atlas_get_size(scenario->reflection_atlas);
  2737. float mesh_lod_threshold = RSG::light_storage->reflection_probe_get_mesh_lod_threshold(p_instance->base) / size;
  2738. Vector3 edge = view_normals[p_step] * extents;
  2739. float distance = ABS(view_normals[p_step].dot(edge) - view_normals[p_step].dot(origin_offset)); //distance from origin offset to actual view distance limit
  2740. max_distance = MAX(max_distance, distance);
  2741. //render cubemap side
  2742. Projection cm;
  2743. cm.set_perspective(90, 1, 0.01, max_distance);
  2744. Transform3D local_view;
  2745. local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]);
  2746. Transform3D xform = p_instance->transform * local_view;
  2747. RID shadow_atlas;
  2748. bool use_shadows = RSG::light_storage->reflection_probe_renders_shadows(p_instance->base);
  2749. if (use_shadows) {
  2750. shadow_atlas = scenario->reflection_probe_shadow_atlas;
  2751. }
  2752. RID environment;
  2753. if (scenario->environment.is_valid()) {
  2754. environment = scenario->environment;
  2755. } else {
  2756. environment = scenario->fallback_environment;
  2757. }
  2758. RENDER_TIMESTAMP("Render ReflectionProbe, Step " + itos(p_step));
  2759. RendererSceneRender::CameraData camera_data;
  2760. camera_data.set_camera(xform, cm, false, false);
  2761. _render_scene(&camera_data, RID(), environment, RID(), RSG::light_storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, RID(), shadow_atlas, reflection_probe->instance, p_step, mesh_lod_threshold, use_shadows);
  2762. } else {
  2763. //do roughness postprocess step until it believes it's done
  2764. RENDER_TIMESTAMP("Post-Process ReflectionProbe, Step " + itos(p_step));
  2765. return scene_render->reflection_probe_instance_postprocess_step(reflection_probe->instance);
  2766. }
  2767. return false;
  2768. }
  2769. void RendererSceneCull::render_probes() {
  2770. /* REFLECTION PROBES */
  2771. SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();
  2772. bool busy = false;
  2773. while (ref_probe) {
  2774. SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
  2775. RID base = ref_probe->self()->owner->base;
  2776. switch (RSG::light_storage->reflection_probe_get_update_mode(base)) {
  2777. case RS::REFLECTION_PROBE_UPDATE_ONCE: {
  2778. if (busy) { //already rendering something
  2779. break;
  2780. }
  2781. bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
  2782. if (done) {
  2783. reflection_probe_render_list.remove(ref_probe);
  2784. } else {
  2785. ref_probe->self()->render_step++;
  2786. }
  2787. busy = true; //do not render another one of this kind
  2788. } break;
  2789. case RS::REFLECTION_PROBE_UPDATE_ALWAYS: {
  2790. int step = 0;
  2791. bool done = false;
  2792. while (!done) {
  2793. done = _render_reflection_probe_step(ref_probe->self()->owner, step);
  2794. step++;
  2795. }
  2796. reflection_probe_render_list.remove(ref_probe);
  2797. } break;
  2798. }
  2799. ref_probe = next;
  2800. }
  2801. /* VOXEL GIS */
  2802. SelfList<InstanceVoxelGIData> *voxel_gi = voxel_gi_update_list.first();
  2803. if (voxel_gi) {
  2804. RENDER_TIMESTAMP("Render VoxelGI");
  2805. }
  2806. while (voxel_gi) {
  2807. SelfList<InstanceVoxelGIData> *next = voxel_gi->next();
  2808. InstanceVoxelGIData *probe = voxel_gi->self();
  2809. //Instance *instance_probe = probe->owner;
  2810. //check if probe must be setup, but don't do if on the lighting thread
  2811. bool cache_dirty = false;
  2812. int cache_count = 0;
  2813. {
  2814. int light_cache_size = probe->light_cache.size();
  2815. const InstanceVoxelGIData::LightCache *caches = probe->light_cache.ptr();
  2816. const RID *instance_caches = probe->light_instances.ptr();
  2817. int idx = 0; //must count visible lights
  2818. for (Instance *E : probe->lights) {
  2819. Instance *instance = E;
  2820. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2821. if (!instance->visible) {
  2822. continue;
  2823. }
  2824. if (cache_dirty) {
  2825. //do nothing, since idx must count all visible lights anyway
  2826. } else if (idx >= light_cache_size) {
  2827. cache_dirty = true;
  2828. } else {
  2829. const InstanceVoxelGIData::LightCache *cache = &caches[idx];
  2830. if (
  2831. instance_caches[idx] != instance_light->instance ||
  2832. cache->has_shadow != RSG::light_storage->light_has_shadow(instance->base) ||
  2833. cache->type != RSG::light_storage->light_get_type(instance->base) ||
  2834. cache->transform != instance->transform ||
  2835. cache->color != RSG::light_storage->light_get_color(instance->base) ||
  2836. cache->energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
  2837. cache->bake_energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
  2838. cache->radius != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
  2839. cache->attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
  2840. cache->spot_angle != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
  2841. cache->spot_attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION)) {
  2842. cache_dirty = true;
  2843. }
  2844. }
  2845. idx++;
  2846. }
  2847. for (const Instance *instance : probe->owner->scenario->directional_lights) {
  2848. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2849. if (!instance->visible) {
  2850. continue;
  2851. }
  2852. if (cache_dirty) {
  2853. //do nothing, since idx must count all visible lights anyway
  2854. } else if (idx >= light_cache_size) {
  2855. cache_dirty = true;
  2856. } else {
  2857. const InstanceVoxelGIData::LightCache *cache = &caches[idx];
  2858. if (
  2859. instance_caches[idx] != instance_light->instance ||
  2860. cache->has_shadow != RSG::light_storage->light_has_shadow(instance->base) ||
  2861. cache->type != RSG::light_storage->light_get_type(instance->base) ||
  2862. cache->transform != instance->transform ||
  2863. cache->color != RSG::light_storage->light_get_color(instance->base) ||
  2864. cache->energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
  2865. cache->bake_energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
  2866. cache->radius != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
  2867. cache->attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
  2868. cache->spot_angle != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
  2869. cache->spot_attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION) ||
  2870. cache->sky_mode != RSG::light_storage->light_directional_get_sky_mode(instance->base)) {
  2871. cache_dirty = true;
  2872. }
  2873. }
  2874. idx++;
  2875. }
  2876. if (idx != light_cache_size) {
  2877. cache_dirty = true;
  2878. }
  2879. cache_count = idx;
  2880. }
  2881. bool update_lights = scene_render->voxel_gi_needs_update(probe->probe_instance);
  2882. if (cache_dirty) {
  2883. probe->light_cache.resize(cache_count);
  2884. probe->light_instances.resize(cache_count);
  2885. if (cache_count) {
  2886. InstanceVoxelGIData::LightCache *caches = probe->light_cache.ptrw();
  2887. RID *instance_caches = probe->light_instances.ptrw();
  2888. int idx = 0; //must count visible lights
  2889. for (Instance *E : probe->lights) {
  2890. Instance *instance = E;
  2891. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2892. if (!instance->visible) {
  2893. continue;
  2894. }
  2895. InstanceVoxelGIData::LightCache *cache = &caches[idx];
  2896. instance_caches[idx] = instance_light->instance;
  2897. cache->has_shadow = RSG::light_storage->light_has_shadow(instance->base);
  2898. cache->type = RSG::light_storage->light_get_type(instance->base);
  2899. cache->transform = instance->transform;
  2900. cache->color = RSG::light_storage->light_get_color(instance->base);
  2901. cache->energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
  2902. cache->bake_energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  2903. cache->radius = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
  2904. cache->attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
  2905. cache->spot_angle = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2906. cache->spot_attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  2907. idx++;
  2908. }
  2909. for (const Instance *instance : probe->owner->scenario->directional_lights) {
  2910. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2911. if (!instance->visible) {
  2912. continue;
  2913. }
  2914. InstanceVoxelGIData::LightCache *cache = &caches[idx];
  2915. instance_caches[idx] = instance_light->instance;
  2916. cache->has_shadow = RSG::light_storage->light_has_shadow(instance->base);
  2917. cache->type = RSG::light_storage->light_get_type(instance->base);
  2918. cache->transform = instance->transform;
  2919. cache->color = RSG::light_storage->light_get_color(instance->base);
  2920. cache->energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
  2921. cache->bake_energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  2922. cache->radius = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
  2923. cache->attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
  2924. cache->spot_angle = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2925. cache->spot_attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  2926. cache->sky_mode = RSG::light_storage->light_directional_get_sky_mode(instance->base);
  2927. idx++;
  2928. }
  2929. }
  2930. update_lights = true;
  2931. }
  2932. scene_cull_result.geometry_instances.clear();
  2933. RID instance_pair_buffer[MAX_INSTANCE_PAIRS];
  2934. for (Instance *E : probe->dynamic_geometries) {
  2935. Instance *ins = E;
  2936. if (!ins->visible) {
  2937. continue;
  2938. }
  2939. InstanceGeometryData *geom = (InstanceGeometryData *)ins->base_data;
  2940. if (ins->scenario && ins->array_index >= 0 && (ins->scenario->instance_data[ins->array_index].flags & InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY)) {
  2941. uint32_t idx = 0;
  2942. for (const Instance *F : geom->voxel_gi_instances) {
  2943. InstanceVoxelGIData *voxel_gi2 = static_cast<InstanceVoxelGIData *>(F->base_data);
  2944. instance_pair_buffer[idx++] = voxel_gi2->probe_instance;
  2945. if (idx == MAX_INSTANCE_PAIRS) {
  2946. break;
  2947. }
  2948. }
  2949. ERR_FAIL_NULL(geom->geometry_instance);
  2950. geom->geometry_instance->pair_voxel_gi_instances(instance_pair_buffer, idx);
  2951. ins->scenario->instance_data[ins->array_index].flags &= ~uint32_t(InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY);
  2952. }
  2953. ERR_FAIL_NULL(geom->geometry_instance);
  2954. scene_cull_result.geometry_instances.push_back(geom->geometry_instance);
  2955. }
  2956. scene_render->voxel_gi_update(probe->probe_instance, update_lights, probe->light_instances, scene_cull_result.geometry_instances);
  2957. voxel_gi_update_list.remove(voxel_gi);
  2958. voxel_gi = next;
  2959. }
  2960. }
  2961. void RendererSceneCull::render_particle_colliders() {
  2962. while (heightfield_particle_colliders_update_list.begin()) {
  2963. Instance *hfpc = *heightfield_particle_colliders_update_list.begin();
  2964. if (hfpc->scenario && hfpc->base_type == RS::INSTANCE_PARTICLES_COLLISION && RSG::particles_storage->particles_collision_is_heightfield(hfpc->base)) {
  2965. //update heightfield
  2966. instance_cull_result.clear();
  2967. scene_cull_result.geometry_instances.clear();
  2968. struct CullAABB {
  2969. PagedArray<Instance *> *result;
  2970. _FORCE_INLINE_ bool operator()(void *p_data) {
  2971. Instance *p_instance = (Instance *)p_data;
  2972. result->push_back(p_instance);
  2973. return false;
  2974. }
  2975. };
  2976. CullAABB cull_aabb;
  2977. cull_aabb.result = &instance_cull_result;
  2978. hfpc->scenario->indexers[Scenario::INDEXER_GEOMETRY].aabb_query(hfpc->transformed_aabb, cull_aabb);
  2979. hfpc->scenario->indexers[Scenario::INDEXER_VOLUMES].aabb_query(hfpc->transformed_aabb, cull_aabb);
  2980. for (int i = 0; i < (int)instance_cull_result.size(); i++) {
  2981. Instance *instance = instance_cull_result[i];
  2982. if (!instance || !((1 << instance->base_type) & (RS::INSTANCE_GEOMETRY_MASK & (~(1 << RS::INSTANCE_PARTICLES))))) { //all but particles to avoid self collision
  2983. continue;
  2984. }
  2985. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  2986. ERR_FAIL_NULL(geom->geometry_instance);
  2987. scene_cull_result.geometry_instances.push_back(geom->geometry_instance);
  2988. }
  2989. scene_render->render_particle_collider_heightfield(hfpc->base, hfpc->transform, scene_cull_result.geometry_instances);
  2990. }
  2991. heightfield_particle_colliders_update_list.remove(heightfield_particle_colliders_update_list.begin());
  2992. }
  2993. }
  2994. void RendererSceneCull::_update_instance_shader_uniforms_from_material(HashMap<StringName, Instance::InstanceShaderParameter> &isparams, const HashMap<StringName, Instance::InstanceShaderParameter> &existing_isparams, RID p_material) {
  2995. List<RendererMaterialStorage::InstanceShaderParam> plist;
  2996. RSG::material_storage->material_get_instance_shader_uniforms(p_material, &plist);
  2997. for (const RendererMaterialStorage::InstanceShaderParam &E : plist) {
  2998. StringName name = E.info.name;
  2999. if (isparams.has(name)) {
  3000. if (isparams[name].info.type != E.info.type) {
  3001. WARN_PRINT("More than one material in instance export the same instance shader uniform '" + E.info.name + "', but they do it with different data types. Only the first one (in order) will display correctly.");
  3002. }
  3003. if (isparams[name].index != E.index) {
  3004. WARN_PRINT("More than one material in instance export the same instance shader uniform '" + E.info.name + "', but they do it with different indices. Only the first one (in order) will display correctly.");
  3005. }
  3006. continue; //first one found always has priority
  3007. }
  3008. Instance::InstanceShaderParameter isp;
  3009. isp.index = E.index;
  3010. isp.info = E.info;
  3011. isp.default_value = E.default_value;
  3012. if (existing_isparams.has(name)) {
  3013. isp.value = existing_isparams[name].value;
  3014. } else {
  3015. isp.value = E.default_value;
  3016. }
  3017. isparams[name] = isp;
  3018. }
  3019. }
  3020. void RendererSceneCull::_update_dirty_instance(Instance *p_instance) {
  3021. if (p_instance->update_aabb) {
  3022. _update_instance_aabb(p_instance);
  3023. }
  3024. if (p_instance->update_dependencies) {
  3025. p_instance->dependency_tracker.update_begin();
  3026. if (p_instance->base.is_valid()) {
  3027. RSG::utilities->base_update_dependency(p_instance->base, &p_instance->dependency_tracker);
  3028. }
  3029. if (p_instance->material_override.is_valid()) {
  3030. RSG::material_storage->material_update_dependency(p_instance->material_override, &p_instance->dependency_tracker);
  3031. }
  3032. if (p_instance->material_overlay.is_valid()) {
  3033. RSG::material_storage->material_update_dependency(p_instance->material_overlay, &p_instance->dependency_tracker);
  3034. }
  3035. if (p_instance->base_type == RS::INSTANCE_MESH) {
  3036. //remove materials no longer used and un-own them
  3037. int new_mat_count = RSG::mesh_storage->mesh_get_surface_count(p_instance->base);
  3038. p_instance->materials.resize(new_mat_count);
  3039. _instance_update_mesh_instance(p_instance);
  3040. }
  3041. if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  3042. // update the process material dependency
  3043. RID particle_material = RSG::particles_storage->particles_get_process_material(p_instance->base);
  3044. if (particle_material.is_valid()) {
  3045. RSG::material_storage->material_update_dependency(particle_material, &p_instance->dependency_tracker);
  3046. }
  3047. }
  3048. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  3049. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  3050. bool can_cast_shadows = true;
  3051. bool is_animated = false;
  3052. HashMap<StringName, Instance::InstanceShaderParameter> isparams;
  3053. if (p_instance->cast_shadows == RS::SHADOW_CASTING_SETTING_OFF) {
  3054. can_cast_shadows = false;
  3055. }
  3056. if (p_instance->material_override.is_valid()) {
  3057. if (!RSG::material_storage->material_casts_shadows(p_instance->material_override)) {
  3058. can_cast_shadows = false;
  3059. }
  3060. is_animated = RSG::material_storage->material_is_animated(p_instance->material_override);
  3061. _update_instance_shader_uniforms_from_material(isparams, p_instance->instance_shader_uniforms, p_instance->material_override);
  3062. } else {
  3063. if (p_instance->base_type == RS::INSTANCE_MESH) {
  3064. RID mesh = p_instance->base;
  3065. if (mesh.is_valid()) {
  3066. bool cast_shadows = false;
  3067. for (int i = 0; i < p_instance->materials.size(); i++) {
  3068. RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : RSG::mesh_storage->mesh_surface_get_material(mesh, i);
  3069. if (!mat.is_valid()) {
  3070. cast_shadows = true;
  3071. } else {
  3072. if (RSG::material_storage->material_casts_shadows(mat)) {
  3073. cast_shadows = true;
  3074. }
  3075. if (RSG::material_storage->material_is_animated(mat)) {
  3076. is_animated = true;
  3077. }
  3078. _update_instance_shader_uniforms_from_material(isparams, p_instance->instance_shader_uniforms, mat);
  3079. RSG::material_storage->material_update_dependency(mat, &p_instance->dependency_tracker);
  3080. }
  3081. }
  3082. if (!cast_shadows) {
  3083. can_cast_shadows = false;
  3084. }
  3085. }
  3086. } else if (p_instance->base_type == RS::INSTANCE_MULTIMESH) {
  3087. RID mesh = RSG::mesh_storage->multimesh_get_mesh(p_instance->base);
  3088. if (mesh.is_valid()) {
  3089. bool cast_shadows = false;
  3090. int sc = RSG::mesh_storage->mesh_get_surface_count(mesh);
  3091. for (int i = 0; i < sc; i++) {
  3092. RID mat = RSG::mesh_storage->mesh_surface_get_material(mesh, i);
  3093. if (!mat.is_valid()) {
  3094. cast_shadows = true;
  3095. } else {
  3096. if (RSG::material_storage->material_casts_shadows(mat)) {
  3097. cast_shadows = true;
  3098. }
  3099. if (RSG::material_storage->material_is_animated(mat)) {
  3100. is_animated = true;
  3101. }
  3102. _update_instance_shader_uniforms_from_material(isparams, p_instance->instance_shader_uniforms, mat);
  3103. RSG::material_storage->material_update_dependency(mat, &p_instance->dependency_tracker);
  3104. }
  3105. }
  3106. if (!cast_shadows) {
  3107. can_cast_shadows = false;
  3108. }
  3109. RSG::utilities->base_update_dependency(mesh, &p_instance->dependency_tracker);
  3110. }
  3111. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  3112. bool cast_shadows = false;
  3113. int dp = RSG::particles_storage->particles_get_draw_passes(p_instance->base);
  3114. for (int i = 0; i < dp; i++) {
  3115. RID mesh = RSG::particles_storage->particles_get_draw_pass_mesh(p_instance->base, i);
  3116. if (!mesh.is_valid()) {
  3117. continue;
  3118. }
  3119. int sc = RSG::mesh_storage->mesh_get_surface_count(mesh);
  3120. for (int j = 0; j < sc; j++) {
  3121. RID mat = RSG::mesh_storage->mesh_surface_get_material(mesh, j);
  3122. if (!mat.is_valid()) {
  3123. cast_shadows = true;
  3124. } else {
  3125. if (RSG::material_storage->material_casts_shadows(mat)) {
  3126. cast_shadows = true;
  3127. }
  3128. if (RSG::material_storage->material_is_animated(mat)) {
  3129. is_animated = true;
  3130. }
  3131. _update_instance_shader_uniforms_from_material(isparams, p_instance->instance_shader_uniforms, mat);
  3132. RSG::material_storage->material_update_dependency(mat, &p_instance->dependency_tracker);
  3133. }
  3134. }
  3135. }
  3136. if (!cast_shadows) {
  3137. can_cast_shadows = false;
  3138. }
  3139. }
  3140. }
  3141. if (p_instance->material_overlay.is_valid()) {
  3142. can_cast_shadows = can_cast_shadows || RSG::material_storage->material_casts_shadows(p_instance->material_overlay);
  3143. is_animated = is_animated || RSG::material_storage->material_is_animated(p_instance->material_overlay);
  3144. _update_instance_shader_uniforms_from_material(isparams, p_instance->instance_shader_uniforms, p_instance->material_overlay);
  3145. }
  3146. if (can_cast_shadows != geom->can_cast_shadows) {
  3147. //ability to cast shadows change, let lights now
  3148. for (const Instance *E : geom->lights) {
  3149. InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
  3150. light->shadow_dirty = true;
  3151. }
  3152. geom->can_cast_shadows = can_cast_shadows;
  3153. }
  3154. geom->material_is_animated = is_animated;
  3155. p_instance->instance_shader_uniforms = isparams;
  3156. if (p_instance->instance_allocated_shader_uniforms != (p_instance->instance_shader_uniforms.size() > 0)) {
  3157. p_instance->instance_allocated_shader_uniforms = (p_instance->instance_shader_uniforms.size() > 0);
  3158. if (p_instance->instance_allocated_shader_uniforms) {
  3159. p_instance->instance_allocated_shader_uniforms_offset = RSG::material_storage->global_shader_uniforms_instance_allocate(p_instance->self);
  3160. ERR_FAIL_NULL(geom->geometry_instance);
  3161. geom->geometry_instance->set_instance_shader_uniforms_offset(p_instance->instance_allocated_shader_uniforms_offset);
  3162. for (const KeyValue<StringName, Instance::InstanceShaderParameter> &E : p_instance->instance_shader_uniforms) {
  3163. if (E.value.value.get_type() != Variant::NIL) {
  3164. RSG::material_storage->global_shader_uniforms_instance_update(p_instance->self, E.value.index, E.value.value);
  3165. }
  3166. }
  3167. } else {
  3168. RSG::material_storage->global_shader_uniforms_instance_free(p_instance->self);
  3169. p_instance->instance_allocated_shader_uniforms_offset = -1;
  3170. ERR_FAIL_NULL(geom->geometry_instance);
  3171. geom->geometry_instance->set_instance_shader_uniforms_offset(-1);
  3172. }
  3173. }
  3174. }
  3175. if (p_instance->skeleton.is_valid()) {
  3176. RSG::mesh_storage->skeleton_update_dependency(p_instance->skeleton, &p_instance->dependency_tracker);
  3177. }
  3178. p_instance->dependency_tracker.update_end();
  3179. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  3180. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  3181. ERR_FAIL_NULL(geom->geometry_instance);
  3182. geom->geometry_instance->set_surface_materials(p_instance->materials);
  3183. }
  3184. }
  3185. _instance_update_list.remove(&p_instance->update_item);
  3186. _update_instance(p_instance);
  3187. p_instance->update_aabb = false;
  3188. p_instance->update_dependencies = false;
  3189. }
  3190. void RendererSceneCull::update_dirty_instances() {
  3191. RSG::utilities->update_dirty_resources();
  3192. while (_instance_update_list.first()) {
  3193. _update_dirty_instance(_instance_update_list.first()->self());
  3194. }
  3195. }
  3196. void RendererSceneCull::update() {
  3197. //optimize bvhs
  3198. uint32_t rid_count = scenario_owner.get_rid_count();
  3199. RID *rids = (RID *)alloca(sizeof(RID) * rid_count);
  3200. scenario_owner.fill_owned_buffer(rids);
  3201. for (uint32_t i = 0; i < rid_count; i++) {
  3202. Scenario *s = scenario_owner.get_or_null(rids[i]);
  3203. s->indexers[Scenario::INDEXER_GEOMETRY].optimize_incremental(indexer_update_iterations);
  3204. s->indexers[Scenario::INDEXER_VOLUMES].optimize_incremental(indexer_update_iterations);
  3205. }
  3206. scene_render->update();
  3207. update_dirty_instances();
  3208. render_particle_colliders();
  3209. }
  3210. bool RendererSceneCull::free(RID p_rid) {
  3211. if (p_rid.is_null()) {
  3212. return true;
  3213. }
  3214. if (scene_render->free(p_rid)) {
  3215. return true;
  3216. }
  3217. if (camera_owner.owns(p_rid)) {
  3218. camera_owner.free(p_rid);
  3219. } else if (scenario_owner.owns(p_rid)) {
  3220. Scenario *scenario = scenario_owner.get_or_null(p_rid);
  3221. while (scenario->instances.first()) {
  3222. instance_set_scenario(scenario->instances.first()->self()->self, RID());
  3223. }
  3224. scenario->instance_aabbs.reset();
  3225. scenario->instance_data.reset();
  3226. scenario->instance_visibility.reset();
  3227. scene_render->free(scenario->reflection_probe_shadow_atlas);
  3228. scene_render->free(scenario->reflection_atlas);
  3229. scenario_owner.free(p_rid);
  3230. RendererSceneOcclusionCull::get_singleton()->remove_scenario(p_rid);
  3231. } else if (RendererSceneOcclusionCull::get_singleton()->is_occluder(p_rid)) {
  3232. RendererSceneOcclusionCull::get_singleton()->free_occluder(p_rid);
  3233. } else if (instance_owner.owns(p_rid)) {
  3234. // delete the instance
  3235. update_dirty_instances();
  3236. Instance *instance = instance_owner.get_or_null(p_rid);
  3237. instance_geometry_set_lightmap(p_rid, RID(), Rect2(), 0);
  3238. instance_set_scenario(p_rid, RID());
  3239. instance_set_base(p_rid, RID());
  3240. instance_geometry_set_material_override(p_rid, RID());
  3241. instance_geometry_set_material_overlay(p_rid, RID());
  3242. instance_attach_skeleton(p_rid, RID());
  3243. if (instance->instance_allocated_shader_uniforms) {
  3244. //free the used shader parameters
  3245. RSG::material_storage->global_shader_uniforms_instance_free(instance->self);
  3246. }
  3247. update_dirty_instances(); //in case something changed this
  3248. instance_owner.free(p_rid);
  3249. } else {
  3250. return false;
  3251. }
  3252. return true;
  3253. }
  3254. TypedArray<Image> RendererSceneCull::bake_render_uv2(RID p_base, const TypedArray<RID> &p_material_overrides, const Size2i &p_image_size) {
  3255. return scene_render->bake_render_uv2(p_base, p_material_overrides, p_image_size);
  3256. }
  3257. void RendererSceneCull::update_visibility_notifiers() {
  3258. SelfList<InstanceVisibilityNotifierData> *E = visible_notifier_list.first();
  3259. while (E) {
  3260. SelfList<InstanceVisibilityNotifierData> *N = E->next();
  3261. InstanceVisibilityNotifierData *visibility_notifier = E->self();
  3262. if (visibility_notifier->just_visible) {
  3263. visibility_notifier->just_visible = false;
  3264. RSG::utilities->visibility_notifier_call(visibility_notifier->base, true, RSG::threaded);
  3265. } else {
  3266. if (visibility_notifier->visible_in_frame != RSG::rasterizer->get_frame_number()) {
  3267. visible_notifier_list.remove(E);
  3268. RSG::utilities->visibility_notifier_call(visibility_notifier->base, false, RSG::threaded);
  3269. }
  3270. }
  3271. E = N;
  3272. }
  3273. }
  3274. /*******************************/
  3275. /* Passthrough to Scene Render */
  3276. /*******************************/
  3277. /* ENVIRONMENT API */
  3278. RendererSceneCull *RendererSceneCull::singleton = nullptr;
  3279. void RendererSceneCull::set_scene_render(RendererSceneRender *p_scene_render) {
  3280. scene_render = p_scene_render;
  3281. geometry_instance_pair_mask = scene_render->geometry_instance_get_pair_mask();
  3282. }
  3283. float get_halton_value(int index, int base) {
  3284. float f = 1;
  3285. float r = 0;
  3286. while (index > 0) {
  3287. f = f / static_cast<float>(base);
  3288. r = r + f * (index % base);
  3289. index = index / base;
  3290. }
  3291. return r * 2.0f - 1.0f;
  3292. };
  3293. RendererSceneCull::RendererSceneCull() {
  3294. render_pass = 1;
  3295. singleton = this;
  3296. instance_cull_result.set_page_pool(&instance_cull_page_pool);
  3297. instance_shadow_cull_result.set_page_pool(&instance_cull_page_pool);
  3298. for (uint32_t i = 0; i < MAX_UPDATE_SHADOWS; i++) {
  3299. render_shadow_data[i].instances.set_page_pool(&geometry_instance_cull_page_pool);
  3300. }
  3301. for (uint32_t i = 0; i < SDFGI_MAX_CASCADES * SDFGI_MAX_REGIONS_PER_CASCADE; i++) {
  3302. render_sdfgi_data[i].instances.set_page_pool(&geometry_instance_cull_page_pool);
  3303. }
  3304. scene_cull_result.init(&rid_cull_page_pool, &geometry_instance_cull_page_pool, &instance_cull_page_pool);
  3305. scene_cull_result_threads.resize(WorkerThreadPool::get_singleton()->get_thread_count());
  3306. for (uint32_t i = 0; i < scene_cull_result_threads.size(); i++) {
  3307. scene_cull_result_threads[i].init(&rid_cull_page_pool, &geometry_instance_cull_page_pool, &instance_cull_page_pool);
  3308. }
  3309. indexer_update_iterations = GLOBAL_GET("rendering/limits/spatial_indexer/update_iterations_per_frame");
  3310. thread_cull_threshold = GLOBAL_GET("rendering/limits/spatial_indexer/threaded_cull_minimum_instances");
  3311. thread_cull_threshold = MAX(thread_cull_threshold, (uint32_t)WorkerThreadPool::get_singleton()->get_thread_count()); //make sure there is at least one thread per CPU
  3312. taa_jitter_array.resize(TAA_JITTER_COUNT);
  3313. for (int i = 0; i < TAA_JITTER_COUNT; i++) {
  3314. taa_jitter_array[i].x = get_halton_value(i, 2);
  3315. taa_jitter_array[i].y = get_halton_value(i, 3);
  3316. }
  3317. dummy_occlusion_culling = memnew(RendererSceneOcclusionCull);
  3318. }
  3319. RendererSceneCull::~RendererSceneCull() {
  3320. instance_cull_result.reset();
  3321. instance_shadow_cull_result.reset();
  3322. for (uint32_t i = 0; i < MAX_UPDATE_SHADOWS; i++) {
  3323. render_shadow_data[i].instances.reset();
  3324. }
  3325. for (uint32_t i = 0; i < SDFGI_MAX_CASCADES * SDFGI_MAX_REGIONS_PER_CASCADE; i++) {
  3326. render_sdfgi_data[i].instances.reset();
  3327. }
  3328. scene_cull_result.reset();
  3329. for (uint32_t i = 0; i < scene_cull_result_threads.size(); i++) {
  3330. scene_cull_result_threads[i].reset();
  3331. }
  3332. scene_cull_result_threads.clear();
  3333. if (dummy_occlusion_culling) {
  3334. memdelete(dummy_occlusion_culling);
  3335. }
  3336. }