From 1d8fdffac5bdcd55f052bbc72a6fae5bece71e3c Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:11:53 +0100 Subject: [PATCH] feat(render): models with lights drawn instanced, behind gfx.instancedlights in eu07.ini (#538) * feat(render): models with lights drawn instanced, behind gfx.instancedlights in eu07.ini Stage 5 of the EU07M model format. A model with lights (lights, Light_On## / Light_Off##), such as a signal head, was drawn instance by instance, a draw call for each part of each one. With gfx.instancedlights 1 the instances of such a model go into the instanced batches like the others, in both renderers, with the culling of the GPU and without it. The default 0 draws them as before. It applies to EU07M and E3D models alike. - The light state of an instance is a word in the element [0][3] of its instance matrix, which an affine matrix leaves unused: bits 0-7 the lit parts shown, bits 8-15 the dark parts, in the mantissa of a float of exponent 128 (0x40000000), a normal number the GPU carries through its matrix products whole. Without that marker the shader draws everything, as before. - model_ubs.light_part says which part of which slot a draw is (0 none, 1 + slot lit, 9 + slot dark); a part the instance doesn't show gets a zero matrix in the vertex shader (instance_hides_part() and effective_modelview() in shaders/vk14/common.glsl and shaders/ogl46/common.glsl). The batch instance shows every light part (TAnimModel::RaPrepareInstanced()). - CPU path: each instance drawn is animated (RaAnimate) and its word put in its matrix (Render_Instanced). GPU culling: the word is in rotationscale[0].w of the instance record, refreshed once a frame for buckets with lights (Refresh_Light_Records), which marks the records to send again when a word changes. - An instance shows the whole lit part or the whole dark one: blinking and switching (ls_On / ls_Off / ls_Blink) change over at half the fade, where the draw instance by instance fades the lit part in over the dark one. Steady states look the same as before. - The freespot lights (TP_FREESPOTLIGHT with flag 0x4000 and no animation) don't keep a model out of the instancing when gfx.instancedlights is on. Light parts aren't put in the ray tracing of an instance batch. Measured on Vulkan, 200 heads s4ipcpb_dd: with gfx.gpucull 0 frame 9.2 ms -> 1.5-2.5 ms and 2400 -> 16 draw calls, with gfx.gpucull 1 9.1 ms -> 3.0 ms and 2410 -> 26 draw calls. Steady light states pixel for pixel the same as drawn instance by instance on all three paths in Vulkan, and on GL 4.6 where the editor panels don't cover them; blinking checked in Vulkan on all three paths (with time let run in the editor for the test only). Not run in the driver mode, blinking not checked on GL 4.6, not built with GCC here. Unit tests 1189/1189. * fix(render): EU07M review of #538: an instance with light colours of its own drawn alone, the light records locked only when stale - An instance with lightcolors of its own isn't instanced: the colours go onto the shared submodels as the instance is prepared, which the instances of a bucket don't each get, so they all showed the colours of one of them. - The walk takes the exclusive lock for the light records of a bucket only when they are stale in this frame (Refresh_Light_Records() checks again under it): the later passes of the frame no longer stop the other walkers. - instance_cull.comp (both renderers) puts the word of the light parts into [0][3] after the product with the view, so a view with a translation can't stretch the first column of a lit instance. - The spec: ls_Dark / ls_Home switch without the fade too, and the instances with light colours of their own. --- docs/eu07m-format.md | 19 ++++ gl/ubo.h | 6 +- model/AnimModel.cpp | 79 +++++++++++++++- model/AnimModel.h | 10 ++ rendering/common/scenewalk.cpp | 123 ++++++++++++++++++++++++- rendering/common/scenewalk.h | 15 +++ rendering/common/scenewalkindirect.cpp | 6 +- rendering/vulkan14/vulkan14frame.cpp | 6 ++ rendering/vulkan14/vulkan14scene.cpp | 6 ++ scene/scene.h | 2 + shaders/ogl46/common.glsl | 24 ++++- shaders/ogl46/instance_cull.comp | 6 +- shaders/vk14/common.glsl | 23 ++++- shaders/vk14/instance_cull.comp | 6 +- utilities/Globals.cpp | 6 ++ utilities/Globals.h | 4 + 16 files changed, 328 insertions(+), 13 deletions(-) diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index 3104b7927..123115653 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -245,6 +245,25 @@ Domyślne `modelformat legacy` zostawia pliki `.ng3d` w spokoju. strumieni przy pierwszym odczycie. - Gwiazdy (`STAR`) trzymają kolor w normalnej, więc idą jako `gfx::basic_vertex` również w Vulkanie. +### Instancjonowanie modeli ze światłami + +Z `gfx.instancedlights 1` w `eu07.ini` modele ze światłami (`lights`, `Light_On##` / `Light_Off##`), np. głowice semaforów, +są rysowane instancjonowane w obu rendererach, z cullingiem GPU i bez niego. Domyślne `0` rysuje je jak dotąd, każdy +egzemplarz osobno. Dotyczy to modeli EU07M i E3D tak samo. + +- Stan świateł egzemplarza to słowo w elemencie `[0][3]` macierzy instancji: bity 0–7 pokazują zapalone części slotów, bity + 8–15 zgaszone, w mantysie liczby o wykładniku 128 (`0x40000000`). Bez tego znacznika shader rysuje wszystko. +- Część światła (`model_ubs.light_part`: 0 brak, 1 + slot zapalona, 9 + slot zgaszona) ukryta w danym egzemplarzu dostaje + w shaderze macierz zerową (`instance_hides_part()` w `common.glsl`). +- Egzemplarz pokazuje całą część zapaloną albo całą zgaszoną. Przy miganiu i przy przełączaniu (`ls_On` / `ls_Off` / + `ls_Blink`) zamiana następuje w połowie przejścia (krycie 0,5), a nie płynnym przenikaniem jak bez instancjonowania. + Stany stałe wyglądają tak samo jak bez instancjonowania. Tak samo bez płynnego przejścia (`fVisible`) zmieniają się + `ls_Dark` i `ls_Home`. +- Egzemplarz z własnymi kolorami świateł (`lightcolors` węzła) jest rysowany osobno: kolory są nadawane wspólnym + submodelom przy przygotowaniu egzemplarza, którego egzemplarze kubełka nie dostają każdy z osobna. +- Pomiar (Vulkan, 200 głowic `s4ipcpb_dd`): z `gfx.gpucull 0` klatka 9,2 ms → 1,5–2,5 ms i 2400 → 16 drawcalli, + z `gfx.gpucull 1` 9,1 ms → 3,0 ms i 2410 → 26 drawcalli. + ## Zgodność wstecz E3D i T3D są czytane jak dotąd. Plik `.ng3d` jest wczytywany tylko wtedy, gdy istnieje, za przełącznikiem `modelformat ng3d` diff --git a/gl/ubo.h b/gl/ubo.h index 6ee7d5d9a..c31016021 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -263,7 +263,11 @@ namespace gl // 1 for the parts of the occupied cab, which the probe of the cab lights and reflects (gl::scene_ubs::cab_probe_box), 2 for the // low poly interiors of the vehicles (gl::scene_ubs::env_params) float cab_interior{0.f}; - UBS_PAD(8); + // the part of a numbered light the draw is of, for the instanced draws of the models with lights (gfx.instancedlights): + // 0 none, 1 + slot for the part lit (Light_On##), 9 + slot for the part dark (Light_Off##). the shaders hide it for the + // instances whose light state (the word in their matrix) doesn't show it + float light_part{0.f}; + UBS_PAD(4); void set_modelview(const glm::mat4 &mv) { diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 42fea67cf..5e697918f 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "model/AnimModel.h" +#include + #include "rendering/renderer.h" #include "model/MdlMngr.h" #include "simulation/simulation.h" @@ -526,7 +528,10 @@ bool submodel_tree_blocks_instancing( TSubModel const *Sub ) { // a text display shows the text of its instance, a tree shared by all instances can't do that if( Sub->eType == TP_TEXT ) { return true; } if( anim_type_unsafe_for_instancing( Sub->b_Anim ) ) { return true; } - if( ( ( Sub->iFlags & 0x4000 ) != 0 ) && ( false == anim_type_shared_by_instances( Sub->b_Anim ) ) ) { return true; } + // a light point gets the flag at load for its glare, not for an animation of its own. it's drawn only in the translucent pass, + // by each instance on its own (Render_Alpha()), so with the instanced lights (gfx.instancedlights) it doesn't keep the model out + auto const lightpoint { ( Sub->eType == TP_FREESPOTLIGHT ) && Global.gfx_instancedlights && ( Sub->b_Anim == TAnimType::at_None ) }; + if( ( ( Sub->iFlags & 0x4000 ) != 0 ) && ( false == anim_type_shared_by_instances( Sub->b_Anim ) ) && ( false == lightpoint ) ) { return true; } if( submodel_tree_blocks_instancing( Sub->Child ) ) { return true; } if( submodel_tree_blocks_instancing( Sub->Next ) ) { return true; } return false; @@ -564,7 +569,12 @@ void TAnimModel::update_instanceable_flag() { m_cameraindependent = ( pModel != nullptr ) && ( false == submodel_tree_faces_camera( pModel->Root ) ); ++s_classified_total; if( pModel == nullptr ) { ++s_rejected_no_pmodel; return; } - if( iNumLights != 0 ) { ++s_rejected_lights; return; } + // gfx.instancedlights: the lights go with the matrix of each instance (instance_light_bits()), and the instanced walk + // animates each instance (RaAnimate) and prepares the model with all the parts of the lights shown (RaPrepareInstanced) + if( ( iNumLights != 0 ) && ( false == Global.gfx_instancedlights ) ) { ++s_rejected_lights; return; } + // light colours of its own (lightcolors of the node) go onto the shared submodels as the instance is prepared (RaPrepare), + // which the instances of a bucket don't each get: such an instance is drawn on its own + if( std::ranges::any_of( m_lightcolors, []( glm::vec3 const &Colour ) { return Colour.r >= 0.f; } ) ) { ++s_rejected_lights; return; } if( !m_animlist.empty() ) { ++s_rejected_animlist; return; } if( submodel_tree_blocks_instancing( pModel->Root ) ) { ++s_rejected_animated_submodel; return; } m_instanceable = true; @@ -765,6 +775,71 @@ void TAnimModel::RaPrepare() } } +// the state of the lit and the dark part of a numbered light, as RaPrepare() shows them +void TAnimModel::light_parts_shown( int const Light, bool &Lit, bool &Dark ) const { + + auto const lightmode { static_cast( std::abs( lsLights[ Light ] ) ) }; + switch( lightmode ) { + case ls_On: + case ls_Off: + case ls_Blink: { + // RaPrepare() fades the lit part in over the dark one; an instance shows one part or the other, whole, so the two + // switch over at half the fade. both opaque at once, the order of the draws would pick the one seen + Lit = m_lightopacities[ Light ] >= 0.5f; + Dark = false == Lit; + return; + } + case ls_Dark: + case ls_Home: { + auto const base { static_cast( lightmode ) }; + auto state { + Global.fLuminance - std::max( 0.f, Global.Overcast - 1.f ) <= ( lsLights[ Light ] == base ? DefaultDarkThresholdLevel : lsLights[ Light ] - base ) }; + if( lightmode == ls_Home ) { + // like ls_dark but off late at night + auto const simulationhour { simulation::Time.data().wHour }; + state = state && ( simulationhour < 1 || simulationhour >= 5 ); + } + Lit = state; + Dark = false == state; + return; + } + default: { + // the modes past home leave the light dark (RaPrepare()) + Lit = false; + Dark = true; + return; + } + } +} + +std::uint32_t TAnimModel::instance_light_bits() const { + + if( iNumLights == 0 ) { return 0; } + // bits 0-7 the lit parts shown, bits 8-15 the dark parts, in the mantissa of a float of exponent 128 (0x40000000, a value + // between 2 and 4): a normal number, which the culling of the gpu carries through its matrix products whole, where one of + // these bits alone would be a denormal it may flush to zero (shaders, instance_hides_part()) + std::uint32_t bits { 0x40000000u }; + for( int idx = 0; idx < std::min( iNumLights, iMaxNumLights ); ++idx ) { + bool lit { false }; + bool dark { false }; + light_parts_shown( idx, lit, dark ); + bits |= ( lit ? 1u << idx : 0u ) | ( dark ? 1u << ( 8 + idx ) : 0u ); + } + return bits; +} + +void TAnimModel::RaPrepareInstanced() { + // as RaPrepare(), with both parts of every light shown and opaque: the shaders hide the ones each instance doesn't show + RaPrepare(); + for( int idx = 0; idx < iNumLights; ++idx ) { + for( auto *part : { LightsOn[ idx ], LightsOff[ idx ] } ) { + if( part == nullptr ) { continue; } + part->iVisible = 1; + part->SetVisibilityLevel( 1.f, true, false ); + } + } +} + glm::mat4 const &TAnimModel::rotation_scale() { if( ( false == m_rotationscalevalid ) || ( vAngle != m_rotationscaleangles ) || ( m_scale != m_rotationscalescale ) ) { diff --git a/model/AnimModel.h b/model/AnimModel.h index d4e971615..e3195d0ed 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -182,6 +182,14 @@ public: public: // methods void RaPrepare(); // ustawienie animacji egzemplarza na wzorcu + // RaPrepare() for the instanced draws of a model with lights (gfx.instancedlights): both parts of every light shown, the + // shaders hide what each instance doesn't show by instance_light_bits() + void RaPrepareInstanced(); + // the light state of the instance for its matrix in the instanced draws: the bits 0x40000000 when the model has numbered + // lights, bits 0-7 the lit parts of the slots shown, bits 8-15 their dark parts, as RaPrepare() shows them. 0 without lights + std::uint32_t instance_light_bits() const; + bool has_lights() const { + return iNumLights > 0; } // rotation and scale of the instance as a matrix: rotate y * rotate x * rotate z * scale glm::mat4 const &rotation_scale(); void RaAnimate( unsigned int const Framestamp ); // przeliczenie animacji egzemplarza @@ -242,6 +250,8 @@ public: bool m_cameraindependent { false }; // helper: evaluates current state and updates m_instanceable accordingly. void update_instanceable_flag(); + // whether the lit and the dark part of the light are shown now, as RaPrepare() sets them + void light_parts_shown( int Light, bool &Lit, bool &Dark ) const; // helper: assigns the model and the replacable skin to the instance, and binds light and variant submodels of the model void assign_model( std::string &name, std::string const &texture, bool const ter ); diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index ad0dafae0..48cf7ed18 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -31,6 +31,7 @@ http://mozilla.org/MPL/2.0/. #include "model/Model3d.h" #include "rendering/common/skyocclusion.h" #include +#include #include #include #include @@ -1032,6 +1033,12 @@ void scene_walk::Queue_Instances( scene::basic_cell const *Cell ) Update_Instance_Records( bucket.first.pModel, instancebucket, Cell->m_area.center ); } } + if( m_instancecullpass && bucket_has_lights( instancebucket ) ) { + // the culling of the gpu takes the light states of the instances from their records. only the first pass of the frame has + // them to refresh (Refresh_Light_Records() checks again under the lock), so the others don't stop the walkers for it + gfx::walk_sync::change change { instancebucket.lightsframe != m_framestamp }; + Refresh_Light_Records( instancebucket ); + } if( buckettests && Bucket_Culled( instancebucket ) ) { walk_bucket_culled( instancebucket ); continue; @@ -1062,6 +1069,31 @@ void scene_walk::Queue_Instances( scene::basic_cell const *Cell ) } // makes the records of the instances held by a bucket of a scene cell, with locations relative to Origin +bool scene_walk::bucket_has_lights( scene::basic_cell::instance_bucket const &Bucket ) +{ + auto const found { std::ranges::find_if( Bucket.instances, []( TAnimModel const *Instance ) { return Instance != nullptr; } ) }; + return ( found != Bucket.instances.end() ) && ( *found )->has_lights(); +} + +void scene_walk::Refresh_Light_Records( scene::basic_cell::instance_bucket const &Bucket ) +{ + // once a frame, by the first pass which gets to the bucket + if( ( Bucket.records.size() != Bucket.instances.size() ) || ( Bucket.lightsframe == m_framestamp ) ) { return; } + Bucket.lightsframe = m_framestamp; + for( std::size_t idx = 0; idx < Bucket.instances.size(); ++idx ) { + auto *instance { Bucket.instances[ idx ] }; + if( instance == nullptr ) { continue; } + // the timers of blinking lights go by the frames (once a frame, whichever pass gets here first) + instance->RaAnimate( m_framestamp ); + auto const bits { instance->instance_light_bits() }; + auto &word { Bucket.records[ idx ].rotationscale[ 0 ].w }; + if( std::bit_cast( word ) != bits ) { + word = std::bit_cast( bits ); + Bucket.gpustale = true; + } + } +} + void scene_walk::Update_Instance_Records( TModel3d const *Model, scene::basic_cell::instance_bucket const &Bucket, glm::dvec3 const &Origin ) { // a submodel is drawn only closer than its fSquareMaxDist, see Render( TSubModel * ). past the largest of these @@ -1102,6 +1134,9 @@ void scene_walk::Update_Instance_Records( TModel3d const *Model, scene::basic_ce for( int column = 0; column < 3; ++column ) { record.rotationscale[ column ] = rotationscale[ column ]; } + // the light state of an instance of a model with lights (gfx.instancedlights) in the w left unused, which the culling of the + // gpu carries into the element [0][3] of the matrix it makes of the record (Refresh_Light_Records() keeps it current) + record.rotationscale[ 0 ].w = std::bit_cast( instance->instance_light_bits() ); } // an empty slot keeps its record without flags, and isn't drawn Bucket.records.emplace_back( record ); @@ -1282,6 +1317,8 @@ void scene_walk::Render_Instanced( TModel3d *Model, std::vector TAnimModel *batch_instance { nullptr }; // the first instance drawn; its RaPrepare() and material serve the whole bucket material_data const *batch_material { nullptr }; float farthest_distancesquared { 0.f }; + // a model with numbered lights (gfx.instancedlights): each instance animates its lights, and their state goes with its matrix + auto const lit { ( frontinstance != nullptr ) && frontinstance->has_lights() }; for( auto const &queued : Instances ) { auto const &record { queued.bucket->records[ queued.index ] }; @@ -1315,11 +1352,23 @@ void scene_walk::Render_Instanced( TModel3d *Model, std::vector auto const radiussquared { record.radius * record.radius }; if( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) { continue; } + auto *instance { queued.bucket->instances[ queued.index ] }; if( batch_instance == nullptr ) { - batch_instance = queued.bucket->instances[ queued.index ]; - batch_instance->RaPrepare(); + batch_instance = instance; + if( lit ) { + batch_instance->RaPrepareInstanced(); + light_parts_of( *Model ); + } + else { + batch_instance->RaPrepare(); + } batch_material = batch_instance->Material(); } + std::uint32_t lightbits { 0 }; + if( lit ) { + instance->RaAnimate( m_framestamp ); + lightbits = instance->instance_light_bits(); + } // Build the camera-relative root modelview for this instance: // mv = view * translate(instance_pos - camera_pos) * rotate(instance_angles) * scale(m_scale) @@ -1334,13 +1383,21 @@ void scene_walk::Render_Instanced( TModel3d *Model, std::vector auto const distance { static_cast( distancesquared ) }; farthest_distancesquared = std::max( farthest_distancesquared, distance ); + auto modelview { view_matrix * root }; + if( lit ) { + // the light state in the element [0][3], which is 0 in an affine matrix (effective_modelview() of the shaders) + modelview[ 0 ][ 3 ] = std::bit_cast( lightbits ); + } m_instance_survivors.push_back( { - view_matrix * root, + modelview, distance, static_cast( std::upper_bound( m_instance_lodbounds.begin(), m_instance_lodbounds.end(), distance ) - m_instance_lodbounds.begin() ) } ); } - if( m_instance_survivors.empty() ) { return; } + if( m_instance_survivors.empty() ) { + m_lightparts.clear(); + return; + } // group the modelviews by lod band into a contiguous array, for the upload. every distance in // a band selects the same lod; the nearest one represents the band. @@ -1410,6 +1467,7 @@ void scene_walk::Render_Instanced( TModel3d *Model, std::vector ++m_renderpass.draw_stats.instanced_drawcalls; } + end_light_parts(); m_renderpass.draw_stats.instances += static_cast( m_instance_survivors.size() ); m_renderpass.draw_stats.models += static_cast( m_instance_survivors.size() ); @@ -2138,6 +2196,47 @@ bool scene_walk::Render(TModel3d *Model, material_data const *Material, float co return result; } +void scene_walk::light_parts_of(TModel3d &Model) +{ + m_lightparts.clear(); + auto const &parts{Model.instance_parts()}; + for (std::size_t slot = 0; slot < parts.lights_on.size(); ++slot) + { + if (parts.lights_on[slot] != nullptr) + { + m_lightparts.emplace_back(parts.lights_on[slot], static_cast(1 + slot)); + } + if (parts.lights_off[slot] != nullptr) + { + m_lightparts.emplace_back(parts.lights_off[slot], static_cast(9 + slot)); + } + } +} + +void scene_walk::end_light_parts() +{ + if (m_lightparts.empty()) + { + return; + } + m_lightparts.clear(); + m_lightpart = 0.f; + model_ubs.light_part = 0.f; +} + +void scene_walk::prepare_group_instance(scene_walk &Walk, TAnimModel *Instance, bool const Instanced, TModel3d &Model) +{ + if (Instanced && Instance->has_lights()) + { + // instances of a model with lights (gfx.instancedlights): the parts of the lights are all walked, the state of each instance + // comes with its matrix from the culling (rotationscale[0].w of its record, Refresh_Light_Records()) + Instance->RaPrepareInstanced(); + Walk.light_parts_of(Model); + return; + } + Instance->RaPrepare(); +} + // opaque characters of a text display, laid out in a row the same way as the translucent ones void scene_walk::Render_text(TSubModel *Submodel) { @@ -2173,6 +2272,17 @@ void scene_walk::Render(TSubModel *Submodel) { glDebug("Render TSubModel"); + // the instanced walk of a model with lights: the part of a light the subtree is of, for the shaders (gl::model_ubs::light_part) + auto const outerlightpart{m_lightpart}; + if (false == m_lightparts.empty()) + { + if (auto const found{std::ranges::find(m_lightparts, Submodel, &std::pair::first)}; found != m_lightparts.end()) + { + m_lightpart = found->second; + } + model_ubs.light_part = m_lightpart; + } + if ((Submodel->iVisible) && (TSubModel::fSquareDist >= Submodel->fSquareMinDist) && (TSubModel::fSquareDist < Submodel->fSquareMaxDist) && (false == m_previewing || Submodel->fVisible > 0.f)) { glm::mat4 future_stack = model_ubs.future; @@ -2341,6 +2451,11 @@ void scene_walk::Render(TSubModel *Submodel) if( Submodel->b_Anim < at_SecondsJump ) Submodel->b_Anim = at_None; // wyłączenie animacji dla kolejnego użycia subm */ + if (false == m_lightparts.empty()) + { + m_lightpart = outerlightpart; + model_ubs.light_part = m_lightpart; + } if (Submodel->Next) if (Submodel->iAlpha & Submodel->iFlags & 0x1F000000) Render(Submodel->Next); // dalsze rekurencyjnie diff --git a/rendering/common/scenewalk.h b/rendering/common/scenewalk.h index 0bdfa63e9..fab87edd8 100644 --- a/rendering/common/scenewalk.h +++ b/rendering/common/scenewalk.h @@ -386,6 +386,21 @@ class scene_walk // when > 0, the walk is inside a Render_Instanced() call: the draws are made for this many instances from // m_current_instance_base onwards. The vertex shader reads per-instance modelview from the instance buffer std::size_t m_current_instance_count{0}; + // the instanced walk of a model with numbered lights (gfx.instancedlights): the submodels of the parts of its lights and + // their values of gl::model_ubs::light_part, and the value of the subtree walked now + std::vector> m_lightparts; + float m_lightpart{0.f}; + // fills m_lightparts for the model, from the instance which prepares it + void light_parts_of(TModel3d &Model); + // m_lightparts emptied after the walk of a model, and the part of the model block reset + void end_light_parts(); + // the instance which prepares the model of a group of the gpu culling, for the walk of Walk: of the instances of a bucket + // (Instanced) of a model with lights, with the parts of its lights walked for all the instances; otherwise as for itself + static void prepare_group_instance(scene_walk &Walk, TAnimModel *Instance, bool Instanced, TModel3d &Model); + // whether the instances of the bucket are of a model with numbered lights + static bool bucket_has_lights(scene::basic_cell::instance_bucket const &Bucket); + // the light states of the instances of the bucket put in their records, for the culling of the gpu (once a frame) + void Refresh_Light_Records(scene::basic_cell::instance_bucket const &Bucket); std::uint32_t m_current_instance_base{0}; // the sleepers and timbers drawn by Render_Timbers, by the model and its part or its level of detail: their camera-space // transforms, or with walk_timbers_gpu() the runs of their instances on the gpu; kept from frame to frame to reuse their allocations diff --git a/rendering/common/scenewalkindirect.cpp b/rendering/common/scenewalkindirect.cpp index 661986bec..c4c74551a 100644 --- a/rendering/common/scenewalkindirect.cpp +++ b/rendering/common/scenewalkindirect.cpp @@ -491,7 +491,7 @@ void scene_walk::Walk_Indirect_Draws(gfx::instance_cull const &Cull, bool const // a model drawn on its own: its lights and animations, the way Render( TAnimModel * ) sets them up group.instance->RaAnimate(m_framestamp); } - group.instance->RaPrepare(); + prepare_group_instance(*this, group.instance, group.key->instance == nullptr, *model); auto const *material{group.instance->Material()}; if (material != nullptr) { @@ -593,6 +593,7 @@ void scene_walk::Walk_Indirect_Draws(gfx::instance_cull const &Cull, bool const m_cascadecommands.insert(m_cascadecommands.end(), m_indirectcommands.begin() + walkfirst, m_indirectcommands.end()); } } + end_light_parts(); } m_indirectrecording = false; m_walkcounts.walktime += std::chrono::duration(std::chrono::steady_clock::now() - walkstart).count(); @@ -689,7 +690,7 @@ void scene_walk::Walk_Groups_Parallel(gfx::instance_cull const &Cull, bool const { group.instance->RaAnimate(m_framestamp); } - group.instance->RaPrepare(); + prepare_group_instance(Helper, group.instance, group.key->instance == nullptr, *model); auto const *material{group.instance->Material()}; if (material != nullptr) { @@ -762,6 +763,7 @@ void scene_walk::Walk_Groups_Parallel(gfx::instance_cull const &Cull, bool const } result.spans.push_back(group_span{static_cast(index), band, static_cast(walkfirst), static_cast(Helper.m_indirectdraws.size() - walkfirst)}); } + Helper.end_light_parts(); } result.draws.swap(Helper.m_indirectdraws); result.commands.swap(Helper.m_indirectcommands); diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 1cd33df8b..672fa0e00 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -2220,6 +2220,12 @@ void vulkan14_renderer::gather_ray_draw(gfx::geometry_handle const &Geometry) { return; } + if ((m_current_instance_count > 0) && (model_ubs.light_part != 0.f)) + { + // a part of a light of the instanced models with lights (gfx.instancedlights): which instances show it the shaders tell, the + // rays can't, so the reflections leave the small parts of the lights out + return; + } if ((Geometry.bank == 0) || (Geometry.bank > m_banks.size()) || (m_banks[Geometry.bank - 1] == nullptr)) { return; diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index 6ca017514..f01aef249 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -2056,6 +2056,12 @@ std::uint32_t vulkan14_renderer::walk_instances(glm::mat4 const *Modelviews, std // noted for the ray tracing: the base is the index of the first of them among those noted auto const base{static_cast(m_rtinstances.size())}; m_rtinstances.insert(m_rtinstances.end(), Modelviews, Modelviews + Count); + // the light state an instance of a model with lights carries in the element [0][3] (gfx.instancedlights) isn't a part of + // its transform + for (auto idx = m_rtinstances.size() - Count; idx < m_rtinstances.size(); ++idx) + { + m_rtinstances[idx][0][3] = 0.f; + } return base; } auto &instances{m_context->scene.instances}; diff --git a/scene/scene.h b/scene/scene.h index e92b11988..3fc8e5192 100644 --- a/scene/scene.h +++ b/scene/scene.h @@ -288,6 +288,8 @@ public: mutable float recordradius { -1.f }; mutable float recordradiusmax { 0.f }; mutable unsigned int recordsversion { 0 }; + // the frame the light states of the instances of a model with lights were last put in the records (gfx.instancedlights) + mutable unsigned int lightsframe { 0 }; // place of the records in the record buffer of the gpu culling: first record, room, and the generation of // the buffer it is good for. gpustale: the records changed since they were sent mutable std::uint32_t gpufirst { 0 }; diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index 0e727e3a1..724e1d9b8 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -285,6 +285,8 @@ struct model_draw_s float shadow_tone; // 1 for the parts of the occupied cab, 2 for the low poly interiors, see gl::model_ubs float cab_interior; + // the part of a numbered light the draw is of (gl::model_ubs::light_part) + float light_part; }; layout(std430, binding = MODEL_DRAW_SSBO_BINDING) readonly buffer model_draw_ssbo @@ -312,6 +314,7 @@ layout(location = 11) flat in uint f_model_draw; #define alpha_mult model_draws[MODEL_DRAW].alpha_mult #define shadow_tone model_draws[MODEL_DRAW].shadow_tone #define cab_interior model_draws[MODEL_DRAW].cab_interior +#define light_part model_draws[MODEL_DRAW].light_part #else layout(std140, binding = MODEL_UBO_BINDING) uniform model_ubo { @@ -327,6 +330,8 @@ layout(std140, binding = MODEL_UBO_BINDING) uniform model_ubo float shadow_tone; // 1 for the parts of the occupied cab, 2 for the low poly interiors, see gl::model_ubs float cab_interior; + // the part of a numbered light the draw is of (gl::model_ubs::light_part) + float light_part; }; #endif @@ -405,8 +410,25 @@ layout(std430, binding = INSTANCE_SSBO_BINDING) readonly buffer instance_ssbo mat4 instance_modelview[]; }; +// the light state of an instance of a model with numbered lights (gfx.instancedlights) goes in the element [0][3] of its matrix, +// as the fourth row of an affine matrix is (0, 0, 0, 1): a float of exponent 128 (0x40000000) says there is one, bits 0-7 show the lit parts of the slots +// 0-7, bits 8-15 their dark parts (TAnimModel::instance_light_bits()). a part of a light the instance doesn't show is hidden +bool instance_hides_part(mat4 Instance) { + uint part = uint(light_part + 0.5); + uint lights = floatBitsToUint(Instance[0][3]); + if ((part == 0u) || ((lights & 0xFF800000u) != 0x40000000u)) + return false; + part -= 1u; + uint bit = (part & 7u) + (part >= 8u ? 8u : 0u); + return ((lights >> bit) & 1u) == 0u; +} + mat4 effective_modelview() { - return instance_modelview[gl_BaseInstance + gl_InstanceID] * modelview; + mat4 instance = instance_modelview[gl_BaseInstance + gl_InstanceID]; + bool hidden = instance_hides_part(instance); + instance[0][3] = 0.0; + // a hidden part collapses into a point outside the view (w = 0), its triangles are left out + return hidden ? mat4(0.0) : instance * modelview; } mat3 effective_modelviewnormal() { // instance_modelview can include per-instance scale (uniform or per-axis), diff --git a/shaders/ogl46/instance_cull.comp b/shaders/ogl46/instance_cull.comp index 5a6fd6ca4..c874d880e 100644 --- a/shaders/ogl46/instance_cull.comp +++ b/shaders/ogl46/instance_cull.comp @@ -226,7 +226,11 @@ void write(uint entry, instance_record record, vec3 location, instance_cull_job modelviews[slot] = originview * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(record.position, 1.0)); return; } - modelviews[slot] = view * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + // the word of the light parts (w of the first column, instance_light_bits()) is put back after the product, so a view with a + // translation can't add to the first column with it + mat4 modelview = view * mat4(vec4(record.rotationscale[0].xyz, 0.0), record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + modelview[0][3] = record.rotationscale[0].w; + modelviews[slot] = modelview; } void main() diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index 6d070d7fd..fab9b129b 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -369,6 +369,8 @@ struct model_draw_s float shadow_tone; // 1 for the parts of the occupied cab, 2 for the low poly interiors, see gl::model_ubs float cab_interior; + // the part of a numbered light the draw is of (gl::model_ubs::light_part) + float light_part; }; layout(std430, set = PASS_SET, binding = DRAW_SSBO) readonly buffer model_draw_ssbo @@ -403,6 +405,7 @@ layout(location = 11) flat in uint f_model_draw; #define alpha_mult model_draws[MODEL_DRAW].alpha_mult #define shadow_tone model_draws[MODEL_DRAW].shadow_tone #define cab_interior model_draws[MODEL_DRAW].cab_interior +#define light_part model_draws[MODEL_DRAW].light_part // per-instance modelview matrices of the instanced draws, element 0 the identity. a draw which isn't instanced is drawn with // firstInstance 0, an instanced one from its base instance on, with modelview set to the submodel-local chain (computed from @@ -463,9 +466,27 @@ layout(std430, set = PASS_SET, binding = CLUSTER_INDEX_SSBO) readonly buffer clu }; #ifdef STAGE_VERTEX +// the light state of an instance of a model with numbered lights (gfx.instancedlights) goes in the element [0][3] of its matrix, +// as the fourth row of an affine matrix is (0, 0, 0, 1): a float of exponent 128 (0x40000000) says there is one, bits 0-7 show the lit parts of the slots +// 0-7, bits 8-15 their dark parts (TAnimModel::instance_light_bits()). a part of a light the instance doesn't show is hidden +bool instance_hides_part(mat4 Instance) +{ + uint part = uint(light_part + 0.5); + uint lights = floatBitsToUint(Instance[0][3]); + if ((part == 0u) || ((lights & 0xFF800000u) != 0x40000000u)) + return false; + part -= 1u; + uint bit = (part & 7u) + (part >= 8u ? 8u : 0u); + return ((lights >> bit) & 1u) == 0u; +} + mat4 effective_modelview() { - return instance_modelview[gl_InstanceIndex] * modelview; + mat4 instance = instance_modelview[gl_InstanceIndex]; + bool hidden = instance_hides_part(instance); + instance[0][3] = 0.0; + // a hidden part collapses into a point outside the view (w = 0), its triangles are left out + return hidden ? mat4(0.0) : instance * modelview; } mat3 effective_modelviewnormal() diff --git a/shaders/vk14/instance_cull.comp b/shaders/vk14/instance_cull.comp index c6b8e0983..b07a59b48 100644 --- a/shaders/vk14/instance_cull.comp +++ b/shaders/vk14/instance_cull.comp @@ -234,7 +234,11 @@ void write(uint entry, instance_record record, vec3 location, instance_cull_job modelviews[slot] = originview * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(record.position, 1.0)); return; } - modelviews[slot] = view * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + // the word of the light parts (w of the first column, instance_light_bits()) is put back after the product, so a view with a + // translation can't add to the first column with it + mat4 modelview = view * mat4(vec4(record.rotationscale[0].xyz, 0.0), record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + modelview[0][3] = record.rotationscale[0].w; + modelviews[slot] = modelview; } void main() diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 158ef4877..f29904734 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1927,6 +1927,11 @@ global_settings::ConfigParse_gfx( cParser &Parser, std::string_view const Token Parser.getTokens(1); Parser >> gfx_gpucull_models; } + else if (Token == "gfx.instancedlights") + { + Parser.getTokens(1); + Parser >> gfx_instancedlights; + } else if (Token == "gfx.gpucull.bucketrange") { Parser.getTokens(1); @@ -2788,6 +2793,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "gfx.gpucull.shadows.lamps", gfx_gpucull_shadows_lamps ); export_as_text( Output, "gfx.gpucull.sleepers", gfx_gpucull_sleepers ); export_as_text( Output, "gfx.gpucull.models", gfx_gpucull_models ); + export_as_text( Output, "gfx.instancedlights", gfx_instancedlights ); export_as_text( Output, "gfx.gpucull.bucketrange", gfx_gpucull_bucketrange ); export_as_text( Output, "gfx.gpucull.walkcache", gfx_gpucull_walkcache ); export_as_text( Output, "gfx.geometry.shared", gfx_geometry_shared ); diff --git a/utilities/Globals.h b/utilities/Globals.h index e21731062..3484657b0 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -455,6 +455,10 @@ struct global_settings { // keep them out of the instanced draws) are culled with the instances as well, each one a group of its own, in every pass // culled on the gpu, and with 1 drawn from the result. models with billboards stay on the cpu bool gfx_gpucull_models = true; + // the scenery models with numbered lights (Light_On## / Light_Off##, the lights event) drawn with the instanced draws: the + // state of the lights of each instance goes with its matrix, and the shaders hide the parts it doesn't show. no: each one + // drawn on its own, as before + bool gfx_instancedlights = false; // the buckets of instances of a scene cell lying wholly beyond their range (the largest range of their instances and of // the submodels of their model) are left out of a pass before the culling, the gpu one included, which would leave out // each of their instances anyway