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(foliage): a density map and a colour map - Foliage.densityMap says how many of the plants stand where, so flowers grow in drifts, and Foliage.colorMap colours them by where they stand, so one mesh and one material make a meadow of many colours

yhh7da472df7fd1
diff --git a/docs/astro/src/content/docs/graphics/foliage.mdx b/docs/astro/src/content/docs/graphics/foliage.mdx
index 0295ea0ff..daabdebbb 100644
--- a/docs/astro/src/content/docs/graphics/foliage.mdx
+++ b/docs/astro/src/content/docs/graphics/foliage.mdx
@@ -22,6 +22,8 @@ replaces it. Nothing is baked.
| `sizeX`, `sizeZ`, `cellSize` | The area, and the side of the cells it is cut into. |
| `count`, `seed` | Plants per cell, and the seed: another seed grows the same plants in other places. |
| `minScale`, `maxScale` | Each plant is given a size between these. |
+| `densityMap` | An image over the area whose red says how many of the plants stand where: none at black, all of `count` at white, a share between. Flowers in drifts, grass that thins toward a path. Its import Use is Data. Empty grows them everywhere. |
+| `colorMap`, `colorMapStrength`, `colorMapFrom` | A picture over the area that colours the plants by where they stand, mixed in by its alpha: pink flowers here, yellow there, from one mesh and one material. `colorMapFrom` is how far up a plant it begins (0 the whole plant; 0.8 only the top of a mesh whose vertex red rises to its petals). Needs a material; read each frame, so changing it grows nothing again. |
| `minUp`, `heightMin`, `heightMax` | Where plants grow: the least a place may face up (lower lets them onto slopes), and a band of world heights. |
| `waterDepth` | How deep under water a plant may stand: `0` (the default) keeps them on dry ground, reeds stand in the shallows. |
| `bladeHeight`, `bladeWidth` | Grass only: the size of a blade at scale 1. |
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 fc25fa029..f31415da5 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
@@ -16,6 +16,8 @@ description: 一个 Foliage 组件,把草或网格散布到一片区域或地形
| `sizeX`、`sizeZ`、`cellSize` | 区域,以及它被切成的格子的边长。 |
| `count`、`seed` | 每格的植物数,以及种子:换一个种子就在别处长出同样的植物。 |
| `minScale`、`maxScale` | 每棵植物的大小在这两者之间。 |
+| `densityMap` | 铺在区域上的一张图,红色通道说明哪里站多少植物:黑处没有,白处是 `count` 的全部,中间按比例。成片的花、朝小路变稀的草。导入用途是数据。留空则到处都长。 |
+| `colorMap`、`colorMapStrength`、`colorMapFrom` | 铺在区域上的一张图,按植物所在位置给它上色,按 alpha 混入:同一个网格和材质,这里是粉花、那里是黄花。`colorMapFrom` 是从植物多高处开始上色(0 为整株;0.8 只染顶部,要求网格的顶点红色通道向花瓣升高)。需要材质;每帧读取,改它不会重新生长。 |
| `minUp`、`heightMin`、`heightMax` | 植物在哪里生长:一个地方最少要朝上多少(调低能让植物长上斜坡),以及一段世界高度范围。 |
| `waterDepth` | 植物能站在水下多深:`0`(默认)让它们只长在干地上,芦苇则站在浅水里。 |
| `bladeHeight`、`bladeWidth` | 只对草:缩放为 1 时一根草叶的大小。 |
diff --git a/sdk/src/asset/textureUse.ts b/sdk/src/asset/textureUse.ts
index 96aa565c7..b1538ede4 100644
--- a/sdk/src/asset/textureUse.ts
+++ b/sdk/src/asset/textureUse.ts
@@ -13,6 +13,8 @@
export const DATA_TEXTURE_FIELDS: Readonly<Record<string, readonly string[]>> = {
// The splatmaps are weights, four a texel: a picture's clear-texel fill writes its neighbours' colour wherever the fourth is 0.
Terrain: ['heightmap', 'splatmap', 'splatmap2'],
+ // How many plants stand where: a number a texel.
+ Foliage: ['densityMap'],
};
/** Whether `component.field` reads its texture as numbers. */
diff --git a/sdk/src/foliage/cellBuild.ts b/sdk/src/foliage/cellBuild.ts
index 48ff75cb2..7f0f380d3 100644
--- a/sdk/src/foliage/cellBuild.ts
+++ b/sdk/src/foliage/cellBuild.ts
@@ -28,6 +28,7 @@ export interface CellSurroundings {
flatY: number;
water: { depthAt(x: number, z: number, y: number): number | null } | null;
zones: { excluding(x: number, z: number, radius: number, tags: readonly string[], seed: number): unknown } | null;
+ density?: DensityMap | null;
}
/** A blade's or a plant's own colours, where no material paints it. */
@@ -60,10 +61,42 @@ export interface FoliageCellSpec {
| { kind: 'mesh'; card: { u0: number; v0: number; u1: number; v1: number }; tent: boolean };
}
+/** How densely plants stand over an area, read from an image's red: 0 none, 255 as many as the field asks. Nothing grows off it. */
+export interface DensityMap {
+ width: number;
+ height: number;
+ values: Uint8Array;
+ /** The corner and the size of what the image covers, in the world. */
+ originX: number;
+ originZ: number;
+ sizeX: number;
+ sizeZ: number;
+}
+
+/** The share of plants that stand at (x, z), 0 to 1: the four texels about it blended. */
+export function densityAt(map: DensityMap, x: number, z: number): number {
+ const u = (x - map.originX) / map.sizeX, v = (z - map.originZ) / map.sizeZ;
+ if (!(u >= 0 && u <= 1 && v >= 0 && v <= 1)) return 0;
+ const fx = Math.min(u * map.width - 0.5, map.width - 1), fz = Math.min(v * map.height - 0.5, map.height - 1);
+ const x0 = Math.max(Math.floor(fx), 0), z0 = Math.max(Math.floor(fz), 0);
+ const x1 = Math.min(x0 + 1, map.width - 1), z1 = Math.min(z0 + 1, map.height - 1);
+ const tx = Math.min(Math.max(fx - x0, 0), 1), tz = Math.min(Math.max(fz - z0, 0), 1);
+ const at = (ix: number, iz: number): number => map.values[iz * map.width + ix]!;
+ return ((at(x0, z0) * (1 - tx) + at(x1, z0) * tx) * (1 - tz) + (at(x0, z1) * (1 - tx) + at(x1, z1) * tx) * tz) / 255;
+}
+
+/** A number from 0 to 1 that is a place's own, whichever cell or thread asks: which plants a density thins out. */
+function lot(x: number, z: number, seed: number): number {
+ let h = Math.imul(Math.floor(x * 64) | 0, 374761393) ^ Math.imul(Math.floor(z * 64) | 0, 668265263) ^ Math.imul(seed | 0, 2246822519);
+ h = Math.imul(h ^ (h >>> 13), 1274126177);
+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
+}
+
/** Where a plant may stand in a cell, as `scatterCell` asks it. */
export function cellGround(spec: FoliageCellSpec, around: CellSurroundings): Ground {
return (x, z) => {
if (around.zones?.excluding(x, z, Math.max(0, spec.zonePadding), spec.tags, spec.seed)) return null;
+ if (around.density && lot(x, z, spec.seed) >= densityAt(around.density, x, z)) return null;
// With a terrain, a plant stands where there is ground and nowhere else; with none, the area is flat at the entity's height.
const y = around.ground ? around.ground.heightAt(x, z) : around.flatY;
if (y === null) return null;
diff --git a/sdk/src/foliage/foliagePlugin.ts b/sdk/src/foliage/foliagePlugin.ts
index 8b85225c7..f387802f8 100644
--- a/sdk/src/foliage/foliagePlugin.ts
+++ b/sdk/src/foliage/foliagePlugin.ts
@@ -30,7 +30,8 @@ import { isEditor, isPlayMode } from '../ecs/env';
import type { Zones } from '../worldgen/zones';
import { installFoliageContacts } from './foliageContacts';
import { lodCullSizeWithin, lodSizeAtDistance, lodSphereRadius } from '../render/lodDistance';
-import { buildFoliageCell, type CellSurroundings, type FoliageCellSpec } from './cellBuild';
+import { buildFoliageCell, type CellSurroundings, type DensityMap, type FoliageCellSpec } from './cellBuild';
+import { imagePixelsAt } from '../terrain/layerArrays';
import { bakesOf } from '../runtime/bakes';
import { firstSend, forgetSent, planPool } from '../runtime/planPool';
import type { FoliageCellRequest, FoliageSurroundingsSpec } from '../worldgen/planWorker';
@@ -50,6 +51,14 @@ export interface FoliageData {
mesh: number;
/** A material on the Foliage shader, which makes the wind. Empty draws the plants in their own colours, still. */
material: number;
+ /** An image over the area whose red says how many of the plants stand where: none at 0, all the field asks at white. Empty grows them everywhere. */
+ densityMap: number;
+ /** A picture over the area that colours the plants by where they stand, mixed in by its alpha (the material's shader reads it). */
+ colorMap: number;
+ /** How much of the colour map is mixed in where its alpha is whole. */
+ colorMapStrength: number;
+ /** How far up a plant the colour map begins: 0 colours it whole, 0.6 only its top (a flower's head, on a mesh whose red rises to it). */
+ colorMapFrom: number;
/** The area, centred on the entity, and the side of the cells it is cut into. */
sizeX: number;
sizeZ: number;
@@ -95,17 +104,21 @@ export interface FoliageData {
* @experimental
*/
export const Foliage: ComponentDef<FoliageData> = defineComponent<FoliageData>('Foliage', {
- mesh: 0, material: 0,
+ mesh: 0, material: 0, densityMap: 0, colorMap: 0, colorMapStrength: 1, colorMapFrom: 0,
sizeX: 400, sizeZ: 400, cellSize: 40, count: 500, seed: 1,
minScale: 0.8, maxScale: 1.25, minUp: 0.7, heightMin: -100000, heightMax: 100000, waterDepth: 0,
bladeHeight: 14, bladeWidth: 1.6, lodDistance: 140, drawDistance: 420, castShadows: true,
zoneWorld: '', zoneTags: '', zonePadding: 0,
cardU0: 0, cardV0: 0, cardU1: 1, cardV1: 1, cardTent: 0,
}, {
- assetFields: [{ field: 'mesh', type: 'mesh' }, { field: 'material', type: 'material' }],
+ assetFields: [{ field: 'mesh', type: 'mesh' }, { field: 'material', type: 'material' }, { field: 'densityMap', type: 'texture' }, { field: 'colorMap', type: 'texture' }],
fields: {
mesh: { tooltip: 'The plant to scatter. Empty grows grass.', category: 'Plant' },
material: { tooltip: 'A material on the Foliage shader, which makes the wind. Empty draws the plants still, in their own colours.', category: 'Plant' },
+ densityMap: { tooltip: 'An image over the area whose red says how many of the plants stand where: none at black, all of them at white. Its Use is Data. Empty grows them everywhere.', category: 'Placement' },
+ colorMap: { tooltip: 'A picture over the area that colours the plants by where they stand, mixed in by its alpha. Needs a material.', category: 'Plant' },
+ colorMapStrength: { min: 0, max: 1, step: 0.01, slider: true, category: 'Plant', tooltip: 'How much of the colour map is mixed in where its alpha is whole.' },
+ colorMapFrom: { min: 0, max: 1, step: 0.01, slider: true, category: 'Plant', tooltip: 'How far up a plant the colour map begins: 0 colours it whole, higher only its top.' },
sizeX: { min: 1, category: 'Area', tooltip: 'World size along x, centred on this entity.' },
sizeZ: { min: 1, category: 'Area', tooltip: 'World size along z, centred on this entity.' },
cellSize: { min: 4, category: 'Area', tooltip: 'Side of the cells the area is cut into. Each is one mesh, culled whole.' },
@@ -137,6 +150,8 @@ interface BuiltFoliage {
signature: string;
data: FoliageData;
source: MeshData | null;
+ /** The density map's red, read once; null where the field has none. */
+ density: { width: number; height: number; values: Uint8Array } | null;
loading: boolean;
epoch: number;
/** What its cells are being grown for now: a cell that lands for an earlier one is not put in the world. */
@@ -174,6 +189,8 @@ export class FoliageField {
/** @internal */ readonly built_ = new Map<Entity, BuiltFoliage>();
/** @internal The u_windStrength each material had before the weather's wind scaled it, to put back. */
readonly authoredWind_ = new Map<number, number>();
+ /** The materials a colour map is written to, so taking it off is written once. */
+ readonly washed_ = new Set<number>();
/** @internal */ app_: App | null = null;
@@ -235,13 +252,17 @@ export class FoliagePlugin implements Plugin {
const waiting = !!terrains?.loading || !!water?.baking;
for (const entity of app.world.getEntitiesWithComponents([Foliage, Transform])) {
const data = app.world.get(entity, Foliage) as FoliageData;
- const signature = JSON.stringify(data);
+ // The colour map is read by the material each frame: changing it grows nothing again.
+ const { colorMap: _c, colorMapStrength: _s, colorMapFrom: _f, ...grown } = data;
+ const signature = JSON.stringify(grown);
let built = field.built_.get(entity);
if (!built || built.signature !== signature) {
- built = { signature, data: { ...data }, source: null, loading: true, epoch: (built?.epoch ?? 0) + 1 };
+ built = { signature, data: { ...data }, source: null, density: null, loading: true, epoch: (built?.epoch ?? 0) + 1 };
field.built_.set(entity, built);
void this.start(app, built);
}
+ built.data = { ...data };
+ this.wash(app, entity, data);
const zones = zonesOf(app, data.zoneWorld);
this.layer(app, entity, built, `${revision}:${zones?.revision ?? 0}`, waiting);
}
@@ -303,6 +324,17 @@ export class FoliagePlugin implements Plugin {
built.source = await app.getResource(Assets).readMeshData(data.mesh);
if (!built.source) log.warn('foliage', `the geometry of mesh ${data.mesh} cannot be read, so its plants are grass instead`);
}
+ if (data.densityMap) {
+ const path = app.getResource(Assets).pathForHandle('texture', data.densityMap);
+ const image = path ? await imagePixelsAt(app, path) : null;
+ if (image) {
+ const values = new Uint8Array(image.width * image.height);
+ for (let i = 0; i < values.length; i++) values[i] = image.pixels[i * 4]!;
+ built.density = { width: image.width, height: image.height, values };
+ } else {
+ log.warn('foliage', `the density map (texture ${data.densityMap}) cannot be read, so its plants grow everywhere`);
+ }
+ }
} catch (e) {
log.error('foliage', 'growing the foliage failed', e);
} finally {
@@ -342,6 +374,30 @@ export class FoliagePlugin implements Plugin {
});
}
+ /** The field's density map where it lies in the world: over the whole area. */
+ private densityOf(app: App, entity: Entity, built: BuiltFoliage): DensityMap | null {
+ const t = app.world.tryGet(entity, Transform) as TransformData | null;
+ if (!built.density || !t) return null;
+ const sizeX = built.data.sizeX * (t.worldScale.x || 1), sizeZ = built.data.sizeZ * (t.worldScale.z || 1);
+ return { ...built.density, originX: t.worldPosition.x - sizeX / 2, originZ: t.worldPosition.z - sizeZ / 2, sizeX, sizeZ };
+ }
+
+ /** Writes the colour map to the field's material: the picture, where it lies and how much of it. */
+ private wash(app: App, entity: Entity, data: FoliageData): void {
+ if (!data.material) return;
+ const field = app.getResource(FoliageRes);
+ const t = app.world.tryGet(entity, Transform) as TransformData | null;
+ const strength = data.colorMap && t ? data.colorMapStrength : 0;
+ if (strength > 0 && t) {
+ const sizeX = data.sizeX * (t.worldScale.x || 1), sizeZ = data.sizeZ * (t.worldScale.z || 1);
+ Material.setUniform(data.material, 'u_colorMap', Material.tex(data.colorMap));
+ Material.setUniform(data.material, 'u_colorMapArea', { x: t.worldPosition.x - sizeX / 2, y: t.worldPosition.z - sizeZ / 2, z: sizeX, w: sizeZ });
+ Material.setUniform(data.material, 'u_colorMapFrom', data.colorMapFrom);
+ }
+ if (strength > 0 || field.washed_.has(data.material)) Material.setUniform(data.material, 'u_colorMapStrength', strength);
+ if (strength > 0) field.washed_.add(data.material); else field.washed_.delete(data.material);
+ }
+
private cellsAcross(data: FoliageData): { x: number; z: number } {
return foliageCellsAcross(data.sizeX, data.sizeZ, data.cellSize);
}
@@ -365,7 +421,8 @@ export class FoliagePlugin implements Plugin {
const waterData = water?.queryData?.() ?? null;
if (water && !waterData && !water.empty) return none();
const zones = zonesOf(app, built.data.zoneWorld);
- const around = (): FoliageSurroundingsSpec => ({ ground, flatY, water: waterData, zones: zones ? [...zones.all()] : [] });
+ const density = this.densityOf(app, entity, built);
+ const around = (): FoliageSurroundingsSpec => ({ ground, flatY, water: waterData, zones: zones ? [...zones.all()] : [], density });
const source = built.source;
const sourceKey = source ? `${key}:mesh` : undefined;
const grow = (cell: FoliageCellSpec): Promise<MeshData[]> => {
@@ -423,6 +480,7 @@ export class FoliagePlugin implements Plugin {
const here = (): MeshData[] => {
const around: CellSurroundings = {
ground: hasTerrain ? terrains! : null, flatY: t.worldPosition.y, water: waterOf(app), zones: zonesOf(app, data.zoneWorld),
+ density: this.densityOf(app, parent, built),
};
return buildFoliageCell(spec, around, built.source);
};
diff --git a/sdk/src/foliage/foliageShader.ts b/sdk/src/foliage/foliageShader.ts
index e7f77f785..d68e5846f 100644
--- a/sdk/src/foliage/foliageShader.ts
+++ b/sdk/src/foliage/foliageShader.ts
@@ -21,6 +21,12 @@ const FOLIAGE = `#pragma shader "Foliage"
#pragma param u_useTexture float default(0) range(0,1) ui(slider)
#pragma param u_alphaCutoff float default(0.5) range(0,1) ui(slider)
#pragma coverage u_alphaCutoff
+// A picture over the field that colours the plants by where they stand (the Foliage component writes it): mixed in by its alpha, from
+// u_colorMapFrom up the plant, over the area whose corner and size u_colorMapArea is.
+#pragma param u_colorMap texture default(white)
+#pragma param u_colorMapStrength float default(0) range(0,1) ui(slider)
+#pragma param u_colorMapFrom float default(0) range(0,1) ui(slider)
+#pragma param u_colorMapArea vec4 default(0,0,1,1)
#pragma param u_roughness float default(0.8) range(0,1) ui(slider)
// Light that comes through a leaf from behind, and how thick the leaf is.
#pragma param u_translucency float default(0.5) range(0,1) ui(slider)
@@ -176,6 +182,14 @@ void main() {
if (alpha <= 0.0) discard;
alpha = min(alpha, 1.0);
}
+#ifdef MESH_NORMALS
+ if (u_colorMapStrength > 0.0) {
+ vec2 over = (P.xz + u_renderOrigin.xz - u_colorMapArea.xy) / max(u_colorMapArea.zw, vec2(1e-4));
+ vec4 wash = textureLod(u_colorMap, over, 0.0);
+ float up = u_colorMapFrom > 0.0 ? smoothstep(u_colorMapFrom * 0.8, u_colorMapFrom, height) : 1.0;
+ albedo = mix(albedo, wash.rgb, wash.a * u_colorMapStrength * up);
+ }
+#endif
albedo *= light;
SurfaceExt ext = surfaceExtNone(N);
if (u_translucency > 0.0) {
@@ -239,6 +253,15 @@ fn packNormal(n : vec3f) -> vec2f {
if (alpha <= 0.0) { discard; }
alpha = min(alpha, 1.0);
}
+#ifdef MESH_NORMALS
+ if (mc.u_colorMapStrength > 0.0) {
+ let over = (P.xz + frame.renderOrigin.xz - mc.u_colorMapArea.xy) / max(mc.u_colorMapArea.zw, vec2f(1e-4));
+ let wash = textureSampleLevel(u_colorMap, u_colorMap_s, over, 0.0);
+ var up = 1.0;
+ if (mc.u_colorMapFrom > 0.0) { up = smoothstep(mc.u_colorMapFrom * 0.8, mc.u_colorMapFrom, height); }
+ albedo = mix(albedo, wash.rgb, vec3f(wash.a * mc.u_colorMapStrength * up));
+ }
+#endif
albedo = albedo * light;
var ext = surfaceExtNone(N);
if (mc.u_translucency > 0.0) {
diff --git a/sdk/src/worldgen/planWorker.ts b/sdk/src/worldgen/planWorker.ts
index 6be91c33e..9522e9bc5 100644
--- a/sdk/src/worldgen/planWorker.ts
+++ b/sdk/src/worldgen/planWorker.ts
@@ -30,7 +30,7 @@ import { faceOf, type SphereNode } from '../terrain/sphere';
import { makePlanetPage, type PlanetPageSource } from '../terrain/planetPages';
import { makePage, type PageImage } from '../terrain/pages';
import type { MeshData } from '../asset/meshFormat';
-import { buildFoliageCell, cellTransfers, type CellSurroundings, type FoliageCellSpec } from '../foliage/cellBuild';
+import { buildFoliageCell, cellTransfers, type CellSurroundings, type DensityMap, type FoliageCellSpec } from '../foliage/cellBuild';
/** What a plan is made from: everything the main thread knew when it made its own. */
export interface PlanSpec {
@@ -221,6 +221,7 @@ export interface FoliageSurroundingsSpec {
flatY: number;
water: WaterQueryData | null;
zones: ZoneDef[];
+ density?: DensityMap | null;
}
/** A cell of a Foliage to grow. */
@@ -249,7 +250,7 @@ export function foliageCell(r: FoliageCellRequest): { result: MeshData[]; transf
for (const z of r.around.zones) zones.set(z);
around = {
ground: r.around.ground ? new GroundQuery(r.around.ground) : null, flatY: r.around.flatY,
- water: r.around.water ? new WaterQuery(r.around.water) : null, zones,
+ water: r.around.water ? new WaterQuery(r.around.water) : null, zones, density: r.around.density ?? null,
};
surroundings.set(r.key, around);
if (surroundings.size > SURROUNDINGS_KEPT) surroundings.delete(surroundings.keys().next().value!);
diff --git a/sdk/tests/foliage-density.test.ts b/sdk/tests/foliage-density.test.ts
new file mode 100644
index 000000000..f2ed8f798
--- /dev/null
+++ b/sdk/tests/foliage-density.test.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A Foliage's density map: how many of the plants stand where, the same whichever cell or thread asks.
+ */
+import { describe, expect, it } from 'vitest';
+import { cellGround, densityAt, type CellSurroundings, type DensityMap, type FoliageCellSpec } from '../src/foliage/cellBuild';
+import { readsTextureAsNumbers } from '../src/asset/textureUse';
+
+const map = (values: number[], width: number, height: number): DensityMap =>
+ ({ width, height, values: new Uint8Array(values), originX: -50, originZ: -50, sizeX: 100, sizeZ: 100 });
+const spec = { seed: 3, zonePadding: 0, tags: ['foliage'], waterDepth: 0 } as unknown as FoliageCellSpec;
+const around = (density: DensityMap | null): CellSurroundings => ({ ground: null, flatY: 7, water: null, zones: null, density });
+const standing = (density: DensityMap | null, from = -50, to = 50): number => {
+ const ground = cellGround(spec, around(density));
+ let n = 0;
+ for (let i = 0; i < 4000; i++) {
+ const x = from + ((i * 0.6180339887) % 1) * (to - from), z = -50 + ((i * 0.7548776662) % 1) * 100;
+ if (ground(x, z)) n++;
+ }
+ return n / 4000;
+};
+
+describe('a density map', () => {
+ it('is read by where a place is on the area, blended between texels, and is nothing off it', () => {
+ const m = map([0, 255], 2, 1);
+ expect(densityAt(m, -50, 0)).toBeCloseTo(0, 6);
+ expect(densityAt(m, 50, 0)).toBeCloseTo(1, 6);
+ expect(densityAt(m, 0, 0)).toBeCloseTo(0.5, 6);
+ expect(densityAt(m, 51, 0)).toBe(0);
+ expect(densityAt(m, 0, -50.5)).toBe(0);
+ });
+
+ it('lets every plant stand where it is white, none where it is black, and its share between', () => {
+ expect(standing(null)).toBe(1);
+ expect(standing(map([255], 1, 1))).toBe(1);
+ expect(standing(map([0], 1, 1))).toBe(0);
+ expect(standing(map([128], 1, 1))).toBeGreaterThan(0.44);
+ expect(standing(map([128], 1, 1))).toBeLessThan(0.56);
+ // Black on the left, white on the right: the plants are on the right.
+ const split = map([0, 0, 255, 255], 4, 1);
+ expect(standing(split, -50, -20)).toBe(0);
+ expect(standing(split, 20, 50)).toBe(1);
+ });
+
+ it('thins the same plants whichever cell asks: a place keeps its own lot', () => {
+ const half = map([128], 1, 1);
+ const a = cellGround({ ...spec, cellKey: 1 } as FoliageCellSpec, around(half)), b = cellGround({ ...spec, cellKey: 9 } as FoliageCellSpec, around(half));
+ for (let i = 0; i < 200; i++) {
+ const x = -40 + i * 0.37, z = 12 - i * 0.21;
+ expect(a(x, z) === null).toBe(b(x, z) === null);
+ }
+ // Another seed is another field's plants.
+ const other = cellGround({ ...spec, seed: 4 } as FoliageCellSpec, around(half));
+ let differs = 0;
+ for (let i = 0; i < 200; i++) if ((a(-40 + i * 0.37, 3) === null) !== (other(-40 + i * 0.37, 3) === null)) differs++;
+ expect(differs).toBeGreaterThan(40);
+ });
+
+ it('is numbers: a Foliage\'s density map is imported as Data', () => {
+ expect(readsTextureAsNumbers('Foliage', 'densityMap')).toBe(true);
+ expect(readsTextureAsNumbers('Foliage', 'colorMap')).toBe(false);
+ });
+});
diff --git a/sdk/tests/texture-use.test.ts b/sdk/tests/texture-use.test.ts
index 1aa1cc7c6..f1ce65032 100644
--- a/sdk/tests/texture-use.test.ts
+++ b/sdk/tests/texture-use.test.ts
@@ -3,10 +3,11 @@
import { describe, expect, it } from 'vitest';
import { DATA_TEXTURE_FIELDS, readsTextureAsNumbers } from '../src/asset/textureUse';
import { Terrain } from '../src/terrain/terrainPlugin';
+import { Foliage } from '../src/foliage/foliagePlugin';
describe('the fields that read a texture as numbers', () => {
it('are texture fields their components declare', () => {
- const declared: Record<string, { assetFields?: Array<{ field: string; type: string }> }> = { Terrain: Terrain as never };
+ const declared: Record<string, { assetFields?: Array<{ field: string; type: string }> }> = { Terrain: Terrain as never, Foliage: Foliage as never };
for (const [component, fields] of Object.entries(DATA_TEXTURE_FIELDS)) {
const assets = (declared[component] as unknown as { assetFields?: Array<{ field: string; type: string }> }).assetFields ?? [];
for (const field of fields) expect(assets.some((a) => a.field === field && a.type === 'texture'), `${component}.${field}`).toBe(true);