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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(water): rivers cut their beds into the terrain
yhh2efa002b8b11
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5c4775f68..3bf6e8c86 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,7 @@ published separately; it ships inside the editor.- **Rays against the terrain, anywhere.** `Terrains.raycast(origin, direction, maxDistance)` meets the ground's triangles exactly (the ones collision and `heightAt` use) wherever the ray goes, with no physics world and no collision tile there, for a line of sight, a pick or a landing spot.- **Far versions for generated decoration.** A recipe member can name its far version (`far`: crossed cards, or a tent for a conifer, showing a rectangle of its texture), drawn past its layer's `lodDistance`, and decoration that leans with the ground (`attach: 'align'`) now leans in its merged mesh too.- **Terrain modifiers, and zones that level their ground.** `Terrains.setModifier` lays a change over the ground (`flattenModifier` levels a circle or a turned box, blending back over its edge) that what is drawn, the queries, rays and collision all follow, remaking only the pages and collision tiles it reaches; `heightBeneathAt` reads the ground as it was made. A `WorldZone` with `flatten` levels its plot to the ground's height at its centre.+- **Rivers cut their beds.** A river's `WaterBody.bedDepth` cuts its bed into the terrain, a trough under its surface with banks that blend back into the ground, laid as terrain modifiers along it so what is drawn, the queries and collision follow, and editing the spline remakes only the ground along the river.- **Whether a place can be walked to.** `Terrains.findPath(from, to, { maxSlope, step, blocked })` searches the ground for a way a walker held to a slope can take, reading the ground where it goes (modifiers too, nothing baked), and returns it pulled straight with its length, or says whether there is no way, the search ran out, or an end stands on no ground: what a game checks a spawn or a goal against.- **World rules as a file, with an editor.** A WorldGen's `rules` can name a `.esworld` file: the biomes, recipes and layers as data, checked as they are read (a missing recipe or layer fails the world with where it went wrong), followed by the cook like a material so the meshes and materials it names ship with the scene, and watched so a saved edit lays the world out again. The editor opens it in a World Rules editor that lists the biomes, recipes and layers, edits each with a form, and says whether the engine would take the rules as they stand.- **How far a place is from the water.** `Waters.shoreAt(x, z)` gives the distance across the ground to the water's edge (above zero on dry land, below on the water), and generated worlds read it as the `shoreDistance` field, so a beach or a band of reeds can follow the shore.diff --git a/docs/WORLD_GENERATION_PLAN.md b/docs/WORLD_GENERATION_PLAN.mdindex c4e2a7428..2efe27475 100644--- a/docs/WORLD_GENERATION_PLAN.md+++ b/docs/WORLD_GENERATION_PLAN.md@@ -72,7 +72,7 @@| --- | --- | --- | --- || P0 引擎 | 海洋范围掩码/连通性:只有与开阔海在海面高度下连通的低地属于海 | 已完成:烘焙先取整片网格地面,从区域边缘泛洪,未连通的低于海面洼地为陆地(`zone.ts openSea`);测试 `water-bodies.test.ts` | 隔绝的低于海面的干盆地不显示海水、不判为水下 || P0 引擎 | 多水体命中规则:范围、垂向有效区间/底部、优先级、归属 | 已完成:湖/河只在水面高于地面处成立(轮廓内高出水面的陆地为陆地);湖/河优先于海;与顺序无关(测试逐格比对);`WaterBody.bodyId` 稳定身份,`Waters.sample().bodyId`、`Waters.bodyAt(x,z)` | 上方湖泊不被下方海洋抢先;顺序无关;陆地不被当作水域 |-| P0 游戏+引擎接口 | 海域连通、盆地/出口、水系连接、独立水位、河床、稳定 waterBodyId | 引擎接口已提供:`findBasins`(优先级泛洪:盆地溢出水位/最深点/出口、填洼高度、排水树与汇流量、海域)、`drainPath`;稳定 `bodyId`。由游戏据此生成湖泊与河流;河床刻蚀仍欠(P1) | 跨块水位/岸线连续;高湖、低湖与干盆地共存;流向有效 |+| P0 游戏+引擎接口 | 海域连通、盆地/出口、水系连接、独立水位、河床、稳定 waterBodyId | 引擎接口已提供:`findBasins`(优先级泛洪:盆地溢出水位/最深点/出口、填洼高度、排水树与汇流量、海域)、`drainPath`;稳定 `bodyId`。由游戏据此生成湖泊与河流;河床刻蚀已补:`WaterBody.bedDepth`(沿河道站点的分段地形修改器,U 形河床+同坡度河岸接回地面,只在河道变化时重设) | 跨块水位/岸线连续;高湖、低湖与干盆地共存;流向有效 || P1 引擎+美术 | 河湖接缝、入海口、急流/瀑布,按类型配置外观 | 部分:区域场已消除河湖接缝;拍岸浪、岸边柔化已有;河口水流纹理仍有问题 | 交界无重复透明面/突变 |### 后续(不阻塞首块可玩地表)diff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdxindex 304919d09..23dcf88d4 100644--- a/docs/astro/src/content/docs/graphics/water.mdx+++ b/docs/astro/src/content/docs/graphics/water.mdx@@ -24,6 +24,7 @@ into one surface. The entity places the body; it may be turned about its up, not| `shoreWidth` | How far in from the shore, and how deep, the waves take to come to full height, for every form. 0 leaves them whole to the edge. || `flowSpeed` | A river's current, in world units a second where it is as wide as its widest. || `waveHeight` | The height of the tallest wave, in world units. The waves' length, speed and heading are the zone's, which every body shares. |+| `bedDepth` | How deep a river cuts its bed into the terrain under its surface, at its middle. 0 leaves the ground as it is. |Moving a body, editing its fields, its outline or its spline, or changing the terrain under it rebakes the zone, so the water follows at once.@@ -140,6 +141,11 @@ so a river runs downhill. Put a `Spline` and a `WaterBody` with `form` River onfading in as the other fades out, so the moment one is put back at its start is hidden by the other, and the surface does not stretch where the river bends.- **Waves.** A river has its own `waveHeight`, calmed toward its banks over `shoreWidth`, like any body. `Waters.sample` gives the current in `flow`(world units a second, along the river; zero elsewhere).+- **Its bed.** With `bedDepth` above zero the river cuts its bed into the terrain: a trough `bedDepth` under the surface at its middle and at+ the surface at its edge, its banks rising on at the same slope until they meet the ground, two widths out at most. It is laid as+ [terrain modifiers](/docs/graphics/terrain/#modifiers) a stretch of the river each, so the drawn ground, its queries and collision all+ follow, editing the spline remakes only the ground along it, and ground already lower than the bed is left alone. Ground a game carves+ itself (a heightmap made with its rivers in it) leaves `bedDepth` at 0.- **Banks and mouths.** A bank is where the field's shore distance crosses zero, traced at the zone's resolution. Where a river runs into a lake, the sea oranother river, the two are blended over a texel and a half, so there is no seam, no shore across the mouth and no step in height.diff --git a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdxindex 1846e2c8e..106ed6bad 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx@@ -20,6 +20,7 @@ description: 若干 WaterBody 组件说明海洋、湖泊或河流在哪里,一| `shoreWidth` | 从岸边往里多远、水多深,波浪才长到完整高度,对所有形态都适用。0 表示波浪一直完整到岸边。 || `flowSpeed` | 河流的流速,世界单位每秒,指河面最宽处的流速。 || `waveHeight` | 最高那道波的高度,世界单位。波浪的波长、速度和方向属于区域,所有水体共用。 |+| `bedDepth` | 河流把河床挖进地形、河道中线处低于水面的深度。0 表示不改动地面。 |移动水体、改它的字段、轮廓或样条,或者改它下面的地形,都会让区域重新烘焙,所以水立刻跟着变。@@ -94,6 +95,7 @@ description: 若干 WaterBody 组件说明海洋、湖泊或河流在哪里,一- **水流。** `flowSpeed` 是河面最宽处的流速;窄的河段更快、宽的河段更慢,范围在它的四分之一到两倍之间,和同样的水流过不同宽度时的情形一致。方向就是曲线的方向。它从河流起点起在一个河宽内渐强,流入别处时在一个河宽内渐弱,所以河口是静水。- **表面随水流动。** 着色器把波浪和涟漪顺流带走:表面的两份拷贝每次沿水流前进一个周期,一份淡入的同时另一份淡出,所以其中一份被放回起点的那一刻被另一份遮住,河道拐弯处表面也不会被拉长。- **波浪。** 河流有自己的 `waveHeight`,和其他水体一样在 `shoreWidth` 内向河岸变平静。`Waters.sample` 在 `flow` 里给出水流(世界单位每秒,沿河道方向;别处为零)。+- **河床。** `bedDepth` 大于零时,河流把河床挖进地形:河道中线处低于水面 `bedDepth`,河边与水面齐平,河岸以相同的坡度继续升高直到接回原地面,最远两个河宽。它以[地形修改器](/docs/zh-cn/graphics/terrain/#修改器)的形式铺设,每段河道一个,所以画出来的地面、查询和碰撞都跟随它;编辑样条只重做河道沿线的地面;比河床更低的地面保持不变。游戏自己刻好河道的地面(带河流一起生成的高度图)请把 `bedDepth` 留为 0。- **河岸与河口。** 河岸是场里岸线距离过零的地方,按区域的分辨率描出。河流流进湖、海或另一条河的地方,两者在一个半纹素内混合,所以没有接缝,河口没有横跨的岸线,也没有高度台阶。## 漂浮diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 1ae25897f..269e92cff 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -7370,6 +7370,13 @@"default": "0.3","doc": "The height of the tallest wave, in world units. Their length, speed and heading are the zone's.","range": "0–800"+ },+ {+ "key": "bedDepth",+ "type": "number",+ "default": "0",+ "doc": "How deep the river cuts its bed into the terrain under its surface, at its middle, its banks blending back into the ground. 0 leaves the ground as it is.",+ "range": "≥ 0"}],"animatable": [@@ -7378,7 +7385,8 @@"sizeZ","shoreWidth","flowSpeed",- "waveHeight"+ "waveHeight",+ "bedDepth"]},{diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 6d3b60608..ad934a860 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -11750,6 +11750,7 @@ ComponentDef<WaterBodyData>## WaterBodyData — interface @experimental```+bedDepth: numberbodyId: stringboundary: Point2[]flowSpeed: numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 3505d8ab7..c017d78a9 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -11963,6 +11963,7 @@ ComponentDef<WaterBodyData>## WaterBodyData — interface @experimental```+bedDepth: numberbodyId: stringboundary: Point2[]flowSpeed: numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 71f0eb8d9..18a9cc404 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -11745,6 +11745,7 @@ ComponentDef<WaterBodyData>## WaterBodyData — interface @experimental```+bedDepth: numberbodyId: stringboundary: Point2[]flowSpeed: numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 6946f4633..4b20c3502 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -12044,6 +12044,7 @@ ComponentDef<WaterBodyData>## WaterBodyData — interface @experimental```+bedDepth: numberbodyId: stringboundary: Point2[]flowSpeed: numberdiff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.mdindex 71d1260d1..be351c3e5 100644--- a/sdk/etc/water.api.md+++ b/sdk/etc/water.api.md@@ -127,6 +127,7 @@ ComponentDef<WaterBodyData>## WaterBodyData — interface @experimental```+bedDepth: numberbodyId: stringboundary: Point2[]flowSpeed: numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 28242c32a..bdcc75c46 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -11752,6 +11752,7 @@ ComponentDef<WaterBodyData>## WaterBodyData — interface @experimental```+bedDepth: numberbodyId: stringboundary: Point2[]flowSpeed: numberdiff --git a/sdk/src/water/riverBed.ts b/sdk/src/water/riverBed.tsnew file mode 100644index 000000000..2a91230b5--- /dev/null+++ b/sdk/src/water/riverBed.ts@@ -0,0 +1,74 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file riverBed.ts+ * @brief A river's bed cut into the terrain: the ground along it lowered under its surface, so the water lies in a channel instead+ * of over grass.+ *+ * @details The bed is a trough across the river, `depth` under the surface at its middle and at the surface at its edge, its banks+ * rising on at the slope the trough meets them with until they are back on the ground. Ground already lower (a valley the+ * river runs down) is left as it is: the bed only cuts. The river is laid over the terrain as modifiers of a stretch each, so+ * a point of ground is weighed against the few stations near it, and editing one river remakes only the ground along it.+ */+import type { TerrainModifier } from '../terrain/source';+import type { RiverStation } from './zone';++/** Stations to a modifier: a stretch a few widths long. */+const STRETCH = 24;+/** How far out from the edge the banks reach, in half-widths, before they give the ground back. */+const BANK = 2;++const smoothstep = (a: number, b: number, x: number): number => {+ const t = Math.min(Math.max((x - a) / (b - a), 0), 1);+ return t * t * (3 - 2 * t);+};++/** The height the bed would have at (x, z) by the stations of one stretch, and how much of it holds there (0 past its banks). */+function bedAt(stations: readonly RiverStation[], from: number, to: number, depth: number, x: number, z: number): { height: number; weight: number } {+ let height = Infinity, weight = 0;+ for (let i = from; i < to; i++) {+ const a = stations[i]!, b = stations[i + 1]!;+ const ex = b.x - a.x, ez = b.z - a.z;+ const len2 = ex * ex + ez * ez;+ const t = len2 > 0 ? Math.min(Math.max(((x - a.x) * ex + (z - a.z) * ez) / len2, 0), 1) : 0;+ const d = Math.hypot(x - (a.x + ex * t), z - (a.z + ez * t));+ const half = Math.max(a.half + (b.half - a.half) * t, 1e-3);+ const reach = half * (1 + BANK);+ if (d >= reach) continue;+ const surface = a.y + (b.y - a.y) * t;+ const u = d / half;+ // Inside, a trough; outside, the bank goes on at the slope the trough meets it with, so there is no crease at the edge.+ const target = u < 1 ? surface - depth * (1 - u * u) : surface + (2 * depth / half) * (d - half);+ height = Math.min(height, target);+ weight = Math.max(weight, 1 - smoothstep(half * BANK, reach, d));+ }+ return { height, weight };+}++/**+ * The modifiers that cut a river's bed `depth` under its surface, a stretch of it each, their ids starting with `prefix`.+ * @experimental+ */+export function riverBedModifiers(prefix: string, stations: readonly RiverStation[], depth: number): TerrainModifier[] {+ if (stations.length < 2 || !(depth > 0)) return [];+ const out: TerrainModifier[] = [];+ for (let from = 0; from < stations.length - 1; from += STRETCH) {+ const to = Math.min(from + STRETCH, stations.length - 1);+ let minX = Infinity, minZ = Infinity, maxX = -Infinity, maxZ = -Infinity;+ for (let i = from; i <= to; i++) {+ const s = stations[i]!, r = s.half * (1 + BANK);+ minX = Math.min(minX, s.x - r); maxX = Math.max(maxX, s.x + r);+ minZ = Math.min(minZ, s.z - r); maxZ = Math.max(maxZ, s.z + r);+ }+ out.push({+ id: `${prefix}${from / STRETCH}`,+ bounds: [minX, minZ, maxX, maxZ],+ apply(x, z, h) {+ const bed = bedAt(stations, from, to, depth, x, z);+ if (bed.weight <= 0 || bed.height >= h) return h;+ return h + (bed.height - h) * bed.weight;+ },+ });+ }+ return out;+}diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.tsindex 3017be6ab..1a8ec0393 100644--- a/sdk/src/water/waterPlugin.ts+++ b/sdk/src/water/waterPlugin.ts@@ -14,6 +14,7 @@* The waves are the ones the Water shader draws: `waves.ts` is the same formula, and {@link Waters.sample} answers from the same field, so* a floating object, a camera under the surface and a splash all read the surface that is on the screen.*/+import { riverBedModifiers } from './riverBed';import type { App, Plugin } from '../app/app';import { defineSystem, Schedule } from '../ecs/system';import { defineResource, Time } from '../ecs/resource';@@ -67,6 +68,8 @@ export interface WaterBodyData {flowSpeed: number;/** The height of the tallest wave, in world units. Their length, speed and heading are the zone's, which every body shares. */waveHeight: number;+ /** How deep a river cuts its bed into the terrain under its surface, at its middle; 0 leaves the ground as it is. */+ bedDepth: number;}/**@@ -75,7 +78,7 @@ export interface WaterBodyData {* @experimental*/export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyData>('WaterBody', {- form: WaterForm.Lake, bodyId: '', sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, flowSpeed: 2, waveHeight: 0.3,+ form: WaterForm.Lake, bodyId: '', sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, flowSpeed: 2, waveHeight: 0.3, bedDepth: 0,}, {fields: {form: { enum: [{ label: 'Ocean', value: WaterForm.Ocean }, { label: 'Lake', value: WaterForm.Lake }, { label: 'River', value: WaterForm.River }], category: 'Shape', tooltip: 'An ocean is without edge: everywhere at its height where the ground is lower; a lake is a rectangle or an outline of its own; a river follows the Spline on the same entity.' },@@ -85,6 +88,7 @@ export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyDboundary: { category: 'Shape', tooltip: 'The outline of a lake: points round it on its own xz plane. Empty is the rectangle of its size.', shownWhen: { field: 'form', values: [WaterForm.Lake] } },shoreWidth: { min: 0, category: 'Shape', tooltip: 'How far in from the shore, and how deep, the waves take to come to full height. 0 leaves them whole to the edge.' },flowSpeed: { min: 0, max: 5000, category: 'Waves', tooltip: 'A river\'s current, in world units a second where it is as wide as its widest. A narrower reach runs faster.', shownWhen: { field: 'form', values: [WaterForm.River] } },+ bedDepth: { min: 0, category: 'Shape', tooltip: 'How deep the river cuts its bed into the terrain under its surface, at its middle, its banks blending back into the ground. 0 leaves the ground as it is.', shownWhen: { field: 'form', values: [WaterForm.River] } },waveHeight: { min: 0, max: 800, category: 'Waves', tooltip: 'The height of the tallest wave, in world units. Their length, speed and heading are the zone\'s.' },},});@@ -341,8 +345,12 @@ export function riverStations(curve: SplineCurve, flowSpeed: number, toWorld: (xreturn stations;}+/** A river whose bed is cut into the terrain. */+interface Bed { key: number; stations: readonly RiverStation[]; depth: number }+/** Everything the zone is baked from, as the scene says it now. */interface Inputs {+ beds: Bed[];bodies: ZoneBody[];grid: ZoneGrid;zone: WaterZoneData;@@ -380,6 +388,8 @@ export class WaterPlugin implements Plugin {private epoch_ = 0;/** The bake in hand, for the inputs `key` names; the field drawn until it lands is the last one baked. */private baking_: { key: string; cancel: () => void } | null = null;+ /** The beds cut into the terrain, by river: what they were cut from, and the ids of their modifiers. */+ private beds_ = new Map<number, { signature: string; ids: string[] }>();build(app: App): void {const waters = new Waters();@@ -393,6 +403,7 @@ export class WaterPlugin implements Plugin {// What the water IS (the baked field) needs no renderer: it is baked 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 inputs = this.gather(app);+ this.carve(app, inputs.beds);waters.zone_ = inputs.zone;if (inputs.bodies.length === 0) {this.baking_?.cancel();@@ -430,6 +441,7 @@ export class WaterPlugin implements Plugin {}cleanup(app?: App): void {+ if (app) this.carve(app, []);if (!app?.hasResource(WatersRes)) return;this.baking_?.cancel();this.baking_ = null;@@ -465,6 +477,7 @@ export class WaterPlugin implements Plugin {*/private gather(app: App): Inputs {const bodies: ZoneBody[] = [];+ const beds: Bed[] = [];const keyParts: unknown[] = [];for (const entity of app.world.getEntitiesWithComponents([WaterBody, Transform])) {const d = app.world.get(entity, WaterBody) as WaterBodyData;@@ -488,6 +501,7 @@ export class WaterPlugin implements Plugin {const curve = new SplineCurve(spline.points, spline.closed);const stations = riverStations(curve, d.flowSpeed, (x, y, z) => fromLocal(t, x, y, z, scale), (x, y, z) => rotate(t.worldRotation, x, y, z), scale);bodies.push({ kind: 'river', key, waveHeight: d.waveHeight, shoreWidth: d.shoreWidth * scale, stations });+ if (d.bedDepth > 0) beds.push({ key, stations, depth: d.bedDepth * scale });keyParts.push([key, d.form, spline.points, spline.closed, d.flowSpeed, d.waveHeight, d.shoreWidth, t.worldPosition, t.worldRotation, scale]);}}@@ -508,7 +522,32 @@ export class WaterPlugin implements Plugin {for (const b of bodies) b.exposure = exposureOf(b, zone.waveLength);const terrain = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;const ground = terrain && terrain.built_.size > 0 ? terrain.revision_ : -1;- return { bodies, grid, zone, key: JSON.stringify([keyParts, grid, ground, zone.surfLength, zone.waveLength]) };+ return { bodies, beds, grid, zone, key: JSON.stringify([keyParts, grid, ground, zone.surfLength, zone.waveLength]) };+ }++ /**+ * Cuts each river's bed into the terrain, and gives the ground back where a river stops cutting or is gone. A bed is laid again only+ * when the river it is cut from changes: the water baked over the cut ground does not cut it again.+ */+ private carve(app: App, beds: readonly Bed[]): void {+ if (beds.length === 0 && this.beds_.size === 0) return;+ const terrains = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;+ const seen = new Set<number>();+ for (const bed of beds) {+ seen.add(bed.key);+ const signature = JSON.stringify([bed.depth, bed.stations]);+ const had = this.beds_.get(bed.key);+ if (had?.signature === signature || !terrains) continue;+ for (const id of had?.ids ?? []) terrains.deleteModifier(id);+ const modifiers = riverBedModifiers(`river-bed:${bed.key}:`, bed.stations, bed.depth);+ for (const m of modifiers) terrains.setModifier(m);+ this.beds_.set(bed.key, { signature, ids: modifiers.map((m) => m.id) });+ }+ for (const [key, had] of this.beds_) {+ if (seen.has(key)) continue;+ if (terrains) for (const id of had.ids) terrains.deleteModifier(id);+ this.beds_.delete(key);+ }}/** The world height of the ground, where a terrain is built. */diff --git a/sdk/tests/water-river-bed.test.ts b/sdk/tests/water-river-bed.test.tsnew file mode 100644index 000000000..9525b6e29--- /dev/null+++ b/sdk/tests/water-river-bed.test.ts@@ -0,0 +1,43 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { riverBedModifiers } from '../src/water/riverBed';+import type { RiverStation } from '../src/water/zone';++/** A straight river along x at z = 0, its surface at 10, 20 wide, a station every 4. */+const stations: RiverStation[] = Array.from({ length: 101 }, (_, i) => ({ x: i * 4, z: 0, y: 10, half: 10, dx: 1, dz: 0, speed: 1 }));+const mods = riverBedModifiers('bed:', stations, 3);+const ground = (x: number, z: number, h: number): number => {+ for (const m of mods) {+ const [x0, z0, x1, z1] = m.bounds;+ if (x >= x0 && x <= x1 && z >= z0 && z <= z1) h = m.apply(x, z, h);+ }+ return h;+};++describe('riverBedModifiers', () => {+ it('cuts a trough depth under the surface at the middle and at the surface at the edge', () => {+ expect(ground(200, 0, 12)).toBeCloseTo(7, 5);+ expect(ground(200, 10, 12)).toBeCloseTo(10, 5);+ expect(ground(200, 5, 12)).toBeCloseTo(10 - 3 * 0.75, 5);+ });++ it('gives the ground back across its banks, smoothly, and leaves lower ground alone', () => {+ expect(ground(200, 40, 12)).toBe(12);+ let prev = ground(200, 0, 12);+ for (let z = 0.5; z <= 30; z += 0.5) {+ const h = ground(200, z, 12);+ expect(h).toBeGreaterThanOrEqual(prev - 1e-9);+ expect(h - prev).toBeLessThan(0.5);+ prev = h;+ }+ expect(ground(200, 0, 5)).toBe(5);+ });++ it('is laid as stretches, each bounded round its own', () => {+ expect(mods.length).toBe(Math.ceil(100 / 24));+ expect(new Set(mods.map((m) => m.id)).size).toBe(mods.length);+ expect(mods[0]!.bounds[2]).toBeLessThan(400);+ expect(riverBedModifiers('x', stations, 0)).toEqual([]);+ });+});diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjsindex 47756d568..62b61ec81 100644--- a/tools/check-gizmo-coverage.mjs+++ b/tools/check-gizmo-coverage.mjs@@ -138,6 +138,7 @@ const DISPOSITION = {'WaterZone.rippleSize': ['no-place', 'the side of a window of ripples that follows the camera, not a region of the entity'],'Floating.radius': ['no-place', 'how deep under the surface a point of the body is wholly wet, not a region of the entity'],'WaterBody.waveHeight': ['no-place', 'the height of the tallest wave, not a region of the entity'],+ 'WaterBody.bedDepth': ['renders', 'a river\'s bed is cut into the terrain, which draws it'],'SpringBone.radius': ['no-place', 'the thickness of the strand, kept clear of the colliders; a margin on each bone, not a region of the root'],'Sprite.size': ['renders', 'the sprite drawn at it is the outline'],'Sprite.tileSize': ['renders', 'the repeat of a drawn sprite'],diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex ad1850955..4d46231e4 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2804,4 +2804,6 @@ export const NOTED = {{"note":"World rules as a file, with an editor."},"feat(terrain): findPath asks whether a place can be walked to under a slope limit":{"note":"Whether a place can be walked to."},+ "feat(water): rivers cut their beds into the terrain":+ {"note":"Rivers cut their beds."},};