renderer_scene_cull.cpp 150 KB

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