renderer_scene_cull.cpp 166 KB

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