renderer_scene_cull.cpp 173 KB

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