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(runtime): rain stays off what is under a roof, and the weather turns a rain track up and down

yhh78e3f0de77f0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ebef6d8af..a0ec2f423 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,7 @@ published separately; it ships inside the editor.
### Added
-- **Weather.** A Weather component puts a scene under clear, mist, overcast, rain or storm, turns between them and cycles by itself. A preset is a set of multipliers of what the scene already has — the sun at a fraction of its strength, the fog thicker, the picture greyer — plus absolute levels for rain and wetness, so one preset fits any project. The component drives the directional and ambient lights (in play mode only), the effects the scene's volumes resolve (Height Fog, Rain, Screen Space Reflections, Colour Grade, Auto Exposure), and takes `registerWeatherPreset` for weathers of a project's own. Volumes whose effects differ only in numbers now write the numbers into the passes they have instead of rebuilding them. Reflection probes follow the weather: the ambient light scales what baked probes show and how much colour they keep. The Ambient `Light` gains `reflectionScale` and `reflectionSaturation`, which the weather drives.
+- **Weather.** A Weather component puts a scene under clear, mist, overcast, rain or storm, turns between them and cycles by itself. A preset is a set of multipliers of what the scene already has — the sun at a fraction of its strength, the fog thicker, the picture greyer — plus absolute levels for rain and wetness, so one preset fits any project. The component drives the directional and ambient lights (in play mode only), the effects the scene's volumes resolve (Height Fog, Rain, Screen Space Reflections, Colour Grade, Auto Exposure), and takes `registerWeatherPreset` for weathers of a project's own. Volumes whose effects differ only in numbers now write the numbers into the passes they have instead of rebuilding them. Reflection probes follow the weather: the ambient light scales what baked probes show and how much colour they keep. The Ambient `Light` gains `reflectionScale` and `reflectionSaturation`, which the weather drives. Rain stays off what stands under a roof, and the Weather component turns a looping rain track up and down. The frame draws the scene once from straight above, depth only, around the camera whenever a `rain` effect is in the chain, and the effect keeps wetness, puddles, ripples and streaks off ground that something stands over; `soundSource` names the `AudioSource` the weather drives.
- **Quality levels are edited in Settings.** Settings → Project → Rendering edits each quality level, including which effects it runs. **Editing level** picks Low, Medium or High and the groups below — Rendering (render scale, minimum scale, MSAA), Shadows, Reflections and particles, Post-processing — show and change that level, so a level is read the way Unity's Quality page reads: a level, then its settings by subsystem. Post-processing lists every effect the engine has, ticked where the level runs it; an unticked one is skipped at that level wherever a camera's volume asks for it, with all of its passes. Device rules — the model, GPU, memory and core conditions Auto chooses a level by — are a table, shown when the mode is Auto, that says so on a row with no condition instead of dropping it while it is typed. Only what you change is saved to `project.esproject`, as a difference to that level, so an engine default that improves later still reaches a project that never touched it; a row's "changed" mark and reset follow the default of the level it is showing. The old per-level shadow distance rows are the Shadows group's Distance now. The effects a level leaves out had been matched by the prefix of a pass's name, which found none of Auto Exposure's passes; they are now matched by effect type. A new Quality Levels page in the performance docs describes it.
- **A G-buffer, and reflections that read it.** Reflections now know how rough and how metal each surface is, from a G-buffer the frame draws on request. A post-process shader that says `#pragma gbuffer` makes the scene target carry a second RGBA8 colour attachment, written in the same pass by the scene's own shaders — octahedral normal in `r`/`g`, roughness in `b`, metalness in `a` (0 where nothing wrote) — and finds it at `u_gbuffer`. A frame whose chain has no such effect makes none and compiles no variant. The render device grew multiple colour attachments for it on both backends: WebGL2 attaches and resolves a second target and sets the draw buffers per pipeline, and WebGPU declares the second target on every pipeline of the pass (written by the ones that write it, an empty write mask for the rest), clears it to zero and resolves it with the colour. Pipelines say whether they write it (`PipelineDesc::gbuffer`), a blended draw never does, and the second output is its own shader variant (`ES_GBUFFER`), so no pass pays for what it did not ask for. The built-in Model shader — what an imported glTF material becomes — writes it from the material's roughness, metalness and normal map. `ssr` reads it: it takes the surface's own normal (normal-map detail that depth cannot see), weighs and blurs the reflection by roughness, reflects a metal at nearly full strength where a dielectric reflects 4%, skips a surface rougher than `maxRoughness` before marching the ray, and takes the Rain effect's `wetness` as a film that smooths the ground. Where nothing wrote a record, it falls back to depth and the dielectric it has always assumed. Verified in the editor on both backends: of two floors that differ only in their material's roughness, the glossy one changes ten times the pixels the rough one does. Quality levels can also leave out expensive effects now: quality levels can now skip expensive post-process effects by name. A level's `skipEffects` lists the effects it leaves out, each named by its effect type (`ssr`, `taa`, `depthOfField`, `lightShafts`, `autoExposure`, …), and an effect leaves with all of its passes however they are named; a project's own list in its quality profile replaces the level's. By default low leaves out reflections, temporal anti-aliasing, depth of field and light shafts, and medium leaves out reflections and depth of field; high leaves out nothing. These defaults come from the work each effect does per pixel, not from a weak device: the editor's new `fx-cost` check measured every effect on Bistro at 2560×1600 on a fast desktop GPU, and none added more than about 6 ms (reflections ~5, bloom ~4, the example's whole eight-effect chain ~11, the rest within the ±3 ms the run drifts by), so the levels have not been checked against the hardware they are for. Screen-space reflections leave a surface that recorded nothing alone, plain meshes now record a rough dielectric, and a puddle reflects the sky and what lies off screen.
- **Rain, wet ground and puddles.** A Rain post-process effect adds falling rain, wet ground, puddles and ripples. `rain` draws three layers of slanted streaks, each at its own distance so a nearer surface hides them and the sky does not; darkens the ground that faces up by `wetness`; lays ripples and splashes where drops land on a grid in the world, so they stay on the ground as the camera moves (ripples need `intensity` above 0: wet ground under no rain is still); and, by `puddles` and `puddleScale`, covers part of the flat ground with standing water that is darker and takes denser, clearer ripples. `ssr` takes the same two numbers and treats those pools as mirrors — flat, far more reflective than dry ground, and sharp — so the pools the rain darkens are the pools that reflect. The clock is `u_time * timeScale + phase`, so a capture can pin it. The rain is a screen-space layer, not particles that collide with the world, and a puddle is flat ground whatever it lies on. Verified in the editor on both backends: streaks light a dark sky and move between two moments, wet ground reads darker, standing water darker still, and puddles change the reflection. Puddles gather in the low places of the ground and thin on its rises, read from the depth buffer. Three rings of depth taps measure the ground around a pixel, so pools gather against a kerb, in a dip and at the foot of a slope instead of lying on the world-space noise alone.
diff --git a/desktop b/desktop
index 4fec511e7..ebf266904 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 4fec511e79b37f6bc88cb3a08f1eb1811e4abc25
+Subproject commit ebf2669045c96a0a7ea090f2c84461ae3f095eb9
diff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdx
index a03adacdf..cfc480bcb 100644
--- a/docs/astro/src/content/docs/graphics/post-processing.mdx
+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx
@@ -65,6 +65,13 @@ darkens are the pools that reflect — flat, whatever the ground under them, and
with a sharp reflection where a dry one is blurred. Wet ground in general is shinier than dry: raise `ssr`'s `intensity`
when it rains.
+**Shelter.** Rain does not fall through a roof. While a `rain` effect is in the chain the frame draws the scene once from straight
+above, depth only, in a 1024² square around the camera (`shelterRange` world units each way) — a map of the highest surface at
+each place — and the effect asks it whether something stands over a point. Ground under an awning stays dry and still (no
+wetness, no puddles, no ripples), the streaks of a layer that stands under a roof are not drawn, and the drops that would have
+fallen there have landed on the awning, which is open to the sky and is wet in its turn. It costs the depth-only draw of the
+resident meshes in range, so keep `shelterRange` to the reach you need; ground outside the map is treated as open.
+
The clock is the game's. A capture that has to be the same on every run sets `timeScale` to 0 and `phase` to the time it
wants. What this is not: the ground's shape is read from what the camera sees (a hollow behind a wall is not known),
and the rain is a screen-space layer, not particles that collide with the world.
diff --git a/docs/astro/src/content/docs/graphics/weather.mdx b/docs/astro/src/content/docs/graphics/weather.mdx
index d0afd7d68..06965f873 100644
--- a/docs/astro/src/content/docs/graphics/weather.mdx
+++ b/docs/astro/src/content/docs/graphics/weather.mdx
@@ -21,6 +21,7 @@ Add a `Weather` component to one entity.
| `sequence` | Presets to cycle through by themselves, comma separated — `clear,mist,rain,clear`. Empty stays put. |
| `hold` | Seconds each weather of the sequence holds before the next turn. |
| `drive` | What the weather drives: Lights, Fog, Rain, Grade, Exposure, Reflections, Sound. |
+| `soundSource` | An entity with a looping `AudioSource` — the sound of the rain. The weather raises its `playing` while it rains and sets its volume to the authored one times how hard it rains. |
A turn is eased, so it starts and ends gently, and a finished turn lands on its target and clears itself.
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 cac8a6e69..425365e33 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
@@ -53,6 +53,11 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess
`puddleScale`,雨压暗的水坑就是会反射的水坑——不管下面是什么地面都是平的,反射比干燥表面强得多,且清晰,而干燥表面的反射是模糊的。
潮湿的地面整体比干燥的更亮泽:下雨时提高 `ssr` 的 `intensity`。
+**遮蔽。** 雨不会穿过屋顶。链路里有 `rain` 效果时,这一帧会把场景从正上方画一遍,只画深度,画在相机周围一个 1024² 的方块里
+(每边 `shelterRange` 世界单位)——一张每处最高表面的地图——效果拿一个点去问它头顶有没有东西。遮阳篷下的地面保持干燥和静止
+(没有潮湿、没有水坑、没有涟漪),站在屋顶下的那一层的雨线不会画出来,本来会落在那里的雨滴落在了遮阳篷上——它对着天空,于是轮到它变湿。
+代价是范围内常驻网格的只写深度绘制,所以把 `shelterRange` 留在你需要的范围;地图之外的地面按露天处理。
+
时钟是游戏的。要在每次运行都相同的截图,把 `timeScale` 设为 0,`phase` 设为想要的时间。它不是什么:地面的形状是从相机看到的东西里读出来的(墙后面的凹处它不知道),
雨是屏幕空间的一层,不是会与世界碰撞的粒子。
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx b/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx
index 45cb8c679..a2b9c6a9d 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx
@@ -19,6 +19,7 @@ description: 一个 Weather 组件,让场景处于晴、薄雾、阴天、雨或
| `sequence` | 自己循环经过的预设,逗号分隔——`clear,mist,rain,clear`。为空则不动。 |
| `hold` | 序列里每种天气停留多少秒再开始下一次转变。 |
| `drive` | 天气驱动什么:灯光、雾、雨、调色、曝光、反射、声音。 |
+| `soundSource` | 一个带循环 `AudioSource` 的实体——雨声。下雨时天气会抬起它的 `playing`,并把音量设为创作时的音量乘以雨的大小。 |
转变带缓动,开始和结束都平缓,完成的转变落在目标上并清空自己。
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 5c212129d..8aa58dddc 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -6657,6 +6657,11 @@
"key": "drive",
"type": "number",
"default": "127"
+ },
+ {
+ "key": "soundSource",
+ "type": "Entity",
+ "default": "none"
}
],
"animatable": [
@@ -6665,7 +6670,8 @@
"progress",
"duration",
"hold",
- "drive"
+ "drive",
+ "soundSource"
]
},
{
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 9d93c430c..670bd5ce1 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -10855,6 +10855,7 @@ hold: number
preset: number
progress: number
sequence: string
+soundSource: number
target: number
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 545182c34..450c578ed 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -11068,6 +11068,7 @@ hold: number
preset: number
progress: number
sequence: string
+soundSource: number
target: number
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 751962817..cb0180167 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -10850,6 +10850,7 @@ hold: number
preset: number
progress: number
sequence: string
+soundSource: number
target: number
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index e01cb46e4..fa9ceff26 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -11149,6 +11149,7 @@ hold: number
preset: number
progress: number
sequence: string
+soundSource: number
target: number
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 7760f8ca9..73e910f33 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -10881,6 +10881,7 @@ hold: number
preset: number
progress: number
sequence: string
+soundSource: number
target: number
```
diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.ts
index c2b1217a4..fbd1f1680 100644
--- a/sdk/src/ecs/component.ts
+++ b/sdk/src/ecs/component.ts
@@ -1346,6 +1346,9 @@ export interface WeatherData {
hold: number;
/** What the weather drives: lights, fog, rain, grade, exposure, reflections, sound. */
drive: number;
+ /** An entity with a looping AudioSource — the sound of the rain. The weather sets its volume (the authored one times
+ * how hard it rains) and raises or lowers its `playing`. 0 = none. */
+ soundSource: number;
}
const WEATHER_PRESET_OPTIONS = [
@@ -1369,7 +1372,9 @@ export const Weather = defineComponent<WeatherData>('Weather', {
sequence: '',
hold: 20,
drive: 127,
+ soundSource: 0,
}, {
+ entityFields: ['soundSource'],
fields: {
preset: { enum: WEATHER_PRESET_OPTIONS },
target: { enum: [{ label: 'None', value: -1 }, ...WEATHER_PRESET_OPTIONS] },
diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
index 795b71e6c..1fe16b36e 100644
--- a/sdk/src/postprocess/effects.ts
+++ b/sdk/src/postprocess/effects.ts
@@ -365,6 +365,9 @@ registerEffect({
{ name: 'u_streakLength', label: 'Streak Length', min: 0.05, max: 0.9, step: 0.01, defaultValue: 0.3 },
// A WORLD length: the size of the grid cell each ring lives in.
{ name: 'u_rippleScale', label: 'Ripple Scale', min: 5, max: 400, step: 1, defaultValue: 60 },
+ // How far from the camera, in world units, the map of what stands over each place reaches: ground under an awning
+ // inside it stays dry. The map is the scene drawn from straight above, so this is also how much of it costs.
+ { name: 'u_shelterRange', label: 'Shelter Range', min: 100, max: 30000, step: 100, defaultValue: 3000 },
// How much of the flat ground is standing water, and how big the pools are (a WORLD length).
// The reflections effect draws the same pools when it is given the same two numbers.
{ name: 'u_puddles', label: 'Puddles', min: 0, max: 1, step: 0.01, defaultValue: 0.3, neutralValue: 0 },
diff --git a/sdk/src/postprocess/postProcessEffects.ts b/sdk/src/postprocess/postProcessEffects.ts
index d9e422c5a..1f8c7c6c4 100644
--- a/sdk/src/postprocess/postProcessEffects.ts
+++ b/sdk/src/postprocess/postProcessEffects.ts
@@ -2403,6 +2403,14 @@ fn streaks(uv : vec2f, aspect : f32, cols : f32, speed : f32, seed : f32, T : f3
#pragma param u_streakColor color default(0.78,0.82,0.9,1)
#pragma param u_timeScale float default(1) range(0,1)
#pragma param u_phase float default(0) range(0,100000)
+#pragma param u_shelterRange float default(3000) range(100,30000)
+#pragma param u_shelterBias float default(40) range(1,500)
+#pragma param u_coverActive float default(0) range(0,1)
+#pragma param u_coverMatrix0 color default(1,0,0,0)
+#pragma param u_coverMatrix1 color default(0,1,0,0)
+#pragma param u_coverMatrix2 color default(0,0,1,0)
+#pragma param u_coverMatrix3 color default(0,0,0,1)
+#pragma param u_rainCover texture default(white)
#pragma fragment
precision highp float;
@@ -2417,6 +2425,18 @@ ${PUDDLE_GLSL}
${BASIN_GLSL}
${GLSL}
+/// 1 where something stands over a point, as the map of the scene seen from straight above says — an awning, a roof,
+/// a tree — and 0 in the open. The map stores the depth the shadow maps do, so a point on the surface itself is not over it.
+float shelteredAt(vec3 W) {
+ if (u_coverActive < 0.5) return 0.0;
+ vec4 c = mat4(u_coverMatrix0, u_coverMatrix1, u_coverMatrix2, u_coverMatrix3) * vec4(W, 1.0);
+ vec2 uv = c.xy / c.w * 0.5 + 0.5;
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return 0.0;
+ float stored = dot(texture(u_rainCover, uv).rgb, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));
+ float here = clamp(c.z / c.w * 0.5 + 0.5, 0.0, 1.0);
+ return stored < here - u_shelterBias / (4.0 * u_shelterRange) ? 1.0 : 0.0;
+}
+
void main() {
vec4 src = texture(u_texture, v_texCoord);
vec2 sz = vec2(textureSize(u_texture, 0));
@@ -2450,11 +2470,15 @@ void main() {
float up = smoothstep(0.86, 0.95, N.y);
// A wet surface is darker, because water in the pores takes the light a dry one scatters;
// standing water is darker still.
- float puddle = puddleMask(P.xz, basinCoverage(c, size, P, u_puddles, u_puddleScale), u_puddleScale) * up * u_wetness;
- col *= 1.0 - 0.32 * u_wetness * up;
+ // What stands over it: rain does not reach ground under an awning, so it stays dry and still, and the drops that
+ // would have fallen there have landed on the awning instead — which, being open to the sky, is wet in its turn.
+ float shelter = shelteredAt(P + vec3(0.0, 1.0, 0.0));
+ float wet = u_wetness * (1.0 - 0.9 * shelter);
+ float puddle = puddleMask(P.xz, basinCoverage(c, size, P, u_puddles, u_puddleScale), u_puddleScale) * up * wet;
+ col *= 1.0 - 0.32 * wet * up;
col *= 1.0 - 0.35 * puddle;
// Drops landing need drops falling: wet ground under no rain is still.
- float falling = clamp(u_intensity, 0.0, 1.0);
+ float falling = clamp(u_intensity, 0.0, 1.0) * (1.0 - shelter);
float near = 1.0 - smoothstep(1200.0, 3500.0, dist);
// Rings where drops land, on a grid in the world; they are denser and clearer on standing water.
vec2 g = P.xz / u_rippleScale;
@@ -2478,10 +2502,12 @@ void main() {
}
// Three layers, nearest last: a layer is drawn only over what is farther than it.
+ // And a layer's drops fall where the layer stands: under a roof there are none.
+ vec3 along = normalize(worldFromDepth(v_texCoord, d < 1.0 ? d : 1.0) - entry);
float rain = 0.0;
- if (dist > 120.0) rain += streaks(v_texCoord, aspect, 70.0, u_speed * 1.0, 1.0, T) * 0.35;
- if (dist > 450.0) rain += streaks(v_texCoord, aspect, 130.0, u_speed * 1.4, 2.0, T) * 0.28;
- if (dist > 1400.0) rain += streaks(v_texCoord, aspect, 230.0, u_speed * 1.9, 3.0, T) * 0.22;
+ if (dist > 120.0) rain += streaks(v_texCoord, aspect, 70.0, u_speed * 1.0, 1.0, T) * 0.35 * (1.0 - shelteredAt(entry + along * 120.0));
+ if (dist > 450.0) rain += streaks(v_texCoord, aspect, 130.0, u_speed * 1.4, 2.0, T) * 0.28 * (1.0 - shelteredAt(entry + along * 450.0));
+ if (dist > 1400.0) rain += streaks(v_texCoord, aspect, 230.0, u_speed * 1.9, 3.0, T) * 0.22 * (1.0 - shelteredAt(entry + along * 1400.0));
col += tint * rain * u_intensity;
fragColor = vec4(col, src.a);
}
@@ -2493,6 +2519,19 @@ ${PUDDLE_WGSL}
${BASIN_WGSL}
${WGSL}
+fn shelteredAt(W : vec3f) -> f32 {
+ if (mc.u_coverActive < 0.5) { return 0.0; }
+ let m = mat4x4f(mc.u_coverMatrix0, mc.u_coverMatrix1, mc.u_coverMatrix2, mc.u_coverMatrix3);
+ let c = m * vec4f(W, 1.0);
+ let uv = c.xy / c.w * 0.5 + 0.5;
+ 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 map was drawn in.
+ let stored = dot(textureSampleLevel(u_rainCover, u_rainCover_s, vec2f(uv.x, 1.0 - uv.y), 0.0).rgb,
+ vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));
+ let here = clamp(c.z / c.w * 0.5 + 0.5, 0.0, 1.0);
+ return select(0.0, 1.0, stored < here - mc.u_shelterBias / (4.0 * mc.u_shelterRange));
+}
+
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
let src = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
let sz = vec2f(vec2i(textureDimensions(t0, 0)));
@@ -2524,10 +2563,12 @@ ${WGSL}
var N = normalize(cross(ax, ay));
if (dot(N, viewDirection(P)) < 0.0) { N = -N; }
let up = smoothstep(0.86, 0.95, N.y);
- let puddle = puddleMask(P.xz, basinCoverage(c, size, P, mc.u_puddles, mc.u_puddleScale), mc.u_puddleScale) * up * mc.u_wetness;
- col = col * (1.0 - 0.32 * mc.u_wetness * up);
+ let shelter = shelteredAt(P + vec3f(0.0, 1.0, 0.0));
+ let wet = mc.u_wetness * (1.0 - 0.9 * shelter);
+ let puddle = puddleMask(P.xz, basinCoverage(c, size, P, mc.u_puddles, mc.u_puddleScale), mc.u_puddleScale) * up * wet;
+ col = col * (1.0 - 0.32 * wet * up);
col = col * (1.0 - 0.35 * puddle);
- let falling = clamp(mc.u_intensity, 0.0, 1.0);
+ let falling = clamp(mc.u_intensity, 0.0, 1.0) * (1.0 - shelter);
let near = 1.0 - smoothstep(1200.0, 3500.0, dist);
let g = P.xz / mc.u_rippleScale;
let id = floor(g);
@@ -2550,10 +2591,13 @@ ${WGSL}
col = col + tint * splash * 0.55 * mc.u_wetness * up * near * falling * (1.0 - puddle);
}
+ var dd1 = d;
+ if (d >= 1.0) { dd1 = 1.0; }
+ let along = normalize(worldFromDepth(v.v_texCoord, dd1) - entry);
var rain = 0.0;
- if (dist > 120.0) { rain = rain + streaks(v.v_texCoord, aspect, 70.0, mc.u_speed * 1.0, 1.0, T) * 0.35; }
- if (dist > 450.0) { rain = rain + streaks(v.v_texCoord, aspect, 130.0, mc.u_speed * 1.4, 2.0, T) * 0.28; }
- if (dist > 1400.0) { rain = rain + streaks(v.v_texCoord, aspect, 230.0, mc.u_speed * 1.9, 3.0, T) * 0.22; }
+ if (dist > 120.0) { rain = rain + streaks(v.v_texCoord, aspect, 70.0, mc.u_speed * 1.0, 1.0, T) * 0.35 * (1.0 - shelteredAt(entry + along * 120.0)); }
+ if (dist > 450.0) { rain = rain + streaks(v.v_texCoord, aspect, 130.0, mc.u_speed * 1.4, 2.0, T) * 0.28 * (1.0 - shelteredAt(entry + along * 450.0)); }
+ if (dist > 1400.0) { rain = rain + streaks(v.v_texCoord, aspect, 230.0, mc.u_speed * 1.9, 3.0, T) * 0.22 * (1.0 - shelteredAt(entry + along * 1400.0)); }
col = col + tint * rain * mc.u_intensity;
return vec4f(col, src.a);
}
diff --git a/sdk/src/postprocess/weatherSystem.ts b/sdk/src/postprocess/weatherSystem.ts
index 80c71a1a4..93d126ffb 100644
--- a/sdk/src/postprocess/weatherSystem.ts
+++ b/sdk/src/postprocess/weatherSystem.ts
@@ -14,6 +14,7 @@ import { Res, Time, type TimeData } from '../ecs/resource';
import { Query, Mut } from '../ecs/query';
import { GetWorld } from '../ecs/system';
import { Weather, Light, type WeatherData, type LightData } from '../ecs/component';
+import { AudioSource, type AudioSourceData } from '../audio/AudioComponents';
import type { World } from '../ecs/world';
import type { Entity } from '../types';
import { isEditor, isPlayMode } from '../ecs/env';
@@ -35,6 +36,9 @@ const bases = new Map<Entity, LightBase>();
/** 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 }>();
+/** The volume a rain track was authored at, so the weather scales the author's number and not its own last answer. */
+const soundBases = new Map<Entity, number>();
+
const LIGHT_DIRECTIONAL = 1;
const LIGHT_AMBIENT = 2;
@@ -84,6 +88,32 @@ function applyLights(world: World, state: WeatherState, drive: number): void {
}
}
+function restoreSound(world: World): void {
+ for (const [entity, volume] of soundBases) {
+ if (world.has(entity, AudioSource)) {
+ const data = world.get(entity, AudioSource) as AudioSourceData;
+ world.set(entity, AudioSource, { ...data, volume, playing: false });
+ }
+ }
+ soundBases.clear();
+}
+
+/** The rain's track, loud as the weather is: raised while it rains at all, lowered when it stops. */
+function applySound(world: World, source: number, state: WeatherState): void {
+ const entity = source as Entity;
+ if (!world.has(entity, AudioSource)) return;
+ const data = world.get(entity, AudioSource) as AudioSourceData;
+ let base = soundBases.get(entity);
+ if (base === undefined) {
+ base = data.volume;
+ soundBases.set(entity, base);
+ }
+ const volume = base * Math.min(state.sound, 1.5);
+ const playing = state.sound > 0.02;
+ if (Math.abs(data.volume - volume) < 1e-4 && data.playing === playing) return;
+ world.set(entity, AudioSource, { ...data, volume, playing, loop: true });
+}
+
/** The preset a name or an id in a sequence stands for. */
function presetOf(token: string): number | undefined {
const trimmed = token.trim();
@@ -129,6 +159,7 @@ export const weatherSystem = defineSystem(
for (const entry of weathers) { found = entry; break; }
if (!found) {
if (bases.size > 0) restoreLights(world);
+ if (soundBases.size > 0) restoreSound(world);
cycles.clear();
setCurrentWeather(null);
return;
@@ -142,6 +173,9 @@ export const weatherSystem = defineSystem(
if (playing && (data.drive & (WeatherDrive.Lights | WeatherDrive.Reflections))) applyLights(world, state, data.drive);
else if (bases.size > 0) restoreLights(world);
+
+ if (playing && (data.drive & WeatherDrive.Sound) && data.soundSource) applySound(world, data.soundSource, state);
+ else if (soundBases.size > 0) restoreSound(world);
},
{ name: 'WeatherSystem' }
);
@@ -149,6 +183,7 @@ export const weatherSystem = defineSystem(
/** Forgets what the system remembers: a device loss, a test, an app shut down. */
export function resetWeatherSystem(): void {
bases.clear();
+ soundBases.clear();
cycles.clear();
setCurrentWeather(null);
}
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cpp
index 9d2549d1e..0b2b854ae 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp
@@ -381,6 +381,46 @@ PostProcessPipeline::TemporalView PostProcessPipeline::peekTemporalView(const gl
return view;
}
+bool PostProcessPipeline::coverWanted() {
+ if (!initialized_ || bypass_) return false;
+ for (const auto& pass : passes_) {
+ if (pass.enabled && passHasTexture(pass, "u_rainCover")) return true;
+ }
+ return false;
+}
+
+f32 PostProcessPipeline::coverRange() {
+ for (const auto& pass : passes_) {
+ if (!pass.enabled || !passHasTexture(pass, "u_rainCover")) continue;
+ if (auto it = pass.floatUniforms.find("u_shelterRange"); it != pass.floatUniforms.end()) {
+ return std::max(it->second, 10.0f);
+ }
+ }
+ return 3000.0f;
+}
+
+rg::ResourceId PostProcessPipeline::declareCover(u32 size) {
+ cover_active_ = false;
+ if (!graph_) return rg::kNoResource;
+ if (!cover_fbo_ || cover_fbo_->getWidth() != size) {
+ FramebufferSpec spec;
+ spec.width = size;
+ spec.height = size;
+ spec.colorFormat = GfxPixelFormat::RGBA8;
+ spec.depthStencil = true;
+ spec.linearFilter = false;
+ cover_fbo_ = Framebuffer::create(device_, spec);
+ if (!cover_fbo_) {
+ ES_LOG_ERROR("PostProcessPipeline: Failed to create the rain cover target");
+ return rg::kNoResource;
+ }
+ }
+ cover_resource_ = graph_->importTarget(cover_fbo_->handle(), size, size, /*output=*/false,
+ cover_fbo_->getColorAttachment());
+ cover_active_ = true;
+ return cover_resource_;
+}
+
rg::ResourceId PostProcessPipeline::declareVelocity() {
velocity_active_ = false;
if (!graph_ || !device_.supportsFloatTargets()) return rg::kNoResource;
@@ -613,6 +653,7 @@ void PostProcessPipeline::declareChain() {
void PostProcessPipeline::chainDone() {
velocity_active_ = false;
+ cover_active_ = false;
if (!initialized_ || !inFrame_) return;
device_.invalidatePipelineCache();
inFrame_ = false;
@@ -658,6 +699,14 @@ void PostProcessPipeline::renderPass(PostProcessPass& pass, const rg::PassContex
}
// An effect that reflects the environment declares its parameters, and takes them from the
// light block the scene was drawn with: how the atlas is laid out, how bright it is, how far the sky has turned.
+ // An effect that asks what stands over a place is handed the matrix the answer was drawn through, and whether there is one.
+ if (layout && layout->find("u_coverMatrix0")) {
+ for (int c = 0; c < 4; ++c) {
+ pass.vec4Uniforms["u_coverMatrix" + std::to_string(c)] = glm::vec4(cover_matrix_[c]);
+ }
+ pass.floatUniforms["u_coverActive"] = cover_active_ ? 1.0f : 0.0f;
+ pass.paramDirty = true;
+ }
if (layout && layout->usesLights) {
// The block the scene was lit with, bound again: the passes between have no claim on its slot, but a
// chain is not the place to find out. And the atlas on the unit the Lit shaders read it from.
@@ -742,6 +791,9 @@ void PostProcessPipeline::renderPass(PostProcessPass& pass, const rg::PassContex
if (slot.name == "u_velocity" && velocity_active_ && velocity_fbo_) {
gpu = velocity_fbo_->getColorAttachment();
}
+ if (slot.name == "u_rainCover" && cover_active_ && cover_fbo_) {
+ gpu = cover_fbo_->getColorAttachment();
+ }
for (const auto& [name, glId] : pass.textureUniforms) {
if (name == slot.name && glId != 0) { gpu = TextureHandle{glId}; break; }
}
@@ -852,6 +904,9 @@ void PostProcessPipeline::runChain(std::vector<PostProcessPass>& passes, rg::Res
if (velocity_active_ && velocity_resource_ != rg::kNoResource && passHasTexture(pass, "u_velocity")) {
node.dependencies.push_back(velocity_resource_);
}
+ if (cover_active_ && cover_resource_ != rg::kNoResource && passHasTexture(pass, "u_rainCover")) {
+ node.dependencies.push_back(cover_resource_);
+ }
if (shadow_resource_ != rg::kNoResource && passUsesLights(pass)) {
node.dependencies.push_back(shadow_resource_);
}
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.hpp b/src/esengine/renderer/frame/PostProcessPipeline.hpp
index b5005f8a6..735a40be8 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.hpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.hpp
@@ -248,6 +248,20 @@ public:
*/
rg::ResourceId declareVelocity();
+ /**
+ * @brief Whether an enabled pass reads what stands over each place (`u_rainCover`).
+ *
+ * @details The frame then draws the scene from straight above, depth only, around the camera: a map of the highest
+ * surface at each spot, so an effect can tell open ground from ground under an awning.
+ */
+ bool coverWanted();
+ /// How far from the camera, in world units, that map reaches each way (the effect's `u_shelterRange`).
+ f32 coverRange();
+ /// The map's target for this frame, declared in the graph (kNoResource when it cannot be made).
+ rg::ResourceId declareCover(u32 size);
+ /// The matrix the map was drawn through, for the effect to put a world point in it.
+ void setCoverMatrix(const glm::mat4& viewProjection) { cover_matrix_ = viewProjection; }
+
/**
* @brief Whether this frame's scene target carries a second attachment for the surface's material.
*
@@ -567,6 +581,10 @@ private:
u32 shadow_texture_ = 0;
rg::ResourceId shadow_resource_ = rg::kNoResource;
/// The motion pass's target, kept across frames for its size, and whether this frame drew into it.
+ Unique<Framebuffer> cover_fbo_;
+ rg::ResourceId cover_resource_ = rg::kNoResource;
+ bool cover_active_ = false;
+ glm::mat4 cover_matrix_{1.0f};
Unique<Framebuffer> velocity_fbo_;
rg::ResourceId velocity_resource_ = rg::kNoResource;
bool velocity_active_ = false;
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index fd94ca4b4..24bbf7208 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -132,7 +132,8 @@ RenderFrame::RenderFrame(GfxDevice& device, RenderContext& context,
, target_pool_(device)
, graph_(device, target_pool_)
, shadow_pool_(device)
- , velocity_pool_(device) {
+ , velocity_pool_(device)
+ , cover_pool_(device) {
target_manager_.setDevice(device);
}
@@ -165,6 +166,7 @@ void RenderFrame::init(u32 width, u32 height) {
pool_.init();
shadow_pool_.init();
velocity_pool_.init();
+ cover_pool_.init();
planar_pool_.init();
batch_shader_id_ = initBatchShader();
@@ -191,6 +193,11 @@ void RenderFrame::shutdown() {
pool_.shutdown();
shadow_pool_.shutdown();
velocity_pool_.shutdown();
+ cover_pool_.shutdown();
+ if (cover_frame_ubo_ != BufferHandle::Invalid) {
+ device_.deleteBuffer(cover_frame_ubo_);
+ cover_frame_ubo_ = BufferHandle::Invalid;
+ }
planar_pool_.shutdown();
releasePlanarCaptures();
releaseShadowFrameUbos();
@@ -234,6 +241,7 @@ void RenderFrame::drawScene() {
jitter = post_process_->beginTemporalView(view_projection_, current_target_);
}
#endif
+ scene_jitter_ = jitter;
context_.updateCameraConstants(view_projection_, jitter);
// Where THIS camera's pixels sit inside the 2D shadow mask. Per camera because the
// mask is screen space: two cameras drew into two parts of one target, and a
@@ -650,6 +658,25 @@ void RenderFrame::end() {
}
#endif
+#ifdef ES_ENABLE_POSTPROCESS
+ // What stands over each place, for an effect that keeps rain off what is sheltered.
+ if (usePostProcess && scene_resource_ != rg::kNoResource && cover_list_.commandCount() > 0) {
+ const rg::ResourceId cover = post_process_->declareCover(1024);
+ if (cover != rg::kNoResource) {
+ post_process_->setCoverMatrix(cover_view_projection_);
+ rg::PassDesc pass;
+ pass.name = "rain-cover";
+ pass.write = cover;
+ pass.clear = true;
+ pass.clearDepth = true;
+ // White is depth 1: nothing above.
+ pass.clearColor[0] = pass.clearColor[1] = pass.clearColor[2] = pass.clearColor[3] = 1.0f;
+ pass.execute = [this](const rg::PassContext&) { executeCoverPass(); };
+ graph_.addPass(std::move(pass));
+ }
+ }
+#endif
+
if (usePostProcess) {
#ifdef ES_ENABLE_POSTPROCESS
post_process_->setShadowAtlas(shadow_texture_id_, shadow_resource_);
@@ -2233,8 +2260,10 @@ void RenderFrame::collectAll(ecs::Registry& registry, bool sceneGBuffer) {
stats_.occluded += collectCtx.occluded;
velocity_list_.clear();
+ cover_list_.clear();
#ifdef ES_ENABLE_POSTPROCESS
if (followMotion) collectMotion(registry);
+ if (sceneGBuffer && post_process_ && post_process_->isEngaged() && post_process_->coverWanted()) collectCover(registry);
#endif
// OR-ed across the frame's cameras, applied at the next beginFrame and never
@@ -2275,6 +2304,64 @@ void RenderFrame::collectMotion(ecs::Registry& registry) {
#endif
}
+void RenderFrame::collectCover(ecs::Registry& registry) {
+ ES_PROFILE_SCOPE("render.collect.cover");
+#ifdef ES_ENABLE_POSTPROCESS
+ const f32 range = post_process_->coverRange();
+ // From above, over the camera, snapped to the map's own texel grid so the map does not shimmer as the camera moves.
+ const glm::vec4 eye4 = cameraFromViewProjection(view_projection_);
+ const glm::vec3 eye = eye4.w > 0.5f ? glm::vec3(eye4) : glm::vec3(0.0f);
+ const f32 texel = (range * 2.0f) / 1024.0f;
+ const glm::vec3 centre(std::floor(eye.x / texel) * texel, eye.y, std::floor(eye.z / texel) * texel);
+ const f32 depth = range * 2.0f;
+ const glm::mat4 view = glm::lookAt(centre + glm::vec3(0.0f, range, 0.0f), centre, glm::vec3(0.0f, 0.0f, -1.0f));
+ // Written out like the shadow maps' own, so the depth it stores runs over [0, 1] on either device.
+ glm::mat4 proj(1.0f);
+ proj[0][0] = 1.0f / range;
+ proj[1][1] = 1.0f / range;
+ proj[2][2] = -1.0f / depth;
+ proj[3][2] = 0.0f;
+ cover_view_projection_ = proj * view;
+
+ cover_pool_.beginFrame();
+ cover_list_.clear();
+ Frustum frustum;
+ frustum.extractFromMatrix(cover_view_projection_);
+ auto ctx = makeContext();
+ ctx.view_projection = cover_view_projection_;
+ ctx.purpose = RenderPurpose::ShadowDepth;
+ RenderCollectContext collectCtx{registry, frustum, clip_state_, cover_pool_, cover_list_, ctx,
+ computeCameraView(cover_view_projection_)};
+ collectCtx.screen_ui = screen_domain_;
+ for (auto& plugin : plugins_) {
+ if (plugin->castsShadows()) plugin->collect(collectCtx);
+ }
+ cover_list_.finalize(cover_pool_);
+ cover_pool_.upload();
+#else
+ (void)registry;
+#endif
+}
+
+void RenderFrame::executeCoverPass() {
+ if (cover_list_.commandCount() == 0) return;
+ ES_PROFILE_SCOPE("render.cover");
+ if (cover_frame_ubo_ == BufferHandle::Invalid) {
+ cover_frame_ubo_ = device_.createBuffer({GfxBufferUsage::Uniform, RenderContext::frameConstantsSize(), /*dynamic=*/true},
+ GfxContent::transient(), nullptr);
+ }
+ if (cover_frame_ubo_ == BufferHandle::Invalid) return;
+ device_.setViewport(0, 0, 1024, 1024);
+ context_.useFrameConstants(cover_frame_ubo_, cover_view_projection_);
+ context_.lights().uploadAndBind();
+ cover_list_.execute(device_, cover_pool_, context_.materials(), context_.getWhiteTextureId(), nullptr,
+ context_.perDrawBlocks());
+ ES_PROFILE_COUNTER("render.cover.draws", cover_list_.mergedDrawCallCount());
+ // The constants the chain after this reads are the camera's, which this pass borrowed the slot from.
+ context_.updateCameraConstants(view_projection_, scene_jitter_);
+ device_.invalidatePipelineCache();
+}
+
void RenderFrame::executeMotionPass() {
if (velocity_list_.commandCount() == 0) return;
ES_PROFILE_SCOPE("render.motion");
diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hpp
index f8465a106..0f12b32cf 100644
--- a/src/esengine/renderer/frame/RenderFrame.hpp
+++ b/src/esengine/renderer/frame/RenderFrame.hpp
@@ -965,6 +965,21 @@ private:
/// Collects the meshes that moved by themselves since the last frame into velocity_list_.
void collectMotion(ecs::Registry& registry);
void executeMotionPass();
+ /**
+ * @brief The scene seen from straight above, depth only, around the camera — what stands over each place.
+ *
+ * @details Collected like a shadow map (the depth variant of every resident mesh) through a camera of its own, because
+ * what an effect asks of it is whether something is above a point, and a shadow map from the sun answers that for
+ * the sun's direction only. Its own buffers and list, for the same reason as the motion pass's.
+ */
+ void collectCover(ecs::Registry& registry);
+ void executeCoverPass();
+ TransientBufferPool cover_pool_;
+ DrawList cover_list_;
+ BufferHandle cover_frame_ubo_ = BufferHandle::Invalid;
+ glm::mat4 cover_view_projection_{1.0f};
+ /// The shift the scene was drawn with, so a pass that borrows the frame's constants can hand them back as they were.
+ glm::vec2 scene_jitter_{0.0f};
/// One per view, kept across frames for the capacity. The whole pass is collected
/// before any of it is drawn, so a view's commands have to outlive its collect.
std::vector<DrawList> shadow_view_lists_;
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index cba130c7c..1a06ce61d 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2501,6 +2501,8 @@ export const NOTED = {
{"note":"Puddles gather in the low places of the ground and thin on its rises, read from the depth buffer."},
"feat(render): auto exposure meters a spot, and depth of field auto-focuses and shapes its bokeh by the aperture":
{"note":"Auto Exposure can meter the middle of the picture or a spot, and Depth of Field focuses by itself and blurs a light into the shape of its aperture."},
+ "feat(runtime): rain stays off what is under a roof, and the weather turns a rain track up and down":
+ {"note":"Rain stays off what stands under a roof, and the Weather component turns a looping rain track up and down."},
"feat(render): reflections no longer guess a surface, plain meshes record themselves, and what the ray never finds is the sky":
{"note":"Screen-space reflections leave a surface that recorded nothing alone, plain meshes now record a rough dielectric, and a puddle reflects the sky and what lies off screen."},
};