visual_server_scene.cpp 113 KB

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