visual_server_scene.cpp 123 KB

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