renderer_scene_cull.cpp 173 KB

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