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
feat(render): a positional light has a height where the surface can measure it
yhh374c89adff32
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e860fecb8..3be17adf3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,10 +25,28 @@ published separately; it ships inside the editor.constant did.It defaults to -1, which is the direction a 2D scene's light has always come- from — every existing scene renders the same bytes, and all 87 pixel gates agree- on both backends. Point and spot lights still synthesize their depth from the- falloff radius; that is what gives a flat scene its shading, and giving them real- positions is a separate change with a compatibility story of its own.+ from — every existing scene renders the same bytes, and all 88 pixel gates agree+ on both backends.++- **A point or spot light has a height, where the surface has the geometry to+ measure it.** Its depth was the falloff radius, so a lamp lit a mesh the same+ whether it sat on the floor or above the ceiling: `radius` doubled as "how far+ above" because a 2D light had nowhere to keep a third coordinate. On a mesh it+ is now the light's own world position — distance, falloff and the angle of+ incidence all come from where the light actually is, and a spot's cone points+ in three dimensions.++ A sprite keeps the plane's convention, and that is the whole compatibility+ story: it has no depth of its own to measure against, so a positional light goes+ on hovering its radius above it. The two are not a branch the frame takes — they+ are which definition of "where is the light" a shader compiles with, chosen by+ the same flag that already says whether a draw brought real normals and a real+ world position. One lighting model, one BRDF, and the surface saying what+ geometry it has.++ A light lying exactly on the surface used to be unreachable and now is not, so it+ is answered rather than left to produce a NaN: it lights along the surface's own+ normal, the limit that approaches from every side.- **FBX import.** A `.fbx` is a model source like a `.gltf` is: drop one in and itwrites the same products — `.esmesh` per material run, the images it embeds, andiff --git a/desktop/public/scenes/mesh-point-3d.esscene b/desktop/public/scenes/mesh-point-3d.esscenenew file mode 100644index 000000000..0ec60caa7--- /dev/null+++ b/desktop/public/scenes/mesh-point-3d.esscene@@ -0,0 +1,76 @@+{+ "version": 1,+ "name": "MeshPoint3D",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": { "position": { "x": 0, "y": 0, "z": 10 } }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 300,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Panel",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": { "x": 0, "y": 0, "z": 0 },+ "scale": { "x": 600, "y": 600, "z": 1 }+ }+ },+ {+ "type": "Mesh2D",+ "data": {+ "mesh": "/scenes/shadow-quad.esmesh",+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },+ "lit": true,+ "opaque": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "Lamp",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": { "position": { "x": 0, "y": 0, "z": 120 } }+ },+ {+ "type": "Light2D",+ "data": {+ "type": 0,+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },+ "intensity": 1,+ "radius": 1000+ }+ }+ ]+ }+ ]+}diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 12b276ed7..23d1fae62 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -653,7 +653,7 @@ void RenderFrame::collectLights(ecs::Registry& registry) {// Gather non-ambient lights, then (if over the UBO's cap) keep the most intense — the// brightest contribute most, and an explicit importance cull beats silently dropping// whichever happened to come last in iteration order. Ambient lights sum without a cap.- std::vector<GpuLight2D>& collected = light_scratch_;+ std::vector<CollectedLight>& collected = light_scratch_;collected.clear();// A light's Transform need is type-dependent: Ambient (a flat scene-wide term) and@@ -679,6 +679,7 @@ void RenderFrame::collectLights(ecs::Registry& registry) {}GpuLight2D gpu;+ bool castsMeshShadow = false;gpu.color = glm::vec4(rgb, light.intensity);// shadow.x = penumbra softness (all types); shadow.y = directional march distance (only the// directional branch of shadowFactor2D reads it; 0 keeps directional shadows off).@@ -689,10 +690,8 @@ void RenderFrame::collectLights(ecs::Registry& registry) {// component, which only a directional light has a use for — point and spot spend// that slot on their falloff radius.gpu.posDir = glm::vec4(light.direction.x, light.direction.y, 1.0f, aimZ(light));- // Marked here and read back after the cap sort, so the slot recorded is the- // slot the shader will index. shadow.z is cleared before it reaches the GPU.if (light.meshShadows && shadow_light_slot_ < 0) {- gpu.shadow.z = 1.0f;+ castsMeshShadow = true;shadow_light_dir_ = glm::vec3(light.direction, aimZ(light));shadow_light_extent_ = std::max(light.shadowExtent, 0.0f);}@@ -703,31 +702,36 @@ void RenderFrame::collectLights(ecs::Registry& registry) {const glm::vec3 p = transform->worldPosition;const f32 typeId = (type == ecs::Light2DType::Spot) ? 2.0f : 0.0f;gpu.posDir = glm::vec4(p.x, p.y, typeId, light.radius);+ // The height a surface with real geometry measures against. A sprite has no+ // depth of its own and keeps the plane's convention, so this reaches only the+ // MESH_NORMALS half of the lighting loop.+ gpu.shadow.z = p.z;if (type == ecs::Light2DType::Spot) {+ // The cone axis unnormalized, so the two halves can each normalize the+ // vector they need: the plane's xy, and the whole of it in three.glm::vec2 aim = light.direction;- aim = (glm::dot(aim, aim) > 1e-8f) ? glm::normalize(aim) : glm::vec2(0.0f, -1.0f);+ if (glm::dot(aim, aim) <= 1e-8f) aim = glm::vec2(0.0f, -1.0f);gpu.spot = glm::vec4(aim.x, aim.y,std::cos(glm::radians(light.innerAngle * 0.5f)),std::cos(glm::radians(light.outerAngle * 0.5f)));+ gpu.shadow.w = light.directionZ;}}- collected.push_back(gpu);+ collected.push_back({gpu, castsMeshShadow});}if (collected.size() > MAX_LIGHTS_2D) {std::partial_sort(collected.begin(), collected.begin() + MAX_LIGHTS_2D, collected.end(),- [](const GpuLight2D& a, const GpuLight2D& b) { return a.color.a > b.color.a; });+ [](const CollectedLight& a, const CollectedLight& b) {+ return a.gpu.color.a > b.gpu.color.a;+ });ES_LOG_WARN("collectLights: {} lights exceed the {}-light cap; keeping the brightest",collected.size(), MAX_LIGHTS_2D);collected.resize(MAX_LIGHTS_2D);}for (u32 slot = 0; slot < collected.size(); ++slot) {- GpuLight2D& gpu = collected[slot];- if (gpu.shadow.z > 0.5f) {- shadow_light_slot_ = static_cast<i32>(slot);- gpu.shadow.z = 0.0f; // a mark for this loop, not a field the shader reads- }- lights.addLight(gpu);+ if (collected[slot].castsMeshShadow) shadow_light_slot_ = static_cast<i32>(slot);+ lights.addLight(collected[slot].gpu);}// Shadow occluders: each enabled ShadowCaster2D becomes a world-space AABB (centered on itsdiff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex 6635cfd50..1090ddebc 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -318,7 +318,14 @@ private:u32 initBatchShader();resource::ShaderHandle compileBatchVariant(const std::vector<std::string>& features);- std::vector<GpuLight2D> light_scratch_; // reused across frames; collectLights only+ /// A collected light and whether it casts the frame's mesh shadow. Paired rather+ /// than flagged inside the GPU struct, because the cap sort reorders these and the+ /// answer has to travel with the light.+ struct CollectedLight {+ GpuLight2D gpu;+ bool castsMeshShadow;+ };+ std::vector<CollectedLight> light_scratch_; // reused across frames; collectLights only/// Which light slot casts the map, and the direction + coverage it asked for./// Written by collectLights, read by renderShadowMap; -1 = nobody asked.i32 shadow_light_slot_ = -1;diff --git a/src/esengine/renderer/store/LightConstants.hpp b/src/esengine/renderer/store/LightConstants.hppindex 128565561..84224bc98 100644--- a/src/esengine/renderer/store/LightConstants.hpp+++ b/src/esengine/renderer/store/LightConstants.hpp@@ -64,7 +64,9 @@ inline constexpr u32 MAX_OCCLUDERS_2D = 8;* LightConstants::ambient instead of occupying a slot.* 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). zw reserved (0). Read by shadowFactor2D.+ * directional light casts no shadow); z = a point/spot light's world height, which+ * only a surface with real geometry measures against (MESH_NORMALS); w = a spot's+ * cone-axis third component. Read by shadowFactor2D and lightVector/spotCone.*/struct GpuLight2D {glm::vec4 posDir{0.0f};diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex f15f6d402..f1b56ebdf 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -895,6 +895,33 @@ fn envRadiance(R : vec3f, roughness : f32) -> vec3f {let b = envSampleMip(R, min(lo + 1.0, lc.u_envParams.z));return lc.u_ambient.rgb + mix(a, b, lod - lo) * lc.u_envTint.rgb;}+#ifdef MESH_NORMALS+fn lightVector(pd : vec4f, sh : vec4f, worldPos : vec3f) -> vec3f {+ return vec3f(pd.xy, sh.z) - worldPos;+}+fn lightDistance(toLight : vec3f) -> f32 { return length(toLight); }+fn spotCone(sp : vec4f, sh : vec4f, toLight : vec3f, dist : f32) -> f32 {+ let axis = normalize(vec3f(sp.xy, sh.w));+ var toFrag = axis;+ if (dist > 0.0001) { toFrag = -toLight / dist; }+ return smoothstep(sp.w, sp.z, dot(axis, toFrag));+}+#else+fn lightVector(pd : vec4f, sh : vec4f, worldPos : vec3f) -> vec3f {+ return vec3f(pd.xy - worldPos.xy, max(pd.w, 1.0));+}+fn lightDistance(toLight : vec3f) -> f32 { return length(toLight.xy); }+fn spotCone(sp : vec4f, sh : vec4f, toLight : vec3f, dist : f32) -> f32 {+ let axis = normalize(sp.xy);+ var toFrag = axis;+ if (dist > 0.0001) { toFrag = -toLight.xy / dist; }+ return smoothstep(sp.w, sp.z, dot(axis, toFrag));+}+#endif+fn towardLight(toLight : vec3f, N : vec3f) -> vec3f {+ if (dot(toLight, toLight) > 1e-8) { return normalize(toLight); }+ return N;+}fn applyLightingPBR(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f, metallic : f32,roughness : f32, specular : f32, ao : f32) -> vec3f {let F0 = mix(vec3f(0.04), albedo, vec3f(metallic));@@ -911,10 +938,10 @@ fn applyLightingPBR(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f, metavar aim = pd.xy;var castShadow = true;if (pd.z < 0.5) {- let d = pd.xy - worldPos.xy;- let dist = length(d);+ let toL = lightVector(pd, sh, worldPos);+ let dist = lightDistance(toL);atten = max(0.0, 1.0 - dist / max(pd.w, 0.0001));- L = normalize(vec3f(d, max(pd.w, 1.0)));+ L = towardLight(toL, N);} else if (pd.z < 1.5) {atten = 1.0;L = normalize(-vec3f(pd.xy, pd.w));@@ -924,13 +951,11 @@ fn applyLightingPBR(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f, metaaim = worldPos.xy + toLight * sh.y;} else {let sp = lc.u_lights[i].spot;- let d = pd.xy - worldPos.xy;- let dist = length(d);+ let toL = lightVector(pd, sh, worldPos);+ let dist = lightDistance(toL);atten = max(0.0, 1.0 - dist / max(pd.w, 0.0001));- L = normalize(vec3f(d, max(pd.w, 1.0)));- var toFrag = sp.xy;- if (dist > 0.0001) { toFrag = -d / dist; }- atten *= smoothstep(sp.w, sp.z, dot(sp.xy, toFrag));+ L = towardLight(toL, N);+ atten *= spotCone(sp, sh, toL, dist);}if (castShadow && col.a > 0.0 && atten > 0.0) {atten *= shadowFactor2D(worldPos.xy, aim, sh.x);@@ -1467,6 +1492,38 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" highp vec3 b = envSampleMip(R, min(lo + 1.0, u_envParams.z));\n"" return u_ambient.rgb + mix(a, b, lod - lo) * u_envTint.rgb;\n""}\n"+ // Where a positional light is, from here, and how far. Real geometry measures+ // against the light's own world height; a sprite has no depth of its own and+ // keeps the plane's convention of one hovering its falloff radius above it.+ "#ifdef MESH_NORMALS\n"+ "highp vec3 lightVector(in highp vec4 pd, in highp vec4 sh, in highp vec3 worldPos) {\n"+ " return vec3(pd.xy, sh.z) - worldPos;\n"+ "}\n"+ "highp float lightDistance(in highp vec3 toLight) { return length(toLight); }\n"+ "highp float spotCone(in highp vec4 sp, in highp vec4 sh, in highp vec3 toLight,\n"+ " in highp float dist) {\n"+ " highp vec3 axis = normalize(vec3(sp.xy, sh.w));\n"+ " highp vec3 toFrag = (dist > 0.0001) ? -toLight / dist : axis;\n"+ " return smoothstep(sp.w, sp.z, dot(axis, toFrag));\n"+ "}\n"+ "#else\n"+ "highp vec3 lightVector(in highp vec4 pd, in highp vec4 sh, in highp vec3 worldPos) {\n"+ " return vec3(pd.xy - worldPos.xy, max(pd.w, 1.0));\n"+ "}\n"+ "highp float lightDistance(in highp vec3 toLight) { return length(toLight.xy); }\n"+ "highp float spotCone(in highp vec4 sp, in highp vec4 sh, in highp vec3 toLight,\n"+ " in highp float dist) {\n"+ " highp vec2 axis = normalize(sp.xy);\n"+ " highp vec2 toFrag = (dist > 0.0001) ? -toLight.xy / dist : axis;\n"+ " return smoothstep(sp.w, sp.z, dot(axis, toFrag));\n"+ "}\n"+ "#endif\n"+ // A light sitting exactly on the surface has no direction to give; the plane's+ // convention could never produce one, real positions can. Lighting it along its+ // own normal is the limit that approaches from every side.+ "highp vec3 towardLight(in highp vec3 toLight, in highp vec3 N) {\n"+ " return dot(toLight, toLight) > 1e-8 ? normalize(toLight) : N;\n"+ "}\n"// The lighting model in its general form; a lit 2D surface is its zero// (metallic 0, roughness 1, specular 0 leaves albedo * NdotL, pixel for pixel// what this engine has always drawn), so there is one model and not two.@@ -1494,10 +1551,10 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" highp vec2 target = pd.xy;\n" // shadow-ray aim point (light position by default)" bool castShadow = true;\n"" if (pd.z < 0.5) {\n"- " highp vec2 d = pd.xy - worldPos.xy;\n"- " highp float dist = length(d);\n"+ " highp vec3 toL = lightVector(pd, sh, worldPos);\n"+ " highp float dist = lightDistance(toL);\n"" atten = max(0.0, 1.0 - dist / max(pd.w, 0.0001));\n"- " L = normalize(vec3(d, max(pd.w, 1.0)));\n"+ " L = towardLight(toL, N);\n"" } else if (pd.z < 1.5) {\n"" atten = 1.0;\n"// pd.w is the aim's third component here; point/spot spend that slot on radius.@@ -1509,12 +1566,11 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" target = worldPos.xy + toLight * sh.y;\n"" } else {\n"" highp vec4 sp = u_lights[i].spot;\n"- " highp vec2 d = pd.xy - worldPos.xy;\n"- " highp float dist = length(d);\n"+ " highp vec3 toL = lightVector(pd, sh, worldPos);\n"+ " highp float dist = lightDistance(toL);\n"" atten = max(0.0, 1.0 - dist / max(pd.w, 0.0001));\n"- " L = normalize(vec3(d, max(pd.w, 1.0)));\n"- " highp vec2 toFrag = (dist > 0.0001) ? (-d / dist) : sp.xy;\n"- " atten *= smoothstep(sp.w, sp.z, dot(sp.xy, toFrag));\n"+ " L = towardLight(toL, N);\n"+ " atten *= spotCone(sp, sh, toL, dist);\n"" }\n"// Only pay for the shadow test when the light actually reaches this fragment (skips the// zeroed/inactive slots and unlit fragments — cheaper than the old unconditional call).diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex f8122210c..081034f06 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -65,6 +65,10 @@ export const SCENES = [// shadow to world +200, where a depth of -1 puts it at +50. Measured: the probe// at 0.833 reads 247 at depth -1 and 0 at this one.{ id: "mesh-shadow-aimed", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-shadow-aimed.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.833,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.167,\"y\":0.5,\"rgb\":[180,180,180],\"tol\":20},{\"x\":0.5,\"y\":0.5,\"rgb\":[180,180,180],\"tol\":20}]" } },+ // A lamp 120 units ABOVE a panel, a height only real geometry measures against.+ // Hand-derived, 255·NdotL·atten: 224 under it and 101 at world +200, where the+ // plane's convention reads 255 and 200.+ { id: "mesh-point-3d", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-point-3d.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[224,224,224],\"tol\":20},{\"x\":0.833,\"y\":0.5,\"rgb\":[102,102,102],\"tol\":20}]" } },// A baked panorama lighting a surface BY DIRECTION: two coplanar triangles, one// white colour, normals up and down under a sky blue above and red below. A flat// ambient term draws the halves identically, which is why the probes invert.