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
perf(shadow): a sun's map leaves out the casters whose shadow cannot reach what the camera sees
yhh0149d20eef37
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e42ffa6ef..4e50ccfcf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -30,6 +30,7 @@ published separately; it ships inside the editor.### Changed+- **A sun's shadow map leaves out the casters that shade nothing the camera sees.** A directional light with a fixed reach (`shadowExtent`) draws one map of its whole reach, so every caster in it was drawn however much of it the camera looked at. A caster's shadow is the segment its bounds sweep along the light's rays down to the lowest thing that can receive it; one whose segment stays outside the camera's view is no longer drawn into the map. The picture is the same (a mean difference under half a level on the Terrain & Water example); its shadow pass is 4.0 to 1.7 ms and 4.7 to 1.4 ms at two of its viewpoints on an RTX 3060, and unchanged where the camera sees the whole island. A cascaded sun (no `shadowExtent`) already fits its maps to the view and is as it was; a frame with a planar reflection keeps every caster.- **The sea takes the sun's shadow as one hard edge.** The water lit itself with the sun's full soft shadow (a search for blockers and a filter of up to sixty-four taps), which a surface the sun seldom leaves and whose edge the waves hide does not need; a shader can now set `g_shadowHard` before it lights to read the shadow as the edge a source with no size throws, nine taps, and the water does. The picture is the same to the eye (a mean difference of a quarter of a level on the Terrain & Water example); the water is about 0.5 ms shorter on an RTX 3060.- **A lit surface no longer works out the light slots nothing shines from.** The light block holds sixteen lights and a scene has one or two, but the lighting loop shaded all sixteen: every empty slot paid for its distance, its direction and the whole specular lobe, to add zero. A slot with no intensity returns at once now; the picture is the same to the pixel gates on WebGL2 and WebGPU. A frame of the Terrain & Water example is 4 to 6 ms shorter on an RTX 3060 (the trees' shading alone is more than a third faster).- **The sky's clouds and the fog's light shafts cost a third of what they did.** The cloud layer, the shadow it casts on the ground and the sun's light through the haze are smooth and were worked out for every pixel of the frame; they are worked out at half size now, and each pixel reads them back from the four texels around it, weighted by how near their depth is to its own, so nothing is carried across the edge of a hill or a leaf. The dome, the sun, the moon and the stars, which have an edge, stay full size. The picture is the same to the eye (a mean difference of a third of a level of 255 on the Terrain & Water example); a frame of it is 5 ms shorter on an RTX 3060 (25.6 to 20.1). The sky and the height fog are two passes each in a chain now, `sky_clouds` and `sky_composite`, `fog_volume` and `fog_composite`.diff --git a/docs/TERRAIN_WATER_GPU_COST.md b/docs/TERRAIN_WATER_GPU_COST.mdindex 232aca9c2..511c47fcf 100644--- a/docs/TERRAIN_WATER_GPU_COST.md+++ b/docs/TERRAIN_WATER_GPU_COST.md@@ -444,3 +444,18 @@### 水面的阴影(2026-10-26,更正)上一节说“水的主要成本是它自己的阴影查找”,**这个说法错了**。水着色器里自己的那一次阴影采样(焦散处)和焦散本身都量了:剪掉后水段不变(1.18 对 1.18、2.15 对 2.13)。关掉阴影后水变便宜,是因为水面用 `applyLightingSurface` 打光,太阳的软阴影(16 个找遮挡点的采样加最多 64 个滤波采样)是在那里面。海面几乎不在阴影里、边缘又被波浪盖住,所以现在水着色器在打光前设 `g_shadowHard = 1`,阴影按“没有大小的光源”读成 9 个采样的硬边:水段 2.16 → 1.68(机位 0)、2.28 → 1.71(机位 3),画面平均差 0.24/255 和 0.54/255,放大看海面上的云影还在。`g_shadowHard` 和 `g_hairShadow` 一样是着色器在打光前设的一个全局,别的着色器也可以用。++### 太阳阴影图只画照得到相机的投射体(2026-10-26)++示例的太阳有固定的 `shadowExtent`,所以画的是一张覆盖整个岛的图,图的内容和相机无关,但**画进图里的投射体**原来是图范围里的全部(再按到相机的距离砍一次)。一个投射体的影子是它的包围球沿光线扫到最低接收面的一段;这段在相机视锥之外,就不会遮住相机看得到的任何东西,不必画进图。(`CollectContext::castsIntoView`,用 `Frustum::intersectsSweptSphere` 判,只对有固定范围的太阳,有平面反射时不做,没有场景包围盒时不做。)++| 机位 | 阴影 pass 之前 | 之后 | 阴影绘制数 | 整图 |+|---|---|---|---|---|+| 1 | 4.04 | 1.69 | 1223 → 609 | 23.6 → 21.1 |+| 2 | 4.69 | 1.42 | 1302 → 447 | 26.5 → 23.3 |+| 3(相机在岛上空,看得到整个岛) | 4.69 | 4.51 | 1302 → 1177 | 不变 |+| 0 | 0.42 | 0.36 | 432 → 385 | 不变 |++画面与之前逐像素比(排除运行间本来就不同的部分):平均差 0.03 到 0.39/255,差超过 24 的像素为 0。`mesh-shadow-cull` 渲染场景在两个后端上钉住两件事:相机身后的投射体仍然给前面的地面投影,一个在图里但影子落在视野外的被画少一个(`render.shadow.castersCulled` = 1)。++**没做的:缓存。**图的内容随相机变(植物只在相机的绘制距离内有),缓存一张整图要么常常失效,要么要像虚拟阴影图那样分页;这次的剔除是不改变任何像素的那一半,先拿了。**另一个发现:**把固定范围设成 8000(图的纹素约 4 个世界单位)时 60 单位宽的投射体的影子整个消失,3000 和 1500 正常,没有查,是另一个问题。diff --git a/fixtures/scenes/mesh-shadow-cull.esscene b/fixtures/scenes/mesh-shadow-cull.esscenenew file mode 100644index 000000000..8a8e926be--- /dev/null+++ b/fixtures/scenes/mesh-shadow-cull.esscene@@ -0,0 +1,191 @@+{+ "version": 4,+ "name": "MeshShadowCull",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 500+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 0,+ "fov": 45,+ "nearPlane": 10,+ "farPlane": 4000,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Ground",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 250+ },+ "scale": {+ "x": 600,+ "y": 600,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "/scenes/shadow-quad.esmesh",+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "lit": true,+ "opaque": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "Caster",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 60,+ "z": 900+ },+ "scale": {+ "x": 60,+ "y": 60,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "/scenes/shadow-quad.esmesh",+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "lit": true,+ "opaque": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 3,+ "name": "Sun",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "Light",+ "data": {+ "type": 1,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "intensity": 1,+ "direction": {+ "x": 0.05,+ "y": 0+ },+ "meshShadows": true,+ "shadowExtent": 3000+ }+ }+ ]+ },+ {+ "id": 4,+ "name": "Aside",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 2000,+ "y": 60,+ "z": 900+ },+ "scale": {+ "x": 60,+ "y": 60,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "/scenes/shadow-quad.esmesh",+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "lit": true,+ "opaque": true,+ "enabled": true+ }+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/src/esengine/renderer/RenderTypePlugin.hpp b/src/esengine/renderer/RenderTypePlugin.hppindex da250d61f..52d1094fe 100644--- a/src/esengine/renderer/RenderTypePlugin.hpp+++ b/src/esengine/renderer/RenderTypePlugin.hpp@@ -265,6 +265,29 @@ struct RenderCollectContext {const OcclusionView* occlusion = nullptr;Entity excluded = INVALID_ENTITY;+ /**+ * @brief A sun's shadow map only: the camera's frustum, which is what its shadows are worth drawing for, and the way the rays travel.+ *+ * @details A caster's shadow is the segment its sphere sweeps along the rays down to the lowest receiver. A caster whose segment stays+ * outside the camera's frustum shades nothing the camera sees, so the map need not hold it. Null: every caster is drawn.+ */+ const Frustum* shadowReceivers = nullptr;+ glm::vec3 shadowRay{0.0f, -1.0f, 0.0f};+ f32 shadowFloor = 0.0f;+ f32 shadowReachCap = 0.0f;+ /// How many casters that left out.+ u32 shadowCulled = 0;++ /** @brief Whether a caster bounded by a sphere can shade anything the camera sees. True where this collect asks no such thing. */+ bool castsIntoView(const glm::vec3& centre, f32 radius) {+ if (!shadowReceivers) return true;+ f32 length = shadowReachCap;+ if (shadowRay.y < -1e-3f) length = std::min(length, std::max(centre.y - shadowFloor + radius, 0.0f) / -shadowRay.y);+ if (shadowReceivers->intersectsSweptSphere(centre, centre + shadowRay * length, radius)) return true;+ ++shadowCulled;+ return false;+ }+/** @brief Whether this collect is the frame's screen overlay. */bool isOverlay() const { return frame_context.purpose == RenderPurpose::ScreenOverlay; }diff --git a/src/esengine/renderer/frame/Frustum.hpp b/src/esengine/renderer/frame/Frustum.hppindex aa45af61f..0b5602594 100644--- a/src/esengine/renderer/frame/Frustum.hpp+++ b/src/esengine/renderer/frame/Frustum.hpp@@ -28,6 +28,9 @@ struct Frustum {Plane planes[6];void extractFromMatrix(const glm::mat4& vp);bool intersectsAABB(const glm::vec3& center, const glm::vec3& halfExtents) const;+ /// Whether the sphere of @p radius swept from @p a to @p b can touch the volume: false only when both ends stand outside the same+ /// plane by more than the radius, so a capsule that clips a corner is kept.+ bool intersectsSweptSphere(const glm::vec3& a, const glm::vec3& b, f32 radius) const;};} // namespace esenginediff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex da029a026..6d72b1604 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -129,6 +129,13 @@ bool Frustum::intersectsAABB(const glm::vec3& center, const glm::vec3& halfExtenreturn true;}+bool Frustum::intersectsSweptSphere(const glm::vec3& a, const glm::vec3& b, f32 radius) const {+ for (u32 i = 0; i < 6; ++i) {+ if (planes[i].signedDistance(a) < -radius && planes[i].signedDistance(b) < -radius) return false;+ }+ return true;+}+RenderFrame::RenderFrame(GfxDevice& device, RenderContext& context,resource::ResourceManager& resource_manager): device_(device)@@ -2216,7 +2223,17 @@ void RenderFrame::buildShadowPlan(ecs::Registry& registry) {continue;}- shadow_views_.push_back(ShadowView{projection, tile.x, tile.y, tile.size});+ ShadowView view{projection, tile.x, tile.y, tile.size};+ // A sun's rays are parallel, so what a caster shades is a segment along them, down to the lowest thing that can receive it. That is+ // worth drawing only where the camera sees some of it. Not with a planar reflection in the frame (it looks through a frustum+ // of its own, and receives from the same atlas), nor without bounds to say where the rays end.+ if (caster.shape == ShadowShape::Box && haveBounds && planar_captures_.empty() && glm::length(caster.dir) > 1e-6f) {+ view.sun = true;+ view.ray = glm::normalize(caster.dir);+ view.floorY = boundsMin.y;+ view.reachCap = glm::length(boundsMax - boundsMin);+ }+ shadow_views_.push_back(view);++plannedTiles;}@@ -2307,6 +2324,7 @@ void RenderFrame::executeShadowPass(ecs::Registry& registry) {// face that stopped being skipped would look exactly like one that never was.u32 shadowTiles = 0;u32 shadowDraws = 0;+ u32 shadowCastersCulled = 0;const usize viewCount = shadow_views_.size();// Reset once for the pass, NOT once per view: a draw carries an offset rather@@ -2337,6 +2355,12 @@ void RenderFrame::executeShadowPass(ecs::Registry& registry) {RenderCollectContext collectCtx{registry, viewFrustum, clip_state_, shadow_pool_,list, ctx,computeCameraView(view.view_projection)};+ if (view.sun && shadow_receiver_cull_) {+ collectCtx.shadowReceivers = &frustum_;+ collectCtx.shadowRay = view.ray;+ collectCtx.shadowFloor = view.floorY;+ collectCtx.shadowReachCap = view.reachCap;+ }collectCtx.screen_ui = screen_domain_;// A shadow is part of the camera's picture: what the camera culled by its level of detail (grass past its distance)// does not cast, and what it draws coarse casts coarse.@@ -2344,6 +2368,7 @@ void RenderFrame::executeShadowPass(ecs::Registry& registry) {for (auto& plugin : plugins_) {if (plugin->castsShadows()) plugin->collect(collectCtx);}+ shadowCastersCulled += collectCtx.shadowCulled;list.finalize(shadow_pool_);}shadow_pool_.upload();@@ -2377,6 +2402,8 @@ void RenderFrame::executeShadowPass(ecs::Registry& registry) {ES_PROFILE_COUNTER("render.shadow.tiles", shadowTiles);ES_PROFILE_COUNTER("render.shadow.draws", shadowDraws);+ ES_PROFILE_COUNTER("render.shadow.castersCulled", shadowCastersCulled);+ ES_PROFILE_COUNTER("render.shadow.cullViews", [&] { u32 n = 0; for (const ShadowView& v : shadow_views_) n += v.sun ? 1u : 0u; return n; }());// The scene draws next, through pipelines nothing here matches.device_.invalidatePipelineCache();}diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex 0ddb12d3a..5e3438fd0 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -966,7 +966,15 @@ private:u32 x = 0;u32 y = 0;u32 size = 0;+ /// A sun's map: the way its rays travel, the lowest height a receiver can stand at and how far a shadow can reach, so a caster whose+ /// shadow falls outside the camera's view is not drawn into it.+ bool sun = false;+ glm::vec3 ray{0.0f, -1.0f, 0.0f};+ f32 floorY = 0.0f;+ f32 reachCap = 0.0f;};+ /// Whether a sun's map leaves out the casters whose shadow cannot reach the camera's view.+ bool shadow_receiver_cull_ = true;/// What the pass will draw, in atlas order. Empty = nothing asked for a map, and/// no pass is declared.std::vector<ShadowView> shadow_views_;diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cppindex 9e7102727..417acf9a2 100644--- a/src/esengine/renderer/plugins/MeshPlugin.cpp+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp@@ -584,6 +584,7 @@ void emitPlacements(const RenderFrameContext& ctx, RenderCollectContext& collectif (ctx.purpose == RenderPurpose::ShadowDepth && set.shadowDistance > 0.0f && distance - radius > set.shadowDistance) continue;}if (!collect.visible(at, glm::vec3(radius), false)) { ++outside; continue; }+ if (ctx.purpose == RenderPurpose::ShadowDepth && !collect.castsIntoView(at, radius)) { ++outside; continue; }(coarse && eyeKnown && set.lodDistance > 0.0f && distance > set.lodDistance ? farList : nearList).push_back(i);}ES_PROFILE_COUNTER("render.placements.seen", count);@@ -768,6 +769,11 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {tick(2);continue;}+ if (shadowDepth && !collect_ctx.castsIntoView(aabbCenter, glm::length(halfExtents))) {+ ++collect_ctx.culled;+ tick(2);+ continue;+ }// Nothing visible is worth measuring precisely, so the cull runs first; what// survives it is measured on the sphere the whole group shares.diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex d008069a1..98fcf5fdd 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2992,4 +2992,6 @@ export const NOTED = {{"note":"A lit surface no longer works out the light slots nothing shines from."},"perf(water): the sea reads the sun's shadow as one hard edge, not as a penumbra":{"note":"The sea takes the sun's shadow as one hard edge."},+ "perf(shadow): a sun's map leaves out the casters whose shadow cannot reach what the camera sees":+ {"note":"A sun's shadow map leaves out the casters that shade nothing the camera sees."},};diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex d8d9bc6ea..3b8a65a65 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -224,6 +224,8 @@ export const SCENES = [// The same question through a PERSPECTIVE camera, which is what a 3D scene uses:// coverage derived from the camera's NDC z=0 slice is the whole view for the// orthographic one above and a sliver near the near plane for this one.+ // The caster behind the camera still shades the floor in front of it (the sun-shadow cull keeps what reaches the view); one far off to the side, whose shadow falls outside it, is left out of the map.+ { id: "mesh-shadow-cull", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-shadow-cull.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_COUNTERS: "{\"render.shadow.castersCulled\": 1}", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.7,\"y\":0.21,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.48,\"y\":0.21,\"rgb\":[255,255,255],\"tol\":20},{\"x\":0.7,\"y\":0.6,\"rgb\":[255,255,255],\"tol\":20}]" } },{ id: "mesh-shadow-caster-behind", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-shadow-caster-behind.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.7,\"y\":0.21,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.48,\"y\":0.21,\"rgb\":[255,255,255],\"tol\":20},{\"x\":0.7,\"y\":0.6,\"rgb\":[255,255,255],\"tol\":20}]" } },// A CONE casting, through the tile and the pass a cascade uses. The shadow is offset// from the caster because a point light projects rather than sweeps; the probes either