renderer_scene_cull.cpp 155 KB

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