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(worldgen): the far versions of a world's plants are laid out in cells as wide as their shortest span allows, so ground cover far off costs far fewer draws
yhhab39b99d0c1b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2269567ea..0bed16011 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. 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`.+- **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 far versions are laid out in cells as wide as the shortest distance they are shown over allows, which took the Terrain & Water example's draws from about 1,800 to about 1,100. 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/world/generation.mdx b/docs/astro/src/content/docs/world/generation.mdxindex ea0db490e..a2295658e 100644--- a/docs/astro/src/content/docs/world/generation.mdx+++ b/docs/astro/src/content/docs/world/generation.mdx@@ -99,7 +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. |+| `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. The far versions are laid out in cells as wide as the shortest distance any of them is shown over allows (up to eight chunks), so ground cover seen from far off is a few draws a cell and not a few a chunk. || `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/world/generation.mdx b/docs/astro/src/content/docs/zh-cn/world/generation.mdxindex de634951b..ae97f7226 100644--- a/docs/astro/src/content/docs/zh-cn/world/generation.mdx+++ b/docs/astro/src/content/docs/zh-cn/world/generation.mdx@@ -76,7 +76,7 @@ registerWorldRules({| 字段 | 含义 ||---|---|| `tints`、`tintScale` | 美术给的几种色调(乘在颜色上的线性系数),以及一片林子多宽(世界单位):一个地方按慢噪声取其中一种,所以林子里有偏暖和偏冷的片,不会是花点。 |-| `farKeep` | 远景版本画多少比例的植物(大于 0 到 1,默认 1):其余的不画,保留的放大来补足覆盖。没有自己卡片的植物可以拿更省的网格作 `far`,并用它来稀疏化。 |+| `farKeep` | 远景版本画多少比例的植物(大于 0 到 1,默认 1):其余的不画,保留的放大来补足覆盖。没有自己卡片的植物可以拿更省的网格作 `far`,并用它来稀疏化。远景版本按格子铺设,格子的宽度由所有远景版本中最短的显示距离决定(最多八个区块),所以远处的地被植物是每格几次绘制,而不是每个区块几次。 || `sink` | 下沉进地面多深,世界单位(石头埋在土里的底面)。 || `unit` | 一个网格单位对应多少世界单位:按米建模的植物放在厘米世界里就是 100。配方的 `scale` 这时是相对模型的大小。 |diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.mdindex 8dac8324d..d777fa0ee 100644--- a/sdk/etc/foliage.api.md+++ b/sdk/etc/foliage.api.md@@ -160,7 +160,7 @@ z: number```app_: App | nullgrowCell: (app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>) => void-growFar: (app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, at: { x: number; z: number; }) => void+growFar: (app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, at: { x: number; z: number; half?: number; }) => voidmade: numberpending: numberqueue: { cell: GrownCell; run: () => void; }[]diff --git a/sdk/src/foliage/plantGrowth.ts b/sdk/src/foliage/plantGrowth.tsindex 4d966147c..ea8e99155 100644--- a/sdk/src/foliage/plantGrowth.ts+++ b/sdk/src/foliage/plantGrowth.ts@@ -45,6 +45,8 @@ interface FarCell {/** Where the cell is, in the world's x and z. */x: number;z: number;+ /** Half the cell's side: how far from its centre it reaches. */+ half: number;owner: Entity;kinds: readonly PlacedKind[];children: { entity: Entity; kind: number; shown: boolean }[];@@ -149,9 +151,9 @@ export class PlantGrowth {/*** Grows the far version of `cell`: each kind with one, its plants as one mesh a far part, hidden until the eye is far enough (`kind.drawDistance`- * to `kind.farDistance` from the cell's centre, at world x and z `at`). Cheap enough (a tree is two cards) to be made at once.+ * to `kind.farDistance` from the cell, at world x and z `at`, reaching `half` each way). Cheap enough (a tree is two cards) to be made at once.*/- growFar(app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, at: { x: number; z: number }): void {+ growFar(app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, at: { x: number; z: number; half?: number }): void {const world = app.world, entity = cell.entity;if (entity === null) return;const assets = app.getResource(Assets);@@ -175,7 +177,7 @@ export class PlantGrowth {children.push({ entity: e, kind: kindIndex, shown: false });}}- if (children.length > 0) this.far_.add({ x: at.x, z: at.z, owner: entity, kinds, children });+ if (children.length > 0) this.far_.add({ x: at.x, z: at.z, half: at.half ?? 0, owner: entity, kinds, children });}/** Lets a cell go: what it made is despawned and given back, and what it had not yet made is left unmade. */@@ -201,11 +203,14 @@ export class PlantGrowth {}if (!eye) return;for (const cell of this.far_) {- const d = Math.hypot(cell.x - eye.x, cell.z - eye.z);+ // A cell that spans a good part of the distances shows wherever any of it is past what its kind draws and within how far it goes.+ const dx = Math.abs(cell.x - eye.x), dz = Math.abs(cell.z - eye.z);+ const nearest = Math.hypot(Math.max(dx - cell.half, 0), Math.max(dz - cell.half, 0));+ const furthest = Math.hypot(dx + cell.half, dz + cell.half);for (const child of cell.children) {const kind = cell.kinds[child.kind];if (!kind) continue;- const show = d > kind.drawDistance && d < kind.farDistance;+ const show = furthest > kind.drawDistance && nearest < kind.farDistance;if (show === child.shown || !world.valid(child.entity)) continue;child.shown = show;world.insert(child.entity, MeshRenderer, { ...(world.get(child.entity, MeshRenderer) as MeshRendererData), enabled: show });diff --git a/sdk/src/worldgen/plants.ts b/sdk/src/worldgen/plants.tsindex f78f9ed9c..737da1a56 100644--- a/sdk/src/worldgen/plants.ts+++ b/sdk/src/worldgen/plants.ts@@ -21,12 +21,14 @@ export interface PlantSet {unitOf(name: string): number;/** The furthest any kind is wanted: where the far versions end. */reach: number;+ /** The least distance a far version is shown over (from what its kind draws to how far it goes): a far cell is as wide as that allows. 0 where none has one. */+ span: number;}export function expandPlants(plants: Readonly<Record<string, PlantKind>>): PlantSet {const kinds: PlacedKind[] = [];const slots = new Map<string, { first: number; count: number; scale: number; seed: number; sink: number; unit: number }>();- let reach = 0;+ let reach = 0, span = 0;for (const [name, p] of Object.entries(plants)) {const tints = p.tints && p.tints.length > 0 ? p.tints : [[1, 1, 1] as [number, number, number]];const first = kinds.length;@@ -36,9 +38,10 @@ export function expandPlants(plants: Readonly<Record<string, PlantKind>>): Plant}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);+ if (p.far.length > 0 && p.farDistance > p.drawDistance) span = span > 0 ? Math.min(span, p.farDistance - p.drawDistance) : p.farDistance - p.drawDistance;}return {- kinds, reach,+ kinds, reach, span,kindAt(name, x, z) {const s = slots.get(name);if (!s) return -1;diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.tsindex ef9fc49ba..d99aa0409 100644--- a/sdk/src/worldgen/worldgenPlugin.ts+++ b/sdk/src/worldgen/worldgenPlugin.ts@@ -162,6 +162,8 @@ interface PlacedChunk {/** The plants of the rules' `plants` in it, by kind, standing relative to `at` (the chunk's centre), and what grew them once published. */planted: Map<number, Plant[]> | null;at: [number, number, number];+ /** The chunk's side. */+ side: number;grown: GrownCell | null;/** Made for the far layer: only the far versions of its plants, which are shown from past what their kinds draw as themselves. */far: boolean;@@ -517,16 +519,22 @@ export class WorldGenPlugin implements Plugin {// where the plants themselves are only grown near the eye. They are shown from past what their kinds draw as themselves.const farId = layerIdOf(entity, `${layer.id}:far`);if (!rendering || !built.plants || built.plants.reach <= layer.drawDistance) { chunks.remove(farId); continue; }+ // A far cell is as many chunks wide as the shortest span a far version is shown over allows: the far versions are one draw a kind a cell, and a ring+ // of ground cover a few chunks wide would otherwise be thousands of them.+ const farSide = Math.min(Math.max(Math.floor(built.plants.span / size), 1), 8);+ const fsize = size * farSide;+ const fextent: [number, number, number, number] | null = bounds+ ? [Math.floor(bounds[0] / fsize), Math.floor(bounds[1] / fsize), Math.ceil(bounds[2] / fsize), Math.ceil(bounds[3] / fsize)] : null;chunks.set<PlacedChunk>(farId, {label: 'Laying out the far plants',- originX: 0, originZ: 0, sizeX: size, sizeZ: size, extent,- loadRadius: built.plants.reach, unloadRadius: built.plants.reach + size,+ originX: 0, originZ: 0, sizeX: fsize, sizeZ: fsize, extent: fextent,+ loadRadius: built.plants.reach, unloadRadius: built.plants.reach + fsize,generation: `${built.signature}:${ground}`,make: (cx, cz) => {- const x0 = cx * size, z0 = cz * size;- if (waiting || (terrains && ![[x0, z0], [x0 + size, z0], [x0, z0 + size], [x0 + size, z0 + size]].every(([x, z]) => terrains.groundKnownAt(x!, z!)))) return null;+ const x0 = cx * fsize, z0 = cz * fsize;+ if (waiting || (terrains && ![[x0, z0], [x0 + fsize, z0], [x0, z0 + fsize], [x0 + fsize, z0 + fsize]].every(([x, z]) => terrains.groundKnownAt(x!, z!)))) return null;if (!built.plantsReady) return null;- return this.chunk(app, plan, diffs, layer, x0, z0, size, rendering, built.plants, true);+ return this.chunk(app, plan, diffs, layer, x0, z0, fsize, rendering, built.plants, true);},publish: (_cx, _cz, value) => this.place(app, gens, entity, value),release: (_cx, _cz, value) => this.unplace(app, gens, value),@@ -547,7 +555,7 @@ export class WorldGenPlugin implements Plugin {const decor = rendering && !far ? placements.filter((p) => p.interactive === null && p.mesh) : [];const meshes = [...new Set(decor.map((p) => p.mesh))];const finish = (): PlacedChunk => {- const out: PlacedChunk = { decor: [], objects, planted: null, at: [x0 + size / 2, 0, z0 + size / 2], grown: null, far, entities: [], meshes: [] };+ const out: PlacedChunk = { decor: [], objects, planted: null, at: [x0 + size / 2, 0, z0 + size / 2], side: size, grown: null, far, entities: [], meshes: [] };// The plants: each at its kind (its colouring there), relative to the chunk's centre, sunk by what its kind says.if (plants && rendering) {const by = new Map<number, Plant[]>();@@ -620,7 +628,7 @@ export class WorldGenPlugin implements Plugin {chunk.entities.push(e);chunk.grown = { entity: e, handles: [], dead: false };const growth = plantGrowthOf(app);- if (chunk.far) growth.growFar(app, chunk.grown, built.plants.kinds, built.plantsReady, chunk.planted, { x: chunk.at[0], z: chunk.at[2] });+ if (chunk.far) growth.growFar(app, chunk.grown, built.plants.kinds, built.plantsReady, chunk.planted, { x: chunk.at[0], z: chunk.at[2], half: chunk.side / 2 });else growth.growCell(app, chunk.grown, built.plants.kinds, built.plantsReady, chunk.planted);}for (const d of chunk.decor) {diff --git a/sdk/tests/worldgen-plants.test.ts b/sdk/tests/worldgen-plants.test.tsindex 1134b8a55..7ed77df3f 100644--- a/sdk/tests/worldgen-plants.test.ts+++ b/sdk/tests/worldgen-plants.test.ts@@ -53,4 +53,11 @@ describe('expanding plants into kinds', () => {expect(set.unitOf('stone')).toBe(1);expect(set.reach).toBe(200000);});++ it('measures the least distance a far version is shown over, for how wide a far cell may be', () => {+ expect(set.span).toBe(184000);+ const cover = expandPlants({ ...plants, grass: { parts: [part('g')], lodDistance: 3000, drawDistance: 9000, far: [part('g')], farDistance: 26000 } });+ expect(cover.span).toBe(17000);+ expect(expandPlants({ stone: plants.stone! }).span).toBe(0);+ });});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex a58db901c..e017dbb78 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2830,6 +2830,8 @@ export const NOTED = {{"note":"A generated world's plants."},"feat(export): a packaged game reports what it is still baking, and the capture launcher can wait for it":{"internal":"An observation seam for capture tooling; no game behaves differently."},+ "feat(worldgen): the far versions of a world's plants are laid out in cells as wide as their shortest span allows, so ground cover far off costs far fewer draws":+ {"note":"A generated world's plants."},"feat(water): two tiled, scrolling detail normal maps give the surface its sparkle":{"note":"Sparkle on the water."},"fix(lod): a LODGroup with only a cull size is no longer ignored":