A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(terrain): rain erodes the ground and its noise is warped, baked over frames with their progress
yhh5197689ab365
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 01498f46c..e66ffc03c 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -800,6 +800,7 @@ export {Foliage, FoliageField, FoliageRes, FoliagePlugin, foliagePlugin, type FoliageData,} from './foliage/foliagePlugin';// Splines and water are optional modules too (`esengine/spline`, `esengine/water`).+export { Bakes, BakesRes, bakesOf, finish, type WorkJob, type BakeProgress } from './runtime/bakes';export { Spline, SplinePlugin, splinePlugin, type SplineData } from './spline/splinePlugin';export { SplineCurve, type SplinePoint, type SplineNearest } from './spline/curve';export {@@ -814,8 +815,8 @@ export {type Plant, type Ground, type ScatterParams, type BladeParams, type CardRect,} from './foliage/builder';export {- heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,- type Heightfield, type ProceduralParams,+ erodeHeightfield, erosionJob, heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,+ type Eroded, type ErosionParams, type Heightfield, type ProceduralParams,} from './terrain/heightfield';export {buildChunkMesh, cellsAtLod, chunkCenter, lodCount, type TerrainShape, type TerrainPaint,diff --git a/sdk/src/runtime/bakes.ts b/sdk/src/runtime/bakes.tsnew file mode 100644index 000000000..256df3bfd--- /dev/null+++ b/sdk/src/runtime/bakes.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file bakes.ts+ * @brief Work the engine spreads over frames (a terrain worn by rain, a water zone baked, chunks built), and how far along it is.+ *+ * @details A bake that runs in one go holds the frame until it is done: the editor freezes, a game's first frame waits, and nobody+ * can say what for. So such work is a job: a generator that yields how far along it is, stepped each frame for as long as+ * the frame can spare. Every job running is listed with its label and progress, which the editor shows in its status bar+ * and a game can put on a loading screen.+ */+import type { App } from '../app/app';+import { defineResource } from '../ecs/resource';+import { defineSystem, Schedule } from '../ecs/system';++/** One piece of work in hand: what it is and how far along, 0 to 1. */+export interface BakeProgress {+ readonly label: string;+ readonly progress: number;+}++/** A job: yields its progress (0 to 1) whenever it may be paused, and returns what it made. */+export type WorkJob<T> = Generator<number, T, void>;++interface Running {+ label: string;+ progress: number;+ job: WorkJob<unknown>;+ done: (value: unknown) => void;+ fail: (error: unknown) => void;+}++/** The jobs an App is running. Read {@link Bakes.active} for what to show. */+export class Bakes {+ /** How long, in milliseconds, the jobs may take of a frame between them. */+ budgetMs = 8;+ private readonly running_ = new Set<Running>();+ private readonly marks_ = new Map<object, { label: string; progress: number }>();++ /**+ * Runs `job` over the frames to come, under `label`; the promise is what it returns. A job that is cancelled (see `cancel`)+ * never settles.+ */+ run<T>(label: string, job: WorkJob<T>): { done: Promise<T>; cancel: () => void } {+ let entry!: Running;+ const done = new Promise<T>((resolve, reject) => {+ entry = { label, progress: 0, job, done: resolve as (v: unknown) => void, fail: reject };+ });+ this.running_.add(entry);+ return { done, cancel: () => { this.running_.delete(entry); } };+ }++ /**+ * Shows work that is stepped elsewhere (chunks built a few a frame) under `label` while `progress` is below 1; `owner` names it,+ * so a later mark replaces it. Mark it 1, or `clear` it, when it is done.+ */+ mark(owner: object, label: string, progress: number): void {+ if (progress >= 1) this.marks_.delete(owner);+ else this.marks_.set(owner, { label, progress: Math.max(0, progress) });+ }++ clear(owner: object): void {+ this.marks_.delete(owner);+ }++ /** Every piece of work in hand now. Empty when the engine is idle. */+ get active(): BakeProgress[] {+ const out: BakeProgress[] = [];+ for (const r of this.running_) out.push({ label: r.label, progress: r.progress });+ for (const m of this.marks_.values()) out.push({ label: m.label, progress: m.progress });+ return out;+ }++ /** Steps the jobs for the frame's budget, oldest first; a job that finishes or throws settles its promise. */+ step(now: () => number = () => performance.now()): void {+ if (this.running_.size === 0) return;+ const end = now() + this.budgetMs;+ for (const r of [...this.running_]) {+ // Every job advances at least once a frame, so a long one cannot starve those behind it.+ do {+ let next: IteratorResult<number, unknown>;+ try {+ next = r.job.next();+ } catch (e) {+ this.running_.delete(r);+ r.fail(e);+ break;+ }+ if (next.done) {+ this.running_.delete(r);+ r.done(next.value);+ break;+ }+ r.progress = Math.min(Math.max(next.value, 0), 1);+ } while (now() < end);+ if (now() >= end) break;+ }+ }+}++/** The resource; {@link bakesOf} installs it where it is missing. @experimental */+export const BakesRes = defineResource<Bakes>(new Bakes(), 'Bakes');++/** The App's jobs, installed (with the system that steps them, before Update) on first use, so a plugin that bakes needs nothing else. */+export function bakesOf(app: App): Bakes {+ if (!app.hasResource(BakesRes)) {+ const bakes = new Bakes();+ app.insertResource(BakesRes, bakes);+ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([], () => bakes.step(), { name: 'BakeSystem' }));+ }+ return app.getResource(BakesRes);+}++/** Runs a job to its end at once, for a caller with no frames to spread it over (a test, a tool). */+export function finish<T>(job: WorkJob<T>): T {+ for (;;) {+ const next = job.next();+ if (next.done) return next.value;+ }+}diff --git a/sdk/src/terrain/heightfield.ts b/sdk/src/terrain/heightfield.tsindex 0aa8972be..8e314e351 100644--- a/sdk/src/terrain/heightfield.ts+++ b/sdk/src/terrain/heightfield.ts@@ -63,18 +63,30 @@ export interface ProceduralParams {persistence: number;/** 0 is rolling hills; 1 is sharp ridges, the way eroded mountains look. */ridged: number;+ /** How far the noise is pushed about by noise of its own before it is read, 0 to 1: bent ridges and winding valleys instead of round hills. */+ warp?: number;}/** Fractal noise as a heightfield, scaled to span 0 to 1 so the terrain's height is its true range. */export function proceduralHeightfield(p: ProceduralParams): Heightfield {const n = Math.max(2, Math.floor(p.resolution));const data = new Float32Array(n * n);+ const warp = Math.min(Math.max(p.warp ?? 0, 0), 1);let min = Infinity, max = -Infinity;for (let j = 0; j < n; j++) {for (let i = 0; i < n; i++) {+ let x = i / (n - 1), y = j / (n - 1);+ if (warp > 0) {+ // Two octaves of noise at the biggest hills' scale move the point up to half a hill before it is read.+ const f = p.frequency;+ const wx = valueNoise(x * f + 5.2, y * f + 1.3, p.seed + 7001) + 0.5 * valueNoise(x * f * 2 + 2.8, y * f * 2 + 9.1, p.seed + 7002);+ const wy = valueNoise(x * f + 8.3, y * f + 2.8, p.seed + 7003) + 0.5 * valueNoise(x * f * 2 + 4.4, y * f * 2 + 6.6, p.seed + 7004);+ x += ((wx / 1.5) * 2 - 1) * warp * 0.5 / f;+ y += ((wy / 1.5) * 2 - 1) * warp * 0.5 / f;+ }let amplitude = 1, frequency = p.frequency, sum = 0, norm = 0;for (let o = 0; o < Math.max(1, Math.min(8, Math.floor(p.octaves))); o++) {- let v = valueNoise(i / (n - 1) * frequency, j / (n - 1) * frequency, p.seed + o * 101);+ let v = valueNoise(x * frequency, y * frequency, p.seed + o * 101);v = v * (1 - p.ridged) + (1 - Math.abs(v * 2 - 1)) * p.ridged;sum += v * amplitude;norm += amplitude;@@ -114,3 +126,128 @@ export function terrainNormal(const len = Math.hypot(dx, 1, dz);return [-dx / len, 1 / len, -dz / len];}++/** What {@link erodeHeightfield} wears the ground with. */+export interface ErosionParams {+ /** How much rain falls, 0 to 1: at 1, a drop for every sample of the field. */+ amount: number;+ seed: number;+ /** The field's world size along x and z, and its world height: erosion works in the ground's own proportions. */+ sizeX: number;+ sizeZ: number;+ height: number;+}++/** The ground after the rain, and where the water ran: `flow` is 0 to 1 per sample, the share of the busiest channel's water that passed. */+export interface Eroded { field: Heightfield; flow: Float32Array }++/**+ * Hydraulic erosion: drops of rain fall at random over the field, each runs downhill carrying what it can for its speed and the water in it,+ * cuts the ground where it carries less than it could, lays it down where it carries more or slows (in a hollow, on a flat, as it dries),+ * and evaporates as it goes. What is left has gullies down the slopes, sharper ridges between them and silt in the valleys, and where the water+ * ran is kept as `flow`. The same seed wears the same ground everywhere.+ */+export function erodeHeightfield(field: Heightfield, p: ErosionParams): Eroded {+ const job = erosionJob(field, p);+ for (;;) {+ const next = job.next();+ if (next.done) return next.value;+ }+}++/** {@link erodeHeightfield} as a job that yields its progress (0 to 1) every few thousand drops, for spreading over frames. */+export function* erosionJob(field: Heightfield, p: ErosionParams): Generator<number, Eroded, void> {+ const w = field.width, h = field.height;+ const drops = Math.min(600_000, Math.floor(Math.min(Math.max(p.amount, 0), 4) * w * h));+ if (drops === 0 || w < 3 || h < 3) return { field, flow: new Float32Array(field.data.length) };+ const cell = Math.max(p.sizeX / Math.max(w - 1, 1), p.sizeZ / Math.max(h - 1, 1), 1e-6);+ // Heights in cells, so slopes and capacities mean the same on any terrain.+ const scale = p.height / cell;+ const H = new Float32Array(field.data.length);+ for (let k = 0; k < H.length; k++) H[k] = field.data[k]! * scale;+ const flow = new Float32Array(field.data.length);+ const random = mulberry32(p.seed * 7919 + 17);+ const INERTIA = 0.05, CAPACITY = 4, MIN_SLOPE = 0.01, DEPOSIT = 0.3, ERODE = 0.3, EVAPORATE = 0.02, GRAVITY = 4, LIFE = 40;+ // A drop wears the ground over the cells about it, the nearer the more.+ const RADIUS = 2;+ const brush: [number, number, number][] = [];+ let total = 0;+ for (let dy = -RADIUS; dy <= RADIUS; dy++) for (let dx = -RADIUS; dx <= RADIUS; dx++) {+ const d = Math.hypot(dx, dy);+ if (d > RADIUS) continue;+ brush.push([dx, dy, 1 - d / RADIUS]);+ total += 1 - d / RADIUS;+ }+ for (const b of brush) b[2] /= total;+ const gradient = (x: number, y: number): [number, number, number] => {+ const ix = Math.min(Math.floor(x), w - 2), iy = Math.min(Math.floor(y), h - 2);+ const fx = x - ix, fy = y - iy;+ const k = iy * w + ix;+ const a = H[k]!, b = H[k + 1]!, c = H[k + w]!, d = H[k + w + 1]!;+ return [(b - a) * (1 - fy) + (d - c) * fy, (c - a) * (1 - fx) + (d - b) * fx, a * (1 - fx) * (1 - fy) + b * fx * (1 - fy) + c * (1 - fx) * fy + d * fx * fy];+ };+ for (let n = 0; n < drops; n++) {+ if (n % 2000 === 0) yield n / drops;+ let x = random() * (w - 1), y = random() * (h - 1);+ let dx = 0, dy = 0, speed = 1, water = 1, sediment = 0;+ for (let life = 0; life < LIFE; life++) {+ const ix = Math.floor(x), iy = Math.floor(y);+ const fx = x - ix, fy = y - iy;+ const [gx, gy, here] = gradient(x, y);+ dx = dx * INERTIA - gx * (1 - INERTIA);+ dy = dy * INERTIA - gy * (1 - INERTIA);+ const len = Math.hypot(dx, dy);+ if (len < 1e-9) break;+ dx /= len; dy /= len;+ const nx = x + dx, ny = y + dy;+ if (nx < 0 || nx > w - 1.001 || ny < 0 || ny > h - 1.001) break;+ const fall = gradient(nx, ny)[2] - here;+ const capacity = Math.max(-fall * speed * water * CAPACITY, MIN_SLOPE);+ const k = iy * w + ix;+ flow[k] = flow[k]! + water;+ if (sediment > capacity || fall > 0) {+ // Uphill, fill the hollow it is leaving (no more than it is deep); else lay down what it cannot carry.+ const put = fall > 0 ? Math.min(fall, sediment) : (sediment - capacity) * DEPOSIT;+ sediment -= put;+ H[k] = H[k]! + put * (1 - fx) * (1 - fy);+ H[k + 1] = H[k + 1]! + put * fx * (1 - fy);+ H[k + w] = H[k + w]! + put * (1 - fx) * fy;+ H[k + w + 1] = H[k + w + 1]! + put * fx * fy;+ } else {+ const take = Math.min((capacity - sediment) * ERODE, -fall);+ for (const [bx, by, weight] of brush) {+ const cx = ix + bx, cy = iy + by;+ if (cx < 0 || cy < 0 || cx >= w || cy >= h) continue;+ const c = cy * w + cx;+ const cut = Math.min(H[c]!, take * weight);+ H[c] = H[c]! - cut;+ sediment += cut;+ }+ }+ speed = Math.sqrt(Math.max(speed * speed - fall * GRAVITY, 0));+ water *= 1 - EVAPORATE;+ x = nx; y = ny;+ }+ }+ const data = new Float32Array(H.length);+ let busiest = 0;+ for (let k = 0; k < H.length; k++) {+ data[k] = Math.min(Math.max(H[k]! / scale, 0), 1);+ busiest = Math.max(busiest, flow[k]!);+ }+ // Channels are told apart over orders of magnitude: the share is taken on a log scale.+ const top = Math.log1p(busiest);+ for (let k = 0; k < flow.length; k++) flow[k] = top > 0 ? Math.log1p(flow[k]!) / top : 0;+ return { field: { width: w, height: h, data }, flow };+}++/** A small seeded random number generator: the same seed gives the same sequence on every host. */+function mulberry32(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}diff --git a/sdk/src/terrain/index.ts b/sdk/src/terrain/index.tsindex 54c36b359..044914d83 100644--- a/sdk/src/terrain/index.ts+++ b/sdk/src/terrain/index.ts@@ -4,8 +4,8 @@ export {Terrain, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, paintWeights, type TerrainData,} from './terrainPlugin';export {- heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,- type Heightfield, type ProceduralParams,+ erodeHeightfield, erosionJob, heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,+ type Eroded, type ErosionParams, type Heightfield, type ProceduralParams,} from './heightfield';export {buildChunkMesh, cellsAtLod, chunkCenter, lodCount, type TerrainShape, type TerrainPaint,diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex 9f7fcf567..d7b189b64 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -25,9 +25,10 @@ import { platformLoadImagePixels } from '../platform/base';import { decodeImagePixels } from '../asset/imageDecode';import { decodePngData } from '../asset/pngData';import { log } from '../util/logger';+import { bakesOf } from '../runtime/bakes';import type { Color, Entity } from '../types';import {- heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal, type Heightfield,+ erosionJob, heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal, type Heightfield,} from './heightfield';import { buildChunkMesh, chunkCenter, lodCount, type TerrainPaint, type TerrainShape } from './mesh';@@ -59,6 +60,10 @@ export interface TerrainData {persistence: number;ridged: number;resolution: number;+ /** How far the noise is bent by noise of its own, 0 to 1: winding valleys and bent ridges instead of round hills. */+ warp: number;+ /** How much rain wears the ground, 0 to 4 (a heightmap's too): gullies down the slopes, silt in the valleys, and dirt where the water ran. */+ erosion: number;/** Painting: how steep ground must be to turn to rock (0 flat, 1 sheer), and the heights, 0 to 1, where dirt and snow start. */rockSlope: number;dirtHeight: number;@@ -81,7 +86,7 @@ export const Terrain: ComponentDef<TerrainData> = defineComponent<TerrainData>('heightmap: 0, splatmap: 0, material: 0,sizeX: 1000, sizeZ: 1000, height: 150,chunks: 8, chunkCells: 32, lodLevels: 4, detail: 1,- seed: 1, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.35, resolution: 257,+ seed: 1, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.35, resolution: 257, warp: 0, erosion: 0,rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88,layerColor0: rgb(0.28, 0.46, 0.2), layerColor1: rgb(0.45, 0.36, 0.24), layerColor2: rgb(0.93, 0.95, 0.98), layerColor3: rgb(0.4, 0.38, 0.36),}, {@@ -103,6 +108,8 @@ export const Terrain: ComponentDef<TerrainData> = defineComponent<TerrainData>('persistence: { min: 0, max: 1, step: 0.01, category: 'Noise', tooltip: 'How much of its height each finer layer keeps. Lower is smoother.' },ridged: { min: 0, max: 1, step: 0.01, category: 'Noise', tooltip: '0 is rolling hills; 1 is sharp ridges.' },resolution: { min: 17, max: 2049, step: 1, category: 'Noise', tooltip: 'Samples along each side of the noise ground.' },+ warp: { min: 0, max: 1, step: 0.01, category: 'Noise', tooltip: 'How far the noise is bent by noise of its own: winding valleys and bent ridges instead of round hills.' },+ erosion: { min: 0, max: 4, step: 0.05, category: 'Shape', tooltip: 'How much rain wears the ground (a heightmap\'s too): gullies down the slopes, silt in the valleys, and dirt painted where the water ran. 0 leaves it as made.' },rockSlope: { min: 0, max: 1, step: 0.01, category: 'Layers', tooltip: 'How steep ground must be to turn to rock. 0 is flat, 1 is sheer.' },dirtHeight: { min: 0, max: 1, step: 0.01, category: 'Layers', tooltip: 'The height, as a share of the terrain, where grass gives way to dirt.' },snowHeight: { min: 0, max: 1, step: 0.01, category: 'Layers', tooltip: 'The height, as a share of the terrain, where snow begins.' },@@ -137,14 +144,19 @@ interface Built {chunks: Entity[];queue: [number, number][];splat: { width: number; height: number; pixels: Uint8Array } | null;+ /** Where the rain ran when the ground was worn (erodeHeightfield), 0 to 1 per sample of the field; null when it was not. */+ flow: Float32Array | null;materialHandle: number;/** Bumped on every rebuild so an answer that arrives for an older one is thrown away. */epoch: number;loading: boolean;+ /** The chunks to build in all, for the progress shown while they are; and the erosion in hand, to stop if the terrain is rebuilt. */+ total: number;+ cancel: (() => void) | null;}-/** Chunks built per frame: enough that a terrain appears quickly, few enough that no frame is a stall. */-const CHUNKS_PER_FRAME = 4;+/** How long a frame may spend building chunks, in milliseconds: a terrain appears quickly, and no frame is a stall. At least one is built a frame. */+const CHUNK_BUDGET_MS = 6;/** Run-time access to the ground: how high it is anywhere, for putting things on it. */export class Terrains {@@ -237,18 +249,21 @@ export class TerrainPlugin implements Plugin {if (!built || built.signature !== signature) {if (built) this.destroy(app, built);built = {- signature, field: null, data: { ...data }, handles: [], chunks: [], queue: [], splat: null,- materialHandle: data.material, epoch: (built?.epoch ?? 0) + 1, loading: true,+ signature, field: null, data: { ...data }, handles: [], chunks: [], queue: [], splat: null, flow: null,+ materialHandle: data.material, epoch: (built?.epoch ?? 0) + 1, loading: true, total: 0, cancel: null,};terrains.built_.set(entity, built);void this.load(app, entity, built);continue;}if (built.loading) continue;- for (let i = 0; i < CHUNKS_PER_FRAME && built.queue.length > 0; i++) {+ const until = performance.now() + CHUNK_BUDGET_MS;+ while (built.queue.length > 0) {const [cx, cz] = built.queue.shift()!;this.buildChunk(app, entity, built, cx, cz);+ if (performance.now() >= until) break;}+ bakesOf(app).mark(built, 'Building the terrain', built.total ? 1 - built.queue.length / built.total : 1);}}, { name: 'TerrainSystem' }));}@@ -287,16 +302,30 @@ export class TerrainPlugin implements Plugin {const height = await pixelsOf(data.heightmap);const splat = await pixelsOf(data.splatmap);if (built.epoch !== epoch || !app.world.valid(entity)) return;- built.field = height+ 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,+ octaves: data.octaves, persistence: data.persistence, ridged: data.ridged, warp: data.warp,});+ 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 }));+ built.cancel = job.cancel;+ const worn = await job.done;+ built.cancel = null;+ if (built.epoch !== epoch || !app.world.valid(entity)) return;+ built.field = worn.field;+ built.flow = worn.flow;+ } else {+ built.field = made;+ }built.splat = splat;app.getResource(TerrainsRes).revision_++;const shape = shapeOf(data);for (let cz = 0; cz < shape.chunks; cz++) for (let cx = 0; cx < shape.chunks; cx++) built.queue.push([cx, cz]);+ built.total = built.queue.length;} catch (e) {log.error('terrain', 'building the terrain failed', e);} finally {@@ -308,6 +337,7 @@ export class TerrainPlugin implements Plugin {const data = built.data;const colors = [data.layerColor0, data.layerColor1, data.layerColor2, data.layerColor3];const splat = built.splat;+ const flow = built.flow, field = built.field;const textured = built.materialHandle !== 0;return (u, v, h, ny) => {let w = paintWeights(h, ny, data);@@ -319,6 +349,13 @@ export class TerrainPlugin implements Plugin {const sum = s[0] + s[1] + s[2] + s[3];if (sum > 0.001) w = [s[0] / sum, s[1] / sum, s[2] / sum, s[3] / sum];}+ if (flow && field) {+ // Where the rain ran it took the grass and left dirt; snow and rock stay as they are.+ const x = Math.min(field.width - 1, Math.max(0, Math.round(u * (field.width - 1))));+ const y = Math.min(field.height - 1, Math.max(0, Math.round(v * (field.height - 1))));+ const channel = smooth(0.45, 0.85, flow[y * field.width + x]!) * 0.8 * w[0];+ w = [w[0] - channel, w[1] + channel, w[2], w[3]];+ }// A material reads the weights; with none the colours are mixed here and the ground is drawn in them.if (textured) return w;return [@@ -370,6 +407,9 @@ export class TerrainPlugin implements Plugin {private destroy(app: App, built: Built): void {built.epoch++;built.queue.length = 0;+ built.cancel?.();+ built.cancel = null;+ bakesOf(app).clear(built);const assets = app.hasResource(Assets) ? app.getResource(Assets) : null;for (const chunk of built.chunks) if (app.world.valid(chunk)) app.world.despawn(chunk);for (const handle of built.handles) assets?.releaseBuiltMesh(handle);diff --git a/sdk/tests/bakes.test.ts b/sdk/tests/bakes.test.tsnew file mode 100644index 000000000..679b31e63--- /dev/null+++ b/sdk/tests/bakes.test.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { Bakes, finish, type WorkJob } from '../src/runtime/bakes';++function* counting(steps: number): WorkJob<string> {+ for (let i = 0; i < steps; i++) yield i / steps;+ return 'done';+}++/** A clock that moves a millisecond each time it is read. */+const ticking = (): (() => number) => { let t = 0; return () => t++; };++describe('jobs spread over frames', () => {+ it('step for the budget of a frame, show their progress, and settle with what they made', async () => {+ const bakes = new Bakes();+ bakes.budgetMs = 3;+ const job = bakes.run('Counting', counting(10));+ bakes.step(ticking());+ expect(bakes.active).toHaveLength(1);+ expect(bakes.active[0]!.label).toBe('Counting');+ expect(bakes.active[0]!.progress).toBeGreaterThan(0);+ expect(bakes.active[0]!.progress).toBeLessThan(1);+ for (let f = 0; f < 10; f++) bakes.step(ticking());+ await expect(job.done).resolves.toBe('done');+ expect(bakes.active).toHaveLength(0);+ });++ it('stop when cancelled, and show marks of work stepped elsewhere until they are done', () => {+ const bakes = new Bakes();+ const job = bakes.run('Never', counting(1000));+ job.cancel();+ expect(bakes.active).toHaveLength(0);+ const owner = {};+ bakes.mark(owner, 'Building', 0.25);+ expect(bakes.active).toEqual([{ label: 'Building', progress: 0.25 }]);+ bakes.mark(owner, 'Building', 1);+ expect(bakes.active).toHaveLength(0);+ });++ it('reject when the job throws', async () => {+ const bakes = new Bakes();+ const job = bakes.run('Broken', (function* () { yield 0; throw new Error('no'); })());+ bakes.step(ticking());+ bakes.step(ticking());+ await expect(job.done).rejects.toThrow('no');+ });++ it('run to their end at once for a caller with no frames', () => {+ expect(finish(counting(5))).toBe('done');+ });+});diff --git a/sdk/tests/terrain-erosion.test.ts b/sdk/tests/terrain-erosion.test.tsnew file mode 100644index 000000000..2c98a3c6a--- /dev/null+++ b/sdk/tests/terrain-erosion.test.ts@@ -0,0 +1,59 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { erodeHeightfield, proceduralHeightfield, type Heightfield } from '../src/terrain/heightfield';++// A valley: two slopes falling toward a line down the middle along z, and the whole tilting down toward +z.+function valley(n: number): Heightfield {+ const data = new Float32Array(n * n);+ for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) {+ const across = Math.abs(i / (n - 1) - 0.5) * 2, along = 1 - j / (n - 1);+ data[j * n + i] = 0.15 + 0.6 * across + 0.25 * along;+ }+ return { width: n, height: n, data };+}+const worn = (field: Heightfield, amount = 1, seed = 3) => erodeHeightfield(field, { amount, seed, sizeX: 1000, sizeZ: 1000, height: 300 });++describe('erosion', () => {+ it('wears the same ground the same way from the same seed, and another way from another', () => {+ const a = worn(valley(65)), b = worn(valley(65)), c = worn(valley(65), 1, 4);+ expect(Array.from(a.field.data)).toEqual(Array.from(b.field.data));+ expect(Array.from(a.field.data)).not.toEqual(Array.from(c.field.data));+ });++ it('leaves the ground alone with no rain', () => {+ const field = valley(33);+ expect(Array.from(worn(field, 0).field.data)).toEqual(Array.from(field.data));+ });++ it('cuts the slopes and lays silt in the valley floor', () => {+ const n = 65, field = valley(n), out = worn(field, 2);+ let cut = 0, laid = 0;+ for (let j = 8; j < n - 8; j++) {+ const side = j * n + 12, floor = j * n + (n - 1) / 2;+ cut += field.data[side]! - out.field.data[side]!;+ laid += out.field.data[floor]! - field.data[floor]!;+ }+ expect(cut).toBeGreaterThan(0);+ expect(laid).toBeGreaterThan(0);+ for (const v of out.field.data) expect(v >= 0 && v <= 1).toBe(true);+ });++ it('keeps where the water ran: the valley floor more than the ridge', () => {+ const n = 65, out = worn(valley(n), 2);+ let floor = 0, ridge = 0;+ for (let j = 8; j < n - 8; j++) { floor += out.flow[j * n + (n - 1) / 2]!; ridge += out.flow[j * n + 1]!; }+ expect(floor).toBeGreaterThan(ridge * 2);+ });+});++describe('warped noise', () => {+ it('bends the ground it would have made, and still spans 0 to 1', () => {+ const base = { resolution: 65, seed: 2, frequency: 3, octaves: 4, persistence: 0.5, ridged: 0.3 };+ const plain = proceduralHeightfield(base), bent = proceduralHeightfield({ ...base, warp: 0.8 });+ expect(Array.from(bent.data)).not.toEqual(Array.from(plain.data));+ expect(Math.min(...bent.data)).toBeCloseTo(0, 6);+ expect(Math.max(...bent.data)).toBeCloseTo(1, 6);+ expect(Array.from(proceduralHeightfield({ ...base, warp: 0 }).data)).toEqual(Array.from(plain.data));+ });+});