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(worldgen): a plant's far version may be its cheaper mesh, thinned by farKeep, so ground cover has a far level of detail

yhh17d951aede8a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c45c0bc0e..2269567ea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,7 @@ published separately; it ships inside the editor.
### Added
- **Sparkle on the water.** The Water shader reads two tiled normal maps that scroll over the surface (`u_detailMap`, `u_detailTile0/1`, `u_detailStrength0/1`, `u_detailFlow0/1`), packed into the one texture a material has room for, so the sun's glints on small slopes come from lit specular response and not a white texture; a material that sets no strength is unchanged.
-- **A generated world's plants.** A recipe's members can name a **plant** in the rules' `plants` (a `.esworld` file holds them): several parts (a trunk and its crown), a cheaper mesh and a far version, the colourings the art gives it, how far it is sunk and its `unit` (100 for metres in a world of centimetres). The world is laid out from the rules as the eye moves, the plants grown a cell at a time by the machinery a `PlacedFoliage` uses: a chunk stands at once and fills in over the frames after it inside the frame's budget, a cheaper mesh stands in at the middle distance, and a tree's crossed cards, laid out as a layer of their own, stand for it far off. The terrain's paint is a field each of its layers (`paint.grass`), a rules file names noise fields of its own, and fields are worked out only where a condition reads them. The Terrain & Water example's woods, shrubs, stones, grass, flowers and reeds are laid out this way from `assets/worlds/plants.esworld`.
+- **A generated world's plants.** A recipe's members can name a **plant** in the rules' `plants` (a `.esworld` file holds them): several parts (a trunk and its crown), a cheaper mesh and a far version, the colourings the art gives it, how far it is sunk and its `unit` (100 for metres in a world of centimetres). The world is laid out from the rules as the eye moves, the plants grown a cell at a time by the machinery a `PlacedFoliage` uses: a chunk stands at once and fills in over the frames after it inside the frame's budget, a cheaper mesh stands in at the middle distance, and a tree's crossed cards, laid out as a layer of their own, stand for it far off. A plant with no cards of its own may use its cheaper mesh as its far version and set `farKeep`, the share of its plants that version draws, so ground cover far off costs a share of what it does near. The terrain's paint is a field each of its layers (`paint.grass`), a rules file names noise fields of its own, and fields are worked out only where a condition reads them. The Terrain & Water example's woods, shrubs, stones, grass, flowers and reeds are laid out this way from `assets/worlds/plants.esworld`.
- **Each terrain layer says how it meets the others.** A `.esterrainlayer` may name a `heightBlend`: 0 blends by the paint alone (grass into sand), 1 by the layers' heights (stones standing through grass), weighted by how much of each layer is there; absent, it is the material's `u_heightBlend`. The editor's layer panel sets it.
- **Placed plants.** `PlacedFoliage` keeps every plant an artist placed by hand as data in one entity, a table of kinds and six numbers a plant, instead of an entity, a renderer and a draw each. The engine cuts the area into cells and grows only those round the eye, each as one mesh for every part of every kind in it, a few milliseconds a piece of the frame's budget so a cell fills in over the frames after it appears, and lets them go past their distance. A kind keeps the mesh as made (normal map, second uv, vertex colour), has a cheaper mesh for the middle distance and a far version, a tree's crossed cards, drawn out to a far distance: a hierarchical level of detail that makes the whole area stand at once. The Terrain & Water example now grows its woods, shrubs, stones, grass, flowers and reeds this way from the lakewood plant set, and its grass and sand are that set's terrain layers.
- **Water zones.** Oceans, lakes and rivers are now drawn as one surface. A `WaterBody` says what water is where (its form, outline or Spline, shore width, current and how high its waves stand), and a new `WaterZone` bakes every body over its region into one field: the surface's height, the distance to the shore, the waves' height, the current and the depth over the terrain. One mesh of rings that follows the camera reads it, so a river runs into a lake or the sea at one height with its banks running on into the shore, its current fades into the still water, and no shore foams across its mouth; a lake or a river over the sea is the lake's, not the sea's, and the sea's waves calm and foam where it shallows over the terrain. The zone holds what the bodies share: the material, the waves' length, speed and heading, the mesh's detail and the ripples. A scene without one gets a zone over its lakes and rivers, and the ocean goes on past it. `Waters.sample` reads the same field, so what floats or looks out from under the water meets the surface that is drawn. In the editor the zone's region is outlined in the viewport.
diff --git a/docs/astro/src/content/docs/graphics/foliage.mdx b/docs/astro/src/content/docs/graphics/foliage.mdx
index 2f1e6a0c0..6055eb6c2 100644
--- a/docs/astro/src/content/docs/graphics/foliage.mdx
+++ b/docs/astro/src/content/docs/graphics/foliage.mdx
@@ -64,6 +64,10 @@ the artist made (a normal map, a second uv, a vertex colour); nothing is painted
The far version is the hierarchical level of detail: a tree's crossed cards, baked to an atlas of their own, merged a cell at a time, shown where the eye is past
what the kind draws as itself. It is cheap enough that the whole area stands at once. A kind with no far version is not drawn past `drawDistance`.
+A kind with no cards of its own can use its cheaper mesh as its far version and set `farKeep`, the share of its plants the far version draws (above 0 to 1):
+every n-th is kept, n the nearest whole number to 1 / `farKeep`, each grown by the square root of n (at most twofold) so the ground they cover is what it was.
+Ground cover far off then costs a share of what it does near, and the ground's own texture carries the rest.
+
Plants stand upright and are scaled uniformly; the records carry no tilt. The paths in `kinds` are the project's, listed so a package carries them.
## In a package
diff --git a/docs/astro/src/content/docs/world/generation.mdx b/docs/astro/src/content/docs/world/generation.mdx
index 45ed2dadb..ea0db490e 100644
--- a/docs/astro/src/content/docs/world/generation.mdx
+++ b/docs/astro/src/content/docs/world/generation.mdx
@@ -99,6 +99,7 @@ A member names a mesh and a material, or a **plant**: an entry in the rules' `pl
| Field | What it is |
|---|---|
| `tints`, `tintScale` | The colourings the art gives it (linear multipliers on its colour), and how many world units a stand is across: a place takes one of them by slow noise, so a wood has warm and cool stands and no speckle. |
+| `farKeep` | The share of its plants the far version draws (above 0 to 1; default 1): the others are left out and the ones kept grown to make up their cover. A plant with no cards of its own may use its cheaper mesh as its `far` and thin it this way. |
| `sink` | How far it is sunk into the ground, in world units (a stone's buried underside). |
| `unit` | World units to a unit of its mesh: 100 for plants modelled in metres in a world of centimetres. A recipe's `scale` is then a size relative to the model. |
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
index 701303a59..14b182239 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
@@ -47,6 +47,8 @@ description: 一个 Foliage 组件,把草或网格散布到一片区域或地形
远景版本就是层级细节(HLOD):树的交叉卡片烘到自己的图集上,按格子合并,镜头比该种类自身的绘制距离更远时显示。它便宜到整个区域可以一次全部长出。没有远景版本的种类,超过 `drawDistance` 就不画。
+没有自己卡片的种类可以拿更省的网格当远景版本,并设置 `farKeep`:远景版本画多少比例的植物(大于 0 到 1)。每 n 棵保留一棵,n 取最接近 1 / `farKeep` 的整数,保留下来的放大到原来的 n 的平方根倍(最多两倍),覆盖的地面面积不变。这样远处的地被只花近处一个比例的代价,其余由地面自己的纹理承担。
+
植物是直立、等比缩放的,记录里没有倾斜。`kinds` 里的路径是项目路径,列出来是为了让包带上它们。
## 在包里
diff --git a/docs/astro/src/content/docs/zh-cn/world/generation.mdx b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
index 20458cbc8..de634951b 100644
--- a/docs/astro/src/content/docs/zh-cn/world/generation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
@@ -76,6 +76,7 @@ registerWorldRules({
| 字段 | 含义 |
|---|---|
| `tints`、`tintScale` | 美术给的几种色调(乘在颜色上的线性系数),以及一片林子多宽(世界单位):一个地方按慢噪声取其中一种,所以林子里有偏暖和偏冷的片,不会是花点。 |
+| `farKeep` | 远景版本画多少比例的植物(大于 0 到 1,默认 1):其余的不画,保留的放大来补足覆盖。没有自己卡片的植物可以拿更省的网格作 `far`,并用它来稀疏化。 |
| `sink` | 下沉进地面多深,世界单位(石头埋在土里的底面)。 |
| `unit` | 一个网格单位对应多少世界单位:按米建模的植物放在厘米世界里就是 100。配方的 `scale` 这时是相对模型的大小。 |
diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.md
index f7c658efa..8dac8324d 100644
--- a/sdk/etc/foliage.api.md
+++ b/sdk/etc/foliage.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/foliage
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 30 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 31 experimental · 0 deprecated
## BladeParams — interface @experimental
```
@@ -129,6 +129,7 @@ ResourceDef<PlacedFoliageField>
drawDistance: number
far: PlacedPart[]
farDistance: number
+farKeep: number | undefined
lodDistance: number
parts: PlacedPart[]
```
@@ -180,6 +181,7 @@ ResourceDef<PlantGrowth>
drawDistance: number
far: PlacedPart[]
farDistance: number
+farKeep: number | undefined
lodDistance: number
parts: PlacedPart[]
sink: number | undefined
@@ -248,3 +250,8 @@ Plugin
(p: ScatterParams, ground: Ground): Plant[]
```
+## thinPlants — function @experimental
+```
+(plants: readonly Plant[], keep: number): readonly Plant[]
+```
+
diff --git a/sdk/src/foliage/builder.ts b/sdk/src/foliage/builder.ts
index b6c6e0632..2b91e5482 100644
--- a/sdk/src/foliage/builder.ts
+++ b/sdk/src/foliage/builder.ts
@@ -293,6 +293,19 @@ export function buildPlacedMesh(source: MeshData, plants: readonly Plant[]): Mes
return { channels: source.channels, vertexStride: stride, vertexCount: count * plants.length, vertices, indices, aabbMin: min, aabbMax: max };
}
+/**
+ * The plants a far version draws, when it draws a share `keep` of them (above 0 to 1): every n-th, n the nearest whole number to 1 / keep, each grown by the
+ * square root of n (to a most of twice) so the ground they cover is what it was. The same plants every time: what is kept is a matter of order.
+ */
+export function thinPlants(plants: readonly Plant[], keep: number): readonly Plant[] {
+ const n = Math.max(1, Math.round(1 / Math.min(Math.max(keep, 1e-3), 1)));
+ if (n === 1) return plants;
+ const grow = Math.min(Math.sqrt(n), 2);
+ const out: Plant[] = [];
+ for (let i = 0; i < plants.length; i += n) out.push({ ...plants[i]!, scale: plants[i]!.scale * grow });
+ return out;
+}
+
/** The turn that takes up (0, 1, 0) to `n` the shortest way, applied to a vector in place; null when `n` is up. */
function leanTo(n: readonly [number, number, number]): ((v: number[]) => void) | null {
const len = Math.hypot(n[0], n[1], n[2]) || 1;
diff --git a/sdk/src/foliage/index.ts b/sdk/src/foliage/index.ts
index a4fc6f388..107abfb7b 100644
--- a/sdk/src/foliage/index.ts
+++ b/sdk/src/foliage/index.ts
@@ -10,7 +10,7 @@ export {
export { PlantGrowth, PlantGrowthRes, plantGrowthOf } from './plantGrowth';
export { PLACED_STRIDE, type PlacedKind, type PlacedPart, type PlantKind } from './plantKind';
export {
- scatterCell, buildGrassMesh, buildInstancedMesh, buildPlacedMesh, buildBillboardMesh, rng,
+ scatterCell, buildGrassMesh, buildInstancedMesh, buildPlacedMesh, thinPlants, buildBillboardMesh, rng,
type Plant, type Ground, type ScatterParams, type BladeParams, type CardRect,
} from './builder';
diff --git a/sdk/src/foliage/plantGrowth.ts b/sdk/src/foliage/plantGrowth.ts
index 6f6d5ad05..4d966147c 100644
--- a/sdk/src/foliage/plantGrowth.ts
+++ b/sdk/src/foliage/plantGrowth.ts
@@ -26,7 +26,7 @@ import type { MeshData } from '../asset/meshFormat';
import { log } from '../util/logger';
import { bakesOf } from '../runtime/bakes';
import type { Entity } from '../types';
-import { buildPlacedMesh, type Plant } from './builder';
+import { buildPlacedMesh, thinPlants, type Plant } from './builder';
import type { PlacedKind, PlacedPart } from './plantKind';
/** A part with what it needs in hand: its geometry read, its handles made. */
@@ -159,8 +159,9 @@ export class PlantGrowth {
for (const [kindIndex, plants] of byKind) {
const parts = ready.far[kindIndex];
if (!parts || parts.length === 0) continue;
+ const kept = thinPlants(plants, kinds[kindIndex]?.farKeep ?? 1);
for (const r of parts) {
- const handle = assets.createMesh(buildPlacedMesh(r.source, plants));
+ const handle = assets.createMesh(buildPlacedMesh(r.source, kept));
if (handle === 0) continue;
cell.handles.push(handle);
const e = world.spawn(`far ${kindIndex}`);
diff --git a/sdk/src/foliage/plantKind.ts b/sdk/src/foliage/plantKind.ts
index 5ae62f9e3..2a7849f04 100644
--- a/sdk/src/foliage/plantKind.ts
+++ b/sdk/src/foliage/plantKind.ts
@@ -32,6 +32,12 @@ export interface PlacedKind {
*/
far: PlacedPart[];
farDistance: number;
+ /**
+ * The share of the plants its far version draws, above 0 to 1 (default 1): the others are left out and the ones kept grown to make up their cover, so
+ * ground cover far off costs a share of what it does near, and the ground's own texture carries the rest. A kind with no cards of its own may use its
+ * cheaper mesh as its far version, thinned.
+ */
+ farKeep?: number;
}
/**
diff --git a/sdk/src/worldgen/plants.ts b/sdk/src/worldgen/plants.ts
index 1af306626..f78f9ed9c 100644
--- a/sdk/src/worldgen/plants.ts
+++ b/sdk/src/worldgen/plants.ts
@@ -32,7 +32,7 @@ export function expandPlants(plants: Readonly<Record<string, PlantKind>>): Plant
const first = kinds.length;
for (const t of tints) {
const tint = (part: PlacedKind['parts'][number]): PlacedKind['parts'][number] => ({ ...part, tint: [part.tint[0] * t[0], part.tint[1] * t[1], part.tint[2] * t[2], part.tint[3]] });
- kinds.push({ parts: p.parts.map(tint), lodDistance: p.lodDistance, drawDistance: p.drawDistance, far: p.far.map(tint), farDistance: p.farDistance });
+ kinds.push({ parts: p.parts.map(tint), lodDistance: p.lodDistance, drawDistance: p.drawDistance, far: p.far.map(tint), farDistance: p.farDistance, ...(p.farKeep === undefined ? {} : { farKeep: p.farKeep }) });
}
slots.set(name, { first, count: tints.length, scale: p.tintScale ?? 1300, seed: hashString(name), sink: p.sink ?? 0, unit: p.unit ?? 1 });
reach = Math.max(reach, p.drawDistance, p.far.length > 0 ? p.farDistance : 0);
diff --git a/sdk/src/worldgen/rulesAsset.ts b/sdk/src/worldgen/rulesAsset.ts
index 098148ff7..aad979839 100644
--- a/sdk/src/worldgen/rulesAsset.ts
+++ b/sdk/src/worldgen/rulesAsset.ts
@@ -86,6 +86,7 @@ function plant(v: unknown, where: string): PlantKind {
parts: (o.parts as unknown[]).map((p, i) => part(p, `${where}.parts[${i}]`)),
lodDistance: num(o.lodDistance ?? 0, `${where}.lodDistance`, 0), drawDistance: num(o.drawDistance, `${where}.drawDistance`, 0),
far, farDistance: far.length > 0 ? num(o.farDistance, `${where}.farDistance`, 0) : 0,
+ ...(o.farKeep === undefined ? {} : { farKeep: num(o.farKeep, `${where}.farKeep`, 1e-3) }),
...(tints ? { tints, tintScale: num(o.tintScale ?? 1300, `${where}.tintScale`, 1e-6) } : {}),
...(o.sink === undefined ? {} : { sink: num(o.sink, `${where}.sink`) }),
...(o.unit === undefined ? {} : { unit: num(o.unit, `${where}.unit`, 1e-9) }),
diff --git a/sdk/tests/foliage-builder.test.ts b/sdk/tests/foliage-builder.test.ts
index 8abe99144..b7330b0a6 100644
--- a/sdk/tests/foliage-builder.test.ts
+++ b/sdk/tests/foliage-builder.test.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../src/asset/meshFormat';
-import { buildBillboardMesh, buildGrassMesh, buildInstancedMesh, buildPlacedMesh, rng, scatterCell, type Ground, type Plant } from '../src/foliage/builder';
+import { buildBillboardMesh, buildGrassMesh, buildInstancedMesh, buildPlacedMesh, thinPlants, rng, scatterCell, type Ground, type Plant } from '../src/foliage/builder';
const flat: Ground = () => ({ y: 2, up: 1 });
const params = {
@@ -190,3 +190,28 @@ describe('placed meshes', () => {
expect(none.indices.length).toBe(0);
});
});
+
+describe('thinning plants for a far version', () => {
+ const plants: Plant[] = Array.from({ length: 12 }, (_, i) => ({ x: i, y: 0, z: 0, yaw: 0, scale: 1, phase: 0, shade: 1 }));
+
+ it('keeps every plant when it keeps them all', () => {
+ expect(thinPlants(plants, 1)).toBe(plants);
+ expect(thinPlants(plants, 2)).toBe(plants);
+ });
+
+ it('keeps every n-th for a share of 1 / n, grown to cover what the others did', () => {
+ const quarter = thinPlants(plants, 0.25);
+ expect(quarter.map((p) => p.x)).toEqual([0, 4, 8]);
+ expect(quarter[0]!.scale).toBeCloseTo(2);
+ const third = thinPlants(plants, 1 / 3);
+ expect(third.map((p) => p.x)).toEqual([0, 3, 6, 9]);
+ expect(third[0]!.scale).toBeCloseTo(Math.sqrt(3));
+ });
+
+ it('is the same plants every time, grows them at most twofold, and leaves the ones given alone', () => {
+ expect(thinPlants(plants, 0.1).map((p) => p.x)).toEqual(thinPlants(plants, 0.1).map((p) => p.x));
+ expect(thinPlants(plants, 0.05)[0]!.scale).toBe(2);
+ expect(plants[0]!.scale).toBe(1);
+ });
+});
+
diff --git a/sdk/tests/worldgen-plants.test.ts b/sdk/tests/worldgen-plants.test.ts
index 97a7263f4..1134b8a55 100644
--- a/sdk/tests/worldgen-plants.test.ts
+++ b/sdk/tests/worldgen-plants.test.ts
@@ -10,7 +10,7 @@ import type { PlantKind } from '../src/foliage/plantKind';
const part = (mesh: string, tint: [number, number, number, number] = [1, 1, 1, 1]) => ({ mesh, lod1Mesh: '', material: '', texture: '', tint, opaque: true });
const plants: Record<string, PlantKind> = {
oak: { parts: [part('trunk', [0.5, 0.5, 0.5, 1]), part('crown')], lodDistance: 6000, drawDistance: 16000, far: [part('cards')], farDistance: 200000,
- tints: [[0.9, 1, 0.9], [1, 1, 1], [1.1, 1, 0.8]], tintScale: 1000, sink: 8, unit: 100 },
+ tints: [[0.9, 1, 0.9], [1, 1, 1], [1.1, 1, 0.8]], tintScale: 1000, sink: 8, unit: 100, farKeep: 0.5 },
stone: { parts: [part('rock')], lodDistance: 0, drawDistance: 30000, far: [], farDistance: 0 },
};
@@ -41,6 +41,11 @@ describe('expanding plants into kinds', () => {
expect(set.kindAt('nothing', 5, 5)).toBe(-1);
});
+ it('carries how much of a plant its far version draws', () => {
+ expect(set.kinds[0]!.farKeep).toBe(0.5);
+ expect(set.kinds[3]!.farKeep).toBeUndefined();
+ });
+
it('knows how far a plant is sunk and how far the furthest of them is wanted', () => {
expect(set.sinkOf('oak')).toBe(8);
expect(set.sinkOf('stone')).toBe(0);
diff --git a/sdk/tests/worldgen-rules-asset.test.ts b/sdk/tests/worldgen-rules-asset.test.ts
index fbde432d4..ccad2c1ad 100644
--- a/sdk/tests/worldgen-rules-asset.test.ts
+++ b/sdk/tests/worldgen-rules-asset.test.ts
@@ -44,7 +44,7 @@ describe('plants in a world rules file', () => {
const r = JSON.parse(JSON.stringify(good));
r.plants = {
oak: { parts: [{ mesh: 'assets/oak_trunk.esmesh', material: 'assets/bark.esmaterial' }, { mesh: 'assets/oak_crown.esmesh', lod1Mesh: 'assets/oak_crown1.esmesh', opaque: true }],
- lodDistance: 6000, drawDistance: 16000, far: [{ mesh: 'assets/oak_cards.esmesh' }], farDistance: 200000, tints: [[0.9, 1, 0.9], [1, 1, 1]], sink: 8 },
+ lodDistance: 6000, drawDistance: 16000, far: [{ mesh: 'assets/oak_cards.esmesh' }], farDistance: 200000, farKeep: 0.25, tints: [[0.9, 1, 0.9], [1, 1, 1]], sink: 8 },
};
r.recipes[0].anchor = { id: 'oak', plant: 'oak', footprint: 8 };
delete r.recipes[0].anchor.mesh;
@@ -61,6 +61,7 @@ describe('plants in a world rules file', () => {
expect(oak.far[0]!.mesh).toBe('assets/oak_cards.esmesh');
expect(oak.tints).toHaveLength(2);
expect(oak.sink).toBe(8);
+ expect(oak.farKeep).toBe(0.25);
});
it('is refused with where it went wrong', () => {
@@ -69,6 +70,7 @@ describe('plants in a world rules file', () => {
expect(bad((r) => { r.plants.oak.parts = []; })).toThrow(/plants\.oak\.parts/);
expect(bad((r) => { r.plants.oak.parts[0].mesh = ''; })).toThrow(/plants\.oak\.parts\[0\]\.mesh/);
expect(bad((r) => { r.plants.oak.tints = [[1, 1]]; })).toThrow(/plants\.oak\.tints\[0\]/);
+ expect(bad((r) => { r.plants.oak.farKeep = 0; })).toThrow(/plants\.oak\.farKeep/);
expect(bad((r) => { delete r.recipes[0].anchor.plant; })).toThrow(/mesh path, or a plant/);
});
});