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(water): quality levels set the waves, ripples, mirror and caustics water spends, and the low level is a lite water with flat geometry

yhhcbed33a26f4b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index de93f323a..ad80e7da2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ published separately; it ships inside the editor.
- **Contact shadows and screen-space bounce light.** Contact Shadows and Screen Space GI effects add small sharp shadows at contacts and one bounce of colour between surfaces, and the weather softens the sun's shadows. `contactShadows` marches a short ray toward the scene's sun in the depth buffer; `ssgi` gathers eight rays a pixel over the G-buffer's normals at half size into a float target and averages the neighbours on the same surface before laying the light, times the receiver's colour, over the picture. The Weather component raises the sun's `sourceAngle` and lowers its `shadowStrength` as the sky clouds over.
- **Terrain and Foliage.** A Terrain component makes ground from a heightmap or noise, paints it with grass, dirt, snow and rock layers and draws it in chunks that coarsen with distance; a Foliage component scatters grass or a mesh over it, swaying in the wind and thinning out with distance.
- **Separate material maps packed on import.** Importing an FBX with separate metalness, roughness and occlusion images now packs them into the one map the Model shader samples, instead of dropping them. Occlusion goes in red, roughness in green and metal in blue, each from its image's red channel (a glossiness map is inverted); a channel with no image stays at full so the material's own value speaks. Only PNG and DDS can be read.
+- **Water quality levels and a lite water.** Water spends what the quality level allows. Each level's profile has `waterWaves` (waves summed, 2 / 3 / 4), `waterRippleCells` (the ripple grid's side, 32 / 64 / 128), `waterDisplacement` (off is the lite water: flat geometry with the waves in the shading only), `waterMirror` and `waterCaustics`. What `Waters.sample` answers follows what is drawn, and a minigame with no quality policy gets the Low level's water.
- **Move gizmo plane handles closer in.** The three plane handles of the move gizmo sit closer to its centre, on the inside corner between each pair of axes, instead of out at a third of the way along them.
- **Water editing in the viewport.** Select a lake or a river and its points are handles in the viewport: drag a point to move it on the body's own plane, drag the circle on an edge to insert one, press and release a point to delete it (a lake keeps three, a river two), and drag the handle beside a river's point to set its width there. Each gesture is one undo step. Details shows a water body only the fields its form uses, with a Boundary row for a lake's outline and the point count and the pressed point's width under a Spline. Also: the move gizmo now travels with the entity while an axis is dragged, instead of staying where the grab began.
- **Blended surfaces ordered against water.** A blended surface (a pane, a particle, a leaf card) is now ordered against water and glass by the pixel and not by when it was drawn: one under the surface is seen through the water, one in front of it lies on the water instead of being covered, and where there is no water it is blended once. The frame is drawn in layers only when it holds both a refracting surface and a blended draw.
diff --git a/desktop b/desktop
index 4878c2acb..5214b1553 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 4878c2acb33ae573f0774acd280f17d67075cfbb
+Subproject commit 5214b155343b8339b9a20611674e64a46ceca8d5
diff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdx
index b6509cfd2..93f7a5113 100644
--- a/docs/astro/src/content/docs/graphics/water.mdx
+++ b/docs/astro/src/content/docs/graphics/water.mdx
@@ -173,6 +173,22 @@ Select a lake or a river and its points are handles in the viewport, the way a p
points. The point last pressed shows its width in Details under the Spline, where it can be typed.
- Each gesture is one undo step, and the points are written back as they are dragged, so the water follows. The handles are the **Water** entry of the Gizmo menu.
+## Quality levels
+
+Water spends what the project's quality level says it may. The five fields are in each level's profile (`project.esproject`, `features.rendering.quality.profiles`), and a project can change what a level means:
+
+| Field | Low | Medium | High | What it does |
+|---|---|---|---|---|
+| `waterWaves` | 2 | 3 | 4 | How many of the four waves are summed: in the geometry, the shading, and what `Waters.sample` answers. |
+| `waterRippleCells` | 32 | 64 | 128 | The most cells along a side of the ripple grid; a body's own `ripples` is held to it, and 0 keeps none. |
+| `waterDisplacement` | off | on | on | Whether the waves lift the geometry. Off is the **lite water**: a flat surface whose waves are in the shading only. |
+| `waterMirror` | off | on | on | Whether the surface seen from below mirrors the world under it (the screen-space march). |
+| `waterCaustics` | off | on | on | Whether the sun's web of light is drawn on what lies under the water, and, seen from under it, the shafts. |
+
+What code reads follows what is drawn: at a level without displacement the surface is flat for `Waters.sample`, floating things sit on the rest plane, and fewer waves is fewer
+waves for both. With a quality policy running, the active level decides; with none, a **minigame** gets the Low profile's water (the least it has to spend), and anything else gets all of it.
+The lite water costs no vertex work for the waves, and the shading still moves, so it reads as water at a distance.
+
## Asking the surface
`Waters.sample(x, y, z)` (the `WatersRes` resource) answers for the body that holds a point:
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
index e9420f6b7..a430441da 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
@@ -116,6 +116,20 @@ Details 只显示水体这种形态用得到的字段:湖有尺寸、边界和
- **河。** 在它的 `Spline` 曲线上同样操作,每个点上还有第二个手柄,沿河的横向偏出宽度的一半:拖动它来设置那里的宽度。河至少保留两个点。最后按下的点,会在 Details 的 Spline 下显示它的宽度,可以直接输入。
- 每次手势是一步撤销,点是边拖边写回的,所以水会跟着变。这些手柄是 Gizmo 菜单里的 **Water** 一项。
+## 画质档位
+
+水只花项目画质档位允许它花的。五个字段在每个档位的配置里(`project.esproject`,`features.rendering.quality.profiles`),项目可以改变一个档位的含义:
+
+| 字段 | 低 | 中 | 高 | 作用 |
+|---|---|---|---|---|
+| `waterWaves` | 2 | 3 | 4 | 四道波里累加几道:几何、着色以及 `Waters.sample` 的回答都按它。 |
+| `waterRippleCells` | 32 | 64 | 128 | 涟漪网格每边最多多少格;水体自己的 `ripples` 会被限制到它,0 表示不保留。 |
+| `waterDisplacement` | 关 | 开 | 开 | 波浪是否抬起几何体。关就是**轻量水**:平的表面,波浪只在着色里。 |
+| `waterMirror` | 关 | 开 | 开 | 从下面看水面时,是否映出它下面的世界(屏幕空间步进)。 |
+| `waterCaustics` | 关 | 开 | 开 | 阳光的光网是否画在水下的东西上,以及从水下看时的光束。 |
+
+代码读到的跟画出来的一致:没有位移的档位里,`Waters.sample` 看到的是平面,漂浮物停在静止平面上,波数少对两者同样生效。有画质策略运行时由当前档位决定;没有时,**小游戏**得到低档的水(它能花的最少),其他情况得到全部。轻量水不为波浪做任何顶点计算,着色仍然在动,所以远看仍是水。
+
## 查询表面
`Waters.sample(x, y, z)`(资源 `WatersRes`)为包含这个点的水体作答:
diff --git a/sdk/src/postprocess/underwater.ts b/sdk/src/postprocess/underwater.ts
index 420ca61f5..3c5893658 100644
--- a/sdk/src/postprocess/underwater.ts
+++ b/sdk/src/postprocess/underwater.ts
@@ -34,6 +34,8 @@ export interface UnderwaterState {
causticStrength: number;
causticScale: number;
causticSpeed: number;
+ /** Whether the sun's light is drawn through the water (the web on what is seen, the shafts). The quality level turns it off; absent is on. */
+ light?: boolean;
}
let current: UnderwaterState | null = null;
@@ -70,6 +72,10 @@ export function applyUnderwaterToEffects(effects: Map<string, BlendedEffect>, st
effect.uniforms.set('u_causticScale', state.causticScale);
effect.uniforms.set('u_causticSpeed', state.causticSpeed);
}
+ if (state.light === false) {
+ effect.uniforms.set('u_causticStrength', 0);
+ effect.uniforms.set('u_shaftStrength', 0);
+ }
effect.uniforms.set('u_amount', Math.min(Math.max(state.amount, 0), 1) * (effect.uniforms.get('u_amount') ?? 1));
effect.uniforms.set('u_cameraDepth', state.depth);
effect.uniforms.set('u_planeNx', state.plane[0]);
diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.ts
index 6816a8134..db37b8a9f 100644
--- a/sdk/src/render/builtinShaders.ts
+++ b/sdk/src/render/builtinShaders.ts
@@ -751,6 +751,11 @@ const WATER = `#pragma shader "Water"
#pragma param u_causticStrength float default(0.6) range(0,3) ui(slider)
#pragma param u_causticScale float default(2) range(0.05,2000) ui(slider)
#pragma param u_causticSpeed float default(0.35) range(0,4) ui(slider)
+// What the quality level allows (the WaterBody component writes these): how many of the four waves are summed, whether the surface seen from below mirrors the world under it,
+// and whether the sun's web of light is drawn on what lies under the water.
+#pragma param u_waveCount float default(4) range(1,4) ui(slider)
+#pragma param u_mirror float default(1) range(0,1) ui(slider)
+#pragma param u_causticOn float default(1) range(0,1) ui(slider)
// The disturbance the water keeps (WaterBody ripples): a window of the body's xz plane, red the height of the ripples (0.5 at rest, u_rippleRange above or below at 1 and 0)
// and green the foam they left, as the CPU stepped them. u_rippleSize is the window's side, u_rippleTexel one texel of it.
#pragma param u_rippleOn float default(0) range(0,1) ui(slider)
@@ -770,6 +775,7 @@ float waterWaveHeight(vec2 p, float time, float cell) {
float height = 0.0;
float base = radians(u_waveDirection);
for (int i = 0; i < 4; ++i) {
+ if (float(i) >= u_waveCount) break;
float length_ = u_waveLength * SET[i].y;
float k = 6.2831853 / length_;
float a = base + radians(SET[i].x);
@@ -794,6 +800,7 @@ fn waterWaveHeight(p : vec2f, time : f32, cell : f32) -> f32 {
var height = 0.0;
let base = radians(mc.u_waveDirection);
for (var i : i32 = 0; i < 4; i = i + 1) {
+ if (f32(i) >= mc.u_waveCount) { break; }
let spec = wave[i];
let span = mc.u_waveLength * spec.y;
let k = 6.2831853 / span;
@@ -868,6 +875,7 @@ vec2 waveSlope(vec2 p, float time, float dist, out float crest) {
float weightSum = 0.0;
float base = radians(u_waveDirection);
for (int i = 0; i < 4; ++i) {
+ if (float(i) >= u_waveCount) break;
float length_ = u_waveLength * SET[i].y;
float k = 6.2831853 / length_;
float a = base + radians(SET[i].x);
@@ -1044,7 +1052,7 @@ void main() {
behind = texture(u_sceneColor, uv1).rgb;
column = max(dist1 - waterDist, 0.0);
// The sun through the waves lights what is under them in a web of bright threads, where the sun reaches it and as much as the water between lets through.
- if (!below && haveDepth && u_causticStrength > 0.0) {
+ if (!below && haveDepth && u_causticStrength > 0.0 && u_causticOn > 0.5) {
vec4 sunDir, sunColor;
ivec2 sunTiles;
waterSun(sunDir, sunColor, sunTiles);
@@ -1096,7 +1104,7 @@ void main() {
vec3 seen = behind * transmit * (1.0 - fresnel) * (1.0 - foam);
// From below the water is a mirror past the critical angle, and what it mirrors is the world under it: the picture, followed along the reflected ray.
vec3 mirror = vec3(0.0);
- if (below && fresnel > 0.02 && haveColor && haveDepth) {
+ if (below && fresnel > 0.02 && haveColor && haveDepth && u_mirror > 0.5) {
vec4 met = waterReflect(P, reflect(-viewDir, N), waterDist);
mirror = met.a > 0.5 ? met.rgb : mix(u_shallowColor.rgb, u_deepColor.rgb, 0.5) * 0.25;
}
@@ -1152,6 +1160,7 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {
var weightSum = 0.0;
let base = radians(mc.u_waveDirection);
for (var i : i32 = 0; i < 4; i = i + 1) {
+ if (f32(i) >= mc.u_waveCount) { break; }
let spec = wave[i];
let span = mc.u_waveLength * spec.y;
let k = 6.2831853 / span;
@@ -1336,7 +1345,7 @@ fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {
if (dist1 < waterDist) { uv1 = clamp(uv0, vec2f(0.001), vec2f(0.999)); dist1 = behindDist; }
behind = textureSampleLevel(u_sceneColor, u_sceneColor_s, uv1, 0.0).rgb;
column = max(dist1 - waterDist, 0.0);
- if (!below && haveDepth && mc.u_causticStrength > 0.0) {
+ if (!below && haveDepth && mc.u_causticStrength > 0.0 && mc.u_causticOn > 0.5) {
let sun = waterSun();
let cosUp = dot(sun.dir.xyz, Ngeo);
if (sun.dir.w > 0.5 && cosUp > 0.05) {
@@ -1382,7 +1391,7 @@ fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {
}
var seen = behind * transmit * (1.0 - fresnel) * (1.0 - foam);
var mirror = vec3f(0.0);
- if (below && fresnel > 0.02 && haveColor && haveDepth) {
+ if (below && fresnel > 0.02 && haveColor && haveDepth && mc.u_mirror > 0.5) {
let met = waterReflect(P, reflect(-viewDir, N), waterDist);
if (met.w > 0.5) { mirror = met.xyz; } else { mirror = mix(mc.u_shallowColor.rgb, mc.u_deepColor.rgb, vec3f(0.5)) * 0.25; }
}
diff --git a/sdk/src/render/quality.ts b/sdk/src/render/quality.ts
index f1af28ad3..b9ed4514d 100644
--- a/sdk/src/render/quality.ts
+++ b/sdk/src/render/quality.ts
@@ -26,6 +26,16 @@ export interface QualityProfile {
planarReflectionUpdatesPerSecond: number;
postProcess: boolean;
ssao: boolean;
+ /** How many of a body of water's four waves are summed: in the geometry, the shading and what the surface answers for code. 1 to 4. */
+ waterWaves: number;
+ /** The most cells along a side of the ripple grid a body of water keeps; the body's own `ripples` is held to it. 0 keeps none. */
+ waterRippleCells: number;
+ /** Whether the waves lift the water's geometry. Off is the lite water: a flat surface whose waves are in the shading only, and which code reads as flat. */
+ waterDisplacement: boolean;
+ /** Whether the surface seen from below mirrors the world under it (a screen-space march per pixel). */
+ waterMirror: boolean;
+ /** Whether the sun's web of light is drawn on what is under the water, and through the surface as shafts. */
+ waterCaustics: boolean;
/**
* Post-process effects this level leaves out, each named by its effect type (`ssr`, `taa`, `depthOfField`,
* `lightShafts`, `autoExposure` …), compared without regard to case. An effect is all of its passes: a
@@ -60,6 +70,7 @@ const PROFILES: Record<QualityLevel, QualityProfile> = {
shadowAtlasSize: 1024, shadowCellSize: 256, shadowCascades: 2,
planarReflectionScale: 0.25, planarReflectionMaxSize: 512, planarReflectionUpdatesPerSecond: 0,
shadowDistance: 0, particleLimit: 1000, postProcess: true, ssao: false,
+ waterWaves: 2, waterRippleCells: 32, waterDisplacement: false, waterMirror: false, waterCaustics: false,
skipEffects: ['ssr', 'taa', 'depthOfField', 'lightShafts', 'motionBlur', 'lensFlare', 'gtao', 'subsurface', 'voxelGI'],
},
medium: {
@@ -67,6 +78,7 @@ const PROFILES: Record<QualityLevel, QualityProfile> = {
shadowAtlasSize: 2048, shadowCellSize: 512, shadowCascades: 3,
planarReflectionScale: 0.5, planarReflectionMaxSize: 1024, planarReflectionUpdatesPerSecond: 0,
shadowDistance: 0, particleLimit: 5000, postProcess: true, ssao: true,
+ waterWaves: 3, waterRippleCells: 64, waterDisplacement: true, waterMirror: true, waterCaustics: true,
skipEffects: ['ssr', 'depthOfField'],
},
high: {
@@ -74,6 +86,7 @@ const PROFILES: Record<QualityLevel, QualityProfile> = {
shadowAtlasSize: 2048, shadowCellSize: 512, shadowCascades: 4,
planarReflectionScale: 1, planarReflectionMaxSize: 2048, planarReflectionUpdatesPerSecond: 0,
shadowDistance: 0, particleLimit: 20000, postProcess: true, ssao: true,
+ waterWaves: 4, waterRippleCells: 128, waterDisplacement: true, waterMirror: true, waterCaustics: true,
skipEffects: [],
},
};
@@ -147,6 +160,11 @@ function resolveProfile(level: QualityLevel, value: unknown): QualityProfile {
planarReflectionUpdatesPerSecond: finite(r.planarReflectionUpdatesPerSecond, base.planarReflectionUpdatesPerSecond, 0, 120),
postProcess: typeof r.postProcess === 'boolean' ? r.postProcess : base.postProcess,
ssao: typeof r.ssao === 'boolean' ? r.ssao : base.ssao,
+ waterWaves: Math.round(finite(r.waterWaves, base.waterWaves, 1, 4)),
+ waterRippleCells: Math.round(finite(r.waterRippleCells, base.waterRippleCells, 0, 256)),
+ waterDisplacement: typeof r.waterDisplacement === 'boolean' ? r.waterDisplacement : base.waterDisplacement,
+ waterMirror: typeof r.waterMirror === 'boolean' ? r.waterMirror : base.waterMirror,
+ waterCaustics: typeof r.waterCaustics === 'boolean' ? r.waterCaustics : base.waterCaustics,
skipEffects: Array.isArray(r.skipEffects)
? r.skipEffects.filter((e): e is string => typeof e === 'string' && e.trim() !== '')
.map((e) => e.trim()).slice(0, 32)
diff --git a/sdk/src/water/underwater.ts b/sdk/src/water/underwater.ts
index db4c107ab..457c05b71 100644
--- a/sdk/src/water/underwater.ts
+++ b/sdk/src/water/underwater.ts
@@ -324,6 +324,7 @@ export class UnderwaterPlugin implements Plugin {
causticStrength: single(instance, 'u_causticStrength', 0.6),
causticScale: single(instance, 'u_causticScale', 2),
causticSpeed: single(instance, 'u_causticSpeed', 0.35),
+ light: waters.quality.caustics,
});
}, { name: 'UnderwaterSystem' }));
}
diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.ts
index 1a6b79ebf..590954e3a 100644
--- a/sdk/src/water/waterPlugin.ts
+++ b/sdk/src/water/waterPlugin.ts
@@ -37,6 +37,9 @@ import { buildRiverMesh, currentShare } from './riverMesh';
import { Spline, type SplineData } from '../spline/splinePlugin';
import { SplineCurve } from '../spline/curve';
import { RippleField } from './ripples';
+import { Quality } from '../render/qualityRuntime';
+import { defaultQualityProfile, type QualityProfile } from '../render/quality';
+import { isMiniGame } from '../platform';
/** What a body of water is. A river follows the `Spline` on its own entity. */
export const WaterForm = { Ocean: 0, Lake: 1, River: 2 } as const;
@@ -124,6 +127,28 @@ export interface WaterSample {
inside: boolean;
}
+/** What the quality level lets water spend: waves summed, the ripple grid's side, whether waves lift the geometry, the mirror from below, the sun's light through it. */
+export interface WaterQuality {
+ waves: number;
+ rippleCells: number;
+ displacement: boolean;
+ mirror: boolean;
+ caustics: boolean;
+}
+
+/** Everything on: a project with no quality policy, off a minigame. */
+export const FULL_WATER: WaterQuality = { waves: 4, rippleCells: 256, displacement: true, mirror: true, caustics: true };
+
+/**
+ * What water is allowed: the active quality profile when the project has a quality policy running; else the low profile on a minigame, which has the least to spend and
+ * gets the lite water (flat geometry, no mirror, no web of light) without anyone asking; else everything.
+ */
+export function waterQualityOf(profile: Readonly<QualityProfile> | null, miniGame: boolean): WaterQuality {
+ const p = profile ?? (miniGame ? defaultQualityProfile('low') : null);
+ if (!p) return FULL_WATER;
+ return { waves: p.waterWaves, rippleCells: p.waterRippleCells, displacement: p.waterDisplacement, mirror: p.waterMirror, caustics: p.waterCaustics };
+}
+
/** What the plugin knows about one body it has built. */
interface Built {
signature: string;
@@ -149,6 +174,8 @@ interface Built {
export class Waters {
/** @internal */ readonly built_ = new Map<Entity, Built>();
/** @internal */ app_: App | null = null;
+ /** What the quality level allows now; the plugin refreshes it each frame, and what is drawn and what is answered both follow it. */
+ quality: WaterQuality = FULL_WATER;
/**
* The surface of the body that holds `(x, y, z)`: how far above it the point is (negative under), the surface's normal and the point on
@@ -184,10 +211,11 @@ export class Waters {
}
const inside = d.form === WaterForm.Ocean || (field ? field.inside(q[0], q[2]) : false);
if (!inside) continue;
- const params = paramsOf(d);
+ const params = { ...paramsOf(d), count: this.quality.waves };
// The waves a lake keeps toward its shore are the ones its mesh was built with.
const damp = field ? field.damp(q[0], q[2]) : 1;
- const h = waveHeight(params, q[0], q[2], time) * damp + (built.ripples ? built.ripples.heightAt(q[0], q[2]) : 0);
+ // The lite water is flat: its waves are in the shading, so the height code reads is the rest plane's.
+ const h = (this.quality.displacement ? waveHeight(params, q[0], q[2], time) * damp : 0) + (built.ripples ? built.ripples.heightAt(q[0], q[2]) : 0);
const [rx, rz] = waveSlope(params, q[0], q[2], time);
const sx = rx * damp, sz = rz * damp;
const len = Math.hypot(sx, 1, sz);
@@ -295,13 +323,19 @@ export class WaterPlugin implements Plugin {
private stock_ = 0;
private stockPending_ = false;
+ /** The resource this plugin installed, for the parts of it that read the quality level. */
+ private waters_: Waters = new Waters();
+
build(app: App): void {
const waters = new Waters();
+ this.waters_ = waters;
waters.app_ = app;
app.insertResource(WatersRes, waters);
app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {
this.sweep(app, waters);
+ const policy = app.hasResource(Quality) ? app.getResource(Quality) : null;
+ waters.quality = waterQualityOf(policy && policy.enabled ? policy.profile : null, isMiniGame());
// What a body IS (its outline and shore, its curve) needs no renderer: it is built here whether or not anything is drawn, so a
// server or a test that never draws can still ask the surface where it is. What is DRAWN waits for the asset layer.
const rendering = app.hasResource(Assets);
@@ -471,8 +505,9 @@ export class WaterPlugin implements Plugin {
*/
private ripple(app: App, entity: Entity, built: Built, eye: [number, number, number] | null, dt: number): void {
const d = built.data;
- if (d.ripples <= 0) { this.dropRipples(built); return; }
- const n = Math.max(8, Math.floor(d.ripples)), size = Math.max(d.rippleSize, 1e-3);
+ if (d.ripples <= 0 || this.waters_.quality.rippleCells <= 0) { this.dropRipples(built); return; }
+ // The level holds the grid to its own side; a body that asks for more gets the level's.
+ const n = Math.max(8, Math.floor(Math.min(d.ripples, this.waters_.quality.rippleCells))), size = Math.max(d.rippleSize, 1e-3);
if (!built.ripples || built.ripples.n !== n || built.ripples.size !== size) {
this.dropRipples(built);
built.ripples = new RippleField(n, size);
@@ -544,11 +579,15 @@ export class WaterPlugin implements Plugin {
app.world.insert(built.child, Transform, { ...child, position: { x: ox, y: 0, z: oz } });
}
const set = (name: string, value: number | { x: number; y: number }): void => { Material.setUniform(built.instance, name, value); };
+ const q = this.waters_.quality;
+ set('u_waveCount', q.waves);
+ set('u_mirror', q.mirror ? 1 : 0);
+ set('u_causticOn', q.caustics ? 1 : 0);
set('u_waveSpace', 1);
set('u_origin', { x: ox, y: oz });
set('u_cellSize', d.cellSize);
set('u_flowSpeed', d.form === WaterForm.River ? d.flowSpeed : 0);
- set('u_geoWaves', d.form === WaterForm.River ? 0 : 1);
+ set('u_geoWaves', d.form === WaterForm.River || !q.displacement ? 0 : 1);
set('u_waveHeight', d.waveHeight);
set('u_waveLength', d.waveLength);
set('u_waveSpeed', d.waveSpeed);
diff --git a/sdk/src/water/waves.ts b/sdk/src/water/waves.ts
index d1bf1f67e..529b4660b 100644
--- a/sdk/src/water/waves.ts
+++ b/sdk/src/water/waves.ts
@@ -30,6 +30,8 @@ export interface WaveParams {
speed: number;
/** The base heading, in degrees. */
direction: number;
+ /** How many of the set's waves are summed, 1 to 4 (the quality level's); all of them when absent. */
+ count?: number;
}
const TAU = Math.PI * 2;
@@ -44,11 +46,18 @@ export function waveFade(length: number, cell: number): number {
return Math.min(Math.max((length / cell - 3) / 3, 0), 1);
}
+/** How many waves of the set a body sums: its count, held to the set. */
+export function waveCount(p: WaveParams): number {
+ return Math.min(Math.max(Math.round(p.count ?? WAVE_SET.length), 1), WAVE_SET.length);
+}
+
/** The surface's height above the body's rest plane at (x, z), `time` seconds in. */
export function waveHeight(p: WaveParams, x: number, z: number, time: number, cell = 0): number {
let height = 0;
const base = p.direction * Math.PI / 180;
+ let used = waveCount(p);
for (const [heading, lengthShare, heightShare, speedShare] of WAVE_SET) {
+ if (used-- <= 0) break;
const length = p.length * lengthShare;
const k = TAU / length;
const a = base + heading * Math.PI / 180;
@@ -63,7 +72,9 @@ export function waveHeight(p: WaveParams, x: number, z: number, time: number, ce
export function waveSlope(p: WaveParams, x: number, z: number, time: number): [number, number] {
let sx = 0, sz = 0;
const base = p.direction * Math.PI / 180;
+ let used = waveCount(p);
for (const [heading, lengthShare, heightShare, speedShare] of WAVE_SET) {
+ if (used-- <= 0) break;
const k = TAU / (p.length * lengthShare);
const a = base + heading * Math.PI / 180;
const dx = Math.sin(a), dz = Math.cos(a);
diff --git a/sdk/tests/water-quality.test.ts b/sdk/tests/water-quality.test.ts
new file mode 100644
index 000000000..c1aa595bc
--- /dev/null
+++ b/sdk/tests/water-quality.test.ts
@@ -0,0 +1,101 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { waveHeight, waveSlope, waveCount, type WaveParams } from '../src/water/waves';
+import { FULL_WATER, waterQualityOf } from '../src/water/waterPlugin';
+import { defaultQualityProfile, resolveQualityProfile, parseQualityConfig } from '../src/render/quality';
+import { applyUnderwaterToEffects, type UnderwaterState } from '../src/postprocess/underwater';
+import type { BlendedEffect } from '../src/postprocess/volumeBlending';
+
+const params: WaveParams = { height: 1, length: 20, speed: 1, direction: 30 };
+
+describe('the wave count', () => {
+ it('is the whole set when absent, and is held to 1 to 4', () => {
+ expect(waveCount(params)).toBe(4);
+ expect(waveCount({ ...params, count: 2 })).toBe(2);
+ expect(waveCount({ ...params, count: 0 })).toBe(1);
+ expect(waveCount({ ...params, count: 9 })).toBe(4);
+ });
+
+ it('sums fewer waves for a lower count, and one wave is the longest alone', () => {
+ const x = 3.7, z = -2.1, t = 1.3;
+ const all = waveHeight(params, x, z, t), two = waveHeight({ ...params, count: 2 }, x, z, t), one = waveHeight({ ...params, count: 1 }, x, z, t);
+ expect(one).not.toBeCloseTo(all, 6);
+ expect(two).not.toBeCloseTo(all, 6);
+ expect(waveHeight({ ...params, count: 4 }, x, z, t)).toBe(all);
+ // The one wave is the set's first, at its own length and height.
+ const k = 2 * Math.PI / 20, a = 30 * Math.PI / 180;
+ const theta = k * (Math.sin(a) * x + Math.cos(a) * z) - Math.sqrt(9.8 * k) * t;
+ expect(one).toBeCloseTo(Math.exp(Math.sin(theta) - 1), 9);
+ });
+
+ it('takes the slope from the same waves the height has', () => {
+ const x = 1, z = 2, t = 0.4, h = 1e-4;
+ for (const count of [1, 2, 3, 4]) {
+ const p = { ...params, count };
+ const [sx, sz] = waveSlope(p, x, z, t);
+ const dx = (waveHeight(p, x + h, z, t) - waveHeight(p, x - h, z, t)) / (2 * h);
+ const dz = (waveHeight(p, x, z + h, t) - waveHeight(p, x, z - h, t)) / (2 * h);
+ expect(sx).toBeCloseTo(dx, 4);
+ expect(sz).toBeCloseTo(dz, 4);
+ }
+ });
+});
+
+describe('what a quality level allows water', () => {
+ it('is everything with no policy, off a minigame', () => {
+ expect(waterQualityOf(null, false)).toEqual(FULL_WATER);
+ });
+
+ it('is the low profile on a minigame with no policy: flat, no mirror, no web of light', () => {
+ const q = waterQualityOf(null, true);
+ expect(q).toEqual({ waves: 2, rippleCells: 32, displacement: false, mirror: false, caustics: false });
+ });
+
+ it('follows the profile of the level a project is at, so a project can change what a level means', () => {
+ expect(waterQualityOf(defaultQualityProfile('high'), false)).toEqual({ waves: 4, rippleCells: 128, displacement: true, mirror: true, caustics: true });
+ const own = resolveQualityProfile('low', { waterMirror: true, waterDisplacement: true, waterWaves: 3 });
+ expect(waterQualityOf(own, true)).toMatchObject({ waves: 3, displacement: true, mirror: true, caustics: false });
+ // A profile wins over the minigame rule: the project said what it wants.
+ expect(waterQualityOf(defaultQualityProfile('high'), true).displacement).toBe(true);
+ });
+
+ it('steps down by level, never up', () => {
+ const levels = (['low', 'medium', 'high'] as const).map((l) => defaultQualityProfile(l));
+ for (let i = 1; i < levels.length; i++) {
+ expect(levels[i]!.waterWaves).toBeGreaterThanOrEqual(levels[i - 1]!.waterWaves);
+ expect(levels[i]!.waterRippleCells).toBeGreaterThanOrEqual(levels[i - 1]!.waterRippleCells);
+ }
+ });
+
+ it('is read and bounded from a project\'s quality block', () => {
+ const q = parseQualityConfig({ mode: 'low', profiles: { low: { waterWaves: 99, waterRippleCells: -5, waterMirror: 'yes', waterCaustics: true } } });
+ const low = q.profiles!.low!;
+ expect(low.waterWaves).toBe(4);
+ expect(low.waterRippleCells).toBe(0);
+ expect(low.waterMirror).toBe(false);
+ expect(low.waterCaustics).toBe(true);
+ });
+});
+
+describe('the underwater effect under a quality level that turns the light off', () => {
+ const state = (extra: Partial<UnderwaterState> = {}): UnderwaterState => ({
+ amount: 1, depth: 4, absorption: [0.4, 0.1, 0.05], density: 0.02, scatter: [0.02, 0.2, 0.3],
+ plane: [0, 1, 0, 0], band: 0.4, causticStrength: 0.6, causticScale: 2, causticSpeed: 0.35, ...extra,
+ });
+
+ it('zeroes the web and the shafts, even where a scene authored them', () => {
+ const authored: BlendedEffect = { enabled: true, uniforms: new Map([['u_causticStrength', 1], ['u_shaftStrength', 2]]), textures: new Map(), colors: new Map() };
+ const effects = new Map<string, BlendedEffect>([['underwater', authored]]);
+ applyUnderwaterToEffects(effects, state({ light: false }));
+ expect(authored.uniforms.get('u_causticStrength')).toBe(0);
+ expect(authored.uniforms.get('u_shaftStrength')).toBe(0);
+ });
+
+ it('leaves them alone when the light is on', () => {
+ const authored: BlendedEffect = { enabled: true, uniforms: new Map([['u_causticStrength', 1], ['u_shaftStrength', 2]]), textures: new Map(), colors: new Map() };
+ applyUnderwaterToEffects(new Map([['underwater', authored]]), state());
+ expect(authored.uniforms.get('u_causticStrength')).toBe(1);
+ expect(authored.uniforms.get('u_shaftStrength')).toBe(2);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 4e9209ba3..cd1cc3723 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2567,6 +2567,8 @@ export const NOTED = {
{"note":"Water holds things up. A Floating component on an entity with a RigidBody3D floats it: a buoyant force against gravity (`buoyancy` is the water's density against the body's, so 2 floats it half under) and a drag against its velocity relative to the water, which brings it to rest in a lake and carries it with a river's current, applied at a few points of the body so waves tip it. It works from the CPU's own water surface, so it needs no renderer, and it needs the 3D physics module, which gains force and mass queries."},
"feat(water): a camera under the surface sees through the water, fogged and tinted by what it has crossed":
{"note":"A camera under water sees through it. Whenever the active camera is below a water body's surface an Underwater effect is added to the post-process volumes: the light of each pixel is taken out colour by colour (red first) by the distance it crossed, with the same absorption and density the surface's material draws with, and the water gives back its own colour, dimmer the deeper the camera is. The surface seen from below turns over and, past the critical angle, reflects whole (Snell's window)."},
+ "feat(water): quality levels set the waves, ripples, mirror and caustics water spends, and the low level is a lite water with flat geometry":
+ {"note":"Water spends what the quality level allows. Each level's profile has `waterWaves` (waves summed, 2 / 3 / 4), `waterRippleCells` (the ripple grid's side, 32 / 64 / 128), `waterDisplacement` (off is the lite water: flat geometry with the waves in the shading only), `waterMirror` and `waterCaustics`. What `Waters.sample` answers follows what is drawn, and a minigame with no quality policy gets the Low level's water."},
"fix(editor): the move gizmo's plane handles sit closer to its centre":
{"note":"The three plane handles of the move gizmo sit closer to its centre, on the inside corner between each pair of axes, instead of out at a third of the way along them."},
"feat(editor): the points of a lake and a river are edited with handles in the viewport, and Details shows only what the form uses":