renderer_scene_cull.cpp 160 KB

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