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(terrain): modifiers change the ground for every reader and remake only what they reach, and a zone can level its plot

yhhb754ac344f0c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 201c48bcf..2adfd7da2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,6 +30,7 @@ published separately; it ships inside the editor.
- **An area without a heightmap is a window on its provider's ground.** Its noise is read from `Terrain.provider` where the area stands in the world, over the provider's height range, instead of being made in the area's own space and stretched to fill it: two areas of the same size side by side join, an area is the same ground its provider gives without end, and a game's own provider can make an area. Ground read from a provider is read again when its terrain is moved, so it stays the world's ground.
- **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.
- **A vertex hook can hand the fragment a colour.** What a material's vertex hook leaves in `es_vertexColor` is now the colour its fragment receives (times the instance's tint), on both backends.
- **Bakes run over frames, with progress.** Work that used to hold a frame until it was done (a terrain worn by rain, a water zone baked, terrain chunks built, plants grown) is now spread over frames within a budget, and listed with its progress in the new `Bakes` resource (`bakesOf(app).active`). The editor's status bar shows it as a bar, for the edit world and for the game running in Play, and a game can show it on a loading screen. Plants wait for the ground and the water they stand on instead of being grown twice.
- **Eroded and warped terrain.** `Terrain.erosion` wears the ground with rain (a heightmap's as well as the noise's): gullies down the slopes, sharper ridges, silt in the valleys, and dirt painted where the water ran; the same seed wears the same ground. `Terrain.warp` bends the noise by noise of its own for winding valleys and bent ridges. `erodeHeightfield` and `erosionJob` do the same for a tool.
diff --git a/docs/WORLD_GENERATION_PLAN.md b/docs/WORLD_GENERATION_PLAN.md
index ec688cd57..f72b641e0 100644
--- a/docs/WORLD_GENERATION_PLAN.md
+++ b/docs/WORLD_GENERATION_PLAN.md
@@ -58,7 +58,8 @@
- 调试:`explain(x,z)`(场、群落权重、区域、各层候选与拒绝原因)、`stats`、`biomeWeights`、`placementsIn`。
- 测试:`sdk/tests/worldgen-plan.test.ts`、`worldgen-plugin.test.ts`。
- 后续已补:装饰远景版本(成员 `far` 卡片 + 层 `lodDistance`,LODGroup 切换);贴地装饰合并时随法线倾斜。
- - 仍欠:有限整地(区域压平地面)、陆地离岸距离场、配方编辑器、可达性/安全落点等验收由游戏用查询接口实现(引擎可后续提供寻路连通查询)。
+ - 后续已补:有限整地——地形修改器(`Terrains.setModifier`,世界空间函数,所有读取方一致,仅重做触及的页与碰撞块),区域 `flatten` 压平(地面未知时挂起重试)。
+ - 仍欠:陆地离岸距离场、配方编辑器、可达性/安全落点等验收由游戏用查询接口实现(引擎可后续提供寻路连通查询)。
- 验收:林地建房后草木不穿地板;采集后卸载重进不重生;同种子不同加载顺序结果相同;安全落点、早期资源、入口可达。
## 水域补充
diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdx
index 664ce78fd..0c55eaf4a 100644
--- a/docs/astro/src/content/docs/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/graphics/terrain.mdx
@@ -153,6 +153,25 @@ cells its own way, and the ground that is collided with would no longer be the g
The tiles go through the `CollisionGeometry` resource (`esengine`), which any system that makes static geometry as the game runs can
use; the 3D physics world keeps one static body for each piece in it.
+### Modifiers
+
+A game changes the ground where it needs to (a plot levelled to build on, a pad, a road's bed) with modifiers: functions of the world
+position and the height the ground has there, each over a square of the world. They are laid over whatever the terrain's ground is,
+in the order they were set, and every reader follows them: what is drawn, `heightAt` and `normalAt`, rays and collision. Only the
+pages and collision tiles a modifier reaches are made again, and what stands on the ground (plants, water, a generated world) is placed
+again.
+
+```ts
+import { flattenModifier } from 'esengine/terrain';
+
+const terrains = app.getResource(TerrainsRes);
+const level = terrains.heightBeneathAt(x, z)!; // the ground as it was made, under every modifier
+terrains.setModifier(flattenModifier('plot 1', { type: 'rect', x, z, halfX: 40, halfZ: 30, yaw }, level, 12));
+terrains.deleteModifier('plot 1'); // the ground comes back
+```
+
+A `WorldZone` with `flatten` levels its ground this way.
+
### Providers and versions
Ground without end is made by a provider: one function of the world position, the same on every machine. It is asked for a region
diff --git a/docs/astro/src/content/docs/world/generation.mdx b/docs/astro/src/content/docs/world/generation.mdx
index f7f26f692..41193aba1 100644
--- a/docs/astro/src/content/docs/world/generation.mdx
+++ b/docs/astro/src/content/docs/world/generation.mdx
@@ -98,6 +98,7 @@ A zone plans an area by hand: a home, a road, a landing site, a building's footp
| `priority` | Where zones overlap, the higher holds the biome. |
| `excludes` | The tags of what it keeps out, separated by commas: a layer, a recipe, a recipe's or member's tags, `decor`, `interactive`; `*` is everything. |
| `biome` | A biome it holds over its area. |
+| `flatten` | Levels the terrain under it to the ground's height at its centre, blending back over `falloff`: a plot to build on. In code, `flatten` is a world height or `'ground'`. |
A game adds zones as it plans and as the player builds:
@@ -150,7 +151,6 @@ Declare the folders they live in always included, in `.esengine/asset-groups.jso
## Limits
-- **No terraforming yet.** A zone keeps generation out of its ground; it does not flatten it.
- **No distance from the shore on land.** `waterDepth` says how deep water stands; a field of how far a dry place is from water is a
game's own for now.
- **Decoration is merged a chunk at a time, not GPU-instanced.** The renderer's instance records are written each frame, which for a
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
index 57c9a2f8d..c67b3dcb4 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
@@ -104,6 +104,21 @@ const n = terrains.normalAt(x, z); // 那里的单位法线,或 null
这些块经由 `CollisionGeometry` 资源(`esengine`)交出,任何在游戏运行中生成静态几何的系统都可以用它;3D 物理世界为其中每一片保留一个静态刚体。
+### 修改器
+
+游戏在需要的地方修改地面(压平一块地基、一个停机坪、一段路基)用的是修改器:以世界位置和该处地面高度为输入的函数,各自作用于世界中的一块方形范围。它们按设置的先后叠加在地形的地面上,所有读取方都跟随它们:画出来的地面、`heightAt` 和 `normalAt`、射线和碰撞。只有修改器触及的页和碰撞块会重做,立在地面上的东西(植被、水、生成世界)会重新放置。
+
+```ts
+import { flattenModifier } from 'esengine/terrain';
+
+const terrains = app.getResource(TerrainsRes);
+const level = terrains.heightBeneathAt(x, z)!; // 地面生成时的高度,不含任何修改器
+terrains.setModifier(flattenModifier('plot 1', { type: 'rect', x, z, halfX: 40, halfZ: 30, yaw }, level, 12));
+terrains.deleteModifier('plot 1'); // 地面恢复原样
+```
+
+带 `flatten` 的 `WorldZone` 就是这样压平它的地面的。
+
### 生成器与版本
无限地面由生成器生成:一个关于世界位置的函数,在每台机器上都一样。它被要求采样一个区域(世界、种子和版本、以世界单位计的起点、间距和每边样本数),返回那里的高度;如果它自己给地面上色,还返回每个样本四个图层权重。每个区域都是同一个函数在不同点上的读数,所以相邻页共享边上的样本,粗页和细页在样本重合处一致,页生成的先后不改变任何东西。位置是世界的,不是地形的:同一个世界上分开摆放的两个地形是同一片地面。
diff --git a/docs/astro/src/content/docs/zh-cn/world/generation.mdx b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
index 787cf7b40..f5cd8f1f8 100644
--- a/docs/astro/src/content/docs/zh-cn/world/generation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
@@ -77,6 +77,7 @@ registerWorldRules({
| `priority` | 区域重叠时,高的决定群落。 |
| `excludes` | 它排除的东西的标签,逗号分隔:层、配方、配方或成员的标签、`decor`、`interactive`;`*` 表示全部。 |
| `biome` | 它在范围内强制的群落。 |
+| `flatten` | 把它下面的地形压平到区域中心处原地面的高度,在 `falloff` 内平滑过渡回去:一块可以建造的地基。代码里 `flatten` 可以是世界高度,或 `'ground'`。 |
游戏在规划时和玩家建造时添加区域:
@@ -124,7 +125,6 @@ gens.diffs().load(saved); // 以及读回
## 限制
-- **还不能整地。** 区域让生成避开它的地面,但不会把地面压平。
- **陆地上没有离岸距离。** `waterDepth` 说明水有多深;干燥的地方离水多远,目前由游戏自己提供场。
- **装饰按区块合并绘制,而不是 GPU 实例化。** 渲染器的实例记录每帧重写,成千上万株植物每帧要上传数兆字节;合并的静态网格每帧不上传任何东西,内存由区块驻留限制住。
- **规则是代码。** 配方是普通数据,可以从 JSON 读取,但还没有编辑器。
diff --git a/examples/worldgen/src/main.ts b/examples/worldgen/src/main.ts
index 52a9f8cbf..bb37ad40a 100644
--- a/examples/worldgen/src/main.ts
+++ b/examples/worldgen/src/main.ts
@@ -123,8 +123,8 @@ addPlugin({
if (gens && input.isKeyPressed('KeyB')) {
const at = { x: x + fx * 260, z: z + fz * 260 };
gens.zones().set({ id: `house ${++built}`, kind: 'building', shape: { type: 'rect', x: at.x, z: at.z, halfX: 40, halfZ: 30, yaw },
- falloff: 12, priority: 20, excludes: ['*'] });
- say(`House ${built} built: the wild is kept out of its ground`, now);
+ falloff: 12, priority: 20, excludes: ['*'], flatten: 'ground' });
+ say(`House ${built} built: its plot levelled and the wild kept out of it`, now);
}
if (status !== null && plan) {
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 3fc0e4f8b..f65b3dce0 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1830 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1833 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -5762,6 +5762,23 @@ completed: boolean | undefined
durationMs: number | undefined
```
+## ModifiedSource — class @experimental
+```
+base: TerrainSource
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+origin: { x: number; y: number; z: number; }
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+touched: (x0: number, z0: number, x1: number, z1: number) => boolean
+static new (base: TerrainSource, modifiers: () => Iterable<TerrainModifier>, origin: { x: number; y: number; z: number; }, step: number): ModifiedSource
+static prototype: ModifiedSource
+```
+
## Modifiers — interface @experimental
```
alt: boolean
@@ -6089,6 +6106,7 @@ atlasSize: number
capacity: number
claim: (key: string, min: number, max: number) => Page | null
clear: () => void
+forget: (test: (key: string) => boolean) => void
get: (key: string) => Page | undefined
origin: (slot: number) => [number, number]
perRow: number
@@ -10010,6 +10028,13 @@ world: string
{ readonly Area: 0; readonly Infinite: 1; }
```
+## TerrainModifier — interface @experimental
+```
+apply: (x: number, z: number, h: number) => number
+bounds: readonly [number, number, number, number]
+id: string
+```
+
## TerrainNode — interface @experimental
```
ix: number
@@ -10083,16 +10108,21 @@ static prototype: TerrainUnavailable
```
@internal app_: App | null
@internal built_: Map<number, Built>
+@internal modifiers_: Map<string, TerrainModifier>
@internal paint_: Repaint | null
+@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
+deleteModifier: (id: string) => void
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
+heightBeneathAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
+setModifier: (modifier: TerrainModifier) => void
setPaint: (paint: Repaint | null) => void
status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
@@ -12353,6 +12383,7 @@ ComponentDef<WorldZoneData>
biome: string
excludes: string
falloff: number
+flatten: boolean
kind: string
priority: number
radius: number
@@ -12372,6 +12403,7 @@ biome: string | undefined
excludes: readonly string[]
falloff: number
fields: Readonly<Record<string, number>> | undefined
+flatten: number | "ground" | undefined
id: string
kind: string
priority: number
@@ -13663,6 +13695,11 @@ EventBindingPlugin
(colour: readonly [number, number, number]): SkyRadiance
```
+## flattenModifier — function @experimental
+```
+(id: string, shape: { type: "circle"; x: number; z: number; radius: number; } | { type: "rect"; x: number; z: number; halfX: number; halfZ: number; yaw?: number; }, height: number, falloff: number): TerrainModifier
+```
+
## flattenPrefab — function @experimental
```
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 4ab4699ac..3b72aa83b 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 164 beta · 1849 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1852 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -5775,6 +5775,23 @@ completed: boolean | undefined
durationMs: number | undefined
```
+## ModifiedSource — class @experimental
+```
+base: TerrainSource
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+origin: { x: number; y: number; z: number; }
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+touched: (x0: number, z0: number, x1: number, z1: number) => boolean
+static new (base: TerrainSource, modifiers: () => Iterable<TerrainModifier>, origin: { x: number; y: number; z: number; }, step: number): ModifiedSource
+static prototype: ModifiedSource
+```
+
## Modifiers — interface @experimental
```
alt: boolean
@@ -6292,6 +6309,7 @@ atlasSize: number
capacity: number
claim: (key: string, min: number, max: number) => Page | null
clear: () => void
+forget: (test: (key: string) => boolean) => void
get: (key: string) => Page | undefined
origin: (slot: number) => [number, number]
perRow: number
@@ -10223,6 +10241,13 @@ world: string
{ readonly Area: 0; readonly Infinite: 1; }
```
+## TerrainModifier — interface @experimental
+```
+apply: (x: number, z: number, h: number) => number
+bounds: readonly [number, number, number, number]
+id: string
+```
+
## TerrainNode — interface @experimental
```
ix: number
@@ -10296,16 +10321,21 @@ static prototype: TerrainUnavailable
```
@internal app_: App | null
@internal built_: Map<number, Built>
+@internal modifiers_: Map<string, TerrainModifier>
@internal paint_: Repaint | null
+@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
+deleteModifier: (id: string) => void
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
+heightBeneathAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
+setModifier: (modifier: TerrainModifier) => void
setPaint: (paint: Repaint | null) => void
status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
@@ -12566,6 +12596,7 @@ ComponentDef<WorldZoneData>
biome: string
excludes: string
falloff: number
+flatten: boolean
kind: string
priority: number
radius: number
@@ -12585,6 +12616,7 @@ biome: string | undefined
excludes: readonly string[]
falloff: number
fields: Readonly<Record<string, number>> | undefined
+flatten: number | "ground" | undefined
id: string
kind: string
priority: number
@@ -13916,6 +13948,11 @@ EventBindingPlugin
(colour: readonly [number, number, number]): SkyRadiance
```
+## flattenModifier — function @experimental
+```
+(id: string, shape: { type: "circle"; x: number; z: number; radius: number; } | { type: "rect"; x: number; z: number; halfX: number; halfZ: number; yaw?: number; }, height: number, falloff: number): TerrainModifier
+```
+
## flattenPrefab — function @experimental
```
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index fc6059217..ca4beb357 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 161 beta · 1829 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1832 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5757,6 +5757,23 @@ completed: boolean | undefined
durationMs: number | undefined
```
+## ModifiedSource — class @experimental
+```
+base: TerrainSource
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+origin: { x: number; y: number; z: number; }
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+touched: (x0: number, z0: number, x1: number, z1: number) => boolean
+static new (base: TerrainSource, modifiers: () => Iterable<TerrainModifier>, origin: { x: number; y: number; z: number; }, step: number): ModifiedSource
+static prototype: ModifiedSource
+```
+
## Modifiers — interface @experimental
```
alt: boolean
@@ -6084,6 +6101,7 @@ atlasSize: number
capacity: number
claim: (key: string, min: number, max: number) => Page | null
clear: () => void
+forget: (test: (key: string) => boolean) => void
get: (key: string) => Page | undefined
origin: (slot: number) => [number, number]
perRow: number
@@ -10005,6 +10023,13 @@ world: string
{ readonly Area: 0; readonly Infinite: 1; }
```
+## TerrainModifier — interface @experimental
+```
+apply: (x: number, z: number, h: number) => number
+bounds: readonly [number, number, number, number]
+id: string
+```
+
## TerrainNode — interface @experimental
```
ix: number
@@ -10078,16 +10103,21 @@ static prototype: TerrainUnavailable
```
@internal app_: App | null
@internal built_: Map<number, Built>
+@internal modifiers_: Map<string, TerrainModifier>
@internal paint_: Repaint | null
+@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
+deleteModifier: (id: string) => void
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
+heightBeneathAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
+setModifier: (modifier: TerrainModifier) => void
setPaint: (paint: Repaint | null) => void
status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
@@ -12348,6 +12378,7 @@ ComponentDef<WorldZoneData>
biome: string
excludes: string
falloff: number
+flatten: boolean
kind: string
priority: number
radius: number
@@ -12367,6 +12398,7 @@ biome: string | undefined
excludes: readonly string[]
falloff: number
fields: Readonly<Record<string, number>> | undefined
+flatten: number | "ground" | undefined
id: string
kind: string
priority: number
@@ -13658,6 +13690,11 @@ EventBindingPlugin
(colour: readonly [number, number, number]): SkyRadiance
```
+## flattenModifier — function @experimental
+```
+(id: string, shape: { type: "circle"; x: number; z: number; radius: number; } | { type: "rect"; x: number; z: number; halfX: number; halfZ: number; yaw?: number; }, height: number, falloff: number): TerrainModifier
+```
+
## flattenPrefab — function @experimental
```
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 2419d79b1..2f40f4b2a 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1851 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1854 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -6050,6 +6050,23 @@ completed: boolean | undefined
durationMs: number | undefined
```
+## ModifiedSource — class @experimental
+```
+base: TerrainSource
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+origin: { x: number; y: number; z: number; }
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+touched: (x0: number, z0: number, x1: number, z1: number) => boolean
+static new (base: TerrainSource, modifiers: () => Iterable<TerrainModifier>, origin: { x: number; y: number; z: number; }, step: number): ModifiedSource
+static prototype: ModifiedSource
+```
+
## Modifiers — interface @experimental
```
alt: boolean
@@ -6377,6 +6394,7 @@ atlasSize: number
capacity: number
claim: (key: string, min: number, max: number) => Page | null
clear: () => void
+forget: (test: (key: string) => boolean) => void
get: (key: string) => Page | undefined
origin: (slot: number) => [number, number]
perRow: number
@@ -10298,6 +10316,13 @@ world: string
{ readonly Area: 0; readonly Infinite: 1; }
```
+## TerrainModifier — interface @experimental
+```
+apply: (x: number, z: number, h: number) => number
+bounds: readonly [number, number, number, number]
+id: string
+```
+
## TerrainNode — interface @experimental
```
ix: number
@@ -10371,16 +10396,21 @@ static prototype: TerrainUnavailable
```
@internal app_: App | null
@internal built_: Map<number, Built>
+@internal modifiers_: Map<string, TerrainModifier>
@internal paint_: Repaint | null
+@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
+deleteModifier: (id: string) => void
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
+heightBeneathAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
+setModifier: (modifier: TerrainModifier) => void
setPaint: (paint: Repaint | null) => void
status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
@@ -12647,6 +12677,7 @@ ComponentDef<WorldZoneData>
biome: string
excludes: string
falloff: number
+flatten: boolean
kind: string
priority: number
radius: number
@@ -12666,6 +12697,7 @@ biome: string | undefined
excludes: readonly string[]
falloff: number
fields: Readonly<Record<string, number>> | undefined
+flatten: number | "ground" | undefined
id: string
kind: string
priority: number
@@ -13962,6 +13994,11 @@ EventBindingPlugin
(colour: readonly [number, number, number]): SkyRadiance
```
+## flattenModifier — function @experimental
+```
+(id: string, shape: { type: "circle"; x: number; z: number; radius: number; } | { type: "rect"; x: number; z: number; halfX: number; halfZ: number; yaw?: number; }, height: number, falloff: number): TerrainModifier
+```
+
## flattenPrefab — function @experimental
```
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
diff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.md
index 76c2d8c89..e42f7c200 100644
--- a/sdk/etc/terrain.api.md
+++ b/sdk/etc/terrain.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/terrain
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 49 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 52 experimental · 0 deprecated
## Eroded — interface @experimental
```
@@ -39,6 +39,23 @@ height: number
width: number
```
+## ModifiedSource — class @experimental
+```
+base: TerrainSource
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+origin: { x: number; y: number; z: number; }
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+touched: (x0: number, z0: number, x1: number, z1: number) => boolean
+static new (base: TerrainSource, modifiers: () => Iterable<TerrainModifier>, origin: { x: number; y: number; z: number; }, step: number): ModifiedSource
+static prototype: ModifiedSource
+```
+
## NOISE_PROVIDER — const @experimental
```
"estella:noise"
@@ -101,6 +118,7 @@ atlasSize: number
capacity: number
claim: (key: string, min: number, max: number) => Page | null
clear: () => void
+forget: (test: (key: string) => boolean) => void
get: (key: string) => Page | undefined
origin: (slot: number) => [number, number]
perRow: number
@@ -203,6 +221,13 @@ world: string
{ readonly Area: 0; readonly Infinite: 1; }
```
+## TerrainModifier — interface @experimental
+```
+apply: (x: number, z: number, h: number) => number
+bounds: readonly [number, number, number, number]
+id: string
+```
+
## TerrainNode — interface @experimental
```
ix: number
@@ -276,16 +301,21 @@ static prototype: TerrainUnavailable
```
@internal app_: App | null
@internal built_: Map<number, Built>
+@internal modifiers_: Map<string, TerrainModifier>
@internal paint_: Repaint | null
+@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
+deleteModifier: (id: string) => void
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
+heightBeneathAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
+setModifier: (modifier: TerrainModifier) => void
setPaint: (paint: Repaint | null) => void
status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
@@ -317,6 +347,11 @@ ResourceDef<Terrains>
(field: Heightfield, p: ErosionParams): Generator<number, Eroded, void>
```
+## flattenModifier — function @experimental
+```
+(id: string, shape: { type: "circle"; x: number; z: number; radius: number; } | { type: "rect"; x: number; z: number; halfX: number; halfZ: number; yaw?: number; }, height: number, falloff: number): TerrainModifier
+```
+
## heightfieldFromPixels — function @experimental
```
(width: number, height: number, pixels: ArrayLike<number>): Heightfield
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 291b7d2c0..12bde0c6b 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1842 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1845 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5764,6 +5764,23 @@ completed: boolean | undefined
durationMs: number | undefined
```
+## ModifiedSource — class @experimental
+```
+base: TerrainSource
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+origin: { x: number; y: number; z: number; }
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+touched: (x0: number, z0: number, x1: number, z1: number) => boolean
+static new (base: TerrainSource, modifiers: () => Iterable<TerrainModifier>, origin: { x: number; y: number; z: number; }, step: number): ModifiedSource
+static prototype: ModifiedSource
+```
+
## Modifiers — interface @experimental
```
alt: boolean
@@ -6091,6 +6108,7 @@ atlasSize: number
capacity: number
claim: (key: string, min: number, max: number) => Page | null
clear: () => void
+forget: (test: (key: string) => boolean) => void
get: (key: string) => Page | undefined
origin: (slot: number) => [number, number]
perRow: number
@@ -10012,6 +10030,13 @@ world: string
{ readonly Area: 0; readonly Infinite: 1; }
```
+## TerrainModifier — interface @experimental
+```
+apply: (x: number, z: number, h: number) => number
+bounds: readonly [number, number, number, number]
+id: string
+```
+
## TerrainNode — interface @experimental
```
ix: number
@@ -10085,16 +10110,21 @@ static prototype: TerrainUnavailable
```
@internal app_: App | null
@internal built_: Map<number, Built>
+@internal modifiers_: Map<string, TerrainModifier>
@internal paint_: Repaint | null
+@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
+deleteModifier: (id: string) => void
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
+heightBeneathAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
+setModifier: (modifier: TerrainModifier) => void
setPaint: (paint: Repaint | null) => void
status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
@@ -12379,6 +12409,7 @@ ComponentDef<WorldZoneData>
biome: string
excludes: string
falloff: number
+flatten: boolean
kind: string
priority: number
radius: number
@@ -12398,6 +12429,7 @@ biome: string | undefined
excludes: readonly string[]
falloff: number
fields: Readonly<Record<string, number>> | undefined
+flatten: number | "ground" | undefined
id: string
kind: string
priority: number
@@ -13689,6 +13721,11 @@ EventBindingPlugin
(colour: readonly [number, number, number]): SkyRadiance
```
+## flattenModifier — function @experimental
+```
+(id: string, shape: { type: "circle"; x: number; z: number; radius: number; } | { type: "rect"; x: number; z: number; halfX: number; halfZ: number; yaw?: number; }, height: number, falloff: number): TerrainModifier
+```
+
## flattenPrefab — function @experimental
```
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
diff --git a/sdk/etc/worldgen.api.md b/sdk/etc/worldgen.api.md
index ad95ca466..a4fa93ff9 100644
--- a/sdk/etc/worldgen.api.md
+++ b/sdk/etc/worldgen.api.md
@@ -278,6 +278,7 @@ ComponentDef<WorldZoneData>
biome: string
excludes: string
falloff: number
+flatten: boolean
kind: string
priority: number
radius: number
@@ -292,6 +293,7 @@ biome: string | undefined
excludes: readonly string[]
falloff: number
fields: Readonly<Record<string, number>> | undefined
+flatten: number | "ground" | undefined
id: string
kind: string
priority: number
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index b97921645..2614c96fa 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -834,7 +834,7 @@ export {
erodeHeightfield, erosionJob, heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,
type Eroded, type ErosionParams, type Heightfield, type ProceduralParams,
} from './terrain/heightfield';
-export { FieldSource, NoiseSource, noised, type NoiseParams, type Splat, type TerrainSource } from './terrain/source';
+export { FieldSource, NoiseSource, ModifiedSource, flattenModifier, noised, type NoiseParams, type Splat, type TerrainSource, type TerrainModifier } from './terrain/source';
export { boxDistance, levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './terrain/quadtree';
export { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type Page, type PageImage } from './terrain/pages';
export { buildPatchMesh } from './terrain/patch';
diff --git a/sdk/src/terrain/index.ts b/sdk/src/terrain/index.ts
index 34c011ecf..0f01a157c 100644
--- a/sdk/src/terrain/index.ts
+++ b/sdk/src/terrain/index.ts
@@ -7,7 +7,7 @@ export {
erodeHeightfield, erosionJob, heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,
type Eroded, type ErosionParams, type Heightfield, type ProceduralParams,
} from './heightfield';
-export { FieldSource, NoiseSource, noised, type NoiseParams, type Splat, type TerrainSource } from './source';
+export { FieldSource, NoiseSource, ModifiedSource, flattenModifier, noised, type NoiseParams, type Splat, type TerrainSource, type TerrainModifier } from './source';
export { boxDistance, levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './quadtree';
export { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type Page, type PageImage } from './pages';
export { buildPatchMesh } from './patch';
diff --git a/sdk/src/terrain/pages.ts b/sdk/src/terrain/pages.ts
index 8b4879f03..363648b8a 100644
--- a/sdk/src/terrain/pages.ts
+++ b/sdk/src/terrain/pages.ts
@@ -130,6 +130,15 @@ export class PageTable {
return page;
}
+ /** Forgets the pages `test` names (the ground changed under them): they are made again as they are wanted. */
+ forget(test: (key: string) => boolean): void {
+ for (const [key, page] of this.pages_) {
+ if (!test(key)) continue;
+ this.pages_.delete(key);
+ this.free_.push(page.slot);
+ }
+ }
+
/** Forgets every page (the device lost the atlas, or the ground changed). */
clear(): void {
this.pages_.clear();
diff --git a/sdk/src/terrain/source.ts b/sdk/src/terrain/source.ts
index 23154ddd1..afc9d8f40 100644
--- a/sdk/src/terrain/source.ts
+++ b/sdk/src/terrain/source.ts
@@ -202,3 +202,118 @@ function smooth(a: number, b: number, x: number): number {
const t = Math.min(Math.max((x - a) / (b - a || 1e-6), 0), 1);
return t * t * (3 - 2 * t);
}
+
+/**
+ * A change made to the ground over part of the world (a building's plot levelled, a riverbed cut): in world space, a height in and a
+ * height out. Modifiers are applied in the order they were set, inside their bounds only.
+ */
+export interface TerrainModifier {
+ readonly id: string;
+ /** The world square it can change, [minX, minZ, maxX, maxZ], its edge included. */
+ readonly bounds: readonly [number, number, number, number];
+ /** The world height at world (x, z), given the height the ground has there. */
+ apply(x: number, z: number, h: number): number;
+}
+
+/** A source with the modifiers laid over it: what the pages, the queries and collision all read. */
+export class ModifiedSource implements TerrainSource {
+ readonly infinite: boolean;
+ readonly bounds: TerrainSource['bounds'];
+ readonly minHeight: number;
+ readonly maxHeight: number;
+ /** The terrain's world position: its space is this far from the world's. Kept current by the terrain. */
+ origin: { x: number; y: number; z: number };
+
+ constructor(readonly base: TerrainSource, private readonly modifiers: () => Iterable<TerrainModifier>,
+ origin: { x: number; y: number; z: number }, private readonly step: number) {
+ this.infinite = base.infinite;
+ this.bounds = base.bounds;
+ this.minHeight = base.minHeight;
+ this.maxHeight = base.maxHeight;
+ this.origin = { ...origin };
+ }
+
+ height(x: number, z: number): number | null {
+ const h = this.base.height(x, z);
+ return h === null ? null : this.modify(x, z, h);
+ }
+
+ normal(x: number, z: number): [number, number, number] | null {
+ if (!this.touched(x - this.step, z - this.step, x + this.step, z + this.step)) return this.base.normal(x, z);
+ const e = this.step;
+ const l = this.height(x - e, z), r = this.height(x + e, z), d = this.height(x, z - e), u = this.height(x, z + e);
+ if (l === null || r === null || d === null || u === null) return null;
+ const sx = (r - l) / (2 * e), sz = (u - d) / (2 * e), len = Math.hypot(sx, 1, sz);
+ return [-sx / len, 1 / len, -sz / len];
+ }
+
+ paint(x: number, z: number, h: number, ny: number): [number, number, number, number] {
+ return this.base.paint(x, z, h, ny);
+ }
+
+ get region(): TerrainSource['region'] {
+ const region = this.base.region?.bind(this.base);
+ if (!region) return undefined;
+ return (x0, z0, spacing, count) => {
+ const got = region(x0, z0, spacing, count);
+ const lay = (r: { heights: Float32Array; paint?: Float32Array }) => {
+ if (!this.touched(x0, z0, x0 + spacing * (count - 1), z0 + spacing * (count - 1))) return r;
+ const heights = new Float32Array(r.heights);
+ for (let j = 0; j < count; j++) for (let i = 0; i < count; i++) {
+ heights[j * count + i] = this.modify(x0 + i * spacing, z0 + j * spacing, heights[j * count + i]!);
+ }
+ return { ...r, heights };
+ };
+ return got instanceof Promise ? got.then(lay) : lay(got);
+ };
+ }
+
+ /** Whether any modifier can change something in the square [x0, x1] by [z0, z1] of the terrain's space. */
+ touched(x0: number, z0: number, x1: number, z1: number): boolean {
+ const ox = this.origin.x, oz = this.origin.z;
+ for (const m of this.modifiers()) {
+ const b = m.bounds;
+ if (b[0] <= x1 + ox && b[2] >= x0 + ox && b[1] <= z1 + oz && b[3] >= z0 + oz) return true;
+ }
+ return false;
+ }
+
+ private modify(x: number, z: number, h: number): number {
+ const wx = x + this.origin.x, wz = z + this.origin.z, oy = this.origin.y;
+ let out = h + oy;
+ for (const m of this.modifiers()) {
+ const b = m.bounds;
+ if (wx < b[0] || wx > b[2] || wz < b[1] || wz > b[3]) continue;
+ out = m.apply(wx, wz, out);
+ }
+ return Math.min(Math.max(out - oy, this.minHeight), this.maxHeight);
+ }
+}
+
+/**
+ * Levels the ground to world height `height` over a circle or a turned rectangle, blending back to the ground over `falloff` world
+ * units past its outline: a plot built on, a landing pad, a road's bed.
+ */
+export function flattenModifier(id: string, shape:
+ | { type: 'circle'; x: number; z: number; radius: number }
+ | { type: 'rect'; x: number; z: number; halfX: number; halfZ: number; yaw?: number }, height: number, falloff: number): TerrainModifier {
+ const reach = (shape.type === 'circle' ? shape.radius : Math.hypot(shape.halfX, shape.halfZ)) + Math.max(falloff, 0);
+ const outside = (x: number, z: number): number => {
+ if (shape.type === 'circle') return Math.hypot(x - shape.x, z - shape.z) - shape.radius;
+ const c = Math.cos(-(shape.yaw ?? 0)), s = Math.sin(-(shape.yaw ?? 0));
+ const dx = x - shape.x, dz = z - shape.z;
+ const lx = Math.abs(dx * c - dz * s) - shape.halfX, lz = Math.abs(dx * s + dz * c) - shape.halfZ;
+ return Math.hypot(Math.max(lx, 0), Math.max(lz, 0)) + Math.min(Math.max(lx, lz), 0);
+ };
+ return {
+ id,
+ bounds: [shape.x - reach, shape.z - reach, shape.x + reach, shape.z + reach],
+ apply(x, z, h) {
+ const d = outside(x, z);
+ if (d <= 0) return height;
+ if (falloff <= 0 || d >= falloff) return h;
+ const t = 1 - d / falloff, w = t * t * (3 - 2 * t);
+ return h + (height - h) * w;
+ },
+ };
+}
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
index 9055cf18b..3d5934150 100644
--- a/sdk/src/terrain/terrainPlugin.ts
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -37,7 +37,7 @@ import { log } from '../util/logger';
import { bakesOf } from '../runtime/bakes';
import type { Color, Entity } from '../types';
import { erosionJob, heightfieldFromPixels, type Heightfield } from './heightfield';
-import { FieldSource, type TerrainSource } from './source';
+import { FieldSource, ModifiedSource, type TerrainModifier, type TerrainSource } from './source';
import { levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './quadtree';
import { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage, type Repaint } from './pages';
import { noiseProvider, ProviderSource, terrainProvider, terrainProvidersRevision, TerrainUnavailable, type TerrainProvider } from './provider';
@@ -212,6 +212,8 @@ interface Built {
pending: boolean;
/** Why the ground could not be made, once it could not: nothing is drawn or answered for it. */
failure: string | null;
+ /** Bumped whenever modifiers change the ground under it: a page asked for before is thrown away when it lands. */
+ edits: number;
}
/** Where a terrain's ground stands: still being made, ready, or failed (with why). */
@@ -239,6 +241,22 @@ export class Terrains {
return null;
}
+ /** The world height of the ground at (x, z) as it was made, under every modifier laid over it: what a plot is levelled from. */
+ heightBeneathAt(x: number, z: number): number | null {
+ const world = this.app_?.world;
+ if (!world) return null;
+ for (const [entity, built] of this.built_) {
+ const source = built.source;
+ if (!source || !world.valid(entity)) continue;
+ const t = world.tryGet(entity, Transform) as TransformData | null;
+ if (!t) continue;
+ const base = source instanceof ModifiedSource ? source.base : source;
+ const h = base.height(x - t.worldPosition.x, z - t.worldPosition.z);
+ if (h !== null) return t.worldPosition.y + h;
+ }
+ return null;
+ }
+
/** Where the ground faces at (x, z) (a unit normal), or null where no terrain is. */
normalAt(x: number, z: number): [number, number, number] | null {
const world = this.app_?.world;
@@ -320,6 +338,46 @@ export class Terrains {
return { state: built.loading || !built.source ? 'loading' : 'ready' };
}
+ /** @internal The modifiers laid over every terrain's ground, by id, in the order they were set. */
+ readonly modifiers_ = new Map<string, TerrainModifier>();
+
+ /**
+ * Lays `modifier` over the ground (or replaces the one with its id): the drawn ground, its queries and its collision all follow it,
+ * and only what it reaches is made again.
+ */
+ setModifier(modifier: TerrainModifier): void {
+ const had = this.modifiers_.get(modifier.id);
+ this.modifiers_.set(modifier.id, modifier);
+ if (had) this.remake_(had.bounds);
+ this.remake_(modifier.bounds);
+ }
+
+ /** Takes a modifier off the ground. */
+ deleteModifier(id: string): void {
+ const had = this.modifiers_.get(id);
+ if (!had) return;
+ this.modifiers_.delete(id);
+ this.remake_(had.bounds);
+ }
+
+ /** @internal Makes again what the world square `b` reaches: its pages and its collision, and what stands on the ground. */
+ remake_(b: readonly [number, number, number, number]): void {
+ const app = this.app_;
+ for (const [entity, built] of this.built_) {
+ const source = built.source;
+ if (!(source instanceof ModifiedSource)) continue;
+ const o = source.origin, leaf = PATCH_CELLS * Math.max(built.data.cellSize, 1e-3);
+ built.table.forget((key) => {
+ const [level, ix, iz] = key.split(':').map(Number) as [number, number, number];
+ const size = leaf * 2 ** level, x0 = ix * size + o.x, z0 = iz * size + o.z;
+ return x0 <= b[2] && x0 + size >= b[0] && z0 <= b[3] && z0 + size >= b[1];
+ });
+ built.edits++;
+ if (app?.hasResource(ProceduralChunksRes)) app.getResource(ProceduralChunksRes).invalidate(collisionLayerOf(entity), b[0], b[1], b[2], b[3]);
+ }
+ this.revision_++;
+ }
+
/** @internal What has the last word on the ground's paint, in world space (a world's biomes), if anything does. */
paint_: Repaint | null = null;
@@ -440,13 +498,21 @@ export class TerrainPlugin implements Plugin {
built = {
signature, data: { ...data }, source: null, surface: null, epoch: (built?.epoch ?? 0) + 1, loading: true, cancel: null,
table: new PageTable(ATLAS_SIZE), heights: 0, paint: 0, mesh: 0, instance: 0,
- nodes: new Map(), spare: [], wanted: new Map(), asked: new Set(), pending: false, failure: null,
+ nodes: new Map(), spare: [], wanted: new Map(), asked: new Set(), pending: false, failure: null, edits: 0,
};
terrains.built_.set(entity, built);
void this.load(app, entity, built);
continue;
}
built.data = { ...data };
+ // Modifiers are the world's: a terrain moved stands under them somewhere else, so what they reached is made again.
+ if (built.source instanceof ModifiedSource) {
+ const at = (app.world.get(entity, Transform) as TransformData).worldPosition, o = built.source.origin;
+ if (at.x !== o.x || at.y !== o.y || at.z !== o.z) {
+ built.source.origin = { x: at.x, y: at.y, z: at.z };
+ for (const m of terrains.modifiers_.values()) terrains.remake_(m.bounds);
+ }
+ }
this.collide(app, entity, built);
if (built.loading || !built.source || !rendering) continue;
if (!built.instance) {
@@ -513,6 +579,9 @@ export class TerrainPlugin implements Plugin {
}
built.source = new FieldSource(field, data, splat, flow, range);
}
+ // The modifiers set on the ground (a plot levelled, a bed cut) are laid over it, for the pages, the queries and collision alike.
+ const terrains = app.getResource(TerrainsRes);
+ built.source = new ModifiedSource(built.source, () => terrains.modifiers_.values(), t.worldPosition, Math.max(data.cellSize, 1e-3));
built.surface = new TerrainSurface(built.source, Math.max(data.cellSize, 1e-3));
app.getResource(TerrainsRes).revision_++;
} catch (e) {
@@ -728,7 +797,7 @@ export class TerrainPlugin implements Plugin {
updateTextureSubregion(app.wasmModule, built.paint, ox, oy, PAGE_SIDE, PAGE_SIDE, image.paint);
return true;
};
- const epoch = built.epoch;
+ const epoch = built.epoch, edits = built.edits;
for (const node of order) {
const key = nodeKey(node.level, node.ix, node.iz);
if (built.asked.has(key)) continue;
@@ -739,7 +808,7 @@ export class TerrainPlugin implements Plugin {
built.asked.add(key);
void image.then((img) => {
built.asked.delete(key);
- if (built.epoch === epoch && built.heights) store(key, img);
+ if (built.epoch === epoch && built.edits === edits && built.heights) store(key, img);
}, (e) => {
built.asked.delete(key);
log.warn('terrain', `the provider failed a page (${key})`, e);
diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.ts
index 81d6cb610..d417544ec 100644
--- a/sdk/src/worldgen/worldgenPlugin.ts
+++ b/sdk/src/worldgen/worldgenPlugin.ts
@@ -28,7 +28,8 @@ import { Assets } from '../asset/AssetPlugin';
import type { MeshData } from '../asset/meshFormat';
import { log } from '../util/logger';
import type { Entity } from '../types';
-import { TerrainsRes } from '../terrain/terrainPlugin';
+import { Terrains, TerrainsRes } from '../terrain/terrainPlugin';
+import { flattenModifier, type TerrainModifier } from '../terrain/source';
import { buildBillboardMesh, buildInstancedMesh, type Plant } from '../foliage/builder';
import { chunksOf, ProceduralChunksRes, type ChunkLayerStatus } from '../residency/chunks';
import { Environment } from './fields';
@@ -84,6 +85,8 @@ export interface WorldZoneData {
excludes: string;
/** A biome it holds over its area; empty holds none. */
biome: string;
+ /** Whether it levels the terrain under it to the ground's height at its centre. */
+ flatten: boolean;
}
/**
@@ -93,7 +96,7 @@ export interface WorldZoneData {
* @experimental
*/
export const WorldZone: ComponentDef<WorldZoneData> = defineComponent<WorldZoneData>('WorldZone', {
- kind: 'reserve', shape: ZoneShapeKind.Circle, radius: 10, sizeX: 20, sizeZ: 20, falloff: 4, priority: 0, excludes: '*', biome: '',
+ kind: 'reserve', shape: ZoneShapeKind.Circle, radius: 10, sizeX: 20, sizeZ: 20, falloff: 4, priority: 0, excludes: '*', biome: '', flatten: false,
}, {
fields: {
kind: { tooltip: 'What the zone is for (home, road, landing, building, resource, view): the game\'s own words.' },
@@ -105,6 +108,7 @@ export const WorldZone: ComponentDef<WorldZoneData> = defineComponent<WorldZoneD
priority: { step: 1, tooltip: 'Where zones overlap, the higher priority holds the biome.' },
excludes: { tooltip: 'The tags of what the zone keeps out, separated by commas (a layer, a recipe, its tags, decor, interactive); * keeps out everything; empty keeps nothing out.' },
biome: { tooltip: 'A biome the zone holds over its area; empty holds none.' },
+ flatten: { tooltip: 'Level the terrain under the zone to the ground\'s height at its centre, blending back over its falloff: a plot to build on.' },
},
});
@@ -140,6 +144,8 @@ interface BuiltWorld {
ground: string;
/** The zones' revision the authored zones were last synced at. */
authored: Set<string>;
+ /** Zones that level their ground and wait for it to be known. */
+ levelling: Set<string>;
}
/** A chunk of a layer: what it places (its decoration merged by mesh, its interactive placements), and what it put in the world. */
@@ -250,7 +256,7 @@ export class WorldGenPlugin implements Plugin {
/** A WorldGen's rules and plan, or why it has none. */
private make(app: App, gens: WorldGens, entity: Entity, data: WorldGenData, had: BuiltWorld | undefined): BuiltWorld {
- const built: BuiltWorld = { signature: `${JSON.stringify(data)}#${worldRulesRevision()}`, data: { ...data }, rules: null, plan: null, failure: null, ground: '', authored: had?.authored ?? new Set() };
+ const built: BuiltWorld = { signature: `${JSON.stringify(data)}#${worldRulesRevision()}`, data: { ...data }, rules: null, plan: null, failure: null, ground: '', authored: had?.authored ?? new Set(), levelling: new Set() };
const rules = worldRules(data.rules);
if (!rules) built.failure = `no world rules ${data.rules || '(none named)'} are registered`;
else if (!rules.versions.includes(data.version)) built.failure = `the world rules ${rules.id} have no version ${data.version} (they have ${rules.versions.join(', ')})`;
@@ -334,12 +340,29 @@ export class WorldGenPlugin implements Plugin {
}
// A zone that holds a biome or sets a field changes the ground's paint under it.
if (terrains && data.paintGround && (zone.biome || zone.fields)) terrains.repaint();
+ // One that levels its ground lays a modifier on the terrain, and takes it off when it goes or stops levelling.
+ if (terrains) {
+ const now = zones.get(zone.id);
+ if (now?.flatten !== undefined) this.level(terrains, built, now);
+ else {
+ built.levelling.delete(zone.id);
+ if (terrains.modifiers_.has(`zone:${zone.id}`)) terrains.deleteModifier(`zone:${zone.id}`);
+ }
+ }
};
gens.diffs(data.world).onChange = (id) => {
const at = this.anchorOf(plan, id);
if (at) chunksOf(app).invalidate(layerIdOf(entity, at.layer), at.x, at.z, at.x, at.z);
};
if (terrains) terrains.setPaint(data.paintGround ? this.painter(plan) : null);
+ // Zones that were there before the plan was made level their ground now.
+ if (terrains) for (const zone of zones.all()) if (zone.flatten !== undefined) this.level(terrains, built, zone);
+ }
+
+ /** Levels a zone's ground, or (the ground under its centre not known yet) keeps it to level once it is. */
+ private level(terrains: Terrains, built: BuiltWorld, zone: ZoneDef): void {
+ const modifier = levelling(terrains, zone);
+ if (modifier) { terrains.setModifier(modifier); built.levelling.delete(zone.id); } else built.levelling.add(zone.id);
}
/** The ground's paint by a plan's biomes. */
@@ -373,6 +396,7 @@ export class WorldGenPlugin implements Plugin {
: { type: 'circle', x: p.x, z: p.z, radius: z.radius },
excludes: z.excludes.split(',').map((s) => s.trim()).filter(Boolean),
...(z.biome ? { biome: z.biome } : {}),
+ ...(z.flatten ? { flatten: 'ground' as const } : {}),
};
zones.set(def);
seen.add(def.id);
@@ -391,6 +415,12 @@ export class WorldGenPlugin implements Plugin {
const ground = `${terrains?.revision_ ?? 0}:${water?.revision_ ?? 0}`;
if (ground !== built.ground) { plan.invalidate(); built.ground = ground; }
const waiting = !!terrains?.loading || !!water?.baking;
+ if (terrains) {
+ for (const id of [...built.levelling]) {
+ const zone = gens.zones(built.data.world).get(id);
+ if (zone?.flatten !== undefined) this.level(terrains, built, zone); else built.levelling.delete(id);
+ }
+ }
const diffs = gens.diffs(built.data.world);
const rendering = app.hasResource(Assets);
const chunks = chunksOf(app);
@@ -547,6 +577,13 @@ export class WorldGenPlugin implements Plugin {
}
}
+/** The modifier a levelling zone lays on the terrain: its outline, to its height or the ground's at its centre, over its falloff. */
+function levelling(terrains: Terrains, zone: ZoneDef): TerrainModifier | null {
+ const s = zone.shape;
+ const height = zone.flatten === 'ground' ? terrains.heightBeneathAt(s.x, s.z) : zone.flatten!;
+ return height === null || height === undefined ? null : flattenModifier(`zone:${zone.id}`, s, height, zone.falloff);
+}
+
/** The meshes and materials a rule set's recipes name by path. */
function assetRefsOf(rules: WorldRules): { kind: 'mesh' | 'material'; ref: string }[] {
const seen = new Map<string, { kind: 'mesh' | 'material'; ref: string }>();
diff --git a/sdk/src/worldgen/zones.ts b/sdk/src/worldgen/zones.ts
index 8a216fd14..0290ddf0e 100644
--- a/sdk/src/worldgen/zones.ts
+++ b/sdk/src/worldgen/zones.ts
@@ -31,6 +31,11 @@ export interface ZoneDef {
biome?: string;
/** Fields it sets over its area. */
fields?: Readonly<Record<string, number>>;
+ /**
+ * Levels the terrain under it: to this world height, or ('ground') to the ground's height at its centre as the ground was made,
+ * blending back over its falloff. What it levels is the terrain's for good, until the zone goes.
+ */
+ flatten?: number | 'ground';
}
/** How far (x, z) is outside a zone's outline: negative inside. */
diff --git a/sdk/tests/terrain-provider.test.ts b/sdk/tests/terrain-provider.test.ts
index 09df8cfc3..ccdb20d73 100644
--- a/sdk/tests/terrain-provider.test.ts
+++ b/sdk/tests/terrain-provider.test.ts
@@ -11,7 +11,7 @@ import {
noiseProvider, ProviderSource, registerTerrainProvider, TerrainUnavailable, type TerrainProvider, type TerrainRegion,
} from '../src/terrain/provider';
import { makePage, PAGE_SIDE, PAGE_TEXELS, type PageImage } from '../src/terrain/pages';
-import type { NoiseParams } from '../src/terrain/source';
+import { flattenModifier, type NoiseParams } from '../src/terrain/source';
const params: NoiseParams = { seed: 7, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.35, warp: 0.3, erosion: 1, sizeX: 2000, height: 300,
rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88 };
@@ -189,3 +189,41 @@ describe('a Terrain with no renderer (a server)', () => {
expect(terrains.heightAt(0, 0)).toBeNull();
});
});
+
+describe('modifiers on the ground', () => {
+ const boot = (): App => {
+ setDefaultContext(new AppContext());
+ setEditorMode(false);
+ setPlayMode(false);
+ const app = App.new();
+ const module = createMockModule();
+ app.connectCpp(module.getRegistry(), module);
+ app.addPlugin(new TerrainPlugin());
+ return app;
+ };
+ const settle = async (app: App) => { for (let i = 0; i < 4; i++) { app.tick(1 / 60); await new Promise((r) => setTimeout(r, 0)); } };
+
+ it('level a plot for every reader, blend back at its edge, and leave the ground as it was when taken off', async () => {
+ const app = boot();
+ const e = app.world.spawn();
+ app.world.insert(e, Transform, { position: { x: 0, y: 0, z: 0 }, worldPosition: { x: 0, y: 0, z: 0 } });
+ app.world.insert(e, Terrain, { ...Terrain._default, extent: TerrainExtent.Infinite, ...params });
+ await settle(app);
+ const terrains = app.getResource(TerrainsRes);
+ const before = [terrains.heightAt(0, 0)!, terrains.heightAt(60, 0)!, terrains.heightAt(200, 0)!];
+ const revision = terrains.revision_;
+ terrains.setModifier(flattenModifier('plot', { type: 'circle', x: 0, z: 0, radius: 40 }, 123, 30));
+ expect(terrains.heightAt(0, 0)).toBeCloseTo(123, 6);
+ expect(terrains.heightAt(20, -20)).toBeCloseTo(123, 6);
+ expect(terrains.normalAt(10, 10)![1]).toBeCloseTo(1, 6);
+ // Halfway through its edge, between the plot and the ground; past it, the ground untouched.
+ const mid = terrains.heightAt(55, 0)!;
+ expect(Math.min(123, terrains.heightBeneathAt(55, 0)!) - 1e-6).toBeLessThanOrEqual(mid);
+ expect(terrains.heightAt(200, 0)).toBeCloseTo(before[2]!, 9);
+ expect(terrains.heightBeneathAt(0, 0)).toBeCloseTo(before[0]!, 9);
+ expect(terrains.revision_).toBeGreaterThan(revision);
+ terrains.deleteModifier('plot');
+ expect(terrains.heightAt(0, 0)).toBeCloseTo(before[0]!, 9);
+ expect(terrains.heightAt(60, 0)).toBeCloseTo(before[1]!, 9);
+ });
+});
diff --git a/sdk/tests/worldgen-plugin.test.ts b/sdk/tests/worldgen-plugin.test.ts
index 224fb4ed2..a996e2537 100644
--- a/sdk/tests/worldgen-plugin.test.ts
+++ b/sdk/tests/worldgen-plugin.test.ts
@@ -16,6 +16,7 @@ import {
} from '../src/worldgen/worldgenPlugin';
import { registerWorldRules, type WorldRules } from '../src/worldgen/rules';
import type { Entity } from '../src/types';
+import { Terrain, TerrainExtent, TerrainPlugin, TerrainsRes } from '../src/terrain/terrainPlugin';
const rules: WorldRules = {
id: 'test:ores', versions: [1],
@@ -125,3 +126,25 @@ describe('a generated world with no renderer', () => {
expect(objects(app)).toHaveLength(0);
});
});
+
+describe('a zone that levels its ground', () => {
+ it('lays the terrain flat under it at the height the ground had at its centre, and gives it back when it goes', async () => {
+ const app = boot();
+ app.addPlugin(new TerrainPlugin());
+ const ground = app.world.spawn();
+ app.world.insert(ground, Transform, placed(0, 0, 0));
+ app.world.insert(ground, Terrain, { ...Terrain._default, extent: TerrainExtent.Infinite, height: 80, sizeX: 600 });
+ world(app);
+ const plot = app.world.spawn();
+ app.world.insert(plot, Transform, placed(30, 0, -20));
+ app.world.insert(plot, WorldZone, { ...WorldZone._default, kind: 'building', shape: ZoneShapeKind.Box, sizeX: 30, sizeZ: 20, falloff: 10, flatten: true });
+ await tick(app, 20);
+ const terrains = app.getResource(TerrainsRes);
+ const level = terrains.heightBeneathAt(30, -20)!;
+ for (const [x, z] of [[30, -20], [20, -15], [44, -27]] as const) expect(terrains.heightAt(x, z)).toBeCloseTo(level, 6);
+ app.world.despawn(plot);
+ await tick(app, 5);
+ // On a lattice node the surface is the ground's own sample.
+ expect(terrains.heightAt(20, -16)).toBeCloseTo(terrains.heightBeneathAt(20, -16)!, 9);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 6c78bd6af..0e3c343a6 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2792,4 +2792,6 @@ export const NOTED = {
{"note":"Rays against the terrain, anywhere."},
"feat(worldgen): decoration has a far version past its layer's lodDistance, and leans with the ground when it is aligned":
{"note":"Far versions for generated decoration."},
+ "feat(terrain): modifiers change the ground for every reader and remake only what they reach, and a zone can level its plot":
+ {"note":"Terrain modifiers, and zones that level their ground."},
};