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.

fix(terrain): the layer arrays are composed again after a device loss instead of kept as a CPU copy

yhhdd4507c48618
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 307d17c57..60a9790d7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -91,6 +91,7 @@ published separately; it ships inside the editor.
- **A scanned preview reaches the game's own server.** The page a phone opens from the preview QR code allowed connections only to itself, so a game that logged in to a server on the LAN worked in Play and in a single-file build but not on the phone. The preview now connects as Play does; a shipping web export still connects only to the servers listed in Project Settings → Allowed server origins.
- **The ground has no dark patches on a Mac.** With the depth prepass on (quality high and medium), a material written as a fragment shader alone, the terrain among them, drew its colour from a vertex stage that did not declare its position invariant, while its depth came from one that did. Metal is free to compute the two a bit apart, and wherever they differed the colour failed the equal-depth test: sand, sea floor and grass showed dark triangles. Both stages now declare it, on WebGL2 and WebGPU.
- **No "uniform not found" warnings for a texture a program does not read.** A material sets each of its textures on every program it is drawn with, and the depth program of a terrain or a lit material reads few of them, so opening a scene filled the log with warnings that read like typos. A texture a program does not use is now skipped quietly.
+- **A terrain with texture layers no longer keeps a second copy of them in memory.** Its layer arrays were made as content the graphics device keeps a CPU copy of, to restore after a GPU loss: 12 MiB on Terrain & Water, which took the copies past their 16 MiB budget and logged a warning. The terrain now says how to make them again: after a loss it reads and packs its layer files once more and puts them back behind the same textures.
- **A subpath of an official package resolves.** Importing `estella-plugin-…/something` from a project script no longer hangs the script build.
- **Background shader compilation, the warm-up and on-demand drawing reach a build whose quality level is Off.** A build dropped the whole `quality` block when the level was Off, though these three choices hold whatever the level: a project that switched `asyncShaderCompile`, `prewarmShaders` or `renderOnDemand` on read them in the editor and shipped a game that ignored them. The block now ships when any of them is on.
- **A terrain and a streamed world run on the Android and iOS templates.** The terrain's layer textures were refused on a device (it has no wasm heap to copy them through), and a chunked world's maker threw on every tick because QuickJS has no `AbortController`. The layers now go over as bytes, as every other texture does, and the world uses a handle of its own where the host has none.
diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.ts
index 066556f00..3b7c9aa2e 100644
--- a/pipeline/src/runtime/gameHost.ts
+++ b/pipeline/src/runtime/gameHost.ts
@@ -21,7 +21,7 @@ import {
AnimatorRootMotion, Playthrough, Name,
worldResidencyReport, PostProcess, Renderer, Audio, Camera,
getComponentRegistry, BakesRes,
- startDebugChannel, glContextAttributes, warmShaders,
+ startDebugChannel, glContextAttributes, warmShaders, getResourceStats,
} from 'esengine';
import { installDevicePreview } from './devicePreviewClient';
declare const __ESTELLA_LAN_PREVIEW__: boolean;
@@ -788,6 +788,8 @@ async function boot(): Promise<void> {
generation: m.renderer_deviceGeneration?.() ?? -1,
programEpoch: m.renderer_programEpoch?.() ?? -1,
lost: gl ? gl.isContextLost() : false,
+ // The CPU copies the device keeps to restore content after a loss.
+ retainedBytes: getResourceStats()?.retainedBytes ?? -1,
};
},
loseDevice(): boolean {
diff --git a/sdk/src/terrain/layerArrays.ts b/sdk/src/terrain/layerArrays.ts
index 12003ee2a..fd29427ba 100644
--- a/sdk/src/terrain/layerArrays.ts
+++ b/sdk/src/terrain/layerArrays.ts
@@ -11,10 +11,10 @@ import { decodeImagePixels } from '../asset/imageDecode';
import { decodePngData } from '../asset/pngData';
import { isMiniGame } from '../platform';
import { createTextureArrayFromPixels } from '../runtime/runtimeAssets';
-import { getResourceManager } from '../wasm/resourceManager';
+import { getResourceManager, provideTextureContent, withdrawTextureContent } from '../wasm/resourceManager';
import { TextureContent } from '../wasm';
import { log } from '../util/logger';
-import { packLayers, type LayerImage, type LayerSource, type TerrainLayerDef } from './layers';
+import { packLayers, type LayerImage, type LayerSource, type PackedLayers, type TerrainLayerDef } from './layers';
/** An image file's pixels exactly as stored (no premultiply, no colour conversion), by its project path or reference. */
export async function imagePixelsAt(app: App, path: string): Promise<{ width: number; height: number; pixels: Uint8Array; wide?: Uint16Array } | null> {
@@ -41,8 +41,8 @@ export interface LayerArrays {
tiles: number[];
}
-/** Reads the layer files `refs` and packs them; null if the engine refuses the arrays. At most `most` layers are packed. */
-export async function loadLayerArrays(app: App, refs: readonly string[], most: number): Promise<LayerArrays | null> {
+/** Reads the layer files `refs` (at most `most`) and packs them, at half the size on a minigame, whose memory is smaller. */
+export async function readAndPackLayers(app: App, refs: readonly string[], most: number): Promise<PackedLayers> {
const assets = app.getResource(Assets);
if (refs.length > most) log.warn('terrain', `a ground draws ${most} layers at most; it names ${refs.length}`);
const sources: LayerSource[] = [];
@@ -56,20 +56,56 @@ export async function loadLayerArrays(app: App, refs: readonly string[], most: n
};
sources.push({ def, albedo: await image(def.albedo), normal: await image(def.normal), mask: await image(def.mask) });
}
- // A minigame's memory holds the layers at half the size.
- const packed = packLayers(sources, isMiniGame() ? 512 : 1024);
- const made = (layers: Uint8Array[], srgb: boolean): number => createTextureArrayFromPixels(app.wasmModule,
- { width: packed.size, height: packed.size, layers }, TextureContent.Retained, { filterMode: 'linear', wrapMode: 'repeat', mipmaps: true, srgb });
- const albedo = made(packed.albedo, true), normal = made(packed.normal, false);
- if (!albedo || !normal) {
- releaseLayerArrays([albedo, normal]);
+ return packLayers(sources, isMiniGame() ? 512 : 1024);
+}
+
+type LayerKind = 'albedo' | 'normal' | 'mask';
+
+/**
+ * One texture array per kind from `packed`. The device keeps no copy of them (four layers of three kinds are 48 MiB): after a device loss
+ * `repack` packs the sources again, once for all the kinds, and each kind's layers are moved behind the handle it had, which is when the
+ * device counts them restored. Null, with nothing left made, if the engine refuses one.
+ */
+export function createLayerArrays(app: App, packed: PackedLayers, kinds: readonly LayerKind[],
+ repack: () => Promise<PackedLayers>): number[] | null {
+ const make = (layers: Uint8Array[], kind: LayerKind, content: TextureContent): number => createTextureArrayFromPixels(app.wasmModule,
+ { width: packed.size, height: packed.size, layers }, content, { filterMode: 'linear', wrapMode: 'repeat', mipmaps: true, srgb: kind === 'albedo' });
+ const handles = kinds.map((kind) => make(packed[kind], kind, TextureContent.Composed));
+ if (handles.some((h) => !h)) {
+ releaseLayerArrays(handles);
return null;
}
- return { albedo, normal, tiles: packed.tiles };
+ let again: Promise<PackedLayers> | null = null;
+ let waiting = 0;
+ handles.forEach((handle, i) => provideTextureContent(handle, async () => {
+ if (!again) { again = repack(); waiting = handles.length; }
+ try {
+ const fresh = make((await again)[kinds[i]!], kinds[i]!, TextureContent.Transient);
+ const rm = getResourceManager();
+ if (!fresh || !rm?.adoptTextureContent) return false;
+ const moved = rm.adoptTextureContent(handle, fresh);
+ rm.releaseTexture(fresh);
+ return moved;
+ } finally {
+ if (--waiting === 0) again = null;
+ }
+ }));
+ return handles;
+}
+
+/** Reads the layer files `refs` and packs them; null if the engine refuses the arrays. At most `most` layers are packed. */
+export async function loadLayerArrays(app: App, refs: readonly string[], most: number): Promise<LayerArrays | null> {
+ const packed = await readAndPackLayers(app, refs, most);
+ const made = createLayerArrays(app, packed, ['albedo', 'normal'], () => readAndPackLayers(app, refs, most));
+ return made ? { albedo: made[0]!, normal: made[1]!, tiles: packed.tiles } : null;
}
-/** Gives the engine back arrays made by {@link loadLayerArrays}. */
+/** Gives the engine back arrays made by {@link createLayerArrays}. */
export function releaseLayerArrays(handles: readonly number[]): void {
const rm = getResourceManager();
- for (const handle of handles) if (handle) rm?.releaseTexture(handle);
+ for (const handle of handles) {
+ if (!handle) continue;
+ withdrawTextureContent(handle);
+ rm?.releaseTexture(handle);
+ }
}
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
index a17b517cd..480685e04 100644
--- a/sdk/src/terrain/terrainPlugin.ts
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -46,14 +46,12 @@ import { levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type T
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';
import { buildPatchMesh } from './patch';
-import { isMiniGame } from '../platform';
-import { packLayers, type LayerImage, type LayerSource, type TerrainLayerDef } from './layers';
import { TerrainSurface, TILE_CELLS, type SurfaceTile } from './surface';
import { groundHeightAt, groundNormalAt, groundPaintAt, type GroundData } from './groundQuery';
import { collisionGeometryOf } from '../runtime/collisionGeometry';
import { chunksOf, ProceduralChunksRes } from '../residency/chunks';
import { movers } from './movers';
-import { imagePixelsAt } from './layerArrays';
+import { createLayerArrays, imagePixelsAt, readAndPackLayers, releaseLayerArrays } from './layerArrays';
/** The engine's own provider of ground without end: seeded noise of the world's position. */
export const NOISE_PROVIDER = 'estella:noise';
@@ -732,31 +730,14 @@ export class TerrainPlugin implements Plugin {
}
void (async () => {
try {
- if (refs.length > MAX_LAYERS) log.warn('terrain', `a terrain draws ${MAX_LAYERS} layers at most; it names ${refs.length}`);
- const sources: LayerSource[] = [];
- for (const ref of refs.slice(0, MAX_LAYERS)) {
- const def = await assets.load<TerrainLayerDef>('terrain-layer', ref);
- const image = async (path: string | undefined): Promise<LayerImage | null> => {
- if (!path) return null;
- const got = await this.pixelsAt(app, path);
- if (!got) log.warn('terrain', `the texture ${path} of terrain layer ${ref} could not be read`);
- return got;
- };
- sources.push({ def, albedo: await image(def.albedo), normal: await image(def.normal), mask: await image(def.mask) });
- }
+ const packed = await readAndPackLayers(app, refs, MAX_LAYERS);
if (built.epoch !== epoch || !built.instance) return;
- // A minigame's memory holds the layers at half the size.
- const packed = packLayers(sources, isMiniGame() ? 512 : 1024);
- const made = (layers: Uint8Array[], srgb: boolean): number => createTextureArrayFromPixels(app.wasmModule,
- { width: packed.size, height: packed.size, layers }, TextureContent.Retained,
- { filterMode: 'linear', wrapMode: 'repeat', mipmaps: true, srgb });
- const arrays = [made(packed.albedo, true), made(packed.normal, false), made(packed.mask, false)];
- if (arrays.some((h) => !h)) {
+ const arrays = createLayerArrays(app, packed, ['albedo', 'normal', 'mask'], () => readAndPackLayers(app, refs, MAX_LAYERS));
+ if (!arrays) {
log.warn('terrain', 'the engine refused the terrain layers\' texture arrays');
- this.releaseArrays(arrays);
return;
}
- this.releaseArrays(built.arrays);
+ releaseLayerArrays(built.arrays);
built.arrays = arrays;
const set = (name: string, value: Parameters<typeof Material.setUniform>[2]): void => { Material.setUniform(built.instance, name, value); };
set('u_albedoLayers', Material.tex(arrays[0]!));
@@ -778,11 +759,6 @@ export class TerrainPlugin implements Plugin {
})();
}
- private releaseArrays(arrays: readonly number[]): void {
- const rm = getResourceManager();
- for (const handle of arrays) if (handle) rm?.releaseTexture(handle);
- }
-
/** Makes what the ground is drawn with: the patch, the atlases and an instance of its material. */
private async prepare(app: App, built: Built): Promise<void> {
built.pending = true;
@@ -1055,7 +1031,7 @@ export class TerrainPlugin implements Plugin {
rm?.releaseTexture(handle);
}
built.heights = built.paint = built.paint2 = 0;
- this.releaseArrays(built.arrays);
+ releaseLayerArrays(built.arrays);
built.arrays = [];
built.packed = '';
if (built.instance) Material.release(built.instance);
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index ca00501dd..960d1c893 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -66,6 +66,8 @@ export const TextureContent = {
GlyphPage: 6,
/** A skeleton's atlas page, decoded again from its image. */
AtlasPage: 7,
+ /** Composed again by its creator from its sources (a terrain's layer arrays). */
+ Composed: 8,
} as const;
export type TextureContent = typeof TextureContent[keyof typeof TextureContent];
diff --git a/sdk/tests/terrain-layer-arrays-refill.test.ts b/sdk/tests/terrain-layer-arrays-refill.test.ts
new file mode 100644
index 000000000..43c31c115
--- /dev/null
+++ b/sdk/tests/terrain-layer-arrays-refill.test.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A ground's layer arrays are not kept by the device: after a loss they are packed again, once for every kind, and moved behind the
+ * handles they had.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { App } from '../src/app/app';
+import { TextureContent, type CppResourceManager } from '../src/wasm';
+import { initResourceManager, shutdownResourceManager, textureRefill } from '../src/wasm/resourceManager';
+import { createLayerArrays, releaseLayerArrays } from '../src/terrain/layerArrays';
+import type { PackedLayers } from '../src/terrain/layers';
+
+const layer = (): Uint8Array => new Uint8Array(2 * 2 * 4);
+const packed = (): PackedLayers => ({ size: 2, albedo: [layer()], normal: [layer()], mask: [layer()], tiles: [4], heightBlends: [-1] });
+
+function engine() {
+ let next = 10;
+ const content = new Map<number, number>();
+ const rm = {
+ createTextureArrayFromBytes: vi.fn((_w: number, _h: number, _n: number, _bytes: Uint8Array, _f: number, _fi: number, _wr: number, c: number) => {
+ const handle = next++;
+ content.set(handle, c);
+ return handle;
+ }),
+ adoptTextureContent: vi.fn(() => true),
+ releaseTexture: vi.fn(),
+ };
+ initResourceManager(rm as unknown as CppResourceManager);
+ return { rm, content, app: { wasmModule: null } as unknown as App };
+}
+
+afterEach(() => shutdownResourceManager());
+
+describe('terrain layer arrays after a device loss', () => {
+ it('are made as content their creator composes, not bytes the device keeps', () => {
+ const { content, app } = engine();
+ const handles = createLayerArrays(app, packed(), ['albedo', 'normal', 'mask'], async () => packed())!;
+ expect(handles.map((h) => content.get(h))).toEqual([TextureContent.Composed, TextureContent.Composed, TextureContent.Composed]);
+ });
+
+ it('are packed again once for all three and moved behind the handles they had, at every loss', async () => {
+ const { rm, content, app } = engine();
+ const repack = vi.fn(async () => packed());
+ const handles = createLayerArrays(app, packed(), ['albedo', 'normal', 'mask'], repack)!;
+
+ for (const loss of [1, 2]) {
+ rm.adoptTextureContent.mockClear();
+ for (const h of handles) expect(await textureRefill(h)!()).toBe(true);
+ expect(repack).toHaveBeenCalledTimes(loss);
+ expect(rm.adoptTextureContent.mock.calls.map(([into]) => into)).toEqual(handles);
+ for (const [, fresh] of rm.adoptTextureContent.mock.calls as unknown as Array<[number, number]>) {
+ expect(content.get(fresh)).toBe(TextureContent.Transient);
+ expect(rm.releaseTexture).toHaveBeenCalledWith(fresh);
+ }
+ }
+ });
+
+ it('take their refills with them when released', () => {
+ const { app } = engine();
+ const handles = createLayerArrays(app, packed(), ['albedo', 'normal'], async () => packed())!;
+ releaseLayerArrays(handles);
+ expect(handles.map((h) => textureRefill(h))).toEqual([undefined, undefined]);
+ });
+});
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index aaedb96f2..46a7e89f8 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -56,6 +56,7 @@ enum class ResourceContent : u32 {
Mesh = 5, ///< Geometry the asset layer replays (MeshRecovery::SourceReplayable).
GlyphPage = 6, ///< Repainted from the glyphs placed on it.
AtlasPage = 7, ///< A skeleton's atlas page, decoded again from its image.
+ Composed = 8, ///< Composed again by its creator from its sources (a terrain's layer arrays).
};
/** @brief The device's policy for a content code; unknown codes are Asset, the one that asks. */
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index e33db2773..7906cee4a 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3430,4 +3430,8 @@ export const NOTED = {
{"note":"The ground has no dark patches on a Mac."},
"fix(render): seeding a material's samplers skips the ones a program optimized out, instead of warning of a typo for each":
{"note":"No \"uniform not found\" warnings for a texture a program does not read."},
+ "fix(terrain): the layer arrays are composed again after a device loss instead of kept as a CPU copy":
+ {"note":"A terrain with texture layers no longer keeps a second copy of them in memory."},
+ "fix(build-tools): --debug builds a debug engine; --release, always on, overrode it":
+ {"internal":"the build command's debug switch; no engine change"},
};