renderer_scene_cull.cpp 157 KB

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