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): the rain's shelters are painted into a mask, so a scene has as many as it has roofs

yhh51c71a88f822
diff --git a/docs/astro/src/content/docs/graphics/sprites.mdx b/docs/astro/src/content/docs/graphics/sprites.mdx
index 23bf433dd..3f5ad1406 100644
--- a/docs/astro/src/content/docs/graphics/sprites.mdx
+++ b/docs/astro/src/content/docs/graphics/sprites.mdx
@@ -261,7 +261,9 @@ has a room that is dry. So one roof carries both components, and the rain stops
| `round` | The covered ground is the ellipse inside the rectangle (a crown), not the whole rectangle (a roof). |
| `margin` | Ground around the sprite's edge that stays dry too, in world units: eaves. |
-The eight shelters nearest the camera are the ones the rain reads. The rings and the darkening of a wet floor are drawn over everything, characters included, because a
+There is no limit on how many shelters a scene has. Each frame the shelters in view are painted into a small mask over the view (one rectangle each, an ellipse as a few strips),
+and the rain reads one texel of it per pixel; a village of roofs costs what a hut does. The mask is 512 texels across, so a shelter's edge is soft by about the view's size over
+that. The rings and the darkening of a wet floor are drawn over everything, characters included, because a
2D picture has no way to tell a character from the ground under it; they are small and low, which is why it reads as rain on the picture.
### Depth layers (2.5D)
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 26e232e29..d36ffa742 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
@@ -229,7 +229,7 @@ world.applyEntityOrder([other, another, card]);
| `round` | 覆盖范围取矩形内接的椭圆(树冠),而不是整个矩形(屋顶)。 |
| `margin` | 精灵边缘外多少世界单位也保持干燥(屋檐)。 |
-雨只读离相机最近的八个遮雨区。涟漪和湿地的变暗是画在所有东西上面的,包括角色,因为 2D 画面分不出角色和脚下的地面;它们小而低,看起来就是画面上的雨。
+遮雨区的数量没有上限。每一帧,视野里的遮雨区会被画进一张覆盖视野的小遮罩(每个一个矩形,椭圆用几条横带),雨每个像素只读遮罩里的一个纹素,所以一整个村子的屋顶和一间小屋的开销差不多。遮罩宽 512 个纹素,遮雨区的边缘大约有"视野尺寸除以 512"那么软。涟漪和湿地的变暗是画在所有东西上面的,包括角色,因为 2D 画面分不出角色和脚下的地面;它们小而低,看起来就是画面上的雨。
### 深度层(2.5D)
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 21ef3ae68..a33918032 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 115,
"beta": 171,
- "experimental": 2661,
+ "experimental": 2662,
"deprecated": 3
},
- "total": 2947,
+ "total": 2948,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index d4214cf01..a341ee17d 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 · 1917 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1918 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -5620,6 +5620,15 @@ static new (): MaskReach
static prototype: MaskReach
```
+## MaskRect — interface @experimental
+```
+dry: number
+h: number
+w: number
+x: number
+y: number
+```
+
## Material — const @experimental
```
{ 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; }
@@ -14822,6 +14831,11 @@ Logger
(world: World, entity: Entity, style: ThemeStyleData): void
```
+## maskRects — function @experimental
+```
+(shelters: readonly Shelter[], view: { left: number; bottom: number; right: number; top: number; }): MaskRect[]
+```
+
## matchLocale — function @experimental
```
(tag: string, available: readonly string[]): string | null
@@ -14912,11 +14926,6 @@ MeshRendererPlugin
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
```
-## nearestShelters — function @experimental
-```
-(shelters: readonly Shelter[], x: number, y: number, count: number): Shelter[]
-```
-
## newMaterialGraph — function @beta
```
(): MaterialGraph
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 21f29f93e..9de311943 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 · 1936 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1937 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -5628,6 +5628,15 @@ static new (): MaskReach
static prototype: MaskReach
```
+## MaskRect — interface @experimental
+```
+dry: number
+h: number
+w: number
+x: number
+y: number
+```
+
## Material — const @experimental
```
{ 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; }
@@ -15085,6 +15094,11 @@ Logger
(world: World, entity: Entity, style: ThemeStyleData): void
```
+## maskRects — function @experimental
+```
+(shelters: readonly Shelter[], view: { left: number; bottom: number; right: number; top: number; }): MaskRect[]
+```
+
## matchLocale — function @experimental
```
(tag: string, available: readonly string[]): string | null
@@ -15175,11 +15189,6 @@ MeshRendererPlugin
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
```
-## nearestShelters — function @experimental
-```
-(shelters: readonly Shelter[], x: number, y: number, count: number): Shelter[]
-```
-
## newMaterialGraph — function @beta
```
(): MaterialGraph
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index a41c70b4c..3231d059a 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 · 1916 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1917 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5615,6 +5615,15 @@ static new (): MaskReach
static prototype: MaskReach
```
+## MaskRect — interface @experimental
+```
+dry: number
+h: number
+w: number
+x: number
+y: number
+```
+
## Material — const @experimental
```
{ 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; }
@@ -14822,6 +14831,11 @@ Logger
(world: World, entity: Entity, style: ThemeStyleData): void
```
+## maskRects — function @experimental
+```
+(shelters: readonly Shelter[], view: { left: number; bottom: number; right: number; top: number; }): MaskRect[]
+```
+
## matchLocale — function @experimental
```
(tag: string, available: readonly string[]): string | null
@@ -14912,11 +14926,6 @@ MeshRendererPlugin
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
```
-## nearestShelters — function @experimental
-```
-(shelters: readonly Shelter[], x: number, y: number, count: number): Shelter[]
-```
-
## newMaterialGraph — function @beta
```
(): MaterialGraph
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 79a4db814..f5ee44be9 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 · 1938 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1939 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5615,6 +5615,15 @@ static new (): MaskReach
static prototype: MaskReach
```
+## MaskRect — interface @experimental
+```
+dry: number
+h: number
+w: number
+x: number
+y: number
+```
+
## Material — const @experimental
```
{ 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; }
@@ -15132,6 +15141,11 @@ Logger
(world: World, entity: Entity, style: ThemeStyleData): void
```
+## maskRects — function @experimental
+```
+(shelters: readonly Shelter[], view: { left: number; bottom: number; right: number; top: number; }): MaskRect[]
+```
+
## matchLocale — function @experimental
```
(tag: string, available: readonly string[]): string | null
@@ -15222,11 +15236,6 @@ MeshRendererPlugin
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
```
-## nearestShelters — function @experimental
-```
-(shelters: readonly Shelter[], x: number, y: number, count: number): Shelter[]
-```
-
## newMaterialGraph — function @beta
```
(): MaterialGraph
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index cc068c8ee..8e04b07d9 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 · 1929 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1930 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5622,6 +5622,15 @@ static new (): MaskReach
static prototype: MaskReach
```
+## MaskRect — interface @experimental
+```
+dry: number
+h: number
+w: number
+x: number
+y: number
+```
+
## Material — const @experimental
```
{ 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; }
@@ -14859,6 +14868,11 @@ Logger
(world: World, entity: Entity, style: ThemeStyleData): void
```
+## maskRects — function @experimental
+```
+(shelters: readonly Shelter[], view: { left: number; bottom: number; right: number; top: number; }): MaskRect[]
+```
+
## matchLocale — function @experimental
```
(tag: string, available: readonly string[]): string | null
@@ -14949,11 +14963,6 @@ MeshRendererPlugin
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
```
-## nearestShelters — function @experimental
-```
-(shelters: readonly Shelter[], x: number, y: number, count: number): Shelter[]
-```
-
## newMaterialGraph — function @beta
```
(): MaterialGraph
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index d6c781e43..09ef58fd2 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -346,7 +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 { RainShelter, drynessOf, nearestShelters, type RainShelterData, type Shelter } from './render/rainShelter';
+export { RainShelter, drynessOf, maskRects, type RainShelterData, type Shelter, type MaskRect } from './render/rainShelter';
export { CoverFade, CoverFadeTarget, coveredGround, 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';
diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
index bf54ca27d..81bd7d59c 100644
--- a/sdk/src/postprocess/effects.ts
+++ b/sdk/src/postprocess/effects.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { ShaderHandle } from '../render/material';
-import { RAIN_SHELTER_UNIFORMS } from './rainShelterSlots';
+import { RAIN_SHELTER_UNIFORMS, RAIN_SHELTER_MASK_TEXTURE } from './rainShelterMask';
import { effectSourcesOf, computeSourceOf } from './effectSources';
import type { basicEffects } from './sources/basic';
import type { atmosphereEffects } from './sources/atmosphere';
@@ -335,9 +335,12 @@ registerEffect({
{ name: 'u_wind', label: 'Wind', min: -1, max: 1, step: 0.01, defaultValue: 0.15 },
{ name: 'u_speed', label: 'Speed', min: 0.2, max: 6, step: 0.1, defaultValue: 1.6 },
{ name: 'u_streakLength', label: 'Streak Length', min: 0.05, max: 0.9, step: 0.01, defaultValue: 0.3 },
- // The shelters, written each frame by the rain-shelter system from the RainShelter sprites nearest the camera.
+ // Where the mask sits in the world, written each frame by the rain-shelter system with the mask itself.
...RAIN_SHELTER_UNIFORMS,
],
+ textures: [
+ { name: RAIN_SHELTER_MASK_TEXTURE, label: 'Shelter Mask', internal: true },
+ ],
colors: [
{ name: 'u_streakColor', label: 'Streak Colour', defaultValue: { r: 0.78, g: 0.82, b: 0.9, a: 1 } },
],
diff --git a/sdk/src/postprocess/rainShelterMask.ts b/sdk/src/postprocess/rainShelterMask.ts
index 541fe6227..7c9b8909a 100644
--- a/sdk/src/postprocess/rainShelterMask.ts
+++ b/sdk/src/postprocess/rainShelterMask.ts
@@ -1,23 +1,18 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file rainShelterSlots.ts
- * @brief The uniforms the 2D rain reads its shelters from, named apart from its shader so every package can carry the names and only the ones that rain carry the source.
+ * @file rainShelterMask.ts
+ * @brief The names the 2D rain reads its shelter mask by, kept apart from its shader so every package can carry the names and only the ones that rain carry the source.
*/
import type { EffectUniformDef } from './effects';
-/** How many shelters the 2D rain reads. Each is five numbers: centre x and y, half width and height (negative for round), dryness. */
-export const RAIN_SHELTER_SLOTS = 8;
-export const SHELTER_FIELDS = ['x', 'y', 'hx', 'hy', 'dry'] as const;
-export type ShelterField = typeof SHELTER_FIELDS[number];
+/** The sampler the mask is bound to. */
+export const RAIN_SHELTER_MASK_TEXTURE = 'u_shelterMask';
-/** The name of a shelter slot's uniform. */
-export function shelterUniform(slot: number, field: ShelterField): string {
- return `u_sh${slot}${field}`;
-}
+/** How many texels a side the mask is. The view is stretched over it, so a shelter's edge is soft by about the view's size over this. */
+export const RAIN_SHELTER_MASK_SIZE = 512;
-/** The slots as effect uniforms: internal, because the shelter system writes them and nobody authors them. */
-export const RAIN_SHELTER_UNIFORMS: EffectUniformDef[] = Array.from({ length: RAIN_SHELTER_SLOTS }, (_, slot) =>
- SHELTER_FIELDS.map((field): EffectUniformDef => ({
- name: shelterUniform(slot, field), label: `Shelter ${slot} ${field}`, min: -100000, max: 100000, step: 1, defaultValue: 0, internal: true,
- }))).flat();
+/** The world rectangle the mask covers: its low corner and its size. Written with the mask each frame, so nobody authors them. */
+export const RAIN_SHELTER_UNIFORMS: EffectUniformDef[] = ['L', 'B', 'W', 'H'].map((edge): EffectUniformDef => ({
+ name: `u_mask${edge}`, label: `Shelter Mask ${edge}`, min: -1e9, max: 1e9, step: 1, defaultValue: 0, internal: true,
+}));
diff --git a/sdk/src/postprocess/runtimeTextures.ts b/sdk/src/postprocess/runtimeTextures.ts
new file mode 100644
index 000000000..3e59f227d
--- /dev/null
+++ b/sdk/src/postprocess/runtimeTextures.ts
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file runtimeTextures.ts
+ * @brief A texture an effect reads that no asset names: one the engine draws each frame and hands to the effect by a ref that carries its handle.
+ * @details An effect's textures are refs that resolve through the Assets, which a texture drawn at run time is not in. The ref says where to look
+ * instead: `@runtime:<name>#<handle>`. The handle is in the ref, so a texture made again after a lost device is a new ref and the stack rebinds.
+ */
+
+const PREFIX = '@runtime:';
+
+/** The ref that names a runtime texture. */
+export function runtimeTextureRef(name: string, handle: number): string {
+ return `${PREFIX}${name}#${handle}`;
+}
+
+/** The resource handle a runtime ref names, or null for a ref that is an asset's. */
+export function runtimeTextureHandle(ref: string): number | null {
+ if (!ref.startsWith(PREFIX)) return null;
+ const handle = Number(ref.slice(ref.lastIndexOf('#') + 1));
+ return Number.isFinite(handle) && handle > 0 ? handle : null;
+}
diff --git a/sdk/src/postprocess/sources/rain2d.ts b/sdk/src/postprocess/sources/rain2d.ts
index 0ba8e7d66..e2f892100 100644
--- a/sdk/src/postprocess/sources/rain2d.ts
+++ b/sdk/src/postprocess/sources/rain2d.ts
@@ -6,9 +6,10 @@
*
* @details The 3D rain finds the ground by its depth and its shelter by a map of the scene seen from above. A 2D scene has neither: its sprites
* are blended and write no depth, and there is no "above" to look from. This rain lays its rings and puddles on the ground plane in
- * WORLD units (found from the screen as the 2D mist finds them) and asks the shelters it is told of where it is dry: up to eight boxes
- * or ellipses, the ones nearest the camera, written each frame by the rain-shelter system. A shelter's dryness is how much of the ground
- * under it can be seen, so an opaque roof (which shows the roof, and the rain falls on that) is not dry, and one faded to show the room is.
+ * WORLD units (found from the screen as the 2D mist finds them) and reads where it is dry from a mask: a small texture the rain-shelter
+ * system paints each frame over the view, a shelter's dryness in its alpha, however many shelters there are. A shelter's dryness is how
+ * much of the ground under it can be seen, so an opaque roof (which shows the roof, and the rain falls on that) is not dry, and one faded
+ * to show the room is.
*
* It cannot tell a character from the ground it stands on, so rings and the darkening of a wet floor are drawn over everything. They are
* small and low, which is why that reads as rain on the picture and not as a fault.
@@ -16,12 +17,6 @@
import type { ShaderHandle } from '../../render/material';
import { Material } from '../../render/material';
-import { RAIN_SHELTER_SLOTS, SHELTER_FIELDS, shelterUniform } from '../rainShelterSlots';
-
-const slots = Array.from({ length: RAIN_SHELTER_SLOTS }, (_, i) => i);
-const PARAMS = slots.flatMap((i) => SHELTER_FIELDS.map((f) => `#pragma param ${shelterUniform(i, f)} float default(0) range(-100000,100000)`)).join('\n');
-const callGlsl = (i: number) => ` d = max(d, shelterOf(w, ${shelterUniform(i, 'x')}, ${shelterUniform(i, 'y')}, ${shelterUniform(i, 'hx')}, ${shelterUniform(i, 'hy')}, ${shelterUniform(i, 'dry')}));`;
-const callWgsl = (i: number) => ` d = max(d, shelterOf(w, mc.${shelterUniform(i, 'x')}, mc.${shelterUniform(i, 'y')}, mc.${shelterUniform(i, 'hx')}, mc.${shelterUniform(i, 'hy')}, mc.${shelterUniform(i, 'dry')}));`;
const GLSL = `
float hash11(float n) { return fract(sin(n * 127.1) * 43758.5453); }
@@ -35,17 +30,12 @@ float vnoise(vec2 p) {
float puddleNoise(vec2 p) {
return vnoise(p) * 0.5 + vnoise(p * 2.07 + vec2(11.0, 5.0)) * 0.3 + vnoise(p * 4.3 + vec2(3.0, 17.0)) * 0.2;
}
-/// How dry a point of the ground is under one shelter: 0 outside it, its dryness inside, soft at the edge. A negative half-height says round.
-float shelterOf(vec2 w, float cx, float cy, float hx, float hy, float dry) {
- if (hx <= 0.0) return 0.0;
- float h = abs(hy);
- float m = hy < 0.0 ? (1.0 - length((w - vec2(cx, cy)) / vec2(hx, h))) * min(hx, h) : min(hx - abs(w.x - cx), h - abs(w.y - cy));
- return smoothstep(0.0, 8.0, m) * dry;
-}
+/// How dry the ground is at a point: the alpha of the shelter mask, which covers the view from (u_maskL, u_maskB) by (u_maskW, u_maskH) world units.
float dryAt(vec2 w) {
- float d = 0.0;
-${slots.map(callGlsl).join('\n')}
- return d;
+ if (u_maskW <= 0.0 || u_maskH <= 0.0) return 0.0;
+ vec2 uv = (w - vec2(u_maskL, u_maskB)) / vec2(u_maskW, u_maskH);
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return 0.0;
+ return textureLod(u_shelterMask, uv, 0.0).a;
}
/// One layer of streaks: columns across the screen, one streak per cell at most, scrolling down.
float streaks(vec2 uv, float aspect, float cols, float speed, float seed, float T) {
@@ -77,17 +67,12 @@ fn vnoise(p : vec2f) -> f32 {
fn puddleNoise(p : vec2f) -> f32 {
return vnoise(p) * 0.5 + vnoise(p * 2.07 + vec2f(11.0, 5.0)) * 0.3 + vnoise(p * 4.3 + vec2f(3.0, 17.0)) * 0.2;
}
-fn shelterOf(w : vec2f, cx : f32, cy : f32, hx : f32, hy : f32, dry : f32) -> f32 {
- if (hx <= 0.0) { return 0.0; }
- let h = abs(hy);
- var m = min(hx - abs(w.x - cx), h - abs(w.y - cy));
- if (hy < 0.0) { m = (1.0 - length((w - vec2f(cx, cy)) / vec2f(hx, h))) * min(hx, h); }
- return smoothstep(0.0, 8.0, m) * dry;
-}
fn dryAt(w : vec2f) -> f32 {
- var d = 0.0;
-${slots.map(callWgsl).join('\n')}
- return d;
+ if (mc.u_maskW <= 0.0 || mc.u_maskH <= 0.0) { return 0.0; }
+ let uv = (w - vec2f(mc.u_maskL, mc.u_maskB)) / vec2f(mc.u_maskW, mc.u_maskH);
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { return 0.0; }
+ // This device's texture rows run the other way from the clip space the mask was drawn in.
+ return textureSampleLevel(u_shelterMask, u_shelterMask_s, vec2f(uv.x, 1.0 - uv.y), 0.0).a;
}
fn streaks(uv : vec2f, aspect : f32, cols : f32, speed : f32, seed : f32, T : f32) -> f32 {
let q = vec2f(uv.x * aspect - (1.0 - uv.y) * mc.u_wind, 1.0 - uv.y);
@@ -119,7 +104,11 @@ const SOURCE = `#pragma shader "PP Rain 2D"
#pragma param u_speed float default(1.6) range(0.2,6)
#pragma param u_streakLength float default(0.3) range(0.05,0.9)
#pragma param u_streakColor color default(0.78,0.82,0.9,1)
-${PARAMS}
+#pragma param u_maskL float default(0) range(-1000000000,1000000000)
+#pragma param u_maskB float default(0) range(-1000000000,1000000000)
+#pragma param u_maskW float default(0) range(0,1000000000)
+#pragma param u_maskH float default(0) range(0,1000000000)
+#pragma param u_shelterMask texture default(black)
#pragma fragment
precision highp float;
diff --git a/sdk/src/postprocess/volumeSystem.ts b/sdk/src/postprocess/volumeSystem.ts
index 3c128a2ff..09d3168bb 100644
--- a/sdk/src/postprocess/volumeSystem.ts
+++ b/sdk/src/postprocess/volumeSystem.ts
@@ -16,6 +16,7 @@ import { Material } from '../render/material';
import { applyWeatherToEffects, currentWeather, currentWeatherDrive } from './weather';
import { applyCloudsToFog } from './cloudShafts';
import { applyRainSheltersToRain } from '../render/rainShelter';
+import { runtimeTextureHandle } from './runtimeTextures';
import { applyUnderwaterToEffects, currentUnderwater } from './underwater';
import { applyTimeToEffects, currentTimeOfDay, currentTimeDrive, timeLightsApplied } from './timeOfDay';
@@ -52,7 +53,7 @@ function applyTextures(
): void {
if (textures.size === 0 || !volumeTextureResolver) return;
for (const [uniformName, ref] of textures) {
- const handle = volumeTextureResolver(ref);
+ const handle = runtimeTextureHandle(ref) ?? volumeTextureResolver(ref);
if (handle) stack.setTexture(passName, uniformName, handle);
}
}
@@ -304,8 +305,8 @@ export function effectsAt(volumes: { data: PostProcessVolumeData; tx: VolumeTran
const clock = currentTimeOfDay();
if (clock) applyTimeToEffects(blended, clock, currentTimeDrive(), timeLightsApplied());
applyCloudsToFog(blended);
- // A 2D rain is told where the ground under a roof is dry.
- applyRainSheltersToRain(blended, x, y);
+ // A 2D rain is told where the ground under a roof is dry, by a mask drawn this frame.
+ applyRainSheltersToRain(blended);
// A camera under water: the effect the water module says it needs.
applyUnderwaterToEffects(blended, currentUnderwater());
return blended;
diff --git a/sdk/src/render/rainShelter.ts b/sdk/src/render/rainShelter.ts
index 21504c78b..9268f952a 100644
--- a/sdk/src/render/rainShelter.ts
+++ b/sdk/src/render/rainShelter.ts
@@ -9,15 +9,24 @@
* follows how much of that ground can be SEEN: an opaque roof shows the roof, which the rain falls on, and the same roof faded by a
* `CoverFade` to show the room has a room that is dry. So one roof carries both components and the rain stops as the room appears.
*
- * The system lists the shelters each frame; the volume system hands the eight nearest the camera to a `rain2d` effect's uniforms.
+ * Every frame the shelters are painted into a small texture that covers the view, each one's dryness in its alpha, and a `rain2d` effect
+ * reads that. A shelter costs a rectangle or a few strips of one draw, not a test in the shader on every pixel, so a village of roofs
+ * costs what a hut does.
*/
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 } from '../ecs/system';
import { Query } from '../ecs/query';
+import { CameraView } from '../camera/Camera';
import { coveredGround } from './coverFade';
-import { RAIN_SHELTER_SLOTS, SHELTER_FIELDS, shelterUniform } from '../postprocess/rainShelterSlots';
+import { Draw } from './draw';
+import { BlendMode } from './blend';
+import { Renderer } from './renderer';
+import { RenderTexture, type RenderTextureHandle } from './renderTexture';
+import { log } from '../util/logger';
+import { RAIN_SHELTER_MASK_SIZE, RAIN_SHELTER_MASK_TEXTURE } from '../postprocess/rainShelterMask';
+import { runtimeTextureRef } from '../postprocess/runtimeTextures';
import type { BlendedEffect } from '../postprocess/volumeBlending';
/** The fields of the `RainShelter` component. @experimental */
@@ -45,7 +54,7 @@ export const RainShelter = defineComponent<RainShelterData>('RainShelter',
},
);
-/** One shelter as the shader reads it: a negative half height says round. */
+/** One shelter: its ground and how dry it is. A negative half height says round. */
export interface Shelter {
x: number;
y: number;
@@ -56,6 +65,15 @@ export interface Shelter {
dry: number;
}
+/** A filled rectangle of the mask, centred, in world units. */
+export interface MaskRect {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ dry: number;
+}
+
let sheltersNow: Shelter[] = [];
/** The shelters the last frame found. */
@@ -80,33 +98,120 @@ export function shelterOf(sprite: SpriteData, transform: TransformData, data: Ra
return { x: centre.x, y: centre.y, hx, hy: data.round ? -hy : hy, dry };
}
-/** The `count` shelters nearest (x, y), nearest first. The distance is to a shelter's edge, so a large roof is not passed over for a small shed. */
-export function nearestShelters(shelters: readonly Shelter[], x: number, y: number, count: number): Shelter[] {
- const reach = (s: Shelter): number => Math.max(Math.hypot(s.x - x, s.y - y) - Math.max(s.hx, Math.abs(s.hy)), 0);
- return [...shelters].sort((a, b) => reach(a) - reach(b)).slice(0, count);
-}
+/** How many strips an ellipse is cut into: the mask is a few hundred texels across, so more would draw what it cannot show. */
+export const ELLIPSE_STRIPS = 32;
/**
- * Writes the shelters nearest the camera into a `rain2d` effect, and empties the slots it does not fill. With no such effect, nothing.
+ * What to draw for the shelters: a rectangle each, an ellipse as strips of one, the driest last so where two overlap the drier wins (a draw
+ * overwrites, and a max is what overlapping shelters want). The mask is not drawn for shelters the view cannot see.
*
- * @param x The camera's x.
- * @param y The camera's y.
+ * @param view The world rectangle the mask covers.
+ */
+export function maskRects(shelters: readonly Shelter[], view: { left: number; bottom: number; right: number; top: number }): MaskRect[] {
+ const rects: MaskRect[] = [];
+ const ordered = [...shelters].sort((a, b) => a.dry - b.dry);
+ for (const s of ordered) {
+ const h = Math.abs(s.hy);
+ if (s.x + s.hx < view.left || s.x - s.hx > view.right || s.y + h < view.bottom || s.y - h > view.top) continue;
+ if (s.hy >= 0) {
+ rects.push({ x: s.x, y: s.y, w: s.hx * 2, h: h * 2, dry: s.dry });
+ continue;
+ }
+ const strip = (h * 2) / ELLIPSE_STRIPS;
+ for (let i = 0; i < ELLIPSE_STRIPS; i++) {
+ const t = ((i + 0.5) / ELLIPSE_STRIPS) * 2 - 1;
+ const width = s.hx * 2 * Math.sqrt(Math.max(1 - t * t, 0));
+ if (width <= 0) continue;
+ rects.push({ x: s.x, y: s.y + t * h, w: width, h: strip, dry: s.dry });
+ }
+ }
+ return rects;
+}
+
+/** The mask as the last frame painted it: the texture the effect reads and the world rectangle it covers. */
+interface MaskState {
+ ref: string;
+ left: number;
+ bottom: number;
+ width: number;
+ height: number;
+}
+
+let maskNow: MaskState | null = null;
+
+/** Column-major orthographic projection over a rectangle: what RenderTexture.begin wants. */
+function ortho(l: number, r: number, b: number, t: number): Float32Array {
+ const m = new Float32Array(16);
+ m[0] = 2 / (r - l);
+ m[5] = 2 / (t - b);
+ m[10] = -1;
+ m[12] = -(r + l) / (r - l);
+ m[13] = -(t + b) / (t - b);
+ m[15] = 1;
+ return m;
+}
+
+/**
+ * Hands a `rain2d` effect the mask painted this frame and where it lies in the world; with no mask (no shelters, no view) the effect
+ * keeps its black default, which is dry nowhere. Other effects, and a disabled rain, are left alone.
*/
-export function applyRainSheltersToRain(effects: Map<string, BlendedEffect>, x: number, y: number): void {
+export function applyRainSheltersToRain(effects: Map<string, BlendedEffect>): void {
const rain = effects.get('rain2d');
if (!rain || !rain.enabled) return;
- const chosen = nearestShelters(sheltersNow, x, y, RAIN_SHELTER_SLOTS);
- for (let slot = 0; slot < RAIN_SHELTER_SLOTS; slot++) {
- const s = chosen[slot];
- const values: Record<typeof SHELTER_FIELDS[number], number> = s
- ? { x: s.x, y: s.y, hx: s.hx, hy: s.hy, dry: s.dry }
- : { x: 0, y: 0, hx: 0, hy: 0, dry: 0 };
- for (const field of SHELTER_FIELDS) rain.uniforms.set(shelterUniform(slot, field), values[field]);
- }
+ const mask = maskNow;
+ rain.uniforms.set('u_maskL', mask ? mask.left : 0);
+ rain.uniforms.set('u_maskB', mask ? mask.bottom : 0);
+ rain.uniforms.set('u_maskW', mask ? mask.width : 0);
+ rain.uniforms.set('u_maskH', mask ? mask.height : 0);
+ if (mask) rain.textures.set(RAIN_SHELTER_MASK_TEXTURE, mask.ref);
}
-/** Installs the system that lists the shelters each frame. Returns the function that forgets them. */
+/** Installs the system that lists the shelters and paints the mask each frame. Returns the function that lets both go. */
export function installRainShelter(app: App): () => void {
+ let target: RenderTextureHandle | null = null;
+ let failed = false;
+
+ /** The world rectangle the camera shows, or null where there is none to cover. */
+ const viewOf = (): { left: number; right: number; bottom: number; top: number } | null => {
+ const view = app.hasResource(CameraView) ? app.getResource(CameraView).getWorldBounds() : null;
+ return view && view.right > view.left && view.top > view.bottom ? view : null;
+ };
+
+ const paint = (rects: readonly MaskRect[], view: { left: number; right: number; bottom: number; top: number }): boolean => {
+ if (failed) return false;
+ try {
+ if (!target) {
+ const created = RenderTexture.create({ width: RAIN_SHELTER_MASK_SIZE, height: RAIN_SHELTER_MASK_SIZE, depth: false, filter: 'linear' });
+ // The renderer may not be up yet: try again next frame.
+ if (created.textureId === 0 || created.texture === 0) { RenderTexture.release(created); return false; }
+ target = created;
+ }
+ const vp = ortho(view.left, view.right, view.bottom, view.top);
+ const cx = (view.left + view.right) / 2;
+ const cy = (view.bottom + view.top) / 2;
+ RenderTexture.begin(target, vp);
+ Draw.begin(vp);
+ // Draw.begin resets the viewport to the screen's; the target's own is what this pass is.
+ Renderer.setViewport(0, 0, target.width, target.height);
+ // Blend off, so a draw writes its colour AND its alpha as given, and the dryness in the alpha is exact whatever the colour space does to the colour.
+ Draw.setBlendMode(BlendMode.None);
+ Draw.rect({ x: cx, y: cy }, { x: view.right - view.left, y: view.top - view.bottom }, { r: 0, g: 0, b: 0, a: 0 });
+ for (const r of rects) Draw.rect({ x: r.x, y: r.y }, { x: r.w, y: r.h }, { r: 0, g: 0, b: 0, a: r.dry });
+ Draw.end();
+ RenderTexture.end();
+ RenderTexture.contentDrawn(target);
+ maskNow = {
+ ref: runtimeTextureRef(RAIN_SHELTER_MASK_TEXTURE, target.texture),
+ left: view.left, bottom: view.bottom, width: view.right - view.left, height: view.top - view.bottom,
+ };
+ return true;
+ } catch (error) {
+ failed = true;
+ log.warn('rain', `the rain shelter mask cannot be painted on this device: ${String(error)}`);
+ return false;
+ }
+ };
+
const system = defineSystem(
[Query(RainShelter, Sprite, Transform)],
(shelters: Iterable<[Entity, RainShelterData, SpriteData, TransformData]>) => {
@@ -116,10 +221,20 @@ export function installRainShelter(app: App): () => void {
if (shelter) found.push(shelter);
}
sheltersNow = found;
+ maskNow = null;
+ if (found.length === 0) return;
+ const view = viewOf();
+ if (view) paint(maskRects(found, view), view);
},
{ name: 'RainShelterSystem' },
);
- // After the cover fade has moved the sprites' alpha, so the rain stops the frame the roof thins and not the one after.
+ // After the cover fade has moved the sprites' alpha (it is installed first), and before the frame is drawn.
app.addSystemToSchedule(Schedule.PostUpdate, system);
- return () => { sheltersNow = []; };
+
+ return () => {
+ sheltersNow = [];
+ maskNow = null;
+ if (target) RenderTexture.release(target);
+ target = null;
+ };
}
diff --git a/sdk/tests/atmosphere-2d.test.ts b/sdk/tests/atmosphere-2d.test.ts
index 011edf7ba..d8cf3c2e0 100644
--- a/sdk/tests/atmosphere-2d.test.ts
+++ b/sdk/tests/atmosphere-2d.test.ts
@@ -2,8 +2,9 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, expect, it } from 'vitest';
import { coversPoint, stepFade } from '../src/render/coverFade';
-import { applyRainSheltersToRain, drynessOf, nearestShelters, shelterOf, type Shelter } from '../src/render/rainShelter';
-import { RAIN_SHELTER_SLOTS, shelterUniform } from '../src/postprocess/rainShelterSlots';
+import { applyRainSheltersToRain, drynessOf, maskRects, shelterOf, ELLIPSE_STRIPS, type Shelter } from '../src/render/rainShelter';
+import { RAIN_SHELTER_MASK_TEXTURE } from '../src/postprocess/rainShelterMask';
+import { runtimeTextureHandle, runtimeTextureRef } from '../src/postprocess/runtimeTextures';
import { Light } from '../src/ecs/component';
import type { SpriteData, TransformData } from '../src/ecs/component';
import { applyWeatherToEffects, blendWeather, WeatherDrive, WEATHER_CLEAR, WEATHER_NONE, WEATHER_RAIN } from '../src/postprocess/weather';
@@ -113,12 +114,12 @@ describe('the 2D rain', () => {
({ worldPosition: { x, y, z: 0 }, worldScale: { x: 1, y: 1, z: 1 } }) as TransformData;
const data = { round: false, margin: 0, enabled: true };
- it('is an effect that asks for no depth and for no shelter map, with every shelter slot internal', () => {
+ it('is an effect that asks for no depth, whose shelter mask and the rectangle it covers are written by the engine', () => {
const def = getEffectDef('rain2d');
expect(def).toBeDefined();
expect(def!.category).toBe('atmosphere');
- const slots = def!.uniforms.filter((u) => u.internal);
- expect(slots).toHaveLength(RAIN_SHELTER_SLOTS * 5);
+ expect(def!.uniforms.filter((u) => u.internal).map((u) => u.name)).toEqual(['u_maskL', 'u_maskB', 'u_maskW', 'u_maskH']);
+ expect(def!.textures).toEqual([{ name: RAIN_SHELTER_MASK_TEXTURE, label: 'Shelter Mask', internal: true }]);
expect(def!.uniforms.map((u) => u.name)).toEqual(expect.arrayContaining(['u_intensity', 'u_wetness', 'u_puddles', 'u_puddleScale', 'u_rippleScale']));
});
@@ -152,26 +153,60 @@ describe('the 2D rain', () => {
expect(s.y).toBeCloseTo(30, 6);
});
- it('hands the shader the shelters nearest the camera, by their edge, so a big roof is not passed over for a small shed', () => {
- const roof: Shelter = { x: 300, y: 0, hx: 250, hy: 250, dry: 1 };
- const shed: Shelter = { x: 120, y: 0, hx: 10, hy: 10, dry: 1 };
- const far: Shelter = { x: 900, y: 0, hx: 10, hy: 10, dry: 1 };
- expect(nearestShelters([far, shed, roof], 0, 0, 2)).toEqual([roof, shed]);
+ const view = { left: -500, bottom: -500, right: 500, top: 500 };
+
+ it('draws a box shelter as one rectangle of its own size', () => {
+ expect(maskRects([{ x: 10, y: 20, hx: 50, hy: 30, dry: 0.7 }], view)).toEqual([{ x: 10, y: 20, w: 100, h: 60, dry: 0.7 }]);
+ });
+
+ it('draws a round shelter as strips whose widths follow the ellipse and whose heights fill it', () => {
+ const rects = maskRects([{ x: 0, y: 0, hx: 100, hy: -50, dry: 1 }], view);
+ expect(rects).toHaveLength(ELLIPSE_STRIPS);
+ expect(rects.reduce((sum, r) => sum + r.h, 0)).toBeCloseTo(100, 6);
+ const widest = Math.max(...rects.map((r) => r.w));
+ expect(widest).toBeGreaterThan(190);
+ expect(widest).toBeLessThanOrEqual(200);
+ expect(Math.min(...rects.map((r) => r.w))).toBeLessThan(80);
+ const area = rects.reduce((sum, r) => sum + r.w * r.h, 0);
+ expect(area).toBeGreaterThan(Math.PI * 100 * 50 * 0.97);
+ expect(area).toBeLessThan(Math.PI * 100 * 50 * 1.03);
+ });
+
+ it('draws the driest last, so where two shelters overlap the drier wins', () => {
+ const rects = maskRects([{ x: 0, y: 0, hx: 10, hy: 10, dry: 0.9 }, { x: 0, y: 0, hx: 40, hy: 40, dry: 0.2 }], view);
+ expect(rects.map((r) => r.dry)).toEqual([0.2, 0.9]);
});
- it('writes the slots of a rain2d effect and leaves other effects and a disabled rain alone', () => {
+ it('leaves out a shelter the view cannot see, and keeps every one it can: there is no count to run out of', () => {
+ const many: Shelter[] = Array.from({ length: 200 }, (_, i) => ({ x: (i % 20) * 40 - 400, y: Math.floor(i / 20) * 40 - 200, hx: 15, hy: 15, dry: 0.5 }));
+ expect(maskRects(many, view)).toHaveLength(200);
+ const away: Shelter[] = [{ x: 5000, y: 0, hx: 10, hy: 10, dry: 1 }, { x: 0, y: -5000, hx: 10, hy: 10, dry: 1 }];
+ expect(maskRects(away, view)).toEqual([]);
+ expect(maskRects([{ x: 540, y: 0, hx: 50, hy: 10, dry: 1 }], view)).toHaveLength(1);
+ });
+
+ it('tells a rain2d effect where the mask lies and which texture it is, and leaves other effects and a disabled rain alone', () => {
const effects = new Map([['rain2d', mist()]]);
- applyRainSheltersToRain(effects, 0, 0);
+ applyRainSheltersToRain(effects);
const rain = effects.get('rain2d')!;
- for (let slot = 0; slot < RAIN_SHELTER_SLOTS; slot++) expect(rain.uniforms.get(shelterUniform(slot, 'hx'))).toBe(0);
+ for (const name of ['u_maskL', 'u_maskB', 'u_maskW', 'u_maskH']) expect(rain.uniforms.get(name)).toBe(0);
+ expect(rain.textures.size).toBe(0);
const none = new Map([['mist2d', mist()]]);
- applyRainSheltersToRain(none, 0, 0);
+ applyRainSheltersToRain(none);
expect(none.get('mist2d')!.uniforms.size).toBe(0);
const off = new Map([['rain2d', { ...mist(), enabled: false }]]);
- applyRainSheltersToRain(off, 0, 0);
+ applyRainSheltersToRain(off);
expect(off.get('rain2d')!.uniforms.size).toBe(0);
});
+ it('names its mask by a ref that carries the handle, so a texture made again is a new ref', () => {
+ const ref = runtimeTextureRef(RAIN_SHELTER_MASK_TEXTURE, 42);
+ expect(runtimeTextureHandle(ref)).toBe(42);
+ expect(runtimeTextureRef(RAIN_SHELTER_MASK_TEXTURE, 43)).not.toBe(ref);
+ expect(runtimeTextureHandle('assets/textures/rain.png')).toBeNull();
+ expect(runtimeTextureHandle('@runtime:rain-shelter-mask#0')).toBeNull();
+ });
+
it('is the rain a weather raises, and brings no second rain beside it', () => {
const rain = blendWeather(WEATHER_RAIN, WEATHER_NONE, 0);
const effects = new Map([['rain2d', mist({ u_intensity: 0.1, u_wetness: 0.1 })]]);