visual_server_scene.cpp 142 KB

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