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): recipes place plants, grown a cell at a time with far versions, and a world on an area ends where the terrain does

yhhcec1c85127af
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8edbc592a..348770cae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,9 @@ published separately; it ships inside the editor.
### Added
+- **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`.
+- **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.
- **Wind and rain on the water.** The weather drives the wind: each preset has a wind and a wave strength (mist calms, a storm raises the waves to over twice their height), the Water Body's waves and the foliage's sway follow it in play, and a Weather that does not drive the wind (`WeatherDrive.Wind`) leaves them as authored. Rain falls on water that keeps ripples as rings, as hard as the weather rains, and the rain effect no longer lays a wet floor or puddles over the water itself.
@@ -58,6 +61,8 @@ published separately; it ships inside the editor.
### Fixed
+- **A world's layers over an area are counted over the area.** The chunks of a procedural layer are walked over the part of the wanted radius that lies in the layer's extent, not over the whole radius, and a generated world on an area of terrain takes the terrain's bounds as its extent: a layer wanted a thousand chunk-widths out no longer costs seconds a frame.
+- **A level-of-detail group with only a cull size is no longer ignored.** A `LODGroup` with no stand-in mesh and a `cullSize` draws the renderer's own mesh while it is big enough and nothing once it is smaller, where it used to be dropped as if it were not there, so a tuft of grass had no distance to be drawn to.
- **A river runs into a lake cleanly, and water casts no shadow.** A river whose spline ran on into a lake drew a bright seam across the lake's bed: the surface was drawn into the sun's shadow map, darkening everything under it but where the river's heights changed its shape. Water no longer stands in the light's way (`MeshRenderer.castShadows`, new and on by default, says whether a mesh does), a lake now holds the water over a river that runs into it, and the surf's slope fades out on the ridge between two shores instead of flipping on a line.
- **Rain and storms on water.** Rain no longer drops dips into the zone's ripples (which twitched and left blotches of foam under a storm): drops ring out on the surface in the Water shader, as fine rings that spread and die, the more the harder it rains, with no foam. The wind's ripples are six short waves around its heading instead of drifting noise, so a lake no longer shows cells of light and dark. A weather raises waves as far as the water is open to the wind (the sea whole, a lake by its width, a river hardly at all), and surf is swell from open water, so a lake's shore laps in a storm instead of breaking like the sea's; what floats rides the same water.
- **Shadows follow what the camera draws.** A mesh the camera's level of detail culls (grass past its draw distance) no longer casts a shadow, and one drawn coarse casts coarse; seen from high up, a field of grass no longer laid an unseen square of shadow on the ground. The terrain's vertices slide between levels by the eye the ground was chosen for in every pass, so a shadow's ground is the ground that is seen, under an orthographic camera too.
diff --git a/docs/astro/src/content/docs/world/generation.mdx b/docs/astro/src/content/docs/world/generation.mdx
index 8ed70f689..45ed2dadb 100644
--- a/docs/astro/src/content/docs/world/generation.mdx
+++ b/docs/astro/src/content/docs/world/generation.mdx
@@ -64,7 +64,7 @@ registerWorldRules({
### Fields
Every decision is made from **fields**: numbers read at any world position. `height`, `up` (how much the ground faces up) and `slope`
-come from the terrain's surface, `waterDepth` and `shoreDistance` (how far a dry place is from the water's edge, negative on the water) from the water; `moisture`, `temperature` and `rock` are seeded noise, slow across the
+come from the terrain's surface, `paint.<layer>` (how much of the ground is that terrain layer, named by its file: `paint.grass` for grass.esterrainlayer, or `paint.grass`, `paint.dirt`, `paint.snow` and `paint.rock` without layer files), `waterDepth` and `shoreDistance` (how far a dry place is from the water's edge, negative on the water) from the water; `moisture`, `temperature` and `rock` are seeded noise, slow across the
world (their scales are the rules' `noise`). A game adds fields of its own with `fields: { name: (x, z, at) => number }`, reading the
built-in ones from `at`. A zone can set any field over its area.
@@ -76,6 +76,10 @@ meet in a mixed band instead of a line — and `transition` makes the edge wande
dirt, snow, rock) pulls the terrain's own paint toward the biome's by its weight and `paintStrength`. A biome lists its recipes, each
with the layer it is placed in and the share of that layer's candidates it takes.
+A rule is worked out for every candidate in every biome, so the fields are read when a condition asks for them and no sooner: a field no biome reads is never computed. A rules file names more noise fields of its own in `noise` (`{ "turf": { "scale": 1400, "octaves": 2 } }`), which any condition may then read by that name.
+
+A candidate takes **one biome, by weight, and then the recipe that biome has in the layer being laid out**: so a biome has to list its recipes in every layer it should stand in, and how thick a layer is where the biome holds is that recipe's `density`. A biome that lists nothing for a layer leaves the candidates that chose it empty. The weights mix biomes where they overlap; they do not thin a biome out, which is the recipes' `density` and the layer's `spacing`.
+
### Recipes
A recipe is a group: an **anchor** and **members** placed round it. Each member says its mesh and material (asset paths, or handles
@@ -88,6 +92,18 @@ group stands.
`version` is part of every placement's id: bump it when a recipe places something else.
+### Plants
+
+A member names a mesh and a material, or a **plant**: an entry in the rules' `plants`, for what a mesh and a material cannot say. A plant is its `parts` (a trunk and a crown are two, each with its `mesh`, a cheaper `lod1Mesh`, `material`, `texture`, `tint` and whether it is `opaque`), the `lodDistance` past which the cheaper meshes stand in and the `drawDistance` past which it is not drawn, a `far` version (a tree's crossed cards, baked to an atlas of their own) drawn from `drawDistance` out to `farDistance`, and optionally:
+
+| 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. |
+| `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. |
+
+Plants are grown a cell at a time by the same machinery as a [placed foliage](/docs/graphics/foliage/#placed-plants): a chunk stands at once and fills in over the frames after it, each mesh a few milliseconds of the frame's budget. The far versions are a layer of their own, laid out as far as the furthest of them goes and shown from past what their kinds draw as themselves, so a layer's `drawDistance` is what its plants draw as themselves and not how far the world is seen. A world on a terrain of an area ends where the terrain does. A plant stands upright; it does not lean with the ground.
+
### Layers
Layers are passes, in order: big things first. Each takes one candidate a cell of a grid `spacing` apart, jittered, with a priority
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 4318aa379..20458cbc8 100644
--- a/docs/astro/src/content/docs/zh-cn/world/generation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
@@ -53,18 +53,34 @@ registerWorldRules({
### 环境场
-每个决定都来自**环境场**:在任意世界位置读到的数值。`height`、`up`(地面朝上的程度)和 `slope` 来自地形的地表,`waterDepth` 和 `shoreDistance`(干燥处离水边多远,水面上为负)来自水体;`moisture`、`temperature` 和 `rock` 是带种子的噪声,在世界尺度上缓慢变化(尺度在规则的 `noise` 里设)。游戏可以用 `fields: { name: (x, z, at) => number }` 加入自己的场,并从 `at` 读取内置场。区域可以在它的范围内设置任意场的值。
+每个决定都来自**环境场**:在任意世界位置读到的数值。`height`、`up`(地面朝上的程度)和 `slope` 来自地形的地表,`paint.<层名>`(这一处地面有多少属于这个地形层,按层文件名取名:grass.esterrainlayer 对应 `paint.grass`;没有层文件时是 `paint.grass`、`paint.dirt`、`paint.snow`、`paint.rock`)、`waterDepth` 和 `shoreDistance`(干燥处离水边多远,水面上为负)来自水体;`moisture`、`temperature` 和 `rock` 是带种子的噪声,在世界尺度上缓慢变化(尺度在规则的 `noise` 里设)。游戏可以用 `fields: { name: (x, z, at) => number }` 加入自己的场,并从 `at` 读取内置场。区域可以在它的范围内设置任意场的值。
### 群落
群落是环境场上的权重:每个条件是某个场的一段区间(`min`、`max`),边缘在 `blend` 范围内衰减,各条件相乘。几个群落同时成立时它们的权重混合——候选点按所在位置的权重选择群落,所以两个群落相接处是一条混合带而不是一条线——`transition` 让边缘按这么多世界单位的噪声摆动。`paint`(草、土、雪、岩)按群落权重和 `paintStrength` 把地形原本的上色拉向群落的上色。群落列出它的配方,以及每个配方所在的层和它占该层候选点的比例。
+每个候选点在每个群落里都要算一遍规则,所以场只在某个条件读到它时才求值,没人读的场根本不会算。规则文件还可以在 `noise` 里自己加命名的噪声场(`{ "turf": { "scale": 1400, "octaves": 2 } }`),任何条件都可以按这个名字读取。
+
+候选点是**先按权重选定一个群落,再取这个群落在当前图层里的配方**:所以群落必须在它要出现的每个图层里都列出配方,这个群落所在的地方这一层有多密,就是这条配方的 `density`。群落在某个图层里没有配方,选中它的候选点就是空的。权重在群落重叠处把它们混合起来,不负责把一个群落变稀;变稀靠配方的 `density` 和图层的 `spacing`。
+
### 配方
配方是一个组:一个**锚点**和围绕它放置的**成员**。每个成员说明它的网格和材质(资源路径,或已加载的句柄)、数量(`count`)、离锚点多远和在什么角度(`ring`、`arc`)、`scale`、它在地面上占的范围(`footprint`:树干),与它在头顶伸展的范围(`canopy`:树冠)分开记录;它是直立还是随地面倾斜(`attach`)、允许多陡(`minUp`)和多深的水里站立(`waterDepth`)、被放置的概率 `chance`,以及它的远景版本(`far`:两张十字交叉卡片显示的贴图矩形,针叶树可用帐篷形,在所在层的 `lodDistance` 之外绘制)。站不住的成员(没有地面、太陡、在水下、被区域排除、压在先放的东西上)会被省去,组仍然成立。
`version` 是每个放置物 ID 的一部分:配方放置的东西变了就把它加一。
+### 植物
+
+成员可以是网格加材质,也可以是**植物**:规则 `plants` 里的一项,用来表达网格和材质表达不了的东西。植物由 `parts` 部件组成(树干和树冠是两个部件,各有 `mesh`、更省的 `lod1Mesh`、`material`、`texture`、`tint` 以及是否 `opaque`),超过 `lodDistance` 换成更省的网格,超过 `drawDistance` 不再绘制,`far` 远景版本(树的交叉卡片,烘到自己的图集上)从 `drawDistance` 一直画到 `farDistance`,另外可选:
+
+| 字段 | 含义 |
+|---|---|
+| `tints`、`tintScale` | 美术给的几种色调(乘在颜色上的线性系数),以及一片林子多宽(世界单位):一个地方按慢噪声取其中一种,所以林子里有偏暖和偏冷的片,不会是花点。 |
+| `sink` | 下沉进地面多深,世界单位(石头埋在土里的底面)。 |
+| `unit` | 一个网格单位对应多少世界单位:按米建模的植物放在厘米世界里就是 100。配方的 `scale` 这时是相对模型的大小。 |
+
+植物由与[手摆植物](/docs/zh-cn/graphics/foliage/#手摆植物)相同的机制按格子生长:区块立刻出现,之后几帧里逐步填满,每个网格只占帧预算里的几毫秒。远景版本是单独的一个图层,一直铺到它们中最远的那个,在镜头比其种类自身绘制距离更远时显示,所以图层的 `drawDistance` 是它的植物以本来面目绘制的距离,不是世界能看多远。建在区域型地形上的世界到地形边缘为止。植物是直立的,不随地面倾斜。
+
### 层
层是按顺序进行的几遍布置:先大后小。每层在间距为 `spacing` 的网格里每格取一个抖动后的候选点,并为它抽一个优先级。两个候选点的组会重叠时,优先级高的成立;每个候选点都避开前面各层的占地,所以蕨类不会长穿树干,石头不会嵌进巨石里。一层以 `chunkSize` 大小的区块发布到 `drawDistance`。`occupies: false` 让后面的层可以和它重叠(地被)。
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 7a3ec1981..c2da37fd9 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -3632,6 +3632,50 @@
"fields": [],
"tag": true
},
+ {
+ "name": "PlacedFoliage",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "sizeX",
+ "type": "number",
+ "default": "256",
+ "doc": "World size along x, centred on this entity.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "sizeZ",
+ "type": "number",
+ "default": "256",
+ "doc": "World size along z, centred on this entity.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "cellSize",
+ "type": "number",
+ "default": "32",
+ "doc": "Side of the cells the area is cut into. Each kind in a cell is one mesh a part, culled whole.",
+ "range": "≥ 4"
+ },
+ {
+ "key": "kinds",
+ "type": "array",
+ "default": "empty",
+ "doc": "What each kind of plant is made of: its parts (mesh, cheaper mesh, material, texture, tint) and how far it is drawn."
+ },
+ {
+ "key": "records",
+ "type": "array",
+ "default": "empty",
+ "doc": "Where each plant stands: kind index, x, y, z, turn about the vertical in radians and scale, six numbers a plant, in this entity's space."
+ }
+ ],
+ "animatable": [
+ "sizeX",
+ "sizeZ",
+ "cellSize"
+ ]
+ },
{
"name": "PlacedObject",
"source": "ts",
diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.md
index 16390faee..f7c658efa 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 · 16 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 30 experimental · 0 deprecated
## BladeParams — interface @experimental
```
@@ -81,6 +81,68 @@ ResourceDef<FoliageField>
(x: number, z: number) => { y: number; up: number } | null
```
+## PLACED_STRIDE — const @experimental
+```
+6
+```
+
+## PlacedFoliage — const @experimental
+```
+ComponentDef<PlacedFoliageData>
+```
+
+## PlacedFoliageData — interface @experimental
+```
+cellSize: number
+kinds: PlacedKind[]
+records: number[]
+sizeX: number
+sizeZ: number
+```
+
+## PlacedFoliageField — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, BuiltPlaced>
+cellCount: number
+pending: number
+static new (): PlacedFoliageField
+static prototype: PlacedFoliageField
+```
+
+## PlacedFoliagePlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): PlacedFoliagePlugin
+static prototype: PlacedFoliagePlugin
+```
+
+## PlacedFoliageRes — const @experimental
+```
+ResourceDef<PlacedFoliageField>
+```
+
+## PlacedKind — interface @experimental
+```
+drawDistance: number
+far: PlacedPart[]
+farDistance: number
+lodDistance: number
+parts: PlacedPart[]
+```
+
+## PlacedPart — interface @experimental
+```
+lod1Mesh: string
+material: string
+mesh: string
+opaque: boolean
+texture: string
+tint: [number, number, number, number]
+```
+
## Plant — interface @experimental
```
phase: number
@@ -93,6 +155,39 @@ yaw: number
z: number
```
+## PlantGrowth — class @experimental
+```
+app_: App | null
+growCell: (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
+made: number
+pending: number
+queue: { cell: GrownCell; run: () => void; }[]
+release: (app: App, cell: GrownCell) => void
+spentMs: number
+step: (app: App) => void
+static new (): PlantGrowth
+static prototype: PlantGrowth
+```
+
+## PlantGrowthRes — const @experimental
+```
+ResourceDef<PlantGrowth>
+```
+
+## PlantKind — interface @experimental
+```
+drawDistance: number
+far: PlacedPart[]
+farDistance: number
+lodDistance: number
+parts: PlacedPart[]
+sink: number | undefined
+tintScale: number | undefined
+tints: [number, number, number][] | undefined
+unit: number | undefined
+```
+
## ScatterParams — interface @experimental
```
cellKey: number
@@ -123,11 +218,26 @@ size: number
(source: MeshData, plants: readonly Plant[], paint?: BladeParams["paint"]): MeshData
```
+## buildPlacedMesh — function @experimental
+```
+(source: MeshData, plants: readonly Plant[]): MeshData
+```
+
## foliagePlugin — const @experimental
```
Plugin
```
+## placedFoliagePlugin — const @experimental
+```
+Plugin
+```
+
+## plantGrowthOf — function @experimental
+```
+(app: App): PlantGrowth
+```
+
## rng — function @experimental
```
(seed: number): () => number
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index cc651933e..07b76ea37 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -6114,6 +6114,7 @@ ySortLayers: number | undefined
## PackedLayers — interface @experimental
```
albedo: Uint8Array<ArrayBufferLike>[]
+heightBlends: number[]
mask: Uint8Array<ArrayBufferLike>[]
normal: Uint8Array<ArrayBufferLike>[]
size: number
@@ -6641,6 +6642,7 @@ material: number
member: string
mesh: number
normal: [number, number, number]
+plant: string | null
recipe: string
recipeVersion: number
scale: number
@@ -7713,8 +7715,9 @@ footprint: number
id: string
interactive: string | undefined
material: string | number | undefined
-mesh: string | number
+mesh: string | number | undefined
minUp: number | undefined
+plant: string | undefined
ring: readonly [number, number] | undefined
scale: readonly [number, number] | undefined
tags: readonly string[] | undefined
@@ -10082,6 +10085,7 @@ static prototype: TerrainLayerAssetLoader
## TerrainLayerDef — interface @experimental
```
albedo: string | undefined
+heightBlend: number | undefined
mask: string | undefined
normal: string | undefined
normalStrength: number
@@ -10181,14 +10185,17 @@ static prototype: TerrainUnavailable
@internal paint_: Repaint | null
@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
+areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
+layerNames: () => string[]
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
+paintAt: (x: number, z: number) => readonly number[] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
@@ -12356,6 +12363,7 @@ fields: Record<string, FieldFn> | undefined
id: string
layers: readonly PlacementLayer[]
noise: Partial<Record<string, NoiseField>> | undefined
+plants: Readonly<Record<string, PlantKind>> | undefined
recipes: readonly Recipe[]
versions: readonly number[]
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 730478eae..b37d65ec0 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -6317,6 +6317,7 @@ ySortLayers: number | undefined
## PackedLayers — interface @experimental
```
albedo: Uint8Array<ArrayBufferLike>[]
+heightBlends: number[]
mask: Uint8Array<ArrayBufferLike>[]
normal: Uint8Array<ArrayBufferLike>[]
size: number
@@ -6844,6 +6845,7 @@ material: number
member: string
mesh: number
normal: [number, number, number]
+plant: string | null
recipe: string
recipeVersion: number
scale: number
@@ -7926,8 +7928,9 @@ footprint: number
id: string
interactive: string | undefined
material: string | number | undefined
-mesh: string | number
+mesh: string | number | undefined
minUp: number | undefined
+plant: string | undefined
ring: readonly [number, number] | undefined
scale: readonly [number, number] | undefined
tags: readonly string[] | undefined
@@ -10295,6 +10298,7 @@ static prototype: TerrainLayerAssetLoader
## TerrainLayerDef — interface @experimental
```
albedo: string | undefined
+heightBlend: number | undefined
mask: string | undefined
normal: string | undefined
normalStrength: number
@@ -10394,14 +10398,17 @@ static prototype: TerrainUnavailable
@internal paint_: Repaint | null
@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
+areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
+layerNames: () => string[]
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
+paintAt: (x: number, z: number) => readonly number[] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
@@ -12569,6 +12576,7 @@ fields: Record<string, FieldFn> | undefined
id: string
layers: readonly PlacementLayer[]
noise: Partial<Record<string, NoiseField>> | undefined
+plants: Readonly<Record<string, PlantKind>> | undefined
recipes: readonly Recipe[]
versions: readonly number[]
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index af49c058f..945c1c003 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -6109,6 +6109,7 @@ ySortLayers: number | undefined
## PackedLayers — interface @experimental
```
albedo: Uint8Array<ArrayBufferLike>[]
+heightBlends: number[]
mask: Uint8Array<ArrayBufferLike>[]
normal: Uint8Array<ArrayBufferLike>[]
size: number
@@ -6636,6 +6637,7 @@ material: number
member: string
mesh: number
normal: [number, number, number]
+plant: string | null
recipe: string
recipeVersion: number
scale: number
@@ -7708,8 +7710,9 @@ footprint: number
id: string
interactive: string | undefined
material: string | number | undefined
-mesh: string | number
+mesh: string | number | undefined
minUp: number | undefined
+plant: string | undefined
ring: readonly [number, number] | undefined
scale: readonly [number, number] | undefined
tags: readonly string[] | undefined
@@ -10077,6 +10080,7 @@ static prototype: TerrainLayerAssetLoader
## TerrainLayerDef — interface @experimental
```
albedo: string | undefined
+heightBlend: number | undefined
mask: string | undefined
normal: string | undefined
normalStrength: number
@@ -10176,14 +10180,17 @@ static prototype: TerrainUnavailable
@internal paint_: Repaint | null
@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
+areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
+layerNames: () => string[]
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
+paintAt: (x: number, z: number) => readonly number[] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
@@ -12351,6 +12358,7 @@ fields: Record<string, FieldFn> | undefined
id: string
layers: readonly PlacementLayer[]
noise: Partial<Record<string, NoiseField>> | undefined
+plants: Readonly<Record<string, PlantKind>> | undefined
recipes: readonly Recipe[]
versions: readonly number[]
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index a805c06d7..18d54f908 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -6402,6 +6402,7 @@ ySortLayers: number | undefined
## PackedLayers — interface @experimental
```
albedo: Uint8Array<ArrayBufferLike>[]
+heightBlends: number[]
mask: Uint8Array<ArrayBufferLike>[]
normal: Uint8Array<ArrayBufferLike>[]
size: number
@@ -6929,6 +6930,7 @@ material: number
member: string
mesh: number
normal: [number, number, number]
+plant: string | null
recipe: string
recipeVersion: number
scale: number
@@ -8001,8 +8003,9 @@ footprint: number
id: string
interactive: string | undefined
material: string | number | undefined
-mesh: string | number
+mesh: string | number | undefined
minUp: number | undefined
+plant: string | undefined
ring: readonly [number, number] | undefined
scale: readonly [number, number] | undefined
tags: readonly string[] | undefined
@@ -10370,6 +10373,7 @@ static prototype: TerrainLayerAssetLoader
## TerrainLayerDef — interface @experimental
```
albedo: string | undefined
+heightBlend: number | undefined
mask: string | undefined
normal: string | undefined
normalStrength: number
@@ -10469,14 +10473,17 @@ static prototype: TerrainUnavailable
@internal paint_: Repaint | null
@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
+areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
+layerNames: () => string[]
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
+paintAt: (x: number, z: number) => readonly number[] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
@@ -12650,6 +12657,7 @@ fields: Record<string, FieldFn> | undefined
id: string
layers: readonly PlacementLayer[]
noise: Partial<Record<string, NoiseField>> | undefined
+plants: Readonly<Record<string, PlantKind>> | undefined
recipes: readonly Recipe[]
versions: readonly number[]
```
diff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.md
index 6e46fd2d5..b7b7cea04 100644
--- a/sdk/etc/terrain.api.md
+++ b/sdk/etc/terrain.api.md
@@ -124,6 +124,7 @@ number
## PackedLayers — interface @experimental
```
albedo: Uint8Array<ArrayBufferLike>[]
+heightBlends: number[]
mask: Uint8Array<ArrayBufferLike>[]
normal: Uint8Array<ArrayBufferLike>[]
size: number
@@ -294,6 +295,7 @@ static prototype: TerrainLayerAssetLoader
## TerrainLayerDef — interface @experimental
```
albedo: string | undefined
+heightBlend: number | undefined
mask: string | undefined
normal: string | undefined
normalStrength: number
@@ -393,14 +395,17 @@ static prototype: TerrainUnavailable
@internal paint_: Repaint | null
@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
+areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
+layerNames: () => string[]
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
+paintAt: (x: number, z: number) => readonly number[] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 97c0a929b..9c7519312 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -6116,6 +6116,7 @@ ySortLayers: number | undefined
## PackedLayers — interface @experimental
```
albedo: Uint8Array<ArrayBufferLike>[]
+heightBlends: number[]
mask: Uint8Array<ArrayBufferLike>[]
normal: Uint8Array<ArrayBufferLike>[]
size: number
@@ -6643,6 +6644,7 @@ material: number
member: string
mesh: number
normal: [number, number, number]
+plant: string | null
recipe: string
recipeVersion: number
scale: number
@@ -7715,8 +7717,9 @@ footprint: number
id: string
interactive: string | undefined
material: string | number | undefined
-mesh: string | number
+mesh: string | number | undefined
minUp: number | undefined
+plant: string | undefined
ring: readonly [number, number] | undefined
scale: readonly [number, number] | undefined
tags: readonly string[] | undefined
@@ -10084,6 +10087,7 @@ static prototype: TerrainLayerAssetLoader
## TerrainLayerDef — interface @experimental
```
albedo: string | undefined
+heightBlend: number | undefined
mask: string | undefined
normal: string | undefined
normalStrength: number
@@ -10183,14 +10187,17 @@ static prototype: TerrainUnavailable
@internal paint_: Repaint | null
@internal remake_: (b: readonly [number, number, number, number]) => void
@internal revision_: number
+areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
+layerNames: () => string[]
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
+paintAt: (x: number, z: number) => readonly number[] | null
pending: number
raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | null
repaint: () => void
@@ -12382,6 +12389,7 @@ fields: Record<string, FieldFn> | undefined
id: string
layers: readonly PlacementLayer[]
noise: Partial<Record<string, NoiseField>> | undefined
+plants: Readonly<Record<string, PlantKind>> | undefined
recipes: readonly Recipe[]
versions: readonly number[]
```
diff --git a/sdk/etc/worldgen.api.md b/sdk/etc/worldgen.api.md
index 470e522d3..451b48c26 100644
--- a/sdk/etc/worldgen.api.md
+++ b/sdk/etc/worldgen.api.md
@@ -102,6 +102,7 @@ material: number
member: string
mesh: number
normal: [number, number, number]
+plant: string | null
recipe: string
recipeVersion: number
scale: number
@@ -175,8 +176,9 @@ footprint: number
id: string
interactive: string | undefined
material: string | number | undefined
-mesh: string | number
+mesh: string | number | undefined
minUp: number | undefined
+plant: string | undefined
ring: readonly [number, number] | undefined
scale: readonly [number, number] | undefined
tags: readonly string[] | undefined
@@ -265,6 +267,7 @@ fields: Record<string, FieldFn> | undefined
id: string
layers: readonly PlacementLayer[]
noise: Partial<Record<string, NoiseField>> | undefined
+plants: Readonly<Record<string, PlantKind>> | undefined
recipes: readonly Recipe[]
versions: readonly number[]
```
diff --git a/sdk/src/residency/chunks.ts b/sdk/src/residency/chunks.ts
index 9135abddf..cf97eae18 100644
--- a/sdk/src/residency/chunks.ts
+++ b/sdk/src/residency/chunks.ts
@@ -195,8 +195,11 @@ export class ProceduralChunks {
const reach = Math.max(d.loadRadius, d.unloadRadius);
const x0 = Math.floor((s.x - reach - d.originX) / d.sizeX), x1 = Math.floor((s.x + reach - d.originX) / d.sizeX);
const z0 = Math.floor((s.z - reach - d.originZ) / d.sizeZ), z1 = Math.floor((s.z + reach - d.originZ) / d.sizeZ);
- for (let cz = z0; cz <= z1; cz++) for (let cx = x0; cx <= x1; cx++) {
- if (d.extent && (cx < d.extent[0] || cz < d.extent[1] || cx >= d.extent[2] || cz >= d.extent[3])) continue;
+ // A layer with an extent is walked over the part of the radius that lies in it, not over a radius that may be a thousand times the area.
+ const ex = d.extent;
+ const cx0 = ex ? Math.max(x0, ex[0]) : x0, cx1 = ex ? Math.min(x1, ex[2] - 1) : x1;
+ const cz0 = ex ? Math.max(z0, ex[1]) : z0, cz1 = ex ? Math.min(z1, ex[3] - 1) : z1;
+ for (let cz = cz0; cz <= cz1; cz++) for (let cx = cx0; cx <= cx1; cx++) {
const mx = d.originX + cx * d.sizeX, mz = d.originZ + cz * d.sizeZ;
const dist = Math.hypot(Math.max(mx - s.x, 0, s.x - mx - d.sizeX), Math.max(mz - s.z, 0, s.z - mz - d.sizeZ));
const key = keyOf(cx, cz);
diff --git a/sdk/src/worldgen/fields.ts b/sdk/src/worldgen/fields.ts
index 0f5e0d594..8f72cdaf6 100644
--- a/sdk/src/worldgen/fields.ts
+++ b/sdk/src/worldgen/fields.ts
@@ -86,20 +86,31 @@ export class Environment {
for (const name of Object.keys(this.noise_)) this.seeds_[name] = (inputs.seed * 7919) ^ hashString(name);
}
- /** Every field at (x, z). */
+ /**
+ * Every field at (x, z), each worked out the first time it is read and not before: a biome reads three or four of the dozen, and a candidate asks
+ * of every biome, so working all of them out for each was most of what laying out a world cost.
+ */
sample(x: number, z: number): FieldValues {
- const g = this.inputs.ground(x, z);
- const at: FieldValues = {
- height: g ? g.y : NaN,
- up: g ? g.up : 1,
- slope: g ? 1 - g.up : 0,
- waterDepth: g && this.inputs.waterDepth ? this.inputs.waterDepth(x, z, g.y) ?? -Infinity : -Infinity,
- shoreDistance: this.inputs.shoreDistance?.(x, z) ?? Infinity,
+ const at: FieldValues = {};
+ const lazy = (name: string, compute: () => number): void => {
+ let done = false, value = 0;
+ Object.defineProperty(at, name, {
+ enumerable: true, configurable: true,
+ get: () => { if (!done) { value = compute(); done = true; } return value; },
+ set: (v: number) => { value = v; done = true; },
+ });
};
+ let g: ReturnType<EnvironmentInputs['ground']> | undefined;
+ const ground = (): ReturnType<EnvironmentInputs['ground']> => (g === undefined ? (g = this.inputs.ground(x, z)) : g);
+ lazy('height', () => ground()?.y ?? NaN);
+ lazy('up', () => ground()?.up ?? 1);
+ lazy('slope', () => 1 - (ground()?.up ?? 1));
+ lazy('waterDepth', () => { const gr = ground(); return gr && this.inputs.waterDepth ? this.inputs.waterDepth(x, z, gr.y) ?? -Infinity : -Infinity; });
+ lazy('shoreDistance', () => this.inputs.shoreDistance?.(x, z) ?? Infinity);
for (const [name, f] of Object.entries(this.noise_)) {
- at[name] = fbm(x / Math.max(f.scale, 1e-6), z / Math.max(f.scale, 1e-6), this.seeds_[name]!, Math.max(1, f.octaves ?? 3));
+ lazy(name, () => fbm(x / Math.max(f.scale, 1e-6), z / Math.max(f.scale, 1e-6), this.seeds_[name]!, Math.max(1, f.octaves ?? 3)));
}
- for (const [name, f] of Object.entries(this.inputs.fields ?? {})) at[name] = f(x, z, at);
+ for (const [name, f] of Object.entries(this.inputs.fields ?? {})) lazy(name, () => f(x, z, at));
for (const o of this.inputs.overrides?.(x, z) ?? []) {
const base = at[o.field] ?? o.value;
at[o.field] = base + (o.value - base) * Math.min(Math.max(o.weight, 0), 1);
diff --git a/sdk/src/worldgen/plan.ts b/sdk/src/worldgen/plan.ts
index 8bbdb2964..6acc2093d 100644
--- a/sdk/src/worldgen/plan.ts
+++ b/sdk/src/worldgen/plan.ts
@@ -45,6 +45,8 @@ export interface Placement {
attach: 'upright' | 'align';
mesh: number;
material: number;
+ /** The kind of plant it is, by its name in the rules' `plants`, or null for a mesh. */
+ plant: string | null;
interactive: string | null;
footprint: number;
canopy: number;
@@ -290,7 +292,7 @@ export class WorldPlan {
biome, zone: this.zones.at(x, z)[0]?.zone.id ?? null,
x, y: f.height!, z, yaw: (turn || h) * Math.PI * 2, scale: lerp(m.scale, hash01(this.worldHash_, hashString(group), k, 11), 1),
normal: n, attach: m.attach ?? 'upright', mesh: typeof m.mesh === 'number' ? m.mesh : 0,
- material: typeof m.material === 'number' ? m.material : 0, interactive: m.interactive ?? null,
+ material: typeof m.material === 'number' ? m.material : 0, plant: m.plant ?? null, interactive: m.interactive ?? null,
footprint: m.footprint, canopy: m.canopy ?? m.footprint, far: m.far ?? null,
};
}
diff --git a/sdk/src/worldgen/plants.ts b/sdk/src/worldgen/plants.ts
new file mode 100644
index 000000000..1af306626
--- /dev/null
+++ b/sdk/src/worldgen/plants.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file plants.ts
+ * @brief The kinds of plant a world's recipes name, made into the kinds a `PlacedFoliage` grows: one kind a plant in each colouring it has.
+ *
+ * @details A plant with `tints` is as many kinds as it has tints (its parts' colour multiplied by each), and a place takes one of them by a slow
+ * noise, so a wood has warm and cool stands and never a speckle. A plant without is one kind.
+ */
+import type { PlacedKind, PlantKind } from '../foliage/plantKind';
+import { fbm, hashString } from './fields';
+
+/** A rules' plants as kinds, and which kind a plant at a place is. */
+export interface PlantSet {
+ kinds: PlacedKind[];
+ /** The index of the kind that the plant `name` is at world (x, z); -1 for a name the set does not have. */
+ kindAt(name: string, x: number, z: number): number;
+ /** How far the plant `name` is sunk into the ground. */
+ sinkOf(name: string): number;
+ /** World units to a unit of the plant `name`'s mesh. */
+ unitOf(name: string): number;
+ /** The furthest any kind is wanted: where the far versions end. */
+ reach: 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;
+ 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;
+ 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 });
+ }
+ 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);
+ }
+ return {
+ kinds, reach,
+ kindAt(name, x, z) {
+ const s = slots.get(name);
+ if (!s) return -1;
+ return s.count === 1 ? s.first : s.first + Math.min(s.count - 1, Math.floor(fbm(x / s.scale, z / s.scale, s.seed, 1) * s.count));
+ },
+ sinkOf: (name) => slots.get(name)?.sink ?? 0,
+ unitOf: (name) => slots.get(name)?.unit ?? 1,
+ };
+}
diff --git a/sdk/src/worldgen/rules.ts b/sdk/src/worldgen/rules.ts
index b4cf8e210..5f8f10eb3 100644
--- a/sdk/src/worldgen/rules.ts
+++ b/sdk/src/worldgen/rules.ts
@@ -18,6 +18,7 @@
* clear of the footprints of the layers before it, and is published in chunks out to `drawDistance`.
*/
import type { FieldFn, NoiseField } from './fields';
+import type { PlantKind } from '../foliage/plantKind';
/** A band of one field with soft edges: full weight between `min` and `max`, fading to none over `blend` past each. */
export interface BiomeCondition { field: string; min?: number; max?: number; blend?: number }
@@ -42,8 +43,13 @@ export interface BiomeDef {
export interface RecipeMember {
/** Stable within the recipe: part of every placement's id. */
id: string;
- /** The mesh it is drawn with, and the material: an asset path (as a recipe file names them) or a handle already loaded. */
- mesh: number | string;
+ /** The mesh it is drawn with, and the material: an asset path (as a recipe file names them) or a handle already loaded. Absent for a member that is a `plant`. */
+ mesh?: number | string;
+ /**
+ * Or the kind of plant it is, by its name in the rules' `plants`: several parts (a trunk and its crown), a cheaper mesh and a far version each,
+ * and the colourings the art gives it. It is grown a cell at a time like a `PlacedFoliage`, in place of the mesh and material above.
+ */
+ plant?: string;
material?: number | string;
/** What a game interacts with it as (ore, tree to fell); absent, it is decoration and drawn merged with its chunk. */
interactive?: string;
@@ -105,6 +111,8 @@ export interface WorldRules {
versions: readonly number[];
biomes: readonly BiomeDef[];
recipes: readonly Recipe[];
+ /** The kinds of plant the recipes' members name. */
+ plants?: Readonly<Record<string, PlantKind>>;
/** In order: each keeps clear of the layers before it. */
layers: readonly PlacementLayer[];
noise?: Partial<Record<string, NoiseField>>;
diff --git a/sdk/src/worldgen/rulesAsset.ts b/sdk/src/worldgen/rulesAsset.ts
index 529df103a..098148ff7 100644
--- a/sdk/src/worldgen/rulesAsset.ts
+++ b/sdk/src/worldgen/rulesAsset.ts
@@ -11,6 +11,7 @@
* a world from half of it.
*/
import type { AssetLoader, LoadContext } from '../asset/AssetLoader';
+import type { PlantKind } from '../foliage/plantKind';
import type { BiomeDef, PlacementLayer, Recipe, RecipeMember, WorldRules } from './rules';
/** Whether a WorldGen's `rules` names a file rather than rules registered by code. */
@@ -42,11 +43,12 @@ function member(v: unknown, where: string): RecipeMember {
if (!v || typeof v !== 'object') fail(where, 'a member, an object');
const m = v as Record<string, unknown>;
const mesh = m.mesh;
- if (typeof mesh !== 'string' && typeof mesh !== 'number') fail(`${where}.mesh`, 'a mesh path');
+ if (m.plant !== undefined) str(m.plant, `${where}.plant`);
+ else if (typeof mesh !== 'string' && typeof mesh !== 'number') fail(`${where}.mesh`, 'a mesh path, or a plant');
return {
...(m as object),
id: str(m.id, `${where}.id`),
- mesh: mesh as string | number,
+ ...(mesh === undefined ? {} : { mesh: mesh as string | number }),
footprint: num(m.footprint, `${where}.footprint`, 0),
count: range(m.count, `${where}.count`),
ring: range(m.ring, `${where}.ring`),
@@ -55,6 +57,41 @@ function member(v: unknown, where: string): RecipeMember {
} as RecipeMember;
}
+function part(v: unknown, where: string): PlantKind['parts'][number] {
+ if (!v || typeof v !== 'object') fail(where, 'a part, an object');
+ const p = v as Record<string, unknown>;
+ const tint = p.tint ?? [1, 1, 1, 1];
+ if (!Array.isArray(tint) || tint.length !== 4) fail(`${where}.tint`, 'four numbers, red, green, blue and alpha');
+ return {
+ mesh: str(p.mesh, `${where}.mesh`), lod1Mesh: typeof p.lod1Mesh === 'string' ? p.lod1Mesh : '', material: typeof p.material === 'string' ? p.material : '',
+ texture: typeof p.texture === 'string' ? p.texture : '', tint: (tint as unknown[]).map((c, i) => num(c, `${where}.tint[${i}]`)) as [number, number, number, number],
+ opaque: p.opaque !== false,
+ };
+}
+
+function plant(v: unknown, where: string): PlantKind {
+ if (!v || typeof v !== 'object') fail(where, 'a plant, an object');
+ const o = v as Record<string, unknown>;
+ if (!Array.isArray(o.parts) || o.parts.length === 0) fail(`${where}.parts`, 'at least one part');
+ const far = Array.isArray(o.far) ? (o.far as unknown[]).map((p, i) => part(p, `${where}.far[${i}]`)) : [];
+ let tints: PlantKind['tints'];
+ if (o.tints !== undefined) {
+ if (!Array.isArray(o.tints) || o.tints.length === 0) fail(`${where}.tints`, 'a list of colourings, each three numbers');
+ tints = (o.tints as unknown[]).map((t, i) => {
+ if (!Array.isArray(t) || t.length !== 3) fail(`${where}.tints[${i}]`, 'three numbers, red, green and blue');
+ return (t as unknown[]).map((c, k) => num(c, `${where}.tints[${i}][${k}]`)) as [number, number, number];
+ });
+ }
+ return {
+ 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,
+ ...(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) }),
+ };
+}
+
/** Rules from a file's JSON, checked; throws naming the first thing a world could not be laid out from. */
export function parseWorldRules(json: unknown, file = 'world rules'): WorldRules {
if (!json || typeof json !== 'object') fail(file, 'an object');
@@ -73,6 +110,17 @@ export function parseWorldRules(json: unknown, file = 'world rules'): WorldRules
members: Array.isArray(o.members) ? (o.members as unknown[]).map((m, k) => member(m, `${where}.members[${k}]`)) : undefined,
} as Recipe;
});
+ let plants: Record<string, PlantKind> | undefined;
+ if (r.plants !== undefined) {
+ if (!r.plants || typeof r.plants !== 'object' || Array.isArray(r.plants)) fail(`${file}.plants`, 'an object of plants by name');
+ plants = {};
+ for (const [name, v] of Object.entries(r.plants as Record<string, unknown>)) plants[name] = plant(v, `${file}.plants.${name}`);
+ }
+ for (const [i, rc] of recipes.entries()) {
+ for (const m of [rc.anchor, ...(rc.members ?? [])]) {
+ if (m.plant !== undefined && !plants?.[m.plant]) fail(`${file}.recipes[${i}].${m.id}.plant`, `no plant ${JSON.stringify(m.plant)} in the file's plants`);
+ }
+ }
if (!Array.isArray(r.layers) || r.layers.length === 0) fail(`${file}.layers`, 'at least one layer');
const layers: PlacementLayer[] = (r.layers as unknown[]).map((v, i) => {
const where = `${file}.layers[${i}]`;
@@ -96,7 +144,7 @@ export function parseWorldRules(json: unknown, file = 'world rules'): WorldRules
}
return { ...(o as object), id: str(o.id, `${where}.id`) } as BiomeDef;
});
- return { id, versions, biomes, recipes, layers, ...(r.noise ? { noise: r.noise as WorldRules['noise'] } : {}) };
+ return { id, versions, biomes, recipes, layers, ...(plants ? { plants } : {}), ...(r.noise ? { noise: r.noise as WorldRules['noise'] } : {}) };
}
/** Loads `.esworld` files as checked world rules. */
diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.ts
index dee8a3ab8..ef9fc49ba 100644
--- a/sdk/src/worldgen/worldgenPlugin.ts
+++ b/sdk/src/worldgen/worldgenPlugin.ts
@@ -32,7 +32,9 @@ import { Terrains, TerrainsRes } from '../terrain/terrainPlugin';
import { flattenModifier, type TerrainModifier } from '../terrain/source';
import { buildBillboardMesh, buildInstancedMesh, type Plant } from '../foliage/builder';
import { chunksOf, ProceduralChunksRes, type ChunkLayerStatus } from '../residency/chunks';
+import { plantGrowthOf, prepareKinds, type GrownCell, type ReadyKinds } from '../foliage/plantGrowth';
import { Environment } from './fields';
+import { expandPlants, type PlantSet } from './plants';
import { WorldPlan, type Placement } from './plan';
import { worldRules, worldRulesRevision, type PlacementLayer, type RecipeMember, type WorldRules } from './rules';
import { Zones, type ZoneDef } from './zones';
@@ -147,6 +149,9 @@ interface BuiltWorld {
authored: Set<string>;
/** Zones that level their ground and wait for it to be known. */
levelling: Set<string>;
+ /** The rules' plants as kinds, and their parts once the assets are in hand (null while they are being loaded, or when the rules have no plants). */
+ plants: PlantSet | null;
+ plantsReady: ReadyKinds | null;
}
/** A chunk of a layer: what it places (its decoration merged by mesh, its interactive placements), and what it put in the world. */
@@ -154,6 +159,12 @@ interface PlacedChunk {
/** A kind of decoration: its near mesh and, when it has one, its far cards; drawn near out to `lodDistance`, out to `drawDistance`. */
decor: { mesh: number; material: number; data: MeshData; far: MeshData | null; origin: [number, number, number]; radius: number; lodDistance: number; drawDistance: number }[];
objects: Placement[];
+ /** 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];
+ 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;
entities: Entity[];
meshes: number[];
}
@@ -262,7 +273,7 @@ export class WorldGenPlugin implements Plugin {
/** A WorldGen's rules and plan, or why it has none. */
private make(app: App, gens: WorldGens, entity: Entity, data: WorldGenData, had: BuiltWorld | undefined): BuiltWorld {
- const built: BuiltWorld = { signature: `${JSON.stringify(data)}#${worldRulesRevision()}`, data: { ...data }, rules: null, plan: null, failure: null, ground: '', authored: had?.authored ?? new Set(), levelling: new Set() };
+ const built: BuiltWorld = { signature: `${JSON.stringify(data)}#${worldRulesRevision()}`, data: { ...data }, rules: null, plan: null, failure: null, ground: '', authored: had?.authored ?? new Set(), levelling: new Set(), plants: null, plantsReady: null };
// Rules in a project file are read first, then made like rules registered by code.
if (isRulesFile(data.rules)) {
if (!app.hasResource(Assets)) {
@@ -307,11 +318,22 @@ export class WorldGenPlugin implements Plugin {
if (built.failure) {
log.error('worldgen', `the world ${data.world} cannot be laid out: ${built.failure}`);
// A world that cannot be laid out shows nothing of the one before it.
- for (const l of had?.rules?.layers ?? []) chunksOf(app).remove(layerIdOf(entity, l.id));
+ for (const l of had?.rules?.layers ?? []) { chunksOf(app).remove(layerIdOf(entity, l.id)); chunksOf(app).remove(layerIdOf(entity, `${l.id}:far`)); }
return;
}
// Layers the new rules no longer have are let go; the ones they keep keep their chunks until they are made again.
- for (const l of had?.rules?.layers ?? []) if (!rules.layers.some((n) => n.id === l.id)) chunksOf(app).remove(layerIdOf(entity, l.id));
+ for (const l of had?.rules?.layers ?? []) if (!rules.layers.some((n) => n.id === l.id)) { chunksOf(app).remove(layerIdOf(entity, l.id)); chunksOf(app).remove(layerIdOf(entity, `${l.id}:far`)); }
+ // The plants the recipes name: as kinds, and their parts read once there is a renderer to grow them with. A chunk waits for them.
+ if (rules.plants && Object.keys(rules.plants).length > 0 && app.hasResource(Assets)) {
+ const set = expandPlants(rules.plants);
+ built.plants = set;
+ void prepareKinds(app.getResource(Assets), set.kinds).then((ready) => {
+ if (gens.built_.get(entity) === built) built.plantsReady = ready;
+ }, (e: unknown) => {
+ built.failure = `the plants' assets could not be loaded: ${e instanceof Error ? e.message : String(e)}`;
+ log.error('worldgen', built.failure);
+ });
+ }
// Recipes name their meshes and materials by path: with a renderer they are loaded first, and the plan is made with them.
const refs = assetRefsOf(rules);
if (refs.length > 0 && app.hasResource(Assets)) {
@@ -349,8 +371,11 @@ export class WorldGenPlugin implements Plugin {
const data = built.data;
const terrains = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;
const zones = gens.zones(data.world);
+ // The terrain's paint is a field for each of its layers, `paint.grass` for a layer file grass.esterrainlayer: how much of the ground there is that.
+ const paintFields: Record<string, (x: number, z: number) => number> = {};
+ if (terrains) terrains.layerNames().forEach((name, i) => { paintFields[`paint.${name}`] = (x, z) => terrains.paintAt(x, z)?.[i] ?? 0; });
const env = new Environment({
- seed: data.seed, noise: rules.noise, fields: rules.fields,
+ seed: data.seed, noise: rules.noise, fields: { ...paintFields, ...rules.fields },
ground: (x, z) => {
if (terrains && terrains.built_.size > 0) {
const y = terrains.heightAt(x, z);
@@ -467,17 +492,41 @@ export class WorldGenPlugin implements Plugin {
const diffs = gens.diffs(built.data.world);
const rendering = app.hasResource(Assets);
const chunks = chunksOf(app);
+ // A world on a terrain of an area ends where the terrain does: its chunks are counted over that, and not over a radius of empty world.
+ const bounds = terrains?.areaBounds() ?? null;
for (const layer of rules.layers) {
const size = layer.chunkSize ?? 64;
+ const extent: [number, number, number, number] | null = bounds
+ ? [Math.floor(bounds[0] / size), Math.floor(bounds[1] / size), Math.ceil(bounds[2] / size), Math.ceil(bounds[3] / size)] : null;
chunks.set<PlacedChunk>(layerIdOf(entity, layer.id), {
label: 'Laying out the world',
- originX: 0, originZ: 0, sizeX: size, sizeZ: size, extent: null,
+ originX: 0, originZ: 0, sizeX: size, sizeZ: size, extent,
loadRadius: layer.drawDistance, unloadRadius: layer.drawDistance + size,
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;
- return this.chunk(app, plan, diffs, layer, x0, z0, size, rendering);
+ // The plants' parts are read before any chunk: a chunk made without them would leave the plants out until it is made again.
+ if (rendering && built.plants && !built.plantsReady) return null;
+ return this.chunk(app, plan, diffs, layer, x0, z0, size, rendering, built.plants);
+ },
+ publish: (_cx, _cz, value) => this.place(app, gens, entity, value),
+ release: (_cx, _cz, value) => this.unplace(app, gens, value),
+ });
+ // The plants' far versions are a layer of their own, wanted as far as the furthest of them goes: they are cheap, so the whole world stands at once,
+ // 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; }
+ 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,
+ 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;
+ if (!built.plantsReady) return null;
+ return this.chunk(app, plan, diffs, layer, x0, z0, size, rendering, built.plants, true);
},
publish: (_cx, _cz, value) => this.place(app, gens, entity, value),
release: (_cx, _cz, value) => this.unplace(app, gens, value),
@@ -487,18 +536,31 @@ export class WorldGenPlugin implements Plugin {
/** What one chunk of a layer places: its decoration merged by mesh, and its interactive placements, with the changes laid over. */
private chunk(app: App, plan: WorldPlan, diffs: PlacementDiffs, layer: PlacementLayer, x0: number, z0: number, size: number,
- rendering: boolean): PlacedChunk | Promise<PlacedChunk> {
+ rendering: boolean, plants: PlantSet | null, far = false): PlacedChunk | Promise<PlacedChunk> {
const placements: Placement[] = [];
for (const p of plan.placementsIn(x0, z0, x0 + size, z0 + size, [layer.id])) {
if (diffs.isRemoved(p.id)) continue;
const c = diffs.changeOf(p.id);
placements.push(c ? { ...p, ...c } : p);
}
- const objects = placements.filter((p) => p.interactive !== null);
- const decor = rendering ? placements.filter((p) => p.interactive === null && p.mesh) : [];
+ const objects = far ? [] : placements.filter((p) => p.interactive !== null);
+ 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, entities: [], meshes: [] };
+ const out: PlacedChunk = { decor: [], objects, planted: null, at: [x0 + size / 2, 0, z0 + size / 2], 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[]>();
+ for (const p of placements) {
+ if (p.interactive !== null || p.plant === null) continue;
+ const k = plants.kindAt(p.plant, p.x, p.z);
+ if (k < 0) continue;
+ let list = by.get(k);
+ if (!list) by.set(k, list = []);
+ list.push({ x: p.x - out.at[0], y: p.y - plants.sinkOf(p.plant), z: p.z - out.at[2], yaw: p.yaw, scale: p.scale * plants.unitOf(p.plant), phase: 0, shade: 1 });
+ }
+ if (by.size > 0) out.planted = by;
+ }
const byKind = new Map<string, Placement[]>();
for (const p of decor) {
const k = `${p.mesh}:${p.material}`;
@@ -548,6 +610,19 @@ export class WorldGenPlugin implements Plugin {
if (!world.valid(parent)) return;
const base = (world.get(parent, Transform) as TransformData).worldPosition;
const assets = app.hasResource(Assets) ? app.getResource(Assets) : null;
+ const built = gens.built_.get(parent);
+ if (chunk.planted && built?.plants && built.plantsReady) {
+ // The plants of the chunk: its entity stands at once, and they grow in it over the frames, as a placed foliage's do.
+ const e = world.spawn('WorldGenPlants');
+ world.insert(e, RuntimeOnly);
+ world.insert(e, Transform, { position: { x: chunk.at[0] - base.x, y: -base.y, z: chunk.at[2] - base.z } });
+ world.setParent(e, parent);
+ 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] });
+ else growth.growCell(app, chunk.grown, built.plants.kinds, built.plantsReady, chunk.planted);
+ }
for (const d of chunk.decor) {
const handle = assets?.createMesh(d.data) ?? 0;
if (!handle) continue;
@@ -594,6 +669,7 @@ export class WorldGenPlugin implements Plugin {
}
private unplace(app: App, gens: WorldGens, chunk: PlacedChunk): void {
+ if (chunk.grown) { plantGrowthOf(app).release(app, chunk.grown); chunk.grown = null; }
const mine = new Set(chunk.entities);
for (const p of chunk.objects) if (mine.has(gens.objects_.get(p.id)!)) gens.objects_.delete(p.id);
for (const e of chunk.entities) if (app.world.valid(e)) app.world.despawn(e);
@@ -606,7 +682,7 @@ export class WorldGenPlugin implements Plugin {
private drop(app: App, gens: WorldGens, entity: Entity): void {
const built = gens.built_.get(entity);
if (app.hasResource(ProceduralChunksRes)) {
- for (const l of built?.rules?.layers ?? []) app.getResource(ProceduralChunksRes).remove(layerIdOf(entity, l.id));
+ for (const l of built?.rules?.layers ?? []) { app.getResource(ProceduralChunksRes).remove(layerIdOf(entity, l.id)); app.getResource(ProceduralChunksRes).remove(layerIdOf(entity, `${l.id}:far`)); }
}
if (built && app.hasResource(TerrainsRes)) app.getResource(TerrainsRes).setPaint(null);
gens.built_.delete(entity);
diff --git a/sdk/tests/worldgen-plan.test.ts b/sdk/tests/worldgen-plan.test.ts
index a1b94991f..99922a23d 100644
--- a/sdk/tests/worldgen-plan.test.ts
+++ b/sdk/tests/worldgen-plan.test.ts
@@ -157,3 +157,35 @@ describe('the environment', () => {
expect(env.sample(-5, 0).shoreDistance).toBe(Infinity);
});
});
+
+describe('plants in a plan', () => {
+ const plantRules: WorldRules = {
+ id: 'test:plants', versions: [1],
+ biomes: [{ id: 'meadow', conditions: [], recipes: [{ recipe: 'tuft', layer: 'cover', density: 1 }] }],
+ recipes: [{ id: 'tuft', version: 1, anchor: { id: 'tuft', plant: 'grass', footprint: 0.2 }, members: [{ id: 'more', plant: 'grass', count: [2, 3], ring: [1, 2], footprint: 0.2 }] }],
+ layers: [{ id: 'cover', spacing: 8, drawDistance: 100 }],
+ };
+ const flat = new Environment({ seed: 1, ground: () => ({ y: 3, up: 1 }) });
+
+ it('carries the name of the plant a member is, and no mesh', () => {
+ const plan = new WorldPlan(plantRules, flat, new Zones(), 1, 'w');
+ const placements = plan.placementsIn(0, 0, 64, 64);
+ expect(placements.length).toBeGreaterThan(8);
+ for (const p of placements) { expect(p.plant).toBe('grass'); expect(p.mesh).toBe(0); }
+ });
+
+ it('works out a field only when a rule reads it', () => {
+ let read = 0;
+ const env = new Environment({
+ seed: 1, ground: () => ({ y: 0, up: 1 }),
+ fields: { costly: () => { read++; return 1; }, unused: () => { read += 1000; return 0; } },
+ });
+ const at = env.sample(5, 5);
+ expect(read).toBe(0);
+ expect(at.costly).toBe(1);
+ expect(at.costly).toBe(1);
+ expect(read).toBe(1);
+ expect(at.height).toBe(0);
+ });
+});
+
diff --git a/sdk/tests/worldgen-plants.test.ts b/sdk/tests/worldgen-plants.test.ts
new file mode 100644
index 000000000..97a7263f4
--- /dev/null
+++ b/sdk/tests/worldgen-plants.test.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The plants a world's recipes name, made into the kinds a placed foliage grows: one kind a colouring, and a place has one.
+ */
+import { describe, expect, it } from 'vitest';
+import { expandPlants } from '../src/worldgen/plants';
+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 },
+ stone: { parts: [part('rock')], lodDistance: 0, drawDistance: 30000, far: [], farDistance: 0 },
+};
+
+describe('expanding plants into kinds', () => {
+ const set = expandPlants(plants);
+
+ it('makes a kind of each colouring, with the tint multiplied into every part and its far parts', () => {
+ expect(set.kinds).toHaveLength(4);
+ const first = set.kinds[0]!;
+ expect(first.parts[0]!.tint[0]).toBeCloseTo(0.45);
+ expect(first.parts[1]!.tint).toEqual([0.9, 1, 0.9, 1]);
+ expect(first.far[0]!.tint).toEqual([0.9, 1, 0.9, 1]);
+ expect(set.kinds[3]!.parts).toHaveLength(1);
+ expect(set.kinds[3]!.far).toHaveLength(0);
+ });
+
+ it('gives a place one colouring, the same each time, and a plant without any its one kind', () => {
+ const seen = new Set<number>();
+ for (let i = 0; i < 400; i++) {
+ const k = set.kindAt('oak', i * 311, i * 97);
+ expect(k).toBeGreaterThanOrEqual(0);
+ expect(k).toBeLessThan(3);
+ expect(set.kindAt('oak', i * 311, i * 97)).toBe(k);
+ seen.add(k);
+ }
+ expect(seen.size).toBe(3);
+ expect(set.kindAt('stone', 5, 5)).toBe(3);
+ expect(set.kindAt('nothing', 5, 5)).toBe(-1);
+ });
+
+ 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);
+ expect(set.unitOf('oak')).toBe(100);
+ expect(set.unitOf('stone')).toBe(1);
+ expect(set.reach).toBe(200000);
+ });
+});
diff --git a/sdk/tests/worldgen-rules-asset.test.ts b/sdk/tests/worldgen-rules-asset.test.ts
index be0b35717..fbde432d4 100644
--- a/sdk/tests/worldgen-rules-asset.test.ts
+++ b/sdk/tests/worldgen-rules-asset.test.ts
@@ -38,3 +38,38 @@ describe('a world rules file', () => {
expect(isRulesFile('game:wilds')).toBe(false);
});
});
+
+describe('plants in a world rules file', () => {
+ const withPlants = () => {
+ 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 },
+ };
+ r.recipes[0].anchor = { id: 'oak', plant: 'oak', footprint: 8 };
+ delete r.recipes[0].anchor.mesh;
+ return r;
+ };
+
+ it('names the plants a member is, with their parts, far version and colourings', () => {
+ const rules = parseWorldRules(withPlants(), 'wilds.esworld');
+ expect(rules.recipes[0]!.anchor.plant).toBe('oak');
+ expect(rules.recipes[0]!.anchor.mesh).toBeUndefined();
+ const oak = rules.plants!.oak!;
+ expect(oak.parts).toHaveLength(2);
+ expect(oak.parts[1]!.lod1Mesh).toBe('assets/oak_crown1.esmesh');
+ expect(oak.far[0]!.mesh).toBe('assets/oak_cards.esmesh');
+ expect(oak.tints).toHaveLength(2);
+ expect(oak.sink).toBe(8);
+ });
+
+ it('is refused with where it went wrong', () => {
+ const bad = (patch: (r: any) => void) => { const r = withPlants(); patch(r); return () => parseWorldRules(r, 'wilds.esworld'); };
+ expect(bad((r) => { r.recipes[0].anchor.plant = 'elm'; })).toThrow(/no plant "elm"/);
+ 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) => { delete r.recipes[0].anchor.plant; })).toThrow(/mesh path, or a plant/);
+ });
+});
+
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 420cc7cc2..809fbbd44 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2822,6 +2822,18 @@ export const NOTED = {
{"note":"Foam is where waves burst, not along every shore."},
"fix(water): a gentle beach keeps less of the breakers' white than rock does":
{"note":"Foam is where waves burst, not along every shore."},
+ "fix(lod): a LODGroup with only a cull size is no longer ignored":
+ {"note":"A level-of-detail group with only a cull size is no longer ignored."},
+ "feat(terrain): each terrain layer says how it meets the others, and the terrain's paint and bounds can be asked":
+ {"note":"Each terrain layer says how it meets the others."},
+ "feat(editor): a terrain layer's height blend, and a recipe member's plant":
+ {"note":"Each terrain layer says how it meets the others."},
+ "feat(foliage): PlacedFoliage keeps hand-placed plants as data in one entity, grown a cell at a time":
+ {"note":"Placed plants."},
+ "feat(worldgen): recipes place plants, grown a cell at a time with far versions, and a world on an area ends where the terrain does":
+ {"note":"A generated world's plants."},
+ "feat(examples): Terrain & Water grows its plants from world rules and the lakewood art":
+ {"note":"A generated world's plants."},
"feat(terrain): up to eight terrain layers with normal and mask maps, from .esterrainlayer files, blended by height":
{"note":"Terrain layers: up to eight kinds of ground, each with its normal and mask maps."},
"feat(editor): terrain layer editor and a Terrain's list of layers":