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): blob shadows, a soft disc on the ground under a thing
yhh01ea6fc8e5bd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7c5a2967e..e053f4a6a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **Blob shadows.** A `BlobShadow` component puts a soft dark disc on the ground under an entity: no shadow map, no light, no extra pass, which is the shadow a phone can afford. It fades and shrinks as the thing leaves the ground (`fadeHeight`, `shrink`), follows the ground (`groundY`, or a height function from `setBlobShadowGround` for ground that is not flat) and is hidden by what stands in front of it. It is a disc, not the light's shadow: it does not stretch with the sun or land on a wall. The same picture on WebGL2 and WebGPU.- **Edge Outline, a coloured line at silhouettes and creases.** A post effect (`edgeOutline`) that draws a line of `u_lineColor` where the scene's surface changes: where the distance from the camera steps (a silhouette) and where the surface's normal turns (the edge of a face, a fold), so a box on a floor is inked along its corners as well as its outline, which `depthOutline` (depth only, black only) does not do. Distance is measured in the world, so one threshold holds across a perspective view, and a plane at a grazing angle draws no line. Creases need surfaces that write their normal (lit meshes, Model and Toon materials); the same picture on WebGL2 and WebGPU.- **Filled polygons and joined strokes.** `setPath(app, entity, points, style)` draws a path on a MeshRenderer: an ear-clipped fill of any simple polygon (concave ones, holes), and a stroke with mitered, rounded or bevelled corners and butt, round or square caps that does not overlap itself at a corner, so a translucent line is even; `feather` fades the outer edge for a quality level without multisampling. It sorts, batches and saves with the scene like any mesh. `Graphics` still fills only rects and circles; `buildPathGeometry`, `cubicBezier`, `quadraticBezier` and `circlePoints` are the pieces. The same picture on WebGL2 and WebGPU.- **Toon and Matcap materials.** `builtin:toon` lights in steps: each lamp's light is cut into flat bands with a shade colour where no lamp reaches, a flat highlight and a rim, and a lamp's shadow is part of its step; the same picture on WebGL2 and WebGPU. `builtin:matcap` shows a picture of a lit sphere looked up by the way the surface faces the camera, with no lamp asked and one texture read, for phones.diff --git a/docs/astro/src/content/docs/graphics/lighting.mdx b/docs/astro/src/content/docs/graphics/lighting.mdxindex b6fd0742c..4599aa837 100644--- a/docs/astro/src/content/docs/graphics/lighting.mdx+++ b/docs/astro/src/content/docs/graphics/lighting.mdx@@ -365,6 +365,29 @@ saying something about its art direction; the fix is to turn shadows off (`shadoof 0 on a sun, or a smaller `radius` that takes a light out of view) on the ones whoseshadows nobody looks at.+## Blob shadows: a disc instead of a shadow map++A shadow map costs a pass from the light and a read in every lit pixel. Where that is too much (a phone, a crowd, a game whose light never moves) a+`BlobShadow` on the entity puts a soft dark disc on the ground under it instead: no map, no light, no extra pass.++```typescript+cmds.spawn()+ .insert(Transform, { position: { x: 0, y: 40, z: 0 } })+ .insert(MeshRenderer, { mesh })+ .insert(BlobShadow, { radius: 60, opacity: 0.6, groundY: 0 });+```++| Field | Meaning |+|---|---|+| `radius`, `opacity`, `softness` | Size on the ground, darkness at the centre, and how soft the edge is (0 hard, 1 fading from the centre). |+| `groundY` | Height of the flat ground. For ground that is not flat, `setBlobShadowGround(app, (x, z) => height)` gives the height under each thing (return `null` to fall back to `groundY`). |+| `fadeHeight`, `shrink` | The shadow fades out as the thing rises this far above the ground, and shrinks by this share on the way (a jumping character's shadow gets smaller and fainter). 0 never fades. |+| `lift` | How far above the ground the disc is drawn, so it does not flicker against it. |++The disc is hidden by what stands in front of it and draws no depth of its own. It is not the light's shadow: it does not stretch with the sun, fall across+steps or land on a wall, so use it where a grounding cue is enough, and a real shadow where the shape of the shadow matters. The disc is an entity of its+own that is never saved with the scene.+## Baked lightSixteen lights reach one frame. The seventeenth is dropped — by brightness, with adiff --git a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdxindex 0e48307a3..1ce7db7c9 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx@@ -286,6 +286,26 @@ cmds.spawn()处理办法是把没人会看那道影子的光关掉阴影(太阳的 `shadowDistance` 设 0,或者用更小的 `radius`让某个光离开视野)。+## 假阴影:用一个圆片代替阴影图++阴影图要从光源再画一遍,并且每个受光像素都要读一次。负担不起的时候(手机、人群、光源不动的游戏),给实体加一个 `BlobShadow`,在它脚下的地面上放一个柔和的深色圆片:没有阴影图、没有光源、没有额外的 pass。++```typescript+cmds.spawn()+ .insert(Transform, { position: { x: 0, y: 40, z: 0 } })+ .insert(MeshRenderer, { mesh })+ .insert(BlobShadow, { radius: 60, opacity: 0.6, groundY: 0 });+```++| 字段 | 含义 |+|---|---|+| `radius`、`opacity`、`softness` | 在地面上的大小、中心的深浅,以及边缘的软硬(0 硬边,1 从中心渐隐)。 |+| `groundY` | 平地的高度。地面不平时用 `setBlobShadowGround(app, (x, z) => 高度)` 给出每个物体脚下的高度(返回 `null` 就退回 `groundY`)。 |+| `fadeHeight`、`shrink` | 物体离地升到这个高度时阴影淡出,途中缩小这么多(跳起来的角色,影子变小变淡)。0 表示不淡出。 |+| `lift` | 圆片比地面抬高多少,免得和地面闪烁。 |++圆片会被挡在它前面的东西遮住,自己不写深度。它不是光源的阴影:不会随太阳拉长,不会落在台阶或墙上,所以只需要"落地感"时用它,阴影形状要紧的地方还是用真阴影。圆片是自己的一个实体,不会随场景保存。+## 烘焙光照一帧最多 16 盏灯。第 17 盏会被丢掉——按亮度取舍,并打出一条说明丢了谁的警告——这个天花板不是画质diff --git a/fixtures/scenes/blob-shadow.esscene b/fixtures/scenes/blob-shadow.esscenenew file mode 100644index 000000000..1b4b1eacf--- /dev/null+++ b/fixtures/scenes/blob-shadow.esscene@@ -0,0 +1,361 @@+{+ "version": 4,+ "name": "blob-shadow",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 320,+ "z": 480+ },+ "rotation": {+ "x": -0.284,+ "y": 0,+ "z": 0,+ "w": 0.9588+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 0,+ "fov": 60,+ "nearPlane": 10,+ "farPlane": 3000,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Floor",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": -200+ },+ "scale": {+ "x": 14,+ "y": 1,+ "z": 14+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:plane",+ "color": {+ "r": 0.75,+ "g": 0.75,+ "b": 0.75,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "WallBack",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 125,+ "z": -600+ },+ "scale": {+ "x": 14,+ "y": 2.5,+ "z": 0.2+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 0.7,+ "g": 0.72,+ "b": 0.78,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 3,+ "name": "WallLeft",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": -600,+ "y": 125,+ "z": -200+ },+ "scale": {+ "x": 0.2,+ "y": 2.5,+ "z": 8+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 0.7,+ "g": 0.72,+ "b": 0.78,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 4,+ "name": "Step",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": -330,+ "y": 25,+ "z": -80+ },+ "scale": {+ "x": 2,+ "y": 0.5,+ "z": 2+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 0.65,+ "g": 0.75,+ "b": 0.6,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 5,+ "name": "BoxContact",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": -110,+ "y": 50,+ "z": -80+ },+ "scale": {+ "x": 1,+ "y": 1,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 0.8,+ "g": 0.55,+ "b": 0.4,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "BlobShadow",+ "data": {+ "enabled": true,+ "radius": 95,+ "opacity": 0.7,+ "softness": 0.6,+ "groundY": 0,+ "fadeHeight": 300,+ "shrink": 0.5,+ "lift": 0.5+ }+ }+ ]+ },+ {+ "id": 6,+ "name": "BoxFloating",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 110,+ "y": 100,+ "z": -80+ },+ "scale": {+ "x": 1,+ "y": 1,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 0.45,+ "g": 0.65,+ "b": 0.8,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "BlobShadow",+ "data": {+ "enabled": true,+ "radius": 95,+ "opacity": 0.7,+ "softness": 0.6,+ "groundY": 0,+ "fadeHeight": 300,+ "shrink": 0.5,+ "lift": 0.5+ }+ }+ ]+ },+ {+ "id": 7,+ "name": "Sphere",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 330,+ "y": 50,+ "z": -80+ },+ "scale": {+ "x": 1,+ "y": 1,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:sphere",+ "color": {+ "r": 0.78,+ "g": 0.7,+ "b": 0.5,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "BlobShadow",+ "data": {+ "enabled": true,+ "radius": 80,+ "opacity": 0.7,+ "softness": 0.6,+ "groundY": 0,+ "fadeHeight": 300,+ "shrink": 0.5,+ "lift": 0.5+ }+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 6c506128e..91e0402f7 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1887 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1893 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1746,6 +1746,28 @@ PremultipliedAlpha = 4Screen = 3```+## BlobShadow — const @experimental+```+ComponentDef<BlobShadowData>+```++## BlobShadowData — interface @experimental+```+enabled: boolean+fadeHeight: number+groundY: number+lift: number+opacity: number+radius: number+shrink: number+softness: number+```++## BlobShadowGround — type @experimental+```+(x: number, z: number) => number | null+```+## BodyType — enum @experimental```Dynamic = 2@@ -13037,6 +13059,11 @@ MotionDriver<AnimatorBlend2DMotion>(from: number, to: number, progress: number): WeatherState```+## blobAlpha — function @experimental+```+(mesh: MeshData, vertex: number): number+```+## boxDistance — function @experimental```(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number@@ -13052,6 +13079,11 @@ MotionDriver<AnimatorBlend2DMotion>(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData```+## buildBlobMesh — function @experimental+```+(softness: number): MeshData+```+## buildFrameProfile — function @experimental```(input: FrameProfileInput): FrameProfile@@ -15702,6 +15734,11 @@ ServicesPlugin(def: AnimatorControllerDef, name: string, patch: { speed?: number; loop?: boolean; rootMotion?: boolean; }, layer?: number): AnimatorControllerDef```+## setBlobShadowGround — function @experimental+```+(app: App, sample: BlobShadowGround | null): void+```+## setButtonState — function @experimental```(world: World, entity: Entity, state: string): voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 4fd4545c1..9df99360a 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 1906 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 1912 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1746,6 +1746,28 @@ PremultipliedAlpha = 4Screen = 3```+## BlobShadow — const @experimental+```+ComponentDef<BlobShadowData>+```++## BlobShadowData — interface @experimental+```+enabled: boolean+fadeHeight: number+groundY: number+lift: number+opacity: number+radius: number+shrink: number+softness: number+```++## BlobShadowGround — type @experimental+```+(x: number, z: number) => number | null+```+## BodyType — enum @experimental```Dynamic = 2@@ -13265,6 +13287,11 @@ MotionDriver<AnimatorBlend2DMotion>(from: number, to: number, progress: number): WeatherState```+## blobAlpha — function @experimental+```+(mesh: MeshData, vertex: number): number+```+## boxDistance — function @experimental```(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number@@ -13280,6 +13307,11 @@ MotionDriver<AnimatorBlend2DMotion>(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData```+## buildBlobMesh — function @experimental+```+(softness: number): MeshData+```+## buildFrameProfile — function @experimental```(input: FrameProfileInput): FrameProfile@@ -15965,6 +15997,11 @@ ServicesPlugin(def: AnimatorControllerDef, name: string, patch: { speed?: number; loop?: boolean; rootMotion?: boolean; }, layer?: number): AnimatorControllerDef```+## setBlobShadowGround — function @experimental+```+(app: App, sample: BlobShadowGround | null): void+```+## setButtonState — function @experimental```(world: World, entity: Entity, state: string): voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex c14da7ce0..4601e6d2f 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 161 beta · 1886 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1892 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1741,6 +1741,28 @@ PremultipliedAlpha = 4Screen = 3```+## BlobShadow — const @experimental+```+ComponentDef<BlobShadowData>+```++## BlobShadowData — interface @experimental+```+enabled: boolean+fadeHeight: number+groundY: number+lift: number+opacity: number+radius: number+shrink: number+softness: number+```++## BlobShadowGround — type @experimental+```+(x: number, z: number) => number | null+```+## BodyType — enum @experimental```Dynamic = 2@@ -13032,6 +13054,11 @@ MotionDriver<AnimatorBlend2DMotion>(from: number, to: number, progress: number): WeatherState```+## blobAlpha — function @experimental+```+(mesh: MeshData, vertex: number): number+```+## boxDistance — function @experimental```(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number@@ -13047,6 +13074,11 @@ MotionDriver<AnimatorBlend2DMotion>(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData```+## buildBlobMesh — function @experimental+```+(softness: number): MeshData+```+## buildFrameProfile — function @experimental```(input: FrameProfileInput): FrameProfile@@ -15707,6 +15739,11 @@ ServicesPlugin(def: AnimatorControllerDef, name: string, patch: { speed?: number; loop?: boolean; rootMotion?: boolean; }, layer?: number): AnimatorControllerDef```+## setBlobShadowGround — function @experimental+```+(app: App, sample: BlobShadowGround | null): void+```+## setButtonState — function @experimental```(world: World, entity: Entity, state: string): voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 53b6c461e..427d07489 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1908 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1914 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1741,6 +1741,28 @@ PremultipliedAlpha = 4Screen = 3```+## BlobShadow — const @experimental+```+ComponentDef<BlobShadowData>+```++## BlobShadowData — interface @experimental+```+enabled: boolean+fadeHeight: number+groundY: number+lift: number+opacity: number+radius: number+shrink: number+softness: number+```++## BlobShadowGround — type @experimental+```+(x: number, z: number) => number | null+```+## BodyType — enum @experimental```Dynamic = 2@@ -13331,6 +13353,11 @@ MotionDriver<AnimatorBlend2DMotion>(from: number, to: number, progress: number): WeatherState```+## blobAlpha — function @experimental+```+(mesh: MeshData, vertex: number): number+```+## boxDistance — function @experimental```(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number@@ -13346,6 +13373,11 @@ MotionDriver<AnimatorBlend2DMotion>(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData```+## buildBlobMesh — function @experimental+```+(softness: number): MeshData+```+## buildFrameProfile — function @experimental```(input: FrameProfileInput): FrameProfile@@ -16011,6 +16043,11 @@ ServicesPlugin(def: AnimatorControllerDef, name: string, patch: { speed?: number; loop?: boolean; rootMotion?: boolean; }, layer?: number): AnimatorControllerDef```+## setBlobShadowGround — function @experimental+```+(app: App, sample: BlobShadowGround | null): void+```+## setButtonState — function @experimental```(world: World, entity: Entity, state: string): voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 5c942f1ee..792dac824 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1899 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1905 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1741,6 +1741,28 @@ PremultipliedAlpha = 4Screen = 3```+## BlobShadow — const @experimental+```+ComponentDef<BlobShadowData>+```++## BlobShadowData — interface @experimental+```+enabled: boolean+fadeHeight: number+groundY: number+lift: number+opacity: number+radius: number+shrink: number+softness: number+```++## BlobShadowGround — type @experimental+```+(x: number, z: number) => number | null+```+## BodyType — enum @experimental```Dynamic = 2@@ -13063,6 +13085,11 @@ MotionDriver<AnimatorBlend2DMotion>(from: number, to: number, progress: number): WeatherState```+## blobAlpha — function @experimental+```+(mesh: MeshData, vertex: number): number+```+## boxDistance — function @experimental```(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number@@ -13078,6 +13105,11 @@ MotionDriver<AnimatorBlend2DMotion>(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData```+## buildBlobMesh — function @experimental+```+(softness: number): MeshData+```+## buildFrameProfile — function @experimental```(input: FrameProfileInput): FrameProfile@@ -15738,6 +15770,11 @@ ServicesPlugin(def: AnimatorControllerDef, name: string, patch: { speed?: number; loop?: boolean; rootMotion?: boolean; }, layer?: number): AnimatorControllerDef```+## setBlobShadowGround — function @experimental+```+(app: App, sample: BlobShadowGround | null): void+```+## setButtonState — function @experimental```(world: World, entity: Entity, state: string): voiddiff --git a/sdk/src/core-render.ts b/sdk/src/core-render.tsindex c330bbca7..94d3cf4f6 100644--- a/sdk/src/core-render.ts+++ b/sdk/src/core-render.ts@@ -346,5 +346,6 @@ export { RenderDemand } from './render/renderDemand';export { buildPathGeometry, mergeGeometry, cubicBezier, quadraticBezier, circlePoints } from './render/vectorPath';export type { PathStyle, PathFill, PathStroke, PathColor, LineJoin, LineCap } from './render/vectorPath';export { setPath, clearPath } from './render/pathRenderer';+export { BlobShadow, setBlobShadowGround, buildBlobMesh, blobAlpha, type BlobShadowData, type BlobShadowGround } from './render/blobShadow';export type { RenderOnDemandOptions } from './render/renderDemand';export type { ShaderWarmup, ShaderWarmupOptions } from './render/shaderWarmup';diff --git a/sdk/src/render/blobShadow.ts b/sdk/src/render/blobShadow.tsnew file mode 100644index 000000000..0523d1f28--- /dev/null+++ b/sdk/src/render/blobShadow.ts@@ -0,0 +1,260 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file blobShadow.ts+ * @brief A soft dark disc on the ground under a thing: the cheapest shadow there is, and often the one a phone can afford.+ *+ * A real shadow is a map drawn from the light and read back by every pixel; a blob shadow is one disc of vertex colour lying on the ground,+ * drawn once, with no map, no light and no extra pass. It says "this stands here" and "this is this high" (the disc fades and shrinks as the+ * thing leaves the ground), which is most of what a shadow tells a player. It is NOT the light's shadow: it does not stretch with the sun, fall+ * across steps, or land on a wall.+ *+ * The component goes on the thing that casts. A disc is made for it (an entity of its own, never saved with the scene) and put on the ground+ * under it each frame. The ground is a height (`groundY`), or a function of where the thing stands ({@link setBlobShadowGround}) for a ground+ * that is not flat.+ */+import type { App } from '../app/app';+import type { Entity } from '../types';+import {+ defineComponent, MeshRenderer, RuntimeOnly, Transform,+ type ComponentDef, type MeshRendererData, type TransformData,+} from '../ecs/component';+import { defineResource } from '../ecs/resource';+import { defineSystem, Schedule } from '../ecs/system';+import { Assets } from '../asset/AssetPlugin';+import type { MaterialShaderSource } from '../asset/loaders/MaterialShaderAssetLoader';+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';+import { CullMode, Material, MATERIAL_FORMAT_VERSION } from './material';+import { BlendMode } from './blend';+import { Renderer } from './renderer';+import { log } from '../util/logger';++/** The fields of the `BlobShadow` component. @experimental */+export interface BlobShadowData {+ enabled: boolean;+ /** Radius of the disc where the thing stands on the ground, in world units. */+ radius: number;+ /** How dark the disc is at its centre, 0 to 1. */+ opacity: number;+ /** How soft its edge is: 0 a hard-edged disc, 1 a disc that fades from its centre. */+ softness: number;+ /** Height of the flat ground, in world units, when no ground function is set. */+ groundY: number;+ /** How far above the ground the thing may be before its shadow is gone. 0 never fades it. */+ fadeHeight: number;+ /** How small the disc is at that height, as a share of its size on the ground: 0 keeps its size, 1 shrinks it to nothing. */+ shrink: number;+ /** How far above the ground the disc is drawn, so it does not flicker against it. */+ lift: number;+}++/**+ * Puts a soft shadow disc on the ground under the entity.+ * @experimental+ */+export const BlobShadow: ComponentDef<BlobShadowData> = defineComponent<BlobShadowData>(+ 'BlobShadow',+ { enabled: true, radius: 50, opacity: 0.5, softness: 0.6, groundY: 0, fadeHeight: 200, shrink: 0.5, lift: 0.5 },+ {+ fields: {+ radius: { min: 0, step: 1, tooltip: 'Radius of the disc on the ground, in world units.' },+ opacity: { min: 0, max: 1, step: 0.01, tooltip: 'How dark the disc is at its centre.' },+ softness: { min: 0, max: 1, step: 0.01, tooltip: 'How soft its edge is (0 hard, 1 fading from the centre).' },+ groundY: { step: 1, tooltip: 'Height of the flat ground. A ground function set from code overrides it.' },+ fadeHeight: { min: 0, step: 1, tooltip: 'Height above the ground at which the shadow is gone (0 never fades it).' },+ shrink: { min: 0, max: 1, step: 0.01, tooltip: 'How small the disc gets at that height (0 keeps its size).' },+ lift: { min: 0, step: 0.1, advanced: true, tooltip: 'How far above the ground the disc is drawn.' },+ },+ },+);++/** Where the ground is under a point, for a ground that is not flat: its height there, or null where there is none (the flat `groundY` is used). @experimental */+export type BlobShadowGround = (x: number, z: number) => number | null;++interface GroundState { sample: BlobShadowGround | null }+const Ground = defineResource<GroundState>({ sample: null }, 'BlobShadowGround');++/** Sets how the ground height is found under each blob shadow; `null` goes back to each shadow's own `groundY`. @experimental */+export function setBlobShadowGround(app: App, sample: BlobShadowGround | null): void {+ if (!app.hasResource(Ground)) app.insertResource(Ground, { sample });+ else app.getResource(Ground).sample = sample;+}++const RINGS = 8;+const SEGMENTS = 28;++/**+ * A unit disc lying in the XZ plane (normal up), its vertex colour black and its alpha falling from the centre to the edge as `softness` says.+ * A resident mesh and not a MeshRenderer's inline geometry: the inline path is drawn in the XY plane only (it turns about Z and no other axis),+ * and a shadow lies on the ground.+ * @experimental+ */+export function buildBlobMesh(softness: number): MeshData {+ const soft = Math.min(Math.max(softness, 0), 1);+ // Where the fade begins: all the way in for a fully soft disc, a hair inside the rim for a hard one.+ const inner = (1 - soft) * 0.96;+ const { channels, vertexStride } = packChannels([+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },+ ]);+ const [pos, uv, color, normal] = channels.map((c) => c.offset) as [number, number, number, number];+ const count = 1 + RINGS * SEGMENTS;+ const vertices = new Uint8Array(count * vertexStride);+ const view = new DataView(vertices.buffer);+ const put = (index: number, x: number, z: number, alpha: number): void => {+ const base = index * vertexStride;+ view.setFloat32(base + pos, x, true); view.setFloat32(base + pos + 4, 0, true); view.setFloat32(base + pos + 8, z, true);+ view.setFloat32(base + uv, x * 0.5 + 0.5, true); view.setFloat32(base + uv + 4, z * 0.5 + 0.5, true);+ view.setUint8(base + color, 0); view.setUint8(base + color + 1, 0); view.setUint8(base + color + 2, 0);+ view.setUint8(base + color + 3, Math.round(alpha * 255));+ view.setFloat32(base + normal, 0, true); view.setFloat32(base + normal + 4, 1, true); view.setFloat32(base + normal + 8, 0, true);+ };+ put(0, 0, 0, 1);+ for (let r = 1; r <= RINGS; r++) {+ const t = r / RINGS;+ const u = Math.min(Math.max((t - inner) / Math.max(1 - inner, 1e-3), 0), 1);+ // The edge is zero, the middle is one, and the way down is a smoothstep: no ring shows as a band.+ const alpha = 1 - u * u * (3 - 2 * u);+ for (let k = 0; k < SEGMENTS; k++) {+ const a = (k / SEGMENTS) * Math.PI * 2;+ put(1 + (r - 1) * SEGMENTS + k, Math.cos(a) * t, Math.sin(a) * t, alpha);+ }+ }+ const indices: number[] = [];+ // Counter-clockwise seen from above (+Y): the way a ground is lit.+ for (let k = 0; k < SEGMENTS; k++) indices.push(0, 1 + ((k + 1) % SEGMENTS), 1 + k);+ for (let r = 1; r < RINGS; r++) {+ const a = 1 + (r - 1) * SEGMENTS, b = 1 + r * SEGMENTS;+ for (let k = 0; k < SEGMENTS; k++) {+ const n = (k + 1) % SEGMENTS;+ indices.push(a + k, a + n, b + n, a + k, b + n, b + k);+ }+ }+ return { channels, vertexStride, vertexCount: count, vertices, indices: new Uint32Array(indices), aabbMin: [-1, -0.01, -1], aabbMax: [1, 0.01, 1] };+}++/** The alpha at a vertex of a blob mesh, 0 to 1. @experimental */+export function blobAlpha(mesh: MeshData, vertex: number): number {+ const colour = mesh.channels.find((c) => c.semantic === MeshChannel.Color)!;+ return mesh.vertices[vertex * mesh.vertexStride + colour.offset + 3]! / 255;+}++/** A disc's entity and the MeshRenderer it was given: an insert REPLACES a component, so each change is the whole of it, written again. */+interface Disc { entity: Entity; softness: number; shown: boolean; mesh: Partial<MeshRendererData> }++/** Installs the system that keeps each blob shadow on the ground. Called once by the mesh renderer's plugin. */+export function installBlobShadows(app: App): () => void {+ const discs = new Map<Entity, Disc>();+ // One resident mesh per softness (rounded to a tenth): a shadow's softness rarely changes, and a hundred shadows of one softness are one mesh.+ const meshes = new Map<number, number>();+ const meshFor = (softness: number): number => {+ const key = Math.round(Math.min(Math.max(softness, 0), 1) * 10);+ let mesh = meshes.get(key);+ if (mesh === undefined) {+ mesh = app.getResource(Assets).createMesh(buildBlobMesh(key / 10)) ?? 0;+ meshes.set(key, mesh);+ }+ return mesh;+ };+ let material = 0;+ let materialPending = false;++ const ensureMaterial = (): number => {+ if (material || materialPending) return material;+ materialPending = true;+ void (async () => {+ try {+ const assets = app.getResource(Assets);+ // The Matcap shader at strength 0: it asks no lamp and reads no shadow, and what it draws is black with the alpha the vertices and the+ // tint give, which is all a shadow is.+ const source = await assets.load<MaterialShaderSource>('material-shader', 'builtin:matcap');+ const shader = source.compile([]);+ // Blended over the ground, tested against what stands in front of it, and writing no depth: a thing in front hides the disc+ // behind it and the disc hides nothing.+ material = Material.createFromAsset({+ version: MATERIAL_FORMAT_VERSION, type: 'material', shader: 'builtin:matcap', blendMode: BlendMode.Normal,+ depthTest: true, depthWrite: false, cull: CullMode.None, properties: { u_matcapStrength: 0 },+ }, shader);+ } catch (error) {+ log.warn('render', 'blob shadow material failed', error);+ } finally {+ materialPending = false;+ }+ })();+ return material;+ };++ const drop = (owner: Entity): void => {+ const disc = discs.get(owner);+ if (!disc) return;+ discs.delete(owner);+ if (app.world.valid(disc.entity)) app.world.despawn(disc.entity);+ };+ const offDespawn = app.world.onDespawn((entity: Entity) => drop(entity));++ const hide = (disc: Disc | undefined): void => {+ if (!disc?.shown) return;+ app.world.insert(disc.entity, MeshRenderer, { ...disc.mesh, enabled: false });+ disc.shown = false;+ };++ const system = defineSystem([], () => {+ const world = app.world;+ const owners = world.getEntitiesWithComponents([BlobShadow, Transform]);+ for (const owner of [...discs.keys()]) {+ if (!world.valid(owner) || !world.has(owner, BlobShadow)) drop(owner);+ }+ if (owners.length === 0) return;+ const mat = ensureMaterial();+ if (!mat) return;+ // The owners' world poses are resolved when the frame draws; read here they would be the previous frame's, and a shadow a frame behind+ // its owner is visibly loose. Resolving them is a pass over the transforms the render system makes again, which costs next to nothing.+ const cpp = world.getCppRegistry();+ if (cpp) Renderer.updateTransforms({ _cpp: cpp });+ const sample = app.hasResource(Ground) ? app.getResource(Ground).sample : null;++ for (const owner of owners) {+ const data = world.get(owner, BlobShadow) as BlobShadowData;+ let disc = discs.get(owner);+ if (!data.enabled || data.radius <= 0 || data.opacity <= 0) { hide(disc); continue; }+ const at = (world.get(owner, Transform) as TransformData).worldPosition;+ const ground = sample?.(at.x, at.z) ?? data.groundY;+ const height = Math.max(at.y - ground, 0);+ const fade = data.fadeHeight > 0 ? Math.min(Math.max(1 - height / data.fadeHeight, 0), 1) : 1;+ if (fade <= 0) { hide(disc); continue; }+ if (!disc) {+ const entity = world.spawn('BlobShadow');+ world.insert(entity, RuntimeOnly);+ world.insert(entity, Transform, {});+ const mesh: Partial<MeshRendererData> = {+ mesh: meshFor(data.softness), material: mat, lit: false, opaque: false, castShadows: false, enabled: true,+ };+ world.insert(entity, MeshRenderer, mesh);+ disc = { entity, softness: data.softness, shown: true, mesh };+ discs.set(owner, disc);+ } else if (disc.softness !== data.softness) {+ disc.mesh = { ...disc.mesh, mesh: meshFor(data.softness) };+ disc.softness = data.softness;+ }+ const radius = data.radius * (1 - data.shrink * (1 - fade));+ world.insert(disc.entity, Transform, {+ position: { x: at.x, y: ground + data.lift, z: at.z },+ scale: { x: radius, y: 1, z: radius },+ });+ world.insert(disc.entity, MeshRenderer, { ...disc.mesh, enabled: true, color: { r: 1, g: 1, b: 1, a: data.opacity * fade } });+ disc.shown = true;+ }+ }, { name: 'BlobShadowSystem' });+ app.addSystemToSchedule(Schedule.PostUpdate, system);++ return () => {+ offDespawn();+ for (const owner of [...discs.keys()]) drop(owner);+ if (app.hasResource(Assets)) {+ for (const mesh of meshes.values()) if (mesh) app.getResource(Assets).releaseBuiltMesh(mesh);+ }+ meshes.clear();+ };+}diff --git a/sdk/src/render/meshRenderer.ts b/sdk/src/render/meshRenderer.tsindex 70613a8d2..9b5c81067 100644--- a/sdk/src/render/meshRenderer.ts+++ b/sdk/src/render/meshRenderer.ts@@ -14,6 +14,7 @@ import type { MeshRendererGeometry } from '../ecs/component';import { defineResource } from '../ecs/resource';import { registerSceneComponentCodec } from '../scene/scene';import { withScratch } from '../wasm/wasmScratch';+import { installBlobShadows } from './blobShadow';function packRgba(colors: number[], v: number): number {const clamp = (x: number) => Math.max(0, Math.min(255, Math.round(x * 255)));@@ -100,6 +101,7 @@ export class MeshRendererPlugin implements Plugin {name = 'meshRenderer';readonly profileDomain = 'render';private offDespawn_: (() => void) | null = null;+ private offBlobShadows_: (() => void) | null = null;build(app: App): void {// `?? {}`: an app with no engine core (a test, a pure-logic host) still gets@@ -108,6 +110,8 @@ export class MeshRendererPlugin implements Plugin {const registry = app.world.getCppRegistry() as CppRegistry;const api = new MeshRendererAPI(engine, registry);app.insertResource(MeshRenderers, api);+ // A BlobShadow on an entity is a mesh this plugin draws; with none in the scene its system finds nothing and returns.+ this.offBlobShadows_ = installBlobShadows(app);this.offDespawn_ = app.world.onDespawn((entity: Entity) => {if (api.getGeometry(entity)) api.clearGeometry(entity);@@ -134,6 +138,8 @@ export class MeshRendererPlugin implements Plugin {}cleanup(): void {+ this.offBlobShadows_?.();+ this.offBlobShadows_ = null;this.offDespawn_?.();this.offDespawn_ = null;}diff --git a/sdk/tests/blob-shadow.test.ts b/sdk/tests/blob-shadow.test.tsnew file mode 100644index 000000000..1cd724f46--- /dev/null+++ b/sdk/tests/blob-shadow.test.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { BlobShadow, blobAlpha, buildBlobMesh } from '../src/render/blobShadow';+import { MeshChannel } from '../src/asset/meshFormat';++function positionOf(mesh: ReturnType<typeof buildBlobMesh>, vertex: number): [number, number, number] {+ const at = mesh.channels.find((c) => c.semantic === MeshChannel.Position)!.offset;+ const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset);+ const base = vertex * mesh.vertexStride + at;+ return [view.getFloat32(base, true), view.getFloat32(base + 4, true), view.getFloat32(base + 8, true)];+}++describe('blob shadow disc', () => {+ it('lies in the ground plane, inside the unit circle, with indices that name its vertices', () => {+ const mesh = buildBlobMesh(0.6);+ expect(mesh.indices.length % 3).toBe(0);+ for (const i of mesh.indices) expect(i).toBeLessThan(mesh.vertexCount);+ for (let v = 0; v < mesh.vertexCount; v++) {+ const [x, y, z] = positionOf(mesh, v);+ expect(y).toBe(0);+ expect(Math.hypot(x, z)).toBeLessThanOrEqual(1 + 1e-6);+ }+ });++ it('winds counter-clockwise seen from above, so a ground-facing cull keeps it', () => {+ const mesh = buildBlobMesh(0.5);+ for (let t = 0; t < mesh.indices.length; t += 3) {+ const [a, b, c] = [positionOf(mesh, mesh.indices[t]!), positionOf(mesh, mesh.indices[t + 1]!), positionOf(mesh, mesh.indices[t + 2]!)];+ // The y of (b - a) x (c - a): positive is facing up.+ const up = (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2]);+ expect(up).toBeGreaterThan(-1e-9);+ }+ });++ it('is opaque at the centre and gone at the rim, softer or harder as asked', () => {+ const soft = buildBlobMesh(1);+ const hard = buildBlobMesh(0);+ expect(blobAlpha(soft, 0)).toBe(1);+ expect(blobAlpha(soft, soft.vertexCount - 1)).toBe(0);+ expect(blobAlpha(hard, hard.vertexCount - 1)).toBe(0);+ // Half way out: the soft disc has already faded, the hard one has not begun.+ const half = 1 + 3 * 28;+ expect(blobAlpha(soft, half)).toBeLessThan(blobAlpha(hard, half));+ expect(blobAlpha(hard, half)).toBe(1);+ });++ it('is a component with defaults a scene can start from', () => {+ expect(BlobShadow._name).toBe('BlobShadow');+ expect(BlobShadow._default).toMatchObject({ enabled: true, radius: 50, opacity: 0.5 });+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 072d0f7d1..02b96c7d5 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3008,4 +3008,6 @@ export const NOTED = {{"note":"Filled polygons and joined strokes."},"feat(render): an edge outline effect with a colour and creases":{"note":"Edge Outline, a coloured line at silhouettes and creases."},+ "feat(render): blob shadows, a soft disc on the ground under a thing":+ {"note":"Blob shadows."},};diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex b21fb1564..e87072150 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -772,6 +772,7 @@ export const SCENES = [// The other half: the same edges, read through an identity post chain.{ id: "aa-edge-post", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/aa-edge-post.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.2353,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.2392,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.749,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.7529,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.502,\"y\":0.502,\"rgb\":[255,255,255],\"tol\":6},{\"x\":0.0784,\"y\":0.0784,\"rgb\":[0,0,0],\"tol\":6}]" } },{ id: "edge-outline", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/edge-outline.esscene", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "480", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.2458,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.5,\"y\":0.85,\"rgb\":[129,129,129],\"tol\":12},{\"x\":0.36,\"y\":0.42,\"rgb\":[137,95,70],\"tol\":15},{\"x\":0.7,\"y\":0.45,\"rgb\":[128,128,128],\"tol\":12}]" } },+ { id: "blob-shadow", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/blob-shadow.esscene", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "480", ESTELLA_VERIFY_STEPS: "6", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.85,\"rgb\":[191,191,191],\"tol\":8},{\"x\":0.38,\"y\":0.4,\"rgb\":[204,140,102],\"tol\":10},{\"x\":0.85,\"y\":0.38,\"rgb\":[199,178,127],\"tol\":12},{\"x\":0.845,\"y\":0.475,\"rgb\":[91,91,91],\"tol\":22},{\"x\":0.61,\"y\":0.46,\"rgb\":[102,102,102],\"tol\":22},{\"x\":0.385,\"y\":0.49,\"rgb\":[124,124,124],\"tol\":22}]" } },{ id: "ssao", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/ssao.esscene", ESTELLA_VERIFY_W: "320", ESTELLA_VERIFY_H: "240", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5016,\"y\":0.8996,\"rgb\":[191,191,191],\"tol\":6},{\"x\":0.3762,\"y\":0.4937,\"rgb\":[144,144,144],\"tol\":20},{\"x\":0.627,\"y\":0.4812,\"rgb\":[172,172,172],\"tol\":9},{\"x\":0.8527,\"y\":0.4686,\"rgb\":[147,147,147],\"tol\":9},{\"x\":0.1881,\"y\":0.5272,\"rgb\":[123,141,113],\"tol\":22},{\"x\":0.1285,\"y\":0.1967,\"rgb\":[133,136,148],\"tol\":9},{\"x\":0.627,\"y\":0.2008,\"rgb\":[179,184,199],\"tol\":5}]" } },// The same occlusion with a neutral colour grade ahead of it in the chain: a pass// behind another one still samples the scene's depth, and on WebGPU the colour it