renderer_scene_cull.cpp 166 KB

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