renderer_scene_cull.cpp 165 KB

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