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(editor): what grows round the view follows the viewport in 2D and 3D, and a terrain stroke keeps only the tiles it touched

yhh3c062b72188b
diff --git a/desktop b/desktop
index bf5e07137..308d1ed7f 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit bf5e0713710930cf93d79ddf8c72ab01d473c245
+Subproject commit 308d1ed7f458a4403f3b848648ce7c7313ba6566
diff --git a/docs/astro/src/content/docs/world/streaming.mdx b/docs/astro/src/content/docs/world/streaming.mdx
index ffd30b47d..c9533202d 100644
--- a/docs/astro/src/content/docs/world/streaming.mdx
+++ b/docs/astro/src/content/docs/world/streaming.mdx
@@ -183,6 +183,10 @@ report.loadCount; // places brought in since boot
Counts rather than a picture, because a cell that is not drawn and a cell that
does not exist look the same from a camera.
+## In the editor
+
+In the edit view, terrain detail, foliage, generated worlds and voxels grow around the viewport, 2D and 3D alike; a `WorldStreamingSource` in the scene only counts while the game runs.
+
## Clearing or replacing a world
Disable or remove the streaming sources, then await `streamer.clear()`. It releases
diff --git a/docs/astro/src/content/docs/zh-cn/world/streaming.mdx b/docs/astro/src/content/docs/zh-cn/world/streaming.mdx
index 27ab6fecf..33e76dd13 100644
--- a/docs/astro/src/content/docs/zh-cn/world/streaming.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/streaming.mdx
@@ -150,6 +150,10 @@ report.loadCount; // 启动以来带进来过多少个地方
给的是计数而不是画面,因为"没有被画出来的格子"和"根本不存在的格子",从相机看是一样的。
+## 在编辑器里
+
+编辑视图下,地形细节、植被、世界生成和体素都围绕视口生成,场景里的 `WorldStreamingSource` 只在运行时才起作用,2D 和 3D 视图都是如此。
+
## 清空或替换世界
先禁用或移除流送源,再等待 `streamer.clear()`。它会释放已经预加载的资源,并等待尚未完成的准备、发布和卸载结束。
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index b1a1c27cc..f50cbbba9 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 115,
"beta": 178,
- "experimental": 2978,
+ "experimental": 2979,
"deprecated": 3
},
- "total": 3271,
+ "total": 3272,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 23750b6f2..7c245fd40 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -11432,6 +11432,7 @@ groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
layerNames: () => string[]
+load: () => TerrainLoad
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
paintAt: (x: number, z: number) => readonly number[] | null
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index c43254dad..e5e4abdee 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -11648,6 +11648,7 @@ groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
layerNames: () => string[]
+load: () => TerrainLoad
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
paintAt: (x: number, z: number) => readonly number[] | null
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index a7893554a..53040ebb7 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -11427,6 +11427,7 @@ groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
layerNames: () => string[]
+load: () => TerrainLoad
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
paintAt: (x: number, z: number) => readonly number[] | null
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 22346145f..2a1562fd9 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -11723,6 +11723,7 @@ groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
layerNames: () => string[]
+load: () => TerrainLoad
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
paintAt: (x: number, z: number) => readonly number[] | null
diff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.md
index e414c3bba..39057c8c3 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 · 110 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 111 experimental · 0 deprecated
## Brush — interface @experimental
```
@@ -526,6 +526,12 @@ tile: number
tint: [number, number, number]
```
+## TerrainLoad — interface @experimental
+```
+cpuBytes: number
+loading: number
+```
+
## TerrainModifier — interface @experimental
```
apply: (x: number, z: number, h: number) => number
@@ -628,6 +634,7 @@ groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
layerNames: () => string[]
+load: () => TerrainLoad
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
paintAt: (x: number, z: number) => readonly number[] | null
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index e7321de4d..0186ff597 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -11434,6 +11434,7 @@ groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
layerNames: () => string[]
+load: () => TerrainLoad
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
paintAt: (x: number, z: number) => readonly number[] | null
diff --git a/sdk/src/camera/EditorView.ts b/sdk/src/camera/EditorView.ts
index d34a8e4cd..4e6857547 100644
--- a/sdk/src/camera/EditorView.ts
+++ b/sdk/src/camera/EditorView.ts
@@ -241,6 +241,11 @@ export function editorViewEye(view: EditorViewData): Vec3 {
};
}
+export function editorViewpoint(view: EditorViewData): Vec3 | null {
+ if (!view.active) return null;
+ return view.perspective ? editorViewEye(view) : { x: view.x, y: view.y, z: view.z ?? 0 };
+}
+
/**
* Move the focus by an offset in the view's OWN axes, in world units.
*
diff --git a/sdk/src/residency/chunks.ts b/sdk/src/residency/chunks.ts
index 194a88ad1..a73a826af 100644
--- a/sdk/src/residency/chunks.ts
+++ b/sdk/src/residency/chunks.ts
@@ -24,7 +24,7 @@ import type { App } from '../app/app';
import { defineResource } from '../ecs/resource';
import { defineSystem, Schedule } from '../ecs/system';
import { Camera, Transform, type CameraData, type TransformData } from '../ecs/component';
-import { EditorView, editorViewEye } from '../camera/EditorView';
+import { EditorView, editorViewpoint } from '../camera/EditorView';
import { WorldStreamingSource, type WorldStreamingSourceData } from './components';
import { bakesOf } from '../runtime/bakes';
import { log } from '../util/logger';
@@ -342,12 +342,12 @@ function stateOf(c: Chunk<unknown>, generation: number | string): ChunkState {
/** The resource; {@link chunksOf} installs it where it is missing. @experimental */
export const ProceduralChunksRes = defineResource<ProceduralChunks>(new ProceduralChunks(), 'ProceduralChunks');
-/**
- * The places the world is wanted round: every enabled WorldStreamingSource and, when there is none, the editor's eye while it looks
- * at the scene in 3D, else the active cameras. The same sources the WorldStreamer reads cells by.
- */
export function streamingSourcesOf(app: App): ChunkSource[] {
const world = app.world;
+ if (app.hasResource(EditorView)) {
+ const at = editorViewpoint(app.getResource(EditorView));
+ if (at) return [{ x: at.x, y: at.y, z: at.z }];
+ }
world.ensureTransformsComposed();
const out: ChunkSource[] = [];
for (const e of world.getEntitiesWithComponents([WorldStreamingSource, Transform])) {
@@ -356,13 +356,6 @@ export function streamingSourcesOf(app: App): ChunkSource[] {
out.push({ x: p.x, y: p.y, z: p.z });
}
if (out.length > 0) return out;
- if (app.hasResource(EditorView)) {
- const view = app.getResource(EditorView);
- if (view.active && view.perspective) {
- const eye = editorViewEye(view);
- return [{ x: eye.x, y: eye.y, z: eye.z }];
- }
- }
for (const e of world.getEntitiesWithComponents([Camera, Transform])) {
if (!(world.get(e, Camera) as CameraData).isActive) continue;
const p = (world.get(e, Transform) as TransformData).worldPosition;
diff --git a/sdk/src/terrain/groundEdit.ts b/sdk/src/terrain/groundEdit.ts
index 431029be9..55281ca74 100644
--- a/sdk/src/terrain/groundEdit.ts
+++ b/sdk/src/terrain/groundEdit.ts
@@ -13,10 +13,15 @@
import type { Heightfield } from './heightfield';
import type { FieldSource, Splat } from './source';
import type { ModifiedSource } from './source';
-import { encodeHeightmap, paintSplat, sculptField, unionDirty, type Dirty } from './sculpt';
+import { encodeHeightmap, paintSplat, reach, sculptField, unionDirty, type Dirty } from './sculpt';
-/** The texels of one array a stroke changed, as they were and as they are. */
-interface Piece<T> { rect: Dirty; width: number; before: T; after: T }
+type Texels = Float32Array | Uint8Array;
+
+interface Tile<T> { rect: Dirty; before: T; after: T }
+
+interface Piece<T> { rect: Dirty; width: number; tiles: Tile<T>[] }
+
+const TILE = 32;
/** What one stroke changed. @experimental */
export interface GroundPatch {
@@ -25,11 +30,30 @@ export interface GroundPatch {
splat2: Piece<Uint8Array> | null;
}
-/** The stroke being made: the arrays as they were, copied when it began. */
+class BeforeTiles<T extends Texels> {
+ readonly kept = new Map<number, { rect: Dirty; before: T }>();
+
+ constructor(private readonly width: number, private readonly height: number, private readonly stride: number) {}
+
+ keep(now: T, span: Dirty): void {
+ for (let tj = span.j0 >> 5; tj <= span.j1 >> 5; tj++) for (let ti = span.i0 >> 5; ti <= span.i1 >> 5; ti++) {
+ const key = tj * (((this.width - 1) >> 5) + 1) + ti;
+ if (this.kept.has(key)) continue;
+ const rect = { i0: ti * TILE, j0: tj * TILE, i1: Math.min(ti * TILE + TILE - 1, this.width - 1), j1: Math.min(tj * TILE + TILE - 1, this.height - 1) };
+ this.kept.set(key, { rect, before: copied(now, this.width, rect, this.stride) });
+ }
+ }
+
+ piece(now: T, rect: Dirty): Piece<T> {
+ const tiles = [...this.kept.values()].map((tile) => ({ ...tile, after: copied(now, this.width, tile.rect, this.stride) }));
+ return { rect, width: this.width, tiles };
+ }
+}
+
interface Open {
- heights: Float32Array;
- splat: Uint8Array | null;
- splat2: Uint8Array | null;
+ heights: BeforeTiles<Float32Array>;
+ splat: BeforeTiles<Uint8Array> | null;
+ splat2: BeforeTiles<Uint8Array> | null;
h: Dirty | null;
s: Dirty | null;
s2: Dirty | null;
@@ -64,12 +88,10 @@ export class GroundEdit {
return this.source.height(x - this.modified.origin.x, z - this.modified.origin.z);
}
- /** Starts a stroke: the arrays are copied so that {@link end} can say what changed. */
begin(): void {
if (this.open_) return;
- const { a, b } = this.source.splats();
this.open_ = {
- heights: this.field.data.slice(), splat: a ? a.pixels.slice() : null, splat2: b ? b.pixels.slice() : null,
+ heights: new BeforeTiles(this.field.width, this.field.height, 1), splat: null, splat2: null,
h: null, s: null, s2: null,
};
}
@@ -82,6 +104,8 @@ export class GroundEdit {
const o = this.modified.origin;
const dab = { mode, brush: { x: x - o.x, z: z - o.z, radius, falloff }, amount: mode <= 1 ? amount / this.span : amount,
target: target === undefined ? undefined : (target - this.minHeight) / this.span };
+ const span = reach(this.field.width, this.field.height, this.sizeX, this.sizeZ, dab.brush);
+ if (this.open_ && span) this.open_.heights.keep(this.field.data, span);
const hit = sculptField(this.field, this.sizeX, this.sizeZ, dab);
if (!hit) return;
if (this.open_) this.open_.h = unionDirty(this.open_.h, hit);
@@ -92,7 +116,13 @@ export class GroundEdit {
paint(layer: number, x: number, z: number, radius: number, falloff: number, strength: number, erase = false): void {
const o = this.modified.origin;
const { a, b } = this.source.ensureSplats(layer > 3);
- const hit = paintSplat(a, b, this.sizeX, this.sizeZ, { layer, brush: { x: x - o.x, z: z - o.z, radius, falloff }, strength, erase });
+ const brush = { x: x - o.x, z: z - o.z, radius, falloff };
+ const span = reach(a.width, a.height, this.sizeX, this.sizeZ, brush);
+ if (this.open_ && span) {
+ (this.open_.splat ??= new BeforeTiles(a.width, a.height, 4)).keep(a.pixels, span);
+ if (b) (this.open_.splat2 ??= new BeforeTiles(b.width, b.height, 4)).keep(b.pixels, span);
+ }
+ const hit = paintSplat(a, b, this.sizeX, this.sizeZ, { layer, brush, strength, erase });
if (!hit) return;
if (this.open_) { this.open_.s = unionDirty(this.open_.s, hit); if (b) this.open_.s2 = unionDirty(this.open_.s2, hit); }
this.remake(x, z, radius, a);
@@ -105,9 +135,9 @@ export class GroundEdit {
if (!o) return null;
const { a, b } = this.source.splats();
const patch: GroundPatch = {
- heights: o.h ? piece(this.field.width, o.h, o.heights, this.field.data) : null,
- splat: o.s && a ? piece(a.width, o.s, o.splat ?? zeros(a), a.pixels, 4) : null,
- splat2: o.s2 && b ? piece(b.width, o.s2, o.splat2 ?? zeros(b), b.pixels, 4) : null,
+ heights: o.h ? o.heights.piece(this.field.data, o.h) : null,
+ splat: o.s && a && o.splat ? o.splat.piece(a.pixels, o.s) : null,
+ splat2: o.s2 && b && o.splat2 ? o.splat2.piece(b.pixels, o.s2) : null,
};
return patch.heights || patch.splat || patch.splat2 ? patch : null;
}
@@ -143,24 +173,25 @@ export class GroundEdit {
}
}
-function zeros(s: Splat): Uint8Array { return new Uint8Array(s.pixels.length); }
+function blank<T extends Texels>(like: T, rect: Dirty, stride: number): T {
+ return new (like.constructor as { new (n: number): T })((rect.i1 - rect.i0 + 1) * (rect.j1 - rect.j0 + 1) * stride);
+}
-/** The texels of `rect` of a `width`-wide array, from `before` (the whole array as it was) and `now`. `stride` is values a texel. */
-function piece<T extends Float32Array | Uint8Array>(width: number, rect: Dirty, before: T, now: T, stride = 1): Piece<T> {
- const w = rect.i1 - rect.i0 + 1, h = rect.j1 - rect.j0 + 1;
- const make = (from: T): T => {
- const out = new (from.constructor as { new (n: number): T })(w * h * stride);
- for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) for (let c = 0; c < stride; c++) {
- out[(j * w + i) * stride + c] = from[((rect.j0 + j) * width + rect.i0 + i) * stride + c]!;
- }
- return out;
- };
- return { rect, width, before: make(before), after: make(now) };
+function copied<T extends Texels>(from: T, width: number, rect: Dirty, stride: number): T {
+ const out = blank(from, rect, stride), w = (rect.i1 - rect.i0 + 1) * stride;
+ for (let j = rect.j0; j <= rect.j1; j++) {
+ const at = (j * width + rect.i0) * stride;
+ out.set(from.subarray(at, at + w) as never, (j - rect.j0) * w);
+ }
+ return out;
}
-function put<T extends Float32Array | Uint8Array>(into: T, p: Piece<T>, side: 'before' | 'after', stride: number): void {
- const from = p[side], r = p.rect, w = r.i1 - r.i0 + 1;
- for (let j = r.j0; j <= r.j1; j++) for (let i = r.i0; i <= r.i1; i++) for (let c = 0; c < stride; c++) {
- into[(j * p.width + i) * stride + c] = from[((j - r.j0) * w + (i - r.i0)) * stride + c]!;
+function put<T extends Texels>(into: T, p: Piece<T>, side: 'before' | 'after', stride: number): void {
+ for (const tile of p.tiles) {
+ const from = tile[side], r = tile.rect, w = (r.i1 - r.i0 + 1) * stride;
+ for (let j = r.j0; j <= r.j1; j++) {
+ const row = (j - r.j0) * w;
+ into.set(from.subarray(row, row + w) as never, (j * p.width + r.i0) * stride);
+ }
}
}
diff --git a/sdk/src/terrain/index.ts b/sdk/src/terrain/index.ts
index 1606a2a07..532f76c81 100644
--- a/sdk/src/terrain/index.ts
+++ b/sdk/src/terrain/index.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
export {
- Terrain, TerrainExtent, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, NOISE_PROVIDER, type TerrainData, type TerrainStatus,
+ Terrain, TerrainExtent, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, NOISE_PROVIDER, type TerrainData, type TerrainStatus, type TerrainLoad,
} from './terrainPlugin';
export {
erodeHeightfield, erosionJob, heightfieldFromPixels, HeightmapFormat, proceduralHeightfield, sampleHeight, terrainNormal,
diff --git a/sdk/src/terrain/planetPlugin.ts b/sdk/src/terrain/planetPlugin.ts
index 623e60ef1..d7de136b7 100644
--- a/sdk/src/terrain/planetPlugin.ts
+++ b/sdk/src/terrain/planetPlugin.ts
@@ -24,7 +24,7 @@ import { CullMode, Material, MATERIAL_FORMAT_VERSION } from '../render/material'
import { BlendMode } from '../render/blend';
import { updateTextureSubregion } from '../runtime/runtimeAssets';
import { getResourceManager, withdrawTextureContent } from '../wasm/resourceManager';
-import { EditorView, editorViewEye } from '../camera/EditorView';
+import { EditorView, editorViewpoint } from '../camera/EditorView';
import { log } from '../util/logger';
import { renderOrigin } from '../render/renderOrigin';
import { bakesOf } from '../runtime/bakes';
@@ -321,14 +321,10 @@ export class PlanetPlugin implements Plugin {
}
}
- /** Where the eye is, in the planet's space: the editor's, while it looks at the scene in 3D, else the active camera's. */
private eye(app: App, t: TransformData): [number, number, number] | null {
if (app.hasResource(EditorView)) {
- const view = app.getResource(EditorView);
- if (view.active && view.perspective) {
- const e = editorViewEye(view);
- return [e.x - t.worldPosition.x, e.y - t.worldPosition.y, e.z - t.worldPosition.z];
- }
+ const e = editorViewpoint(app.getResource(EditorView));
+ if (e) return [e.x - t.worldPosition.x, e.y - t.worldPosition.y, e.z - t.worldPosition.z];
}
for (const entity of app.world.getEntitiesWithComponents([Camera, Transform])) {
if (!(app.world.get(entity, Camera) as CameraData).isActive) continue;
diff --git a/sdk/src/terrain/sculpt.ts b/sdk/src/terrain/sculpt.ts
index f2dbc3951..94910f2e7 100644
--- a/sdk/src/terrain/sculpt.ts
+++ b/sdk/src/terrain/sculpt.ts
@@ -37,7 +37,7 @@ export function brushWeight(d: number, radius: number, falloff: number): number
}
/** The texel span of a brush over a grid `width` by `height` laid across `sizeX` by `sizeZ`, or null when it reaches none. */
-function reach(width: number, height: number, sizeX: number, sizeZ: number, b: Brush): Dirty | null {
+export function reach(width: number, height: number, sizeX: number, sizeZ: number, b: Brush): Dirty | null {
const u0 = (b.x - b.radius) / sizeX + 0.5, u1 = (b.x + b.radius) / sizeX + 0.5;
const v0 = (b.z - b.radius) / sizeZ + 0.5, v1 = (b.z + b.radius) / sizeZ + 0.5;
const i0 = Math.max(Math.ceil(u0 * (width - 1)), 0), i1 = Math.min(Math.floor(u1 * (width - 1)), width - 1);
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
index 7542da289..bc3a8a8f2 100644
--- a/sdk/src/terrain/terrainPlugin.ts
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -32,7 +32,7 @@ import { BlendMode } from '../render/blend';
import { createTextureArrayFromPixels, updateTextureSubregion } from '../runtime/runtimeAssets';
import { getResourceManager, withdrawTextureContent } from '../wasm/resourceManager';
import { TextureContent } from '../wasm';
-import { EditorView, editorViewEye } from '../camera/EditorView';
+import { EditorView, editorViewpoint } from '../camera/EditorView';
import { log } from '../util/logger';
import { bakesOf } from '../runtime/bakes';
import type { Color, Entity } from '../types';
@@ -234,6 +234,8 @@ interface Built {
/** Where a terrain's ground stands: still being made, ready, or failed (with why). */
export interface TerrainStatus { state: 'loading' | 'ready' | 'failed'; reason?: string }
+export interface TerrainLoad { loading: number; cpuBytes: number }
+
/** Run-time access to the ground: how high it is anywhere, for putting things on it. */
export class Terrains {
/** @internal */ readonly built_ = new Map<Entity, Built>();
@@ -429,6 +431,18 @@ export class Terrains {
return { state: built.loading || !built.source ? 'loading' : 'ready' };
}
+ load(): TerrainLoad {
+ let loading = 0, cpuBytes = 0;
+ for (const built of this.built_.values()) {
+ if (built.loading) loading++;
+ const source = built.source instanceof ModifiedSource ? built.source.base : built.source;
+ if (!(source instanceof FieldSource)) continue;
+ const { a, b } = source.splats();
+ cpuBytes += source.field.data.byteLength + (a?.pixels.byteLength ?? 0) + (b?.pixels.byteLength ?? 0);
+ }
+ return { loading, cpuBytes };
+ }
+
/** @internal The modifiers laid over every terrain's ground, by id, in the order they were set. */
readonly modifiers_ = new Map<string, TerrainModifier>();
@@ -860,14 +874,10 @@ export class TerrainPlugin implements Plugin {
});
}
- /** Where the eye is, in the terrain's space: the active camera, or the editor's own eye while it looks at the scene in 3D. */
private eye(app: App, t: TransformData): [number, number, number] | null {
if (app.hasResource(EditorView)) {
- const view = app.getResource(EditorView);
- if (view.active && view.perspective) {
- const e = editorViewEye(view);
- return [e.x - t.worldPosition.x, e.y - t.worldPosition.y, e.z - t.worldPosition.z];
- }
+ const e = editorViewpoint(app.getResource(EditorView));
+ if (e) return [e.x - t.worldPosition.x, e.y - t.worldPosition.y, e.z - t.worldPosition.z];
}
for (const entity of app.world.getEntitiesWithComponents([Camera, Transform])) {
if (!(app.world.get(entity, Camera) as CameraData).isActive) continue;
diff --git a/sdk/tests/editor-viewpoint.test.ts b/sdk/tests/editor-viewpoint.test.ts
new file mode 100644
index 000000000..8b953dd07
--- /dev/null
+++ b/sdk/tests/editor-viewpoint.test.ts
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { AppContext, setDefaultContext } from '../src/ecs/context';
+import { createMockModule } from './mocks/wasm';
+import { describe, expect, it } from 'vitest';
+import { App } from '../src/app/app';
+import { DEFAULT_EDITOR_VIEW, EditorView, editorViewEye } from '../src/camera/EditorView';
+import { Camera, Transform } from '../src/ecs/component';
+import { streamingSourcesOf } from '../src/residency/chunks';
+import { WorldStreamingSource } from '../src/residency/components';
+
+const at = (x: number, y: number, z: number) => ({ position: { x, y, z }, worldPosition: { x, y, z } });
+
+function world(): App {
+ setDefaultContext(new AppContext());
+ const app = App.new(), module = createMockModule();
+ app.connectCpp(module.getRegistry(), module);
+ const source = app.world.spawn();
+ app.world.insert(source, Transform, at(500, 0, 500));
+ app.world.insert(source, WorldStreamingSource, { ...WorldStreamingSource._default });
+ const camera = app.world.spawn();
+ app.world.insert(camera, Transform, at(-900, 10, -900));
+ app.world.insert(camera, Camera, { isActive: true });
+ return app;
+}
+
+const ORBIT = { ...DEFAULT_EDITOR_VIEW, active: true, perspective: true, x: 2000, y: 40, z: -3000, distance: 300, yaw: 0.4, pitch: -0.5 };
+
+describe('what grows round the editor view', () => {
+ it('follows the 3D viewport past a streaming source in the scene', () => {
+ const app = world();
+ app.insertResource(EditorView, ORBIT);
+ const eye = editorViewEye(ORBIT);
+ expect(streamingSourcesOf(app)).toEqual([{ x: eye.x, y: eye.y, z: eye.z }]);
+ });
+
+ it('follows the 2D viewport to what it is looking at', () => {
+ const app = world();
+ app.insertResource(EditorView, { ...DEFAULT_EDITOR_VIEW, active: true, x: 700, y: -250 });
+ expect(streamingSourcesOf(app)).toEqual([{ x: 700, y: -250, z: 0 }]);
+ });
+
+ it('gives the running game its sources once the view stands down', () => {
+ const app = world();
+ app.insertResource(EditorView, { ...ORBIT, active: false });
+ expect(streamingSourcesOf(app)).toEqual([{ x: 500, y: 0, z: 500 }]);
+ });
+});
diff --git a/sdk/tests/terrain-sculpt.test.ts b/sdk/tests/terrain-sculpt.test.ts
index 807beedc9..85ec669fe 100644
--- a/sdk/tests/terrain-sculpt.test.ts
+++ b/sdk/tests/terrain-sculpt.test.ts
@@ -3,8 +3,9 @@
/**
* @file Brushes on an area's ground: what each one does to a field and to the splatmaps, and that a stroke can be taken back.
*/
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { GroundEdit } from '../src/terrain/groundEdit';
+import { Terrains } from '../src/terrain/terrainPlugin';
import { FieldSource, ModifiedSource, type Splat } from '../src/terrain/source';
import type { Heightfield } from '../src/terrain/heightfield';
import { SculptMode, brushWeight, encodeHeightmap, paintSplat, sculptField } from '../src/terrain/sculpt';
@@ -108,6 +109,18 @@ describe('paintSplat', () => {
});
});
+describe('Terrains.load', () => {
+ it('counts what is still loading and the ground and paint held in memory', () => {
+ const terrains = new Terrains();
+ const field = flat(65);
+ const source = new FieldSource(field, data, { width: 8, height: 8, pixels: new Uint8Array(256) }, null);
+ const wrapped = new ModifiedSource(source, () => [], { x: 0, y: 0, z: 0 }, 1);
+ terrains.built_.set(1 as never, { loading: false, source: wrapped } as never);
+ terrains.built_.set(2 as never, { loading: true, source: null } as never);
+ expect(terrains.load()).toEqual({ loading: 1, cpuBytes: field.data.byteLength + 256 });
+ });
+});
+
describe('GroundEdit', () => {
const make = (): { edit: GroundEdit; field: Heightfield; remade: number[][] } => {
const field = flat(65);
@@ -158,6 +171,47 @@ describe('GroundEdit', () => {
expect(a.pixels[mid + 3]).toBe(0);
});
+ it('copies nothing of the ground to begin a stroke', () => {
+ const { edit, field } = make();
+ const slice = vi.spyOn(field.data, 'slice');
+ edit.begin();
+ edit.sculpt(SculptMode.Raise, 0, 0, 5, 0.5, 5);
+ edit.end();
+ expect(slice).not.toHaveBeenCalled();
+ });
+
+ it('keeps what a diagonal stroke touched, not the square round it', () => {
+ const field = flat(513);
+ const source = new FieldSource(field, data, null, null);
+ const modified = new ModifiedSource(source, () => [], { x: 0, y: 0, z: 0 }, 1);
+ const edit = new GroundEdit({ remake: () => {} }, source, modified, 100, 100);
+ edit.begin();
+ for (let t = -45; t <= 45; t += 2) edit.sculpt(SculptMode.Raise, t, t, 2, 0.5, 5);
+ const patch = edit.end()!;
+ const { rect, tiles } = patch.heights!;
+ const kept = tiles.reduce((n, tile) => n + tile.before.length, 0);
+ expect(kept).toBeLessThan((rect.i1 - rect.i0 + 1) * (rect.j1 - rect.j0 + 1) / 3);
+ const peak = Float32Array.from(field.data);
+ edit.apply(patch, 'before');
+ expect(field.data.every((v) => v === 0.5)).toBe(true);
+ edit.apply(patch, 'after');
+ expect(field.data).toEqual(peak);
+ });
+
+ it('takes a first paint back to the ground it was laid over', () => {
+ const { edit } = make();
+ const ground = (() => {
+ const { edit: untouched } = make();
+ untouched.paint(0, 0, 0, 0.001, 0, 0);
+ return Uint8Array.from(untouched.splatmapPixels().a!.pixels);
+ })();
+ edit.begin();
+ edit.paint(2, 0, 0, 10, 0.5, 1);
+ const patch = edit.end()!;
+ edit.apply(patch, 'before');
+ expect(edit.splatmapPixels().a!.pixels).toEqual(ground);
+ });
+
it('encodes heights as sixteen bits across red and green', () => {
const f = flat(2, 0);
f.data[1] = 1; f.data[2] = 0.5;