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
fix: budget terrain page sampling and painting across frames
yhh99d06e432c3a
diff --git a/sdk/src/terrain/pages.ts b/sdk/src/terrain/pages.tsindex 9061e2ecc..7e12b7366 100644--- a/sdk/src/terrain/pages.ts+++ b/sdk/src/terrain/pages.ts@@ -46,13 +46,25 @@ export function makePage(source: TerrainSource, x0: number, z0: number, size: nureturn got instanceof Promise ? got.then((r) => encodePage(source, x0, z0, step, r.heights, r, repaint)): encodePage(source, x0, z0, step, got.heights, got, repaint);}- const h = new Float32Array(n * n);+ return finishPage(makePageJob(source, x0, z0, size, repaint));+}++/** A page made in bounded sample batches. Use only when height() is ready and synchronous; region-only providers keep their async path. */+export function* makePageJob(source: TerrainSource, x0: number, z0: number, size: number, repaint?: Repaint): Generator<number, PageImage, void> {+ const n = PAGE_SIDE, step = size / PAGE_TEXELS, h = new Float32Array(n * n);const [bx0, bz0, bx1, bz1] = source.bounds ?? [-Infinity, -Infinity, Infinity, Infinity];- for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) {+ for (let k = 0; k < h.length; k++) {+ const i = k % n, j = Math.floor(k / n);const x = Math.min(Math.max(x0 + (i - 1) * step, bx0), bx1), z = Math.min(Math.max(z0 + (j - 1) * step, bz0), bz1);- h[j * n + i] = source.height(x, z) ?? source.minHeight;+ h[k] = source.height(x, z) ?? source.minHeight;+ if ((k + 1) % 32 === 0) yield 0.4 * (k + 1) / h.length;}- return encodePage(source, x0, z0, step, h, undefined, repaint);+ yield 0.4;+ return yield* encodePageJob(source, x0, z0, step, h, undefined, repaint);+}++function finishPage(job: Generator<number, PageImage, void>): PageImage {+ for (;;) { const next = job.next(); if (next.done) return next.value; }}/** The paint of a sample at (x, z) in the terrain's space, `h` high and facing `ny` up, from what it would otherwise be. */@@ -60,6 +72,10 @@ export type Repaint = (x: number, z: number, h: number, ny: number, w: LayerWeig/** Encodes a page's samples (row by row, one past each edge): heights and normals into one image, the paint into the other. */function encodePage(source: TerrainSource, x0: number, z0: number, step: number, h: Float32Array, given?: TerrainRegionSamples, repaint?: Repaint): PageImage {+ return finishPage(encodePageJob(source, x0, z0, step, h, given, repaint));+}++function* encodePageJob(source: TerrainSource, x0: number, z0: number, step: number, h: Float32Array, given?: TerrainRegionSamples, repaint?: Repaint): Generator<number, PageImage, void> {const n = PAGE_SIDE;const [bx0, bz0, bx1, bz1] = source.bounds ?? [-Infinity, -Infinity, Infinity, Infinity];let min = Infinity, max = -Infinity;@@ -88,6 +104,7 @@ function encodePage(source: TerrainSource, x0: number, z0: number, step: number,paint[k * 4 + c] = Math.round(Math.min(Math.max(w[c] ?? 0, 0), 1) * 255);paint2[k * 4 + c] = Math.round(Math.min(Math.max(w[c + 4] ?? 0, 0), 1) * 255);}+ if ((k + 1) % 32 === 0) yield 0.4 + 0.6 * (k + 1) / (n * n);}return { heights, paint, paint2, min: Number.isFinite(min) ? min : source.minHeight, max: Number.isFinite(max) ? max : source.maxHeight };}diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex f22b26269..7542da289 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -44,7 +44,7 @@ export { paintWeights };import { GroundEdit } from './groundEdit';import { FieldSource, ModifiedSource, NoiseSource, 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 { makePage, makePageJob, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage, type Repaint } from './pages';import { noiseProvider, ProviderSource, terrainProvider, terrainProvidersRevision, TerrainUnavailable, type TerrainProvider } from './provider';import { buildPatchMesh } from './patch';import { TerrainSurface, TILE_CELLS, type SurfaceTile } from './surface';@@ -216,6 +216,8 @@ interface Built {wanted: Map<string, TerrainNode>;/** Pages asked of a provider that answers later, by key: the frame's budget is not spent waiting for them. */asked: Set<string>;+ /** A synchronous source's page paused inside sampling/painting, rather than blocking a whole frame. */+ pageWork?: { key: string; epoch: number; edits: number; job: Generator<number, PageImage, void>; image?: PageImage };pending: boolean;/** Why the ground could not be made, once it could not: nothing is drawn or answered for it. */failure: string | null;@@ -492,7 +494,11 @@ export class Terrains {/** Makes every page again, for a paint that changed what it answers. */repaint(): void {- for (const built of this.built_.values()) built.table.clear();+ for (const built of this.built_.values()) {+ built.edits++;+ built.pageWork = undefined;+ built.table.clear();+ }}/** @internal Bumped whenever a terrain's ground changes, so what stands on it knows to stand again. */@@ -939,7 +945,8 @@ export class TerrainPlugin implements Plugin {const paint = app.getResource(TerrainsRes).paint_;const repaint: Repaint | undefined = paint ? (x, z, h, ny, w) => paint(x + at.x, z + at.z, h + at.y, ny, w) : undefined;const bakes = bakesOf(app);- if (built.wanted.size === 0) { bakes.mark(built, 'Building the terrain', 1); return; }+ if (built.wanted.size === 0) { built.pageWork = undefined; bakes.mark(built, 'Building the terrain', 1); return; }+ if (built.pageWork && (built.pageWork.epoch !== built.epoch || built.pageWork.edits !== built.edits || !built.wanted.has(built.pageWork.key))) built.pageWork = undefined;const order = [...built.wanted.values()].sort((a, b) => b.level - a.level|| Math.hypot(a.x0 + a.size / 2 - eye[0], a.z0 + a.size / 2 - eye[2]) - Math.hypot(b.x0 + b.size / 2 - eye[0], b.z0 + b.size / 2 - eye[2]));let made = 0;@@ -953,6 +960,29 @@ export class TerrainPlugin implements Plugin {return true;};const epoch = built.epoch, edits = built.edits;+ const base = source instanceof ModifiedSource ? source.base : source;+ // The built-in noise provider has ready point samples identical to its region samples. External region providers may not.+ const incremental = !source.region || (base instanceof ProviderSource && base.provider.id === NOISE_PROVIDER);+ if (incremental) {+ do {+ if (!built.pageWork) {+ const node = order.find((n) => built.wanted.has(nodeKey(n.level, n.ix, n.iz)));+ if (!node) break;+ built.pageWork = { key: nodeKey(node.level, node.ix, node.iz), epoch, edits, job: makePageJob(source, node.x0, node.z0, node.size, repaint) };+ }+ const work = built.pageWork;+ if (!work.image) {+ const next = work.job.next();+ if (next.done) work.image = next.value;+ }+ if (work.image) {+ if (!store(work.key, work.image)) break;+ built.wanted.delete(work.key); built.pageWork = undefined; made++;+ }+ } while (bakes.hasTime());+ bakes.mark(built, 'Building the terrain', made === 0 ? 0 : 1 - built.wanted.size / (built.wanted.size + made));+ return;+ }for (const node of order) {const key = nodeKey(node.level, node.ix, node.iz);if (built.asked.has(key)) continue;@@ -1030,6 +1060,7 @@ export class TerrainPlugin implements Plugin {built.nodes.clear();built.spare.length = 0;built.wanted.clear();+ built.pageWork = undefined;const rm = getResourceManager();for (const handle of [built.heights, built.paint, built.paint2]) {if (!handle) continue;diff --git a/sdk/tests/terrain-page-budget.test.ts b/sdk/tests/terrain-page-budget.test.tsnew file mode 100644index 000000000..093a800d5--- /dev/null+++ b/sdk/tests/terrain-page-budget.test.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: Apache-2.0+import { describe, expect, it } from 'vitest';+import { makePage, makePageJob, PAGE_SIDE, type PageImage } from '../src/terrain/pages';+import { noiseProvider, ProviderSource } from '../src/terrain/provider';+import type { TerrainSource } from '../src/terrain/source';++describe('incremental terrain pages', () => {+ it('pauses during both height sampling and biome painting, not only between whole pages', () => {+ let heights = 0, paints = 0;+ const source: TerrainSource = { infinite: true, bounds: null, minHeight: 0, maxHeight: 100,+ height: (x, z) => { heights++; return 20 + x * 0.1 + z * 0.05; },+ normal: () => [0, 1, 0], paint: () => [1, 0, 0, 0] };+ const job = makePageJob(source, 0, 0, 64, (_x, _z, _h, _up, w) => { paints++; return w; });+ expect(heights).toBe(0);+ let lastHeight = 0, lastPaint = 0, progress = 0, turns = 0;+ for (;;) {+ const next = job.next(); turns++;+ expect(heights - lastHeight).toBeLessThanOrEqual(32);+ expect(paints - lastPaint).toBeLessThanOrEqual(32);+ lastHeight = heights; lastPaint = paints;+ if (next.done) { expect(next.value.min).toBeGreaterThan(19); break; }+ expect(next.value).toBeGreaterThanOrEqual(progress); progress = next.value;+ }+ expect(heights).toBe(PAGE_SIDE ** 2);+ expect(paints).toBe(PAGE_SIDE ** 2);+ expect(turns).toBeGreaterThan(250);+ });++ it('matches the built-in provider region path byte for byte, including repaint and edge normals', () => {+ const provider = noiseProvider(() => ({ seed: 4, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.3,+ warp: 0.35, erosion: 1, sizeX: 4200, height: 520, rockSlope: 0.34, dirtHeight: 0.74, snowHeight: 0.95 }));+ const source = new ProviderSource(provider, 'demo', 4, 1, 120, -30, 4, (_h, up) => [up, 1 - up, 0, 0]);+ const repaint = (x: number, z: number, _h: number, _up: number, w: readonly number[]) => [w[0]!, w[1]!, (Math.sin(x + z) + 1) / 2, 0];+ const expected = makePage(source, -32, 64, 128, repaint) as PageImage;+ const job = makePageJob(source, -32, 64, 128, repaint);+ for (;;) {+ const next = job.next();+ if (next.done) { expect(next.value).toEqual(expected); break; }+ }+ });++ it('abandoning an obsolete page performs no further source queries', () => {+ let calls = 0;+ const source: TerrainSource = { infinite: true, bounds: null, minHeight: 0, maxHeight: 10,+ height: () => { calls++; return 5; }, normal: () => [0, 1, 0], paint: () => [1, 0, 0, 0] };+ const job = makePageJob(source, 0, 0, 64);+ job.next(); const before = calls;+ job.return(undefined as never);+ expect(job.next().done).toBe(true);+ expect(calls).toBe(before);+ });+});