renderer_scene_cull.cpp 173 KB

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