visual_server_scene.cpp 114 KB

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