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): a Weather component puts a scene under a preset, turns between presets and cycles through a sequence

yhh37a5f7ffe9ff
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 702ac0def..d11672d38 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +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.
- **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.
diff --git a/desktop b/desktop
index c99c43169..65e7cba4e 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit c99c431698cce68db37bc2a037ca0a456f9f2e67
+Subproject commit 65e7cba4edcb125832383b3e665611ac458ec4f0
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index 2bb181164..8bee66ec7 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -223,6 +223,7 @@ export default defineConfig({
{ label: 'Materials & Shaders', translations: { 'zh-CN': '材质与着色器' }, slug: 'graphics/materials' },
{ label: '2D Lighting & Shadows', translations: { 'zh-CN': '2D 光照与阴影' }, slug: 'graphics/lighting' },
{ label: 'Post-processing', translations: { 'zh-CN': '后处理' }, slug: 'graphics/post-processing' },
+ { label: 'Weather', translations: { 'zh-CN': '天气' }, slug: 'graphics/weather' },
{ label: 'Custom Drawing', translations: { 'zh-CN': '自定义绘制' }, slug: 'graphics/drawing' },
{ label: 'Video', translations: { 'zh-CN': '视频' }, slug: 'graphics/video' },
],
diff --git a/docs/astro/src/content/docs/graphics/weather.mdx b/docs/astro/src/content/docs/graphics/weather.mdx
new file mode 100644
index 000000000..d53b51add
--- /dev/null
+++ b/docs/astro/src/content/docs/graphics/weather.mdx
@@ -0,0 +1,64 @@
+---
+title: Weather
+description: A Weather component that puts a scene under clear, mist, overcast, rain or storm, turns between them, and cycles by itself.
+---
+
+A scene's weather is not a pile of effect parameters. A project's fog is in its own units and its sun is as bright
+as its author made it, so a weather is expressed as **multipliers of what the scene already says** — the sun at a
+quarter of its strength, the fog five times as thick, the picture a little greyer — plus a few levels that mean the same
+everywhere: how hard it rains, how wet the ground is. The same preset then fits any project.
+
+## The component
+
+Add a `Weather` component to one entity.
+
+| Field | What it does |
+|---|---|
+| `preset` | The weather the scene is in: Clear, Mist, Overcast, Rain, Storm. |
+| `target` | The weather it is turning into; None for none. |
+| `progress` | How far along that turn it is (0–1). The game advances it; set it in the editor to preview a half-turn. |
+| `duration` | Seconds a turn takes. |
+| `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. |
+
+A turn is eased, so it starts and ends gently, and a finished turn lands on its target and clears itself.
+
+## What a weather changes
+
+- **Lights.** Directional lights are scaled (and tinted) and the ambient light is scaled, from the strengths they were
+ authored with — the weather scales your number, never its own last answer — and they are put back when the weather
+ is taken away or `Lights` is switched off. Only while the game runs: in the editor the lights are left alone, so
+ previewing a weather never changes the scene you save.
+- **Fog.** Height Fog's density, its sun glow and the volumetric light it carries are scaled, its sky haze is raised, and
+ its colour moves toward the weather's.
+- **Rain.** The Rain effect is brought with the weather (when the scene has none) at the preset's strength, and Rain and
+ Screen Space Reflections are given the wetness and puddles it leaves. Where the scene authored its own rain, the
+ weather can only raise it.
+- **Grade and exposure.** Colour Grade's saturation and contrast are scaled, and Auto Exposure's compensation raised.
+
+The effects are applied after the scene's volumes have blended, so a scene that fogs itself thinly stays thinner than
+one that fogs itself thickly in the same rain.
+
+## Your own weathers
+
+```ts
+import { registerWeatherPreset, WEATHER_CLEAR } from 'esengine';
+
+// A preset names only what it changes; everything else is neutral.
+const sandstorm = registerWeatherPreset('sandstorm', {
+ sun: 0.5, fogDensity: 10, fogTint: [0.82, 0.62, 0.38], fogTintAmount: 0.85,
+ saturation: 0.8, exposure: 0.4,
+});
+```
+
+A custom preset answers to its name in a `sequence`, and to the id `registerWeatherPreset` returns in `preset` and
+`target`. Registering a built-in name again retunes it.
+
+## Turning by code
+
+The component is data: write `target` and `progress: 0` and the system does the rest.
+
+```ts
+world.insert(weatherEntity, Weather, { target: WEATHER_RAIN, progress: 0, duration: 10 });
+```
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx b/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx
new file mode 100644
index 000000000..c418d73b7
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx
@@ -0,0 +1,57 @@
+---
+title: 天气
+description: 一个 Weather 组件,让场景处于晴、薄雾、阴天、雨或暴风雨之下,在它们之间过渡,并能自己循环。
+---
+
+场景的天气不是一堆特效参数。项目的雾有它自己的单位,太阳有作者给它的亮度,所以天气表达成**场景已有设定的倍率**——
+太阳降到四分之一、雾厚五倍、画面灰一点——再加几个在哪里都含义相同的量:雨下多大、地面多湿。同一个预设于是适配任何项目。
+
+## 组件
+
+给某个实体加一个 `Weather` 组件。
+
+| 字段 | 作用 |
+|---|---|
+| `preset` | 场景所处的天气:晴、薄雾、阴天、雨、暴风雨。 |
+| `target` | 正在转向的天气;无则为 None。 |
+| `progress` | 这次转变走了多远(0–1)。游戏会推进它;在编辑器里设置它可以预览转到一半。 |
+| `duration` | 一次转变用多少秒。 |
+| `sequence` | 自己循环经过的预设,逗号分隔——`clear,mist,rain,clear`。为空则不动。 |
+| `hold` | 序列里每种天气停留多少秒再开始下一次转变。 |
+| `drive` | 天气驱动什么:灯光、雾、雨、调色、曝光、反射、声音。 |
+
+转变带缓动,开始和结束都平缓,完成的转变落在目标上并清空自己。
+
+## 天气改变什么
+
+- **灯光。** 方向光被缩放(并着色),环境光被缩放,依据的是它们创作时的强度——天气缩放的是你的数字,而不是它自己上一次的结果——
+ 天气被拿走或关掉 `Lights` 时它们会被还原。只在游戏运行时:编辑器里灯光不动,所以预览天气不会改动你要保存的场景。
+- **雾。** Height Fog 的密度、太阳辉光和它带的体积光被缩放,天空雾霾被提高,颜色向天气的颜色移动。
+- **雨。** 场景没有 Rain 效果时天气会带来一个,强度按预设;Rain 和屏幕空间反射还会得到天气留下的湿度和水坑。场景自己创作了雨,
+ 天气只能把它提高。
+- **调色与曝光。** Colour Grade 的饱和度和对比度被缩放,Auto Exposure 的补偿被提高。
+
+这些效果在场景的体积混合之后才施加,所以在同一场雨里,雾设得薄的场景仍然比雾设得厚的场景薄。
+
+## 自己的天气
+
+```ts
+import { registerWeatherPreset } from 'esengine';
+
+// 预设只写它要改的;其余保持中性。
+const sandstorm = registerWeatherPreset('sandstorm', {
+ sun: 0.5, fogDensity: 10, fogTint: [0.82, 0.62, 0.38], fogTintAmount: 0.85,
+ saturation: 0.8, exposure: 0.4,
+});
+```
+
+自定义预设在 `sequence` 里按名字使用,在 `preset` 和 `target` 里按 `registerWeatherPreset` 返回的 id 使用。
+重新注册内置名字就是重新调它。
+
+## 用代码转变
+
+组件就是数据:写入 `target` 和 `progress: 0`,系统会做剩下的事。
+
+```ts
+world.insert(weatherEntity, Weather, { target: WEATHER_RAIN, progress: 0, duration: 10 });
+```
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 9922b74d6..0bf46ba1a 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -1,12 +1,12 @@
{
"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.",
"counts": {
- "public": 115,
+ "public": 120,
"beta": 164,
- "experimental": 2279,
+ "experimental": 2292,
"deprecated": 3
},
- "total": 2558,
+ "total": 2576,
"subsystems": [
{
"id": "mobile-controls",
@@ -1718,6 +1718,30 @@
"minigame"
]
},
+ {
+ "name": "blendWeather",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
+ {
+ "name": "currentWeather",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "defineComponent",
"kind": "function",
@@ -1825,6 +1849,42 @@
"wechat",
"minigame"
]
+ },
+ {
+ "name": "registerWeatherPreset",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
+ {
+ "name": "weatherPresetId",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
+ {
+ "name": "weatherPresetNames",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
}
],
"beta": [
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index c059779ed..e6eed3a04 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -72,6 +72,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
Light: { category: 'graphics', summary: 'A light — point, directional, spot or ambient — read by lit renderers, Lit materials and mesh shadow maps.', doc: 'graphics/lighting', anchor: 'light-types', anchorZh: '光源类型' },
ShadowCaster2D: { category: 'graphics', summary: 'Marks a renderer as an occluder, so 2D lights cast shadows from its silhouette.', doc: 'graphics/lighting', anchor: 'casting-shadows', anchorZh: '投射阴影' },
PostProcessVolume: { category: 'graphics', summary: 'A stack of full-screen effects (bloom, vignette, colour grading) applied after the scene is drawn.', doc: 'graphics/post-processing', anchor: 'using-a-postprocessvolume', anchorZh: '使用-postprocessvolume' },
+ Weather: { category: 'graphics', summary: 'The weather of a scene — a preset, a turn toward another, and an optional cycle — driving lights, fog, rain, grade, exposure and reflections.', doc: 'graphics/weather' },
MeshRenderer: { category: 'graphics', summary: 'Geometry drawn as an entity — your own vertices or an imported mesh, with a material and a sorting layer.', doc: 'graphics/drawing', anchor: 'custom-meshes-meshrenderer', anchorZh: '自定义网格meshrenderer' },
MeshSkin: { category: 'graphics', summary: 'The joint entities that deform a MeshRenderer — an imported skin, in the order its bind matrices are in.', doc: 'assets/models', anchor: 'skinning', anchorZh: '蒙皮' },
MeshMorph: { category: 'graphics', summary: 'How far a MeshRenderer is blended towards each of the shapes its mesh carries — one weight per morph target.', doc: 'assets/models', anchor: 'morph-targets', anchorZh: 'morph-target' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index abca55bb2..6d6a97fa4 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -6585,6 +6585,73 @@
"handle"
]
},
+ {
+ "name": "Weather",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "preset",
+ "type": "enum",
+ "default": "Clear",
+ "values": [
+ "Clear",
+ "Mist",
+ "Overcast",
+ "Rain",
+ "Storm"
+ ]
+ },
+ {
+ "key": "target",
+ "type": "enum",
+ "default": "None",
+ "values": [
+ "None",
+ "Clear",
+ "Mist",
+ "Overcast",
+ "Rain",
+ "Storm"
+ ]
+ },
+ {
+ "key": "progress",
+ "type": "number",
+ "default": "0",
+ "range": "0–1, step 0.01"
+ },
+ {
+ "key": "duration",
+ "type": "number",
+ "default": "6",
+ "range": "0.1–600, step 0.1"
+ },
+ {
+ "key": "sequence",
+ "type": "string",
+ "default": "empty"
+ },
+ {
+ "key": "hold",
+ "type": "number",
+ "default": "20",
+ "range": "0–3600, step 1"
+ },
+ {
+ "key": "drive",
+ "type": "number",
+ "default": "127"
+ }
+ ],
+ "animatable": [
+ "preset",
+ "target",
+ "progress",
+ "duration",
+ "hold",
+ "drive"
+ ]
+ },
{
"name": "WheelJoint2D",
"source": "ts",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index ab179d3ea..d3e3c5626 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 · 152 beta · 1653 experimental · 3 deprecated
+Symbols: 120 public · 152 beta · 1664 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -10788,6 +10788,36 @@ returnSpeed: number | undefined
world: World
```
+## WEATHER_CLEAR — const @experimental
+```
+0
+```
+
+## WEATHER_MIST — const @experimental
+```
+1
+```
+
+## WEATHER_NONE — const @experimental
+```
+-1
+```
+
+## WEATHER_OVERCAST — const @experimental
+```
+2
+```
+
+## WEATHER_RAIN — const @experimental
+```
+3
+```
+
+## WEATHER_STORM — const @experimental
+```
+4
+```
+
## WORLD_DIR — const @experimental
```
"world"
@@ -10810,6 +10840,54 @@ static new (options: GameSocketOptions): WeChatSocket
static prototype: WeChatSocket
```
+## Weather — const @experimental
+```
+ComponentDef<WeatherData>
+```
+
+## WeatherData — interface @experimental
+```
+drive: number
+duration: number
+hold: number
+preset: number
+progress: number
+sequence: string
+target: number
+```
+
+## WeatherDrive — const @experimental
+```
+{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly All: 127; }
+```
+
+## WeatherPreset — type @experimental
+```
+Partial<WeatherState>
+```
+
+## WeatherState — interface @experimental
+```
+contrast: number
+exposure: number
+fogDensity: number
+fogGlow: number
+fogTint: [number, number, number]
+fogTintAmount: number
+puddles: number
+rain: number
+reflection: number
+reflectionSaturation: number
+saturation: number
+sky: number
+skyFog: number
+sound: number
+ssr: number
+sun: number
+sunTint: [number, number, number]
+wetness: number
+```
+
## WebAppOptions — interface @experimental
```
colorSpace: "gamma" | "linear" | undefined
@@ -11468,6 +11546,11 @@ MotionDriver<AnimatorBlend2DMotion>
(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
```
+## blendWeather — function @public
+```
+(from: number, to: number, progress: number): WeatherState
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -11918,6 +12001,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentWeather — function @public
+```
+(): WeatherState | null
+```
+
## cutWorld — function @experimental
```
(scene: SceneData, sceneName: string, options: PartitionOptions): CutWorld | null
@@ -13513,6 +13601,11 @@ PrefabsPlugin
(name: string, spec: AiValueSpec<AiContext>): void
```
+## registerWeatherPreset — function @public
+```
+(name: string, preset: WeatherPreset): number
+```
+
## registryEntityFields — function @experimental
```
(): (componentType: string) => readonly string[]
@@ -14413,6 +14506,16 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
+## weatherPresetId — function @public
+```
+(name: string): number | undefined
+```
+
+## weatherPresetNames — function @public
+```
+(): string[]
+```
+
## widgetToPrefab — function @experimental
```
(build: (world: World) => Entity, name: string): PrefabData
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index ce321ef82..d5d173580 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 · 157 beta · 1672 experimental · 3 deprecated
+Symbols: 120 public · 157 beta · 1683 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -11001,6 +11001,36 @@ returnSpeed: number | undefined
world: World
```
+## WEATHER_CLEAR — const @experimental
+```
+0
+```
+
+## WEATHER_MIST — const @experimental
+```
+1
+```
+
+## WEATHER_NONE — const @experimental
+```
+-1
+```
+
+## WEATHER_OVERCAST — const @experimental
+```
+2
+```
+
+## WEATHER_RAIN — const @experimental
+```
+3
+```
+
+## WEATHER_STORM — const @experimental
+```
+4
+```
+
## WORLD_DIR — const @experimental
```
"world"
@@ -11023,6 +11053,54 @@ static new (options: GameSocketOptions): WeChatSocket
static prototype: WeChatSocket
```
+## Weather — const @experimental
+```
+ComponentDef<WeatherData>
+```
+
+## WeatherData — interface @experimental
+```
+drive: number
+duration: number
+hold: number
+preset: number
+progress: number
+sequence: string
+target: number
+```
+
+## WeatherDrive — const @experimental
+```
+{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly All: 127; }
+```
+
+## WeatherPreset — type @experimental
+```
+Partial<WeatherState>
+```
+
+## WeatherState — interface @experimental
+```
+contrast: number
+exposure: number
+fogDensity: number
+fogGlow: number
+fogTint: [number, number, number]
+fogTintAmount: number
+puddles: number
+rain: number
+reflection: number
+reflectionSaturation: number
+saturation: number
+sky: number
+skyFog: number
+sound: number
+ssr: number
+sun: number
+sunTint: [number, number, number]
+wetness: number
+```
+
## WebAppOptions — interface @experimental
```
colorSpace: "gamma" | "linear" | undefined
@@ -11696,6 +11774,11 @@ MotionDriver<AnimatorBlend2DMotion>
(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
```
+## blendWeather — function @public
+```
+(from: number, to: number, progress: number): WeatherState
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -12171,6 +12254,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentWeather — function @public
+```
+(): WeatherState | null
+```
+
## cutWorld — function @experimental
```
(scene: SceneData, sceneName: string, options: PartitionOptions): CutWorld | null
@@ -13776,6 +13864,11 @@ PrefabsPlugin
(name: string, spec: AiValueSpec<AiContext>): void
```
+## registerWeatherPreset — function @public
+```
+(name: string, preset: WeatherPreset): number
+```
+
## registryEntityFields — function @experimental
```
(): (componentType: string) => readonly string[]
@@ -14676,6 +14769,16 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
+## weatherPresetId — function @public
+```
+(name: string): number | undefined
+```
+
+## weatherPresetNames — function @public
+```
+(): string[]
+```
+
## widgetToPrefab — function @experimental
```
(build: (world: World) => Entity, name: string): PrefabData
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index e704d1118..f900bf921 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 · 154 beta · 1652 experimental · 3 deprecated
+Symbols: 120 public · 154 beta · 1663 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -10783,6 +10783,36 @@ returnSpeed: number | undefined
world: World
```
+## WEATHER_CLEAR — const @experimental
+```
+0
+```
+
+## WEATHER_MIST — const @experimental
+```
+1
+```
+
+## WEATHER_NONE — const @experimental
+```
+-1
+```
+
+## WEATHER_OVERCAST — const @experimental
+```
+2
+```
+
+## WEATHER_RAIN — const @experimental
+```
+3
+```
+
+## WEATHER_STORM — const @experimental
+```
+4
+```
+
## WORLD_DIR — const @experimental
```
"world"
@@ -10805,6 +10835,54 @@ static new (options: GameSocketOptions): WeChatSocket
static prototype: WeChatSocket
```
+## Weather — const @experimental
+```
+ComponentDef<WeatherData>
+```
+
+## WeatherData — interface @experimental
+```
+drive: number
+duration: number
+hold: number
+preset: number
+progress: number
+sequence: string
+target: number
+```
+
+## WeatherDrive — const @experimental
+```
+{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly All: 127; }
+```
+
+## WeatherPreset — type @experimental
+```
+Partial<WeatherState>
+```
+
+## WeatherState — interface @experimental
+```
+contrast: number
+exposure: number
+fogDensity: number
+fogGlow: number
+fogTint: [number, number, number]
+fogTintAmount: number
+puddles: number
+rain: number
+reflection: number
+reflectionSaturation: number
+saturation: number
+sky: number
+skyFog: number
+sound: number
+ssr: number
+sun: number
+sunTint: [number, number, number]
+wetness: number
+```
+
## WebAppOptions — interface @experimental
```
colorSpace: "gamma" | "linear" | undefined
@@ -11463,6 +11541,11 @@ MotionDriver<AnimatorBlend2DMotion>
(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
```
+## blendWeather — function @public
+```
+(from: number, to: number, progress: number): WeatherState
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -11913,6 +11996,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentWeather — function @public
+```
+(): WeatherState | null
+```
+
## cutWorld — function @experimental
```
(scene: SceneData, sceneName: string, options: PartitionOptions): CutWorld | null
@@ -13518,6 +13606,11 @@ PrefabsPlugin
(name: string, spec: AiValueSpec<AiContext>): void
```
+## registerWeatherPreset — function @public
+```
+(name: string, preset: WeatherPreset): number
+```
+
## registryEntityFields — function @experimental
```
(): (componentType: string) => readonly string[]
@@ -14418,6 +14511,16 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
+## weatherPresetId — function @public
+```
+(name: string): number | undefined
+```
+
+## weatherPresetNames — function @public
+```
+(): string[]
+```
+
## widgetToPrefab — function @experimental
```
(build: (world: World) => Entity, name: string): PrefabData
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 168f6b109..c2543b890 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 · 152 beta · 1674 experimental · 3 deprecated
+Symbols: 120 public · 152 beta · 1685 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -11082,6 +11082,36 @@ returnSpeed: number | undefined
world: World
```
+## WEATHER_CLEAR — const @experimental
+```
+0
+```
+
+## WEATHER_MIST — const @experimental
+```
+1
+```
+
+## WEATHER_NONE — const @experimental
+```
+-1
+```
+
+## WEATHER_OVERCAST — const @experimental
+```
+2
+```
+
+## WEATHER_RAIN — const @experimental
+```
+3
+```
+
+## WEATHER_STORM — const @experimental
+```
+4
+```
+
## WORLD_DIR — const @experimental
```
"world"
@@ -11104,6 +11134,54 @@ static new (options: GameSocketOptions): WeChatSocket
static prototype: WeChatSocket
```
+## Weather — const @experimental
+```
+ComponentDef<WeatherData>
+```
+
+## WeatherData — interface @experimental
+```
+drive: number
+duration: number
+hold: number
+preset: number
+progress: number
+sequence: string
+target: number
+```
+
+## WeatherDrive — const @experimental
+```
+{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly All: 127; }
+```
+
+## WeatherPreset — type @experimental
+```
+Partial<WeatherState>
+```
+
+## WeatherState — interface @experimental
+```
+contrast: number
+exposure: number
+fogDensity: number
+fogGlow: number
+fogTint: [number, number, number]
+fogTintAmount: number
+puddles: number
+rain: number
+reflection: number
+reflectionSaturation: number
+saturation: number
+sky: number
+skyFog: number
+sound: number
+ssr: number
+sun: number
+sunTint: [number, number, number]
+wetness: number
+```
+
## WebAppOptions — interface @experimental
```
colorSpace: "gamma" | "linear" | undefined
@@ -11762,6 +11840,11 @@ MotionDriver<AnimatorBlend2DMotion>
(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
```
+## blendWeather — function @public
+```
+(from: number, to: number, progress: number): WeatherState
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -12217,6 +12300,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentWeather — function @public
+```
+(): WeatherState | null
+```
+
## cutWorld — function @experimental
```
(scene: SceneData, sceneName: string, options: PartitionOptions): CutWorld | null
@@ -13822,6 +13910,11 @@ PrefabsPlugin
(name: string, spec: AiValueSpec<AiContext>): void
```
+## registerWeatherPreset — function @public
+```
+(name: string, preset: WeatherPreset): number
+```
+
## registryEntityFields — function @experimental
```
(): (componentType: string) => readonly string[]
@@ -14722,6 +14815,16 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
+## weatherPresetId — function @public
+```
+(name: string): number | undefined
+```
+
+## weatherPresetNames — function @public
+```
+(): string[]
+```
+
## widgetToPrefab — function @experimental
```
(build: (world: World) => Entity, name: string): PrefabData
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 4ccca183e..5fbc79fbe 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 · 152 beta · 1665 experimental · 3 deprecated
+Symbols: 120 public · 152 beta · 1676 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -10790,6 +10790,36 @@ returnSpeed: number | undefined
world: World
```
+## WEATHER_CLEAR — const @experimental
+```
+0
+```
+
+## WEATHER_MIST — const @experimental
+```
+1
+```
+
+## WEATHER_NONE — const @experimental
+```
+-1
+```
+
+## WEATHER_OVERCAST — const @experimental
+```
+2
+```
+
+## WEATHER_RAIN — const @experimental
+```
+3
+```
+
+## WEATHER_STORM — const @experimental
+```
+4
+```
+
## WORLD_DIR — const @experimental
```
"world"
@@ -10836,6 +10866,54 @@ static new (options: GameSocketOptions): WeChatSocket
static prototype: WeChatSocket
```
+## Weather — const @experimental
+```
+ComponentDef<WeatherData>
+```
+
+## WeatherData — interface @experimental
+```
+drive: number
+duration: number
+hold: number
+preset: number
+progress: number
+sequence: string
+target: number
+```
+
+## WeatherDrive — const @experimental
+```
+{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly All: 127; }
+```
+
+## WeatherPreset — type @experimental
+```
+Partial<WeatherState>
+```
+
+## WeatherState — interface @experimental
+```
+contrast: number
+exposure: number
+fogDensity: number
+fogGlow: number
+fogTint: [number, number, number]
+fogTintAmount: number
+puddles: number
+rain: number
+reflection: number
+reflectionSaturation: number
+saturation: number
+sky: number
+skyFog: number
+sound: number
+ssr: number
+sun: number
+sunTint: [number, number, number]
+wetness: number
+```
+
## WebAppOptions — interface @experimental
```
colorSpace: "gamma" | "linear" | undefined
@@ -11494,6 +11572,11 @@ MotionDriver<AnimatorBlend2DMotion>
(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
```
+## blendWeather — function @public
+```
+(from: number, to: number, progress: number): WeatherState
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -11944,6 +12027,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentWeather — function @public
+```
+(): WeatherState | null
+```
+
## cutWorld — function @experimental
```
(scene: SceneData, sceneName: string, options: PartitionOptions): CutWorld | null
@@ -13549,6 +13637,11 @@ PrefabsPlugin
(name: string, spec: AiValueSpec<AiContext>): void
```
+## registerWeatherPreset — function @public
+```
+(name: string, preset: WeatherPreset): number
+```
+
## registryEntityFields — function @experimental
```
(): (componentType: string) => readonly string[]
@@ -14449,6 +14542,16 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
+## weatherPresetId — function @public
+```
+(name: string): number | undefined
+```
+
+## weatherPresetNames — function @public
+```
+(): string[]
+```
+
## wechatProfile — const @experimental
```
MiniGameProfile
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 3cfc471db..73466e1bc 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -174,6 +174,20 @@ export {
getEffectDef,
getEffectTypes,
getAllEffectDefs,
+ registerWeatherPreset,
+ weatherPresetId,
+ weatherPresetNames,
+ blendWeather,
+ currentWeather,
+ WeatherDrive,
+ WEATHER_CLEAR,
+ WEATHER_MIST,
+ WEATHER_OVERCAST,
+ WEATHER_RAIN,
+ WEATHER_STORM,
+ WEATHER_NONE,
+ type WeatherState,
+ type WeatherPreset,
} from './postprocess';
// =============================================================================
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index 0974b2fd1..00ce622c6 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -165,6 +165,8 @@ export {
type ParticleForceFieldData,
PostProcessVolume,
type PostProcessVolumeData,
+ Weather,
+ type WeatherData,
} from './ecs/component';
export {
diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.ts
index eafcd70c6..c2b1217a4 100644
--- a/sdk/src/ecs/component.ts
+++ b/sdk/src/ecs/component.ts
@@ -1331,6 +1331,58 @@ export const PostProcessVolume = defineComponent<PostProcessVolumeData>('PostPro
},
});
+export interface WeatherData {
+ /** The weather the scene is in (the built-in presets: Clear, Mist, Overcast, Rain, Storm). */
+ preset: number;
+ /** The weather it is turning into; -1 for none. */
+ target: number;
+ /** How far along that turn it is, 0..1. The system advances it in play, and a value set here previews it in the editor. */
+ progress: number;
+ /** Seconds a turn takes. */
+ duration: number;
+ /** Presets to cycle through by themselves, by name or id, comma separated ("clear,mist,rain,clear"); empty = stay. */
+ sequence: string;
+ /** Seconds each weather of the sequence holds before the next turn begins. */
+ hold: number;
+ /** What the weather drives: lights, fog, rain, grade, exposure, reflections, sound. */
+ drive: number;
+}
+
+const WEATHER_PRESET_OPTIONS = [
+ { label: 'Clear', value: 0 }, { label: 'Mist', value: 1 }, { label: 'Overcast', value: 2 },
+ { label: 'Rain', value: 3 }, { label: 'Storm', value: 4 },
+];
+
+/**
+ * The weather of a scene: one of a few presets, a turn toward another, and an optional cycle between them.
+ *
+ * @details A preset is a handful of multipliers on what the scene already has — the sun at a fraction of its strength,
+ * the fog thicker, the picture a little greyer — and a few absolute levels (how hard it rains, how wet the ground
+ * is), so the same weather fits any project. The component drives the scene's lights (in play), the post-process
+ * effects its volumes resolve (rain, fog, grade, exposure, reflections) and the sound of the rain.
+ */
+export const Weather = defineComponent<WeatherData>('Weather', {
+ preset: 0,
+ target: -1,
+ progress: 0,
+ duration: 6,
+ sequence: '',
+ hold: 20,
+ drive: 127,
+}, {
+ fields: {
+ preset: { enum: WEATHER_PRESET_OPTIONS },
+ target: { enum: [{ label: 'None', value: -1 }, ...WEATHER_PRESET_OPTIONS] },
+ progress: { min: 0, max: 1, step: 0.01 },
+ duration: { min: 0.1, max: 600, step: 0.1, unit: 's' },
+ hold: { min: 0, max: 3600, step: 1, unit: 's' },
+ drive: { flags: [
+ { label: 'Lights', value: 1 }, { label: 'Fog', value: 2 }, { label: 'Rain', value: 4 }, { label: 'Grade', value: 8 },
+ { label: 'Exposure', value: 16 }, { label: 'Reflections', value: 32 }, { label: 'Sound', value: 64 },
+ ] },
+ },
+});
+
export type {
RigidBody2DData, BoxCollider2DData, CircleCollider2DData, CapsuleCollider2DData,
};
diff --git a/sdk/src/postprocess.ts b/sdk/src/postprocess.ts
index 423e69f9b..e88306f1c 100644
--- a/sdk/src/postprocess.ts
+++ b/sdk/src/postprocess.ts
@@ -21,4 +21,18 @@ export {
getAllEffectDefs,
PostProcessPlugin,
postProcessPlugin,
+ registerWeatherPreset,
+ weatherPresetId,
+ weatherPresetNames,
+ blendWeather,
+ currentWeather,
+ WeatherDrive,
+ WEATHER_CLEAR,
+ WEATHER_MIST,
+ WEATHER_OVERCAST,
+ WEATHER_RAIN,
+ WEATHER_STORM,
+ WEATHER_NONE,
+ type WeatherState,
+ type WeatherPreset,
} from './postprocess/index';
diff --git a/sdk/src/postprocess/PostProcessPlugin.ts b/sdk/src/postprocess/PostProcessPlugin.ts
index ef92ddf24..ed94cb40d 100644
--- a/sdk/src/postprocess/PostProcessPlugin.ts
+++ b/sdk/src/postprocess/PostProcessPlugin.ts
@@ -5,6 +5,7 @@ import { Schedule } from '../ecs/system';
import { Assets } from '../asset/AssetPlugin';
import { PostProcess, PostProcessAPI } from './PostProcessAPI';
import { postProcessVolumeSystem, cleanupVolumeSystem, setVolumeTextureResolver, PostProcessVolumeConfigResource } from './volumeSystem';
+import { weatherSystem, resetWeatherSystem } from './weatherSystem';
export class PostProcessPlugin implements Plugin {
name = 'postProcess';
@@ -23,10 +24,13 @@ export class PostProcessPlugin implements Plugin {
// cache lookup by the time a volume applies.
setVolumeTextureResolver((ref) =>
app.hasResource(Assets) ? (app.getResource(Assets).getTexture(ref)?.handle ?? 0) : 0);
+ // The weather first: the volumes read what it has decided.
+ app.addSystemToSchedule(Schedule.PostUpdate, weatherSystem);
app.addSystemToSchedule(Schedule.PostUpdate, postProcessVolumeSystem);
}
cleanup(app?: App): void {
+ resetWeatherSystem();
if (app?.hasResource(PostProcess)) {
cleanupVolumeSystem(app.getResource(PostProcess));
}
diff --git a/sdk/src/postprocess/index.ts b/sdk/src/postprocess/index.ts
index fff5866a2..a9aa246e5 100644
--- a/sdk/src/postprocess/index.ts
+++ b/sdk/src/postprocess/index.ts
@@ -31,3 +31,19 @@ export {
type PostProcessVolumeConfig,
} from './volumeSystem';
export { PostProcessPlugin, postProcessPlugin } from './PostProcessPlugin';
+export {
+ registerWeatherPreset,
+ weatherPresetId,
+ weatherPresetNames,
+ blendWeather,
+ currentWeather,
+ WeatherDrive,
+ WEATHER_CLEAR,
+ WEATHER_MIST,
+ WEATHER_OVERCAST,
+ WEATHER_RAIN,
+ WEATHER_STORM,
+ WEATHER_NONE,
+ type WeatherState,
+ type WeatherPreset,
+} from './weather';
diff --git a/sdk/src/postprocess/volumeSystem.ts b/sdk/src/postprocess/volumeSystem.ts
index 5649c5b53..27c66b2e5 100644
--- a/sdk/src/postprocess/volumeSystem.ts
+++ b/sdk/src/postprocess/volumeSystem.ts
@@ -10,6 +10,7 @@ import { getEffectDef } from './effects';
import { blendVolumeEffects, computeVolumeFactor, type ActiveVolume, type BlendedEffect, type VolumeTransform } from './volumeBlending';
import type { ShaderHandle } from '../render/material';
import { Material } from '../render/material';
+import { applyWeatherToEffects, currentWeather, currentWeatherDrive } from './weather';
export interface PostProcessVolumeConfig {
enabled: boolean;
@@ -65,6 +66,43 @@ function applyColors(
// skip the whole wasm-boundary rebuild. Keyed by the stack object (auto-cleared
// when the stack is destroyed/GC'd).
const lastEffectSig = new WeakMap<object, string>();
+// And of its SHAPE alone — which effects, which parameters, which textures — so a frame that only moved numbers
+// (a weather in transition, a fading volume) writes them into the passes it has instead of building them again.
+const lastShapeSig = new WeakMap<object, string>();
+
+function shapeSignature(effects: ResolvedEffects): string {
+ let sig = '';
+ for (const [type, data] of effects) {
+ if (!data.enabled) continue;
+ sig += type + ':';
+ for (const k of data.uniforms.keys()) sig += k + ',';
+ sig += '|';
+ for (const [k, ref] of data.textures) sig += k + '=' + ref + ';';
+ sig += '|';
+ for (const k of data.colors.keys()) sig += k + ',';
+ sig += '#';
+ }
+ return sig;
+}
+
+/** The names of the passes an effect becomes: one, or the several a multi-pass effect is made of. */
+function passNamesOf(effectType: string): string[] {
+ const def = getEffectDef(effectType);
+ if (def?.multiPass) return def.multiPass.map((p) => p.name);
+ return [effectType];
+}
+
+function writeValues(stack: ReturnType<PostProcessAPI['createStack']>, effects: ResolvedEffects): void {
+ for (const [effectType, effectData] of effects) {
+ if (!effectData.enabled || !getEffectDef(effectType)) continue;
+ for (const passName of passNamesOf(effectType)) {
+ for (const [uniformName, uniformValue] of effectData.uniforms) {
+ stack.setUniform(passName, uniformName, uniformValue);
+ }
+ applyColors(stack, passName, effectData.colors);
+ }
+ }
+}
/** Stable string of the enabled effects (type + uniforms + textures). */
function effectsSignature(effects: ResolvedEffects): string {
@@ -110,6 +148,14 @@ function applyBlendedEffects(
if (lastEffectSig.get(stack) === sig) return;
lastEffectSig.set(stack, sig);
+ // The same effects with other numbers: write the numbers.
+ const shape = shapeSignature(effects);
+ if (lastShapeSig.get(stack) === shape) {
+ writeValues(stack, effects);
+ return;
+ }
+ lastShapeSig.set(stack, shape);
+
stack.clearPasses();
for (const [effectType, effectData] of effects) {
@@ -179,6 +225,11 @@ export const postProcessVolumeSystem = defineSystem(
? blendVolumeEffects(activeVolumes)
: new Map() as ResolvedEffects;
+ // The weather, if a Weather component is in the scene: scales and tints what the volumes resolved, and
+ // brings the effects a weather implies.
+ const weather = currentWeather();
+ if (weather) applyWeatherToEffects(blended, weather, currentWeatherDrive());
+
applyBlendedEffects(api, cameraEntity, blended);
}
},
diff --git a/sdk/src/postprocess/weather.ts b/sdk/src/postprocess/weather.ts
new file mode 100644
index 000000000..13d0b5c90
--- /dev/null
+++ b/sdk/src/postprocess/weather.ts
@@ -0,0 +1,272 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file weather.ts
+ * @brief What a weather IS — a handful of scales and levels — and how it reaches the picture.
+ *
+ * @details A weather is not a set of effect parameters: a project's fog density is in its own units and its sun is as
+ * bright as its author made it. A preset therefore speaks in MULTIPLIERS of what the scene already says (the sun
+ * at a quarter of its strength, the fog five times as thick) and in a few absolute levels where a number means
+ * the same everywhere (how hard it rains, how wet the ground is). The same preset then fits any scene.
+ *
+ * The state is blended between two presets by a transition's progress, and applied in two places: to the lights
+ * (the component's own, in play mode only — see weatherSystem) and, after the volumes have blended, to the
+ * effects that result.
+ */
+import type { BlendedEffect, Rgba } from './volumeBlending';
+import { getEffectDef } from './effects';
+
+export interface WeatherState {
+ /** × the directional lights' strength. */
+ sun: number;
+ /** × the ambient light's strength. */
+ sky: number;
+ /** × the directional light's colour. */
+ sunTint: [number, number, number];
+ /** × Height Fog's density. */
+ fogDensity: number;
+ /** The colour fog moves toward, and how far (0 = its own colour). */
+ fogTint: [number, number, number];
+ fogTintAmount: number;
+ /** × Height Fog's sun glow and the shafts it carries. */
+ fogGlow: number;
+ /** × Height Fog's sky haze, capped at 1. */
+ skyFog: number;
+ /** × Colour Grade's saturation and contrast. */
+ saturation: number;
+ contrast: number;
+ /** Stops added to Auto Exposure's compensation. */
+ exposure: number;
+ /** The rain effect's strength, and the wetness and puddles it leaves. Absolute. */
+ rain: number;
+ wetness: number;
+ puddles: number;
+ /** × Screen Space Reflections' strength. */
+ ssr: number;
+ /** × what baked reflection probes show, and × their colour (1 keeps it, 0 is grey): a probe was baked under
+ * whatever sky the scene had then. */
+ reflection: number;
+ reflectionSaturation: number;
+ /** How loud the rain on the soundtrack is, 0..2. */
+ sound: number;
+}
+
+export type WeatherPreset = Partial<WeatherState>;
+
+const NEUTRAL: WeatherState = {
+ sun: 1, sky: 1, sunTint: [1, 1, 1],
+ fogDensity: 1, fogTint: [0.7, 0.72, 0.76], fogTintAmount: 0, fogGlow: 1, skyFog: 1,
+ saturation: 1, contrast: 1, exposure: 0,
+ rain: 0, wetness: 0, puddles: 0, ssr: 1,
+ reflection: 1, reflectionSaturation: 1, sound: 0,
+};
+
+/** The presets every project has. Their ids are the dropdown's values, so they only ever grow. */
+export const WEATHER_CLEAR = 0;
+export const WEATHER_MIST = 1;
+export const WEATHER_OVERCAST = 2;
+export const WEATHER_RAIN = 3;
+export const WEATHER_STORM = 4;
+/** What `target` says when there is nothing to move toward. */
+export const WEATHER_NONE = -1;
+
+const registry = new Map<number, { name: string; state: WeatherState }>();
+const byName = new Map<string, number>();
+let nextCustomId = 100;
+
+function fill(preset: WeatherPreset): WeatherState {
+ return {
+ ...NEUTRAL, ...preset,
+ sunTint: preset.sunTint ?? NEUTRAL.sunTint,
+ fogTint: preset.fogTint ?? NEUTRAL.fogTint,
+ };
+}
+
+function define(id: number, name: string, preset: WeatherPreset): void {
+ registry.set(id, { name, state: fill(preset) });
+ byName.set(name, id);
+}
+
+define(WEATHER_CLEAR, 'clear', {});
+define(WEATHER_MIST, 'mist', {
+ sun: 0.45, sky: 0.9, fogDensity: 8, fogTint: [0.86, 0.86, 0.84], fogTintAmount: 0.7, fogGlow: 1.8, skyFog: 1.7,
+ saturation: 0.86, contrast: 0.94, exposure: 0.2, wetness: 0.2, puddles: 0.1, ssr: 1.3, reflection: 0.85,
+ reflectionSaturation: 0.9,
+});
+define(WEATHER_OVERCAST, 'overcast', {
+ sun: 0.25, sky: 0.85, sunTint: [0.9, 0.93, 1], fogDensity: 3, fogTint: [0.62, 0.66, 0.72], fogTintAmount: 0.5,
+ fogGlow: 0.3, skyFog: 1.4, saturation: 0.85, contrast: 0.96, exposure: 0.25, wetness: 0.1, ssr: 1.2,
+ reflection: 0.7, reflectionSaturation: 0.7,
+});
+define(WEATHER_RAIN, 'rain', {
+ sun: 0.04, sky: 0.75, sunTint: [0.8, 0.86, 1], fogDensity: 5.5, fogTint: [0.58, 0.63, 0.7], fogTintAmount: 0.8,
+ fogGlow: 0, skyFog: 1.7, saturation: 0.73, contrast: 0.93, exposure: 0.45, rain: 1.1, wetness: 1, puddles: 0.6,
+ ssr: 2.6, reflection: 0.55, reflectionSaturation: 0.5, sound: 1,
+});
+define(WEATHER_STORM, 'storm', {
+ sun: 0.02, sky: 0.5, sunTint: [0.7, 0.78, 1], fogDensity: 8, fogTint: [0.4, 0.44, 0.5], fogTintAmount: 0.9,
+ fogGlow: 0, skyFog: 1.8, saturation: 0.6, contrast: 0.9, exposure: 0.8, rain: 2.2, wetness: 1, puddles: 1,
+ ssr: 3, reflection: 0.4, reflectionSaturation: 0.35, sound: 1.6,
+});
+
+/**
+ * Adds a weather of the project's own, and returns the id it answers to.
+ *
+ * @details A preset names only what it changes; the rest is neutral. Registering a name again replaces it, so a
+ * project can retune a built-in one. A custom id is for code (`weatherTo`, a component's `preset` value) — the
+ * Inspector's dropdown lists the built-ins.
+ *
+ * @public
+ */
+export function registerWeatherPreset(name: string, preset: WeatherPreset): number {
+ const existing = byName.get(name);
+ const id = existing ?? nextCustomId++;
+ define(id, name, preset);
+ return id;
+}
+
+/** The id a preset answers to, or undefined. @public */
+export function weatherPresetId(name: string): number | undefined {
+ return byName.get(name);
+}
+
+/** Every preset, built-in first. @public */
+export function weatherPresetNames(): string[] {
+ return [...registry.entries()].sort((a, b) => a[0] - b[0]).map(([, v]) => v.name);
+}
+
+const ease = (t: number): number => t * t * (3 - 2 * t);
+
+const mix = (a: number, b: number, t: number): number => a + (b - a) * t;
+
+/**
+ * The weather `progress` of the way from one preset to another, eased so a transition starts and ends gently.
+ *
+ * @public
+ */
+export function blendWeather(from: number, to: number, progress: number): WeatherState {
+ const a = (registry.get(from) ?? registry.get(WEATHER_CLEAR)!).state;
+ if (to === WEATHER_NONE || progress <= 0) return { ...a, sunTint: [...a.sunTint], fogTint: [...a.fogTint] };
+ const b = (registry.get(to) ?? registry.get(WEATHER_CLEAR)!).state;
+ const t = ease(Math.min(Math.max(progress, 0), 1));
+ const out = {} as WeatherState;
+ for (const key of Object.keys(a) as (keyof WeatherState)[]) {
+ const x = a[key];
+ const y = b[key];
+ (out as unknown as Record<string, unknown>)[key] = Array.isArray(x)
+ ? x.map((v, i) => mix(v, (y as number[])[i], t))
+ : mix(x as number, y as number, t);
+ }
+ return out;
+}
+
+// What a Weather component drives. A bit each, so a project can take the fog from the weather and keep its own light.
+export const WeatherDrive = {
+ Lights: 1,
+ Fog: 2,
+ Rain: 4,
+ Grade: 8,
+ Exposure: 16,
+ Reflections: 32,
+ Sound: 64,
+ All: 127,
+} as const;
+
+/** The state the frame is under, or null when no Weather component is. Set by the weather system, read by the volumes. */
+let current: { state: WeatherState; drive: number } | null = null;
+
+export function setCurrentWeather(state: WeatherState | null, drive: number = WeatherDrive.All): void {
+ current = state ? { state, drive } : null;
+}
+
+/** @public */
+export function currentWeather(): WeatherState | null {
+ return current ? current.state : null;
+}
+
+/** The bits of {@link WeatherDrive} the current weather has been asked to apply. */
+export function currentWeatherDrive(): number {
+ return current ? current.drive : 0;
+}
+
+/** What an effect's uniform is now: the scene's word if it said one, the effect's own default if it did not. */
+function value(effect: BlendedEffect, type: string, name: string, fallback = 0): number {
+ const set = effect.uniforms.get(name);
+ if (set !== undefined) return set;
+ return getEffectDef(type)?.uniforms.find((u) => u.name === name)?.defaultValue ?? fallback;
+}
+
+function entry(effects: Map<string, BlendedEffect>, type: string): BlendedEffect {
+ let e = effects.get(type);
+ if (!e) {
+ e = { enabled: true, uniforms: new Map(), textures: new Map(), colors: new Map() };
+ effects.set(type, e);
+ }
+ return e;
+}
+
+const towards = (c: Rgba, tint: [number, number, number], amount: number): Rgba => ({
+ r: c.r * (1 - amount) + tint[0] * amount,
+ g: c.g * (1 - amount) + tint[1] * amount,
+ b: c.b * (1 - amount) + tint[2] * amount,
+ a: c.a,
+});
+
+/**
+ * Applies the weather to what the volumes blended: the effects the scene authored are scaled and tinted, and the
+ * ones a weather brings with it (rain, and the grade a weather implies) are added when the scene has none.
+ *
+ * @details Multipliers act on whatever the scene resolved — the authored density, the authored saturation — so a scene
+ * that fogs itself thinly stays thinner than one that fogs itself thickly in the same rain.
+ */
+export function applyWeatherToEffects(effects: Map<string, BlendedEffect>, state: WeatherState, drive: number): void {
+ if (drive & WeatherDrive.Fog) {
+ const fog = effects.get('heightFog');
+ if (fog && fog.enabled) {
+ fog.uniforms.set('u_density', value(fog, 'heightFog', 'u_density') * state.fogDensity);
+ fog.uniforms.set('u_inscatter', value(fog, 'heightFog', 'u_inscatter') * state.fogGlow);
+ fog.uniforms.set('u_volumetric', value(fog, 'heightFog', 'u_volumetric') * state.fogGlow);
+ fog.uniforms.set('u_skyFog', Math.min(value(fog, 'heightFog', 'u_skyFog') * state.skyFog, 1));
+ const colour = fog.colors.get('u_fogColor')
+ ?? getEffectDef('heightFog')?.colors?.find((c) => c.name === 'u_fogColor')?.defaultValue;
+ if (colour && state.fogTintAmount > 0) fog.colors.set('u_fogColor', towards(colour, state.fogTint, state.fogTintAmount));
+ }
+ }
+ if (drive & WeatherDrive.Rain) {
+ if (state.rain > 0.001 || state.wetness > 0.001) {
+ // A rain the scene authored is a floor the weather rises above; one the weather brings is exactly its own.
+ const authored = effects.has('rain');
+ const rain = entry(effects, 'rain');
+ const pick = (name: string, level: number): number => authored ? Math.max(value(rain, 'rain', name), level) : level;
+ rain.uniforms.set('u_intensity', pick('u_intensity', state.rain));
+ rain.uniforms.set('u_wetness', pick('u_wetness', state.wetness));
+ rain.uniforms.set('u_puddles', pick('u_puddles', state.puddles));
+ }
+ const ssr = effects.get('ssr');
+ if (ssr && ssr.enabled) {
+ ssr.uniforms.set('u_intensity', value(ssr, 'ssr', 'u_intensity') * state.ssr);
+ ssr.uniforms.set('u_wetness', Math.max(value(ssr, 'ssr', 'u_wetness'), state.wetness));
+ ssr.uniforms.set('u_puddles', Math.max(value(ssr, 'ssr', 'u_puddles'), state.puddles));
+ }
+ }
+ if (drive & WeatherDrive.Grade) {
+ const neutral = Math.abs(state.saturation - 1) < 1e-3 && Math.abs(state.contrast - 1) < 1e-3;
+ const grade = effects.get('colorGrade');
+ if (grade && grade.enabled) {
+ grade.uniforms.set('u_saturation', value(grade, 'colorGrade', 'u_saturation', 1) * state.saturation);
+ grade.uniforms.set('u_contrast', value(grade, 'colorGrade', 'u_contrast', 1) * state.contrast);
+ } else if (!neutral) {
+ const added = entry(effects, 'colorGrade');
+ added.uniforms.set('u_saturation', state.saturation);
+ added.uniforms.set('u_contrast', state.contrast);
+ }
+ }
+ if (drive & WeatherDrive.Exposure) {
+ const ae = effects.get('autoExposure');
+ if (ae && ae.enabled) ae.uniforms.set('u_bias', value(ae, 'autoExposure', 'u_bias') + state.exposure);
+ else if (Math.abs(state.exposure) > 1e-3) {
+ const grade = effects.get('colorGrade');
+ if (grade && grade.enabled) grade.uniforms.set('u_exposure', value(grade, 'colorGrade', 'u_exposure') + state.exposure);
+ }
+ }
+}
diff --git a/sdk/src/postprocess/weatherSystem.ts b/sdk/src/postprocess/weatherSystem.ts
new file mode 100644
index 000000000..40bb9c0ee
--- /dev/null
+++ b/sdk/src/postprocess/weatherSystem.ts
@@ -0,0 +1,138 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file weatherSystem.ts
+ * @brief Runs the scene's Weather: advances its turns and cycle, and puts it on the lights.
+ *
+ * @details Only the lights are written to — the effects are read from `currentWeather()` by the volume system a step later,
+ * which is what lets the editor preview the post-process half of a weather without the scene's own lights being
+ * changed (and saved) by it. The lights are rewritten only in play mode, from the strengths they were authored
+ * with, and put back when the weather goes.
+ */
+import { defineSystem } from '../ecs/system';
+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 type { World } from '../ecs/world';
+import type { Entity } from '../types';
+import { isEditor, isPlayMode } from '../ecs/env';
+import {
+ blendWeather, setCurrentWeather, weatherPresetId, WEATHER_NONE, WeatherDrive, type WeatherState,
+} from './weather';
+
+/** What a light was authored with, kept so a weather scales the author's number and never its own last answer. */
+interface LightBase {
+ intensity: number;
+ color: { r: number; g: number; b: number; a: number };
+ applied: number;
+}
+
+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 }>();
+
+const LIGHT_DIRECTIONAL = 1;
+const LIGHT_AMBIENT = 2;
+
+function restoreLights(world: World): void {
+ for (const [entity, base] of bases) {
+ if (world.has(entity, Light)) {
+ const data = world.get(entity, Light) as LightData;
+ world.set(entity, Light, { ...data, intensity: base.intensity, color: { ...base.color } });
+ }
+ }
+ bases.clear();
+}
+
+function applyLights(world: World, state: WeatherState): void {
+ for (const entity of world.getEntitiesWithComponents([Light])) {
+ const data = world.get(entity, Light) as LightData;
+ if (data.type !== LIGHT_DIRECTIONAL && data.type !== LIGHT_AMBIENT) continue;
+ let base = bases.get(entity);
+ if (!base) {
+ base = { intensity: data.intensity, color: { ...data.color }, applied: Number.NaN };
+ bases.set(entity, base);
+ }
+ const sun = data.type === LIGHT_DIRECTIONAL;
+ const scale = sun ? state.sun : state.sky;
+ // The key is what the light would be told: nothing is written for a frame that would say the same again.
+ const key = scale + (sun ? state.sunTint[0] * 7 + state.sunTint[1] * 13 + state.sunTint[2] * 29 : 0);
+ if (base.applied === key) continue;
+ base.applied = key;
+ const color = sun
+ ? { r: base.color.r * state.sunTint[0], g: base.color.g * state.sunTint[1], b: base.color.b * state.sunTint[2], a: base.color.a }
+ : { ...base.color };
+ world.set(entity, Light, { ...data, intensity: base.intensity * scale, color });
+ }
+}
+
+/** The preset a name or an id in a sequence stands for. */
+function presetOf(token: string): number | undefined {
+ const trimmed = token.trim();
+ if (trimmed === '') return undefined;
+ const named = weatherPresetId(trimmed.toLowerCase());
+ if (named !== undefined) return named;
+ const n = Number(trimmed);
+ return Number.isFinite(n) ? n : undefined;
+}
+
+function advance(entity: Entity, data: WeatherData, dt: number): void {
+ if (data.target !== WEATHER_NONE) {
+ data.progress += dt / Math.max(data.duration, 0.01);
+ if (data.progress >= 1) {
+ data.preset = data.target;
+ data.target = WEATHER_NONE;
+ data.progress = 0;
+ }
+ return;
+ }
+ if (!data.sequence) return;
+ const list = data.sequence.split(',').map(presetOf).filter((v): v is number => v !== undefined);
+ if (list.length < 2) return;
+ let cycle = cycles.get(entity);
+ if (!cycle) {
+ // Joins the sequence where the scene is: the first entry that is the weather now, else the start.
+ const at = list.indexOf(data.preset);
+ cycle = { index: at < 0 ? 0 : at, held: 0 };
+ cycles.set(entity, cycle);
+ }
+ cycle.held += dt;
+ if (cycle.held < data.hold) return;
+ cycle.held = 0;
+ cycle.index = (cycle.index + 1) % list.length;
+ data.target = list[cycle.index];
+ data.progress = 0;
+}
+
+export const weatherSystem = defineSystem(
+ [Query(Mut(Weather)), Res(Time), GetWorld()],
+ (weathers: Iterable<[Entity, WeatherData]>, time: TimeData, world: World) => {
+ let found: [Entity, WeatherData] | null = null;
+ for (const entry of weathers) { found = entry; break; }
+ if (!found) {
+ if (bases.size > 0) restoreLights(world);
+ cycles.clear();
+ setCurrentWeather(null);
+ return;
+ }
+ const [entity, data] = found;
+ const playing = !isEditor() || isPlayMode();
+ if (playing) advance(entity, data, time.delta);
+
+ const state = blendWeather(data.preset, data.target, data.progress);
+ setCurrentWeather(state, data.drive);
+
+ if (playing && (data.drive & WeatherDrive.Lights)) applyLights(world, state);
+ else if (bases.size > 0) restoreLights(world);
+ },
+ { name: 'WeatherSystem' }
+);
+
+/** Forgets what the system remembers: a device loss, a test, an app shut down. */
+export function resetWeatherSystem(): void {
+ bases.clear();
+ cycles.clear();
+ setCurrentWeather(null);
+}
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
index 4345cd045..03e6241c5 100644
--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -1516,5 +1516,108 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"tooltip": "Local scale per axis (1 = original size; negative flips).",
},
},
+ "Weather": {
+ "drive": {
+ "flags": [
+ {
+ "label": "Lights",
+ "value": 1,
+ },
+ {
+ "label": "Fog",
+ "value": 2,
+ },
+ {
+ "label": "Rain",
+ "value": 4,
+ },
+ {
+ "label": "Grade",
+ "value": 8,
+ },
+ {
+ "label": "Exposure",
+ "value": 16,
+ },
+ {
+ "label": "Reflections",
+ "value": 32,
+ },
+ {
+ "label": "Sound",
+ "value": 64,
+ },
+ ],
+ },
+ "duration": {
+ "max": 600,
+ "min": 0.1,
+ "step": 0.1,
+ "unit": "s",
+ },
+ "hold": {
+ "max": 3600,
+ "min": 0,
+ "step": 1,
+ "unit": "s",
+ },
+ "preset": {
+ "enum": [
+ {
+ "label": "Clear",
+ "value": 0,
+ },
+ {
+ "label": "Mist",
+ "value": 1,
+ },
+ {
+ "label": "Overcast",
+ "value": 2,
+ },
+ {
+ "label": "Rain",
+ "value": 3,
+ },
+ {
+ "label": "Storm",
+ "value": 4,
+ },
+ ],
+ },
+ "progress": {
+ "max": 1,
+ "min": 0,
+ "step": 0.01,
+ },
+ "target": {
+ "enum": [
+ {
+ "label": "None",
+ "value": -1,
+ },
+ {
+ "label": "Clear",
+ "value": 0,
+ },
+ {
+ "label": "Mist",
+ "value": 1,
+ },
+ {
+ "label": "Overcast",
+ "value": 2,
+ },
+ {
+ "label": "Rain",
+ "value": 3,
+ },
+ {
+ "label": "Storm",
+ "value": 4,
+ },
+ ],
+ },
+ },
}
`;
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 4937fa18c..67dbe6765 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2493,6 +2493,8 @@ export const NOTED = {
{"note":"Skinned meshes are followed by their bones, from the palette they were last drawn with."},
"feat(render): fog follows the scene's sun and can walk the air against its shadow map":
{"note":"Height Fog and Light Shafts follow the scene's own sun, and Height Fog can carry the sun's shadows as volumetric light."},
+ "feat(runtime): a Weather component puts a scene under a preset, turns between presets and cycles through a sequence":
+ {"note":"A Weather component puts a scene under clear, mist, overcast, rain or storm, turns between them and cycles by itself."},
"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."},
};