A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(render): a shadow map lands where the atlas says, and a light reads its own
yhh6d94bd290d52
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 1783e0cb3..a32535c54 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -29,7 +29,7 @@ env:test_registry_ondestroy test_view_api_matrixtest_shader_device test_draw_params test_texture_fb test_buffer_devicetest_compressed_format test_batch_builder test_boundary_span test_webgpu_device- test_clip_depth+ test_clip_depth test_shadow_atlastest_text_edit test_render_graph test_device_loss test_physics_interpolationjobs:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9784af9f4..65e4e3b1e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,34 @@ published separately; it ships inside the editor.### Changed+- **A shadow map lands where the atlas says, and a light reads its own.** Two facts+ were spelled as literals, and between them they made "one light casts" a property+ of the code rather than a decision. Where a cascade sits was+ `vec2(i % 2, i / 2) * 0.5` in one shader and its mirror image in the other — four+ quadrants, so four maps, so one light with four cascades and nothing else. Which+ light reads them was `float(i) == u_shadowParams.w`: a single slot number, so the+ other fifteen could not have a map even if the atlas had room.++ `ShadowAtlas` is where a square comes from now — a grid of cells handed out as+ aligned blocks, all-or-nothing, so a caller never gets half a cascade set and+ leaves the rest reading depths belonging to someone else. A tile's rect leaves it+ as DATA the shader indexes (`shadowTile[i]` = origin, side, bias) rather than an+ expression the shader recomputes, which is what makes tiles of different sizes+ cost the shader nothing: what it reads is an origin and a side either way. And a+ light carries its own tile range (`GpuLight2D::shadowMap`), so "which map is mine"+ is a question each light answers instead of a slot number only one can hold.++ Nothing renders differently. The allocator reproduces the old quadrant order+ exactly — its first four claims are the same four squares in the same order — and+ the whole pr tier is unmoved on both backends.++ It is pinned by a C++ test rather than a scene, because **no pixel gate can see+ it**: with `unitRect` sabotaged to report tile 0 for every tile, all 69 scenes+ still pass. A scene whose fragments resolve in one cascade draws the same picture+ whichever tile the other three sample, and `mesh-shadow-cascade` — the only+ multi-cascade gate there is — turns out to be such a scene. That hole predates+ this change: the expression it replaces was never verified either.+- **A device is asked what its clip volume is, instead of being assumed to be GL.**Every projection in the engine is built for clip z in `[-1, 1]` and was handed toboth backends unchanged. WebGPU keeps `[0, 1]` and discards the rest, so andiff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex b826b87aa..a23257269 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -806,17 +806,9 @@ bool RenderFrame::collectEnvironment(const ecs::Light2D& light, const glm::vec3&return true;}-/// Side length of ONE cascade. One size for every scene: the coverage adapts to the-/// camera instead, so the texel density a scene gets is a property of how far it asked-/// the light to reach rather than of a knob nobody can calibrate.-static constexpr u32 kShadowMapSize = 1024;--/// The atlas holding them, 2x2. The RHI has no array textures — the same reason the-/// environment reflection is an atlas — so a cascade is a quadrant of one texture.-static constexpr u32 kShadowAtlasSize = kShadowMapSize * 2;--/// Depth bias in the map's own [0,1] units. Large enough for a 1024 map over a-/// camera-sized area to stop shadowing itself, small enough not to detach contact.+/// Depth bias in the map's own [0,1] units, before the tile it lands in scales it.+/// Large enough for a 1024 tile over a camera-sized area to stop shadowing itself,+/// small enough not to detach contact.static constexpr f32 kShadowBias = 0.0015f;/// The world box every GPU-resident mesh occupies, or false when none does — what@@ -870,9 +862,10 @@ static f32 splitFraction(u32 i, u32 count, f32 nearDist, f32 farDist) {void RenderFrame::renderShadowMap(ecs::Registry& registry) {shadow_texture_id_ = 0;- // Zeroed params first: a matrix that outlived its map would shadow the scene- // against geometry from a frame that no longer exists.- context_.lights().setShadow(nullptr, 0, glm::vec4(0.0f), glm::vec4(0.0f));+ // Zeroed first, and the atlas given back: a tile that outlived its map would+ // shadow the scene against geometry from a frame that no longer exists.+ shadow_atlas_.reset();+ context_.lights().setShadowTiles(nullptr, nullptr, 0, glm::vec4(0.0f));if (!in_frame_ || shadow_light_slot_ < 0 || !device_.isDeviceUsable()) return;if (shadow_rt_ == 0) {@@ -919,10 +912,16 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {const glm::mat4 sceneVP = view_projection_;const GfxDevice::Viewport sceneViewport = device_.viewport();- glm::mat4 matrices[MAX_SHADOW_CASCADES];- glm::vec4 bias(0.0f);+ // Every tile this light needs or none of them: half a cascade set leaves the+ // rest of the fragments reading depths that belong to somebody else.+ const i32 firstTile = shadow_atlas_.allocate(cascades, kShadowCascadeCells);+ if (firstTile < 0) return;+ glm::mat4 matrices[MAX_SHADOW_TILES];+ glm::vec4 tiles[MAX_SHADOW_TILES];+ bool cleared = false;for (u32 c = 0; c < cascades; ++c) {+ const ShadowTile& tile = shadow_atlas_.tile(static_cast<u32>(firstTile) + c);glm::vec3 centre(0.0f);f32 radius = 1.0f;if (cascades == 1) {@@ -952,7 +951,7 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {// Snap to the map's own texel grid, in the light's axes: without it the// cascade slides continuously with the camera and every shadow edge// crawls along the geometry a texel at a time.- const f32 texel = (radius * 2.0f) / static_cast<f32>(kShadowMapSize);+ const f32 texel = (radius * 2.0f) / static_cast<f32>(tile.size);glm::vec3 inLight = glm::vec3(lightRot * glm::vec4(centre, 1.0f));inLight.x = std::floor(inLight.x / texel) * texel;inLight.y = std::floor(inLight.y / texel) * texel;@@ -982,27 +981,26 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {lightProj[2][2] = -1.0f / range;lightProj[3][2] = 0.0f;matrices[c] = lightProj * lightView;- // Scaled by what a texel is worth AND by what a unit of packed depth spans:- // the number stopping the near cascade shadowing itself would let a coarser- // one detach from whatever casts into it.- bias[static_cast<int>(c)] = kShadowBias * std::max(radius, 1.0f)- / (0.5f * static_cast<f32>(kShadowMapSize))- * (4.0f * std::max(radius, 1.0f) / std::max(range, 1.0f));+ // The tile's rect, and in its w the bias it needs — scaled by what a texel+ // of THIS tile is worth: the number stopping a near cascade shadowing+ // itself would let a coarser one detach from whatever casts into it.+ tiles[c] = shadow_atlas_.unitRect(static_cast<u32>(firstTile) + c);+ tiles[c].w = kShadowBias * std::max(radius, 1.0f)+ / (0.5f * static_cast<f32>(tile.size))+ * (4.0f * std::max(radius, 1.0f) / std::max(range, 1.0f));// A self-contained pass, in the shape renderToTarget uses: swap what the frame is// looking through, collect only what casts, draw, and hand the target back.- RenderPassDesc pass{rt->getFramebuffer(), /*clearColor=*/c == 0};- // Depth too: the map keeps the NEAREST occluder, which is the depth buffer's job,- // and last frame's contents would reject this frame's geometry outright.- pass.clearDepth = true;- // White is depth 1 unpacked — "nothing here", so an untouched texel never shadows.+ // The whole atlas, once — a later clear would wipe what an earlier tile+ // wrote, and each tile only ever tests inside its own viewport. White is+ // depth 1 unpacked: a texel nobody drew into never shadows.+ RenderPassDesc pass{rt->getFramebuffer(), /*clearColor=*/!cleared};+ pass.clearDepth = !cleared;pass.clearColorValue[0] = pass.clearColorValue[1] = pass.clearColorValue[2] = 1.0f;pass.clearColorValue[3] = 1.0f;device_.beginRenderPass(pass);- // This cascade's quadrant, in the order cascadeOrigin() reads them back: 0- // lower-left, 1 lower-right, 2 upper-left, 3 upper-right.- device_.setViewport((c % 2) * kShadowMapSize, (c / 2) * kShadowMapSize,- kShadowMapSize, kShadowMapSize);+ cleared = true;+ device_.setViewport(tile.x, tile.y, tile.size, tile.size);view_projection_ = matrices[c];frustum_.extractFromMatrix(matrices[c]);@@ -1033,11 +1031,13 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {device_.invalidatePipelineCache();shadow_texture_id_ = static_cast<u32>(rt->getColorTexture());- context_.lights().setShadow(- matrices, cascades,- glm::vec4(1.0f, static_cast<f32>(cascades), 1.0f / static_cast<f32>(kShadowAtlasSize),- static_cast<f32>(shadow_light_slot_)),- bias);+ context_.lights().setShadowTiles(+ matrices, tiles, cascades,+ glm::vec4(1.0f, 1.0f / static_cast<f32>(kShadowAtlasSize), 0.0f, 0.0f));+ // Which of them this light reads. Without it a fragment would test against every+ // map in the atlas, including ones rendered from somewhere it cannot see.+ context_.lights().setLightShadowTiles(static_cast<u32>(shadow_light_slot_),+ static_cast<u32>(firstTile), cascades);// Back to the frame's own target and camera. The scene has drawn nothing yet, so// re-opening the pass costs a load rather than the frame's contents.diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex caa61ca68..5e2d59bf7 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -7,6 +7,7 @@#include "../rhi/RenderTarget.hpp"#include "./RenderContext.hpp"#include "../store/LightConstants.hpp"+#include "../store/ShadowAtlas.hpp"#include "../RenderTypePlugin.hpp"#ifdef ES_ENABLE_POSTPROCESS#include "./PostProcessPipeline.hpp"@@ -30,6 +31,16 @@ namespace esengine {namespace ecs { struct Light2D; }+/// The one shadow texture every map a frame renders shares. One size for every+/// scene: coverage adapts to the camera instead, so texel density is a property of+/// how far a light was asked to reach rather than of a knob nobody can calibrate.+inline constexpr u32 kShadowAtlasSize = 2048;+/// The unit the atlas is handed out in. A cascade takes a 2x2 block of them; the+/// texel snap and the depth bias are derived from the tile that comes back, not+/// from this, so a smaller tile is a smaller answer rather than a wrong one.+inline constexpr u32 kShadowCellSize = 512;+inline constexpr u32 kShadowCascadeCells = 2;+struct Plane {glm::vec3 normal;f32 distance;@@ -362,6 +373,9 @@ private:glm::vec3 shadow_light_dir_{0.0f, 0.0f, -1.0f};f32 shadow_light_extent_ = 0.0f;RenderTargetManager::Handle shadow_rt_ = 0;+ /// Who owns which square of it. Rebuilt every frame: a tile means nothing once+ /// the depths in it belong to a frame that is gone.+ ShadowAtlas shadow_atlas_{kShadowAtlasSize, kShadowCellSize};/// The map's colour texture, handed to every mesh that receives it. 0 = none this frame.u32 shadow_texture_id_ = 0;/// The frame environment's reflection atlas, on the same terms. 0 = none this frame.diff --git a/src/esengine/renderer/store/LightConstants.hpp b/src/esengine/renderer/store/LightConstants.hppindex ec69cb900..9ee59f321 100644--- a/src/esengine/renderer/store/LightConstants.hpp+++ b/src/esengine/renderer/store/LightConstants.hpp@@ -53,16 +53,22 @@ inline constexpr u32 MAX_LIGHTS_2D = 16;inline constexpr u32 MAX_OCCLUDERS_2D = 8;/**- * @brief Cascades one directional shadow map is split into, laid out 2x2 in one- * atlas texture (the RHI has no array textures, the same reason the- * environment reflection is an atlas). Each covers a slice of the view,- * so the near one spends its texels on what is near instead of on the- * whole scene. Must match `u_shadowMatrix[..]` in the injected shaders.+ * @brief Slices one directional shadow map is split into, each covering a stretch+ * of the view — so the near one spends its texels on what is near instead+ * of on the whole scene. Where they LAND is the atlas's answer, not this+ * number's: a cascade claims a tile like anything else that casts.*/inline constexpr u32 MAX_SHADOW_CASCADES = 4;/**- * @brief One 2D light, std140-packed (four vec4s, 64 bytes, 16-aligned).+ * @brief Max shadow tiles one frame's atlas hands out — the shader's array bound.+ * @details Not the same number as the cascades above: a cascade is one reason to want+ * a tile and a spot light is another, and the atlas does not care which asked.+ */+inline constexpr u32 MAX_SHADOW_TILES = 8;++/**+ * @brief One 2D light, std140-packed (five vec4s, 80 bytes, 16-aligned).* @details posDir: xy = world position (point/spot) or aim direction (directional); z = type* (0 = point, 1 = directional, 2 = spot); w = falloff radius in world units for* point/spot, and the aim's third component for directional — the two never share@@ -71,6 +77,7 @@ inline constexpr u32 MAX_SHADOW_CASCADES = 4;* spot: xy = normalized cone axis, z = cos(innerHalfAngle), w = cos(outerHalfAngle)* (spot only; zero for other types). Ambient lights are folded into* LightConstants::ambient instead of occupying a slot.+ * shadowMap: x = first atlas tile, y = tile count (0 = casts no map).* shadow: x = penumbra softness (light-source half-extent in world units; 0 = hard,* backward-compatible); y = directional shadow march distance (world units; 0 = a* directional light casts no shadow); z = a point/spot light's world height, which@@ -82,13 +89,16 @@ struct GpuLight2D {glm::vec4 color{0.0f};glm::vec4 spot{0.0f};glm::vec4 shadow{0.0f};+ /// x = this light's first tile in the shadow atlas, y = how many it owns; zw unused.+ /// y = 0 is a light with no map, which is every light that did not ask for one.+ glm::vec4 shadowMap{0.0f};};/*** @brief CPU mirror of the GLSL LightConstants block (std140).* @details ambient: rgb = summed ambient color, a = active light count (informational).- * std140 array-of-struct stride is 64 (each GpuLight2D is four 16-aligned vec4s), so- * lights start at offset 16 and the lights array spans 64*MAX_LIGHTS_2D bytes.+ * std140 array-of-struct stride is 80 (each GpuLight2D is five 16-aligned vec4s), so+ * lights start at offset 16 and the lights array spans 80*MAX_LIGHTS_2D bytes.*/struct LightConstants {glm::vec4 ambient{0.0f};@@ -100,18 +110,16 @@ struct LightConstants {/// fragment→light segment (or, for directional, the fragment→far-along-light-dir segment)/// crosses any box.glm::vec4 occluders[MAX_OCCLUDERS_2D];- /// World -> each cascade's clip space, for the one directional light casting a- /// map. Identity where a cascade is unused; `shadowParams.x` says whether any- /// may be read and `shadowParams.y` how many.- glm::mat4 shadowMatrix[MAX_SHADOW_CASCADES];- /// x = 1 when a shadow map was rendered this frame — the master switch, so w's- /// zeroed default cannot darken slot 0 before one exists; y = how many cascades- /// carry one; z = one texel of the atlas; w = the light slot that cast it.+ /// World -> tile i's clip space. Identity where a tile is unclaimed; which tiles+ /// a light may read are the ones its own `shadowMap` names.+ glm::mat4 shadowMatrix[MAX_SHADOW_TILES];+ /// Where tile i sits: xy = its low corner as a fraction of the atlas, z = its side+ /// as one, w = its depth bias. DATA and not an expression the shader recomputes, so+ /// tiles need not all be one size; the bias derives from what that one covers.+ glm::vec4 shadowTile[MAX_SHADOW_TILES];+ /// x = 1 when the atlas holds a map this frame — the master switch, so a zeroed+ /// tile record cannot darken anything before one exists; y = one texel of the atlas.glm::vec4 shadowParams{0.0f};- /// Depth bias per cascade, in the map's own [0,1] units, xyzw = cascade 0..3.- /// Per cascade because one covers less world in the same texels than the next:- /// a bias that stops the near one shadowing itself lets the far one detach.- glm::vec4 shadowBias{0.0f};/// The frame environment's nine irradiance coefficients, rgb in xyz. Zero when/// no light carries one, which makes the flat `ambient` term the order-zero case/// of one expression rather than a second path. vec4: std140 pads vec3 anyway.@@ -125,9 +133,10 @@ struct LightConstants {glm::vec4 envTint{0.0f};};-static_assert(sizeof(GpuLight2D) == 64, "GpuLight2D must be std140-tight (four vec4s)");-static_assert(sizeof(LightConstants) == 16 + 64 * MAX_LIGHTS_2D + 16 + 16 * MAX_OCCLUDERS_2D- + 64 * MAX_SHADOW_CASCADES + 16 + 16 + 16 * 9 + 16 + 16,+static_assert(sizeof(GpuLight2D) == 80, "GpuLight2D must be std140-tight (five vec4s)");+static_assert(sizeof(LightConstants) == 16 + 80 * MAX_LIGHTS_2D + 16 + 16 * MAX_OCCLUDERS_2D+ + 64 * MAX_SHADOW_TILES + 16 * MAX_SHADOW_TILES+ + 16 + 16 * 9 + 16 + 16,"LightConstants must match the std140 GLSL block layout");} // namespace esenginediff --git a/src/esengine/renderer/store/LightStore.hpp b/src/esengine/renderer/store/LightStore.hppindex af5b0f5e3..b5719674a 100644--- a/src/esengine/renderer/store/LightStore.hpp+++ b/src/esengine/renderer/store/LightStore.hpp@@ -69,16 +69,26 @@ public:dirty_ = true;}- /// Hands over the shadow map a frame rendered: one world -> clip matrix per- /// cascade, the bias each needs, and the params whose x is the master switch.- /// Zeroed `params` when no light cast one, so no matrix outlives its map.- void setShadow(const glm::mat4* matrices, u32 count, const glm::vec4& params,- const glm::vec4& bias) {- for (u32 i = 0; i < MAX_SHADOW_CASCADES; ++i) {+ /// Hands over the shadow tiles a frame rendered: per tile a world -> clip matrix+ /// and the atlas rect it was drawn into (bias in w), plus the params whose x is+ /// the master switch. Zeroed when nothing cast, so no matrix outlives its map.+ void setShadowTiles(const glm::mat4* matrices, const glm::vec4* tiles, u32 count,+ const glm::vec4& params) {+ for (u32 i = 0; i < MAX_SHADOW_TILES; ++i) {data_.shadowMatrix[i] = i < count ? matrices[i] : glm::mat4(1.0f);+ data_.shadowTile[i] = i < count ? tiles[i] : glm::vec4(0.0f);}data_.shadowParams = params;- data_.shadowBias = bias;+ dirty_ = true;+ }++ /// Names the atlas tiles light @p slot casts into. What lets a fragment read the+ /// right map once more than one light has rendered one; a slot nobody names keeps+ /// the zeroed count, which is a light with no map.+ void setLightShadowTiles(u32 slot, u32 first, u32 tiles) {+ if (slot >= count_) return;+ data_.lights[slot].shadowMap = glm::vec4(static_cast<f32>(first),+ static_cast<f32>(tiles), 0.0f, 0.0f);dirty_ = true;}diff --git a/src/esengine/renderer/store/ShadowAtlas.hpp b/src/esengine/renderer/store/ShadowAtlas.hppnew file mode 100644index 000000000..44bef358f--- /dev/null+++ b/src/esengine/renderer/store/ShadowAtlas.hpp@@ -0,0 +1,133 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ShadowAtlas.hpp+ * @brief Who owns which square of the one shadow texture.+ * @details The RHI has no array textures, so every shadow map a frame renders shares+ * one atlas — and something has to say where each lands. That was four+ * hard-coded quadrants, which is why exactly one light could cast.+ *+ * A tile's rect leaves here as DATA the shader indexes, not an expression it+ * recomputes, so tiles of different sizes cost the shader nothing: what a+ * light reads is an origin and a side either way.+ */+#pragma once++#include "../../core/Types.hpp"+#include "./LightConstants.hpp"++#include <glm/glm.hpp>++#include <vector>++namespace esengine {++/** @brief One tile's square, in atlas texels. */+struct ShadowTile {+ u32 x = 0;+ u32 y = 0;+ u32 size = 0;+};++/**+ * @brief A square texture divided into a grid of cells, handed out as square blocks.+ *+ * @details Cell-aligned rather than free-form: a block of n x n cells can only start+ * on a multiple of n, which is what keeps allocation a scan instead of a+ * packing problem, and what makes the order it produces reproducible.+ */+class ShadowAtlas {+public:+ ShadowAtlas(u32 atlasSize, u32 cellSize)+ : size_(atlasSize), cell_(cellSize > 0 ? cellSize : 1),+ cols_(atlasSize / (cellSize > 0 ? cellSize : 1)) {+ used_.assign(static_cast<usize>(cols_) * cols_, false);+ }++ /** @brief Gives the whole atlas back. Called once per frame, before any claim. */+ void reset() {+ tiles_.clear();+ used_.assign(used_.size(), false);+ }++ /**+ * @brief Claims @p count tiles of @p cells x @p cells cells each.+ * @return The first tile's index, or -1 when the atlas or the tile budget has no+ * room for all of them — all or nothing, so a caller never renders half a+ * cascade set and leaves the rest reading someone else's depths.+ */+ i32 allocate(u32 count, u32 cells) {+ if (count == 0 || cells == 0 || cells > cols_) return -1;+ if (tiles_.size() + count > MAX_SHADOW_TILES) return -1;+ const usize before = tiles_.size();+ for (u32 i = 0; i < count; ++i) {+ if (!claim(cells)) {+ tiles_.resize(before);+ rebuildUsed();+ return -1;+ }+ }+ return static_cast<i32>(before);+ }++ u32 tileCount() const { return static_cast<u32>(tiles_.size()); }+ const ShadowTile& tile(u32 index) const { return tiles_[index]; }++ /**+ * @brief Tile @p index as a fraction of the atlas: (origin.x, origin.y, side, 0).+ * @details The origin is the low corner in the convention the atlas is RENDERED+ * in, which is GL's. A backend that samples the other way up turns it+ * over where it samples — see the WGSL twin of shadowFactor3D.+ */+ glm::vec4 unitRect(u32 index) const {+ const ShadowTile& t = tiles_[index];+ const f32 inv = 1.0f / static_cast<f32>(size_);+ return {static_cast<f32>(t.x) * inv, static_cast<f32>(t.y) * inv,+ static_cast<f32>(t.size) * inv, 0.0f};+ }++private:+ bool claim(u32 cells) {+ for (u32 cy = 0; cy + cells <= cols_; cy += cells) {+ for (u32 cx = 0; cx + cells <= cols_; cx += cells) {+ if (!free(cx, cy, cells)) continue;+ mark(cx, cy, cells, true);+ tiles_.push_back({cx * cell_, cy * cell_, cells * cell_});+ return true;+ }+ }+ return false;+ }++ bool free(u32 cx, u32 cy, u32 cells) const {+ for (u32 y = cy; y < cy + cells; ++y) {+ for (u32 x = cx; x < cx + cells; ++x) {+ if (used_[static_cast<usize>(y) * cols_ + x]) return false;+ }+ }+ return true;+ }++ void mark(u32 cx, u32 cy, u32 cells, bool value) {+ for (u32 y = cy; y < cy + cells; ++y) {+ for (u32 x = cx; x < cx + cells; ++x) {+ used_[static_cast<usize>(y) * cols_ + x] = value;+ }+ }+ }++ void rebuildUsed() {+ used_.assign(used_.size(), false);+ for (const ShadowTile& t : tiles_) {+ mark(t.x / cell_, t.y / cell_, t.size / cell_, true);+ }+ }++ u32 size_;+ u32 cell_;+ u32 cols_;+ std::vector<ShadowTile> tiles_;+ std::vector<bool> used_;+};++} // namespace esenginediff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 891695df5..1520163d4 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -725,15 +725,15 @@ fn linearToSrgb(c : vec3f) -> vec3f {})";-const char* kLit2DHeaderWGSL = R"(struct Light2D { posDir : vec4f, color : vec4f, spot : vec4f, shadow : vec4f };+const char* kLit2DHeaderWGSL = R"(struct Light2D { posDir : vec4f, color : vec4f, spot : vec4f, shadow : vec4f, shadowMap : vec4f };struct LightConstants {u_ambient : vec4f,u_lights : array<Light2D, 16>,u_occluderCount : vec4f,u_occluders : array<vec4f, 8>,- u_shadowMatrix : array<mat4x4f, 4>,+ u_shadowMatrix : array<mat4x4f, 8>,+ u_shadowTile : array<vec4f, 8>,u_shadowParams : vec4f,- u_shadowBias : vec4f,u_envIrradiance : array<vec4f, 9>,u_envParams : vec4f,u_envTint : vec4f,@@ -746,40 +746,32 @@ fn packDepth(d : f32) -> vec3f {fn unpackDepth(c : vec3f) -> f32 {return dot(c, vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));}-// The ONE place the two backends must not agree. Both WRITE the same quadrant (a rect-// arrives in GL's terms and is flipped there), but v = 0 samples a texture's bottom in-// GL and its top here: this turns the atlas over, cascadeUV the square inside it.-fn cascadeOrigin(index : i32) -> vec2f {- return vec2f(f32(index % 2), 1.0 - f32(index / 2)) * 0.5;-}-fn cascadeUV(uv : vec2f) -> vec2f {- return vec2f(uv.x, 1.0 - uv.y) * 0.5;-}-fn shadowFactor3D(worldPos : vec3f) -> f32 {+fn shadowFactor3D(worldPos : vec3f, first : i32, count : i32) -> f32 {#ifndef ES_RECEIVE_SHADOWreturn 1.0;#elseif (lc.u_shadowParams.x < 0.5) { return 1.0; }- let count = i32(lc.u_shadowParams.y);- // Copied out of the uniform first: a vector in that address space cannot be- // indexed by a value the shader computes, and what comes back is a pipeline- // that will not build with nothing in the log about a shader.- var bias = lc.u_shadowBias;- // Nearest cascade first: they overlap, and the first one covering a fragment- // is the one that spends the most texels on it.- for (var c = 0; c < 4; c++) {- if (c >= count) { break; }- let lcp = lc.u_shadowMatrix[c] * vec4f(worldPos, 1.0);+ // Nearest tile first: a light's tiles overlap, and the first one covering a+ // fragment is the one that spends the most texels on it.+ for (var k = 0; k < 8; k++) {+ if (k >= count) { break; }+ let t = first + k;+ let lcp = lc.u_shadowMatrix[t] * vec4f(worldPos, 1.0);let proj = lcp.xyz / lcp.w;let uv = proj.xy * 0.5 + 0.5;if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { continue; }- let here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - bias[c];- let base = cascadeOrigin(c);+ let rect = lc.u_shadowTile[t];+ let here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - rect.w;+ // The ONE place the two backends must not agree: v = 0 samples a texture's+ // bottom in GL and its top here, and the rect arrives with its low corner in+ // GL's terms — so the tile and the square inside it are both turned over.+ let base = vec2f(rect.x, 1.0 - rect.y - rect.z);var lit = 0.0;for (var y = 0; y < 2; y++) {for (var x = 0; x < 2; x++) {- let o = (vec2f(f32(x), f32(y)) - 0.5) * lc.u_shadowParams.z;- let d = unpackDepth(textureSampleLevel(t2, s2, base + cascadeUV(uv) + o, 0.0).rgb);+ let o = (vec2f(f32(x), f32(y)) - 0.5) * lc.u_shadowParams.y;+ let at = base + vec2f(uv.x, 1.0 - uv.y) * rect.z + o;+ let d = unpackDepth(textureSampleLevel(t2, s2, at, 0.0).rgb);if (d >= here) { lit += 1.0; }}}@@ -985,8 +977,9 @@ fn applyLightingPBR(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f, metaif (castShadow && col.a > 0.0 && atten > 0.0) {atten *= shadowFactor2D(worldPos.xy, aim, sh.x);}- if (f32(i) == lc.u_shadowParams.w && atten > 0.0) {- atten *= shadowFactor3D(worldPos);+ let sm = lc.u_lights[i].shadowMap;+ if (sm.y > 0.0 && atten > 0.0) {+ atten *= shadowFactor3D(worldPos, i32(sm.x), i32(sm.y));}let ndotl = max(dot(N, L), 0.0);let radiance = col.rgb * (col.a * ndotl * atten);@@ -1299,15 +1292,16 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p// GpuLight2D = four vec4s).if (stage == ShaderStage::Fragment && parsed.domain == "Lit2D") {static const char* kLit2DHeader =- "struct Light2D { highp vec4 posDir; highp vec4 color; highp vec4 spot; highp vec4 shadow; };\n"+ "struct Light2D { highp vec4 posDir; highp vec4 color; highp vec4 spot; highp vec4 shadow;"+ " highp vec4 shadowMap; };\n""layout(std140) uniform LightConstants {\n"" highp vec4 u_ambient;\n"" Light2D u_lights[16];\n"" highp vec4 u_occluderCount;\n" // x = active occluder count" highp vec4 u_occluders[8];\n" // world AABBs (minX,minY,maxX,maxY)- " highp mat4 u_shadowMatrix[4];\n" // world -> each cascade's clip- " highp vec4 u_shadowParams;\n" // x = has map, y = cascades, z = texel- " highp vec4 u_shadowBias;\n" // per-cascade depth bias+ " highp mat4 u_shadowMatrix[8];\n" // world -> each atlas tile's clip+ " highp vec4 u_shadowTile[8];\n" // xy = origin, z = side, w = bias+ " highp vec4 u_shadowParams;\n" // x = has map, y = one atlas texel" highp vec4 u_envIrradiance[9];\n" // SH9, rgb in xyz; zero = no environment" highp vec4 u_envParams;\n" // x = has map, y = range, z = maxLod, w = face" highp vec4 u_envTint;\n" // the ambient light's colour, scaling both halves@@ -1334,38 +1328,31 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p// Visibility of a world point from the light that rendered the map. Depth is// written and compared through the SAME matrix and expression, so the two// backends' clip-z conventions cancel. 2x2 taps: one is a staircase.- // Where a cascade's [0,1] square sits in the 2x2 atlas: 0 lower-left,- // 1 lower-right, 2 upper-left, 3 upper-right. One expression, so both- // backends land on one texel.- "highp vec2 cascadeOrigin(in int index) {\n"- " return vec2(float(index - (index / 2) * 2), float(index / 2)) * 0.5;\n"- "}\n"- "highp vec2 cascadeUV(in highp vec2 uv) {\n"- " return uv * 0.5;\n"- "}\n"- "highp float shadowFactor3D(in highp vec3 worldPos) {\n"+ "highp float shadowFactor3D(in highp vec3 worldPos, in int first, in int count) {\n""#ifndef ES_RECEIVE_SHADOW\n"" return 1.0;\n""#else\n"" if (u_shadowParams.x < 0.5) return 1.0;\n"- " int count = int(u_shadowParams.y);\n"- // Nearest cascade first: they overlap, and the first one covering a- // fragment is the one that spends the most texels on it.- " for (int c = 0; c < 4; ++c) {\n"- " if (c >= count) break;\n"- " highp vec4 lc = u_shadowMatrix[c] * vec4(worldPos, 1.0);\n"+ // Nearest tile first: a light's tiles overlap, and the first one covering+ // a fragment is the one that spends the most texels on it.+ " for (int k = 0; k < 8; ++k) {\n"+ " if (k >= count) break;\n"+ " int t = first + k;\n"+ " highp vec4 lc = u_shadowMatrix[t] * vec4(worldPos, 1.0);\n"" highp vec3 proj = lc.xyz / lc.w;\n"" highp vec2 uv = proj.xy * 0.5 + 0.5;\n"- // Outside every cascade is lit: a map covers what the camera can see,- // and darkening everything beyond it would be a visible square of night.+ // Outside every tile is lit: a map covers what the camera can see, and+ // darkening everything beyond it would be a visible square of night." if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) continue;\n"- " highp float here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - u_shadowBias[c];\n"- " highp vec2 base = cascadeOrigin(c);\n"+ // The tile's rect is data, so a tile need not be the same size as its+ // neighbour and this expression does not care which one it is reading.+ " highp vec4 rect = u_shadowTile[t];\n"+ " highp float here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - rect.w;\n"" highp float lit = 0.0;\n"" for (int y = 0; y < 2; ++y) {\n"" for (int x = 0; x < 2; ++x) {\n"- " highp vec2 o = (vec2(float(x), float(y)) - 0.5) * u_shadowParams.z;\n"- " highp vec2 at = base + cascadeUV(uv) + o;\n"+ " highp vec2 o = (vec2(float(x), float(y)) - 0.5) * u_shadowParams.y;\n"+ " highp vec2 at = rect.xy + uv * rect.z + o;\n"" lit += unpackDepth(texture(u_shadowMap, at).rgb) < here ? 0.0 : 1.0;\n"" }\n"" }\n"@@ -1624,10 +1611,12 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" if (castShadow && col.a > 0.0 && atten > 0.0) {\n"" atten *= shadowFactor2D(worldPos.xy, target, sh.x);\n"" }\n"- // One map, one light: params.w names the slot that rendered it, so the- // other fifteen are not darkened by someone else's occluders.- " if (float(i) == u_shadowParams.w && atten > 0.0) {\n"- " atten *= shadowFactor3D(worldPos);\n"+ // The tiles this light rendered into, which are its own: a fragment+ // tested against every map in the atlas would be darkened by geometry+ // seen from somewhere no light reaching it is standing.+ " highp vec4 sm = u_lights[i].shadowMap;\n"+ " if (sm.y > 0.0 && atten > 0.0) {\n"+ " atten *= shadowFactor3D(worldPos, int(sm.x), int(sm.y));\n"" }\n"" highp float ndotl = max(dot(N, L), 0.0);\n"" highp vec3 radiance = col.rgb * (col.a * ndotl * atten);\n"diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex 51c2186fc..b6a71993e 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -91,6 +91,16 @@ target_include_directories(test_clip_depth PRIVATE)add_test(NAME test_clip_depth COMMAND test_clip_depth)+# Shadow atlas allocation. Header-only, and deliberately here rather than in a+# pixel gate: a scene whose fragments resolve in one cascade draws the same+# picture whichever tile the others sample.+add_executable(test_shadow_atlas renderer/test_shadow_atlas.cpp)+target_include_directories(test_shadow_atlas PRIVATE+ ${CMAKE_SOURCE_DIR}/src+ ${CMAKE_SOURCE_DIR}/third_party/glm+)+add_test(NAME test_shadow_atlas COMMAND test_shadow_atlas)+# Shader variant (feature-permutation) system (RC7-6). Compiles ShaderParser.cpp# directly — no GL/engine link — and checks #pragma feature parsing + #define injection.add_executable(test_shader_variantdiff --git a/tests/renderer/test_shadow_atlas.cpp b/tests/renderer/test_shadow_atlas.cppnew file mode 100644index 000000000..2c77328c6--- /dev/null+++ b/tests/renderer/test_shadow_atlas.cpp@@ -0,0 +1,96 @@+// Who owns which square of the shadow texture, pinned here because no pixel gate+// can see it: a scene whose fragments all resolve in one cascade draws the same+// picture whichever tile the other three sample.++#include "esengine/renderer/store/ShadowAtlas.hpp"++#include <cstdio>+#include <cmath>++using namespace esengine;++static int g_failures = 0;+#define CHECK(cond, msg) \+ do { \+ if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; } \+ else { std::printf("ok: %s\n", msg); } \+ } while (0)++static bool near(f32 a, f32 b) { return std::fabs(a - b) < 1e-6f; }++static bool isTile(const ShadowTile& t, u32 x, u32 y, u32 size) {+ return t.x == x && t.y == y && t.size == size;+}++static bool isRect(const glm::vec4& r, f32 x, f32 y, f32 size) {+ return near(r.x, x) && near(r.y, y) && near(r.z, size);+}++int main() {+ // The frame's own atlas: 2048 handed out in 512 cells, a cascade taking 2x2.+ ShadowAtlas atlas(2048, 512);++ const i32 first = atlas.allocate(4, 2);+ CHECK(first == 0, "the first claim starts at tile 0");+ CHECK(atlas.tileCount() == 4, "four cascades claim four tiles");++ // The order the expression this replaced produced: 0 lower-left, 1 lower-right,+ // 2 upper-left, 3 upper-right. A different order is a different picture, and+ // no pixel gate would say so.+ CHECK(isTile(atlas.tile(0), 0, 0, 1024), "tile 0 is the lower-left quadrant");+ CHECK(isTile(atlas.tile(1), 1024, 0, 1024), "tile 1 is the lower-right quadrant");+ CHECK(isTile(atlas.tile(2), 0, 1024, 1024), "tile 2 is the upper-left quadrant");+ CHECK(isTile(atlas.tile(3), 1024, 1024, 1024), "tile 3 is the upper-right quadrant");++ // What the shader indexes with — the same squares as a fraction of the atlas.+ CHECK(isRect(atlas.unitRect(0), 0.0f, 0.0f, 0.5f), "tile 0's rect is (0, 0, 1/2)");+ CHECK(isRect(atlas.unitRect(1), 0.5f, 0.0f, 0.5f), "tile 1's rect is (1/2, 0, 1/2)");+ CHECK(isRect(atlas.unitRect(2), 0.0f, 0.5f, 0.5f), "tile 2's rect is (0, 1/2, 1/2)");+ CHECK(isRect(atlas.unitRect(3), 0.5f, 0.5f, 0.5f), "tile 3's rect is (1/2, 1/2, 1/2)");++ // A full atlas has nothing left, and says so rather than handing out a square+ // somebody else is already drawing into.+ CHECK(atlas.allocate(1, 2) < 0, "a full atlas refuses the next claim");++ // All or nothing: a caller that gets half a cascade set would leave the rest+ // reading depths that belong to another light.+ ShadowAtlas partial(2048, 512);+ CHECK(partial.allocate(3, 2) == 0, "three of the four fit");+ CHECK(partial.allocate(2, 2) < 0, "two more do not, and the claim is refused");+ CHECK(partial.tileCount() == 3, "a refused claim leaves the atlas as it was");+ CHECK(partial.allocate(1, 2) == 3, "and the one that does fit still can");++ // Tiles need not all be one size — which is the whole reason the rect is data.+ // A spot light taking one cell sits beside a cascade taking four.+ ShadowAtlas mixed(2048, 512);+ CHECK(mixed.allocate(1, 2) == 0, "a 2x2 block lands first");+ const i32 small = mixed.allocate(2, 1);+ CHECK(small == 1, "single cells claim after it");+ CHECK(isTile(mixed.tile(1), 1024, 0, 512), "the first single cell clears the block");+ CHECK(isRect(mixed.unitRect(1), 0.5f, 0.0f, 0.25f), "and reports a quarter-side rect");++ // The budget is the shader's array bound, not the texture's room: a 4096 atlas+ // of 512 cells has 64 of them and the block still stops at MAX_SHADOW_TILES.+ ShadowAtlas wide(4096, 512);+ CHECK(wide.allocate(MAX_SHADOW_TILES + 1, 1) < 0, "the tile budget is a hard bound");+ CHECK(wide.allocate(MAX_SHADOW_TILES, 1) == 0, "and exactly the bound fits");++ // A frame gives it all back: a tile means nothing once the depths in it are+ // from a frame that is gone.+ ShadowAtlas reused(2048, 512);+ reused.allocate(4, 2);+ reused.reset();+ CHECK(reused.tileCount() == 0, "reset empties the atlas");+ CHECK(reused.allocate(4, 2) == 0, "and the next frame claims the same squares");+ CHECK(isTile(reused.tile(0), 0, 0, 1024), "starting again at the lower-left");++ // A block larger than the grid has nowhere to go, and a zero-sized claim is not+ // a claim — both answer rather than indexing something that is not there.+ ShadowAtlas small2(1024, 512);+ CHECK(small2.allocate(1, 4) < 0, "a block wider than the atlas is refused");+ CHECK(small2.allocate(0, 2) < 0, "so is a claim for no tiles");+ CHECK(small2.allocate(1, 0) < 0, "so is a claim for empty ones");++ std::printf(g_failures ? "\n%d check(s) failed\n" : "\nall checks passed\n", g_failures);+ return g_failures == 0 ? 0 : 1;+}