visual_server_scene.cpp 113 KB

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