renderer_scene_cull.cpp 164 KB

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