visual_server_scene.cpp 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916
  1. /*************************************************************************/
  2. /* visual_server_scene.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 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 "visual_server_scene.h"
  31. #include "os/os.h"
  32. #include "visual_server_global.h"
  33. #include "visual_server_raster.h"
  34. /* CAMERA API */
  35. RID VisualServerScene::camera_create() {
  36. Camera *camera = memnew(Camera);
  37. return camera_owner.make_rid(camera);
  38. }
  39. void VisualServerScene::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {
  40. Camera *camera = camera_owner.get(p_camera);
  41. ERR_FAIL_COND(!camera);
  42. camera->type = Camera::PERSPECTIVE;
  43. camera->fov = p_fovy_degrees;
  44. camera->znear = p_z_near;
  45. camera->zfar = p_z_far;
  46. }
  47. void VisualServerScene::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
  48. Camera *camera = camera_owner.get(p_camera);
  49. ERR_FAIL_COND(!camera);
  50. camera->type = Camera::ORTHOGONAL;
  51. camera->size = p_size;
  52. camera->znear = p_z_near;
  53. camera->zfar = p_z_far;
  54. }
  55. void VisualServerScene::camera_set_transform(RID p_camera, const Transform &p_transform) {
  56. Camera *camera = camera_owner.get(p_camera);
  57. ERR_FAIL_COND(!camera);
  58. camera->transform = p_transform.orthonormalized();
  59. }
  60. void VisualServerScene::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {
  61. Camera *camera = camera_owner.get(p_camera);
  62. ERR_FAIL_COND(!camera);
  63. camera->visible_layers = p_layers;
  64. }
  65. void VisualServerScene::camera_set_environment(RID p_camera, RID p_env) {
  66. Camera *camera = camera_owner.get(p_camera);
  67. ERR_FAIL_COND(!camera);
  68. camera->env = p_env;
  69. }
  70. void VisualServerScene::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {
  71. Camera *camera = camera_owner.get(p_camera);
  72. ERR_FAIL_COND(!camera);
  73. camera->vaspect = p_enable;
  74. }
  75. /* SCENARIO API */
  76. void *VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int) {
  77. //VisualServerScene *self = (VisualServerScene*)p_self;
  78. Instance *A = p_A;
  79. Instance *B = p_B;
  80. //instance indices are designed so greater always contains lesser
  81. if (A->base_type > B->base_type) {
  82. SWAP(A, B); //lesser always first
  83. }
  84. if (B->base_type == VS::INSTANCE_LIGHT && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  85. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  86. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  87. InstanceLightData::PairInfo pinfo;
  88. pinfo.geometry = A;
  89. pinfo.L = geom->lighting.push_back(B);
  90. List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo);
  91. if (geom->can_cast_shadows) {
  92. light->shadow_dirty = true;
  93. }
  94. geom->lighting_dirty = true;
  95. return E; //this element should make freeing faster
  96. } else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  97. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  98. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  99. InstanceReflectionProbeData::PairInfo pinfo;
  100. pinfo.geometry = A;
  101. pinfo.L = geom->reflection_probes.push_back(B);
  102. List<InstanceReflectionProbeData::PairInfo>::Element *E = reflection_probe->geometries.push_back(pinfo);
  103. geom->reflection_dirty = true;
  104. return E; //this element should make freeing faster
  105. } else if (B->base_type == VS::INSTANCE_GI_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  106. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  107. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  108. InstanceGIProbeData::PairInfo pinfo;
  109. pinfo.geometry = A;
  110. pinfo.L = geom->gi_probes.push_back(B);
  111. List<InstanceGIProbeData::PairInfo>::Element *E = gi_probe->geometries.push_back(pinfo);
  112. geom->gi_probes_dirty = true;
  113. return E; //this element should make freeing faster
  114. } else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) {
  115. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  116. InstanceLightData *light = static_cast<InstanceLightData *>(A->base_data);
  117. return gi_probe->lights.insert(A);
  118. }
  119. return NULL;
  120. }
  121. void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int, void *udata) {
  122. //VisualServerScene *self = (VisualServerScene*)p_self;
  123. Instance *A = p_A;
  124. Instance *B = p_B;
  125. //instance indices are designed so greater always contains lesser
  126. if (A->base_type > B->base_type) {
  127. SWAP(A, B); //lesser always first
  128. }
  129. if (B->base_type == VS::INSTANCE_LIGHT && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  130. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  131. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  132. List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element *>(udata);
  133. geom->lighting.erase(E->get().L);
  134. light->geometries.erase(E);
  135. if (geom->can_cast_shadows) {
  136. light->shadow_dirty = true;
  137. }
  138. geom->lighting_dirty = true;
  139. } else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  140. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  141. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  142. List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element *>(udata);
  143. geom->reflection_probes.erase(E->get().L);
  144. reflection_probe->geometries.erase(E);
  145. geom->reflection_dirty = true;
  146. } else if (B->base_type == VS::INSTANCE_GI_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  147. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  148. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  149. List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element *>(udata);
  150. geom->gi_probes.erase(E->get().L);
  151. gi_probe->geometries.erase(E);
  152. geom->gi_probes_dirty = true;
  153. } else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) {
  154. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  155. InstanceLightData *light = static_cast<InstanceLightData *>(A->base_data);
  156. Set<Instance *>::Element *E = reinterpret_cast<Set<Instance *>::Element *>(udata);
  157. gi_probe->lights.erase(E);
  158. }
  159. }
  160. RID VisualServerScene::scenario_create() {
  161. Scenario *scenario = memnew(Scenario);
  162. ERR_FAIL_COND_V(!scenario, RID());
  163. RID scenario_rid = scenario_owner.make_rid(scenario);
  164. scenario->self = scenario_rid;
  165. scenario->octree.set_pair_callback(_instance_pair, this);
  166. scenario->octree.set_unpair_callback(_instance_unpair, this);
  167. scenario->reflection_probe_shadow_atlas = VSG::scene_render->shadow_atlas_create();
  168. VSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
  169. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
  170. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
  171. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
  172. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
  173. scenario->reflection_atlas = VSG::scene_render->reflection_atlas_create();
  174. return scenario_rid;
  175. }
  176. void VisualServerScene::scenario_set_debug(RID p_scenario, VS::ScenarioDebugMode p_debug_mode) {
  177. Scenario *scenario = scenario_owner.get(p_scenario);
  178. ERR_FAIL_COND(!scenario);
  179. scenario->debug = p_debug_mode;
  180. }
  181. void VisualServerScene::scenario_set_environment(RID p_scenario, RID p_environment) {
  182. Scenario *scenario = scenario_owner.get(p_scenario);
  183. ERR_FAIL_COND(!scenario);
  184. scenario->environment = p_environment;
  185. }
  186. void VisualServerScene::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {
  187. Scenario *scenario = scenario_owner.get(p_scenario);
  188. ERR_FAIL_COND(!scenario);
  189. scenario->fallback_environment = p_environment;
  190. }
  191. void VisualServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_size, int p_subdiv) {
  192. Scenario *scenario = scenario_owner.get(p_scenario);
  193. ERR_FAIL_COND(!scenario);
  194. VSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas, p_size);
  195. VSG::scene_render->reflection_atlas_set_subdivision(scenario->reflection_atlas, p_subdiv);
  196. }
  197. /* INSTANCING API */
  198. void VisualServerScene::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_materials) {
  199. if (p_update_aabb)
  200. p_instance->update_aabb = true;
  201. if (p_update_materials)
  202. p_instance->update_materials = true;
  203. if (p_instance->update_item.in_list())
  204. return;
  205. _instance_update_list.add(&p_instance->update_item);
  206. }
  207. // from can be mesh, light, area and portal so far.
  208. RID VisualServerScene::instance_create() {
  209. Instance *instance = memnew(Instance);
  210. ERR_FAIL_COND_V(!instance, RID());
  211. RID instance_rid = instance_owner.make_rid(instance);
  212. instance->self = instance_rid;
  213. return instance_rid;
  214. }
  215. void VisualServerScene::instance_set_base(RID p_instance, RID p_base) {
  216. Instance *instance = instance_owner.get(p_instance);
  217. ERR_FAIL_COND(!instance);
  218. Scenario *scenario = instance->scenario;
  219. if (instance->base_type != VS::INSTANCE_NONE) {
  220. //free anything related to that base
  221. VSG::storage->instance_remove_dependency(instance->base, instance);
  222. if (scenario && instance->octree_id) {
  223. scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
  224. instance->octree_id = 0;
  225. }
  226. switch (instance->base_type) {
  227. case VS::INSTANCE_LIGHT: {
  228. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  229. if (instance->scenario && light->D) {
  230. instance->scenario->directional_lights.erase(light->D);
  231. light->D = NULL;
  232. }
  233. VSG::scene_render->free(light->instance);
  234. } break;
  235. case VS::INSTANCE_REFLECTION_PROBE: {
  236. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  237. VSG::scene_render->free(reflection_probe->instance);
  238. if (reflection_probe->update_list.in_list()) {
  239. reflection_probe_render_list.remove(&reflection_probe->update_list);
  240. }
  241. } break;
  242. case VS::INSTANCE_GI_PROBE: {
  243. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  244. while (gi_probe->dynamic.updating_stage == GI_UPDATE_STAGE_LIGHTING) {
  245. //wait until bake is done if it's baking
  246. OS::get_singleton()->delay_usec(1);
  247. }
  248. if (gi_probe->update_element.in_list()) {
  249. gi_probe_update_list.remove(&gi_probe->update_element);
  250. }
  251. if (gi_probe->dynamic.probe_data.is_valid()) {
  252. VSG::storage->free(gi_probe->dynamic.probe_data);
  253. }
  254. VSG::scene_render->free(gi_probe->probe_instance);
  255. } break;
  256. }
  257. if (instance->base_data) {
  258. memdelete(instance->base_data);
  259. instance->base_data = NULL;
  260. }
  261. instance->blend_values.clear();
  262. for (int i = 0; i < instance->materials.size(); i++) {
  263. if (instance->materials[i].is_valid()) {
  264. VSG::storage->material_remove_instance_owner(instance->materials[i], instance);
  265. }
  266. }
  267. instance->materials.clear();
  268. }
  269. instance->base_type = VS::INSTANCE_NONE;
  270. instance->base = RID();
  271. if (p_base.is_valid()) {
  272. instance->base_type = VSG::storage->get_base_type(p_base);
  273. ERR_FAIL_COND(instance->base_type == VS::INSTANCE_NONE);
  274. switch (instance->base_type) {
  275. case VS::INSTANCE_LIGHT: {
  276. InstanceLightData *light = memnew(InstanceLightData);
  277. if (scenario && VSG::storage->light_get_type(p_base) == VS::LIGHT_DIRECTIONAL) {
  278. light->D = scenario->directional_lights.push_back(instance);
  279. }
  280. light->instance = VSG::scene_render->light_instance_create(p_base);
  281. instance->base_data = light;
  282. } break;
  283. case VS::INSTANCE_MESH:
  284. case VS::INSTANCE_MULTIMESH:
  285. case VS::INSTANCE_IMMEDIATE:
  286. case VS::INSTANCE_PARTICLES: {
  287. InstanceGeometryData *geom = memnew(InstanceGeometryData);
  288. instance->base_data = geom;
  289. } break;
  290. case VS::INSTANCE_REFLECTION_PROBE: {
  291. InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
  292. reflection_probe->owner = instance;
  293. instance->base_data = reflection_probe;
  294. reflection_probe->instance = VSG::scene_render->reflection_probe_instance_create(p_base);
  295. } break;
  296. case VS::INSTANCE_GI_PROBE: {
  297. InstanceGIProbeData *gi_probe = memnew(InstanceGIProbeData);
  298. instance->base_data = gi_probe;
  299. gi_probe->owner = instance;
  300. if (scenario && !gi_probe->update_element.in_list()) {
  301. gi_probe_update_list.add(&gi_probe->update_element);
  302. }
  303. gi_probe->probe_instance = VSG::scene_render->gi_probe_instance_create();
  304. } break;
  305. }
  306. VSG::storage->instance_add_dependency(p_base, instance);
  307. instance->base = p_base;
  308. if (scenario)
  309. _instance_queue_update(instance, true, true);
  310. }
  311. }
  312. void VisualServerScene::instance_set_scenario(RID p_instance, RID p_scenario) {
  313. Instance *instance = instance_owner.get(p_instance);
  314. ERR_FAIL_COND(!instance);
  315. if (instance->scenario) {
  316. instance->scenario->instances.remove(&instance->scenario_item);
  317. if (instance->octree_id) {
  318. instance->scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
  319. instance->octree_id = 0;
  320. }
  321. switch (instance->base_type) {
  322. case VS::INSTANCE_LIGHT: {
  323. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  324. if (light->D) {
  325. instance->scenario->directional_lights.erase(light->D);
  326. light->D = NULL;
  327. }
  328. } break;
  329. case VS::INSTANCE_REFLECTION_PROBE: {
  330. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  331. VSG::scene_render->reflection_probe_release_atlas_index(reflection_probe->instance);
  332. } break;
  333. case VS::INSTANCE_GI_PROBE: {
  334. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  335. if (gi_probe->update_element.in_list()) {
  336. gi_probe_update_list.remove(&gi_probe->update_element);
  337. }
  338. } break;
  339. }
  340. instance->scenario = NULL;
  341. }
  342. if (p_scenario.is_valid()) {
  343. Scenario *scenario = scenario_owner.get(p_scenario);
  344. ERR_FAIL_COND(!scenario);
  345. instance->scenario = scenario;
  346. scenario->instances.add(&instance->scenario_item);
  347. switch (instance->base_type) {
  348. case VS::INSTANCE_LIGHT: {
  349. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  350. if (VSG::storage->light_get_type(instance->base) == VS::LIGHT_DIRECTIONAL) {
  351. light->D = scenario->directional_lights.push_back(instance);
  352. }
  353. } break;
  354. case VS::INSTANCE_GI_PROBE: {
  355. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  356. if (!gi_probe->update_element.in_list()) {
  357. gi_probe_update_list.add(&gi_probe->update_element);
  358. }
  359. } break;
  360. }
  361. _instance_queue_update(instance, true, true);
  362. }
  363. }
  364. void VisualServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {
  365. Instance *instance = instance_owner.get(p_instance);
  366. ERR_FAIL_COND(!instance);
  367. instance->layer_mask = p_mask;
  368. }
  369. void VisualServerScene::instance_set_transform(RID p_instance, const Transform &p_transform) {
  370. Instance *instance = instance_owner.get(p_instance);
  371. ERR_FAIL_COND(!instance);
  372. if (instance->transform == p_transform)
  373. return; //must be checked to avoid worst evil
  374. instance->transform = p_transform;
  375. _instance_queue_update(instance, true);
  376. }
  377. void VisualServerScene::instance_attach_object_instance_id(RID p_instance, ObjectID p_ID) {
  378. Instance *instance = instance_owner.get(p_instance);
  379. ERR_FAIL_COND(!instance);
  380. instance->object_ID = p_ID;
  381. }
  382. void VisualServerScene::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {
  383. Instance *instance = instance_owner.get(p_instance);
  384. ERR_FAIL_COND(!instance);
  385. if (instance->update_item.in_list()) {
  386. _update_dirty_instance(instance);
  387. }
  388. ERR_FAIL_INDEX(p_shape, instance->blend_values.size());
  389. instance->blend_values[p_shape] = p_weight;
  390. }
  391. void VisualServerScene::instance_set_surface_material(RID p_instance, int p_surface, RID p_material) {
  392. Instance *instance = instance_owner.get(p_instance);
  393. ERR_FAIL_COND(!instance);
  394. if (instance->update_item.in_list()) {
  395. _update_dirty_instance(instance);
  396. }
  397. ERR_FAIL_INDEX(p_surface, instance->materials.size());
  398. if (instance->materials[p_surface].is_valid()) {
  399. VSG::storage->material_remove_instance_owner(instance->materials[p_surface], instance);
  400. }
  401. instance->materials[p_surface] = p_material;
  402. instance->base_material_changed();
  403. if (instance->materials[p_surface].is_valid()) {
  404. VSG::storage->material_add_instance_owner(instance->materials[p_surface], instance);
  405. }
  406. }
  407. void VisualServerScene::instance_set_visible(RID p_instance, bool p_visible) {
  408. Instance *instance = instance_owner.get(p_instance);
  409. ERR_FAIL_COND(!instance);
  410. if (instance->visible == p_visible)
  411. return;
  412. instance->visible = p_visible;
  413. switch (instance->base_type) {
  414. case VS::INSTANCE_LIGHT: {
  415. if (VSG::storage->light_get_type(instance->base) != VS::LIGHT_DIRECTIONAL && instance->octree_id && instance->scenario) {
  416. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_LIGHT, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
  417. }
  418. } break;
  419. case VS::INSTANCE_REFLECTION_PROBE: {
  420. if (instance->octree_id && instance->scenario) {
  421. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_REFLECTION_PROBE, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
  422. }
  423. } break;
  424. case VS::INSTANCE_GI_PROBE: {
  425. if (instance->octree_id && instance->scenario) {
  426. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_GI_PROBE, p_visible ? (VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT)) : 0);
  427. }
  428. } break;
  429. }
  430. }
  431. void VisualServerScene::instance_attach_skeleton(RID p_instance, RID p_skeleton) {
  432. Instance *instance = instance_owner.get(p_instance);
  433. ERR_FAIL_COND(!instance);
  434. if (instance->skeleton == p_skeleton)
  435. return;
  436. if (instance->skeleton.is_valid()) {
  437. VSG::storage->instance_remove_skeleton(instance->skeleton, instance);
  438. }
  439. instance->skeleton = p_skeleton;
  440. if (instance->skeleton.is_valid()) {
  441. VSG::storage->instance_add_skeleton(instance->skeleton, instance);
  442. }
  443. _instance_queue_update(instance, true);
  444. }
  445. void VisualServerScene::instance_set_exterior(RID p_instance, bool p_enabled) {
  446. }
  447. void VisualServerScene::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
  448. }
  449. Vector<ObjectID> VisualServerScene::instances_cull_aabb(const Rect3 &p_aabb, RID p_scenario) const {
  450. Vector<ObjectID> instances;
  451. Scenario *scenario = scenario_owner.get(p_scenario);
  452. ERR_FAIL_COND_V(!scenario, instances);
  453. const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  454. int culled = 0;
  455. Instance *cull[1024];
  456. culled = scenario->octree.cull_aabb(p_aabb, cull, 1024);
  457. for (int i = 0; i < culled; i++) {
  458. Instance *instance = cull[i];
  459. ERR_CONTINUE(!instance);
  460. if (instance->object_ID == 0)
  461. continue;
  462. instances.push_back(instance->object_ID);
  463. }
  464. return instances;
  465. }
  466. Vector<ObjectID> VisualServerScene::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
  467. Vector<ObjectID> instances;
  468. Scenario *scenario = scenario_owner.get(p_scenario);
  469. ERR_FAIL_COND_V(!scenario, instances);
  470. const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  471. int culled = 0;
  472. Instance *cull[1024];
  473. culled = scenario->octree.cull_segment(p_from, p_to * 10000, cull, 1024);
  474. for (int i = 0; i < culled; i++) {
  475. Instance *instance = cull[i];
  476. ERR_CONTINUE(!instance);
  477. if (instance->object_ID == 0)
  478. continue;
  479. instances.push_back(instance->object_ID);
  480. }
  481. return instances;
  482. }
  483. Vector<ObjectID> VisualServerScene::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {
  484. Vector<ObjectID> instances;
  485. Scenario *scenario = scenario_owner.get(p_scenario);
  486. ERR_FAIL_COND_V(!scenario, instances);
  487. const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  488. int culled = 0;
  489. Instance *cull[1024];
  490. culled = scenario->octree.cull_convex(p_convex, cull, 1024);
  491. for (int i = 0; i < culled; i++) {
  492. Instance *instance = cull[i];
  493. ERR_CONTINUE(!instance);
  494. if (instance->object_ID == 0)
  495. continue;
  496. instances.push_back(instance->object_ID);
  497. }
  498. return instances;
  499. }
  500. void VisualServerScene::instance_geometry_set_flag(RID p_instance, VS::InstanceFlags p_flags, bool p_enabled) {
  501. Instance *instance = instance_owner.get(p_instance);
  502. ERR_FAIL_COND(!instance);
  503. switch (p_flags) {
  504. case VS::INSTANCE_FLAG_USE_BAKED_LIGHT: {
  505. instance->baked_light = p_enabled;
  506. } break;
  507. }
  508. }
  509. void VisualServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting) {
  510. Instance *instance = instance_owner.get(p_instance);
  511. ERR_FAIL_COND(!instance);
  512. instance->cast_shadows = p_shadow_casting_setting;
  513. instance->base_material_changed(); // to actually compute if shadows are visible or not
  514. }
  515. void VisualServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material) {
  516. Instance *instance = instance_owner.get(p_instance);
  517. ERR_FAIL_COND(!instance);
  518. if (instance->material_override.is_valid()) {
  519. VSG::storage->material_remove_instance_owner(instance->material_override, instance);
  520. }
  521. instance->material_override = p_material;
  522. instance->base_material_changed();
  523. if (instance->material_override.is_valid()) {
  524. VSG::storage->material_add_instance_owner(instance->material_override, instance);
  525. }
  526. }
  527. void VisualServerScene::instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) {
  528. }
  529. void VisualServerScene::instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) {
  530. }
  531. void VisualServerScene::_update_instance(Instance *p_instance) {
  532. p_instance->version++;
  533. if (p_instance->base_type == VS::INSTANCE_LIGHT) {
  534. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  535. VSG::scene_render->light_instance_set_transform(light->instance, p_instance->transform);
  536. light->shadow_dirty = true;
  537. }
  538. if (p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) {
  539. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  540. VSG::scene_render->reflection_probe_instance_set_transform(reflection_probe->instance, p_instance->transform);
  541. reflection_probe->reflection_dirty = true;
  542. }
  543. if (p_instance->base_type == VS::INSTANCE_PARTICLES) {
  544. VSG::storage->particles_set_emission_transform(p_instance->base, p_instance->transform);
  545. }
  546. if (p_instance->aabb.has_no_surface()) {
  547. return;
  548. }
  549. if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  550. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  551. //make sure lights are updated if it casts shadow
  552. if (geom->can_cast_shadows) {
  553. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  554. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  555. light->shadow_dirty = true;
  556. }
  557. }
  558. }
  559. p_instance->mirror = p_instance->transform.basis.determinant() < 0.0;
  560. Rect3 new_aabb;
  561. new_aabb = p_instance->transform.xform(p_instance->aabb);
  562. p_instance->transformed_aabb = new_aabb;
  563. if (!p_instance->scenario) {
  564. return;
  565. }
  566. if (p_instance->octree_id == 0) {
  567. uint32_t base_type = 1 << p_instance->base_type;
  568. uint32_t pairable_mask = 0;
  569. bool pairable = false;
  570. if (p_instance->base_type == VS::INSTANCE_LIGHT || p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) {
  571. pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK : 0;
  572. pairable = true;
  573. }
  574. if (p_instance->base_type == VS::INSTANCE_GI_PROBE) {
  575. //lights and geometries
  576. pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT) : 0;
  577. pairable = true;
  578. }
  579. // not inside octree
  580. p_instance->octree_id = p_instance->scenario->octree.create(p_instance, new_aabb, 0, pairable, base_type, pairable_mask);
  581. } else {
  582. /*
  583. if (new_aabb==p_instance->data.transformed_aabb)
  584. return;
  585. */
  586. p_instance->scenario->octree.move(p_instance->octree_id, new_aabb);
  587. }
  588. }
  589. void VisualServerScene::_update_instance_aabb(Instance *p_instance) {
  590. Rect3 new_aabb;
  591. ERR_FAIL_COND(p_instance->base_type != VS::INSTANCE_NONE && !p_instance->base.is_valid());
  592. switch (p_instance->base_type) {
  593. case VisualServer::INSTANCE_NONE: {
  594. // do nothing
  595. } break;
  596. case VisualServer::INSTANCE_MESH: {
  597. new_aabb = VSG::storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);
  598. } break;
  599. case VisualServer::INSTANCE_MULTIMESH: {
  600. new_aabb = VSG::storage->multimesh_get_aabb(p_instance->base);
  601. } break;
  602. case VisualServer::INSTANCE_IMMEDIATE: {
  603. new_aabb = VSG::storage->immediate_get_aabb(p_instance->base);
  604. } break;
  605. case VisualServer::INSTANCE_PARTICLES: {
  606. new_aabb = VSG::storage->particles_get_aabb(p_instance->base);
  607. } break;
  608. case VisualServer::INSTANCE_LIGHT: {
  609. new_aabb = VSG::storage->light_get_aabb(p_instance->base);
  610. } break;
  611. case VisualServer::INSTANCE_REFLECTION_PROBE: {
  612. new_aabb = VSG::storage->reflection_probe_get_aabb(p_instance->base);
  613. } break;
  614. case VisualServer::INSTANCE_GI_PROBE: {
  615. new_aabb = VSG::storage->gi_probe_get_bounds(p_instance->base);
  616. } break;
  617. default: {}
  618. }
  619. if (p_instance->extra_margin)
  620. new_aabb.grow_by(p_instance->extra_margin);
  621. p_instance->aabb = new_aabb;
  622. }
  623. void VisualServerScene::_light_instance_update_shadow(Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_shadow_atlas, Scenario *p_scenario) {
  624. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  625. switch (VSG::storage->light_get_type(p_instance->base)) {
  626. case VS::LIGHT_DIRECTIONAL: {
  627. float max_distance = p_cam_projection.get_z_far();
  628. float shadow_max = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
  629. if (shadow_max > 0) {
  630. max_distance = MIN(shadow_max, max_distance);
  631. }
  632. max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
  633. float range = max_distance - p_cam_projection.get_z_near();
  634. int splits = 0;
  635. switch (VSG::storage->light_directional_get_shadow_mode(p_instance->base)) {
  636. case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: splits = 1; break;
  637. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: splits = 2; break;
  638. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: splits = 4; break;
  639. }
  640. float distances[5];
  641. distances[0] = p_cam_projection.get_z_near();
  642. for (int i = 0; i < splits; i++) {
  643. distances[i + 1] = p_cam_projection.get_z_near() + VSG::storage->light_get_param(p_instance->base, VS::LightParam(VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
  644. };
  645. distances[splits] = max_distance;
  646. float texture_size = VSG::scene_render->get_directional_light_shadow_size(light->instance);
  647. bool overlap = VSG::storage->light_directional_get_blend_splits(p_instance->base);
  648. float first_radius = 0.0;
  649. for (int i = 0; i < splits; i++) {
  650. // setup a camera matrix for that range!
  651. CameraMatrix camera_matrix;
  652. float aspect = p_cam_projection.get_aspect();
  653. if (p_cam_orthogonal) {
  654. float w, h;
  655. p_cam_projection.get_viewport_size(w, h);
  656. camera_matrix.set_orthogonal(w, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  657. } else {
  658. float fov = p_cam_projection.get_fov();
  659. camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  660. }
  661. //obtain the frustum endpoints
  662. Vector3 endpoints[8]; // frustum plane endpoints
  663. bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
  664. ERR_CONTINUE(!res);
  665. // obtain the light frustm ranges (given endpoints)
  666. Transform transform = p_instance->transform.orthonormalized(); //discard scale and stabilize light
  667. Vector3 x_vec = transform.basis.get_axis(Vector3::AXIS_X).normalized();
  668. Vector3 y_vec = transform.basis.get_axis(Vector3::AXIS_Y).normalized();
  669. Vector3 z_vec = transform.basis.get_axis(Vector3::AXIS_Z).normalized();
  670. //z_vec points agsint the camera, like in default opengl
  671. float x_min, x_max;
  672. float y_min, y_max;
  673. float z_min, z_max;
  674. float x_min_cam, x_max_cam;
  675. float y_min_cam, y_max_cam;
  676. float z_min_cam, z_max_cam;
  677. float bias_scale = 1.0;
  678. //used for culling
  679. for (int j = 0; j < 8; j++) {
  680. float d_x = x_vec.dot(endpoints[j]);
  681. float d_y = y_vec.dot(endpoints[j]);
  682. float d_z = z_vec.dot(endpoints[j]);
  683. if (j == 0 || d_x < x_min)
  684. x_min = d_x;
  685. if (j == 0 || d_x > x_max)
  686. x_max = d_x;
  687. if (j == 0 || d_y < y_min)
  688. y_min = d_y;
  689. if (j == 0 || d_y > y_max)
  690. y_max = d_y;
  691. if (j == 0 || d_z < z_min)
  692. z_min = d_z;
  693. if (j == 0 || d_z > z_max)
  694. z_max = d_z;
  695. }
  696. {
  697. //camera viewport stuff
  698. //this trick here is what stabilizes the shadow (make potential jaggies to not move)
  699. //at the cost of some wasted resolution. Still the quality increase is very well worth it
  700. Vector3 center;
  701. for (int j = 0; j < 8; j++) {
  702. center += endpoints[j];
  703. }
  704. center /= 8.0;
  705. //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;
  706. float radius = 0;
  707. for (int j = 0; j < 8; j++) {
  708. float d = center.distance_to(endpoints[j]);
  709. if (d > radius)
  710. radius = d;
  711. }
  712. radius *= texture_size / (texture_size - 2.0); //add a texel by each side, so stepified texture will always fit
  713. if (i == 0) {
  714. first_radius = radius;
  715. } else {
  716. bias_scale = radius / first_radius;
  717. }
  718. x_max_cam = x_vec.dot(center) + radius;
  719. x_min_cam = x_vec.dot(center) - radius;
  720. y_max_cam = y_vec.dot(center) + radius;
  721. y_min_cam = y_vec.dot(center) - radius;
  722. z_max_cam = z_vec.dot(center) + radius;
  723. z_min_cam = z_vec.dot(center) - radius;
  724. float unit = radius * 2.0 / texture_size;
  725. x_max_cam = Math::stepify(x_max_cam, unit);
  726. x_min_cam = Math::stepify(x_min_cam, unit);
  727. y_max_cam = Math::stepify(y_max_cam, unit);
  728. y_min_cam = Math::stepify(y_min_cam, unit);
  729. }
  730. //now that we now all ranges, we can proceed to make the light frustum planes, for culling octree
  731. Vector<Plane> light_frustum_planes;
  732. light_frustum_planes.resize(6);
  733. //right/left
  734. light_frustum_planes[0] = Plane(x_vec, x_max);
  735. light_frustum_planes[1] = Plane(-x_vec, -x_min);
  736. //top/bottom
  737. light_frustum_planes[2] = Plane(y_vec, y_max);
  738. light_frustum_planes[3] = Plane(-y_vec, -y_min);
  739. //near/far
  740. light_frustum_planes[4] = Plane(z_vec, z_max + 1e6);
  741. light_frustum_planes[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed
  742. int cull_count = p_scenario->octree.cull_convex(light_frustum_planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  743. // a pre pass will need to be needed to determine the actual z-near to be used
  744. Plane near_plane(p_instance->transform.origin, -p_instance->transform.basis.get_axis(2));
  745. for (int j = 0; j < cull_count; j++) {
  746. float min, max;
  747. Instance *instance = instance_shadow_cull_result[j];
  748. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  749. cull_count--;
  750. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  751. j--;
  752. continue;
  753. }
  754. instance->transformed_aabb.project_range_in_plane(Plane(z_vec, 0), min, max);
  755. instance->depth = near_plane.distance_to(instance->transform.origin);
  756. instance->depth_layer = 0;
  757. if (max > z_max)
  758. z_max = max;
  759. }
  760. {
  761. CameraMatrix ortho_camera;
  762. real_t half_x = (x_max_cam - x_min_cam) * 0.5;
  763. real_t half_y = (y_max_cam - y_min_cam) * 0.5;
  764. ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));
  765. Transform ortho_transform;
  766. ortho_transform.basis = transform.basis;
  767. ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;
  768. VSG::scene_render->light_instance_set_shadow_transform(light->instance, ortho_camera, ortho_transform, 0, distances[i + 1], i, bias_scale);
  769. }
  770. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  771. }
  772. } break;
  773. case VS::LIGHT_OMNI: {
  774. VS::LightOmniShadowMode shadow_mode = VSG::storage->light_omni_get_shadow_mode(p_instance->base);
  775. switch (shadow_mode) {
  776. case VS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID: {
  777. for (int i = 0; i < 2; i++) {
  778. //using this one ensures that raster deferred will have it
  779. float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
  780. float z = i == 0 ? -1 : 1;
  781. Vector<Plane> planes;
  782. planes.resize(5);
  783. planes[0] = p_instance->transform.xform(Plane(Vector3(0, 0, z), radius));
  784. planes[1] = p_instance->transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
  785. planes[2] = p_instance->transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
  786. planes[3] = p_instance->transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
  787. planes[4] = p_instance->transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));
  788. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  789. Plane near_plane(p_instance->transform.origin, p_instance->transform.basis.get_axis(2) * z);
  790. for (int j = 0; j < cull_count; j++) {
  791. Instance *instance = instance_shadow_cull_result[j];
  792. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  793. cull_count--;
  794. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  795. j--;
  796. } else {
  797. instance->depth = near_plane.distance_to(instance->transform.origin);
  798. instance->depth_layer = 0;
  799. }
  800. }
  801. VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), p_instance->transform, radius, 0, i);
  802. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  803. }
  804. } break;
  805. case VS::LIGHT_OMNI_SHADOW_CUBE: {
  806. float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
  807. CameraMatrix cm;
  808. cm.set_perspective(90, 1, 0.01, radius);
  809. for (int i = 0; i < 6; i++) {
  810. //using this one ensures that raster deferred will have it
  811. static const Vector3 view_normals[6] = {
  812. Vector3(-1, 0, 0),
  813. Vector3(+1, 0, 0),
  814. Vector3(0, -1, 0),
  815. Vector3(0, +1, 0),
  816. Vector3(0, 0, -1),
  817. Vector3(0, 0, +1)
  818. };
  819. static const Vector3 view_up[6] = {
  820. Vector3(0, -1, 0),
  821. Vector3(0, -1, 0),
  822. Vector3(0, 0, -1),
  823. Vector3(0, 0, +1),
  824. Vector3(0, -1, 0),
  825. Vector3(0, -1, 0)
  826. };
  827. Transform xform = p_instance->transform * Transform().looking_at(view_normals[i], view_up[i]);
  828. Vector<Plane> planes = cm.get_projection_planes(xform);
  829. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  830. Plane near_plane(xform.origin, -xform.basis.get_axis(2));
  831. for (int j = 0; j < cull_count; j++) {
  832. Instance *instance = instance_shadow_cull_result[j];
  833. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  834. cull_count--;
  835. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  836. j--;
  837. } else {
  838. instance->depth = near_plane.distance_to(instance->transform.origin);
  839. instance->depth_layer = 0;
  840. }
  841. }
  842. VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i);
  843. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  844. }
  845. //restore the regular DP matrix
  846. VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), p_instance->transform, radius, 0, 0);
  847. } break;
  848. }
  849. } break;
  850. case VS::LIGHT_SPOT: {
  851. float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
  852. float angle = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  853. CameraMatrix cm;
  854. cm.set_perspective(angle * 2.0, 1.0, 0.01, radius);
  855. Vector<Plane> planes = cm.get_projection_planes(p_instance->transform);
  856. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  857. Plane near_plane(p_instance->transform.origin, -p_instance->transform.basis.get_axis(2));
  858. for (int j = 0; j < cull_count; j++) {
  859. Instance *instance = instance_shadow_cull_result[j];
  860. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  861. cull_count--;
  862. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  863. j--;
  864. } else {
  865. instance->depth = near_plane.distance_to(instance->transform.origin);
  866. instance->depth_layer = 0;
  867. }
  868. }
  869. VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, p_instance->transform, radius, 0, 0);
  870. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, 0, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  871. } break;
  872. }
  873. }
  874. void VisualServerScene::render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
  875. // render to mono camera
  876. Camera *camera = camera_owner.getornull(p_camera);
  877. ERR_FAIL_COND(!camera);
  878. /* STEP 1 - SETUP CAMERA */
  879. CameraMatrix camera_matrix;
  880. bool ortho = false;
  881. switch (camera->type) {
  882. case Camera::ORTHOGONAL: {
  883. camera_matrix.set_orthogonal(
  884. camera->size,
  885. p_viewport_size.width / (float)p_viewport_size.height,
  886. camera->znear,
  887. camera->zfar,
  888. camera->vaspect
  889. );
  890. ortho = true;
  891. } break;
  892. case Camera::PERSPECTIVE: {
  893. camera_matrix.set_perspective(
  894. camera->fov,
  895. p_viewport_size.width / (float)p_viewport_size.height,
  896. camera->znear,
  897. camera->zfar,
  898. camera->vaspect
  899. );
  900. ortho = false;
  901. } break;
  902. }
  903. _render_scene(camera->transform, camera_matrix, ortho, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), -1);
  904. }
  905. void VisualServerScene::render_camera(Ref<ARVRInterface> &p_interface, ARVRInterface::Eyes p_eye, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
  906. // render for AR/VR interface
  907. Camera *camera = camera_owner.getornull(p_camera);
  908. ERR_FAIL_COND(!camera);
  909. /* SETUP CAMERA, we are ignoring type and FOV here */
  910. bool ortho = false;
  911. float aspect = p_viewport_size.width / (float)p_viewport_size.height;
  912. CameraMatrix camera_matrix = p_interface->get_projection_for_eye(p_eye, aspect, camera->znear, camera->zfar);
  913. // We also ignore our camera position, it will have been positioned with a slightly old tracking position.
  914. // Instead we take our origin point and have our ar/vr interface add fresh tracking data! Whoohoo!
  915. Transform world_origin = ARVRServer::get_singleton()->get_world_origin();
  916. Transform cam_transform = p_interface->get_transform_for_eye(p_eye, world_origin);
  917. _render_scene(cam_transform, camera_matrix, ortho, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), -1);
  918. };
  919. void VisualServerScene::_render_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {
  920. Scenario *scenario = scenario_owner.getornull(p_scenario);
  921. render_pass++;
  922. uint32_t camera_layer_mask = p_visible_layers;
  923. VSG::scene_render->set_scene_pass(render_pass);
  924. //rasterizer->set_camera(camera->transform, camera_matrix,ortho);
  925. Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
  926. Plane near_plane(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2).normalized());
  927. float z_far = p_cam_projection.get_z_far();
  928. /* STEP 2 - CULL */
  929. int cull_count = scenario->octree.cull_convex(planes, instance_cull_result, MAX_INSTANCE_CULL);
  930. light_cull_count = 0;
  931. reflection_probe_cull_count = 0;
  932. //light_samplers_culled=0;
  933. /* print_line("OT: "+rtos( (OS::get_singleton()->get_ticks_usec()-t)/1000.0));
  934. print_line("OTO: "+itos(p_scenario->octree.get_octant_count()));
  935. //print_line("OTE: "+itos(p_scenario->octree.get_elem_count()));
  936. print_line("OTP: "+itos(p_scenario->octree.get_pair_count()));
  937. */
  938. /* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */
  939. //removed, will replace with culling
  940. /* STEP 4 - REMOVE FURTHER CULLED OBJECTS, ADD LIGHTS */
  941. for (int i = 0; i < cull_count; i++) {
  942. Instance *ins = instance_cull_result[i];
  943. bool keep = false;
  944. if ((camera_layer_mask & ins->layer_mask) == 0) {
  945. //failure
  946. } else if (ins->base_type == VS::INSTANCE_LIGHT && ins->visible) {
  947. if (ins->visible && light_cull_count < MAX_LIGHTS_CULLED) {
  948. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  949. if (!light->geometries.empty()) {
  950. //do not add this light if no geometry is affected by it..
  951. light_cull_result[light_cull_count] = ins;
  952. light_instance_cull_result[light_cull_count] = light->instance;
  953. if (p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(ins->base)) {
  954. VSG::scene_render->light_instance_mark_visible(light->instance); //mark it visible for shadow allocation later
  955. }
  956. light_cull_count++;
  957. }
  958. }
  959. } else if (ins->base_type == VS::INSTANCE_REFLECTION_PROBE && ins->visible) {
  960. if (ins->visible && reflection_probe_cull_count < MAX_REFLECTION_PROBES_CULLED) {
  961. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(ins->base_data);
  962. if (p_reflection_probe != reflection_probe->instance) {
  963. //avoid entering The Matrix
  964. if (!reflection_probe->geometries.empty()) {
  965. //do not add this light if no geometry is affected by it..
  966. if (reflection_probe->reflection_dirty || VSG::scene_render->reflection_probe_instance_needs_redraw(reflection_probe->instance)) {
  967. if (!reflection_probe->update_list.in_list()) {
  968. reflection_probe->render_step = 0;
  969. reflection_probe_render_list.add_last(&reflection_probe->update_list);
  970. }
  971. reflection_probe->reflection_dirty = false;
  972. }
  973. if (VSG::scene_render->reflection_probe_instance_has_reflection(reflection_probe->instance)) {
  974. reflection_probe_instance_cull_result[reflection_probe_cull_count] = reflection_probe->instance;
  975. reflection_probe_cull_count++;
  976. }
  977. }
  978. }
  979. }
  980. } else if (ins->base_type == VS::INSTANCE_GI_PROBE && ins->visible) {
  981. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(ins->base_data);
  982. if (!gi_probe->update_element.in_list()) {
  983. gi_probe_update_list.add(&gi_probe->update_element);
  984. }
  985. } else if ((1 << ins->base_type) & VS::INSTANCE_GEOMETRY_MASK && ins->visible && ins->cast_shadows != VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  986. keep = true;
  987. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(ins->base_data);
  988. if (ins->base_type == VS::INSTANCE_PARTICLES) {
  989. //particles visible? process them
  990. VSG::storage->particles_request_process(ins->base);
  991. //particles visible? request redraw
  992. VisualServerRaster::redraw_request();
  993. }
  994. if (geom->lighting_dirty) {
  995. int l = 0;
  996. //only called when lights AABB enter/exit this geometry
  997. ins->light_instances.resize(geom->lighting.size());
  998. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  999. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  1000. ins->light_instances[l++] = light->instance;
  1001. }
  1002. geom->lighting_dirty = false;
  1003. }
  1004. if (geom->reflection_dirty) {
  1005. int l = 0;
  1006. //only called when reflection probe AABB enter/exit this geometry
  1007. ins->reflection_probe_instances.resize(geom->reflection_probes.size());
  1008. for (List<Instance *>::Element *E = geom->reflection_probes.front(); E; E = E->next()) {
  1009. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->get()->base_data);
  1010. ins->reflection_probe_instances[l++] = reflection_probe->instance;
  1011. }
  1012. geom->reflection_dirty = false;
  1013. }
  1014. if (geom->gi_probes_dirty) {
  1015. int l = 0;
  1016. //only called when reflection probe AABB enter/exit this geometry
  1017. ins->gi_probe_instances.resize(geom->gi_probes.size());
  1018. for (List<Instance *>::Element *E = geom->gi_probes.front(); E; E = E->next()) {
  1019. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(E->get()->base_data);
  1020. ins->gi_probe_instances[l++] = gi_probe->probe_instance;
  1021. }
  1022. geom->gi_probes_dirty = false;
  1023. }
  1024. ins->depth = near_plane.distance_to(ins->transform.origin);
  1025. ins->depth_layer = CLAMP(int(ins->depth * 16 / z_far), 0, 15);
  1026. }
  1027. if (!keep) {
  1028. // remove, no reason to keep
  1029. cull_count--;
  1030. SWAP(instance_cull_result[i], instance_cull_result[cull_count]);
  1031. i--;
  1032. ins->last_render_pass = 0; // make invalid
  1033. } else {
  1034. ins->last_render_pass = render_pass;
  1035. }
  1036. }
  1037. /* STEP 5 - PROCESS LIGHTS */
  1038. RID *directional_light_ptr = &light_instance_cull_result[light_cull_count];
  1039. int directional_light_count = 0;
  1040. // directional lights
  1041. {
  1042. Instance **lights_with_shadow = (Instance **)alloca(sizeof(Instance *) * scenario->directional_lights.size());
  1043. int directional_shadow_count = 0;
  1044. for (List<Instance *>::Element *E = scenario->directional_lights.front(); E; E = E->next()) {
  1045. if (light_cull_count + directional_light_count >= MAX_LIGHTS_CULLED) {
  1046. break;
  1047. }
  1048. if (!E->get()->visible)
  1049. continue;
  1050. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  1051. //check shadow..
  1052. if (light) {
  1053. if (p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(E->get()->base)) {
  1054. lights_with_shadow[directional_shadow_count++] = E->get();
  1055. }
  1056. //add to list
  1057. directional_light_ptr[directional_light_count++] = light->instance;
  1058. }
  1059. }
  1060. VSG::scene_render->set_directional_shadow_count(directional_shadow_count);
  1061. for (int i = 0; i < directional_shadow_count; i++) {
  1062. _light_instance_update_shadow(lights_with_shadow[i], p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario);
  1063. }
  1064. }
  1065. { //setup shadow maps
  1066. //SortArray<Instance*,_InstanceLightsort> sorter;
  1067. //sorter.sort(light_cull_result,light_cull_count);
  1068. for (int i = 0; i < light_cull_count; i++) {
  1069. Instance *ins = light_cull_result[i];
  1070. if (!p_shadow_atlas.is_valid() || !VSG::storage->light_has_shadow(ins->base))
  1071. continue;
  1072. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  1073. float coverage;
  1074. { //compute coverage
  1075. Transform cam_xf = p_cam_transform;
  1076. float zn = p_cam_projection.get_z_near();
  1077. Plane p(cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2)); //camera near plane
  1078. float vp_w, vp_h; //near plane size in screen coordinates
  1079. p_cam_projection.get_viewport_size(vp_w, vp_h);
  1080. switch (VSG::storage->light_get_type(ins->base)) {
  1081. case VS::LIGHT_OMNI: {
  1082. float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE);
  1083. //get two points parallel to near plane
  1084. Vector3 points[2] = {
  1085. ins->transform.origin,
  1086. ins->transform.origin + cam_xf.basis.get_axis(0) * radius
  1087. };
  1088. if (!p_cam_orthogonal) {
  1089. //if using perspetive, map them to near plane
  1090. for (int j = 0; j < 2; j++) {
  1091. if (p.distance_to(points[j]) < 0) {
  1092. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  1093. }
  1094. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  1095. }
  1096. }
  1097. float screen_diameter = points[0].distance_to(points[1]) * 2;
  1098. coverage = screen_diameter / (vp_w + vp_h);
  1099. } break;
  1100. case VS::LIGHT_SPOT: {
  1101. float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE);
  1102. float angle = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  1103. float w = radius * Math::sin(Math::deg2rad(angle));
  1104. float d = radius * Math::cos(Math::deg2rad(angle));
  1105. Vector3 base = ins->transform.origin - ins->transform.basis.get_axis(2).normalized() * d;
  1106. Vector3 points[2] = {
  1107. base,
  1108. base + cam_xf.basis.get_axis(0) * w
  1109. };
  1110. if (!p_cam_orthogonal) {
  1111. //if using perspetive, map them to near plane
  1112. for (int j = 0; j < 2; j++) {
  1113. if (p.distance_to(points[j]) < 0) {
  1114. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  1115. }
  1116. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  1117. }
  1118. }
  1119. float screen_diameter = points[0].distance_to(points[1]) * 2;
  1120. coverage = screen_diameter / (vp_w + vp_h);
  1121. } break;
  1122. default: {
  1123. ERR_PRINT("Invalid Light Type");
  1124. }
  1125. }
  1126. }
  1127. if (light->shadow_dirty) {
  1128. light->last_version++;
  1129. light->shadow_dirty = false;
  1130. }
  1131. bool redraw = VSG::scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
  1132. if (redraw) {
  1133. //must redraw!
  1134. _light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario);
  1135. }
  1136. }
  1137. }
  1138. /* ENVIRONMENT */
  1139. RID environment;
  1140. if (p_force_environment.is_valid()) //camera has more environment priority
  1141. environment = p_force_environment;
  1142. else if (scenario->environment.is_valid())
  1143. environment = scenario->environment;
  1144. else
  1145. environment = scenario->fallback_environment;
  1146. /* STEP 6 - PROCESS GEOMETRY AND DRAW SCENE*/
  1147. VSG::scene_render->render_scene(p_cam_transform, p_cam_projection, p_cam_orthogonal, (RasterizerScene::InstanceBase **)instance_cull_result, cull_count, light_instance_cull_result, light_cull_count + directional_light_count, reflection_probe_instance_cull_result, reflection_probe_cull_count, environment, p_shadow_atlas, scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass);
  1148. }
  1149. void VisualServerScene::render_empty_scene(RID p_scenario, RID p_shadow_atlas) {
  1150. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1151. RID environment;
  1152. if (scenario->environment.is_valid())
  1153. environment = scenario->environment;
  1154. else
  1155. environment = scenario->fallback_environment;
  1156. VSG::scene_render->render_scene(Transform(), CameraMatrix(), true, NULL, 0, NULL, 0, NULL, 0, environment, p_shadow_atlas, scenario->reflection_atlas, RID(), 0);
  1157. }
  1158. bool VisualServerScene::_render_reflection_probe_step(Instance *p_instance, int p_step) {
  1159. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  1160. Scenario *scenario = p_instance->scenario;
  1161. ERR_FAIL_COND_V(!scenario, true);
  1162. if (p_step == 0) {
  1163. if (!VSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
  1164. return true; //sorry, all full :(
  1165. }
  1166. }
  1167. if (p_step >= 0 && p_step < 6) {
  1168. static const Vector3 view_normals[6] = {
  1169. Vector3(-1, 0, 0),
  1170. Vector3(+1, 0, 0),
  1171. Vector3(0, -1, 0),
  1172. Vector3(0, +1, 0),
  1173. Vector3(0, 0, -1),
  1174. Vector3(0, 0, +1)
  1175. };
  1176. Vector3 extents = VSG::storage->reflection_probe_get_extents(p_instance->base);
  1177. Vector3 origin_offset = VSG::storage->reflection_probe_get_origin_offset(p_instance->base);
  1178. float max_distance = VSG::storage->reflection_probe_get_origin_max_distance(p_instance->base);
  1179. Vector3 edge = view_normals[p_step] * extents;
  1180. 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
  1181. max_distance = MAX(max_distance, distance);
  1182. //render cubemap side
  1183. CameraMatrix cm;
  1184. cm.set_perspective(90, 1, 0.01, max_distance);
  1185. static const Vector3 view_up[6] = {
  1186. Vector3(0, -1, 0),
  1187. Vector3(0, -1, 0),
  1188. Vector3(0, 0, -1),
  1189. Vector3(0, 0, +1),
  1190. Vector3(0, -1, 0),
  1191. Vector3(0, -1, 0)
  1192. };
  1193. Transform local_view;
  1194. local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]);
  1195. Transform xform = p_instance->transform * local_view;
  1196. RID shadow_atlas;
  1197. if (VSG::storage->reflection_probe_renders_shadows(p_instance->base)) {
  1198. shadow_atlas = scenario->reflection_probe_shadow_atlas;
  1199. }
  1200. _render_scene(xform, cm, false, RID(), VSG::storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, p_step);
  1201. } else {
  1202. //do roughness postprocess step until it belives it's done
  1203. return VSG::scene_render->reflection_probe_instance_postprocess_step(reflection_probe->instance);
  1204. }
  1205. return false;
  1206. }
  1207. void VisualServerScene::_gi_probe_fill_local_data(int p_idx, int p_level, int p_x, int p_y, int p_z, const GIProbeDataCell *p_cell, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, Vector<uint32_t> *prev_cell) {
  1208. if (p_level == p_header->cell_subdiv - 1) {
  1209. Vector3 emission;
  1210. emission.x = (p_cell[p_idx].emission >> 24) / 255.0;
  1211. emission.y = ((p_cell[p_idx].emission >> 16) & 0xFF) / 255.0;
  1212. emission.z = ((p_cell[p_idx].emission >> 8) & 0xFF) / 255.0;
  1213. float l = (p_cell[p_idx].emission & 0xFF) / 255.0;
  1214. l *= 8.0;
  1215. emission *= l;
  1216. p_local_data[p_idx].energy[0] = uint16_t(emission.x * 1024); //go from 0 to 1024 for light
  1217. p_local_data[p_idx].energy[1] = uint16_t(emission.y * 1024); //go from 0 to 1024 for light
  1218. p_local_data[p_idx].energy[2] = uint16_t(emission.z * 1024); //go from 0 to 1024 for light
  1219. } else {
  1220. p_local_data[p_idx].energy[0] = 0;
  1221. p_local_data[p_idx].energy[1] = 0;
  1222. p_local_data[p_idx].energy[2] = 0;
  1223. int half = (1 << (p_header->cell_subdiv - 1)) >> (p_level + 1);
  1224. for (int i = 0; i < 8; i++) {
  1225. uint32_t child = p_cell[p_idx].children[i];
  1226. if (child == 0xFFFFFFFF)
  1227. continue;
  1228. int x = p_x;
  1229. int y = p_y;
  1230. int z = p_z;
  1231. if (i & 1)
  1232. x += half;
  1233. if (i & 2)
  1234. y += half;
  1235. if (i & 4)
  1236. z += half;
  1237. _gi_probe_fill_local_data(child, p_level + 1, x, y, z, p_cell, p_header, p_local_data, prev_cell);
  1238. }
  1239. }
  1240. //position for each part of the mipmaped texture
  1241. p_local_data[p_idx].pos[0] = p_x >> (p_header->cell_subdiv - p_level - 1);
  1242. p_local_data[p_idx].pos[1] = p_y >> (p_header->cell_subdiv - p_level - 1);
  1243. p_local_data[p_idx].pos[2] = p_z >> (p_header->cell_subdiv - p_level - 1);
  1244. prev_cell[p_level].push_back(p_idx);
  1245. }
  1246. void VisualServerScene::_gi_probe_bake_threads(void *self) {
  1247. VisualServerScene *vss = (VisualServerScene *)self;
  1248. vss->_gi_probe_bake_thread();
  1249. }
  1250. void VisualServerScene::_setup_gi_probe(Instance *p_instance) {
  1251. InstanceGIProbeData *probe = static_cast<InstanceGIProbeData *>(p_instance->base_data);
  1252. if (probe->dynamic.probe_data.is_valid()) {
  1253. VSG::storage->free(probe->dynamic.probe_data);
  1254. probe->dynamic.probe_data = RID();
  1255. }
  1256. probe->dynamic.light_data = VSG::storage->gi_probe_get_dynamic_data(p_instance->base);
  1257. if (probe->dynamic.light_data.size() == 0)
  1258. return;
  1259. //using dynamic data
  1260. PoolVector<int>::Read r = probe->dynamic.light_data.read();
  1261. const GIProbeDataHeader *header = (GIProbeDataHeader *)r.ptr();
  1262. probe->dynamic.local_data.resize(header->cell_count);
  1263. int cell_count = probe->dynamic.local_data.size();
  1264. PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe->dynamic.local_data.write();
  1265. const GIProbeDataCell *cells = (GIProbeDataCell *)&r[16];
  1266. probe->dynamic.level_cell_lists.resize(header->cell_subdiv);
  1267. _gi_probe_fill_local_data(0, 0, 0, 0, 0, cells, header, ldw.ptr(), probe->dynamic.level_cell_lists.ptr());
  1268. bool compress = VSG::storage->gi_probe_is_compressed(p_instance->base);
  1269. probe->dynamic.compression = compress ? VSG::storage->gi_probe_get_dynamic_data_get_preferred_compression() : RasterizerStorage::GI_PROBE_UNCOMPRESSED;
  1270. probe->dynamic.probe_data = VSG::storage->gi_probe_dynamic_data_create(header->width, header->height, header->depth, probe->dynamic.compression);
  1271. probe->dynamic.bake_dynamic_range = VSG::storage->gi_probe_get_dynamic_range(p_instance->base);
  1272. probe->dynamic.mipmaps_3d.clear();
  1273. probe->dynamic.propagate = VSG::storage->gi_probe_get_propagation(p_instance->base);
  1274. probe->dynamic.grid_size[0] = header->width;
  1275. probe->dynamic.grid_size[1] = header->height;
  1276. probe->dynamic.grid_size[2] = header->depth;
  1277. int size_limit = 1;
  1278. int size_divisor = 1;
  1279. if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
  1280. print_line("S3TC");
  1281. size_limit = 4;
  1282. size_divisor = 4;
  1283. }
  1284. for (int i = 0; i < (int)header->cell_subdiv; i++) {
  1285. uint32_t x = header->width >> i;
  1286. uint32_t y = header->height >> i;
  1287. uint32_t z = header->depth >> i;
  1288. //create and clear mipmap
  1289. PoolVector<uint8_t> mipmap;
  1290. int size = x * y * z * 4;
  1291. size /= size_divisor;
  1292. mipmap.resize(size);
  1293. PoolVector<uint8_t>::Write w = mipmap.write();
  1294. zeromem(w.ptr(), size);
  1295. w = PoolVector<uint8_t>::Write();
  1296. probe->dynamic.mipmaps_3d.push_back(mipmap);
  1297. if (x <= size_limit || y <= size_limit || z <= size_limit)
  1298. break;
  1299. }
  1300. probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK;
  1301. probe->invalid = false;
  1302. probe->dynamic.enabled = true;
  1303. Transform cell_to_xform = VSG::storage->gi_probe_get_to_cell_xform(p_instance->base);
  1304. Rect3 bounds = VSG::storage->gi_probe_get_bounds(p_instance->base);
  1305. float cell_size = VSG::storage->gi_probe_get_cell_size(p_instance->base);
  1306. probe->dynamic.light_to_cell_xform = cell_to_xform * p_instance->transform.affine_inverse();
  1307. VSG::scene_render->gi_probe_instance_set_light_data(probe->probe_instance, p_instance->base, probe->dynamic.probe_data);
  1308. VSG::scene_render->gi_probe_instance_set_transform_to_data(probe->probe_instance, probe->dynamic.light_to_cell_xform);
  1309. VSG::scene_render->gi_probe_instance_set_bounds(probe->probe_instance, bounds.size / cell_size);
  1310. probe->base_version = VSG::storage->gi_probe_get_version(p_instance->base);
  1311. //if compression is S3TC, fill it up
  1312. if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
  1313. //create all blocks
  1314. Vector<Map<uint32_t, InstanceGIProbeData::CompBlockS3TC> > comp_blocks;
  1315. int mipmap_count = probe->dynamic.mipmaps_3d.size();
  1316. comp_blocks.resize(mipmap_count);
  1317. for (int i = 0; i < cell_count; i++) {
  1318. const GIProbeDataCell &c = cells[i];
  1319. const InstanceGIProbeData::LocalData &ld = ldw[i];
  1320. int level = c.level_alpha >> 16;
  1321. int mipmap = header->cell_subdiv - level - 1;
  1322. if (mipmap >= mipmap_count)
  1323. continue; //uninteresting
  1324. int blockx = (ld.pos[0] >> 2);
  1325. int blocky = (ld.pos[1] >> 2);
  1326. int blockz = (ld.pos[2]); //compression is x/y only
  1327. int blockw = (header->width >> mipmap) >> 2;
  1328. int blockh = (header->height >> mipmap) >> 2;
  1329. //print_line("cell "+itos(i)+" level "+itos(level)+"mipmap: "+itos(mipmap)+" pos: "+Vector3(blockx,blocky,blockz)+" size "+Vector2(blockw,blockh));
  1330. uint32_t key = blockz * blockw * blockh + blocky * blockw + blockx;
  1331. Map<uint32_t, InstanceGIProbeData::CompBlockS3TC> &cmap = comp_blocks[mipmap];
  1332. if (!cmap.has(key)) {
  1333. InstanceGIProbeData::CompBlockS3TC k;
  1334. k.offset = key; //use offset as counter first
  1335. k.source_count = 0;
  1336. cmap[key] = k;
  1337. }
  1338. InstanceGIProbeData::CompBlockS3TC &k = cmap[key];
  1339. ERR_CONTINUE(k.source_count == 16);
  1340. k.sources[k.source_count++] = i;
  1341. }
  1342. //fix the blocks, precomputing what is needed
  1343. probe->dynamic.mipmaps_s3tc.resize(mipmap_count);
  1344. for (int i = 0; i < mipmap_count; i++) {
  1345. print_line("S3TC level: " + itos(i) + " blocks: " + itos(comp_blocks[i].size()));
  1346. probe->dynamic.mipmaps_s3tc[i].resize(comp_blocks[i].size());
  1347. PoolVector<InstanceGIProbeData::CompBlockS3TC>::Write w = probe->dynamic.mipmaps_s3tc[i].write();
  1348. int block_idx = 0;
  1349. for (Map<uint32_t, InstanceGIProbeData::CompBlockS3TC>::Element *E = comp_blocks[i].front(); E; E = E->next()) {
  1350. InstanceGIProbeData::CompBlockS3TC k = E->get();
  1351. //PRECOMPUTE ALPHA
  1352. int max_alpha = -100000;
  1353. int min_alpha = k.source_count == 16 ? 100000 : 0; //if the block is not completely full, minimum is always 0, (and those blocks will map to 1, which will be zero)
  1354. uint8_t alpha_block[4][4] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } };
  1355. for (int j = 0; j < k.source_count; j++) {
  1356. int alpha = (cells[k.sources[j]].level_alpha >> 8) & 0xFF;
  1357. if (alpha < min_alpha)
  1358. min_alpha = alpha;
  1359. if (alpha > max_alpha)
  1360. max_alpha = alpha;
  1361. //fill up alpha block
  1362. alpha_block[ldw[k.sources[j]].pos[0] % 4][ldw[k.sources[j]].pos[1] % 4] = alpha;
  1363. }
  1364. //use the first mode (8 adjustable levels)
  1365. k.alpha[0] = max_alpha;
  1366. k.alpha[1] = min_alpha;
  1367. uint64_t alpha_bits = 0;
  1368. if (max_alpha != min_alpha) {
  1369. int idx = 0;
  1370. for (int y = 0; y < 4; y++) {
  1371. for (int x = 0; x < 4; x++) {
  1372. //subtract minimum
  1373. uint32_t a = uint32_t(alpha_block[x][y]) - min_alpha;
  1374. //convert range to 3 bits
  1375. a = int((a * 7.0 / (max_alpha - min_alpha)) + 0.5);
  1376. a = CLAMP(a, 0, 7); //just to be sure
  1377. a = 7 - a; //because range is inverted in this mode
  1378. if (a == 0) {
  1379. //do none, remain
  1380. } else if (a == 7) {
  1381. a = 1;
  1382. } else {
  1383. a = a + 1;
  1384. }
  1385. alpha_bits |= uint64_t(a) << (idx * 3);
  1386. idx++;
  1387. }
  1388. }
  1389. }
  1390. k.alpha[2] = (alpha_bits >> 0) & 0xFF;
  1391. k.alpha[3] = (alpha_bits >> 8) & 0xFF;
  1392. k.alpha[4] = (alpha_bits >> 16) & 0xFF;
  1393. k.alpha[5] = (alpha_bits >> 24) & 0xFF;
  1394. k.alpha[6] = (alpha_bits >> 32) & 0xFF;
  1395. k.alpha[7] = (alpha_bits >> 40) & 0xFF;
  1396. w[block_idx++] = k;
  1397. }
  1398. }
  1399. }
  1400. }
  1401. void VisualServerScene::_gi_probe_bake_thread() {
  1402. while (true) {
  1403. probe_bake_sem->wait();
  1404. if (probe_bake_thread_exit) {
  1405. break;
  1406. }
  1407. Instance *to_bake = NULL;
  1408. probe_bake_mutex->lock();
  1409. if (!probe_bake_list.empty()) {
  1410. to_bake = probe_bake_list.front()->get();
  1411. probe_bake_list.pop_front();
  1412. }
  1413. probe_bake_mutex->unlock();
  1414. if (!to_bake)
  1415. continue;
  1416. _bake_gi_probe(to_bake);
  1417. }
  1418. }
  1419. uint32_t VisualServerScene::_gi_bake_find_cell(const GIProbeDataCell *cells, int x, int y, int z, int p_cell_subdiv) {
  1420. uint32_t cell = 0;
  1421. int ofs_x = 0;
  1422. int ofs_y = 0;
  1423. int ofs_z = 0;
  1424. int size = 1 << (p_cell_subdiv - 1);
  1425. int half = size / 2;
  1426. if (x < 0 || x >= size)
  1427. return -1;
  1428. if (y < 0 || y >= size)
  1429. return -1;
  1430. if (z < 0 || z >= size)
  1431. return -1;
  1432. for (int i = 0; i < p_cell_subdiv - 1; i++) {
  1433. const GIProbeDataCell *bc = &cells[cell];
  1434. int child = 0;
  1435. if (x >= ofs_x + half) {
  1436. child |= 1;
  1437. ofs_x += half;
  1438. }
  1439. if (y >= ofs_y + half) {
  1440. child |= 2;
  1441. ofs_y += half;
  1442. }
  1443. if (z >= ofs_z + half) {
  1444. child |= 4;
  1445. ofs_z += half;
  1446. }
  1447. cell = bc->children[child];
  1448. if (cell == 0xFFFFFFFF)
  1449. return 0xFFFFFFFF;
  1450. half >>= 1;
  1451. }
  1452. return cell;
  1453. }
  1454. static float _get_normal_advance(const Vector3 &p_normal) {
  1455. Vector3 normal = p_normal;
  1456. Vector3 unorm = normal.abs();
  1457. if ((unorm.x >= unorm.y) && (unorm.x >= unorm.z)) {
  1458. // x code
  1459. unorm = normal.x > 0.0 ? Vector3(1.0, 0.0, 0.0) : Vector3(-1.0, 0.0, 0.0);
  1460. } else if ((unorm.y > unorm.x) && (unorm.y >= unorm.z)) {
  1461. // y code
  1462. unorm = normal.y > 0.0 ? Vector3(0.0, 1.0, 0.0) : Vector3(0.0, -1.0, 0.0);
  1463. } else if ((unorm.z > unorm.x) && (unorm.z > unorm.y)) {
  1464. // z code
  1465. unorm = normal.z > 0.0 ? Vector3(0.0, 0.0, 1.0) : Vector3(0.0, 0.0, -1.0);
  1466. } else {
  1467. // oh-no we messed up code
  1468. // has to be
  1469. unorm = Vector3(1.0, 0.0, 0.0);
  1470. }
  1471. return 1.0 / normal.dot(unorm);
  1472. }
  1473. void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header, const GIProbeDataCell *cells, InstanceGIProbeData::LocalData *local_data, const uint32_t *leaves, int p_leaf_count, const InstanceGIProbeData::LightCache &light_cache, int p_sign) {
  1474. int light_r = int(light_cache.color.r * light_cache.energy * 1024.0) * p_sign;
  1475. int light_g = int(light_cache.color.g * light_cache.energy * 1024.0) * p_sign;
  1476. int light_b = int(light_cache.color.b * light_cache.energy * 1024.0) * p_sign;
  1477. float limits[3] = { float(header->width), float(header->height), float(header->depth) };
  1478. Plane clip[3];
  1479. int clip_planes = 0;
  1480. switch (light_cache.type) {
  1481. case VS::LIGHT_DIRECTIONAL: {
  1482. float max_len = Vector3(limits[0], limits[1], limits[2]).length() * 1.1;
  1483. Vector3 light_axis = -light_cache.transform.basis.get_axis(2).normalized();
  1484. for (int i = 0; i < 3; i++) {
  1485. if (ABS(light_axis[i]) < CMP_EPSILON)
  1486. continue;
  1487. clip[clip_planes].normal[i] = 1.0;
  1488. if (light_axis[i] < 0) {
  1489. clip[clip_planes].d = limits[i] + 1;
  1490. } else {
  1491. clip[clip_planes].d -= 1.0;
  1492. }
  1493. clip_planes++;
  1494. }
  1495. float distance_adv = _get_normal_advance(light_axis);
  1496. int success_count = 0;
  1497. uint64_t us = OS::get_singleton()->get_ticks_usec();
  1498. for (int i = 0; i < p_leaf_count; i++) {
  1499. uint32_t idx = leaves[i];
  1500. const GIProbeDataCell *cell = &cells[idx];
  1501. InstanceGIProbeData::LocalData *light = &local_data[idx];
  1502. Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5);
  1503. Vector3 norm(
  1504. (((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0,
  1505. (((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0,
  1506. (((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0);
  1507. float att = norm.dot(-light_axis);
  1508. if (att < 0.001) {
  1509. //not lighting towards this
  1510. continue;
  1511. }
  1512. Vector3 from = to - max_len * light_axis;
  1513. for (int j = 0; j < clip_planes; j++) {
  1514. clip[j].intersects_segment(from, to, &from);
  1515. }
  1516. float distance = (to - from).length();
  1517. distance += distance_adv - Math::fmod(distance, distance_adv); //make it reach the center of the box always
  1518. from = to - light_axis * distance;
  1519. uint32_t result = 0xFFFFFFFF;
  1520. while (distance > -distance_adv) { //use this to avoid precision errors
  1521. result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv);
  1522. if (result != 0xFFFFFFFF) {
  1523. break;
  1524. }
  1525. from += light_axis * distance_adv;
  1526. distance -= distance_adv;
  1527. }
  1528. if (result == idx) {
  1529. //cell hit itself! hooray!
  1530. light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0);
  1531. light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0);
  1532. light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0);
  1533. success_count++;
  1534. }
  1535. }
  1536. //print_line("BAKE TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0));
  1537. //print_line("valid cells: " + itos(success_count));
  1538. } break;
  1539. case VS::LIGHT_OMNI:
  1540. case VS::LIGHT_SPOT: {
  1541. uint64_t us = OS::get_singleton()->get_ticks_usec();
  1542. Vector3 light_pos = light_cache.transform.origin;
  1543. Vector3 spot_axis = -light_cache.transform.basis.get_axis(2).normalized();
  1544. float local_radius = light_cache.radius * light_cache.transform.basis.get_axis(2).length();
  1545. for (int i = 0; i < p_leaf_count; i++) {
  1546. uint32_t idx = leaves[i];
  1547. const GIProbeDataCell *cell = &cells[idx];
  1548. InstanceGIProbeData::LocalData *light = &local_data[idx];
  1549. Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5);
  1550. Vector3 norm(
  1551. (((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0,
  1552. (((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0,
  1553. (((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0);
  1554. Vector3 light_axis = (to - light_pos).normalized();
  1555. float distance_adv = _get_normal_advance(light_axis);
  1556. float att = norm.dot(-light_axis);
  1557. if (att < 0.001) {
  1558. //not lighting towards this
  1559. continue;
  1560. }
  1561. {
  1562. float d = light_pos.distance_to(to);
  1563. if (d + distance_adv > local_radius)
  1564. continue; // too far away
  1565. float dt = CLAMP((d + distance_adv) / local_radius, 0, 1);
  1566. att *= powf(1.0 - dt, light_cache.attenuation);
  1567. }
  1568. if (light_cache.type == VS::LIGHT_SPOT) {
  1569. float angle = Math::rad2deg(acos(light_axis.dot(spot_axis)));
  1570. if (angle > light_cache.spot_angle)
  1571. continue;
  1572. float d = CLAMP(angle / light_cache.spot_angle, 1, 0);
  1573. att *= powf(1.0 - d, light_cache.spot_attenuation);
  1574. }
  1575. clip_planes = 0;
  1576. for (int c = 0; c < 3; c++) {
  1577. if (ABS(light_axis[c]) < CMP_EPSILON)
  1578. continue;
  1579. clip[clip_planes].normal[c] = 1.0;
  1580. if (light_axis[c] < 0) {
  1581. clip[clip_planes].d = limits[c] + 1;
  1582. } else {
  1583. clip[clip_planes].d -= 1.0;
  1584. }
  1585. clip_planes++;
  1586. }
  1587. Vector3 from = light_pos;
  1588. for (int j = 0; j < clip_planes; j++) {
  1589. clip[j].intersects_segment(from, to, &from);
  1590. }
  1591. float distance = (to - from).length();
  1592. distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer
  1593. from = to - light_axis * distance;
  1594. uint32_t result = 0xFFFFFFFF;
  1595. while (distance > -distance_adv) { //use this to avoid precision errors
  1596. result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv);
  1597. if (result != 0xFFFFFFFF) {
  1598. break;
  1599. }
  1600. from += light_axis * distance_adv;
  1601. distance -= distance_adv;
  1602. }
  1603. if (result == idx) {
  1604. //cell hit itself! hooray!
  1605. light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0);
  1606. light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0);
  1607. light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0);
  1608. }
  1609. }
  1610. //print_line("BAKE TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0));
  1611. } break;
  1612. }
  1613. }
  1614. void VisualServerScene::_bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell *p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, float p_propagate) {
  1615. //average light to upper level
  1616. float divisor = 0;
  1617. float sum[3] = { 0.0, 0.0, 0.0 };
  1618. for (int i = 0; i < 8; i++) {
  1619. uint32_t child = p_cells[p_idx].children[i];
  1620. if (child == 0xFFFFFFFF)
  1621. continue;
  1622. if (p_level + 1 < (int)p_header->cell_subdiv - 1) {
  1623. _bake_gi_downscale_light(child, p_level + 1, p_cells, p_header, p_local_data, p_propagate);
  1624. }
  1625. sum[0] += p_local_data[child].energy[0];
  1626. sum[1] += p_local_data[child].energy[1];
  1627. sum[2] += p_local_data[child].energy[2];
  1628. divisor += 1.0;
  1629. }
  1630. divisor = Math::lerp((float)8.0, divisor, p_propagate);
  1631. sum[0] /= divisor;
  1632. sum[1] /= divisor;
  1633. sum[2] /= divisor;
  1634. //divide by eight for average
  1635. p_local_data[p_idx].energy[0] = Math::fast_ftoi(sum[0]);
  1636. p_local_data[p_idx].energy[1] = Math::fast_ftoi(sum[1]);
  1637. p_local_data[p_idx].energy[2] = Math::fast_ftoi(sum[2]);
  1638. }
  1639. void VisualServerScene::_bake_gi_probe(Instance *p_gi_probe) {
  1640. InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data);
  1641. PoolVector<int>::Read r = probe_data->dynamic.light_data.read();
  1642. const GIProbeDataHeader *header = (const GIProbeDataHeader *)r.ptr();
  1643. const GIProbeDataCell *cells = (const GIProbeDataCell *)&r[16];
  1644. int leaf_count = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].size();
  1645. const uint32_t *leaves = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].ptr();
  1646. PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe_data->dynamic.local_data.write();
  1647. InstanceGIProbeData::LocalData *local_data = ldw.ptr();
  1648. //remove what must be removed
  1649. for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache.front(); E; E = E->next()) {
  1650. RID rid = E->key();
  1651. const InstanceGIProbeData::LightCache &lc = E->get();
  1652. if (!probe_data->dynamic.light_cache_changes.has(rid) || !(probe_data->dynamic.light_cache_changes[rid] == lc)) {
  1653. //erase light data
  1654. _bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, -1);
  1655. }
  1656. }
  1657. //add what must be added
  1658. for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache_changes.front(); E; E = E->next()) {
  1659. RID rid = E->key();
  1660. const InstanceGIProbeData::LightCache &lc = E->get();
  1661. if (!probe_data->dynamic.light_cache.has(rid) || !(probe_data->dynamic.light_cache[rid] == lc)) {
  1662. //add light data
  1663. _bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, 1);
  1664. }
  1665. }
  1666. SWAP(probe_data->dynamic.light_cache_changes, probe_data->dynamic.light_cache);
  1667. //downscale to lower res levels
  1668. _bake_gi_downscale_light(0, 0, cells, header, local_data, probe_data->dynamic.propagate);
  1669. //plot result to 3D texture!
  1670. if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_UNCOMPRESSED) {
  1671. for (int i = 0; i < (int)header->cell_subdiv; i++) {
  1672. int stage = header->cell_subdiv - i - 1;
  1673. if (stage >= probe_data->dynamic.mipmaps_3d.size())
  1674. continue; //no mipmap for this one
  1675. //print_line("generating mipmap stage: " + itos(stage));
  1676. int level_cell_count = probe_data->dynamic.level_cell_lists[i].size();
  1677. const uint32_t *level_cells = probe_data->dynamic.level_cell_lists[i].ptr();
  1678. PoolVector<uint8_t>::Write lw = probe_data->dynamic.mipmaps_3d[stage].write();
  1679. uint8_t *mipmapw = lw.ptr();
  1680. uint32_t sizes[3] = { header->width >> stage, header->height >> stage, header->depth >> stage };
  1681. for (int j = 0; j < level_cell_count; j++) {
  1682. uint32_t idx = level_cells[j];
  1683. uint32_t r = (uint32_t(local_data[idx].energy[0]) / probe_data->dynamic.bake_dynamic_range) >> 2;
  1684. uint32_t g = (uint32_t(local_data[idx].energy[1]) / probe_data->dynamic.bake_dynamic_range) >> 2;
  1685. uint32_t b = (uint32_t(local_data[idx].energy[2]) / probe_data->dynamic.bake_dynamic_range) >> 2;
  1686. uint32_t a = (cells[idx].level_alpha >> 8) & 0xFF;
  1687. uint32_t mm_ofs = sizes[0] * sizes[1] * (local_data[idx].pos[2]) + sizes[0] * (local_data[idx].pos[1]) + (local_data[idx].pos[0]);
  1688. mm_ofs *= 4; //for RGBA (4 bytes)
  1689. mipmapw[mm_ofs + 0] = uint8_t(CLAMP(r, 0, 255));
  1690. mipmapw[mm_ofs + 1] = uint8_t(CLAMP(g, 0, 255));
  1691. mipmapw[mm_ofs + 2] = uint8_t(CLAMP(b, 0, 255));
  1692. mipmapw[mm_ofs + 3] = uint8_t(CLAMP(a, 0, 255));
  1693. }
  1694. }
  1695. } else if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
  1696. int mipmap_count = probe_data->dynamic.mipmaps_3d.size();
  1697. for (int mmi = 0; mmi < mipmap_count; mmi++) {
  1698. PoolVector<uint8_t>::Write mmw = probe_data->dynamic.mipmaps_3d[mmi].write();
  1699. int block_count = probe_data->dynamic.mipmaps_s3tc[mmi].size();
  1700. PoolVector<InstanceGIProbeData::CompBlockS3TC>::Read mmr = probe_data->dynamic.mipmaps_s3tc[mmi].read();
  1701. for (int i = 0; i < block_count; i++) {
  1702. const InstanceGIProbeData::CompBlockS3TC &b = mmr[i];
  1703. uint8_t *blockptr = &mmw[b.offset * 16];
  1704. copymem(blockptr, b.alpha, 8); //copy alpha part, which is precomputed
  1705. Vector3 colors[16];
  1706. for (int j = 0; j < b.source_count; j++) {
  1707. colors[j].x = (local_data[b.sources[j]].energy[0] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
  1708. colors[j].y = (local_data[b.sources[j]].energy[1] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
  1709. colors[j].z = (local_data[b.sources[j]].energy[2] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
  1710. }
  1711. //super quick and dirty compression
  1712. //find 2 most further apart
  1713. float distance = 0;
  1714. Vector3 from, to;
  1715. if (b.source_count == 16) {
  1716. //all cells are used so, find minmax between them
  1717. int further_apart[2] = { 0, 0 };
  1718. for (int j = 0; j < b.source_count; j++) {
  1719. for (int k = j + 1; k < b.source_count; k++) {
  1720. float d = colors[j].distance_squared_to(colors[k]);
  1721. if (d > distance) {
  1722. distance = d;
  1723. further_apart[0] = j;
  1724. further_apart[1] = k;
  1725. }
  1726. }
  1727. }
  1728. from = colors[further_apart[0]];
  1729. to = colors[further_apart[1]];
  1730. } else {
  1731. //if a block is missing, the priority is that this block remains black,
  1732. //otherwise the geometry will appear deformed
  1733. //correct shape wins over correct color in this case
  1734. //average all colors first
  1735. Vector3 average;
  1736. for (int j = 0; j < b.source_count; j++) {
  1737. average += colors[j];
  1738. }
  1739. average.normalize();
  1740. //find max distance in normal from average
  1741. for (int j = 0; j < b.source_count; j++) {
  1742. float d = average.dot(colors[j]);
  1743. distance = MAX(d, distance);
  1744. }
  1745. from = Vector3(); //from black
  1746. to = average * distance;
  1747. //find max distance
  1748. }
  1749. int indices[16];
  1750. uint16_t color_0 = 0;
  1751. color_0 = CLAMP(int(from.x * 31), 0, 31) << 11;
  1752. color_0 |= CLAMP(int(from.y * 63), 0, 63) << 5;
  1753. color_0 |= CLAMP(int(from.z * 31), 0, 31);
  1754. uint16_t color_1 = 0;
  1755. color_1 = CLAMP(int(to.x * 31), 0, 31) << 11;
  1756. color_1 |= CLAMP(int(to.y * 63), 0, 63) << 5;
  1757. color_1 |= CLAMP(int(to.z * 31), 0, 31);
  1758. if (color_1 > color_0) {
  1759. SWAP(color_1, color_0);
  1760. SWAP(from, to);
  1761. }
  1762. if (distance > 0) {
  1763. Vector3 dir = (to - from).normalized();
  1764. for (int j = 0; j < b.source_count; j++) {
  1765. float d = (colors[j] - from).dot(dir) / distance;
  1766. indices[j] = int(d * 3 + 0.5);
  1767. static const int index_swap[4] = { 0, 3, 1, 2 };
  1768. indices[j] = index_swap[CLAMP(indices[j], 0, 3)];
  1769. }
  1770. } else {
  1771. for (int j = 0; j < b.source_count; j++) {
  1772. indices[j] = 0;
  1773. }
  1774. }
  1775. //by default, 1 is black, otherwise it will be overridden by source
  1776. uint32_t index_block[16] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
  1777. for (int j = 0; j < b.source_count; j++) {
  1778. int x = local_data[b.sources[j]].pos[0] % 4;
  1779. int y = local_data[b.sources[j]].pos[1] % 4;
  1780. index_block[y * 4 + x] = indices[j];
  1781. }
  1782. uint32_t encode = 0;
  1783. for (int j = 0; j < 16; j++) {
  1784. encode |= index_block[j] << (j * 2);
  1785. }
  1786. blockptr[8] = color_0 & 0xFF;
  1787. blockptr[9] = (color_0 >> 8) & 0xFF;
  1788. blockptr[10] = color_1 & 0xFF;
  1789. blockptr[11] = (color_1 >> 8) & 0xFF;
  1790. blockptr[12] = encode & 0xFF;
  1791. blockptr[13] = (encode >> 8) & 0xFF;
  1792. blockptr[14] = (encode >> 16) & 0xFF;
  1793. blockptr[15] = (encode >> 24) & 0xFF;
  1794. }
  1795. }
  1796. }
  1797. //send back to main thread to update un little chunks
  1798. probe_data->dynamic.updating_stage = GI_UPDATE_STAGE_UPLOADING;
  1799. }
  1800. bool VisualServerScene::_check_gi_probe(Instance *p_gi_probe) {
  1801. InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data);
  1802. probe_data->dynamic.light_cache_changes.clear();
  1803. bool all_equal = true;
  1804. for (List<Instance *>::Element *E = p_gi_probe->scenario->directional_lights.front(); E; E = E->next()) {
  1805. InstanceGIProbeData::LightCache lc;
  1806. lc.type = VSG::storage->light_get_type(E->get()->base);
  1807. lc.color = VSG::storage->light_get_color(E->get()->base);
  1808. lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY);
  1809. lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE);
  1810. lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION);
  1811. lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  1812. lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION);
  1813. lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform;
  1814. if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self] == lc)) {
  1815. all_equal = false;
  1816. }
  1817. probe_data->dynamic.light_cache_changes[E->get()->self] = lc;
  1818. }
  1819. for (Set<Instance *>::Element *E = probe_data->lights.front(); E; E = E->next()) {
  1820. InstanceGIProbeData::LightCache lc;
  1821. lc.type = VSG::storage->light_get_type(E->get()->base);
  1822. lc.color = VSG::storage->light_get_color(E->get()->base);
  1823. lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY);
  1824. lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE);
  1825. lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION);
  1826. lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  1827. lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION);
  1828. lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform;
  1829. if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self] == lc)) {
  1830. all_equal = false;
  1831. }
  1832. probe_data->dynamic.light_cache_changes[E->get()->self] = lc;
  1833. }
  1834. //lighting changed from after to before, must do some updating
  1835. return !all_equal || probe_data->dynamic.light_cache_changes.size() != probe_data->dynamic.light_cache.size();
  1836. }
  1837. void VisualServerScene::render_probes() {
  1838. /* REFLECTION PROBES */
  1839. SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();
  1840. bool busy = false;
  1841. while (ref_probe) {
  1842. SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
  1843. RID base = ref_probe->self()->owner->base;
  1844. switch (VSG::storage->reflection_probe_get_update_mode(base)) {
  1845. case VS::REFLECTION_PROBE_UPDATE_ONCE: {
  1846. if (busy) //already rendering something
  1847. break;
  1848. bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
  1849. if (done) {
  1850. reflection_probe_render_list.remove(ref_probe);
  1851. } else {
  1852. ref_probe->self()->render_step++;
  1853. }
  1854. busy = true; //do not render another one of this kind
  1855. } break;
  1856. case VS::REFLECTION_PROBE_UPDATE_ALWAYS: {
  1857. int step = 0;
  1858. bool done = false;
  1859. while (!done) {
  1860. done = _render_reflection_probe_step(ref_probe->self()->owner, step);
  1861. step++;
  1862. }
  1863. reflection_probe_render_list.remove(ref_probe);
  1864. } break;
  1865. }
  1866. ref_probe = next;
  1867. }
  1868. /* GI PROBES */
  1869. SelfList<InstanceGIProbeData> *gi_probe = gi_probe_update_list.first();
  1870. while (gi_probe) {
  1871. SelfList<InstanceGIProbeData> *next = gi_probe->next();
  1872. InstanceGIProbeData *probe = gi_probe->self();
  1873. Instance *instance_probe = probe->owner;
  1874. //check if probe must be setup, but don't do if on the lighting thread
  1875. bool force_lighting = false;
  1876. if (probe->invalid || (probe->dynamic.updating_stage == GI_UPDATE_STAGE_CHECK && probe->base_version != VSG::storage->gi_probe_get_version(instance_probe->base))) {
  1877. _setup_gi_probe(instance_probe);
  1878. force_lighting = true;
  1879. }
  1880. float propagate = VSG::storage->gi_probe_get_propagation(instance_probe->base);
  1881. if (probe->dynamic.propagate != propagate) {
  1882. probe->dynamic.propagate = propagate;
  1883. force_lighting = true;
  1884. }
  1885. if (probe->invalid == false && probe->dynamic.enabled) {
  1886. switch (probe->dynamic.updating_stage) {
  1887. case GI_UPDATE_STAGE_CHECK: {
  1888. if (_check_gi_probe(instance_probe) || force_lighting) {
  1889. //send to lighting thread
  1890. probe->dynamic.updating_stage = GI_UPDATE_STAGE_LIGHTING;
  1891. #ifndef NO_THREADS
  1892. probe_bake_mutex->lock();
  1893. probe_bake_list.push_back(instance_probe);
  1894. probe_bake_mutex->unlock();
  1895. probe_bake_sem->post();
  1896. #else
  1897. _bake_gi_probe(instance_probe);
  1898. #endif
  1899. }
  1900. } break;
  1901. case GI_UPDATE_STAGE_LIGHTING: {
  1902. //do none, wait til done!
  1903. } break;
  1904. case GI_UPDATE_STAGE_UPLOADING: {
  1905. uint64_t us = OS::get_singleton()->get_ticks_usec();
  1906. for (int i = 0; i < (int)probe->dynamic.mipmaps_3d.size(); i++) {
  1907. int mmsize = probe->dynamic.mipmaps_3d[i].size();
  1908. PoolVector<uint8_t>::Read r = probe->dynamic.mipmaps_3d[i].read();
  1909. VSG::storage->gi_probe_dynamic_data_update(probe->dynamic.probe_data, 0, probe->dynamic.grid_size[2] >> i, i, r.ptr());
  1910. }
  1911. probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK;
  1912. //print_line("UPLOAD TIME: "+rtos((OS::get_singleton()->get_ticks_usec()-us)/1000000.0));
  1913. } break;
  1914. }
  1915. }
  1916. //_update_gi_probe(gi_probe->self()->owner);
  1917. gi_probe = next;
  1918. }
  1919. }
  1920. void VisualServerScene::_update_dirty_instance(Instance *p_instance) {
  1921. if (p_instance->update_aabb) {
  1922. _update_instance_aabb(p_instance);
  1923. }
  1924. if (p_instance->update_materials) {
  1925. if (p_instance->base_type == VS::INSTANCE_MESH) {
  1926. //remove materials no longer used and un-own them
  1927. int new_mat_count = VSG::storage->mesh_get_surface_count(p_instance->base);
  1928. for (int i = p_instance->materials.size() - 1; i >= new_mat_count; i--) {
  1929. if (p_instance->materials[i].is_valid()) {
  1930. VSG::storage->material_remove_instance_owner(p_instance->materials[i], p_instance);
  1931. }
  1932. }
  1933. p_instance->materials.resize(new_mat_count);
  1934. int new_blend_shape_count = VSG::storage->mesh_get_blend_shape_count(p_instance->base);
  1935. if (new_blend_shape_count != p_instance->blend_values.size()) {
  1936. p_instance->blend_values.resize(new_blend_shape_count);
  1937. for (int i = 0; i < new_blend_shape_count; i++) {
  1938. p_instance->blend_values[i] = 0;
  1939. }
  1940. }
  1941. }
  1942. if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  1943. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1944. bool can_cast_shadows = true;
  1945. if (p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_OFF) {
  1946. can_cast_shadows = false;
  1947. } else if (p_instance->material_override.is_valid()) {
  1948. can_cast_shadows = VSG::storage->material_casts_shadows(p_instance->material_override);
  1949. } else {
  1950. if (p_instance->base_type == VS::INSTANCE_MESH) {
  1951. RID mesh = p_instance->base;
  1952. if (mesh.is_valid()) {
  1953. bool cast_shadows = false;
  1954. for (int i = 0; i < p_instance->materials.size(); i++) {
  1955. RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : VSG::storage->mesh_surface_get_material(mesh, i);
  1956. if (!mat.is_valid()) {
  1957. cast_shadows = true;
  1958. break;
  1959. }
  1960. if (VSG::storage->material_casts_shadows(mat)) {
  1961. cast_shadows = true;
  1962. break;
  1963. }
  1964. }
  1965. if (!cast_shadows) {
  1966. can_cast_shadows = false;
  1967. }
  1968. }
  1969. } else if (p_instance->base_type == VS::INSTANCE_MULTIMESH) {
  1970. RID mesh = VSG::storage->multimesh_get_mesh(p_instance->base);
  1971. if (mesh.is_valid()) {
  1972. bool cast_shadows = false;
  1973. int sc = VSG::storage->mesh_get_surface_count(mesh);
  1974. for (int i = 0; i < sc; i++) {
  1975. RID mat = VSG::storage->mesh_surface_get_material(mesh, i);
  1976. if (!mat.is_valid()) {
  1977. cast_shadows = true;
  1978. break;
  1979. }
  1980. if (VSG::storage->material_casts_shadows(mat)) {
  1981. cast_shadows = true;
  1982. break;
  1983. }
  1984. }
  1985. if (!cast_shadows) {
  1986. can_cast_shadows = false;
  1987. }
  1988. }
  1989. } else if (p_instance->base_type == VS::INSTANCE_IMMEDIATE) {
  1990. RID mat = VSG::storage->immediate_get_material(p_instance->base);
  1991. if (!mat.is_valid() || VSG::storage->material_casts_shadows(mat)) {
  1992. can_cast_shadows = true;
  1993. } else {
  1994. can_cast_shadows = false;
  1995. }
  1996. } else if (p_instance->base_type == VS::INSTANCE_PARTICLES) {
  1997. bool cast_shadows = false;
  1998. int dp = VSG::storage->particles_get_draw_passes(p_instance->base);
  1999. for (int i = 0; i < dp; i++) {
  2000. RID mesh = VSG::storage->particles_get_draw_pass_mesh(p_instance->base, i);
  2001. if (!mesh.is_valid())
  2002. continue;
  2003. int sc = VSG::storage->mesh_get_surface_count(mesh);
  2004. for (int j = 0; j < sc; j++) {
  2005. RID mat = VSG::storage->mesh_surface_get_material(mesh, j);
  2006. if (!mat.is_valid()) {
  2007. cast_shadows = true;
  2008. break;
  2009. }
  2010. if (VSG::storage->material_casts_shadows(mat)) {
  2011. cast_shadows = true;
  2012. break;
  2013. }
  2014. }
  2015. }
  2016. if (!cast_shadows) {
  2017. can_cast_shadows = false;
  2018. }
  2019. }
  2020. }
  2021. if (can_cast_shadows != geom->can_cast_shadows) {
  2022. //ability to cast shadows change, let lights now
  2023. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  2024. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  2025. light->shadow_dirty = true;
  2026. }
  2027. geom->can_cast_shadows = can_cast_shadows;
  2028. }
  2029. }
  2030. }
  2031. _update_instance(p_instance);
  2032. p_instance->update_aabb = false;
  2033. p_instance->update_materials = false;
  2034. _instance_update_list.remove(&p_instance->update_item);
  2035. }
  2036. void VisualServerScene::update_dirty_instances() {
  2037. VSG::storage->update_dirty_resources();
  2038. while (_instance_update_list.first()) {
  2039. _update_dirty_instance(_instance_update_list.first()->self());
  2040. }
  2041. }
  2042. bool VisualServerScene::free(RID p_rid) {
  2043. if (camera_owner.owns(p_rid)) {
  2044. Camera *camera = camera_owner.get(p_rid);
  2045. camera_owner.free(p_rid);
  2046. memdelete(camera);
  2047. } else if (scenario_owner.owns(p_rid)) {
  2048. Scenario *scenario = scenario_owner.get(p_rid);
  2049. while (scenario->instances.first()) {
  2050. instance_set_scenario(scenario->instances.first()->self()->self, RID());
  2051. }
  2052. VSG::scene_render->free(scenario->reflection_probe_shadow_atlas);
  2053. VSG::scene_render->free(scenario->reflection_atlas);
  2054. scenario_owner.free(p_rid);
  2055. memdelete(scenario);
  2056. } else if (instance_owner.owns(p_rid)) {
  2057. // delete the instance
  2058. update_dirty_instances();
  2059. Instance *instance = instance_owner.get(p_rid);
  2060. instance_set_scenario(p_rid, RID());
  2061. instance_set_base(p_rid, RID());
  2062. instance_geometry_set_material_override(p_rid, RID());
  2063. instance_attach_skeleton(p_rid, RID());
  2064. update_dirty_instances(); //in case something changed this
  2065. instance_owner.free(p_rid);
  2066. memdelete(instance);
  2067. } else {
  2068. return false;
  2069. }
  2070. return true;
  2071. }
  2072. VisualServerScene *VisualServerScene::singleton = NULL;
  2073. VisualServerScene::VisualServerScene() {
  2074. #ifndef NO_THREADS
  2075. probe_bake_sem = Semaphore::create();
  2076. probe_bake_mutex = Mutex::create();
  2077. probe_bake_thread = Thread::create(_gi_probe_bake_threads, this);
  2078. probe_bake_thread_exit = false;
  2079. #endif
  2080. render_pass = 1;
  2081. singleton = this;
  2082. }
  2083. VisualServerScene::~VisualServerScene() {
  2084. #ifndef NO_THREADS
  2085. probe_bake_thread_exit = true;
  2086. Thread::wait_to_finish(probe_bake_thread);
  2087. memdelete(probe_bake_thread);
  2088. memdelete(probe_bake_sem);
  2089. memdelete(probe_bake_mutex);
  2090. #endif
  2091. }