renderer_scene_cull.cpp 133 KB

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