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): an area without a heightmap is a window on its provider's ground, and ground read from a provider stays the world's when its terrain moves

yhhd833b9670650
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa93d29d4..54be5d892 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,7 @@ published separately; it ships inside the editor.
- **Procedural chunks, with one owner and one budget.** What a game makes as it runs is now chunks of layers in `ProceduralChunks` (`chunksOf(app)`): each layer says how it is cut, how far round the streaming sources it is wanted and how a chunk is made, published and released, and the chunks are made nearest first within the frame's budget (the one `Bakes.budgetMs`, shared with the bakes and the terrain's pages), released with everything they published past the unload radius, and made again when the layer's generation changes, the old version staying until the new one replaces it; an answer for an older generation is thrown away. `status` and `stateAt` say where they stand. Terrain collision and foliage cells are layers: plants now grow round the eye out to `drawDistance` and are let go past it, and a changed field or ground regrows them without blinking out.
- **Generated worlds.** The new `esengine/worldgen` lays a world out by a game's rules as it is explored: biomes weighed from fields (the terrain's height and slope, the water's depth, seeded moisture, temperature and rock, and a game's own), mixed at their edges and painting the terrain; recipes an artist composes (an anchor and members round it, with footprint apart from canopy) placed in layers, big things first, each keeping clear of what was placed before it; and `WorldZone`s (a home, a road, a building) that keep out what they name and hold a biome, fading at their edge. The same seed lays out the same world in whatever order its chunks are made, every placement has an id that outlives rules added later, interactive ones are entities with a `PlacedObject`, and what players change (`diffs().remove(id)`) is kept apart and laid over before anything is shown. `plan().explain(x, z)` says why anything stands or does not. A new example, Generated World, walks through one.
- **Which water a place is.** The sea fills only low ground joined to the open sea past the water zone's edge: a hollow below its level walled off by higher ground stays dry (or holds a lake of its own). A lake or a river is water only where its surface is over its ground, so a hill inside its outline is land, for what is drawn and what `Waters.sample` answers, whatever order the bodies were added in. `WaterBody.bodyId` names a body the same in every session; `Waters.sample` carries it and `Waters.bodyAt(x, z)` says which body a place belongs to. `findBasins` gives a game the ground's basins (each filled to the lowest point of its rim, with its outlet), the drainage down to the edge and the sea's reach, for deciding where its lakes and rivers go; `drainPath` follows the water from a point.
+- **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.
- **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 c6ce843b7..a4e980a83 100644
--- a/docs/WORLD_GENERATION_PLAN.md
+++ b/docs/WORLD_GENERATION_PLAN.md
@@ -20,7 +20,7 @@
- 需要:程序化区块数据入口,接收 `generateChunk(seed, algoVersion, cx, cz)` 或同职责的 provider;输入含星球/区块身份、生成器版本、世界坐标原点、采样间距、高度与群落权重;渲染、碰撞、放置、服务端共用同一数据。不替换已保存星球的旧算法。
- 失败处理:高度数据缺失或加载失败时,持久星球报告失败并保持旧数据或等待,不得悄悄回退为噪声。
-- 当前状态:已完成(e4937e148)。`TerrainProvider`(`sdk/src/terrain/provider.ts`)按区域采样(世界、种子、版本、世界坐标起点、间距、样本数),可异步;`registerTerrainProvider` 注册游戏自己的生成器,引擎噪声为 `estella:noise` 版本 1;`Terrain.provider/world/generatorVersion`;未注册、版本不存在、高度图读不到 → `Terrains.status` 为 failed 并给出原因,不回退噪声。测试 `sdk/tests/terrain-provider.test.ts`。仍欠:区域(Area)噪声仍按局部归一化,不用于连续世界;地形实体移动后 provider 原点不更新。
+- 当前状态:已完成(e4937e148)。`TerrainProvider`(`sdk/src/terrain/provider.ts`)按区域采样(世界、种子、版本、世界坐标起点、间距、样本数),可异步;`registerTerrainProvider` 注册游戏自己的生成器,引擎噪声为 `estella:noise` 版本 1;`Terrain.provider/world/generatorVersion`;未注册、版本不存在、高度图读不到 → `Terrains.status` 为 failed 并给出原因,不回退噪声。测试 `sdk/tests/terrain-provider.test.ts`。后续已补:无高度图的区域改为在世界坐标向其生成器取样(区域即生成器地面的窗口,相邻同尺寸区域无缝,可用游戏自定义生成器);以生成器取样的地形在实体移动后重建、世界地面不变。
- 验收:同版本/种子/坐标在客户端与服务端结果相同;不同加载顺序一致;共享边高度与法线一致;缺失数据不改变旧星球。
### T-02 碰撞、贴地查询与可视表面一致
diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdx
index 270af1379..ddbef62c2 100644
--- a/docs/astro/src/content/docs/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/graphics/terrain.mdx
@@ -14,7 +14,9 @@ Add a `Terrain` component to an entity. It is placed at that entity; its childre
The ground is one of two kinds, chosen by `extent`:
-- **Area**: ground `sizeX` by `sizeZ`, centred on the entity, from a heightmap or from noise made once. It may be worn by rain and
+- **Area**: ground `sizeX` by `sizeZ`, centred on the entity, from a heightmap or, without one, a window on its provider's ground
+ read where the area stands in the world (so two areas of the same size and noise side by side join, and an area is the same
+ ground its provider gives without end; moving it moves the window, not the ground). It may be worn by rain and
painted by a splatmap.
- **Infinite**: ground made by a provider (below) read at any point in the world, so it has no edge. The same provider, world, seed
and version are the same ground everywhere, in the editor, in a game and on a server. It is drawn round the eye out to
@@ -29,7 +31,7 @@ The ground is one of two kinds, chosen by `extent`:
| `detail` | A multiplier on how far the finest cells reach before the ground coarsens. Above 1 is finer at a distance and costs more triangles. |
| `drawDistance` | Infinite only. How far from the eye the ground is drawn. |
| `collision`, `collisionDistance` | Whether 3D bodies and characters collide with the ground, and how far round each one that moves the ground is built for it. `collisionLayer` and `friction` (advanced) are the ground's layer and grip. |
-| `provider`, `world`, `generatorVersion` | Infinite only. The generator the ground is made by (`estella:noise`, the engine's noise, or one the game registers), the world it belongs to as the game names it, and the generator version that world was made with. |
+| `provider`, `world`, `generatorVersion` | Infinite, or an area with no heightmap. The generator the ground is made by (`estella:noise`, the engine's noise, or one the game registers), the world it belongs to as the game names it, and the generator version that world was made with. |
| `seed`, `frequency`, `octaves`, `persistence`, `ridged` | The noise: another seed is another ground; `frequency` is how many hills across; `ridged` goes from rolling hills to sharp ridges. |
| `resolution` | Area only. Samples along each side of an area's noise ground. |
| `warp` | 0 to 1: how far the noise is bent by noise of its own, which gives winding valleys and bent ridges instead of round hills. |
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 b0b566532..8c8f37cf0 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
@@ -11,7 +11,7 @@ description: 一个 Terrain 组件,用高度图或噪声生成地面,可以是
地面有两种,由 `extent` 选择:
-- **Area(区域)**:以实体为中心、`sizeX` 乘 `sizeZ` 的一片地面,来自高度图或一次性生成的噪声。可以被雨水侵蚀,也可以用 splatmap 上色。
+- **Area(区域)**:以实体为中心、`sizeX` 乘 `sizeZ` 的一片地面,来自高度图;没有高度图时,是在区域所在的世界位置上读取其生成器地面的一扇窗口(所以尺寸和噪声相同的两块区域并排时无缝相接,区域与其生成器的无限地面是同一片地面;移动区域移动的是窗口,不是地面)。可以被雨水侵蚀,也可以用 splatmap 上色。
- **Infinite(无限)**:由一个生成器(provider,见下)在世界中任意一点读取的地面,所以没有边缘。同一个生成器、世界、种子和版本在任何地方都是同一片地面,编辑器里、游戏里、服务器上都一样。它围绕视点绘制到 `drawDistance` 为止。
| 字段 | 作用 |
@@ -23,7 +23,7 @@ description: 一个 Terrain 组件,用高度图或噪声生成地面,可以是
| `detail` | 最细格子在地面变粗之前能延伸多远的倍率。大于 1 时远处更细,三角形也更多。 |
| `drawDistance` | 仅无限地面。地面从视点向外绘制多远。 |
| `collision`、`collisionDistance` | 3D 刚体和角色是否与地面碰撞,以及在每个运动物体周围多远的范围内为碰撞构建地面。`collisionLayer` 和 `friction`(高级)是地面的碰撞层和摩擦。 |
-| `provider`、`world`、`generatorVersion` | 仅无限。生成地面的生成器(`estella:noise` 为引擎自带噪声,或游戏注册的生成器)、游戏给这个世界起的名字,以及这个世界生成时用的生成器版本。 |
+| `provider`、`world`、`generatorVersion` | 无限地形,或没有高度图的区域。生成地面的生成器(`estella:noise` 为引擎自带噪声,或游戏注册的生成器)、游戏给这个世界起的名字,以及这个世界生成时用的生成器版本。 |
| `seed`、`frequency`、`octaves`、`persistence`、`ridged` | 噪声:换一个种子就是另一片地面;`frequency` 是横跨有几座山丘;`ridged` 从起伏的丘陵到尖锐的山脊。 |
| `resolution` | 仅区域。区域噪声地面每边的采样数。 |
| `warp` | 0 到 1:噪声被它自己的另一层噪声扭曲多远,得到蜿蜒的山谷和弯折的山脊,而不是圆圆的山丘。 |
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 22731733d..330be44ba 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -4059,10 +4059,10 @@ field: Heightfield
height: (x: number, z: number) => number | null
infinite: false
maxHeight: number
-minHeight: 0
+minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
-static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number]): FieldSource
static prototype: FieldSource
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index ea8db522d..7c0c3f70f 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -4067,10 +4067,10 @@ field: Heightfield
height: (x: number, z: number) => number | null
infinite: false
maxHeight: number
-minHeight: 0
+minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
-static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number]): FieldSource
static prototype: FieldSource
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 535208313..910149118 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -4054,10 +4054,10 @@ field: Heightfield
height: (x: number, z: number) => number | null
infinite: false
maxHeight: number
-minHeight: 0
+minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
-static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number]): FieldSource
static prototype: FieldSource
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 5d7bc35a4..b5664ee7c 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -4054,10 +4054,10 @@ field: Heightfield
height: (x: number, z: number) => number | null
infinite: false
maxHeight: number
-minHeight: 0
+minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
-static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number]): FieldSource
static prototype: FieldSource
```
diff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.md
index 2a9e6e5ce..9c852ecd7 100644
--- a/sdk/etc/terrain.api.md
+++ b/sdk/etc/terrain.api.md
@@ -25,10 +25,10 @@ field: Heightfield
height: (x: number, z: number) => number | null
infinite: false
maxHeight: number
-minHeight: 0
+minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
-static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number]): FieldSource
static prototype: FieldSource
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index d19750502..0f2c8654e 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -4054,10 +4054,10 @@ field: Heightfield
height: (x: number, z: number) => number | null
infinite: false
maxHeight: number
-minHeight: 0
+minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
-static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number]): FieldSource
static prototype: FieldSource
```
diff --git a/sdk/src/terrain/source.ts b/sdk/src/terrain/source.ts
index d96c8c03f..23154ddd1 100644
--- a/sdk/src/terrain/source.ts
+++ b/sdk/src/terrain/source.ts
@@ -41,11 +41,14 @@ export interface TerrainSource {
/** The pixels of a splatmap, as the terrain read them. */
export interface Splat { width: number; height: number; pixels: Uint8Array }
-/** An area's ground: a field of heights `height` tall, centred on the terrain, with its splatmap and where its rain ran. */
+/**
+ * An area's ground: a field of heights (0 to 1 over `range`, from 0 to `height` by default), centred on the terrain, with its splatmap
+ * and where its rain ran.
+ */
export class FieldSource implements TerrainSource {
readonly infinite = false;
readonly bounds: readonly [number, number, number, number];
- readonly minHeight = 0;
+ readonly minHeight: number;
readonly maxHeight: number;
constructor(
@@ -53,27 +56,32 @@ export class FieldSource implements TerrainSource {
private readonly data: Pick<TerrainData, 'sizeX' | 'sizeZ' | 'height' | 'rockSlope' | 'dirtHeight' | 'snowHeight'>,
private readonly splat: Splat | null,
private readonly flow: Float32Array | null,
+ range: readonly [number, number] = [0, data.height],
) {
this.bounds = [-data.sizeX / 2, -data.sizeZ / 2, data.sizeX / 2, data.sizeZ / 2];
- this.maxHeight = data.height;
+ [this.minHeight, this.maxHeight] = range;
+ }
+
+ private get span(): number {
+ return Math.max(this.maxHeight - this.minHeight, 1e-6);
}
height(x: number, z: number): number | null {
const u = x / this.data.sizeX + 0.5, v = z / this.data.sizeZ + 0.5;
if (u < 0 || u > 1 || v < 0 || v > 1) return null;
- return sampleHeight(this.field, u, v) * this.data.height;
+ return this.minHeight + sampleHeight(this.field, u, v) * this.span;
}
/** The ground's normal at (x, z), or null off the area. */
normal(x: number, z: number): [number, number, number] | null {
const u = x / this.data.sizeX + 0.5, v = z / this.data.sizeZ + 0.5;
if (u < 0 || u > 1 || v < 0 || v > 1) return null;
- return terrainNormal(this.field, u, v, this.data.sizeX, this.data.sizeZ, this.data.height);
+ return terrainNormal(this.field, u, v, this.data.sizeX, this.data.sizeZ, this.span);
}
paint(x: number, z: number, h: number, ny: number): [number, number, number, number] {
const u = Math.min(Math.max(x / this.data.sizeX + 0.5, 0), 1), v = Math.min(Math.max(z / this.data.sizeZ + 0.5, 0), 1);
- let w = paintWeights(h / Math.max(this.data.height, 1e-6), ny, this.data);
+ let w = paintWeights((h - this.minHeight) / this.span, ny, this.data);
const splat = this.splat;
if (splat) {
const sx = Math.round(u * (splat.width - 1)), sy = Math.round(v * (splat.height - 1));
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
index f0d79b763..b53c1cdd3 100644
--- a/sdk/src/terrain/terrainPlugin.ts
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -36,11 +36,11 @@ import { EditorView, editorViewEye } from '../camera/EditorView';
import { log } from '../util/logger';
import { bakesOf } from '../runtime/bakes';
import type { Color, Entity } from '../types';
-import { erosionJob, heightfieldFromPixels, proceduralHeightfield } from './heightfield';
+import { erosionJob, heightfieldFromPixels, type Heightfield } from './heightfield';
import { FieldSource, 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 } from './provider';
+import { noiseProvider, ProviderSource, terrainProvider, terrainProvidersRevision, TerrainUnavailable, type TerrainProvider } from './provider';
import { buildPatchMesh } from './patch';
import { TerrainSurface, TILE_CELLS, type SurfaceTile } from './surface';
import { collisionGeometryOf } from '../runtime/collisionGeometry';
@@ -58,8 +58,9 @@ export interface TerrainData {
/** {@link TerrainExtent}: an area `sizeX` by `sizeZ`, or ground that goes on for ever (from a provider, read anywhere). */
extent: number;
/**
- * Ground without end: the provider it is made by (`estella:noise`, the engine's noise, or one a game registers with
- * registerTerrainProvider), the world it belongs to as the game names it, and the generator version that world was made with.
+ * Ground read from a provider (without end, or an area with no heightmap, a window on it where the area stands): the provider
+ * (`estella:noise`, the engine's noise, or one a game registers with registerTerrainProvider), the world it belongs to as the game
+ * names it, and the generator version that world was made with.
*/
provider: string;
world: string;
@@ -126,9 +127,9 @@ export const Terrain: ComponentDef<TerrainData> = defineComponent<TerrainData>('
assetFields: [{ field: 'heightmap', type: 'texture' }, { field: 'splatmap', type: 'texture' }, { field: 'material', type: 'material' }],
fields: {
extent: { enum: [{ label: 'Area', value: TerrainExtent.Area }, { label: 'Infinite', value: TerrainExtent.Infinite }], category: 'Shape', tooltip: 'An area of its own size, from a heightmap or noise; or ground that goes on for ever, from noise read anywhere (the same seed is the same ground).' },
- provider: { category: 'Shape', tooltip: 'The generator ground without end is made by: estella:noise, or one the game registers. The same provider, world, seed and version are the same ground on every machine.', shownWhen: { field: 'extent', values: [TerrainExtent.Infinite] } },
- world: { category: 'Shape', tooltip: 'The world (a planet, a level) the ground belongs to, as the game names it; handed to the provider.', shownWhen: { field: 'extent', values: [TerrainExtent.Infinite] } },
- generatorVersion: { min: 1, step: 1, category: 'Shape', tooltip: 'The generator version the world was made with. A version the provider no longer has fails the terrain rather than growing other ground under what was built.', shownWhen: { field: 'extent', values: [TerrainExtent.Infinite] } },
+ provider: { category: 'Shape', tooltip: 'The generator the ground is made by, without end or (with no heightmap) in an area: estella:noise, or one the game registers. The same provider, world, seed and version are the same ground on every machine, and two areas side by side join.' },
+ world: { category: 'Shape', tooltip: 'The world (a planet, a level) the ground belongs to, as the game names it; handed to the provider.' },
+ generatorVersion: { min: 1, step: 1, category: 'Shape', tooltip: 'The generator version the world was made with. A version the provider no longer has fails the terrain rather than growing other ground under what was built.' },
heightmap: { tooltip: 'A heightmap image: red is the height. Empty makes the ground from noise; a heightmap that cannot be read fails the terrain instead.', category: 'Shape', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },
splatmap: { tooltip: 'An image whose red, green, blue and alpha are the weights of grass, dirt, snow and rock.', category: 'Layers', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },
material: { tooltip: 'A material on the Terrain shader. Empty draws the layer colours onto the ground.', category: 'Layers' },
@@ -332,11 +333,43 @@ export class Terrains {
export const TerrainsRes = defineResource<Terrains>(new Terrains(), 'Terrains');
/** What, changed, rebuilds the ground: everything but the colours, the detail and the collision, which are read each frame. */
-function signatureOf(data: TerrainData): string {
+function signatureOf(data: TerrainData, at: { x: number; z: number }): string {
const { layerColor0: _a, layerColor1: _b, layerColor2: _c, layerColor3: _d, detail: _e, drawDistance: _f,
collision: _g, collisionDistance: _h, collisionLayer: _i, friction: _j, ...shape } = data;
- // A game's own provider is read again when one is registered under its name.
- return `${JSON.stringify(shape)}${data.extent === TerrainExtent.Infinite && data.provider !== NOISE_PROVIDER ? `#${terrainProvidersRevision()}` : ''}`;
+ // Ground read from a provider is the world's where the terrain stands: moved, it is read again; and a game's own provider is read
+ // again when one is registered under its name.
+ const fromProvider = data.extent === TerrainExtent.Infinite || !data.heightmap;
+ const where = fromProvider ? `@${at.x},${at.z}` : '';
+ const late = fromProvider && data.provider !== NOISE_PROVIDER ? `#${terrainProvidersRevision()}` : '';
+ return `${JSON.stringify(shape)}${where}${late}`;
+}
+
+/** The provider a terrain names, or why it cannot have it. */
+function providerOf(data: TerrainData): TerrainProvider {
+ const provider = data.provider === NOISE_PROVIDER ? noiseProvider(() => data) : terrainProvider(data.provider);
+ if (!provider) throw new TerrainUnavailable(`no terrain provider ${data.provider} is registered`);
+ return provider;
+}
+
+/** The ground's paint by height (over the provider's range) and slope, for a provider that does not paint. */
+function paintBy(provider: TerrainProvider, data: TerrainData): (h: number, ny: number) => [number, number, number, number] {
+ const [lo, hi] = provider.range(data.seed, data.generatorVersion);
+ return (h, ny) => paintWeights((h - lo) / Math.max(hi - lo, 1e-6), ny, data);
+}
+
+/** An area's window on its provider's ground: `resolution` samples along its longer side, over the provider's range. */
+async function windowOf(provider: TerrainProvider, data: TerrainData, cx: number, cz: number, range: [number, number]): Promise<Heightfield> {
+ const res = Math.min(2049, Math.max(17, Math.floor(data.resolution)));
+ const spacing = Math.max(data.sizeX, data.sizeZ) / (res - 1);
+ const nx = Math.max(2, Math.round(data.sizeX / spacing) + 1), nz = Math.max(2, Math.round(data.sizeZ / spacing) + 1);
+ const count = Math.max(nx, nz);
+ const got = await provider.sample({
+ world: data.world, seed: data.seed, version: data.generatorVersion, x0: cx - data.sizeX / 2, z0: cz - data.sizeZ / 2, spacing, count,
+ });
+ const span = Math.max(range[1] - range[0], 1e-6);
+ const out = new Float32Array(nx * nz);
+ for (let j = 0; j < nz; j++) for (let i = 0; i < nx; i++) out[j * nx + i] = (got.heights[j * count + i]! - range[0]) / span;
+ return { width: nx, height: nz, data: out };
}
/** Where what collides with the ground is: every moving 3D body and every character. */
@@ -374,7 +407,7 @@ export class TerrainPlugin implements Plugin {
this.sweep(app, terrains);
for (const entity of app.world.getEntitiesWithComponents([Terrain, Transform])) {
const data = app.world.get(entity, Terrain) as TerrainData;
- const signature = signatureOf(data);
+ const signature = signatureOf(data, (app.world.get(entity, Transform) as TransformData).worldPosition);
let built = terrains.built_.get(entity);
if (!built || built.signature !== signature) {
if (built) this.destroy(app, built);
@@ -416,29 +449,35 @@ export class TerrainPlugin implements Plugin {
const epoch = built.epoch;
const data = built.data;
try {
+ const t = app.world.get(entity, Transform) as TransformData;
if (data.extent === TerrainExtent.Infinite) {
- const t = app.world.get(entity, Transform) as TransformData;
- const provider = data.provider === NOISE_PROVIDER ? noiseProvider(() => data) : terrainProvider(data.provider);
- if (!provider) throw new TerrainUnavailable(`no terrain provider ${data.provider} is registered`);
+ const provider = providerOf(data);
built.source = new ProviderSource(provider, data.world, data.seed, data.generatorVersion, t.worldPosition.x, t.worldPosition.z,
- Math.max(data.cellSize, 1e-3), (h, ny) => paintWeights(h / Math.max(provider.range(data.seed, data.generatorVersion)[1], 1e-6), ny, data));
+ Math.max(data.cellSize, 1e-3), paintBy(provider, data));
} else {
// A heightmap named and not read is a failure: a world built on that ground must not quietly get other ground.
const height = await this.pixelsOf(app, data.heightmap);
if (data.heightmap && !height) throw new TerrainUnavailable(`the heightmap (texture ${data.heightmap}) could not be read`);
const splat = await this.pixelsOf(app, data.splatmap);
if (built.epoch !== epoch || !app.world.valid(entity)) return;
- const made = height
- ? heightfieldFromPixels(height.width, height.height, height.pixels)
- : proceduralHeightfield({
- resolution: Math.min(2049, Math.max(17, Math.floor(data.resolution))), seed: data.seed, frequency: data.frequency,
- octaves: data.octaves, persistence: data.persistence, ridged: data.ridged, warp: data.warp,
- });
+ // Without a heightmap an area is a window on its provider's ground, read where it stands in the world: two areas side by
+ // side are one ground, and the area is the same ground the provider gives without end.
+ let range: [number, number] = [0, data.height];
+ let made: Heightfield;
+ if (height) {
+ made = heightfieldFromPixels(height.width, height.height, height.pixels);
+ } else {
+ const provider = providerOf({ ...data, erosion: 0 });
+ const checked = new ProviderSource(provider, data.world, data.seed, data.generatorVersion, 0, 0, 1, paintBy(provider, data));
+ range = [checked.minHeight, checked.maxHeight];
+ made = await windowOf(provider, data, t.worldPosition.x, t.worldPosition.z, range);
+ if (built.epoch !== epoch || !app.world.valid(entity)) return;
+ }
let field = made, flow: Float32Array | null = null;
if (data.erosion > 0) {
// Rain over a big field is seconds of work: it is spread over frames, and shown while it runs.
const job = bakesOf(app).run('Eroding the terrain',
- erosionJob(made, { amount: data.erosion, seed: data.seed, sizeX: data.sizeX, sizeZ: data.sizeZ, height: data.height }));
+ erosionJob(made, { amount: data.erosion, seed: data.seed, sizeX: data.sizeX, sizeZ: data.sizeZ, height: range[1] - range[0] }));
built.cancel = job.cancel;
const worn = await job.done;
built.cancel = null;
@@ -446,7 +485,7 @@ export class TerrainPlugin implements Plugin {
field = worn.field;
flow = worn.flow;
}
- built.source = new FieldSource(field, data, splat, flow);
+ built.source = new FieldSource(field, data, splat, flow, range);
}
built.surface = new TerrainSurface(built.source, Math.max(data.cellSize, 1e-3));
app.getResource(TerrainsRes).revision_++;
diff --git a/sdk/tests/terrain-provider.test.ts b/sdk/tests/terrain-provider.test.ts
index 07eb263eb..09df8cfc3 100644
--- a/sdk/tests/terrain-provider.test.ts
+++ b/sdk/tests/terrain-provider.test.ts
@@ -131,6 +131,52 @@ describe('a Terrain with no renderer (a server)', () => {
expect(terrains.heightAt(0, 0)).toBeNull();
});
+ it('reads an area with no heightmap from its provider where it stands, so areas side by side are one ground', async () => {
+ const app = boot();
+ const area = (x: number) => {
+ const e = app.world.spawn();
+ app.world.insert(e, Transform, { position: { x, y: 0, z: 0 }, worldPosition: { x, y: 0, z: 0 } });
+ app.world.insert(e, Terrain, { ...Terrain._default, ...params, erosion: 0, sizeX: 1000, sizeZ: 1000, resolution: 257, cellSize: 2 });
+ return e;
+ };
+ const west = area(-500), east = area(500);
+ const endless = app.world.spawn();
+ app.world.insert(endless, Transform, { position: { x: 0, y: 0, z: 9000 }, worldPosition: { x: 0, y: 0, z: 9000 } });
+ await settle(app);
+ const terrains = app.getResource(TerrainsRes);
+ expect(terrains.status(west)!.state).toBe('ready');
+ expect(terrains.status(east)!.state).toBe('ready');
+ // Either side of the seam, and the same ground the provider gives there without end (its hills spread over the areas' size).
+ const noise = ground(noiseProvider(() => ({ ...params, erosion: 0, sizeX: 1000 })));
+ for (const z of [-300, 0, 220]) {
+ const a = terrains.heightAt(-0.001, z)!, b = terrains.heightAt(0.001, z)!;
+ expect(Math.abs(a - b)).toBeLessThan(0.5);
+ expect(a).toBeCloseTo(noise.height(0, z)!, -1);
+ }
+ });
+
+ it('stands on the same world ground when it is moved', 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(1234, -566)!;
+ app.world.insert(e, Transform, { position: { x: 700, y: 0, z: -300 }, worldPosition: { x: 700, y: 0, z: -300 } });
+ await settle(app);
+ expect(terrains.heightAt(1234, -566)).toBeCloseTo(before, 6);
+ });
+
+ it('fails an area with no heightmap whose provider has not the version asked for', async () => {
+ const app = boot();
+ const e = app.world.spawn();
+ app.world.insert(e, Transform, {});
+ app.world.insert(e, Terrain, { ...Terrain._default, generatorVersion: 4 });
+ await settle(app);
+ expect(app.getResource(TerrainsRes).status(e)!.reason).toMatch(/version 4/);
+ });
+
it('fails when its heightmap cannot be read, instead of growing noise in its place', async () => {
const app = boot();
const e = app.world.spawn();
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 809603fa2..1a8ce8ceb 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2782,4 +2782,6 @@ export const NOTED = {
{"note":"Which water a place is."},
"fix(render): a shadow is cast by what the camera's level of detail draws, and the terrain slides its vertices by the eye in every pass":
{"note":"Shadows follow what the camera draws."},
+ "feat(terrain): an area without a heightmap is a window on its provider's ground, and ground read from a provider stays the world's when its terrain moves":
+ {"note":"An area without a heightmap is a window on its provider's ground."},
};