rendering_server_scene.cpp 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156
  1. /*************************************************************************/
  2. /* rendering_server_scene.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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 "rendering_server_scene.h"
  31. #include "core/os/os.h"
  32. #include "rendering_server_globals.h"
  33. #include "rendering_server_raster.h"
  34. #include <new>
  35. /* CAMERA API */
  36. RID RenderingServerScene::camera_create() {
  37. Camera *camera = memnew(Camera);
  38. return camera_owner.make_rid(camera);
  39. }
  40. void RenderingServerScene::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {
  41. Camera *camera = camera_owner.getornull(p_camera);
  42. ERR_FAIL_COND(!camera);
  43. camera->type = Camera::PERSPECTIVE;
  44. camera->fov = p_fovy_degrees;
  45. camera->znear = p_z_near;
  46. camera->zfar = p_z_far;
  47. }
  48. void RenderingServerScene::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
  49. Camera *camera = camera_owner.getornull(p_camera);
  50. ERR_FAIL_COND(!camera);
  51. camera->type = Camera::ORTHOGONAL;
  52. camera->size = p_size;
  53. camera->znear = p_z_near;
  54. camera->zfar = p_z_far;
  55. }
  56. void RenderingServerScene::camera_set_frustum(RID p_camera, float p_size, Vector2 p_offset, float p_z_near, float p_z_far) {
  57. Camera *camera = camera_owner.getornull(p_camera);
  58. ERR_FAIL_COND(!camera);
  59. camera->type = Camera::FRUSTUM;
  60. camera->size = p_size;
  61. camera->offset = p_offset;
  62. camera->znear = p_z_near;
  63. camera->zfar = p_z_far;
  64. }
  65. void RenderingServerScene::camera_set_transform(RID p_camera, const Transform &p_transform) {
  66. Camera *camera = camera_owner.getornull(p_camera);
  67. ERR_FAIL_COND(!camera);
  68. camera->transform = p_transform.orthonormalized();
  69. }
  70. void RenderingServerScene::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {
  71. Camera *camera = camera_owner.getornull(p_camera);
  72. ERR_FAIL_COND(!camera);
  73. camera->visible_layers = p_layers;
  74. }
  75. void RenderingServerScene::camera_set_environment(RID p_camera, RID p_env) {
  76. Camera *camera = camera_owner.getornull(p_camera);
  77. ERR_FAIL_COND(!camera);
  78. camera->env = p_env;
  79. }
  80. void RenderingServerScene::camera_set_camera_effects(RID p_camera, RID p_fx) {
  81. Camera *camera = camera_owner.getornull(p_camera);
  82. ERR_FAIL_COND(!camera);
  83. camera->effects = p_fx;
  84. }
  85. void RenderingServerScene::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {
  86. Camera *camera = camera_owner.getornull(p_camera);
  87. ERR_FAIL_COND(!camera);
  88. camera->vaspect = p_enable;
  89. }
  90. /* SCENARIO API */
  91. void *RenderingServerScene::_instance_pair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int) {
  92. //RenderingServerScene *self = (RenderingServerScene*)p_self;
  93. Instance *A = p_A;
  94. Instance *B = p_B;
  95. //instance indices are designed so greater always contains lesser
  96. if (A->base_type > B->base_type) {
  97. SWAP(A, B); //lesser always first
  98. }
  99. if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  100. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  101. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  102. InstanceLightData::PairInfo pinfo;
  103. pinfo.geometry = A;
  104. pinfo.L = geom->lighting.push_back(B);
  105. List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo);
  106. if (geom->can_cast_shadows) {
  107. light->shadow_dirty = true;
  108. }
  109. geom->lighting_dirty = true;
  110. return E; //this element should make freeing faster
  111. } else if (B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  112. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  113. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  114. InstanceReflectionProbeData::PairInfo pinfo;
  115. pinfo.geometry = A;
  116. pinfo.L = geom->reflection_probes.push_back(B);
  117. List<InstanceReflectionProbeData::PairInfo>::Element *E = reflection_probe->geometries.push_back(pinfo);
  118. geom->reflection_dirty = true;
  119. return E; //this element should make freeing faster
  120. } else if (B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  121. InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
  122. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  123. InstanceDecalData::PairInfo pinfo;
  124. pinfo.geometry = A;
  125. pinfo.L = geom->decals.push_back(B);
  126. List<InstanceDecalData::PairInfo>::Element *E = decal->geometries.push_back(pinfo);
  127. geom->decal_dirty = true;
  128. return E; //this element should make freeing faster
  129. } else if (B->base_type == RS::INSTANCE_LIGHTMAP_CAPTURE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  130. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(B->base_data);
  131. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  132. InstanceLightmapCaptureData::PairInfo pinfo;
  133. pinfo.geometry = A;
  134. pinfo.L = geom->lightmap_captures.push_back(B);
  135. List<InstanceLightmapCaptureData::PairInfo>::Element *E = lightmap_capture->geometries.push_back(pinfo);
  136. ((RenderingServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture
  137. return E; //this element should make freeing faster
  138. } else if (B->base_type == RS::INSTANCE_GI_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  139. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  140. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  141. InstanceGIProbeData::PairInfo pinfo;
  142. pinfo.geometry = A;
  143. pinfo.L = geom->gi_probes.push_back(B);
  144. List<InstanceGIProbeData::PairInfo>::Element *E;
  145. if (A->dynamic_gi) {
  146. E = gi_probe->dynamic_geometries.push_back(pinfo);
  147. } else {
  148. E = gi_probe->geometries.push_back(pinfo);
  149. }
  150. geom->gi_probes_dirty = true;
  151. return E; //this element should make freeing faster
  152. } else if (B->base_type == RS::INSTANCE_GI_PROBE && A->base_type == RS::INSTANCE_LIGHT) {
  153. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  154. return gi_probe->lights.insert(A);
  155. }
  156. return nullptr;
  157. }
  158. void RenderingServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int, void *udata) {
  159. //RenderingServerScene *self = (RenderingServerScene*)p_self;
  160. Instance *A = p_A;
  161. Instance *B = p_B;
  162. //instance indices are designed so greater always contains lesser
  163. if (A->base_type > B->base_type) {
  164. SWAP(A, B); //lesser always first
  165. }
  166. if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  167. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  168. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  169. List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element *>(udata);
  170. geom->lighting.erase(E->get().L);
  171. light->geometries.erase(E);
  172. if (geom->can_cast_shadows) {
  173. light->shadow_dirty = true;
  174. }
  175. geom->lighting_dirty = true;
  176. } else if (B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  177. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  178. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  179. List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element *>(udata);
  180. geom->reflection_probes.erase(E->get().L);
  181. reflection_probe->geometries.erase(E);
  182. geom->reflection_dirty = true;
  183. } else if (B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  184. InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
  185. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  186. List<InstanceDecalData::PairInfo>::Element *E = reinterpret_cast<List<InstanceDecalData::PairInfo>::Element *>(udata);
  187. geom->decals.erase(E->get().L);
  188. decal->geometries.erase(E);
  189. geom->decal_dirty = true;
  190. } else if (B->base_type == RS::INSTANCE_LIGHTMAP_CAPTURE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  191. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(B->base_data);
  192. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  193. List<InstanceLightmapCaptureData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightmapCaptureData::PairInfo>::Element *>(udata);
  194. geom->lightmap_captures.erase(E->get().L);
  195. lightmap_capture->geometries.erase(E);
  196. ((RenderingServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture
  197. } else if (B->base_type == RS::INSTANCE_GI_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  198. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  199. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  200. List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element *>(udata);
  201. geom->gi_probes.erase(E->get().L);
  202. if (A->dynamic_gi) {
  203. gi_probe->dynamic_geometries.erase(E);
  204. } else {
  205. gi_probe->geometries.erase(E);
  206. }
  207. geom->gi_probes_dirty = true;
  208. } else if (B->base_type == RS::INSTANCE_GI_PROBE && A->base_type == RS::INSTANCE_LIGHT) {
  209. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  210. Set<Instance *>::Element *E = reinterpret_cast<Set<Instance *>::Element *>(udata);
  211. gi_probe->lights.erase(E);
  212. }
  213. }
  214. RID RenderingServerScene::scenario_create() {
  215. Scenario *scenario = memnew(Scenario);
  216. ERR_FAIL_COND_V(!scenario, RID());
  217. RID scenario_rid = scenario_owner.make_rid(scenario);
  218. scenario->self = scenario_rid;
  219. scenario->octree.set_pair_callback(_instance_pair, this);
  220. scenario->octree.set_unpair_callback(_instance_unpair, this);
  221. scenario->reflection_probe_shadow_atlas = RSG::scene_render->shadow_atlas_create();
  222. RSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
  223. RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
  224. RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
  225. RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
  226. RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
  227. scenario->reflection_atlas = RSG::scene_render->reflection_atlas_create();
  228. return scenario_rid;
  229. }
  230. void RenderingServerScene::scenario_set_debug(RID p_scenario, RS::ScenarioDebugMode p_debug_mode) {
  231. Scenario *scenario = scenario_owner.getornull(p_scenario);
  232. ERR_FAIL_COND(!scenario);
  233. scenario->debug = p_debug_mode;
  234. }
  235. void RenderingServerScene::scenario_set_environment(RID p_scenario, RID p_environment) {
  236. Scenario *scenario = scenario_owner.getornull(p_scenario);
  237. ERR_FAIL_COND(!scenario);
  238. scenario->environment = p_environment;
  239. }
  240. void RenderingServerScene::scenario_set_camera_effects(RID p_scenario, RID p_camera_effects) {
  241. Scenario *scenario = scenario_owner.getornull(p_scenario);
  242. ERR_FAIL_COND(!scenario);
  243. scenario->camera_effects = p_camera_effects;
  244. }
  245. void RenderingServerScene::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {
  246. Scenario *scenario = scenario_owner.getornull(p_scenario);
  247. ERR_FAIL_COND(!scenario);
  248. scenario->fallback_environment = p_environment;
  249. }
  250. void RenderingServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_reflection_size, int p_reflection_count) {
  251. Scenario *scenario = scenario_owner.getornull(p_scenario);
  252. ERR_FAIL_COND(!scenario);
  253. RSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas, p_reflection_size, p_reflection_count);
  254. }
  255. /* INSTANCING API */
  256. void RenderingServerScene::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_dependencies) {
  257. if (p_update_aabb)
  258. p_instance->update_aabb = true;
  259. if (p_update_dependencies)
  260. p_instance->update_dependencies = true;
  261. if (p_instance->update_item.in_list())
  262. return;
  263. _instance_update_list.add(&p_instance->update_item);
  264. }
  265. RID RenderingServerScene::instance_create() {
  266. Instance *instance = memnew(Instance);
  267. ERR_FAIL_COND_V(!instance, RID());
  268. RID instance_rid = instance_owner.make_rid(instance);
  269. instance->self = instance_rid;
  270. return instance_rid;
  271. }
  272. void RenderingServerScene::instance_set_base(RID p_instance, RID p_base) {
  273. Instance *instance = instance_owner.getornull(p_instance);
  274. ERR_FAIL_COND(!instance);
  275. Scenario *scenario = instance->scenario;
  276. if (instance->base_type != RS::INSTANCE_NONE) {
  277. //free anything related to that base
  278. if (scenario && instance->octree_id) {
  279. scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
  280. instance->octree_id = 0;
  281. }
  282. switch (instance->base_type) {
  283. case RS::INSTANCE_LIGHT: {
  284. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  285. #ifdef DEBUG_ENABLED
  286. if (light->geometries.size()) {
  287. ERR_PRINT("BUG, indexing did not unpair geometries from light.");
  288. }
  289. #endif
  290. if (instance->scenario && light->D) {
  291. instance->scenario->directional_lights.erase(light->D);
  292. light->D = nullptr;
  293. }
  294. RSG::scene_render->free(light->instance);
  295. } break;
  296. case RS::INSTANCE_REFLECTION_PROBE: {
  297. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  298. RSG::scene_render->free(reflection_probe->instance);
  299. if (reflection_probe->update_list.in_list()) {
  300. reflection_probe_render_list.remove(&reflection_probe->update_list);
  301. }
  302. } break;
  303. case RS::INSTANCE_DECAL: {
  304. InstanceDecalData *decal = static_cast<InstanceDecalData *>(instance->base_data);
  305. RSG::scene_render->free(decal->instance);
  306. } break;
  307. case RS::INSTANCE_LIGHTMAP_CAPTURE: {
  308. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(instance->base_data);
  309. //erase dependencies, since no longer a lightmap
  310. while (lightmap_capture->users.front()) {
  311. instance_set_use_lightmap(lightmap_capture->users.front()->get()->self, RID(), RID());
  312. }
  313. } break;
  314. case RS::INSTANCE_GI_PROBE: {
  315. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  316. #ifdef DEBUG_ENABLED
  317. if (gi_probe->geometries.size()) {
  318. ERR_PRINT("BUG, indexing did not unpair geometries from GIProbe.");
  319. }
  320. #endif
  321. #ifdef DEBUG_ENABLED
  322. if (gi_probe->lights.size()) {
  323. ERR_PRINT("BUG, indexing did not unpair lights from GIProbe.");
  324. }
  325. #endif
  326. if (gi_probe->update_element.in_list()) {
  327. gi_probe_update_list.remove(&gi_probe->update_element);
  328. }
  329. if (instance->lightmap_capture) {
  330. Instance *capture = (Instance *)instance->lightmap_capture;
  331. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(capture->base_data);
  332. lightmap_capture->users.erase(instance);
  333. instance->lightmap_capture = nullptr;
  334. instance->lightmap = RID();
  335. }
  336. RSG::scene_render->free(gi_probe->probe_instance);
  337. } break;
  338. default: {
  339. }
  340. }
  341. if (instance->base_data) {
  342. memdelete(instance->base_data);
  343. instance->base_data = nullptr;
  344. }
  345. instance->blend_values.clear();
  346. instance->materials.clear();
  347. }
  348. instance->base_type = RS::INSTANCE_NONE;
  349. instance->base = RID();
  350. if (p_base.is_valid()) {
  351. instance->base_type = RSG::storage->get_base_type(p_base);
  352. ERR_FAIL_COND(instance->base_type == RS::INSTANCE_NONE);
  353. switch (instance->base_type) {
  354. case RS::INSTANCE_LIGHT: {
  355. InstanceLightData *light = memnew(InstanceLightData);
  356. if (scenario && RSG::storage->light_get_type(p_base) == RS::LIGHT_DIRECTIONAL) {
  357. light->D = scenario->directional_lights.push_back(instance);
  358. }
  359. light->instance = RSG::scene_render->light_instance_create(p_base);
  360. instance->base_data = light;
  361. } break;
  362. case RS::INSTANCE_MESH:
  363. case RS::INSTANCE_MULTIMESH:
  364. case RS::INSTANCE_IMMEDIATE:
  365. case RS::INSTANCE_PARTICLES: {
  366. InstanceGeometryData *geom = memnew(InstanceGeometryData);
  367. instance->base_data = geom;
  368. if (instance->base_type == RS::INSTANCE_MESH) {
  369. instance->blend_values.resize(RSG::storage->mesh_get_blend_shape_count(p_base));
  370. }
  371. } break;
  372. case RS::INSTANCE_REFLECTION_PROBE: {
  373. InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
  374. reflection_probe->owner = instance;
  375. instance->base_data = reflection_probe;
  376. reflection_probe->instance = RSG::scene_render->reflection_probe_instance_create(p_base);
  377. } break;
  378. case RS::INSTANCE_DECAL: {
  379. InstanceDecalData *decal = memnew(InstanceDecalData);
  380. decal->owner = instance;
  381. instance->base_data = decal;
  382. decal->instance = RSG::scene_render->decal_instance_create(p_base);
  383. } break;
  384. case RS::INSTANCE_LIGHTMAP_CAPTURE: {
  385. InstanceLightmapCaptureData *lightmap_capture = memnew(InstanceLightmapCaptureData);
  386. instance->base_data = lightmap_capture;
  387. //lightmap_capture->instance = RSG::scene_render->lightmap_capture_instance_create(p_base);
  388. } break;
  389. case RS::INSTANCE_GI_PROBE: {
  390. InstanceGIProbeData *gi_probe = memnew(InstanceGIProbeData);
  391. instance->base_data = gi_probe;
  392. gi_probe->owner = instance;
  393. if (scenario && !gi_probe->update_element.in_list()) {
  394. gi_probe_update_list.add(&gi_probe->update_element);
  395. }
  396. gi_probe->probe_instance = RSG::scene_render->gi_probe_instance_create(p_base);
  397. } break;
  398. default: {
  399. }
  400. }
  401. instance->base = p_base;
  402. //forcefully update the dependency now, so if for some reason it gets removed, we can immediately clear it
  403. RSG::storage->base_update_dependency(p_base, instance);
  404. }
  405. _instance_queue_update(instance, true, true);
  406. }
  407. void RenderingServerScene::instance_set_scenario(RID p_instance, RID p_scenario) {
  408. Instance *instance = instance_owner.getornull(p_instance);
  409. ERR_FAIL_COND(!instance);
  410. if (instance->scenario) {
  411. instance->scenario->instances.remove(&instance->scenario_item);
  412. if (instance->octree_id) {
  413. instance->scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
  414. instance->octree_id = 0;
  415. }
  416. switch (instance->base_type) {
  417. case RS::INSTANCE_LIGHT: {
  418. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  419. #ifdef DEBUG_ENABLED
  420. if (light->geometries.size()) {
  421. ERR_PRINT("BUG, indexing did not unpair geometries from light.");
  422. }
  423. #endif
  424. if (light->D) {
  425. instance->scenario->directional_lights.erase(light->D);
  426. light->D = nullptr;
  427. }
  428. } break;
  429. case RS::INSTANCE_REFLECTION_PROBE: {
  430. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  431. RSG::scene_render->reflection_probe_release_atlas_index(reflection_probe->instance);
  432. } break;
  433. case RS::INSTANCE_GI_PROBE: {
  434. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  435. #ifdef DEBUG_ENABLED
  436. if (gi_probe->geometries.size()) {
  437. ERR_PRINT("BUG, indexing did not unpair geometries from GIProbe.");
  438. }
  439. #endif
  440. #ifdef DEBUG_ENABLED
  441. if (gi_probe->lights.size()) {
  442. ERR_PRINT("BUG, indexing did not unpair lights from GIProbe.");
  443. }
  444. #endif
  445. if (gi_probe->update_element.in_list()) {
  446. gi_probe_update_list.remove(&gi_probe->update_element);
  447. }
  448. } break;
  449. default: {
  450. }
  451. }
  452. instance->scenario = nullptr;
  453. }
  454. if (p_scenario.is_valid()) {
  455. Scenario *scenario = scenario_owner.getornull(p_scenario);
  456. ERR_FAIL_COND(!scenario);
  457. instance->scenario = scenario;
  458. scenario->instances.add(&instance->scenario_item);
  459. switch (instance->base_type) {
  460. case RS::INSTANCE_LIGHT: {
  461. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  462. if (RSG::storage->light_get_type(instance->base) == RS::LIGHT_DIRECTIONAL) {
  463. light->D = scenario->directional_lights.push_back(instance);
  464. }
  465. } break;
  466. case RS::INSTANCE_GI_PROBE: {
  467. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  468. if (!gi_probe->update_element.in_list()) {
  469. gi_probe_update_list.add(&gi_probe->update_element);
  470. }
  471. } break;
  472. default: {
  473. }
  474. }
  475. _instance_queue_update(instance, true, true);
  476. }
  477. }
  478. void RenderingServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {
  479. Instance *instance = instance_owner.getornull(p_instance);
  480. ERR_FAIL_COND(!instance);
  481. instance->layer_mask = p_mask;
  482. }
  483. void RenderingServerScene::instance_set_transform(RID p_instance, const Transform &p_transform) {
  484. Instance *instance = instance_owner.getornull(p_instance);
  485. ERR_FAIL_COND(!instance);
  486. if (instance->transform == p_transform)
  487. return; //must be checked to avoid worst evil
  488. #ifdef DEBUG_ENABLED
  489. for (int i = 0; i < 4; i++) {
  490. const Vector3 &v = i < 3 ? p_transform.basis.elements[i] : p_transform.origin;
  491. ERR_FAIL_COND(Math::is_inf(v.x));
  492. ERR_FAIL_COND(Math::is_nan(v.x));
  493. ERR_FAIL_COND(Math::is_inf(v.y));
  494. ERR_FAIL_COND(Math::is_nan(v.y));
  495. ERR_FAIL_COND(Math::is_inf(v.z));
  496. ERR_FAIL_COND(Math::is_nan(v.z));
  497. }
  498. #endif
  499. instance->transform = p_transform;
  500. _instance_queue_update(instance, true);
  501. }
  502. void RenderingServerScene::instance_attach_object_instance_id(RID p_instance, ObjectID p_id) {
  503. Instance *instance = instance_owner.getornull(p_instance);
  504. ERR_FAIL_COND(!instance);
  505. instance->object_id = p_id;
  506. }
  507. void RenderingServerScene::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {
  508. Instance *instance = instance_owner.getornull(p_instance);
  509. ERR_FAIL_COND(!instance);
  510. if (instance->update_item.in_list()) {
  511. _update_dirty_instance(instance);
  512. }
  513. ERR_FAIL_INDEX(p_shape, instance->blend_values.size());
  514. instance->blend_values.write[p_shape] = p_weight;
  515. }
  516. void RenderingServerScene::instance_set_surface_material(RID p_instance, int p_surface, RID p_material) {
  517. Instance *instance = instance_owner.getornull(p_instance);
  518. ERR_FAIL_COND(!instance);
  519. if (instance->base_type == RS::INSTANCE_MESH) {
  520. //may not have been updated yet, may also have not been set yet. When updated will be correcte, worst case
  521. instance->materials.resize(MAX(p_surface + 1, RSG::storage->mesh_get_surface_count(instance->base)));
  522. }
  523. ERR_FAIL_INDEX(p_surface, instance->materials.size());
  524. instance->materials.write[p_surface] = p_material;
  525. _instance_queue_update(instance, false, true);
  526. }
  527. void RenderingServerScene::instance_set_visible(RID p_instance, bool p_visible) {
  528. Instance *instance = instance_owner.getornull(p_instance);
  529. ERR_FAIL_COND(!instance);
  530. if (instance->visible == p_visible)
  531. return;
  532. instance->visible = p_visible;
  533. switch (instance->base_type) {
  534. case RS::INSTANCE_LIGHT: {
  535. if (RSG::storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && instance->octree_id && instance->scenario) {
  536. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_LIGHT, p_visible ? RS::INSTANCE_GEOMETRY_MASK : 0);
  537. }
  538. } break;
  539. case RS::INSTANCE_REFLECTION_PROBE: {
  540. if (instance->octree_id && instance->scenario) {
  541. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_REFLECTION_PROBE, p_visible ? RS::INSTANCE_GEOMETRY_MASK : 0);
  542. }
  543. } break;
  544. case RS::INSTANCE_DECAL: {
  545. if (instance->octree_id && instance->scenario) {
  546. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_DECAL, p_visible ? RS::INSTANCE_GEOMETRY_MASK : 0);
  547. }
  548. } break;
  549. case RS::INSTANCE_LIGHTMAP_CAPTURE: {
  550. if (instance->octree_id && instance->scenario) {
  551. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_LIGHTMAP_CAPTURE, p_visible ? RS::INSTANCE_GEOMETRY_MASK : 0);
  552. }
  553. } break;
  554. case RS::INSTANCE_GI_PROBE: {
  555. if (instance->octree_id && instance->scenario) {
  556. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_GI_PROBE, p_visible ? (RS::INSTANCE_GEOMETRY_MASK | (1 << RS::INSTANCE_LIGHT)) : 0);
  557. }
  558. } break;
  559. default: {
  560. }
  561. }
  562. }
  563. inline bool is_geometry_instance(RenderingServer::InstanceType p_type) {
  564. return p_type == RS::INSTANCE_MESH || p_type == RS::INSTANCE_MULTIMESH || p_type == RS::INSTANCE_PARTICLES || p_type == RS::INSTANCE_IMMEDIATE;
  565. }
  566. void RenderingServerScene::instance_set_use_lightmap(RID p_instance, RID p_lightmap_instance, RID p_lightmap) {
  567. Instance *instance = instance_owner.getornull(p_instance);
  568. ERR_FAIL_COND(!instance);
  569. if (instance->lightmap_capture) {
  570. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(((Instance *)instance->lightmap_capture)->base_data);
  571. lightmap_capture->users.erase(instance);
  572. instance->lightmap = RID();
  573. instance->lightmap_capture = nullptr;
  574. }
  575. if (p_lightmap_instance.is_valid()) {
  576. Instance *lightmap_instance = instance_owner.getornull(p_lightmap_instance);
  577. ERR_FAIL_COND(!lightmap_instance);
  578. ERR_FAIL_COND(lightmap_instance->base_type != RS::INSTANCE_LIGHTMAP_CAPTURE);
  579. instance->lightmap_capture = lightmap_instance;
  580. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(((Instance *)instance->lightmap_capture)->base_data);
  581. lightmap_capture->users.insert(instance);
  582. instance->lightmap = p_lightmap;
  583. }
  584. }
  585. void RenderingServerScene::instance_set_custom_aabb(RID p_instance, AABB p_aabb) {
  586. Instance *instance = instance_owner.getornull(p_instance);
  587. ERR_FAIL_COND(!instance);
  588. ERR_FAIL_COND(!is_geometry_instance(instance->base_type));
  589. if (p_aabb != AABB()) {
  590. // Set custom AABB
  591. if (instance->custom_aabb == nullptr)
  592. instance->custom_aabb = memnew(AABB);
  593. *instance->custom_aabb = p_aabb;
  594. } else {
  595. // Clear custom AABB
  596. if (instance->custom_aabb != nullptr) {
  597. memdelete(instance->custom_aabb);
  598. instance->custom_aabb = nullptr;
  599. }
  600. }
  601. if (instance->scenario)
  602. _instance_queue_update(instance, true, false);
  603. }
  604. void RenderingServerScene::instance_attach_skeleton(RID p_instance, RID p_skeleton) {
  605. Instance *instance = instance_owner.getornull(p_instance);
  606. ERR_FAIL_COND(!instance);
  607. if (instance->skeleton == p_skeleton)
  608. return;
  609. instance->skeleton = p_skeleton;
  610. if (p_skeleton.is_valid()) {
  611. //update the dependency now, so if cleared, we remove it
  612. RSG::storage->skeleton_update_dependency(p_skeleton, instance);
  613. }
  614. _instance_queue_update(instance, true, true);
  615. }
  616. void RenderingServerScene::instance_set_exterior(RID p_instance, bool p_enabled) {
  617. }
  618. void RenderingServerScene::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
  619. Instance *instance = instance_owner.getornull(p_instance);
  620. ERR_FAIL_COND(!instance);
  621. instance->extra_margin = p_margin;
  622. _instance_queue_update(instance, true, false);
  623. }
  624. Vector<ObjectID> RenderingServerScene::instances_cull_aabb(const AABB &p_aabb, RID p_scenario) const {
  625. Vector<ObjectID> instances;
  626. Scenario *scenario = scenario_owner.getornull(p_scenario);
  627. ERR_FAIL_COND_V(!scenario, instances);
  628. const_cast<RenderingServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  629. int culled = 0;
  630. Instance *cull[1024];
  631. culled = scenario->octree.cull_aabb(p_aabb, cull, 1024);
  632. for (int i = 0; i < culled; i++) {
  633. Instance *instance = cull[i];
  634. ERR_CONTINUE(!instance);
  635. if (instance->object_id.is_null())
  636. continue;
  637. instances.push_back(instance->object_id);
  638. }
  639. return instances;
  640. }
  641. Vector<ObjectID> RenderingServerScene::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
  642. Vector<ObjectID> instances;
  643. Scenario *scenario = scenario_owner.getornull(p_scenario);
  644. ERR_FAIL_COND_V(!scenario, instances);
  645. const_cast<RenderingServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  646. int culled = 0;
  647. Instance *cull[1024];
  648. culled = scenario->octree.cull_segment(p_from, p_from + p_to * 10000, cull, 1024);
  649. for (int i = 0; i < culled; i++) {
  650. Instance *instance = cull[i];
  651. ERR_CONTINUE(!instance);
  652. if (instance->object_id.is_null())
  653. continue;
  654. instances.push_back(instance->object_id);
  655. }
  656. return instances;
  657. }
  658. Vector<ObjectID> RenderingServerScene::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {
  659. Vector<ObjectID> instances;
  660. Scenario *scenario = scenario_owner.getornull(p_scenario);
  661. ERR_FAIL_COND_V(!scenario, instances);
  662. const_cast<RenderingServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  663. int culled = 0;
  664. Instance *cull[1024];
  665. culled = scenario->octree.cull_convex(p_convex, cull, 1024);
  666. for (int i = 0; i < culled; i++) {
  667. Instance *instance = cull[i];
  668. ERR_CONTINUE(!instance);
  669. if (instance->object_id.is_null())
  670. continue;
  671. instances.push_back(instance->object_id);
  672. }
  673. return instances;
  674. }
  675. void RenderingServerScene::instance_geometry_set_flag(RID p_instance, RS::InstanceFlags p_flags, bool p_enabled) {
  676. Instance *instance = instance_owner.getornull(p_instance);
  677. ERR_FAIL_COND(!instance);
  678. //ERR_FAIL_COND(((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK));
  679. switch (p_flags) {
  680. case RS::INSTANCE_FLAG_USE_BAKED_LIGHT: {
  681. instance->baked_light = p_enabled;
  682. } break;
  683. case RS::INSTANCE_FLAG_USE_DYNAMIC_GI: {
  684. if (p_enabled == instance->dynamic_gi) {
  685. //bye, redundant
  686. return;
  687. }
  688. if (instance->octree_id != 0) {
  689. //remove from octree, it needs to be re-paired
  690. instance->scenario->octree.erase(instance->octree_id);
  691. instance->octree_id = 0;
  692. _instance_queue_update(instance, true, true);
  693. }
  694. //once out of octree, can be changed
  695. instance->dynamic_gi = p_enabled;
  696. } break;
  697. case RS::INSTANCE_FLAG_DRAW_NEXT_FRAME_IF_VISIBLE: {
  698. instance->redraw_if_visible = p_enabled;
  699. } break;
  700. default: {
  701. }
  702. }
  703. }
  704. void RenderingServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, RS::ShadowCastingSetting p_shadow_casting_setting) {
  705. Instance *instance = instance_owner.getornull(p_instance);
  706. ERR_FAIL_COND(!instance);
  707. instance->cast_shadows = p_shadow_casting_setting;
  708. _instance_queue_update(instance, false, true);
  709. }
  710. void RenderingServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material) {
  711. Instance *instance = instance_owner.getornull(p_instance);
  712. ERR_FAIL_COND(!instance);
  713. instance->material_override = p_material;
  714. _instance_queue_update(instance, false, true);
  715. }
  716. void RenderingServerScene::instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) {
  717. }
  718. void RenderingServerScene::instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) {
  719. }
  720. void RenderingServerScene::instance_geometry_set_shader_parameter(RID p_instance, const StringName &p_parameter, const Variant &p_value) {
  721. Instance *instance = instance_owner.getornull(p_instance);
  722. ERR_FAIL_COND(!instance);
  723. Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter>::Element *E = instance->instance_shader_parameters.find(p_parameter);
  724. if (!E) {
  725. RasterizerScene::InstanceBase::InstanceShaderParameter isp;
  726. isp.index = -1;
  727. isp.info = PropertyInfo();
  728. isp.value = p_value;
  729. instance->instance_shader_parameters[p_parameter] = isp;
  730. } else {
  731. E->get().value = p_value;
  732. if (E->get().index >= 0 && instance->instance_allocated_shader_parameters) {
  733. //update directly
  734. RSG::storage->global_variables_instance_update(p_instance, E->get().index, p_value);
  735. }
  736. }
  737. }
  738. Variant RenderingServerScene::instance_geometry_get_shader_parameter(RID p_instance, const StringName &p_parameter) const {
  739. const Instance *instance = const_cast<RenderingServerScene *>(this)->instance_owner.getornull(p_instance);
  740. ERR_FAIL_COND_V(!instance, Variant());
  741. if (instance->instance_shader_parameters.has(p_parameter)) {
  742. return instance->instance_shader_parameters[p_parameter].value;
  743. }
  744. return Variant();
  745. }
  746. Variant RenderingServerScene::instance_geometry_get_shader_parameter_default_value(RID p_instance, const StringName &p_parameter) const {
  747. const Instance *instance = const_cast<RenderingServerScene *>(this)->instance_owner.getornull(p_instance);
  748. ERR_FAIL_COND_V(!instance, Variant());
  749. if (instance->instance_shader_parameters.has(p_parameter)) {
  750. return instance->instance_shader_parameters[p_parameter].default_value;
  751. }
  752. return Variant();
  753. }
  754. void RenderingServerScene::instance_geometry_get_shader_parameter_list(RID p_instance, List<PropertyInfo> *p_parameters) const {
  755. const Instance *instance = const_cast<RenderingServerScene *>(this)->instance_owner.getornull(p_instance);
  756. ERR_FAIL_COND(!instance);
  757. const_cast<RenderingServerScene *>(this)->update_dirty_instances();
  758. Vector<StringName> names;
  759. for (Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter>::Element *E = instance->instance_shader_parameters.front(); E; E = E->next()) {
  760. names.push_back(E->key());
  761. }
  762. names.sort_custom<StringName::AlphCompare>();
  763. for (int i = 0; i < names.size(); i++) {
  764. PropertyInfo pinfo = instance->instance_shader_parameters[names[i]].info;
  765. p_parameters->push_back(pinfo);
  766. }
  767. }
  768. void RenderingServerScene::_update_instance(Instance *p_instance) {
  769. p_instance->version++;
  770. if (p_instance->base_type == RS::INSTANCE_LIGHT) {
  771. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  772. RSG::scene_render->light_instance_set_transform(light->instance, p_instance->transform);
  773. light->shadow_dirty = true;
  774. }
  775. if (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE) {
  776. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  777. RSG::scene_render->reflection_probe_instance_set_transform(reflection_probe->instance, p_instance->transform);
  778. reflection_probe->reflection_dirty = true;
  779. }
  780. if (p_instance->base_type == RS::INSTANCE_DECAL) {
  781. InstanceDecalData *decal = static_cast<InstanceDecalData *>(p_instance->base_data);
  782. RSG::scene_render->decal_instance_set_transform(decal->instance, p_instance->transform);
  783. }
  784. if (p_instance->base_type == RS::INSTANCE_GI_PROBE) {
  785. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(p_instance->base_data);
  786. RSG::scene_render->gi_probe_instance_set_transform_to_data(gi_probe->probe_instance, p_instance->transform);
  787. }
  788. if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  789. RSG::storage->particles_set_emission_transform(p_instance->base, p_instance->transform);
  790. }
  791. if (p_instance->aabb.has_no_surface()) {
  792. return;
  793. }
  794. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  795. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  796. //make sure lights are updated if it casts shadow
  797. if (geom->can_cast_shadows) {
  798. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  799. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  800. light->shadow_dirty = true;
  801. }
  802. }
  803. if (!p_instance->lightmap_capture && geom->lightmap_captures.size()) {
  804. //affected by lightmap captures, must update capture info!
  805. _update_instance_lightmap_captures(p_instance);
  806. } else {
  807. if (!p_instance->lightmap_capture_data.empty()) {
  808. p_instance->lightmap_capture_data.resize(0); //not in use, clear capture data
  809. }
  810. }
  811. }
  812. p_instance->mirror = p_instance->transform.basis.determinant() < 0.0;
  813. AABB new_aabb;
  814. new_aabb = p_instance->transform.xform(p_instance->aabb);
  815. p_instance->transformed_aabb = new_aabb;
  816. if (!p_instance->scenario) {
  817. return;
  818. }
  819. if (p_instance->octree_id == 0) {
  820. uint32_t base_type = 1 << p_instance->base_type;
  821. uint32_t pairable_mask = 0;
  822. bool pairable = false;
  823. if (p_instance->base_type == RS::INSTANCE_LIGHT || p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE || p_instance->base_type == RS::INSTANCE_DECAL || p_instance->base_type == RS::INSTANCE_LIGHTMAP_CAPTURE) {
  824. pairable_mask = p_instance->visible ? RS::INSTANCE_GEOMETRY_MASK : 0;
  825. pairable = true;
  826. }
  827. if (p_instance->base_type == RS::INSTANCE_GI_PROBE) {
  828. //lights and geometries
  829. pairable_mask = p_instance->visible ? RS::INSTANCE_GEOMETRY_MASK | (1 << RS::INSTANCE_LIGHT) : 0;
  830. pairable = true;
  831. }
  832. // not inside octree
  833. p_instance->octree_id = p_instance->scenario->octree.create(p_instance, new_aabb, 0, pairable, base_type, pairable_mask);
  834. } else {
  835. /*
  836. if (new_aabb==p_instance->data.transformed_aabb)
  837. return;
  838. */
  839. p_instance->scenario->octree.move(p_instance->octree_id, new_aabb);
  840. }
  841. }
  842. void RenderingServerScene::_update_instance_aabb(Instance *p_instance) {
  843. AABB new_aabb;
  844. ERR_FAIL_COND(p_instance->base_type != RS::INSTANCE_NONE && !p_instance->base.is_valid());
  845. switch (p_instance->base_type) {
  846. case RenderingServer::INSTANCE_NONE: {
  847. // do nothing
  848. } break;
  849. case RenderingServer::INSTANCE_MESH: {
  850. if (p_instance->custom_aabb)
  851. new_aabb = *p_instance->custom_aabb;
  852. else
  853. new_aabb = RSG::storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);
  854. } break;
  855. case RenderingServer::INSTANCE_MULTIMESH: {
  856. if (p_instance->custom_aabb)
  857. new_aabb = *p_instance->custom_aabb;
  858. else
  859. new_aabb = RSG::storage->multimesh_get_aabb(p_instance->base);
  860. } break;
  861. case RenderingServer::INSTANCE_IMMEDIATE: {
  862. if (p_instance->custom_aabb)
  863. new_aabb = *p_instance->custom_aabb;
  864. else
  865. new_aabb = RSG::storage->immediate_get_aabb(p_instance->base);
  866. } break;
  867. case RenderingServer::INSTANCE_PARTICLES: {
  868. if (p_instance->custom_aabb)
  869. new_aabb = *p_instance->custom_aabb;
  870. else
  871. new_aabb = RSG::storage->particles_get_aabb(p_instance->base);
  872. } break;
  873. case RenderingServer::INSTANCE_LIGHT: {
  874. new_aabb = RSG::storage->light_get_aabb(p_instance->base);
  875. } break;
  876. case RenderingServer::INSTANCE_REFLECTION_PROBE: {
  877. new_aabb = RSG::storage->reflection_probe_get_aabb(p_instance->base);
  878. } break;
  879. case RenderingServer::INSTANCE_DECAL: {
  880. new_aabb = RSG::storage->decal_get_aabb(p_instance->base);
  881. } break;
  882. case RenderingServer::INSTANCE_GI_PROBE: {
  883. new_aabb = RSG::storage->gi_probe_get_bounds(p_instance->base);
  884. } break;
  885. case RenderingServer::INSTANCE_LIGHTMAP_CAPTURE: {
  886. new_aabb = RSG::storage->lightmap_capture_get_bounds(p_instance->base);
  887. } break;
  888. default: {
  889. }
  890. }
  891. // <Zylann> This is why I didn't re-use Instance::aabb to implement custom AABBs
  892. if (p_instance->extra_margin)
  893. new_aabb.grow_by(p_instance->extra_margin);
  894. p_instance->aabb = new_aabb;
  895. }
  896. _FORCE_INLINE_ static void _light_capture_sample_octree(const RasterizerStorage::LightmapCaptureOctree *p_octree, int p_cell_subdiv, const Vector3 &p_pos, const Vector3 &p_dir, float p_level, Vector3 &r_color, float &r_alpha) {
  897. static const Vector3 aniso_normal[6] = {
  898. Vector3(-1, 0, 0),
  899. Vector3(1, 0, 0),
  900. Vector3(0, -1, 0),
  901. Vector3(0, 1, 0),
  902. Vector3(0, 0, -1),
  903. Vector3(0, 0, 1)
  904. };
  905. int size = 1 << (p_cell_subdiv - 1);
  906. int clamp_v = size - 1;
  907. //first of all, clamp
  908. Vector3 pos;
  909. pos.x = CLAMP(p_pos.x, 0, clamp_v);
  910. pos.y = CLAMP(p_pos.y, 0, clamp_v);
  911. pos.z = CLAMP(p_pos.z, 0, clamp_v);
  912. float level = (p_cell_subdiv - 1) - p_level;
  913. int target_level;
  914. float level_filter;
  915. if (level <= 0.0) {
  916. level_filter = 0;
  917. target_level = 0;
  918. } else {
  919. target_level = Math::ceil(level);
  920. level_filter = target_level - level;
  921. }
  922. Vector3 color[2][8];
  923. float alpha[2][8];
  924. zeromem(alpha, sizeof(float) * 2 * 8);
  925. //find cell at given level first
  926. for (int c = 0; c < 2; c++) {
  927. int current_level = MAX(0, target_level - c);
  928. int level_cell_size = (1 << (p_cell_subdiv - 1)) >> current_level;
  929. for (int n = 0; n < 8; n++) {
  930. int x = int(pos.x);
  931. int y = int(pos.y);
  932. int z = int(pos.z);
  933. if (n & 1)
  934. x += level_cell_size;
  935. if (n & 2)
  936. y += level_cell_size;
  937. if (n & 4)
  938. z += level_cell_size;
  939. int ofs_x = 0;
  940. int ofs_y = 0;
  941. int ofs_z = 0;
  942. x = CLAMP(x, 0, clamp_v);
  943. y = CLAMP(y, 0, clamp_v);
  944. z = CLAMP(z, 0, clamp_v);
  945. int half = size / 2;
  946. uint32_t cell = 0;
  947. for (int i = 0; i < current_level; i++) {
  948. const RasterizerStorage::LightmapCaptureOctree *bc = &p_octree[cell];
  949. int child = 0;
  950. if (x >= ofs_x + half) {
  951. child |= 1;
  952. ofs_x += half;
  953. }
  954. if (y >= ofs_y + half) {
  955. child |= 2;
  956. ofs_y += half;
  957. }
  958. if (z >= ofs_z + half) {
  959. child |= 4;
  960. ofs_z += half;
  961. }
  962. cell = bc->children[child];
  963. if (cell == RasterizerStorage::LightmapCaptureOctree::CHILD_EMPTY)
  964. break;
  965. half >>= 1;
  966. }
  967. if (cell == RasterizerStorage::LightmapCaptureOctree::CHILD_EMPTY) {
  968. alpha[c][n] = 0;
  969. } else {
  970. alpha[c][n] = p_octree[cell].alpha;
  971. for (int i = 0; i < 6; i++) {
  972. //anisotropic read light
  973. float amount = p_dir.dot(aniso_normal[i]);
  974. if (amount < 0)
  975. amount = 0;
  976. color[c][n].x += p_octree[cell].light[i][0] / 1024.0 * amount;
  977. color[c][n].y += p_octree[cell].light[i][1] / 1024.0 * amount;
  978. color[c][n].z += p_octree[cell].light[i][2] / 1024.0 * amount;
  979. }
  980. }
  981. //print_line("\tlev " + itos(c) + " - " + itos(n) + " alpha: " + rtos(cells[test_cell].alpha) + " col: " + color[c][n]);
  982. }
  983. }
  984. float target_level_size = size >> target_level;
  985. Vector3 pos_fract[2];
  986. pos_fract[0].x = Math::fmod(pos.x, target_level_size) / target_level_size;
  987. pos_fract[0].y = Math::fmod(pos.y, target_level_size) / target_level_size;
  988. pos_fract[0].z = Math::fmod(pos.z, target_level_size) / target_level_size;
  989. target_level_size = size >> MAX(0, target_level - 1);
  990. pos_fract[1].x = Math::fmod(pos.x, target_level_size) / target_level_size;
  991. pos_fract[1].y = Math::fmod(pos.y, target_level_size) / target_level_size;
  992. pos_fract[1].z = Math::fmod(pos.z, target_level_size) / target_level_size;
  993. float alpha_interp[2];
  994. Vector3 color_interp[2];
  995. for (int i = 0; i < 2; i++) {
  996. Vector3 color_x00 = color[i][0].lerp(color[i][1], pos_fract[i].x);
  997. Vector3 color_xy0 = color[i][2].lerp(color[i][3], pos_fract[i].x);
  998. Vector3 blend_z0 = color_x00.lerp(color_xy0, pos_fract[i].y);
  999. Vector3 color_x0z = color[i][4].lerp(color[i][5], pos_fract[i].x);
  1000. Vector3 color_xyz = color[i][6].lerp(color[i][7], pos_fract[i].x);
  1001. Vector3 blend_z1 = color_x0z.lerp(color_xyz, pos_fract[i].y);
  1002. color_interp[i] = blend_z0.lerp(blend_z1, pos_fract[i].z);
  1003. float alpha_x00 = Math::lerp(alpha[i][0], alpha[i][1], pos_fract[i].x);
  1004. float alpha_xy0 = Math::lerp(alpha[i][2], alpha[i][3], pos_fract[i].x);
  1005. float alpha_z0 = Math::lerp(alpha_x00, alpha_xy0, pos_fract[i].y);
  1006. float alpha_x0z = Math::lerp(alpha[i][4], alpha[i][5], pos_fract[i].x);
  1007. float alpha_xyz = Math::lerp(alpha[i][6], alpha[i][7], pos_fract[i].x);
  1008. float alpha_z1 = Math::lerp(alpha_x0z, alpha_xyz, pos_fract[i].y);
  1009. alpha_interp[i] = Math::lerp(alpha_z0, alpha_z1, pos_fract[i].z);
  1010. }
  1011. r_color = color_interp[0].lerp(color_interp[1], level_filter);
  1012. r_alpha = Math::lerp(alpha_interp[0], alpha_interp[1], level_filter);
  1013. //print_line("pos: " + p_posf + " level " + rtos(p_level) + " down to " + itos(target_level) + "." + rtos(level_filter) + " color " + r_color + " alpha " + rtos(r_alpha));
  1014. }
  1015. _FORCE_INLINE_ static Color _light_capture_voxel_cone_trace(const RasterizerStorage::LightmapCaptureOctree *p_octree, const Vector3 &p_pos, const Vector3 &p_dir, float p_aperture, int p_cell_subdiv) {
  1016. float bias = 0.0; //no need for bias here
  1017. float max_distance = (Vector3(1, 1, 1) * (1 << (p_cell_subdiv - 1))).length();
  1018. float dist = bias;
  1019. float alpha = 0.0;
  1020. Vector3 color;
  1021. Vector3 scolor;
  1022. float salpha;
  1023. while (dist < max_distance && alpha < 0.95) {
  1024. float diameter = MAX(1.0, 2.0 * p_aperture * dist);
  1025. _light_capture_sample_octree(p_octree, p_cell_subdiv, p_pos + dist * p_dir, p_dir, log2(diameter), scolor, salpha);
  1026. float a = (1.0 - alpha);
  1027. color += scolor * a;
  1028. alpha += a * salpha;
  1029. dist += diameter * 0.5;
  1030. }
  1031. return Color(color.x, color.y, color.z, alpha);
  1032. }
  1033. void RenderingServerScene::_update_instance_lightmap_captures(Instance *p_instance) {
  1034. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1035. static const Vector3 cone_traces[12] = {
  1036. Vector3(0, 0, 1),
  1037. Vector3(0.866025, 0, 0.5),
  1038. Vector3(0.267617, 0.823639, 0.5),
  1039. Vector3(-0.700629, 0.509037, 0.5),
  1040. Vector3(-0.700629, -0.509037, 0.5),
  1041. Vector3(0.267617, -0.823639, 0.5),
  1042. Vector3(0, 0, -1),
  1043. Vector3(0.866025, 0, -0.5),
  1044. Vector3(0.267617, 0.823639, -0.5),
  1045. Vector3(-0.700629, 0.509037, -0.5),
  1046. Vector3(-0.700629, -0.509037, -0.5),
  1047. Vector3(0.267617, -0.823639, -0.5)
  1048. };
  1049. float cone_aperture = 0.577; // tan(angle) 60 degrees
  1050. if (p_instance->lightmap_capture_data.empty()) {
  1051. p_instance->lightmap_capture_data.resize(12);
  1052. }
  1053. //print_line("update captures for pos: " + p_instance->transform.origin);
  1054. for (int i = 0; i < 12; i++)
  1055. new (&p_instance->lightmap_capture_data.ptrw()[i]) Color;
  1056. //this could use some sort of blending..
  1057. for (List<Instance *>::Element *E = geom->lightmap_captures.front(); E; E = E->next()) {
  1058. const Vector<RasterizerStorage::LightmapCaptureOctree> *octree = RSG::storage->lightmap_capture_get_octree_ptr(E->get()->base);
  1059. //print_line("octree size: " + itos(octree->size()));
  1060. if (octree->size() == 0)
  1061. continue;
  1062. Transform to_cell_xform = RSG::storage->lightmap_capture_get_octree_cell_transform(E->get()->base);
  1063. int cell_subdiv = RSG::storage->lightmap_capture_get_octree_cell_subdiv(E->get()->base);
  1064. to_cell_xform = to_cell_xform * E->get()->transform.affine_inverse();
  1065. const RasterizerStorage::LightmapCaptureOctree *octree_r = octree->ptr();
  1066. Vector3 pos = to_cell_xform.xform(p_instance->transform.origin);
  1067. for (int i = 0; i < 12; i++) {
  1068. Vector3 dir = to_cell_xform.basis.xform(cone_traces[i]).normalized();
  1069. Color capture = _light_capture_voxel_cone_trace(octree_r, pos, dir, cone_aperture, cell_subdiv);
  1070. p_instance->lightmap_capture_data.write[i] += capture;
  1071. }
  1072. }
  1073. }
  1074. bool RenderingServerScene::_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) {
  1075. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1076. Transform light_transform = p_instance->transform;
  1077. light_transform.orthonormalize(); //scale does not count on lights
  1078. bool animated_material_found = false;
  1079. switch (RSG::storage->light_get_type(p_instance->base)) {
  1080. case RS::LIGHT_DIRECTIONAL: {
  1081. real_t max_distance = p_cam_projection.get_z_far();
  1082. real_t shadow_max = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
  1083. if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera
  1084. max_distance = MIN(shadow_max, max_distance);
  1085. }
  1086. max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
  1087. real_t min_distance = MIN(p_cam_projection.get_z_near(), max_distance);
  1088. RS::LightDirectionalShadowDepthRangeMode depth_range_mode = RSG::storage->light_directional_get_shadow_depth_range_mode(p_instance->base);
  1089. real_t pancake_size = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE);
  1090. if (depth_range_mode == RS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_OPTIMIZED) {
  1091. //optimize min/max
  1092. Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
  1093. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
  1094. Plane base(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2));
  1095. //check distance max and min
  1096. bool found_items = false;
  1097. real_t z_max = -1e20;
  1098. real_t z_min = 1e20;
  1099. for (int i = 0; i < cull_count; i++) {
  1100. Instance *instance = instance_shadow_cull_result[i];
  1101. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1102. continue;
  1103. }
  1104. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1105. animated_material_found = true;
  1106. }
  1107. real_t max, min;
  1108. instance->transformed_aabb.project_range_in_plane(base, min, max);
  1109. if (max > z_max) {
  1110. z_max = max;
  1111. }
  1112. if (min < z_min) {
  1113. z_min = min;
  1114. }
  1115. found_items = true;
  1116. }
  1117. if (found_items) {
  1118. min_distance = MAX(min_distance, z_min);
  1119. max_distance = MIN(max_distance, z_max);
  1120. }
  1121. }
  1122. real_t range = max_distance - min_distance;
  1123. int splits = 0;
  1124. switch (RSG::storage->light_directional_get_shadow_mode(p_instance->base)) {
  1125. case RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
  1126. splits = 1;
  1127. break;
  1128. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
  1129. splits = 2;
  1130. break;
  1131. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
  1132. splits = 4;
  1133. break;
  1134. }
  1135. real_t distances[5];
  1136. distances[0] = min_distance;
  1137. for (int i = 0; i < splits; i++) {
  1138. distances[i + 1] = min_distance + RSG::storage->light_get_param(p_instance->base, RS::LightParam(RS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
  1139. };
  1140. distances[splits] = max_distance;
  1141. real_t texture_size = RSG::scene_render->get_directional_light_shadow_size(light->instance);
  1142. bool overlap = RSG::storage->light_directional_get_blend_splits(p_instance->base);
  1143. real_t first_radius = 0.0;
  1144. real_t min_distance_bias_scale = pancake_size > 0 ? distances[1] / 10.0 : 0;
  1145. for (int i = 0; i < splits; i++) {
  1146. RENDER_TIMESTAMP("Culling Directional Light split" + itos(i));
  1147. // setup a camera matrix for that range!
  1148. CameraMatrix camera_matrix;
  1149. real_t aspect = p_cam_projection.get_aspect();
  1150. if (p_cam_orthogonal) {
  1151. Vector2 vp_he = p_cam_projection.get_viewport_half_extents();
  1152. camera_matrix.set_orthogonal(vp_he.y * 2.0, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  1153. } else {
  1154. real_t fov = p_cam_projection.get_fov(); //this is actually yfov, because set aspect tries to keep it
  1155. camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
  1156. }
  1157. //obtain the frustum endpoints
  1158. Vector3 endpoints[8]; // frustum plane endpoints
  1159. bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
  1160. ERR_CONTINUE(!res);
  1161. // obtain the light frustm ranges (given endpoints)
  1162. Transform transform = light_transform; //discard scale and stabilize light
  1163. Vector3 x_vec = transform.basis.get_axis(Vector3::AXIS_X).normalized();
  1164. Vector3 y_vec = transform.basis.get_axis(Vector3::AXIS_Y).normalized();
  1165. Vector3 z_vec = transform.basis.get_axis(Vector3::AXIS_Z).normalized();
  1166. //z_vec points agsint the camera, like in default opengl
  1167. real_t x_min = 0.f, x_max = 0.f;
  1168. real_t y_min = 0.f, y_max = 0.f;
  1169. real_t z_min = 0.f, z_max = 0.f;
  1170. // FIXME: z_max_cam is defined, computed, but not used below when setting up
  1171. // ortho_camera. Commented out for now to fix warnings but should be investigated.
  1172. real_t x_min_cam = 0.f, x_max_cam = 0.f;
  1173. real_t y_min_cam = 0.f, y_max_cam = 0.f;
  1174. real_t z_min_cam = 0.f;
  1175. //real_t z_max_cam = 0.f;
  1176. real_t bias_scale = 1.0;
  1177. real_t aspect_bias_scale = 1.0;
  1178. //used for culling
  1179. for (int j = 0; j < 8; j++) {
  1180. real_t d_x = x_vec.dot(endpoints[j]);
  1181. real_t d_y = y_vec.dot(endpoints[j]);
  1182. real_t d_z = z_vec.dot(endpoints[j]);
  1183. if (j == 0 || d_x < x_min)
  1184. x_min = d_x;
  1185. if (j == 0 || d_x > x_max)
  1186. x_max = d_x;
  1187. if (j == 0 || d_y < y_min)
  1188. y_min = d_y;
  1189. if (j == 0 || d_y > y_max)
  1190. y_max = d_y;
  1191. if (j == 0 || d_z < z_min)
  1192. z_min = d_z;
  1193. if (j == 0 || d_z > z_max)
  1194. z_max = d_z;
  1195. }
  1196. real_t radius = 0;
  1197. real_t soft_shadow_expand = 0;
  1198. Vector3 center;
  1199. {
  1200. //camera viewport stuff
  1201. for (int j = 0; j < 8; j++) {
  1202. center += endpoints[j];
  1203. }
  1204. center /= 8.0;
  1205. //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;
  1206. for (int j = 0; j < 8; j++) {
  1207. real_t d = center.distance_to(endpoints[j]);
  1208. if (d > radius)
  1209. radius = d;
  1210. }
  1211. radius *= texture_size / (texture_size - 2.0); //add a texel by each side
  1212. if (i == 0) {
  1213. first_radius = radius;
  1214. } else {
  1215. bias_scale = radius / first_radius;
  1216. }
  1217. z_min_cam = z_vec.dot(center) - radius;
  1218. {
  1219. float soft_shadow_angle = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SIZE);
  1220. if (soft_shadow_angle > 0.0 && pancake_size > 0.0) {
  1221. float z_range = (z_vec.dot(center) + radius + pancake_size) - z_min_cam;
  1222. soft_shadow_expand = Math::tan(Math::deg2rad(soft_shadow_angle)) * z_range;
  1223. x_max += soft_shadow_expand;
  1224. y_max += soft_shadow_expand;
  1225. x_min -= soft_shadow_expand;
  1226. y_min -= soft_shadow_expand;
  1227. }
  1228. }
  1229. x_max_cam = x_vec.dot(center) + radius + soft_shadow_expand;
  1230. x_min_cam = x_vec.dot(center) - radius - soft_shadow_expand;
  1231. y_max_cam = y_vec.dot(center) + radius + soft_shadow_expand;
  1232. y_min_cam = y_vec.dot(center) - radius - soft_shadow_expand;
  1233. if (depth_range_mode == RS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_STABLE) {
  1234. //this trick here is what stabilizes the shadow (make potential jaggies to not move)
  1235. //at the cost of some wasted resolution. Still the quality increase is very well worth it
  1236. real_t unit = radius * 2.0 / texture_size;
  1237. x_max_cam = Math::stepify(x_max_cam, unit);
  1238. x_min_cam = Math::stepify(x_min_cam, unit);
  1239. y_max_cam = Math::stepify(y_max_cam, unit);
  1240. y_min_cam = Math::stepify(y_min_cam, unit);
  1241. }
  1242. }
  1243. //now that we now all ranges, we can proceed to make the light frustum planes, for culling octree
  1244. Vector<Plane> light_frustum_planes;
  1245. light_frustum_planes.resize(6);
  1246. //right/left
  1247. light_frustum_planes.write[0] = Plane(x_vec, x_max);
  1248. light_frustum_planes.write[1] = Plane(-x_vec, -x_min);
  1249. //top/bottom
  1250. light_frustum_planes.write[2] = Plane(y_vec, y_max);
  1251. light_frustum_planes.write[3] = Plane(-y_vec, -y_min);
  1252. //near/far
  1253. light_frustum_planes.write[4] = Plane(z_vec, z_max + 1e6);
  1254. light_frustum_planes.write[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed
  1255. int cull_count = p_scenario->octree.cull_convex(light_frustum_planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
  1256. // a pre pass will need to be needed to determine the actual z-near to be used
  1257. Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2));
  1258. real_t cull_max = 0;
  1259. for (int j = 0; j < cull_count; j++) {
  1260. real_t min, max;
  1261. Instance *instance = instance_shadow_cull_result[j];
  1262. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1263. cull_count--;
  1264. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1265. j--;
  1266. continue;
  1267. }
  1268. instance->transformed_aabb.project_range_in_plane(Plane(z_vec, 0), min, max);
  1269. instance->depth = near_plane.distance_to(instance->transform.origin);
  1270. instance->depth_layer = 0;
  1271. if (j == 0 || max > cull_max) {
  1272. cull_max = max;
  1273. }
  1274. }
  1275. if (cull_max > z_max) {
  1276. z_max = cull_max;
  1277. }
  1278. if (pancake_size > 0) {
  1279. z_max = z_vec.dot(center) + radius + pancake_size;
  1280. }
  1281. if (aspect != 1.0) {
  1282. // if the aspect is different, then the radius will become larger.
  1283. // if this happens, then bias needs to be adjusted too, as depth will increase
  1284. // to do this, compare the depth of one that would have resulted from a square frustum
  1285. CameraMatrix camera_matrix_square;
  1286. if (p_cam_orthogonal) {
  1287. Vector2 vp_he = camera_matrix.get_viewport_half_extents();
  1288. if (p_cam_vaspect) {
  1289. camera_matrix_square.set_orthogonal(vp_he.x * 2.0, 1.0, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
  1290. } else {
  1291. camera_matrix_square.set_orthogonal(vp_he.y * 2.0, 1.0, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  1292. }
  1293. } else {
  1294. Vector2 vp_he = camera_matrix.get_viewport_half_extents();
  1295. if (p_cam_vaspect) {
  1296. camera_matrix_square.set_frustum(vp_he.x * 2.0, 1.0, Vector2(), distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
  1297. } else {
  1298. camera_matrix_square.set_frustum(vp_he.y * 2.0, 1.0, Vector2(), distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  1299. }
  1300. if (i == 0) {
  1301. //print_line("prev he: " + vp_he + " new he: " + camera_matrix_square.get_viewport_half_extents());
  1302. }
  1303. }
  1304. Vector3 endpoints_square[8]; // frustum plane endpoints
  1305. res = camera_matrix_square.get_endpoints(p_cam_transform, endpoints_square);
  1306. ERR_CONTINUE(!res);
  1307. Vector3 center_square;
  1308. real_t z_max_square = 0;
  1309. for (int j = 0; j < 8; j++) {
  1310. center_square += endpoints_square[j];
  1311. real_t d_z = z_vec.dot(endpoints_square[j]);
  1312. if (j == 0 || d_z > z_max_square)
  1313. z_max_square = d_z;
  1314. }
  1315. if (cull_max > z_max_square) {
  1316. z_max_square = cull_max;
  1317. }
  1318. center_square /= 8.0;
  1319. real_t radius_square = 0;
  1320. for (int j = 0; j < 8; j++) {
  1321. real_t d = center_square.distance_to(endpoints_square[j]);
  1322. if (d > radius_square)
  1323. radius_square = d;
  1324. }
  1325. radius_square *= texture_size / (texture_size - 2.0); //add a texel by each side
  1326. if (pancake_size > 0) {
  1327. z_max_square = z_vec.dot(center_square) + radius_square + pancake_size;
  1328. }
  1329. real_t z_min_cam_square = z_vec.dot(center_square) - radius_square;
  1330. aspect_bias_scale = (z_max - z_min_cam) / (z_max_square - z_min_cam_square);
  1331. // this is not entirely perfect, because the cull-adjusted z-max may be different
  1332. // but at least it's warranted that it results in a greater bias, so no acne should be present either way.
  1333. // pancaking also helps with this.
  1334. }
  1335. {
  1336. CameraMatrix ortho_camera;
  1337. real_t half_x = (x_max_cam - x_min_cam) * 0.5;
  1338. real_t half_y = (y_max_cam - y_min_cam) * 0.5;
  1339. ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));
  1340. Vector2 uv_scale(1.0 / (x_max_cam - x_min_cam), 1.0 / (y_max_cam - y_min_cam));
  1341. Transform ortho_transform;
  1342. ortho_transform.basis = transform.basis;
  1343. ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;
  1344. {
  1345. Vector3 max_in_view = p_cam_transform.affine_inverse().xform(z_vec * cull_max);
  1346. Vector3 dir_in_view = p_cam_transform.xform_inv(z_vec).normalized();
  1347. cull_max = dir_in_view.dot(max_in_view);
  1348. }
  1349. RSG::scene_render->light_instance_set_shadow_transform(light->instance, ortho_camera, ortho_transform, z_max - z_min_cam, distances[i + 1], i, radius * 2.0 / texture_size, bias_scale * aspect_bias_scale * min_distance_bias_scale, z_max, uv_scale);
  1350. }
  1351. RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1352. }
  1353. } break;
  1354. case RS::LIGHT_OMNI: {
  1355. RS::LightOmniShadowMode shadow_mode = RSG::storage->light_omni_get_shadow_mode(p_instance->base);
  1356. if (shadow_mode == RS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID || !RSG::scene_render->light_instances_can_render_shadow_cube()) {
  1357. for (int i = 0; i < 2; i++) {
  1358. //using this one ensures that raster deferred will have it
  1359. RENDER_TIMESTAMP("Culling Shadow Paraboloid" + itos(i));
  1360. real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1361. real_t z = i == 0 ? -1 : 1;
  1362. Vector<Plane> planes;
  1363. planes.resize(6);
  1364. planes.write[0] = light_transform.xform(Plane(Vector3(0, 0, z), radius));
  1365. planes.write[1] = light_transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
  1366. planes.write[2] = light_transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
  1367. planes.write[3] = light_transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
  1368. planes.write[4] = light_transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));
  1369. planes.write[5] = light_transform.xform(Plane(Vector3(0, 0, -z), 0));
  1370. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
  1371. Plane near_plane(light_transform.origin, light_transform.basis.get_axis(2) * z);
  1372. for (int j = 0; j < cull_count; j++) {
  1373. Instance *instance = instance_shadow_cull_result[j];
  1374. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1375. cull_count--;
  1376. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1377. j--;
  1378. } else {
  1379. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1380. animated_material_found = true;
  1381. }
  1382. instance->depth = near_plane.distance_to(instance->transform.origin);
  1383. instance->depth_layer = 0;
  1384. }
  1385. }
  1386. RSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, i, 0);
  1387. RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1388. }
  1389. } else { //shadow cube
  1390. real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1391. CameraMatrix cm;
  1392. cm.set_perspective(90, 1, 0.01, radius);
  1393. for (int i = 0; i < 6; i++) {
  1394. RENDER_TIMESTAMP("Culling Shadow Cube side" + itos(i));
  1395. //using this one ensures that raster deferred will have it
  1396. static const Vector3 view_normals[6] = {
  1397. Vector3(+1, 0, 0),
  1398. Vector3(-1, 0, 0),
  1399. Vector3(0, -1, 0),
  1400. Vector3(0, +1, 0),
  1401. Vector3(0, 0, +1),
  1402. Vector3(0, 0, -1)
  1403. };
  1404. static const Vector3 view_up[6] = {
  1405. Vector3(0, -1, 0),
  1406. Vector3(0, -1, 0),
  1407. Vector3(0, 0, -1),
  1408. Vector3(0, 0, +1),
  1409. Vector3(0, -1, 0),
  1410. Vector3(0, -1, 0)
  1411. };
  1412. Transform xform = light_transform * Transform().looking_at(view_normals[i], view_up[i]);
  1413. Vector<Plane> planes = cm.get_projection_planes(xform);
  1414. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
  1415. Plane near_plane(xform.origin, -xform.basis.get_axis(2));
  1416. for (int j = 0; j < cull_count; j++) {
  1417. Instance *instance = instance_shadow_cull_result[j];
  1418. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1419. cull_count--;
  1420. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1421. j--;
  1422. } else {
  1423. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1424. animated_material_found = true;
  1425. }
  1426. instance->depth = near_plane.distance_to(instance->transform.origin);
  1427. instance->depth_layer = 0;
  1428. }
  1429. }
  1430. RSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i, 0);
  1431. RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1432. }
  1433. //restore the regular DP matrix
  1434. RSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, 0, 0);
  1435. }
  1436. } break;
  1437. case RS::LIGHT_SPOT: {
  1438. RENDER_TIMESTAMP("Culling Spot Light");
  1439. real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1440. real_t angle = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  1441. CameraMatrix cm;
  1442. cm.set_perspective(angle * 2.0, 1.0, 0.01, radius);
  1443. Vector<Plane> planes = cm.get_projection_planes(light_transform);
  1444. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
  1445. Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2));
  1446. for (int j = 0; j < cull_count; j++) {
  1447. Instance *instance = instance_shadow_cull_result[j];
  1448. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1449. cull_count--;
  1450. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1451. j--;
  1452. } else {
  1453. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1454. animated_material_found = true;
  1455. }
  1456. instance->depth = near_plane.distance_to(instance->transform.origin);
  1457. instance->depth_layer = 0;
  1458. }
  1459. }
  1460. RSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, light_transform, radius, 0, 0, 0);
  1461. RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, 0, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1462. } break;
  1463. }
  1464. return animated_material_found;
  1465. }
  1466. void RenderingServerScene::render_camera(RID p_render_buffers, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
  1467. // render to mono camera
  1468. #ifndef _3D_DISABLED
  1469. Camera *camera = camera_owner.getornull(p_camera);
  1470. ERR_FAIL_COND(!camera);
  1471. /* STEP 1 - SETUP CAMERA */
  1472. CameraMatrix camera_matrix;
  1473. bool ortho = false;
  1474. switch (camera->type) {
  1475. case Camera::ORTHOGONAL: {
  1476. camera_matrix.set_orthogonal(
  1477. camera->size,
  1478. p_viewport_size.width / (float)p_viewport_size.height,
  1479. camera->znear,
  1480. camera->zfar,
  1481. camera->vaspect);
  1482. ortho = true;
  1483. } break;
  1484. case Camera::PERSPECTIVE: {
  1485. camera_matrix.set_perspective(
  1486. camera->fov,
  1487. p_viewport_size.width / (float)p_viewport_size.height,
  1488. camera->znear,
  1489. camera->zfar,
  1490. camera->vaspect);
  1491. ortho = false;
  1492. } break;
  1493. case Camera::FRUSTUM: {
  1494. camera_matrix.set_frustum(
  1495. camera->size,
  1496. p_viewport_size.width / (float)p_viewport_size.height,
  1497. camera->offset,
  1498. camera->znear,
  1499. camera->zfar,
  1500. camera->vaspect);
  1501. ortho = false;
  1502. } break;
  1503. }
  1504. _prepare_scene(camera->transform, camera_matrix, ortho, camera->vaspect, camera->env, camera->effects, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
  1505. _render_scene(p_render_buffers, camera->transform, camera_matrix, ortho, camera->env, camera->effects, p_scenario, p_shadow_atlas, RID(), -1);
  1506. #endif
  1507. }
  1508. void RenderingServerScene::render_camera(RID p_render_buffers, Ref<XRInterface> &p_interface, XRInterface::Eyes p_eye, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
  1509. // render for AR/VR interface
  1510. Camera *camera = camera_owner.getornull(p_camera);
  1511. ERR_FAIL_COND(!camera);
  1512. /* SETUP CAMERA, we are ignoring type and FOV here */
  1513. float aspect = p_viewport_size.width / (float)p_viewport_size.height;
  1514. CameraMatrix camera_matrix = p_interface->get_projection_for_eye(p_eye, aspect, camera->znear, camera->zfar);
  1515. // We also ignore our camera position, it will have been positioned with a slightly old tracking position.
  1516. // Instead we take our origin point and have our ar/vr interface add fresh tracking data! Whoohoo!
  1517. Transform world_origin = XRServer::get_singleton()->get_world_origin();
  1518. Transform cam_transform = p_interface->get_transform_for_eye(p_eye, world_origin);
  1519. // For stereo render we only prepare for our left eye and then reuse the outcome for our right eye
  1520. if (p_eye == XRInterface::EYE_LEFT) {
  1521. // Center our transform, we assume basis is equal.
  1522. Transform mono_transform = cam_transform;
  1523. Transform right_transform = p_interface->get_transform_for_eye(XRInterface::EYE_RIGHT, world_origin);
  1524. mono_transform.origin += right_transform.origin;
  1525. mono_transform.origin *= 0.5;
  1526. // We need to combine our projection frustums for culling.
  1527. // Ideally we should use our clipping planes for this and combine them,
  1528. // however our shadow map logic uses our projection matrix.
  1529. // Note: as our left and right frustums should be mirrored, we don't need our right projection matrix.
  1530. // - get some base values we need
  1531. float eye_dist = (mono_transform.origin - cam_transform.origin).length();
  1532. float z_near = camera_matrix.get_z_near(); // get our near plane
  1533. float z_far = camera_matrix.get_z_far(); // get our far plane
  1534. float width = (2.0 * z_near) / camera_matrix.matrix[0][0];
  1535. float x_shift = width * camera_matrix.matrix[2][0];
  1536. float height = (2.0 * z_near) / camera_matrix.matrix[1][1];
  1537. float y_shift = height * camera_matrix.matrix[2][1];
  1538. // printf("Eye_dist = %f, Near = %f, Far = %f, Width = %f, Shift = %f\n", eye_dist, z_near, z_far, width, x_shift);
  1539. // - calculate our near plane size (horizontal only, right_near is mirrored)
  1540. float left_near = -eye_dist - ((width - x_shift) * 0.5);
  1541. // - calculate our far plane size (horizontal only, right_far is mirrored)
  1542. float left_far = -eye_dist - (z_far * (width - x_shift) * 0.5 / z_near);
  1543. float left_far_right_eye = eye_dist - (z_far * (width + x_shift) * 0.5 / z_near);
  1544. if (left_far > left_far_right_eye) {
  1545. // on displays smaller then double our iod, the right eye far frustrum can overtake the left eyes.
  1546. left_far = left_far_right_eye;
  1547. }
  1548. // - figure out required z-shift
  1549. float slope = (left_far - left_near) / (z_far - z_near);
  1550. float z_shift = (left_near / slope) - z_near;
  1551. // - figure out new vertical near plane size (this will be slightly oversized thanks to our z-shift)
  1552. float top_near = (height - y_shift) * 0.5;
  1553. top_near += (top_near / z_near) * z_shift;
  1554. float bottom_near = -(height + y_shift) * 0.5;
  1555. bottom_near += (bottom_near / z_near) * z_shift;
  1556. // 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);
  1557. // - generate our frustum
  1558. CameraMatrix combined_matrix;
  1559. combined_matrix.set_frustum(left_near, -left_near, bottom_near, top_near, z_near + z_shift, z_far + z_shift);
  1560. // and finally move our camera back
  1561. Transform apply_z_shift;
  1562. apply_z_shift.origin = Vector3(0.0, 0.0, z_shift); // z negative is forward so this moves it backwards
  1563. mono_transform *= apply_z_shift;
  1564. // now prepare our scene with our adjusted transform projection matrix
  1565. _prepare_scene(mono_transform, combined_matrix, false, false, camera->env, camera->effects, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
  1566. } else if (p_eye == XRInterface::EYE_MONO) {
  1567. // For mono render, prepare as per usual
  1568. _prepare_scene(cam_transform, camera_matrix, false, false, camera->env, camera->effects, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
  1569. }
  1570. // And render our scene...
  1571. _render_scene(p_render_buffers, cam_transform, camera_matrix, false, camera->env, camera->effects, p_scenario, p_shadow_atlas, RID(), -1);
  1572. };
  1573. void RenderingServerScene::_prepare_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect, RID p_force_environment, RID p_force_camera_effects, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, bool p_using_shadows) {
  1574. // Note, in stereo rendering:
  1575. // - p_cam_transform will be a transform in the middle of our two eyes
  1576. // - p_cam_projection is a wider frustrum that encompasses both eyes
  1577. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1578. render_pass++;
  1579. uint32_t camera_layer_mask = p_visible_layers;
  1580. RSG::scene_render->set_scene_pass(render_pass);
  1581. RENDER_TIMESTAMP("Frustum Culling");
  1582. //rasterizer->set_camera(camera->transform, camera_matrix,ortho);
  1583. Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
  1584. Plane near_plane(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2).normalized());
  1585. float z_far = p_cam_projection.get_z_far();
  1586. /* STEP 2 - CULL */
  1587. instance_cull_count = scenario->octree.cull_convex(planes, instance_cull_result, MAX_INSTANCE_CULL);
  1588. light_cull_count = 0;
  1589. reflection_probe_cull_count = 0;
  1590. decal_cull_count = 0;
  1591. gi_probe_cull_count = 0;
  1592. //light_samplers_culled=0;
  1593. /*
  1594. print_line("OT: "+rtos( (OS::get_singleton()->get_ticks_usec()-t)/1000.0));
  1595. print_line("OTO: "+itos(p_scenario->octree.get_octant_count()));
  1596. print_line("OTE: "+itos(p_scenario->octree.get_elem_count()));
  1597. print_line("OTP: "+itos(p_scenario->octree.get_pair_count()));
  1598. */
  1599. /* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */
  1600. //removed, will replace with culling
  1601. /* STEP 4 - REMOVE FURTHER CULLED OBJECTS, ADD LIGHTS */
  1602. for (int i = 0; i < instance_cull_count; i++) {
  1603. Instance *ins = instance_cull_result[i];
  1604. bool keep = false;
  1605. if ((camera_layer_mask & ins->layer_mask) == 0) {
  1606. //failure
  1607. } else if (ins->base_type == RS::INSTANCE_LIGHT && ins->visible) {
  1608. if (light_cull_count < MAX_LIGHTS_CULLED) {
  1609. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  1610. if (!light->geometries.empty()) {
  1611. //do not add this light if no geometry is affected by it..
  1612. light_cull_result[light_cull_count] = ins;
  1613. light_instance_cull_result[light_cull_count] = light->instance;
  1614. if (p_shadow_atlas.is_valid() && RSG::storage->light_has_shadow(ins->base)) {
  1615. RSG::scene_render->light_instance_mark_visible(light->instance); //mark it visible for shadow allocation later
  1616. }
  1617. light_cull_count++;
  1618. }
  1619. }
  1620. } else if (ins->base_type == RS::INSTANCE_REFLECTION_PROBE && ins->visible) {
  1621. if (reflection_probe_cull_count < MAX_REFLECTION_PROBES_CULLED) {
  1622. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(ins->base_data);
  1623. if (p_reflection_probe != reflection_probe->instance) {
  1624. //avoid entering The Matrix
  1625. if (!reflection_probe->geometries.empty()) {
  1626. //do not add this light if no geometry is affected by it..
  1627. if (reflection_probe->reflection_dirty || RSG::scene_render->reflection_probe_instance_needs_redraw(reflection_probe->instance)) {
  1628. if (!reflection_probe->update_list.in_list()) {
  1629. reflection_probe->render_step = 0;
  1630. reflection_probe_render_list.add_last(&reflection_probe->update_list);
  1631. }
  1632. reflection_probe->reflection_dirty = false;
  1633. }
  1634. if (RSG::scene_render->reflection_probe_instance_has_reflection(reflection_probe->instance)) {
  1635. reflection_probe_instance_cull_result[reflection_probe_cull_count] = reflection_probe->instance;
  1636. reflection_probe_cull_count++;
  1637. }
  1638. }
  1639. }
  1640. }
  1641. } else if (ins->base_type == RS::INSTANCE_DECAL && ins->visible) {
  1642. if (decal_cull_count < MAX_DECALS_CULLED) {
  1643. InstanceDecalData *decal = static_cast<InstanceDecalData *>(ins->base_data);
  1644. if (!decal->geometries.empty()) {
  1645. //do not add this decal if no geometry is affected by it..
  1646. decal_instance_cull_result[decal_cull_count] = decal->instance;
  1647. decal_cull_count++;
  1648. }
  1649. }
  1650. } else if (ins->base_type == RS::INSTANCE_GI_PROBE && ins->visible) {
  1651. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(ins->base_data);
  1652. if (!gi_probe->update_element.in_list()) {
  1653. gi_probe_update_list.add(&gi_probe->update_element);
  1654. }
  1655. if (gi_probe_cull_count < MAX_GI_PROBES_CULLED) {
  1656. gi_probe_instance_cull_result[gi_probe_cull_count] = gi_probe->probe_instance;
  1657. gi_probe_cull_count++;
  1658. }
  1659. } else if (((1 << ins->base_type) & RS::INSTANCE_GEOMETRY_MASK) && ins->visible && ins->cast_shadows != RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  1660. keep = true;
  1661. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(ins->base_data);
  1662. if (ins->redraw_if_visible) {
  1663. RenderingServerRaster::redraw_request();
  1664. }
  1665. if (ins->base_type == RS::INSTANCE_PARTICLES) {
  1666. //particles visible? process them
  1667. if (RSG::storage->particles_is_inactive(ins->base)) {
  1668. //but if nothing is going on, don't do it.
  1669. keep = false;
  1670. } else {
  1671. RSG::storage->particles_request_process(ins->base);
  1672. //particles visible? request redraw
  1673. RenderingServerRaster::redraw_request();
  1674. }
  1675. }
  1676. if (geom->lighting_dirty) {
  1677. int l = 0;
  1678. //only called when lights AABB enter/exit this geometry
  1679. ins->light_instances.resize(geom->lighting.size());
  1680. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  1681. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  1682. ins->light_instances.write[l++] = light->instance;
  1683. }
  1684. geom->lighting_dirty = false;
  1685. }
  1686. if (geom->reflection_dirty) {
  1687. int l = 0;
  1688. //only called when reflection probe AABB enter/exit this geometry
  1689. ins->reflection_probe_instances.resize(geom->reflection_probes.size());
  1690. for (List<Instance *>::Element *E = geom->reflection_probes.front(); E; E = E->next()) {
  1691. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->get()->base_data);
  1692. ins->reflection_probe_instances.write[l++] = reflection_probe->instance;
  1693. }
  1694. geom->reflection_dirty = false;
  1695. }
  1696. if (geom->gi_probes_dirty) {
  1697. int l = 0;
  1698. //only called when reflection probe AABB enter/exit this geometry
  1699. ins->gi_probe_instances.resize(geom->gi_probes.size());
  1700. for (List<Instance *>::Element *E = geom->gi_probes.front(); E; E = E->next()) {
  1701. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(E->get()->base_data);
  1702. ins->gi_probe_instances.write[l++] = gi_probe->probe_instance;
  1703. }
  1704. geom->gi_probes_dirty = false;
  1705. }
  1706. ins->depth = near_plane.distance_to(ins->transform.origin);
  1707. ins->depth_layer = CLAMP(int(ins->depth * 16 / z_far), 0, 15);
  1708. }
  1709. if (!keep) {
  1710. // remove, no reason to keep
  1711. instance_cull_count--;
  1712. SWAP(instance_cull_result[i], instance_cull_result[instance_cull_count]);
  1713. i--;
  1714. ins->last_render_pass = 0; // make invalid
  1715. } else {
  1716. ins->last_render_pass = render_pass;
  1717. }
  1718. }
  1719. /* STEP 5 - PROCESS LIGHTS */
  1720. RID *directional_light_ptr = &light_instance_cull_result[light_cull_count];
  1721. directional_light_count = 0;
  1722. // directional lights
  1723. {
  1724. Instance **lights_with_shadow = (Instance **)alloca(sizeof(Instance *) * scenario->directional_lights.size());
  1725. int directional_shadow_count = 0;
  1726. for (List<Instance *>::Element *E = scenario->directional_lights.front(); E; E = E->next()) {
  1727. if (light_cull_count + directional_light_count >= MAX_LIGHTS_CULLED) {
  1728. break;
  1729. }
  1730. if (!E->get()->visible)
  1731. continue;
  1732. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  1733. //check shadow..
  1734. if (light) {
  1735. if (p_using_shadows && p_shadow_atlas.is_valid() && RSG::storage->light_has_shadow(E->get()->base)) {
  1736. lights_with_shadow[directional_shadow_count++] = E->get();
  1737. }
  1738. //add to list
  1739. directional_light_ptr[directional_light_count++] = light->instance;
  1740. }
  1741. }
  1742. RSG::scene_render->set_directional_shadow_count(directional_shadow_count);
  1743. for (int i = 0; i < directional_shadow_count; i++) {
  1744. RENDER_TIMESTAMP(">Rendering Directional Light " + itos(i));
  1745. _light_instance_update_shadow(lights_with_shadow[i], p_cam_transform, p_cam_projection, p_cam_orthogonal, p_cam_vaspect, p_shadow_atlas, scenario);
  1746. RENDER_TIMESTAMP("<Rendering Directional Light " + itos(i));
  1747. }
  1748. }
  1749. if (p_using_shadows) { //setup shadow maps
  1750. //SortArray<Instance*,_InstanceLightsort> sorter;
  1751. //sorter.sort(light_cull_result,light_cull_count);
  1752. for (int i = 0; i < light_cull_count; i++) {
  1753. Instance *ins = light_cull_result[i];
  1754. if (!p_shadow_atlas.is_valid() || !RSG::storage->light_has_shadow(ins->base))
  1755. continue;
  1756. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  1757. float coverage = 0.f;
  1758. { //compute coverage
  1759. Transform cam_xf = p_cam_transform;
  1760. float zn = p_cam_projection.get_z_near();
  1761. Plane p(cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2)); //camera near plane
  1762. // near plane half width and height
  1763. Vector2 vp_half_extents = p_cam_projection.get_viewport_half_extents();
  1764. switch (RSG::storage->light_get_type(ins->base)) {
  1765. case RS::LIGHT_OMNI: {
  1766. float radius = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
  1767. //get two points parallel to near plane
  1768. Vector3 points[2] = {
  1769. ins->transform.origin,
  1770. ins->transform.origin + cam_xf.basis.get_axis(0) * radius
  1771. };
  1772. if (!p_cam_orthogonal) {
  1773. //if using perspetive, map them to near plane
  1774. for (int j = 0; j < 2; j++) {
  1775. if (p.distance_to(points[j]) < 0) {
  1776. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  1777. }
  1778. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  1779. }
  1780. }
  1781. float screen_diameter = points[0].distance_to(points[1]) * 2;
  1782. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  1783. } break;
  1784. case RS::LIGHT_SPOT: {
  1785. float radius = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
  1786. float angle = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  1787. float w = radius * Math::sin(Math::deg2rad(angle));
  1788. float d = radius * Math::cos(Math::deg2rad(angle));
  1789. Vector3 base = ins->transform.origin - ins->transform.basis.get_axis(2).normalized() * d;
  1790. Vector3 points[2] = {
  1791. base,
  1792. base + cam_xf.basis.get_axis(0) * w
  1793. };
  1794. if (!p_cam_orthogonal) {
  1795. //if using perspetive, map them to near plane
  1796. for (int j = 0; j < 2; j++) {
  1797. if (p.distance_to(points[j]) < 0) {
  1798. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  1799. }
  1800. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  1801. }
  1802. }
  1803. float screen_diameter = points[0].distance_to(points[1]) * 2;
  1804. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  1805. } break;
  1806. default: {
  1807. ERR_PRINT("Invalid Light Type");
  1808. }
  1809. }
  1810. }
  1811. if (light->shadow_dirty) {
  1812. light->last_version++;
  1813. light->shadow_dirty = false;
  1814. }
  1815. bool redraw = RSG::scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
  1816. if (redraw) {
  1817. //must redraw!
  1818. RENDER_TIMESTAMP(">Rendering Light " + itos(i));
  1819. light->shadow_dirty = _light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_cam_vaspect, p_shadow_atlas, scenario);
  1820. RENDER_TIMESTAMP("<Rendering Light " + itos(i));
  1821. }
  1822. }
  1823. }
  1824. }
  1825. void RenderingServerScene::_render_scene(RID p_render_buffers, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, RID p_force_camera_effects, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {
  1826. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1827. /* ENVIRONMENT */
  1828. RID environment;
  1829. if (p_force_environment.is_valid()) //camera has more environment priority
  1830. environment = p_force_environment;
  1831. else if (scenario->environment.is_valid())
  1832. environment = scenario->environment;
  1833. else
  1834. environment = scenario->fallback_environment;
  1835. RID camera_effects;
  1836. if (p_force_camera_effects.is_valid()) {
  1837. camera_effects = p_force_camera_effects;
  1838. } else {
  1839. camera_effects = scenario->camera_effects;
  1840. }
  1841. /* PROCESS GEOMETRY AND DRAW SCENE */
  1842. RENDER_TIMESTAMP("Render Scene ");
  1843. RSG::scene_render->render_scene(p_render_buffers, p_cam_transform, p_cam_projection, p_cam_orthogonal, (RasterizerScene::InstanceBase **)instance_cull_result, instance_cull_count, light_instance_cull_result, light_cull_count + directional_light_count, reflection_probe_instance_cull_result, reflection_probe_cull_count, gi_probe_instance_cull_result, gi_probe_cull_count, decal_instance_cull_result, decal_cull_count, environment, camera_effects, p_shadow_atlas, p_reflection_probe.is_valid() ? RID() : scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass);
  1844. }
  1845. void RenderingServerScene::render_empty_scene(RID p_render_buffers, RID p_scenario, RID p_shadow_atlas) {
  1846. #ifndef _3D_DISABLED
  1847. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1848. RID environment;
  1849. if (scenario->environment.is_valid())
  1850. environment = scenario->environment;
  1851. else
  1852. environment = scenario->fallback_environment;
  1853. RENDER_TIMESTAMP("Render Empty Scene ");
  1854. RSG::scene_render->render_scene(p_render_buffers, Transform(), CameraMatrix(), true, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, environment, RID(), p_shadow_atlas, scenario->reflection_atlas, RID(), 0);
  1855. #endif
  1856. }
  1857. bool RenderingServerScene::_render_reflection_probe_step(Instance *p_instance, int p_step) {
  1858. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  1859. Scenario *scenario = p_instance->scenario;
  1860. ERR_FAIL_COND_V(!scenario, true);
  1861. RenderingServerRaster::redraw_request(); //update, so it updates in editor
  1862. if (p_step == 0) {
  1863. if (!RSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
  1864. return true; //all full
  1865. }
  1866. }
  1867. if (p_step >= 0 && p_step < 6) {
  1868. static const Vector3 view_normals[6] = {
  1869. Vector3(+1, 0, 0),
  1870. Vector3(-1, 0, 0),
  1871. Vector3(0, +1, 0),
  1872. Vector3(0, -1, 0),
  1873. Vector3(0, 0, +1),
  1874. Vector3(0, 0, -1)
  1875. };
  1876. static const Vector3 view_up[6] = {
  1877. Vector3(0, -1, 0),
  1878. Vector3(0, -1, 0),
  1879. Vector3(0, 0, +1),
  1880. Vector3(0, 0, -1),
  1881. Vector3(0, -1, 0),
  1882. Vector3(0, -1, 0)
  1883. };
  1884. Vector3 extents = RSG::storage->reflection_probe_get_extents(p_instance->base);
  1885. Vector3 origin_offset = RSG::storage->reflection_probe_get_origin_offset(p_instance->base);
  1886. float max_distance = RSG::storage->reflection_probe_get_origin_max_distance(p_instance->base);
  1887. Vector3 edge = view_normals[p_step] * extents;
  1888. 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
  1889. max_distance = MAX(max_distance, distance);
  1890. //render cubemap side
  1891. CameraMatrix cm;
  1892. cm.set_perspective(90, 1, 0.01, max_distance);
  1893. Transform local_view;
  1894. local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]);
  1895. Transform xform = p_instance->transform * local_view;
  1896. RID shadow_atlas;
  1897. bool use_shadows = RSG::storage->reflection_probe_renders_shadows(p_instance->base);
  1898. if (use_shadows) {
  1899. shadow_atlas = scenario->reflection_probe_shadow_atlas;
  1900. }
  1901. RENDER_TIMESTAMP("Render Reflection Probe, Step " + itos(p_step));
  1902. _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, use_shadows);
  1903. _render_scene(RID(), xform, cm, false, RID(), RID(), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, p_step);
  1904. } else {
  1905. //do roughness postprocess step until it believes it's done
  1906. RENDER_TIMESTAMP("Post-Process Reflection Probe, Step " + itos(p_step));
  1907. return RSG::scene_render->reflection_probe_instance_postprocess_step(reflection_probe->instance);
  1908. }
  1909. return false;
  1910. }
  1911. void RenderingServerScene::render_probes() {
  1912. /* REFLECTION PROBES */
  1913. SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();
  1914. bool busy = false;
  1915. while (ref_probe) {
  1916. SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
  1917. RID base = ref_probe->self()->owner->base;
  1918. switch (RSG::storage->reflection_probe_get_update_mode(base)) {
  1919. case RS::REFLECTION_PROBE_UPDATE_ONCE: {
  1920. if (busy) //already rendering something
  1921. break;
  1922. bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
  1923. if (done) {
  1924. reflection_probe_render_list.remove(ref_probe);
  1925. } else {
  1926. ref_probe->self()->render_step++;
  1927. }
  1928. busy = true; //do not render another one of this kind
  1929. } break;
  1930. case RS::REFLECTION_PROBE_UPDATE_ALWAYS: {
  1931. int step = 0;
  1932. bool done = false;
  1933. while (!done) {
  1934. done = _render_reflection_probe_step(ref_probe->self()->owner, step);
  1935. step++;
  1936. }
  1937. reflection_probe_render_list.remove(ref_probe);
  1938. } break;
  1939. }
  1940. ref_probe = next;
  1941. }
  1942. /* GI PROBES */
  1943. SelfList<InstanceGIProbeData> *gi_probe = gi_probe_update_list.first();
  1944. if (gi_probe) {
  1945. RENDER_TIMESTAMP("Render GI Probes");
  1946. }
  1947. while (gi_probe) {
  1948. SelfList<InstanceGIProbeData> *next = gi_probe->next();
  1949. InstanceGIProbeData *probe = gi_probe->self();
  1950. //Instance *instance_probe = probe->owner;
  1951. //check if probe must be setup, but don't do if on the lighting thread
  1952. bool cache_dirty = false;
  1953. int cache_count = 0;
  1954. {
  1955. int light_cache_size = probe->light_cache.size();
  1956. const InstanceGIProbeData::LightCache *caches = probe->light_cache.ptr();
  1957. const RID *instance_caches = probe->light_instances.ptr();
  1958. int idx = 0; //must count visible lights
  1959. for (Set<Instance *>::Element *E = probe->lights.front(); E; E = E->next()) {
  1960. Instance *instance = E->get();
  1961. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  1962. if (!instance->visible) {
  1963. continue;
  1964. }
  1965. if (cache_dirty) {
  1966. //do nothing, since idx must count all visible lights anyway
  1967. } else if (idx >= light_cache_size) {
  1968. cache_dirty = true;
  1969. } else {
  1970. const InstanceGIProbeData::LightCache *cache = &caches[idx];
  1971. if (
  1972. instance_caches[idx] != instance_light->instance ||
  1973. cache->has_shadow != RSG::storage->light_has_shadow(instance->base) ||
  1974. cache->type != RSG::storage->light_get_type(instance->base) ||
  1975. cache->transform != instance->transform ||
  1976. cache->color != RSG::storage->light_get_color(instance->base) ||
  1977. cache->energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
  1978. cache->bake_energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
  1979. cache->radius != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
  1980. cache->attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
  1981. cache->spot_angle != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
  1982. cache->spot_attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION)) {
  1983. cache_dirty = true;
  1984. }
  1985. }
  1986. idx++;
  1987. }
  1988. for (List<Instance *>::Element *E = probe->owner->scenario->directional_lights.front(); E; E = E->next()) {
  1989. Instance *instance = E->get();
  1990. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  1991. if (!instance->visible) {
  1992. continue;
  1993. }
  1994. if (cache_dirty) {
  1995. //do nothing, since idx must count all visible lights anyway
  1996. } else if (idx >= light_cache_size) {
  1997. cache_dirty = true;
  1998. } else {
  1999. const InstanceGIProbeData::LightCache *cache = &caches[idx];
  2000. if (
  2001. instance_caches[idx] != instance_light->instance ||
  2002. cache->has_shadow != RSG::storage->light_has_shadow(instance->base) ||
  2003. cache->type != RSG::storage->light_get_type(instance->base) ||
  2004. cache->transform != instance->transform ||
  2005. cache->color != RSG::storage->light_get_color(instance->base) ||
  2006. cache->energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
  2007. cache->bake_energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
  2008. cache->radius != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
  2009. cache->attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
  2010. cache->spot_angle != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
  2011. cache->spot_attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION)) {
  2012. cache_dirty = true;
  2013. }
  2014. }
  2015. idx++;
  2016. }
  2017. if (idx != light_cache_size) {
  2018. cache_dirty = true;
  2019. }
  2020. cache_count = idx;
  2021. }
  2022. bool update_lights = RSG::scene_render->gi_probe_needs_update(probe->probe_instance);
  2023. if (cache_dirty) {
  2024. probe->light_cache.resize(cache_count);
  2025. probe->light_instances.resize(cache_count);
  2026. if (cache_count) {
  2027. InstanceGIProbeData::LightCache *caches = probe->light_cache.ptrw();
  2028. RID *instance_caches = probe->light_instances.ptrw();
  2029. int idx = 0; //must count visible lights
  2030. for (Set<Instance *>::Element *E = probe->lights.front(); E; E = E->next()) {
  2031. Instance *instance = E->get();
  2032. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2033. if (!instance->visible) {
  2034. continue;
  2035. }
  2036. InstanceGIProbeData::LightCache *cache = &caches[idx];
  2037. instance_caches[idx] = instance_light->instance;
  2038. cache->has_shadow = RSG::storage->light_has_shadow(instance->base);
  2039. cache->type = RSG::storage->light_get_type(instance->base);
  2040. cache->transform = instance->transform;
  2041. cache->color = RSG::storage->light_get_color(instance->base);
  2042. cache->energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
  2043. cache->bake_energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  2044. cache->radius = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
  2045. cache->attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
  2046. cache->spot_angle = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2047. cache->spot_attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  2048. idx++;
  2049. }
  2050. for (List<Instance *>::Element *E = probe->owner->scenario->directional_lights.front(); E; E = E->next()) {
  2051. Instance *instance = E->get();
  2052. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2053. if (!instance->visible) {
  2054. continue;
  2055. }
  2056. InstanceGIProbeData::LightCache *cache = &caches[idx];
  2057. instance_caches[idx] = instance_light->instance;
  2058. cache->has_shadow = RSG::storage->light_has_shadow(instance->base);
  2059. cache->type = RSG::storage->light_get_type(instance->base);
  2060. cache->transform = instance->transform;
  2061. cache->color = RSG::storage->light_get_color(instance->base);
  2062. cache->energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
  2063. cache->bake_energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  2064. cache->radius = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
  2065. cache->attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
  2066. cache->spot_angle = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2067. cache->spot_attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  2068. idx++;
  2069. }
  2070. }
  2071. update_lights = true;
  2072. }
  2073. instance_cull_count = 0;
  2074. for (List<InstanceGIProbeData::PairInfo>::Element *E = probe->dynamic_geometries.front(); E; E = E->next()) {
  2075. if (instance_cull_count < MAX_INSTANCE_CULL) {
  2076. Instance *ins = E->get().geometry;
  2077. if (!ins->visible) {
  2078. continue;
  2079. }
  2080. InstanceGeometryData *geom = (InstanceGeometryData *)ins->base_data;
  2081. if (geom->gi_probes_dirty) {
  2082. //giprobes may be dirty, so update
  2083. int l = 0;
  2084. //only called when reflection probe AABB enter/exit this geometry
  2085. ins->gi_probe_instances.resize(geom->gi_probes.size());
  2086. for (List<Instance *>::Element *F = geom->gi_probes.front(); F; F = F->next()) {
  2087. InstanceGIProbeData *gi_probe2 = static_cast<InstanceGIProbeData *>(F->get()->base_data);
  2088. ins->gi_probe_instances.write[l++] = gi_probe2->probe_instance;
  2089. }
  2090. geom->gi_probes_dirty = false;
  2091. }
  2092. instance_cull_result[instance_cull_count++] = E->get().geometry;
  2093. }
  2094. }
  2095. RSG::scene_render->gi_probe_update(probe->probe_instance, update_lights, probe->light_instances, instance_cull_count, (RasterizerScene::InstanceBase **)instance_cull_result);
  2096. gi_probe_update_list.remove(gi_probe);
  2097. gi_probe = next;
  2098. }
  2099. }
  2100. void RenderingServerScene::_update_instance_shader_parameters_from_material(Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter> &isparams, const Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter> &existing_isparams, RID p_material) {
  2101. List<RasterizerStorage::InstanceShaderParam> plist;
  2102. RSG::storage->material_get_instance_shader_parameters(p_material, &plist);
  2103. for (List<RasterizerStorage::InstanceShaderParam>::Element *E = plist.front(); E; E = E->next()) {
  2104. StringName name = E->get().info.name;
  2105. if (isparams.has(name)) {
  2106. if (isparams[name].info.type != E->get().info.type) {
  2107. 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.");
  2108. }
  2109. if (isparams[name].index != E->get().index) {
  2110. 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.");
  2111. }
  2112. continue; //first one found always has priority
  2113. }
  2114. RasterizerScene::InstanceBase::InstanceShaderParameter isp;
  2115. isp.index = E->get().index;
  2116. isp.info = E->get().info;
  2117. isp.default_value = E->get().default_value;
  2118. if (existing_isparams.has(name)) {
  2119. isp.value = existing_isparams[name].value;
  2120. } else {
  2121. isp.value = E->get().default_value;
  2122. }
  2123. isparams[name] = isp;
  2124. }
  2125. }
  2126. void RenderingServerScene::_update_dirty_instance(Instance *p_instance) {
  2127. if (p_instance->update_aabb) {
  2128. _update_instance_aabb(p_instance);
  2129. }
  2130. if (p_instance->update_dependencies) {
  2131. p_instance->instance_increase_version();
  2132. if (p_instance->base.is_valid()) {
  2133. RSG::storage->base_update_dependency(p_instance->base, p_instance);
  2134. }
  2135. if (p_instance->material_override.is_valid()) {
  2136. RSG::storage->material_update_dependency(p_instance->material_override, p_instance);
  2137. }
  2138. if (p_instance->base_type == RS::INSTANCE_MESH) {
  2139. //remove materials no longer used and un-own them
  2140. int new_mat_count = RSG::storage->mesh_get_surface_count(p_instance->base);
  2141. p_instance->materials.resize(new_mat_count);
  2142. int new_blend_shape_count = RSG::storage->mesh_get_blend_shape_count(p_instance->base);
  2143. if (new_blend_shape_count != p_instance->blend_values.size()) {
  2144. p_instance->blend_values.resize(new_blend_shape_count);
  2145. for (int i = 0; i < new_blend_shape_count; i++) {
  2146. p_instance->blend_values.write[i] = 0;
  2147. }
  2148. }
  2149. }
  2150. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  2151. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  2152. bool can_cast_shadows = true;
  2153. bool is_animated = false;
  2154. Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter> isparams;
  2155. if (p_instance->cast_shadows == RS::SHADOW_CASTING_SETTING_OFF) {
  2156. can_cast_shadows = false;
  2157. }
  2158. if (p_instance->material_override.is_valid()) {
  2159. if (!RSG::storage->material_casts_shadows(p_instance->material_override)) {
  2160. can_cast_shadows = false;
  2161. }
  2162. is_animated = RSG::storage->material_is_animated(p_instance->material_override);
  2163. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, p_instance->material_override);
  2164. } else {
  2165. if (p_instance->base_type == RS::INSTANCE_MESH) {
  2166. RID mesh = p_instance->base;
  2167. if (mesh.is_valid()) {
  2168. bool cast_shadows = false;
  2169. for (int i = 0; i < p_instance->materials.size(); i++) {
  2170. RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : RSG::storage->mesh_surface_get_material(mesh, i);
  2171. if (!mat.is_valid()) {
  2172. cast_shadows = true;
  2173. } else {
  2174. if (RSG::storage->material_casts_shadows(mat)) {
  2175. cast_shadows = true;
  2176. }
  2177. if (RSG::storage->material_is_animated(mat)) {
  2178. is_animated = true;
  2179. }
  2180. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2181. RSG::storage->material_update_dependency(mat, p_instance);
  2182. }
  2183. }
  2184. if (!cast_shadows) {
  2185. can_cast_shadows = false;
  2186. }
  2187. }
  2188. } else if (p_instance->base_type == RS::INSTANCE_MULTIMESH) {
  2189. RID mesh = RSG::storage->multimesh_get_mesh(p_instance->base);
  2190. if (mesh.is_valid()) {
  2191. bool cast_shadows = false;
  2192. int sc = RSG::storage->mesh_get_surface_count(mesh);
  2193. for (int i = 0; i < sc; i++) {
  2194. RID mat = RSG::storage->mesh_surface_get_material(mesh, i);
  2195. if (!mat.is_valid()) {
  2196. cast_shadows = true;
  2197. } else {
  2198. if (RSG::storage->material_casts_shadows(mat)) {
  2199. cast_shadows = true;
  2200. }
  2201. if (RSG::storage->material_is_animated(mat)) {
  2202. is_animated = true;
  2203. }
  2204. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2205. RSG::storage->material_update_dependency(mat, p_instance);
  2206. }
  2207. }
  2208. if (!cast_shadows) {
  2209. can_cast_shadows = false;
  2210. }
  2211. RSG::storage->base_update_dependency(mesh, p_instance);
  2212. }
  2213. } else if (p_instance->base_type == RS::INSTANCE_IMMEDIATE) {
  2214. RID mat = RSG::storage->immediate_get_material(p_instance->base);
  2215. if (!(!mat.is_valid() || RSG::storage->material_casts_shadows(mat))) {
  2216. can_cast_shadows = false;
  2217. }
  2218. if (mat.is_valid() && RSG::storage->material_is_animated(mat)) {
  2219. is_animated = true;
  2220. }
  2221. if (mat.is_valid()) {
  2222. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2223. }
  2224. if (mat.is_valid()) {
  2225. RSG::storage->material_update_dependency(mat, p_instance);
  2226. }
  2227. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  2228. bool cast_shadows = false;
  2229. int dp = RSG::storage->particles_get_draw_passes(p_instance->base);
  2230. for (int i = 0; i < dp; i++) {
  2231. RID mesh = RSG::storage->particles_get_draw_pass_mesh(p_instance->base, i);
  2232. if (!mesh.is_valid())
  2233. continue;
  2234. int sc = RSG::storage->mesh_get_surface_count(mesh);
  2235. for (int j = 0; j < sc; j++) {
  2236. RID mat = RSG::storage->mesh_surface_get_material(mesh, j);
  2237. if (!mat.is_valid()) {
  2238. cast_shadows = true;
  2239. } else {
  2240. if (RSG::storage->material_casts_shadows(mat)) {
  2241. cast_shadows = true;
  2242. }
  2243. if (RSG::storage->material_is_animated(mat)) {
  2244. is_animated = true;
  2245. }
  2246. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2247. RSG::storage->material_update_dependency(mat, p_instance);
  2248. }
  2249. }
  2250. }
  2251. if (!cast_shadows) {
  2252. can_cast_shadows = false;
  2253. }
  2254. }
  2255. }
  2256. if (can_cast_shadows != geom->can_cast_shadows) {
  2257. //ability to cast shadows change, let lights now
  2258. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  2259. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  2260. light->shadow_dirty = true;
  2261. }
  2262. geom->can_cast_shadows = can_cast_shadows;
  2263. }
  2264. geom->material_is_animated = is_animated;
  2265. p_instance->instance_shader_parameters = isparams;
  2266. if (p_instance->instance_allocated_shader_parameters != (p_instance->instance_shader_parameters.size() > 0)) {
  2267. p_instance->instance_allocated_shader_parameters = (p_instance->instance_shader_parameters.size() > 0);
  2268. if (p_instance->instance_allocated_shader_parameters) {
  2269. p_instance->instance_allocated_shader_parameters_offset = RSG::storage->global_variables_instance_allocate(p_instance->self);
  2270. for (Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter>::Element *E = p_instance->instance_shader_parameters.front(); E; E = E->next()) {
  2271. if (E->get().value.get_type() != Variant::NIL) {
  2272. RSG::storage->global_variables_instance_update(p_instance->self, E->get().index, E->get().value);
  2273. }
  2274. }
  2275. } else {
  2276. RSG::storage->global_variables_instance_free(p_instance->self);
  2277. p_instance->instance_allocated_shader_parameters_offset = -1;
  2278. }
  2279. }
  2280. }
  2281. if (p_instance->skeleton.is_valid()) {
  2282. RSG::storage->skeleton_update_dependency(p_instance->skeleton, p_instance);
  2283. }
  2284. p_instance->clean_up_dependencies();
  2285. }
  2286. _instance_update_list.remove(&p_instance->update_item);
  2287. _update_instance(p_instance);
  2288. p_instance->update_aabb = false;
  2289. p_instance->update_dependencies = false;
  2290. }
  2291. void RenderingServerScene::update_dirty_instances() {
  2292. RSG::storage->update_dirty_resources();
  2293. while (_instance_update_list.first()) {
  2294. _update_dirty_instance(_instance_update_list.first()->self());
  2295. }
  2296. }
  2297. bool RenderingServerScene::free(RID p_rid) {
  2298. if (camera_owner.owns(p_rid)) {
  2299. Camera *camera = camera_owner.getornull(p_rid);
  2300. camera_owner.free(p_rid);
  2301. memdelete(camera);
  2302. } else if (scenario_owner.owns(p_rid)) {
  2303. Scenario *scenario = scenario_owner.getornull(p_rid);
  2304. while (scenario->instances.first()) {
  2305. instance_set_scenario(scenario->instances.first()->self()->self, RID());
  2306. }
  2307. RSG::scene_render->free(scenario->reflection_probe_shadow_atlas);
  2308. RSG::scene_render->free(scenario->reflection_atlas);
  2309. scenario_owner.free(p_rid);
  2310. memdelete(scenario);
  2311. } else if (instance_owner.owns(p_rid)) {
  2312. // delete the instance
  2313. update_dirty_instances();
  2314. Instance *instance = instance_owner.getornull(p_rid);
  2315. instance_set_use_lightmap(p_rid, RID(), RID());
  2316. instance_set_scenario(p_rid, RID());
  2317. instance_set_base(p_rid, RID());
  2318. instance_geometry_set_material_override(p_rid, RID());
  2319. instance_attach_skeleton(p_rid, RID());
  2320. if (instance->instance_allocated_shader_parameters) {
  2321. //free the used shader parameters
  2322. RSG::storage->global_variables_instance_free(instance->self);
  2323. }
  2324. update_dirty_instances(); //in case something changed this
  2325. instance_owner.free(p_rid);
  2326. memdelete(instance);
  2327. } else {
  2328. return false;
  2329. }
  2330. return true;
  2331. }
  2332. RenderingServerScene *RenderingServerScene::singleton = nullptr;
  2333. RenderingServerScene::RenderingServerScene() {
  2334. render_pass = 1;
  2335. singleton = this;
  2336. }
  2337. RenderingServerScene::~RenderingServerScene() {
  2338. }