Skip to content

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.

feat(2d): mist, sprite wind and cover fade, so a top-down scene can have the weather a forest needs

yhh060a6beb4211
diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdx
index 6fc193e07..591a0a8d5 100644
--- a/docs/astro/src/content/docs/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/graphics/materials.mdx
@@ -27,6 +27,7 @@ creates a material from a built-in template — the same list ships in code as
|---|---|---|
| **Unlit** | `sprite-unlit` | Texture × vertex color × `u_tint`. The plain default. |
| **Lit** | `sprite-lit` | Lit by the scene's 2D lights; `u_tint` + optional `u_normalMap`. |
+| **Sway** | `sprite-sway` | Leans in the wind with the foot fixed and the tip free — grass, reeds, hanging cloth. `u_swayStrength` is the lean as a share of the sprite's width; the weather's `wind` scales it. Lit, with an optional normal map. |
| **Hit Flash** | `sprite-hit-flash` | Blends toward `u_flashColor` by `u_flash` — drive it from code for damage blinks. |
| **Outline** | `sprite-outline` | Colored silhouette outline (`u_outlineColor`, `u_outlineWidth` in texels). |
| **Dissolve** | `sprite-dissolve` | Noise burn-away with a glowing edge (`u_progress` 0→1). |
diff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdx
index 1e61025ad..840c5a128 100644
--- a/docs/astro/src/content/docs/graphics/post-processing.mdx
+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx
@@ -24,6 +24,7 @@ several can stack in one frame at no extra target cost beyond the passes.
| `chromaticAberration` | RGB fringing | `intensity` |
| `blur` | Gaussian blur | `intensity` |
| `fxaa` | Fast anti-aliasing | `intensity` |
+| `mist2d` | Drifting banks of mist laid over the ground in world units. Reads no depth, so a 2D scene can have it; what is lit glows through it | `density`, `coverage`, `scale`, `speed`, `direction`, `glow`, colour |
| `distanceFog` | Linear fog by distance from the camera | `near`, `far`, `intensity`, colour |
| `heightFog` | Exponential height fog with the sun's glow and a hazy horizon | `density`, `heightFalloff`, `baseHeight`, `sunAzimuth`, `sunElevation`, `skyFog`, colours |
| `skyAtmosphere` | An atmosphere that scatters the sun's light, with sun, moon, stars and volumetric clouds, drawn where there is no surface | `intensity`, `haze`, `altitude`, `clouds`, `cloudBase`, `cloudThickness`, `windSpeed`, `overcast`, `sunAzimuth`, `sunElevation` |
@@ -496,7 +497,7 @@ package carries only when its content uses one:
| Group | Subpath | Effects |
|---|---|---|
| Basic | `esengine/fx-basic` | blur, bloom, vignette, grayscale, colorGrade, lutGrade, agx, chromaticAberration, tonemap, fxaa, sharpen, lensDistortion, pixelate, outline, depthOutline, edgeOutline, filmGrain, motionBlur, lensFlare |
-| Atmosphere | `esengine/fx-atmosphere` | skyAtmosphere, heightFog, distanceFog, rain |
+| Atmosphere | `esengine/fx-atmosphere` | mist2d, skyAtmosphere, heightFog, distanceFog, rain |
| Lighting | `esengine/fx-lighting` | ssao, gtao, ssr, ssgi, voxelGI, contactShadows, lightShafts, autoExposure, depthOfField, subsurface, taa |
The export reads the effects a `PostProcessVolume` names (and a `Weather` or `TimeOfDay` component, which drive the atmosphere group) and imports
diff --git a/docs/astro/src/content/docs/graphics/sprites.mdx b/docs/astro/src/content/docs/graphics/sprites.mdx
index a789a376d..db598f760 100644
--- a/docs/astro/src/content/docs/graphics/sprites.mdx
+++ b/docs/astro/src/content/docs/graphics/sprites.mdx
@@ -233,6 +233,21 @@ front of it — no manual `layer` or z juggling.
gameplay layer(s) that need it.
</Aside>
+### Fading a roof or a crown over the player
+
+A roof, or a tree crown, drawn over the ground it covers hides whoever walks in. Put `CoverFade` on the covering sprite and `CoverFadeTarget` on the
+thing that must stay visible (the player): while a target stands on the sprite's ground, the sprite eases down to `opacity` of its own alpha over `fadeTime`,
+and eases back when the target leaves.
+
+| Field | What it does |
+|---|---|
+| `opacity` | The sprite's alpha, as a share of its own, while something stands under it. |
+| `fadeTime` | Seconds the fade takes, either way. |
+| `margin` | Ground around the sprite's edge that counts as under it, so the fade starts as a target steps up to the edge. |
+| `round` | The covered ground is the ellipse inside the rectangle (a crown), not the whole rectangle (a roof). |
+
+The covered ground is the sprite's size and pivot under the entity's scale; rotation is not read. It runs in play only.
+
### Depth layers (2.5D)
Check a layer under **Settings → Project → Rendering → Advanced → Depth-sorted layers** and it
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
index f2fa68dae..3ecde61a5 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
@@ -23,6 +23,7 @@ std140 uniform 块,于是 CPU 能按名字设置、并安全地送到 GPU。一
|---|---|---|
| **Unlit** | `sprite-unlit` | 纹理 × 顶点色 × `u_tint`,普通默认。 |
| **Lit** | `sprite-lit` | 被场景 2D 灯光照亮;`u_tint` + 可选 `u_normalMap`。 |
+| **Sway** | `sprite-sway` | 随风倾斜,底部固定、顶部自由——草、芦苇、悬挂的布。`u_swayStrength` 是倾斜幅度占精灵宽度的比例,天气的 `wind` 会放大它。受光照,可带法线贴图。 |
| **Hit Flash** | `sprite-hit-flash` | 按 `u_flash` 混向 `u_flashColor`——代码里驱动它做受击闪白。 |
| **Outline** | `sprite-outline` | 彩色剪影描边(`u_outlineColor`、`u_outlineWidth`,单位纹素)。 |
| **Dissolve** | `sprite-dissolve` | 噪声烧蚀 + 发光边缘(`u_progress` 0→1)。 |
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx
index fbb246a1a..fdf146ff7 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx
@@ -26,6 +26,7 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess
| `lensFlare` | 亮于阈值的物体投出的鬼影和光晕,带色彩边缘 | `intensity`、`threshold`、`ghosts`、`dispersal`、`haloWidth`、`chromatic`、`tint` |
| `blur` | 高斯模糊 | `intensity` |
| `fxaa` | 快速抗锯齿 | `intensity` |
+| `mist2d` | 按世界坐标铺在地面上的、会飘动的成团薄雾。不读深度,2D 场景也能用;被照亮的东西会在雾里发光 | `density`、`coverage`、`scale`、`speed`、`direction`、`glow`、颜色 |
| `distanceFog` | 按到相机的距离做线性雾 | `near`、`far`、`intensity`、颜色 |
| `heightFog` | 指数高度雾,带太阳辉光和朦胧的地平线 | `density`、`heightFalloff`、`baseHeight`、`sunAzimuth`、`sunElevation`、`skyFog`、颜色 |
| `skyAtmosphere` | 散射太阳光的大气,带太阳、月亮、星星和体积云,画在没有表面的地方 | `intensity`、`haze`、`altitude`、`clouds`、`cloudBase`、`cloudThickness`、`windSpeed`、`overcast`、`sunAzimuth`、`sunElevation` |
@@ -380,7 +381,7 @@ stack.addPass('lutGrade', getEffectDef('lutGrade')!.factory())
| 组 | 子路径 | 效果 |
|---|---|---|
| 基础 | `esengine/fx-basic` | blur、bloom、vignette、grayscale、colorGrade、lutGrade、chromaticAberration、tonemap、fxaa、sharpen、lensDistortion、pixelate、outline、depthOutline、edgeOutline、filmGrain、motionBlur、lensFlare |
-| 大气 | `esengine/fx-atmosphere` | skyAtmosphere、heightFog、distanceFog、rain |
+| 大气 | `esengine/fx-atmosphere` | mist2d、skyAtmosphere、heightFog、distanceFog、rain |
| 光照 | `esengine/fx-lighting` | ssao、gtao、ssr、ssgi、voxelGI、contactShadows、lightShafts、autoExposure、depthOfField、subsurface、taa |
导出会读 `PostProcessVolume` 里写了哪些效果(以及驱动大气组的 `Weather`、`TimeOfDay` 组件),并导入它们需要的组。**从脚本里**加的效果——
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx b/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
index 8455a9cee..080b69999 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
@@ -205,6 +205,19 @@ world.applyEntityOrder([other, another, card]);
只对需要它的玩法层开启 Y 排序。
</Aside>
+### 屋顶与树冠遮挡淡出
+
+盖在地面上的屋顶、树冠会挡住走进去的人。给遮挡的精灵加 `CoverFade`,给必须看得见的对象(玩家)加 `CoverFadeTarget`:目标站在精灵所覆盖的地面上时,精灵在 `fadeTime` 内淡到自身 alpha 的 `opacity` 倍,离开后淡回。
+
+| 字段 | 作用 |
+|---|---|
+| `opacity` | 有东西站在下面时,精灵 alpha 占自身的比例。 |
+| `fadeTime` | 淡出或淡回所需的秒数。 |
+| `margin` | 精灵边缘外多少世界单位也算"在下面",让淡出在目标走到边缘时就开始。 |
+| `round` | 覆盖范围取矩形内接的椭圆(树冠),而不是整个矩形(屋顶)。 |
+
+覆盖范围取精灵尺寸与锚点、乘以实体缩放,不读旋转。只在运行时生效。
+
### 深度层(2.5D)
在 **设置 → 项目 → 渲染 → 高级 → 深度排序层** 勾选某个层后,该层完全不再依赖
diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.ts
index b1bb3d97e..8c6df012b 100644
--- a/pipeline/src/project/targetSupport.ts
+++ b/pipeline/src/project/targetSupport.ts
@@ -86,7 +86,7 @@ export const POST_PROCESS_EFFECT_GROUP: Readonly<Record<string, Subsystem>> = {
chromaticAberration: 'fxBasic', tonemap: 'fxBasic', fxaa: 'fxBasic', lensDistortion: 'fxBasic', pixelate: 'fxBasic',
outline: 'fxBasic', depthOutline: 'fxBasic', edgeOutline: 'fxBasic', lutGrade: 'fxBasic', agx: 'fxBasic', sharpen: 'fxBasic', filmGrain: 'fxBasic',
motionBlur: 'fxBasic', lensFlare: 'fxBasic',
- distanceFog: 'fxAtmosphere', skyAtmosphere: 'fxAtmosphere', heightFog: 'fxAtmosphere', rain: 'fxAtmosphere',
+ mist2d: 'fxAtmosphere', distanceFog: 'fxAtmosphere', skyAtmosphere: 'fxAtmosphere', heightFog: 'fxAtmosphere', rain: 'fxAtmosphere',
voxelGI: 'fxLighting', ssgi: 'fxLighting', contactShadows: 'fxLighting', lightShafts: 'fxLighting',
autoExposure: 'fxLighting', depthOfField: 'fxLighting', ssao: 'fxLighting', subsurface: 'fxLighting',
gtao: 'fxLighting', ssr: 'fxLighting', taa: 'fxLighting',
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 7fd7515c3..753ce641e 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 · 1906 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1911 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2855,6 +2855,25 @@ pageHeight: number
pageWidth: number
```
+## CoverFade — const @experimental
+```
+ComponentDef<CoverFadeData>
+```
+
+## CoverFadeData — interface @experimental
+```
+enabled: boolean
+fadeTime: number
+margin: number
+opacity: number
+round: boolean
+```
+
+## CoverFadeTarget — const @experimental
+```
+ComponentDef<Record<string, never>>
+```
+
## CreateListViewOptions — interface @experimental
```
background: UIVisualInit | undefined
@@ -5601,7 +5620,7 @@ static prototype: MaskReach
## Material — const @experimental
```
-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }
+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }
```
## MaterialAssetData — interface @experimental
@@ -13500,6 +13519,11 @@ MotionDriver<AnimatorBlend2DMotion>
Plugin
```
+## coversPoint — function @experimental
+```
+(px: number, py: number, centre: { x: number; y: number; }, half: { x: number; y: number; }, margin: number, round: boolean): boolean
+```
+
## createAnimClip — function @experimental
```
(texture: string, cellWidth: number, cellHeight: number, pageWidth: number, pageHeight: number): AnimClipAssetData
@@ -16150,6 +16174,11 @@ Plugin
StatsPlugin
```
+## stepFade — function @experimental
+```
+(current: number, goal: number, dt: number, fadeTime: number): number
+```
+
## stopSoundEventSource — function @beta
```
(world: World, entity: Entity): void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index f5beb9a57..ed9b1d493 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 · 1925 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1930 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2863,6 +2863,25 @@ pageHeight: number
pageWidth: number
```
+## CoverFade — const @experimental
+```
+ComponentDef<CoverFadeData>
+```
+
+## CoverFadeData — interface @experimental
+```
+enabled: boolean
+fadeTime: number
+margin: number
+opacity: number
+round: boolean
+```
+
+## CoverFadeTarget — const @experimental
+```
+ComponentDef<Record<string, never>>
+```
+
## CreateListViewOptions — interface @experimental
```
background: UIVisualInit | undefined
@@ -5609,7 +5628,7 @@ static prototype: MaskReach
## Material — const @experimental
```
-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }
+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }
```
## MaterialAssetData — interface @experimental
@@ -13728,6 +13747,11 @@ MotionDriver<AnimatorBlend2DMotion>
Plugin
```
+## coversPoint — function @experimental
+```
+(px: number, py: number, centre: { x: number; y: number; }, half: { x: number; y: number; }, margin: number, round: boolean): boolean
+```
+
## createAnimClip — function @experimental
```
(texture: string, cellWidth: number, cellHeight: number, pageWidth: number, pageHeight: number): AnimClipAssetData
@@ -16413,6 +16437,11 @@ Plugin
StatsPlugin
```
+## stepFade — function @experimental
+```
+(current: number, goal: number, dt: number, fadeTime: number): number
+```
+
## stopSoundEventSource — function @beta
```
(world: World, entity: Entity): void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 255cf9db6..930456aaa 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 · 1905 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1910 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2850,6 +2850,25 @@ pageHeight: number
pageWidth: number
```
+## CoverFade — const @experimental
+```
+ComponentDef<CoverFadeData>
+```
+
+## CoverFadeData — interface @experimental
+```
+enabled: boolean
+fadeTime: number
+margin: number
+opacity: number
+round: boolean
+```
+
+## CoverFadeTarget — const @experimental
+```
+ComponentDef<Record<string, never>>
+```
+
## CreateListViewOptions — interface @experimental
```
background: UIVisualInit | undefined
@@ -5596,7 +5615,7 @@ static prototype: MaskReach
## Material — const @experimental
```
-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }
+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }
```
## MaterialAssetData — interface @experimental
@@ -13495,6 +13514,11 @@ MotionDriver<AnimatorBlend2DMotion>
Plugin
```
+## coversPoint — function @experimental
+```
+(px: number, py: number, centre: { x: number; y: number; }, half: { x: number; y: number; }, margin: number, round: boolean): boolean
+```
+
## createAnimClip — function @experimental
```
(texture: string, cellWidth: number, cellHeight: number, pageWidth: number, pageHeight: number): AnimClipAssetData
@@ -16155,6 +16179,11 @@ Plugin
StatsPlugin
```
+## stepFade — function @experimental
+```
+(current: number, goal: number, dt: number, fadeTime: number): number
+```
+
## stopSoundEventSource — function @beta
```
(world: World, entity: Entity): void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 5b9914ae3..cfc995504 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 · 1927 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1932 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2850,6 +2850,25 @@ pageHeight: number
pageWidth: number
```
+## CoverFade — const @experimental
+```
+ComponentDef<CoverFadeData>
+```
+
+## CoverFadeData — interface @experimental
+```
+enabled: boolean
+fadeTime: number
+margin: number
+opacity: number
+round: boolean
+```
+
+## CoverFadeTarget — const @experimental
+```
+ComponentDef<Record<string, never>>
+```
+
## CreateListViewOptions — interface @experimental
```
background: UIVisualInit | undefined
@@ -5596,7 +5615,7 @@ static prototype: MaskReach
## Material — const @experimental
```
-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }
+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }
```
## MaterialAssetData — interface @experimental
@@ -13795,6 +13814,11 @@ MotionDriver<AnimatorBlend2DMotion>
Plugin
```
+## coversPoint — function @experimental
+```
+(px: number, py: number, centre: { x: number; y: number; }, half: { x: number; y: number; }, margin: number, round: boolean): boolean
+```
+
## createAnimClip — function @experimental
```
(texture: string, cellWidth: number, cellHeight: number, pageWidth: number, pageHeight: number): AnimClipAssetData
@@ -16460,6 +16484,11 @@ Plugin
StatsPlugin
```
+## stepFade — function @experimental
+```
+(current: number, goal: number, dt: number, fadeTime: number): number
+```
+
## stopSoundEventSource — function @beta
```
(world: World, entity: Entity): void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index e5e9d8ad6..ba7992597 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 · 1918 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1923 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2850,6 +2850,25 @@ pageHeight: number
pageWidth: number
```
+## CoverFade — const @experimental
+```
+ComponentDef<CoverFadeData>
+```
+
+## CoverFadeData — interface @experimental
+```
+enabled: boolean
+fadeTime: number
+margin: number
+opacity: number
+round: boolean
+```
+
+## CoverFadeTarget — const @experimental
+```
+ComponentDef<Record<string, never>>
+```
+
## CreateListViewOptions — interface @experimental
```
background: UIVisualInit | undefined
@@ -5603,7 +5622,7 @@ static prototype: MaskReach
## Material — const @experimental
```
-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }
+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }
```
## MaterialAssetData — interface @experimental
@@ -13527,6 +13546,11 @@ MotionDriver<AnimatorBlend2DMotion>
Plugin
```
+## coversPoint — function @experimental
+```
+(px: number, py: number, centre: { x: number; y: number; }, half: { x: number; y: number; }, margin: number, round: boolean): boolean
+```
+
## createAnimClip — function @experimental
```
(texture: string, cellWidth: number, cellHeight: number, pageWidth: number, pageHeight: number): AnimClipAssetData
@@ -16187,6 +16211,11 @@ Plugin
StatsPlugin
```
+## stepFade — function @experimental
+```
+(current: number, goal: number, dt: number, fadeTime: number): number
+```
+
## stopSoundEventSource — function @beta
```
(world: World, entity: Entity): void
diff --git a/sdk/src/animation/AnimationPlugin.ts b/sdk/src/animation/AnimationPlugin.ts
index cf5145283..b06fadb4f 100644
--- a/sdk/src/animation/AnimationPlugin.ts
+++ b/sdk/src/animation/AnimationPlugin.ts
@@ -22,6 +22,7 @@ import { AnimatorController, AnimatorControllerAPI, type AnimatorControllerDef }
import type { AnimatorAvatar } from './animatorAvatar';
import { appRegistryAsset } from '../asset/registryLookup';
import { playModeOnly } from '../ecs/env';
+import { installCoverFade } from '../render/coverFade';
import { SystemLabel } from '../ecs/systemLabels';
export class AnimationPlugin implements Plugin {
@@ -52,8 +53,11 @@ export class AnimationPlugin implements Plugin {
anim.removeEntityListeners(entity);
animator.removeEntity(entity);
});
- this.despawnCleanups_.set(app, offDespawn);
- this.latestDespawnCleanup_ = offDespawn;
+ // A roof or a crown with a CoverFade thins out over what stands under it; with none in the scene the system finds nothing and returns.
+ const offCoverFade = installCoverFade(app);
+ const release = (): void => { offDespawn(); offCoverFade(); };
+ this.despawnCleanups_.set(app, release);
+ this.latestDespawnCleanup_ = release;
app.addSystemToSchedule(Schedule.Update, defineSystem(
[Res(Time), Res(Tween)],
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 94d3cf4f6..f7b3df7e1 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -346,6 +346,7 @@ 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 { CoverFade, CoverFadeTarget, coversPoint, stepFade, type CoverFadeData } from './render/coverFade';
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/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
index 35dce55f9..8147e2ba0 100644
--- a/sdk/src/postprocess/effects.ts
+++ b/sdk/src/postprocess/effects.ts
@@ -296,6 +296,27 @@ registerEffect({
],
});
+registerEffect({
+ type: 'mist2d',
+ label: 'Mist 2D',
+ factory: () => postProcessEffects.createMist2d(),
+ uniforms: [
+ // How thick the mist is where it is thickest.
+ { name: 'u_density', label: 'Density', min: 0, max: 1, step: 0.01, defaultValue: 0.55, neutralValue: 0 },
+ // How much of the ground it covers: 0 is none, 1 nearly all.
+ { name: 'u_coverage', label: 'Coverage', min: 0, max: 1, step: 0.01, defaultValue: 0.6 },
+ // WORLD lengths: the size of the banks, how fast they drift, and which way (degrees from +X).
+ { name: 'u_scale', label: 'Scale', min: 40, max: 4000, step: 10, defaultValue: 520 },
+ { name: 'u_speed', label: 'Speed', min: 0, max: 400, step: 1, defaultValue: 18 },
+ { name: 'u_direction', label: 'Direction', min: 0, max: 360, step: 1, defaultValue: 25 },
+ // How much of what is lit scatters in the mist: a lamp glows in it.
+ { name: 'u_glow', label: 'Glow', min: 0, max: 2, step: 0.01, defaultValue: 0.6 },
+ ],
+ colors: [
+ { name: 'u_fogColor', label: 'Colour', defaultValue: { r: 0.62, g: 0.72, b: 0.76, a: 1 } },
+ ],
+});
+
registerEffect({
type: 'distanceFog',
label: 'Distance Fog',
@@ -840,7 +861,7 @@ const CATEGORIES: Record<EffectCategory, string[]> = {
lens: ['bloom', 'depthOfField', 'motionBlur', 'lensFlare', 'filmGrain', 'chromaticAberration', 'lensDistortion', 'vignette', 'sharpen'],
color: ['tonemap', 'agx', 'colorGrade', 'lutGrade', 'displayLut', 'autoExposure', 'grayscale'],
light: ['ssao', 'gtao', 'ssgi', 'ssr', 'voxelGI', 'contactShadows', 'lightShafts', 'subsurface'],
- atmosphere: ['distanceFog', 'heightFog', 'skyAtmosphere', 'rain'],
+ atmosphere: ['mist2d', 'distanceFog', 'heightFog', 'skyAtmosphere', 'rain'],
aa: ['fxaa', 'taa'],
stylize: ['blur', 'pixelate', 'outline', 'depthOutline', 'edgeOutline'],
};
diff --git a/sdk/src/postprocess/sources/atmosphere.ts b/sdk/src/postprocess/sources/atmosphere.ts
index efc9118c7..1721d78a2 100644
--- a/sdk/src/postprocess/sources/atmosphere.ts
+++ b/sdk/src/postprocess/sources/atmosphere.ts
@@ -2361,6 +2361,99 @@ fn shelteredAt(W : vec3f) -> f32 {
return vec4f(col, src.a);
}
#pragma end
+`;
+ return Material.compileShader(source);
+ },
+ createMist2d(): ShaderHandle {
+ // Fog that does not ask the depth buffer, because a 2D scene has none: sprites are blended, they write no depth, so the
+ // fogs that measure a distance see nothing to fog. This one is a layer of drifting noise laid over the ground in WORLD
+ // units, found from the screen by un-projecting at the near plane, which for an orthographic eye is the world's x and y.
+ // It sits over the finished picture, so what is lit shows through it: `u_glow` lets a lamp's light scatter in the haze.
+ const GLSL = `
+float mistHash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
+float mistNoise(vec2 p) {
+ vec2 i = floor(p);
+ vec2 f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(mistHash(i), mistHash(i + vec2(1.0, 0.0)), f.x), mix(mistHash(i + vec2(0.0, 1.0)), mistHash(i + vec2(1.0, 1.0)), f.x), f.y);
+}
+float mistFbm(vec2 p) {
+ float a = 0.5;
+ float s = 0.0;
+ for (int k = 0; k < 3; k++) { s += a * mistNoise(p); p = p * 2.03 + vec2(17.3, 9.1); a *= 0.5; }
+ return s / 0.875;
+}`;
+ const WGSL = `
+fn mistHash(p : vec2f) -> f32 { return fract(sin(dot(p, vec2f(127.1, 311.7))) * 43758.5453); }
+fn mistNoise(p : vec2f) -> f32 {
+ let i = floor(p);
+ var f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(mistHash(i), mistHash(i + vec2f(1.0, 0.0)), f.x), mix(mistHash(i + vec2f(0.0, 1.0)), mistHash(i + vec2f(1.0, 1.0)), f.x), f.y);
+}
+fn mistFbm(q : vec2f) -> f32 {
+ var p = q;
+ var a = 0.5;
+ var s = 0.0;
+ for (var k = 0; k < 3; k = k + 1) { s = s + a * mistNoise(p); p = p * 2.03 + vec2f(17.3, 9.1); a = a * 0.5; }
+ return s / 0.875;
+}`;
+ const source = `#pragma shader "PP Mist 2D"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_fogColor color default(0.62,0.72,0.76,1)
+#pragma param u_density float default(0.55) range(0,1)
+#pragma param u_coverage float default(0.6) range(0,1)
+#pragma param u_scale float default(520) range(40,4000)
+#pragma param u_speed float default(18) range(0,400)
+#pragma param u_direction float default(25) range(0,360)
+#pragma param u_glow float default(0.6) range(0,2)
+
+#pragma fragment
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+out vec4 fragColor;
+${GLSL}
+
+void main() {
+ vec4 src = texture(u_texture, v_texCoord);
+ vec2 world = worldFromDepth(v_texCoord, 0.0).xy + u_renderOrigin.xy;
+ float angle = radians(u_direction);
+ vec2 p = (world - vec2(cos(angle), sin(angle)) * (u_speed * u_time.x)) / max(u_scale, 1.0);
+ // Warped by a slower noise of its own, so the banks fold into one another and do not just slide.
+ float n = mistFbm(p + 0.4 * vec2(mistFbm(p * 0.6 + 3.1), mistFbm(p * 0.6 + 8.4)));
+ float lo = 1.0 - u_coverage * 0.9;
+ float t = smoothstep(lo, lo + 0.35, n) * u_density;
+ vec3 fog = u_fogColor.rgb;
+#ifdef ES_LINEAR
+ fog = srgbToLinear(fog);
+#endif
+ vec3 col = mix(src.rgb, fog, t) + src.rgb * (t * u_glow);
+ fragColor = vec4(col, src.a);
+}
+#pragma end
+
+#pragma fragment wgsl
+${WGSL}
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let src = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
+ let world = worldFromDepth(v.v_texCoord, 0.0).xy + frame.renderOrigin.xy;
+ let angle = radians(mc.u_direction);
+ let p = (world - vec2f(cos(angle), sin(angle)) * (mc.u_speed * tc.u_time.x)) / max(mc.u_scale, 1.0);
+ let n = mistFbm(p + 0.4 * vec2f(mistFbm(p * 0.6 + 3.1), mistFbm(p * 0.6 + 8.4)));
+ let lo = 1.0 - mc.u_coverage * 0.9;
+ let t = smoothstep(lo, lo + 0.35, n) * mc.u_density;
+ var fog = mc.u_fogColor.rgb;
+#ifdef ES_LINEAR
+ fog = srgbToLinear(fog);
+#endif
+ let col = mix(src.rgb, fog, vec3f(t)) + src.rgb * (t * mc.u_glow);
+ return vec4f(col, src.a);
+}
+#pragma end
`;
return Material.compileShader(source);
},
diff --git a/sdk/src/postprocess/weather.ts b/sdk/src/postprocess/weather.ts
index 63a17cb55..a9ed39c75 100644
--- a/sdk/src/postprocess/weather.ts
+++ b/sdk/src/postprocess/weather.ts
@@ -245,6 +245,19 @@ export function applyWeatherToEffects(effects: Map<string, BlendedEffect>, state
if (colour && state.fogTintAmount > 0) fog.colors.set('u_fogColor', towards(colour, state.fogTint, state.fogTintAmount));
}
}
+ if (drive & WeatherDrive.Fog) {
+ // A 2D scene's mist is an opacity, not an exponent: the weather's multiplier is taken as a root so a rain thickens it
+ // without clamping straight to opaque, and it spreads as it thickens (more of the ground under it, not only denser banks).
+ const mist = effects.get('mist2d');
+ if (mist && mist.enabled) {
+ mist.uniforms.set('u_density', Math.min(value(mist, 'mist2d', 'u_density') * Math.sqrt(state.fogDensity), 1));
+ mist.uniforms.set('u_coverage', Math.min(value(mist, 'mist2d', 'u_coverage') * (1 + 0.1 * (state.fogDensity - 1)), 1));
+ mist.uniforms.set('u_glow', value(mist, 'mist2d', 'u_glow') * state.fogGlow);
+ const colour = mist.colors.get('u_fogColor')
+ ?? getEffectDef('mist2d')?.colors?.find((c) => c.name === 'u_fogColor')?.defaultValue;
+ if (colour && state.fogTintAmount > 0) mist.colors.set('u_fogColor', towards(colour, state.fogTint, state.fogTintAmount));
+ }
+ }
if (drive & WeatherDrive.Fog) {
const sky = effects.get('skyAtmosphere');
if (sky && sky.enabled) sky.uniforms.set('u_overcast', Math.max(value(sky, 'skyAtmosphere', 'u_overcast'), state.overcast));
diff --git a/sdk/src/postprocess/weatherSystem.ts b/sdk/src/postprocess/weatherSystem.ts
index ed32c4413..180b0c51a 100644
--- a/sdk/src/postprocess/weatherSystem.ts
+++ b/sdk/src/postprocess/weatherSystem.ts
@@ -25,6 +25,7 @@ import { isEditor, isPlayMode } from '../ecs/env';
import {
blendWeather, setCurrentWeather, weatherPresetId, WEATHER_NONE, WeatherDrive, type WeatherState,
} from './weather';
+import { Material } from '../render/material';
import { timeOfDayAt, setCurrentTimeOfDay, TimeDrive, type TimeOfDayState } from './timeOfDay';
/** What a light was authored with, kept so a weather scales the author's number and never its own last answer. */
@@ -44,6 +45,21 @@ interface LightBase {
const bases = new Map<Entity, LightBase>();
+/** The materials the weather has put its wind on, so they can be set back to 1 when it goes. */
+const blown = new Set<number>();
+
+/**
+ * The weather's wind on sprites that sway: a material that declares `u_swayWind` (the Sway template) is told how hard it blows, as the Foliage
+ * module tells its own. A value written per frame, not scaled from an authored one, so there is nothing to put back but the 1 it started at.
+ */
+function blowSprites(wind: number): void {
+ if (wind === 1 && blown.size === 0) return;
+ for (const material of Material.materialsDeclaring('u_swayWind')) {
+ Material.setUniform(material, 'u_swayWind', wind);
+ if (wind === 1) blown.delete(material); else blown.add(material);
+ }
+}
+
/** Where each Weather is in its sequence, and how long it has held. Not in the component: a scene file need not carry it. */
const cycles = new Map<Entity, { index: number; held: number }>();
@@ -267,6 +283,7 @@ export const weatherSystem = defineSystem(
let clock: [Entity, TimeOfDayData] | null = null;
for (const entry of times) { clock = entry; break; }
if (!found && !clock) {
+ blowSprites(1);
if (bases.size > 0) restoreLights(world);
if (soundBases.size > 0) restoreSound(world);
cycles.clear();
@@ -300,6 +317,8 @@ export const weatherSystem = defineSystem(
setCurrentTimeOfDay(null);
}
+ blowSprites(weatherState && playing && (weatherDrive & WeatherDrive.Wind) ? weatherState.wind : 1);
+
const lightWork = (weatherState !== null && (weatherDrive & (WeatherDrive.Lights | WeatherDrive.Reflections)) !== 0)
|| (timeState !== null && (timeDrive & (TimeDrive.Lights | TimeDrive.Reflections)) !== 0);
if (playing && lightWork) applyLights(world, { weather: weatherState, weatherDrive, time: timeState, timeDrive });
@@ -315,6 +334,7 @@ export const weatherSystem = defineSystem(
export function resetWeatherSystem(): void {
bases.clear();
soundBases.clear();
+ blown.clear();
cycles.clear();
setCurrentWeather(null);
setCurrentTimeOfDay(null);
diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.ts
index b98cc8b5d..ec3d93cd5 100644
--- a/sdk/src/render/builtinShaders.ts
+++ b/sdk/src/render/builtinShaders.ts
@@ -135,6 +135,62 @@ void main() {
#pragma end
`;
+// Grass, reeds, hanging cloth: the sprite's top leans and returns, its foot stays. A sprite shader is a fragment shader, so the lean is a shift of where
+// the texture is read, growing from nothing at the bottom edge to u_swayStrength (a share of the sprite's width) at the top; the sprite's picture should
+// leave a margin at the sides for it to lean into. u_swayWind is the weather's wind, written by the engine each frame (1 with none).
+const SPRITE_SWAY = `#pragma shader "Sway"
+#pragma version 300 es
+#pragma domain Lit
+#pragma param u_tint color default(1,1,1,1)
+#pragma param u_normalMap texture default(flatnormal) texel(data)
+#pragma param u_swayStrength float default(0.12) range(0,0.5) ui(slider)
+#pragma param u_swaySpeed float default(1.6) range(0,8) ui(slider)
+#pragma param u_swayScale float default(260) range(20,2000)
+#pragma param u_swayWind float default(1) range(0,4)
+
+#pragma fragment
+precision mediump float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+in highp vec2 v_worldPos;
+
+uniform sampler2D u_textures[8];
+
+out vec4 fragColor;
+
+void main() {
+ // The gust travels across the world, so neighbouring plants lean in turn and not together.
+ highp float t = u_time.x * u_swaySpeed;
+ highp float phase = (v_worldPos.x + v_worldPos.y * 0.5) / u_swayScale;
+ float gust = sin(t + phase) + 0.5 * sin(t * 2.3 + phase * 1.7);
+ float tip = pow(clamp(v_texCoord.y, 0.0, 1.0), 1.5);
+ vec2 uv = vec2(v_texCoord.x - gust * u_swayStrength * u_swayWind * tip, v_texCoord.y);
+ vec4 base = texture(u_textures[0], uv) * v_color * u_tint;
+ if (uv.x < 0.0 || uv.x > 1.0) base.a = 0.0;
+ vec3 N = sampleNormal(u_normalMap, uv);
+ fragColor = vec4(applyLighting2D(base.rgb, N, v_worldPos), base.a);
+}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ // Taken before any branch: a derivative needs every fragment of its quad.
+ let duvx = dpdx(v.v_texCoord);
+ let duvy = dpdy(v.v_texCoord);
+ let t = tc.u_time.x * mc.u_swaySpeed;
+ let phase = (v.v_worldPos.x + v.v_worldPos.y * 0.5) / mc.u_swayScale;
+ let gust = sin(t + phase) + 0.5 * sin(t * 2.3 + phase * 1.7);
+ let tip = pow(clamp(v.v_texCoord.y, 0.0, 1.0), 1.5);
+ let uv = vec2f(v.v_texCoord.x - gust * mc.u_swayStrength * mc.u_swayWind * tip, v.v_texCoord.y);
+ var base = textureSampleGrad(t0, s0, uv, duvx, duvy) * v.v_color * mc.u_tint;
+ if (uv.x < 0.0 || uv.x > 1.0) { base.a = 0.0; }
+ let N = sampleNormalGrad(u_normalMap, u_normalMap_s, uv, duvx, duvy);
+ return vec4f(applyLighting2D(base.rgb, N, v.v_worldPos), base.a);
+}
+#pragma end
+`;
+
const SPRITE_HIT_FLASH = `#pragma shader "Hit Flash"
#pragma version 300 es
#pragma domain Unlit
@@ -1022,6 +1078,8 @@ fn packNormal(n : vec3f) -> vec2f {
export const BUILTIN_SHADER_TEMPLATES: readonly BuiltinShaderTemplate[] = [
template('sprite-unlit', 'Unlit', 'Texture × vertex color × tint, no lighting.', SPRITE_UNLIT),
template('sprite-lit', 'Lit', 'Lit by the scene\'s 2D lights; optional normal map.', SPRITE_LIT),
+ template('sprite-sway', 'Sway',
+ 'Leans in the wind, foot fixed and tip free: grass, reeds, hanging cloth. Takes the weather wind.', SPRITE_SWAY),
template('sprite-hit-flash', 'Hit Flash',
'Blend toward a flash color; drive u_flash from code for damage blinks.', SPRITE_HIT_FLASH),
template('sprite-outline', 'Outline',
diff --git a/sdk/src/render/coverFade.ts b/sdk/src/render/coverFade.ts
new file mode 100644
index 000000000..14fa12615
--- /dev/null
+++ b/sdk/src/render/coverFade.ts
@@ -0,0 +1,150 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file coverFade.ts
+ * @brief A roof or a tree crown that thins out while something stands under it, so the player is never hidden by the thing they walked into.
+ *
+ * @details Top-down games draw a roof OVER the floor it covers, and the player walking in is then behind it. The usual answer is to fade the roof;
+ * this is that, as two components and no code. `CoverFade` goes on the sprite that covers (its own rectangle, or the ellipse inside it, is
+ * the covered ground); `CoverFadeTarget` goes on whatever should never be hidden. While a target stands inside the covered ground the sprite
+ * eases down to `opacity`, and eases back when it leaves. The sprite's own authored alpha is what it eases from and back to.
+ *
+ * The covered ground is read from the sprite's size, pivot and the entity's scale, not its rotation: a roof is axis-aligned in a top-down
+ * view, and a rotated crown is a circle either way. It runs in play only; in the editor a scene is left as authored.
+ */
+import type { App } from '../app/app';
+import type { Entity } from '../types';
+import { defineComponent, Sprite, Transform, type SpriteData, type TransformData } from '../ecs/component';
+import { defineSystem, Schedule, GetWorld } from '../ecs/system';
+import { Res, Time, type TimeData } from '../ecs/resource';
+import { Query } from '../ecs/query';
+import type { World } from '../ecs/world';
+import { isEditor, isPlayMode } from '../ecs/env';
+
+/** The fields of the `CoverFade` component. @experimental */
+export interface CoverFadeData {
+ /** The sprite's alpha, as a share of its own, while something stands under it. 0 is gone, 1 is no fade. */
+ opacity: number;
+ /** Seconds the fade takes, either way. */
+ fadeTime: number;
+ /** Ground around the sprite's edge, in world units, that counts as under it: the fade starts as a target steps up to the edge, not after it is in. */
+ margin: number;
+ /** The covered ground is the ellipse inside the sprite's rectangle, not the whole rectangle: a tree crown, not a roof. */
+ round: boolean;
+ /** Off: the sprite stays as authored. */
+ enabled: boolean;
+}
+
+/**
+ * Makes the sprite on this entity thin out while a `CoverFadeTarget` stands under it.
+ *
+ * @experimental
+ */
+export const CoverFade = defineComponent<CoverFadeData>('CoverFade',
+ { opacity: 0.25, fadeTime: 0.25, margin: 0, round: false, enabled: true },
+ {
+ fields: {
+ opacity: { min: 0, max: 1, step: 0.01, tooltip: "The sprite's alpha, as a share of its own, while something stands under it." },
+ fadeTime: { min: 0, max: 5, step: 0.05, unit: 's', tooltip: 'Seconds the fade takes, either way.' },
+ margin: { min: 0, step: 1, tooltip: "Ground around the sprite's edge that counts as under it, in world units." },
+ round: { tooltip: "The covered ground is the ellipse inside the sprite's rectangle (a tree crown) and not the whole of it (a roof)." },
+ },
+ },
+);
+
+/** Marks what a `CoverFade` keeps visible: the player, and anything else that must not be hidden. @experimental */
+export const CoverFadeTarget = defineComponent<Record<string, never>>('CoverFadeTarget', {});
+
+/** Whether the point (px, py) is on the ground a sprite covers. */
+export function coversPoint(
+ px: number, py: number,
+ centre: { x: number; y: number }, half: { x: number; y: number },
+ margin: number, round: boolean,
+): boolean {
+ const hx = half.x + margin;
+ const hy = half.y + margin;
+ if (hx <= 0 || hy <= 0) return false;
+ const dx = (px - centre.x) / hx;
+ const dy = (py - centre.y) / hy;
+ return round ? dx * dx + dy * dy <= 1 : Math.abs(dx) <= 1 && Math.abs(dy) <= 1;
+}
+
+/** The share of its alpha a sprite shows after `dt`, moving from `current` toward `goal` in `fadeTime` seconds. */
+export function stepFade(current: number, goal: number, dt: number, fadeTime: number): number {
+ if (fadeTime <= 0) return goal;
+ const step = dt / fadeTime;
+ return goal > current ? Math.min(goal, current + step) : Math.max(goal, current - step);
+}
+
+interface Fading {
+ /** The alpha the sprite was authored with, which the fade is a share of. */
+ authored: number;
+ /** The share shown now, 1 down to the component's `opacity`. */
+ shown: number;
+}
+
+/** Installs the system that does the fading. Returns the function that removes what it changed. */
+export function installCoverFade(app: App): () => void {
+ const fading = new Map<Entity, Fading>();
+
+ const put = (world: World, entity: Entity, alpha: number): void => {
+ const sprite = world.get(entity, Sprite) as SpriteData;
+ if (sprite.color.a === alpha) return;
+ world.set(entity, Sprite, { ...sprite, color: { ...sprite.color, a: alpha } });
+ };
+ const restore = (world: World, entity: Entity, state: Fading): void => {
+ if (world.has(entity, Sprite)) put(world, entity, state.authored);
+ fading.delete(entity);
+ };
+
+ // system-access: the sprite's alpha is read and written through the world, per entity, because the fade owns a share of it.
+ const system = defineSystem(
+ [Query(CoverFade, Sprite, Transform), Query(CoverFadeTarget, Transform), Res(Time), GetWorld()],
+ (
+ covers: Iterable<[Entity, CoverFadeData, SpriteData, TransformData]>,
+ targets: Iterable<[Entity, unknown, TransformData]>,
+ time: TimeData, world: World,
+ ) => {
+ if (isEditor() && !isPlayMode()) {
+ if (fading.size > 0) for (const [entity, state] of [...fading]) restore(world, entity, state);
+ return;
+ }
+ const points: { x: number; y: number }[] = [];
+ for (const [, , transform] of targets) points.push({ x: transform.worldPosition.x, y: transform.worldPosition.y });
+
+ const seen = new Set<Entity>();
+ for (const [entity, cover, sprite, transform] of covers) {
+ seen.add(entity);
+ let state = fading.get(entity);
+ if (!cover.enabled) { if (state) restore(world, entity, state); continue; }
+ if (!state) { state = { authored: sprite.color.a, shown: 1 }; fading.set(entity, state); }
+
+ const scale = transform.worldScale;
+ const half = { x: Math.abs(sprite.size.x * scale.x) / 2, y: Math.abs(sprite.size.y * scale.y) / 2 };
+ // The pivot is where the entity's position sits in the sprite: 0.5 is the middle.
+ const origin = transform.worldPosition;
+ const centre = {
+ x: origin.x + (0.5 - sprite.pivot.x) * half.x * 2,
+ y: origin.y + (0.5 - sprite.pivot.y) * half.y * 2,
+ };
+ let under = false;
+ for (const p of points) {
+ if (coversPoint(p.x, p.y, centre, half, cover.margin, cover.round)) { under = true; break; }
+ }
+ const goal = under ? Math.min(Math.max(cover.opacity, 0), 1) : 1;
+ if (state.shown === goal) continue;
+ state.shown = stepFade(state.shown, goal, time.delta, cover.fadeTime);
+ put(world, entity, state.authored * state.shown);
+ }
+ // What lost its component, or was despawned, goes back to what it was authored as.
+ for (const [entity, state] of [...fading]) if (!seen.has(entity)) restore(world, entity, state);
+ },
+ { name: 'CoverFadeSystem' },
+ );
+ app.addSystemToSchedule(Schedule.PostUpdate, system);
+
+ return () => {
+ const world = app.world;
+ for (const [entity, state] of [...fading]) restore(world, entity, state);
+ };
+}
diff --git a/sdk/src/render/material.ts b/sdk/src/render/material.ts
index d675e4098..c594cafcd 100644
--- a/sdk/src/render/material.ts
+++ b/sdk/src/render/material.ts
@@ -473,6 +473,18 @@ export const Material = {
return handle;
},
+ /**
+ * Every live material whose shader declares `param`: what a value that belongs to the whole scene (the weather's wind) is written to, without
+ * asking each sprite which material it wears.
+ */
+ materialsDeclaring(param: string): MaterialHandle[] {
+ const found: MaterialHandle[] = [];
+ for (const [handle, data] of materials) {
+ if (declaredParams.get(data.shader)?.has(param)) found.push(handle);
+ }
+ return found;
+ },
+
/** Gets an enabled static switch (false when unset). */
getSwitch(material: MaterialHandle, name: string): boolean {
return materials.get(material)?.switches[name] ?? false;
diff --git a/sdk/tests/atmosphere-2d.test.ts b/sdk/tests/atmosphere-2d.test.ts
new file mode 100644
index 000000000..8c0617bcb
--- /dev/null
+++ b/sdk/tests/atmosphere-2d.test.ts
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { coversPoint, stepFade } from '../src/render/coverFade';
+import { applyWeatherToEffects, blendWeather, WeatherDrive, WEATHER_CLEAR, WEATHER_NONE, WEATHER_RAIN } from '../src/postprocess/weather';
+import { getEffectDef } from '../src/postprocess/effects';
+import type { BlendedEffect } from '../src/postprocess/volumeBlending';
+import { BUILTIN_SHADER_TEMPLATES } from '../src/render/builtinShaders';
+import { reflectEsshader } from '../src/render/shaderReflect';
+
+const mist = (uniforms: Record<string, number> = {}): BlendedEffect =>
+ ({ enabled: true, uniforms: new Map(Object.entries(uniforms)), textures: new Map(), colors: new Map() });
+
+describe('the ground a cover fade reads as under it', () => {
+ const centre = { x: 100, y: 50 };
+ const half = { x: 40, y: 20 };
+
+ it('is the whole rectangle for a roof', () => {
+ expect(coversPoint(100, 50, centre, half, 0, false)).toBe(true);
+ expect(coversPoint(139, 69, centre, half, 0, false)).toBe(true);
+ expect(coversPoint(141, 50, centre, half, 0, false)).toBe(false);
+ });
+
+ it('is the ellipse inside it for a crown: a corner of the rectangle is open sky', () => {
+ expect(coversPoint(139, 69, centre, half, 0, true)).toBe(false);
+ expect(coversPoint(130, 50, centre, half, 0, true)).toBe(true);
+ });
+
+ it('reaches a margin past the edge, so the fade starts as a target steps up to it', () => {
+ expect(coversPoint(145, 50, centre, half, 0, false)).toBe(false);
+ expect(coversPoint(145, 50, centre, half, 10, false)).toBe(true);
+ });
+
+ it('covers nothing for a sprite with no size', () => {
+ expect(coversPoint(0, 0, { x: 0, y: 0 }, { x: 0, y: 0 }, 0, false)).toBe(false);
+ });
+});
+
+describe('the fade itself', () => {
+ it('moves toward its goal at one whole fade per fadeTime, and stops on it', () => {
+ expect(stepFade(1, 0.2, 0.1, 0.4)).toBeCloseTo(0.75, 6);
+ expect(stepFade(0.3, 0.2, 1, 0.4)).toBe(0.2);
+ expect(stepFade(0.2, 1, 0.2, 0.4)).toBeCloseTo(0.7, 6);
+ expect(stepFade(0.9, 1, 1, 0.4)).toBe(1);
+ });
+
+ it('is immediate with no fade time', () => {
+ expect(stepFade(1, 0.1, 0.016, 0)).toBe(0.1);
+ });
+});
+
+describe('the 2D mist', () => {
+ it('is an effect that asks for no depth, so a scene that draws none can still have it', () => {
+ const def = getEffectDef('mist2d');
+ expect(def).toBeDefined();
+ expect(def!.category).toBe('atmosphere');
+ expect(def!.uniforms.map((u) => u.name)).toEqual(expect.arrayContaining(['u_density', 'u_coverage', 'u_scale', 'u_speed', 'u_direction', 'u_glow']));
+ });
+
+ it('thickens and spreads under rain, and stays within what an opacity can be', () => {
+ const rain = blendWeather(WEATHER_RAIN, WEATHER_NONE, 0);
+ const effects = new Map([['mist2d', mist({ u_density: 0.4, u_coverage: 0.5 })]]);
+ applyWeatherToEffects(effects, rain, WeatherDrive.Fog);
+ const out = effects.get('mist2d')!;
+ expect(out.uniforms.get('u_density')).toBeGreaterThan(0.4);
+ expect(out.uniforms.get('u_density')).toBeLessThanOrEqual(1);
+ expect(out.uniforms.get('u_coverage')).toBeGreaterThan(0.5);
+ expect(out.uniforms.get('u_coverage')).toBeLessThanOrEqual(1);
+ });
+
+ it('is left as authored under a clear sky and by a weather that does not drive the fog', () => {
+ const clear = blendWeather(WEATHER_CLEAR, WEATHER_NONE, 0);
+ const effects = new Map([['mist2d', mist({ u_density: 0.4, u_coverage: 0.5 })]]);
+ applyWeatherToEffects(effects, clear, WeatherDrive.Fog);
+ expect(effects.get('mist2d')!.uniforms.get('u_density')).toBeCloseTo(0.4, 6);
+ const rain = blendWeather(WEATHER_RAIN, WEATHER_NONE, 0);
+ const untouched = new Map([['mist2d', mist({ u_density: 0.4 })]]);
+ applyWeatherToEffects(untouched, rain, WeatherDrive.Rain);
+ expect(untouched.get('mist2d')!.uniforms.get('u_density')).toBe(0.4);
+ });
+});
+
+describe('the Sway sprite template', () => {
+ const template = BUILTIN_SHADER_TEMPLATES.find((t) => t.id === 'sprite-sway');
+
+ it('is a built-in one, with both backends and the weather\'s wind as a parameter', () => {
+ expect(template).toBeDefined();
+ expect(template!.source).toContain('#pragma fragment wgsl');
+ const names = reflectEsshader(template!.source).params.map((p) => p.name);
+ expect(names).toEqual(expect.arrayContaining(['u_swayStrength', 'u_swaySpeed', 'u_swayScale', 'u_swayWind', 'u_tint', 'u_normalMap']));
+ });
+
+ it('starts with no wind added and a lean that is a share of the sprite', () => {
+ expect(template!.defaults.u_swayWind).toBe(1);
+ expect(template!.defaults.u_swayStrength as number).toBeGreaterThan(0);
+ expect(template!.defaults.u_swayStrength as number).toBeLessThan(0.5);
+ });
+
+ it('holds the foot: the lean grows from nothing at the bottom edge, where the texture coordinate is 0', () => {
+ expect(template!.source).toContain('pow(clamp(v_texCoord.y, 0.0, 1.0), 1.5)');
+ expect(template!.source).toContain('pow(clamp(v.v_texCoord.y, 0.0, 1.0), 1.5)');
+ });
+});
diff --git a/sdk/tests/shader-twins.test.ts b/sdk/tests/shader-twins.test.ts
index f816813ff..f1a8304d3 100644
--- a/sdk/tests/shader-twins.test.ts
+++ b/sdk/tests/shader-twins.test.ts
@@ -53,7 +53,7 @@ describe('embedded .esshader structure', () => {
it('found the filter, effect and grid sources', () => {
expect(CASES.filter((c) => c.name.startsWith('filters.ts')).length).toBe(1);
expect(CASES.filter((c) => c.name.startsWith('spriteFilter.ts')).length).toBe(2);
- expect(CASES.filter((c) => c.name.startsWith('postProcessEffects.ts')).length).toBe(39);
+ expect(CASES.filter((c) => c.name.startsWith('postProcessEffects.ts')).length).toBe(40);
expect(CASES.filter((c) => c.name.startsWith('editorGridRenderer.ts')).length).toBe(1);
});