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): far versions that thin plant by plant and are grown only where they are drawn - up to three, each the same plants fewer and larger, chosen by each plant's own number so nothing jumps where one takes over; with a material each is a layer of cells of its own, so a meadow is whole near the eye and a tenth of itself far off, and it fades to none at its draw distance

yhh69180a56ff2d
diff --git a/docs/astro/src/content/docs/graphics/foliage.mdx b/docs/astro/src/content/docs/graphics/foliage.mdx
index daabdebbb..67fb870e4 100644
--- a/docs/astro/src/content/docs/graphics/foliage.mdx
+++ b/docs/astro/src/content/docs/graphics/foliage.mdx
@@ -27,7 +27,9 @@ replaces it. Nothing is baked.
| `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. |
-| `lodDistance`, `drawDistance` | Past the first a cell is drawn as its far version; past the second it is not drawn. |
+| `lodDistance`, `drawDistance` | Past the first a cell is drawn as its first far version; past the second it is not drawn, and its plants have thinned to none by then, one by one, so the field has no edge. |
+| `farLevels`, `farKeep`, `farStep`, `farGrow` | The far versions: how many (1 to 3), the share of its plants each keeps of the one before (0.34), how many times further out each takes over than the last (2), and the most a kept plant is grown by to cover the ground of those left out (2). Every plant has a number of its own; they thin by it with distance, and a far version holds exactly the plants still drawn where it takes over, so nothing jumps at the switch. With a material each version is a layer of cells of its own, grown only as far out as it is drawn: the full meadow exists near the eye and a tenth of it far off. |
+| `farCards` | A mesh's far version is crossed cards of its texture (on: a tree) or the plant itself, fewer and larger (off: a flower, a fern). |
| `cardU0`, `cardV0`, `cardU1`, `cardV1` | A mesh's far version is two crossed cards showing this rectangle of its texture (`cardTent` `1` cuts them as tents, a conifer's outline, instead of rectangles). |
If the scene has a [Terrain](/docs/graphics/terrain/), plants stand on it, keep off what is too steep, and wait for it to be built; with none, the
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 f31415da5..3ada281ae 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
@@ -21,7 +21,9 @@ description: 一个 Foliage 组件,把草或网格散布到一片区域或地形
| `minUp`、`heightMin`、`heightMax` | 植物在哪里生长:一个地方最少要朝上多少(调低能让植物长上斜坡),以及一段世界高度范围。 |
| `waterDepth` | 植物能站在水下多深:`0`(默认)让它们只长在干地上,芦苇则站在浅水里。 |
| `bladeHeight`、`bladeWidth` | 只对草:缩放为 1 时一根草叶的大小。 |
-| `lodDistance`、`drawDistance` | 超过前者,格子用它的远景版本绘制;超过后者就不画。 |
+| `lodDistance`、`drawDistance` | 超过前者,格子画成第一级远景;超过后者不再绘制,到那里植物已经一株一株稀到没有,所以这片植被没有边界线。 |
+| `farLevels`、`farKeep`、`farStep`、`farGrow` | 远景各级:有几级(1 到 3)、每级保留上一级植物的份额(0.34)、每级比上一级远多少倍接管(2)、保留下来的植物最多放大多少来盖住被去掉的那些的地面(2)。每株植物有自己的一个号码,随距离按它变稀;某一级远景在它接管的地方恰好就是那时还画着的那些植物,所以换级时不会跳。有材质时每一级是各自的一层格子,只长到它被画到的距离:完整的草甸只存在于眼前,远处只有十分之一。 |
+| `farCards` | 网格的远景是用它的贴图做的交叉面片(开:树),还是植物本身、更少更大(关:花、蕨)。 |
| `cardU0`、`cardV0`、`cardU1`、`cardV1` | 网格的远景版本是两张交叉的卡片,显示它纹理的这个矩形(`cardTent` 为 `1` 时卡片裁成帐篷形,即针叶树的轮廓,而不是矩形)。 |
如果场景里有 [Terrain](/docs/zh-cn/graphics/terrain/),植物就站在它上面,避开太陡的地方,并等它构建完;没有地形时,区域是实体所在高度的平地。
diff --git a/sdk/src/foliage/builder.ts b/sdk/src/foliage/builder.ts
index d8ffe3b56..9c739045f 100644
--- a/sdk/src/foliage/builder.ts
+++ b/sdk/src/foliage/builder.ts
@@ -88,8 +88,13 @@ export function scatterCell(p: ScatterParams, ground: Ground): Plant[] {
return out;
}
+/** A band as a colour's alpha: thirds, which a byte holds exactly; 1 where there is none (the shader is then told there are no bands). */
+const bandAlpha = (band: number | undefined): number => (band === undefined ? 1 : Math.min(Math.max(Math.round(band), 0), 3) / 3);
+
/** The vertices a patch is made of, before they are packed. */
interface Builder {
+ /** What every vertex's colour carries in its alpha: which far version the mesh is (see BladeParams.band). */
+ alpha: number;
pos: number[];
uv: number[];
color: number[];
@@ -97,13 +102,13 @@ interface Builder {
idx: number[];
}
-const newBuilder = (): Builder => ({ pos: [], uv: [], color: [], nrm: [], idx: [] });
+const newBuilder = (alpha = 1): Builder => ({ alpha, pos: [], uv: [], color: [], nrm: [], idx: [] });
function vertex(b: Builder, x: number, y: number, z: number, u: number, v: number,
r: number, g: number, bl: number, nx: number, ny: number, nz: number): number {
b.pos.push(x, y, z);
b.uv.push(u, v);
- b.color.push(r, g, bl, 1);
+ b.color.push(r, g, bl, b.alpha);
b.nrm.push(nx, ny, nz);
return b.pos.length / 3 - 1;
}
@@ -148,6 +153,8 @@ export interface BladeParams {
thin: number;
/** Paint a colour the plain material shows, instead of the wind's weights. */
paint?: { base: [number, number, number]; tip: [number, number, number] } | null;
+ /** Which version of its cell this mesh is, 0 the near one to 3, written to every vertex for the Foliage shader to draw it only in its own band of distances. Absent: drawn at any. */
+ band?: number;
}
/**
@@ -155,7 +162,7 @@ export interface BladeParams {
* so a meadow is lit as one surface and not as ten thousand knives.
*/
export function buildGrassMesh(plants: readonly Plant[], blade: BladeParams): MeshData {
- const b = newBuilder();
+ const b = newBuilder(bandAlpha(blade.band));
const segments = Math.max(1, Math.floor(blade.segments));
const thin = Math.max(1, Math.floor(blade.thin));
const widen = Math.sqrt(thin);
@@ -216,8 +223,8 @@ function reader(mesh: MeshData, semantic: number, components: number): ((v: numb
* Copies of a mesh, one per plant, as one mesh: placed, turned about the vertical and scaled, with the wind's weights painted by how
* high each vertex stands on its own copy (a tree's trunk hardly moves, its crown does).
*/
-export function buildInstancedMesh(source: MeshData, plants: readonly Plant[], paint?: BladeParams['paint']): MeshData {
- const b = newBuilder();
+export function buildInstancedMesh(source: MeshData, plants: readonly Plant[], paint?: BladeParams['paint'], band?: number): MeshData {
+ const b = newBuilder(bandAlpha(band));
const readPosition = reader(source, MeshChannel.Position, 3);
const readNormal = reader(source, MeshChannel.Normal, 3);
const readUv = reader(source, MeshChannel.TexCoord0, 2);
@@ -357,6 +364,21 @@ export function softenNormals(source: MeshData, amount: number): MeshData {
return { ...source, vertices };
}
+/**
+ * The plants a far version keeps when it keeps a share `keep` of them: those whose own number (`phase`) is under it, each grown so the
+ * ground they cover is what it was, to `most` times at most. By the plant's number and not its place in the list, because that number is
+ * what the Foliage shader thins by: the version that takes over at a distance holds exactly the plants still drawn there. `slack` keeps a
+ * few more, for the stretch either side of the switch where the two versions trade places.
+ */
+export function rankedPlants(plants: readonly Plant[], keep: number, most: number, slack = 1.25): readonly Plant[] {
+ const share = Math.min(Math.max(keep, 1e-3), 1);
+ if (share >= 1) return plants;
+ const grow = Math.min(Math.sqrt(1 / share), Math.max(most, 1));
+ const out: Plant[] = [];
+ for (const p of plants) if (p.phase < share * slack) out.push({ ...p, scale: p.scale * grow });
+ return out;
+}
+
/**
* The plants a far version draws, when it draws a share `keep` of them (above 0 to 1): every n-th, n the nearest whole number to 1 / keep, each grown by the
* square root of n (to a most of twice) so the ground they cover is what it was. The same plants every time: what is kept is a matter of order.
diff --git a/sdk/src/foliage/cellBuild.ts b/sdk/src/foliage/cellBuild.ts
index 7f0f380d3..4d810aee4 100644
--- a/sdk/src/foliage/cellBuild.ts
+++ b/sdk/src/foliage/cellBuild.ts
@@ -13,7 +13,7 @@
* provider). One implementation is also why the two cannot come to disagree about a cell.
*/
import type { MeshData } from '../asset/meshFormat';
-import { buildBillboardMesh, buildGrassMesh, buildInstancedMesh, scatterCell, type Ground } from './builder';
+import { buildBillboardMesh, buildGrassMesh, rankedPlants, buildInstancedMesh, scatterCell, type Ground } from './builder';
/** The ground a cell's plants stand on, as the terrain answers it. */
export interface CellGround {
@@ -56,6 +56,12 @@ export interface FoliageCellSpec {
/** The Foliage entity's height: the plants carry the ground's height relative to it. */
baseY: number;
paint: CellPaint;
+ /**
+ * The far versions: how many there are (1 to 3), the share of its plants each keeps of the one before, the most a kept plant is
+ * grown by, and whether a mesh's far version is cards (a tree) or the plant itself, fewer and larger. With `only`, the cell is that one
+ * version alone (0 the near one), marked with its band: each version is then a layer of cells of its own, grown only as far out as it is drawn.
+ */
+ far: { levels: number; keep: number; grow: number; cards: boolean; only?: number | null };
/** Grass, as blades of this size; or copies of a mesh, with the card its far version is drawn as. */
look: { kind: 'grass'; bladeHeight: number; bladeWidth: number }
| { kind: 'mesh'; card: { u0: number; v0: number; u1: number; v1: number }; tent: boolean };
@@ -121,16 +127,41 @@ export function buildFoliageCell(spec: FoliageCellSpec, around: CellSurroundings
if (plants.length === 0) return [];
// The cell stands at its centre, on the entity's own base height; the plants carry the ground's height relative to that.
for (const p of plants) p.y -= spec.baseY;
- if (spec.look.kind === 'mesh') {
- if (!source) throw new Error('a cell of copies needs the mesh it copies');
- const width = Math.max(source.aabbMax[0] - source.aabbMin[0], source.aabbMax[2] - source.aabbMin[2]);
- return [
- buildInstancedMesh(source, plants, spec.paint),
- buildBillboardMesh(plants, width, source.aabbMax[1] - source.aabbMin[1], spec.look.card, spec.paint, spec.look.tent),
- ];
+ const levels = Math.min(Math.max(Math.floor(spec.far.levels), 1), 3);
+ const share = (level: number): number => Math.pow(Math.min(Math.max(spec.far.keep, 0.01), 1), level);
+ const wider = (level: number): number => Math.min(Math.sqrt(1 / share(level)), Math.max(spec.far.grow, 1));
+ const only = spec.far.only ?? null;
+ const band = only === null ? undefined : only;
+ const copies = (level: number): MeshData | null => {
+ const kept = level === 0 ? plants : rankedPlants(plants, share(level), spec.far.grow);
+ return kept.length === 0 ? null : buildInstancedMesh(source!, kept, spec.paint, band);
+ };
+ // A far blade is one quad, a little taller and as much wider as covers the ground of the ones left out: grass grows broader, not higher.
+ const blades = (level: number): MeshData | null => {
+ if (spec.look.kind !== 'grass') return null;
+ const blade = { height: spec.look.bladeHeight, width: spec.look.bladeWidth, paint: spec.paint, band };
+ if (level === 0) return buildGrassMesh(plants, { ...blade, segments: 3, thin: 1 });
+ const kept = rankedPlants(plants, share(level), 1);
+ return kept.length === 0 ? null : buildGrassMesh(kept, { ...blade, height: blade.height * 1.1, width: blade.width * wider(level), segments: 1, thin: 1 });
+ };
+ if (spec.look.kind === 'mesh' && !source) throw new Error('a cell of copies needs the mesh it copies');
+ const version = spec.look.kind === 'mesh' ? copies : blades;
+ if (only !== null) {
+ const mesh = version(Math.min(Math.max(Math.floor(only), 0), levels));
+ return mesh ? [mesh] : [];
+ }
+ if (spec.look.kind === 'mesh' && spec.far.cards) {
+ const width = Math.max(source!.aabbMax[0] - source!.aabbMin[0], source!.aabbMax[2] - source!.aabbMin[2]);
+ return [copies(0)!, buildBillboardMesh(plants, width, source!.aabbMax[1] - source!.aabbMin[1], spec.look.card, spec.paint, spec.look.tent)];
}
- const blade = { height: spec.look.bladeHeight, width: spec.look.bladeWidth, paint: spec.paint };
- return [buildGrassMesh(plants, { ...blade, segments: 3, thin: 1 }), buildGrassMesh(plants, { ...blade, segments: 1, thin: 3 })];
+ // A far version with no plant left is the end of them: past the last, the cell draws nothing.
+ const out: MeshData[] = [];
+ for (let level = 0; level <= levels; level++) {
+ const mesh = version(level);
+ if (!mesh) break;
+ out.push(mesh);
+ }
+ return out;
}
/** The buffers of a cell's meshes, to hand them between threads without a copy. */
diff --git a/sdk/src/foliage/foliagePlugin.ts b/sdk/src/foliage/foliagePlugin.ts
index f387802f8..685a28883 100644
--- a/sdk/src/foliage/foliagePlugin.ts
+++ b/sdk/src/foliage/foliagePlugin.ts
@@ -57,6 +57,16 @@ export interface FoliageData {
colorMap: number;
/** How much of the colour map is mixed in where its alpha is whole. */
colorMapStrength: number;
+ /** How many far versions a cell has, 1 to 3: each is the same plants, fewer and larger, and takes over `farStep` times further out than the last. */
+ farLevels: number;
+ /** The share of its plants each far version keeps of the one before. They thin to it plant by plant before it takes over, so nothing jumps. */
+ farKeep: number;
+ /** How many times further out each far version takes over than the one before: the first at `lodDistance`. */
+ farStep: number;
+ /** The most a plant kept in a far version is grown by, to cover the ground the ones left out did. */
+ farGrow: number;
+ /** A mesh's far version is crossed cards of its texture (a tree). Off, it is the plant itself, fewer and larger (a flower). */
+ farCards: boolean;
/** 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. */
@@ -105,6 +115,7 @@ export interface FoliageData {
*/
export const Foliage: ComponentDef<FoliageData> = defineComponent<FoliageData>('Foliage', {
mesh: 0, material: 0, densityMap: 0, colorMap: 0, colorMapStrength: 1, colorMapFrom: 0,
+ farLevels: 1, farKeep: 0.34, farStep: 2, farGrow: 2, farCards: true,
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,
@@ -132,6 +143,11 @@ export const Foliage: ComponentDef<FoliageData> = defineComponent<FoliageData>('
waterDepth: { min: 0, category: 'Placement', tooltip: 'How deep under water a plant may stand. 0 keeps them on dry ground; reeds stand in the shallows.' },
bladeHeight: { min: 0.1, category: 'Grass', tooltip: 'Height of a blade at scale 1.' },
bladeWidth: { min: 0.01, category: 'Grass', tooltip: 'Width of a blade at its base, at scale 1.' },
+ farLevels: { min: 1, max: 3, step: 1, category: 'Distance', tooltip: 'How many far versions a cell has: each is the same plants, fewer and larger, and takes over further out than the last.' },
+ farKeep: { min: 0.1, max: 1, step: 0.01, slider: true, category: 'Distance', tooltip: 'The share of its plants each far version keeps of the one before. They thin to it plant by plant before it takes over.' },
+ farStep: { min: 1.2, max: 4, step: 0.05, category: 'Distance', tooltip: 'How many times further out each far version takes over than the one before. The first takes over at the LOD distance.' },
+ farGrow: { min: 1, max: 6, step: 0.1, category: 'Distance', tooltip: 'The most a plant kept in a far version is grown by, to cover the ground the ones left out did.' },
+ farCards: { category: 'Far version', tooltip: 'A mesh\'s far version is crossed cards of its texture (a tree). Off, it is the plant itself, fewer and larger (a flower).' },
lodDistance: { min: 1, category: 'Distance', tooltip: 'Past this a cell is drawn as its far version: fewer, broader blades, or a tree as crossed cards.' },
drawDistance: { min: 1, category: 'Distance', tooltip: 'Past this a cell is not drawn.' },
castShadows: { category: 'Distance', tooltip: 'Generated cells cast shadows. Turn off for dense short grass to avoid drawing every cell again into each shadow cascade. Lighting and received shadows remain.' },
@@ -182,7 +198,18 @@ function zonesOf(app: App, world: string | undefined): Zones | null {
}
/** The chunk layer a Foliage's cells are. */
-const layerOf = (entity: Entity): string => `foliage:${entity}`;
+/** The most far versions a cell has. */
+const FAR_LEVELS = 3;
+/** A field's layer of cells; with `level`, the layer of one version of them (0 the near one). */
+const layerOf = (entity: Entity, level = 0): string => (level === 0 ? `foliage:${entity}` : `foliage:${entity}:${level}`);
+/**
+ * Whether a field's versions are layers of their own, each grown only as far out as it is drawn and told apart by the shader: what a
+ * material makes possible, for grass and for a mesh whose far version is itself. Else a cell holds its versions and a LODGroup picks one.
+ */
+const farLevelsOf = (data: FoliageData, mesh: boolean): number =>
+ (data.material && (!mesh || !data.farCards) ? Math.min(Math.max(Math.floor(data.farLevels), 1), FAR_LEVELS) : 0);
+/** Where far version `level` (1 on) takes over from the one before. */
+const takesOverAt = (data: FoliageData, level: number): number => data.lodDistance * Math.pow(Math.max(data.farStep, 1.01), level - 1);
/** Run-time facts about the foliage the plugin has grown. */
export class FoliageField {
@@ -200,7 +227,10 @@ export class FoliageField {
/** How many cells near enough to be drawn, across every field, are still waiting to be grown. */
get pending(): number {
let n = 0;
- for (const [entity, b] of this.built_) n += (this.statusOf_(entity)?.pending ?? 0) + (b.loading ? 1 : 0);
+ for (const [entity, b] of this.built_) {
+ for (let level = 0; level <= FAR_LEVELS; level++) n += this.statusOf_(entity, level)?.pending ?? 0;
+ if (b.loading) n++;
+ }
return n;
}
@@ -208,15 +238,17 @@ export class FoliageField {
get cellCount(): number {
let n = 0;
for (const entity of this.built_.keys()) {
- const s = this.statusOf_(entity);
- if (s) n += s.ready + s.stale;
+ for (let level = 0; level <= FAR_LEVELS; level++) {
+ const s = this.statusOf_(entity, level);
+ if (s) n += s.ready + s.stale;
+ }
}
return n;
}
- private statusOf_(entity: Entity): ChunkLayerStatus | null {
+ private statusOf_(entity: Entity, level = 0): ChunkLayerStatus | null {
const app = this.app_;
- return app?.hasResource(ProceduralChunksRes) ? app.getResource(ProceduralChunksRes).status(layerOf(entity)) : null;
+ return app?.hasResource(ProceduralChunksRes) ? app.getResource(ProceduralChunksRes).status(layerOf(entity, level)) : null;
}
}
@@ -309,7 +341,7 @@ export class FoliagePlugin implements Plugin {
if (!app?.hasResource(FoliageRes)) return;
const field = app.getResource(FoliageRes);
for (const entity of field.built_.keys()) {
- if (app.hasResource(ProceduralChunksRes)) app.getResource(ProceduralChunksRes).remove(layerOf(entity));
+ if (app.hasResource(ProceduralChunksRes)) for (let level = 0; level <= FAR_LEVELS; level++) app.getResource(ProceduralChunksRes).remove(layerOf(entity, level));
}
field.built_.clear();
// What had come back and not landed is let go with the field: its cells are no longer anyone's.
@@ -354,24 +386,32 @@ export class FoliagePlugin implements Plugin {
const generation = `${built.epoch}:${revision}:${t.worldPosition.x}:${t.worldPosition.y}:${t.worldPosition.z}:${sx}:${sz}`;
built.generation = generation;
const away = waiting || built.loading ? null : this.awayFor(app, entity, built, revision, t.worldPosition.y);
- chunksOf(app).set<GrownCell>(layerOf(entity), {
- label: 'Growing the plants',
- // Made on the workers where they can be: the layer then takes none of the frame's budget to make, only to land.
- async: away !== null,
- originX: t.worldPosition.x - data.sizeX / 2 * sx, originZ: t.worldPosition.z - data.sizeZ / 2 * sz,
- sizeX: data.sizeX / cells.x * sx, sizeZ: data.sizeZ / cells.z * sz,
- extent: [0, 0, cells.x, cells.z],
- loadRadius: data.drawDistance,
- unloadRadius: data.drawDistance + Math.max(1, data.cellSize) * 1.5,
- generation,
- // Plants stand on the ground and keep out of the water: while either is still being made, they wait.
- make: (cx, cz, signal) => (waiting || built.loading ? null : this.grow(app, entity, built, cx, cz, away, generation, signal)),
- publish: (_cx, _cz, cell) => { if (cell.entity !== null) app.world.setParent(cell.entity, entity); },
- release: (_cx, _cz, cell) => {
- if (cell.entity !== null && app.world.valid(cell.entity)) app.world.despawn(cell.entity);
- for (const handle of cell.handles) assets.releaseBuiltMesh(handle);
- },
- });
+ const far = farLevelsOf(data, !!built.source);
+ const side = Math.max(1, data.cellSize);
+ for (let level = 0; level <= FAR_LEVELS; level++) {
+ if (level > far) { chunksOf(app).remove(layerOf(entity, level)); continue; }
+ // A version is grown as far out as it is drawn: to where the next takes over, and the last to the draw distance.
+ const reach = far === 0 || level === far ? data.drawDistance : Math.min(takesOverAt(data, level + 1) + side, data.drawDistance);
+ const only = far === 0 ? null : level;
+ chunksOf(app).set<GrownCell>(layerOf(entity, level), {
+ label: 'Growing the plants',
+ // Made on the workers where they can be: the layer then takes none of the frame's budget to make, only to land.
+ async: away !== null,
+ originX: t.worldPosition.x - data.sizeX / 2 * sx, originZ: t.worldPosition.z - data.sizeZ / 2 * sz,
+ sizeX: data.sizeX / cells.x * sx, sizeZ: data.sizeZ / cells.z * sz,
+ extent: [0, 0, cells.x, cells.z],
+ loadRadius: reach,
+ unloadRadius: reach + side * 1.5,
+ generation,
+ // Plants stand on the ground and keep out of the water: while either is still being made, they wait.
+ make: (cx, cz, signal) => (waiting || built.loading ? null : this.grow(app, entity, built, cx, cz, away, generation, signal, only)),
+ publish: (_cx, _cz, cell) => { if (cell.entity !== null) app.world.setParent(cell.entity, entity); },
+ release: (_cx, _cz, cell) => {
+ if (cell.entity !== null && app.world.valid(cell.entity)) app.world.despawn(cell.entity);
+ for (const handle of cell.handles) assets.releaseBuiltMesh(handle);
+ },
+ });
+ }
}
/** The field's density map where it lies in the world: over the whole area. */
@@ -448,7 +488,8 @@ export class FoliagePlugin implements Plugin {
* The geometry is made on a worker where `away` can make it, and the cell lands a frame or two later; else it is made here.
*/
private grow(app: App, parent: Entity, built: BuiltFoliage, cx: number, cz: number,
- away: ((cell: FoliageCellSpec) => Promise<MeshData[]>) | null = null, generation?: string, signal?: AbortSignal): GrownCell | Promise<GrownCell | null> | null {
+ away: ((cell: FoliageCellSpec) => Promise<MeshData[]>) | null = null, generation?: string, signal?: AbortSignal,
+ only: number | null = null): GrownCell | Promise<GrownCell | null> | null {
const world = app.world;
if (!world.valid(parent)) return null;
const data = built.data;
@@ -463,8 +504,15 @@ export class FoliagePlugin implements Plugin {
const sx = t.worldScale.x || 1, sz = t.worldScale.z || 1;
const worldX = t.worldPosition.x + localX * sx, worldZ = t.worldPosition.z + localZ * sz;
const hasTerrain = !!terrains && terrains.built_.size > 0;
- // Grass thins toward where its cells turn to their far version, so a near cell beside a far one is not three times as thick.
- if (data.material && !built.source) Material.setUniform(data.material, 'u_thinDistance', data.lodDistance);
+ // Plants thin, each by its own number, to what the next far version keeps before it takes over, and to none at the draw distance.
+ if (data.material) {
+ const thins = !built.source || !data.farCards;
+ Material.setUniform(data.material, 'u_thinLevels', farLevelsOf(data, !!built.source));
+ Material.setUniform(data.material, 'u_thinDistance', thins ? data.lodDistance : 0);
+ Material.setUniform(data.material, 'u_thinKeep', Math.min(Math.max(data.farKeep, 0.01), 1));
+ Material.setUniform(data.material, 'u_thinStep', Math.max(data.farStep, 1.01));
+ Material.setUniform(data.material, 'u_thinEnd', thins ? data.drawDistance : 0);
+ }
const spec: FoliageCellSpec = {
centerX: worldX, centerZ: worldZ, size: Math.min(side, data.sizeX / cells.x), count: Math.floor(data.count), seed: data.seed,
cellKey: cz * 1000 + cx, minScale: data.minScale, maxScale: data.maxScale, minUp: data.minUp,
@@ -473,6 +521,7 @@ export class FoliagePlugin implements Plugin {
tags: ['foliage', data.mesh ? 'tree' : 'grass', ...(data.zoneTags ?? '').split(',').map((s) => s.trim()).filter(Boolean)],
baseY: t.worldPosition.y,
paint: data.material ? null : { base: [0.14, 0.3, 0.08], tip: [0.55, 0.72, 0.25] },
+ far: { levels: data.farLevels, keep: data.farKeep, grow: data.farGrow, cards: data.farCards, only },
look: built.source
? { kind: 'mesh', card: { u0: data.cardU0, v0: data.cardV0, u1: data.cardU1, v1: data.cardV1 }, tent: data.cardTent === 1 }
: { kind: 'grass', bladeHeight: data.bladeHeight, bladeWidth: data.bladeWidth },
@@ -496,15 +545,15 @@ export class FoliagePlugin implements Plugin {
// Put in the world on a later frame, within its budget; not at all if the field has moved on while it was being made.
field.landed_.push(() => {
if (signal?.aborted || built.generation !== generation || !app.world.valid(parent)) { resolve(null); return; }
- try { resolve(this.land(app, built, cx, cz, localX, localZ, meshes ?? here())); } catch (e) { reject(e); }
+ try { resolve(this.land(app, built, cx, cz, localX, localZ, meshes ?? here(), only !== null)); } catch (e) { reject(e); }
});
}));
}
- return this.land(app, built, cx, cz, localX, localZ, here());
+ return this.land(app, built, cx, cz, localX, localZ, here(), only !== null);
}
/** Puts a cell's geometry in the world: its meshes on the GPU and the entity that draws them (its parent is set on publishing). */
- private land(app: App, built: BuiltFoliage, cx: number, cz: number, localX: number, localZ: number, meshes: MeshData[]): GrownCell {
+ private land(app: App, built: BuiltFoliage, cx: number, cz: number, localX: number, localZ: number, meshes: MeshData[], banded = false): GrownCell {
if (meshes.length === 0) return { entity: null, handles: [] };
const world = app.world, data = built.data;
const assets = app.getResource(Assets);
@@ -526,14 +575,17 @@ export class FoliagePlugin implements Plugin {
castShadows: data.castShadows !== false,
color: { r: 1, g: 1, b: 1, a: 1 },
} as Partial<MeshRendererData>);
- const lodDef = getComponent('LODGroup');
+ // A version that is a layer of its own is drawn in its band by its shader and let go with its layer: nothing picks among versions.
+ const lodDef = banded ? null : getComponent('LODGroup');
if (lodDef) {
// The component's distances as the screen sizes the engine compares, on the sphere it will measure: the one round the
// plants this cell grew, not round the cell — a cell with a few plants at one edge is a fraction of its own square.
const radius = lodSphereRadius(handles.length > 1 ? meshes : [meshes[0]]);
+ const step = Math.max(data.farStep, 1.01);
+ const sizeAt = (level: number): number => (handles[level] ? lodSizeAtDistance(radius, data.lodDistance * Math.pow(step, level - 1)) : 0);
world.insert(cell, lodDef, {
- lod1: handles[1] ?? 0, lod2: 0, lod3: 0,
- lod1Size: lodSizeAtDistance(radius, data.lodDistance), lod2Size: 0, lod3Size: 0,
+ lod1: handles[1] ?? 0, lod2: handles[2] ?? 0, lod3: handles[3] ?? 0,
+ lod1Size: sizeAt(1), lod2Size: sizeAt(2), lod3Size: sizeAt(3),
cullSize: lodCullSizeWithin(radius, data.drawDistance), hysteresis: 0.1, enabled: true,
});
}
@@ -543,7 +595,7 @@ export class FoliagePlugin implements Plugin {
private sweep(app: App, field: FoliageField): void {
for (const entity of field.built_.keys()) {
if (app.world.valid(entity) && app.world.has(entity, Foliage)) continue;
- if (app.hasResource(ProceduralChunksRes)) app.getResource(ProceduralChunksRes).remove(layerOf(entity));
+ if (app.hasResource(ProceduralChunksRes)) for (let level = 0; level <= FAR_LEVELS; level++) app.getResource(ProceduralChunksRes).remove(layerOf(entity, level));
field.built_.delete(entity);
}
}
diff --git a/sdk/src/foliage/foliageShader.ts b/sdk/src/foliage/foliageShader.ts
index d68e5846f..9b3940a63 100644
--- a/sdk/src/foliage/foliageShader.ts
+++ b/sdk/src/foliage/foliageShader.ts
@@ -16,6 +16,8 @@ const FOLIAGE = `#pragma shader "Foliage"
#pragma domain Lit
#pragma param u_baseColor color default(0.14,0.30,0.08,1)
#pragma param u_tipColor color default(0.55,0.72,0.25,1)
+// How far up the plant the tip's colour begins: 0 runs from the root (a blade), 0.85 keeps a stem the base colour under a head of the tip's.
+#pragma param u_tipFrom float default(0) range(0,0.99) ui(slider)
// A texture over the plant (leaves, bark), and whether it is used at all: grass is drawn from the two colours and wants none.
#pragma param u_albedo texture default(white)
#pragma param u_useTexture float default(0) range(0,1) ui(slider)
@@ -37,9 +39,16 @@ const FOLIAGE = `#pragma shader "Foliage"
#pragma param u_windDirection float default(40) range(0,360) ui(slider)
#pragma param u_gustScale float default(0.02) range(0.001,0.5) ui(slider)
#pragma param u_flutter float default(0.4) range(0,4) ui(slider)
-// Grass thins out toward the distance its cells switch to their far version (the Foliage component writes it; 0 thins nothing): each blade
-// by its own random key, down to the third the far version keeps, so a near cell beside a far one is not three times as dense.
+// Plants thin with distance, each by its own number (the Foliage component writes these; a thin distance of 0 thins nothing): the share
+// drawn falls as a power of the distance so that it is u_thinKeep where the first far version takes over (u_thinDistance), u_thinKeep of
+// that u_thinStep times further out, and so on, and none at u_thinEnd. Each far version holds the plants still drawn where it takes over.
#pragma param u_thinDistance float default(0) range(0,1000000) ui(slider)
+#pragma param u_thinKeep float default(0.34) range(0.01,1) ui(slider)
+#pragma param u_thinStep float default(2) range(1.01,8) ui(slider)
+#pragma param u_thinEnd float default(0) range(0,1000000) ui(slider)
+// How many far versions are layers of their own (0: none are, and a mesh is drawn at any distance): a mesh says which it is in its
+// colour's alpha, in thirds, and is drawn from where it takes over to where the next does.
+#pragma param u_thinLevels float default(0) range(0,3) ui(slider)
// How far plants part from what touches them, as a share of its reach. The four contacts are written each frame (a FoliageContact): where each is, and how far it reaches now.
#pragma param u_contactBend float default(0.7) range(0,2) ui(slider)
#pragma param u_contact0 vec4 default(0,0,0,0)
@@ -84,7 +93,15 @@ void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {
if (u_thinDistance > 0.0 && u_camera.w > 0.5) {
// Measured from the cell's centre, so every vertex of a blade agrees on whether it is kept.
vec3 cell = (esInstanceModel() * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
- float keep = mix(1.0, 0.34, smoothstep(u_thinDistance * 0.55, u_thinDistance, length(cell - u_camera.xyz)));
+ float away = max(length(cell - u_camera.xyz), 1e-3);
+ float keep = min(pow(u_thinDistance / (u_thinStep * away), log(1.0 / u_thinKeep) / log(u_thinStep)), 1.0);
+ if (u_thinEnd > 0.0) keep *= 1.0 - smoothstep(u_thinEnd * 0.85, u_thinEnd, away);
+ if (u_thinLevels > 0.5) {
+ float level = floor(es_vertexColor.a * 3.0 + 0.5);
+ float nearEdge = level < 0.5 ? 0.0 : u_thinDistance * pow(u_thinStep, level - 1.0);
+ float farEdge = level > u_thinLevels - 0.5 ? 1e30 : u_thinDistance * pow(u_thinStep, level);
+ if (away < nearEdge || away >= farEdge) keep = -1.0;
+ }
// Every vertex of a blade left out goes to one point: its triangles have no area and draw nothing.
if (es_vertexColor.g > keep) local = vec3(0.0);
}
@@ -126,7 +143,17 @@ fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, ve
(*local).y = (*local).y - abs(bend) * 0.35 * weight;
if (mc.u_thinDistance > 0.0 && frame.camera.w > 0.5) {
let cell = (esInstanceModel() * vec4f(0.0, 0.0, 0.0, 1.0)).xyz;
- let keep = mix(1.0, 0.34, smoothstep(mc.u_thinDistance * 0.55, mc.u_thinDistance, length(cell - frame.camera.xyz)));
+ let away = max(length(cell - frame.camera.xyz), 1e-3);
+ var keep = min(pow(mc.u_thinDistance / (mc.u_thinStep * away), log(1.0 / mc.u_thinKeep) / log(mc.u_thinStep)), 1.0);
+ if (mc.u_thinEnd > 0.0) { keep = keep * (1.0 - smoothstep(mc.u_thinEnd * 0.85, mc.u_thinEnd, away)); }
+ if (mc.u_thinLevels > 0.5) {
+ let level = floor(es_vertexColor.a * 3.0 + 0.5);
+ var nearEdge = 0.0;
+ if (level > 0.5) { nearEdge = mc.u_thinDistance * pow(mc.u_thinStep, level - 1.0); }
+ var farEdge = 1e30;
+ if (level < mc.u_thinLevels - 0.5) { farEdge = mc.u_thinDistance * pow(mc.u_thinStep, level); }
+ if (away < nearEdge || away >= farEdge) { keep = -1.0; }
+ }
if (es_vertexColor.g > keep) { *local = vec3f(0.0); }
}
}
@@ -173,7 +200,7 @@ void main() {
vec4 tex = texture(u_albedo, v_texCoord);
// Before the branch: a derivative needs every fragment of its quad.
float edgeA = fwidth(tex.a);
- vec3 albedo = mix(u_baseColor.rgb, u_tipColor.rgb, height);
+ vec3 albedo = mix(u_baseColor.rgb, u_tipColor.rgb, clamp((height - u_tipFrom) / (1.0 - u_tipFrom), 0.0, 1.0));
float alpha = 1.0;
if (u_useTexture > 0.5) {
albedo *= tex.rgb;
@@ -245,7 +272,7 @@ fn packNormal(n : vec3f) -> vec2f {
#endif
let height = clamp(v.v_color.r, 0.0, 1.0);
let light = v.v_color.b;
- var albedo = mix(mc.u_baseColor.rgb, mc.u_tipColor.rgb, vec3f(height));
+ var albedo = mix(mc.u_baseColor.rgb, mc.u_tipColor.rgb, vec3f(clamp((height - mc.u_tipFrom) / (1.0 - mc.u_tipFrom), 0.0, 1.0)));
var alpha = 1.0;
if (mc.u_useTexture > 0.5) {
albedo = albedo * tex.rgb;
diff --git a/sdk/src/runtime/planWorkerBundle.generated.ts b/sdk/src/runtime/planWorkerBundle.generated.ts
index 4478915f8..a6149d7d4 100644
--- a/sdk/src/runtime/planWorkerBundle.generated.ts
+++ b/sdk/src/runtime/planWorkerBundle.generated.ts
@@ -2,4 +2,4 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
// Generated by sdk/scripts/build-worker.mjs from src/worldgen/planWorker.ts: do not edit.
/** The planning worker's script: what a pool of planning workers is started from. */
-export const PLAN_WORKER_SOURCE = "(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=(e,t,n)=>{let r=Math.min(Math.max((n-e)/(t-e||1e-6),0),1);return r*r*(3-2*r)};function n(e,n,r){let i=t(r.rockSlope-.08,r.rockSlope+.08,1-n),a=t(r.snowHeight-.06,r.snowHeight+.06,e)*(1-i*.85),o=t(r.dirtHeight-.15,r.dirtHeight+.15,e)*(1-a)*(1-i),s=(1-i)*(1-a)*(1-o),c=s+o+a+i||1;return[s/c,o/c,a/c,i/c]}function r(e,t,n){let r=Math.min(Math.max(t,0),1)*(e.width-1),i=Math.min(Math.max(n,0),1)*(e.height-1),a=Math.min(Math.floor(r),e.width-2),o=Math.min(Math.floor(i),e.height-2),s=r-a,c=i-o,l=(t,n)=>e.data[n*e.width+t],u=l(a,o)+(l(a+1,o)-l(a,o))*s;return u+(l(a,o+1)+(l(a+1,o+1)-l(a,o+1))*s-u)*c}function i(e,t,n,i,a,o){let s=1/(e.width-1),c=1/(e.height-1),l=(r(e,t+s,n)-r(e,t-s,n))*o/(2*s*i),u=(r(e,t,n+c)-r(e,t,n-c))*o/(2*c*a),d=Math.hypot(l,1,u);return[-l/d,1/d,-u/d]}var a=class e{constructor(e,t,n,r,i=[0,t.height],a=null){this.field=e,this.data=t,this.splat=n,this.flow=r,this.splat2=a,this.infinite=!1,this.bounds=[-t.sizeX/2,-t.sizeZ/2,t.sizeX/2,t.sizeZ/2],[this.minHeight,this.maxHeight]=i}ensureSplats(e){let t=this.field,r=Math.min(t.width,1024),i=Math.min(t.height,1024);if(!this.splat){let e=new Uint8Array(r*i*4),t=this.data.sizeX,a=this.data.sizeZ;for(let o=0;o<i;o++)for(let s=0;s<r;s++){let c=(s/(r-1)-.5)*t,l=(o/(i-1)-.5)*a,u=this.height(c,l)??this.minHeight,d=this.normal(c,l),f=n((u-this.minHeight)/this.span,d?d[1]:1,this.data);for(let t=0;t<4;t++)e[(o*r+s)*4+t]=Math.round(f[t]*255)}this.splat={width:r,height:i,pixels:e}}return e&&!this.splat2&&(this.splat2={width:this.splat.width,height:this.splat.height,pixels:new Uint8Array(this.splat.width*this.splat.height*4)}),{a:this.splat,b:this.splat2}}splats(){return{a:this.splat,b:this.splat2}}get span(){return Math.max(this.maxHeight-this.minHeight,1e-6)}toData(){let e=this.data;return{field:this.field,params:{sizeX:e.sizeX,sizeZ:e.sizeZ,height:e.height,rockSlope:e.rockSlope,dirtHeight:e.dirtHeight,snowHeight:e.snowHeight},splat:this.splat,splat2:this.splat2,flow:this.flow,range:[this.minHeight,this.maxHeight]}}static fromData(t){return new e(t.field,t.params,t.splat,t.flow,t.range,t.splat2)}height(e,t){let n=e/this.data.sizeX+.5,i=t/this.data.sizeZ+.5;return n<0||n>1||i<0||i>1?null:this.minHeight+r(this.field,n,i)*this.span}normal(e,t){let n=e/this.data.sizeX+.5,r=t/this.data.sizeZ+.5;return n<0||n>1||r<0||r>1?null:i(this.field,n,r,this.data.sizeX,this.data.sizeZ,this.span)}paint(e,t,r,i){let a=Math.min(Math.max(e/this.data.sizeX+.5,0),1),o=Math.min(Math.max(t/this.data.sizeZ+.5,0),1),s=[...n((r-this.minHeight)/this.span,i,this.data)],c=e=>{if(!e)return[0,0,0,0];let t=Math.round(a*(e.width-1)),n=(Math.round(o*(e.height-1))*e.width+t)*4;return[e.pixels[n]/255,e.pixels[n+1]/255,e.pixels[n+2]/255,e.pixels[n+3]/255]};if(this.splat||this.splat2){let e=[...c(this.splat),...this.splat2?c(this.splat2):[]],t=e.reduce((e,t)=>e+t,0);t>.001&&(s=e.map(e=>e/t))}if(this.flow){let e=Math.round(a*(this.field.width-1)),t=Math.round(o*(this.field.height-1)),n=d(.45,.85,this.flow[t*this.field.width+e])*.8*s[0];s[0]-=n,s[1]+=n}return s}},o=class e{constructor(e){this.p=e,this.infinite=!0,this.bounds=null,this.minHeight=0,this.maxHeight=e.height}toData(){return{...this.p}}static fromData(t){return new e(t)}height(e,t){return this.sample(e,t)[0]*this.p.height}normal(e,t){let[,n,r]=this.sample(e,t),i=n*this.p.height,a=r*this.p.height,o=Math.hypot(i,1,a);return[-i/o,1/o,-a/o]}paint(e,t,r,i){return n(r/Math.max(this.p.height,1e-6),i,this.p)}sample(e,t){let n=this.p,r=Math.max(n.frequency,1e-6)/Math.max(n.sizeX,1e-6),i=e*r,a=t*r,o=Math.min(Math.max(n.warp,0),1);o>0&&(i+=(u(i+5.2,a+1.3,n.seed+7001)[0]*2-1)*o*.5,a+=(u(i+8.3,a+2.8,n.seed+7003)[0]*2-1)*o*.5);let l=Math.max(1,Math.min(8,Math.floor(n.octaves))),d=Math.min(Math.max(n.erosion,0),4),f=1,p=1,m=0,h=0,g=0,_=0,v=0,y=0;for(let e=0;e<l;e++){let[t,r,o]=u(i*p,a*p,n.seed+e*101),l=t,b=r*p,x=o*p;if(n.ridged>0){let e=t*2-1,r=Math.sqrt(e*e+s*s),i=(r-s)/c,a=e/r/c*2;l=t*(1-n.ridged)+(1-i)*n.ridged,b=b*(1-n.ridged)-a*b*n.ridged,x=x*(1-n.ridged)-a*x*n.ridged}v+=b*f,y+=x*f;let S=d>0?1/(1+d*(v*v+y*y)*.25):1;m+=l*f*S,g+=b*f*S,_+=x*f*S,h+=f,f*=n.persistence,p*=2}return[m/h,g/h*r,_/h*r]}};let s=.06,c=Math.sqrt(1.0036)-s;function l(e,t,n){let r=Math.imul(e,374761393)+Math.imul(t,668265263)+Math.imul(n|0,2147483647)|0;return r=Math.imul(r^r>>>13,1274126177),r=(r^r>>>16)>>>0,r/4294967295}function u(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=e-r,o=t-i,s=a*a*(3-2*a),c=o*o*(3-2*o),u=6*a*(1-a),d=6*o*(1-o),f=l(r,i,n),p=l(r+1,i,n),m=l(r,i+1,n),h=l(r+1,i+1,n),g=p-f,_=m-f,v=f-p-m+h;return[f+g*s+_*c+v*s*c,(g+v*c)*u,(_+v*s)*d]}function d(e,t,n){let r=Math.min(Math.max((n-e)/(t-e||1e-6),0),1);return r*r*(3-2*r)}let f={moisture:{scale:900,octaves:4},temperature:{scale:2400,octaves:3},rock:{scale:500,octaves:4}};function p(...e){let t=-1640531527;for(let n of e)t=Math.imul(t^(n|0),2246822507),t=t^t>>>13|0,t=Math.imul(t,3266489909),t=t^t>>>16|0;return(t>>>0)/4294967296}function m(e){let t=-2128831035;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return t|0}function h(e,t,n,r,i){let a=0,o=0,s=1,c=1;for(let l=0;l<i;l++)a+=_(e*c,t*c,n*c,r+l*131)*s,o+=s,s*=.5,c*=2;return a/o}function g(e,t,n,r){return p(e,t,n,r)}function _(e,t,n,r){let i=Math.floor(e),a=Math.floor(t),o=Math.floor(n),s=e-i,c=t-a,l=n-o,u=s*s*(3-2*s),d=c*c*(3-2*c),f=l*l*(3-2*l),p=(e,t,n)=>g(i+e,a+t,o+n,r),m=p(0,0,0)+(p(1,0,0)-p(0,0,0))*u,h=p(0,1,0)+(p(1,1,0)-p(0,1,0))*u,_=p(0,0,1)+(p(1,0,1)-p(0,0,1))*u,v=p(0,1,1)+(p(1,1,1)-p(0,1,1))*u,y=m+(h-m)*d;return y+(_+(v-_)*d-y)*f}function v(e,t,n,r){let i=0,a=0,o=1,s=1;for(let c=0;c<r;c++)i+=u(e*s,t*s,n+c*131)[0]*o,a+=o,o*=.5,s*=2;return i/a}var y=class{constructor(e){this.inputs=e,this.seeds_={},this.noise_={...f};for(let[t,n]of Object.entries(e.noise??{}))n&&(this.noise_[t]=n);for(let t of Object.keys(this.noise_))this.seeds_[t]=e.seed*7919^m(t)}sample(e,t){let n={},r=(e,t)=>{let r=!1,i=0;Object.defineProperty(n,e,{enumerable:!0,configurable:!0,get:()=>(r||=(i=t(),!0),i),set:e=>{i=e,r=!0}})},i,a=()=>i===void 0?i=this.inputs.ground(e,t):i;r(`height`,()=>a()?.y??NaN),r(`up`,()=>a()?.up??1),r(`slope`,()=>1-(a()?.up??1)),r(`waterDepth`,()=>{let n=a();return n&&this.inputs.waterDepth?this.inputs.waterDepth(e,t,n.y)??-1/0:-1/0}),r(`shoreDistance`,()=>this.inputs.shoreDistance?.(e,t)??1/0);for(let[n,i]of Object.entries(this.noise_)){let a=Math.max(i.scale,1e-6),o=Math.max(1,i.octaves??3);this.inputs.space?r(n,()=>{let r=this.inputs.space(e,t);return h(r[0]/a,r[1]/a,r[2]/a,this.seeds_[n],o)}):r(n,()=>v(e/a,t/a,this.seeds_[n],o))}for(let[i,a]of Object.entries(this.inputs.fields??{}))r(i,()=>a(e,t,n));for(let r of this.inputs.overrides?.(e,t)??[]){let e=n[r.field]??r.value;n[r.field]=e+(r.value-e)*Math.min(Math.max(r.weight,0),1)}return n}};function b(e,t,n){if(e.type===`circle`)return Math.hypot(t-e.x,n-e.z)-e.radius;let r=Math.cos(-(e.yaw??0)),i=Math.sin(-(e.yaw??0)),a=t-e.x,o=n-e.z,s=Math.abs(a*r-o*i)-e.halfX,c=Math.abs(a*i+o*r)-e.halfZ;return Math.hypot(Math.max(s,0),Math.max(c,0))+Math.min(Math.max(s,c),0)}function x(e,t){if(t<=0)return 1;if(e.falloff<=0||t>=e.falloff)return 0;let n=1-t/e.falloff;return n*n*(3-2*n)}function S(e){let t=e.shape,n=(t.type===`circle`?t.radius:Math.hypot(t.halfX,t.halfZ))+Math.max(e.falloff,0);return[t.x-n,t.z-n,t.x+n,t.z+n]}var C=class{constructor(){this.zones_=new Map,this.listeners_=new Set,this.revision=0,this.onChange=null}subscribe(e){return this.listeners_.add(e),()=>{this.listeners_.delete(e)}}changed(e){let t=S(e);this.onChange?.(t,e);for(let n of this.listeners_)n(t,e)}set(e){let t=this.zones_.get(e.id);t&&JSON.stringify(t)===JSON.stringify(e)||(this.zones_.set(e.id,e),this.revision++,t&&this.changed(t),this.changed(e))}delete(e){let t=this.zones_.get(e);t&&(this.zones_.delete(e),this.revision++,this.changed(t))}get(e){return this.zones_.get(e)}all(){return this.zones_.values()}at(e,t,n=0){let r=[];for(let i of this.zones_.values()){let a=x(i,b(i.shape,e,t)-n);a>0&&r.push({zone:i,weight:a})}return r.sort((e,t)=>t.zone.priority-e.zone.priority||(e.zone.id<t.zone.id?-1:1))}excluding(e,t,n,r,i){for(let{zone:a,weight:o}of this.at(e,t,n))if(a.excludes.some(e=>e===`*`||r.includes(e))&&(o>=1||p(i,m(a.id),Math.floor(e*16),Math.floor(t*16))<o))return a;return null}};let w=[{normal:[1,0,0],a:[0,0,-1],b:[0,1,0]},{normal:[-1,0,0],a:[0,0,1],b:[0,1,0]},{normal:[0,1,0],a:[1,0,0],b:[0,0,-1]},{normal:[0,-1,0],a:[1,0,0],b:[0,0,1]},{normal:[0,0,1],a:[1,0,0],b:[0,1,0]},{normal:[0,0,-1],a:[-1,0,0],b:[0,1,0]}],T=Math.PI/4;function E(e,t,n,r=[0,0,0]){let i=w[e],a=Math.tan(t*T),o=Math.tan(n*T),s=i.normal[0]+a*i.a[0]+o*i.b[0],c=i.normal[1]+a*i.a[1]+o*i.b[1],l=i.normal[2]+a*i.a[2]+o*i.b[2],u=Math.hypot(s,c,l);return r[0]=s/u,r[1]=c/u,r[2]=l/u,r}function D(e,t,n){let r=Math.abs(e),i=Math.abs(t),a=Math.abs(n),o;o=r>=i&&r>=a?e>=0?0:1:i>=a?t>=0?2:3:n>=0?4:5;let s=w[o],c=e*s.normal[0]+t*s.normal[1]+n*s.normal[2],l=e*s.a[0]+t*s.a[1]+n*s.a[2],u=e*s.b[0]+t*s.b[1]+n*s.b[2];return{face:o,u:Math.atan(l/c)/T,v:Math.atan(u/c)/T}}function O(e,t,n,r){let i=w[e],a=t*i.normal[0]+n*i.normal[1]+r*i.normal[2];if(a<=1e-6)return null;let o=t*i.a[0]+n*i.a[1]+r*i.a[2],s=t*i.b[0]+n*i.b[1]+r*i.b[2];return{u:Math.atan(o/a)/T,v:Math.atan(s/a)/T}}let k=(e,t)=>2/2**(e-1-t);function A(e,t){let n=k(e,t.level);return{u0:-1+t.ix*n,v0:-1+t.iz*n,span:n}}function j(e,t,n,r,i){let a=r/64;if(e.region){let r=e.region(t-a,n-a,a,67);return r instanceof Promise?r.then(r=>ee(e,t,n,a,r.heights,r,i)):ee(e,t,n,a,r.heights,r,i)}return N(M(e,t,n,r,i))}function*M(e,t,n,r,i){let a=r/64,o=new Float32Array(4489),[s,c,l,u]=e.bounds??[-1/0,-1/0,1/0,1/0];for(let r=0;r<o.length;r++){let i=r%67,d=Math.floor(r/67),f=Math.min(Math.max(t+(i-1)*a,s),l),p=Math.min(Math.max(n+(d-1)*a,c),u);o[r]=e.height(f,p)??e.minHeight,(r+1)%32==0&&(yield .4*(r+1)/o.length)}return yield .4,yield*te(e,t,n,a,o,void 0,i)}function N(e){for(;;){let t=e.next();if(t.done)return t.value}}function ee(e,t,n,r,i,a,o){return N(te(e,t,n,r,i,a,o))}function*te(e,t,n,r,i,a,o){let[s,c,l,u]=e.bounds??[-1/0,-1/0,1/0,1/0],d=1/0,f=-1/0;for(let e=1;e<=65;e++)for(let t=1;t<=65;t++){let n=i[e*67+t];d=Math.min(d,n),f=Math.max(f,n)}let p=Math.max(e.maxHeight-e.minHeight,1e-6),m=new Uint8Array(17956),h=new Uint8Array(17956),g=new Uint8Array(17956);for(let d=0;d<67;d++)for(let f=0;f<67;f++){let _=d*67+f,v=Math.round(Math.min(Math.max((i[_]-e.minHeight)/p,0),1)*65535),y=i[d*67+Math.max(f-1,0)],b=i[d*67+Math.min(f+1,66)],x=i[Math.max(d-1,0)*67+f],S=i[Math.min(d+1,66)*67+f],C=(b-y)/(2*r),w=(S-x)/(2*r),T=Math.hypot(C,1,w),E=-C/T,D=1/T,O=-w/T;m[_*4]=v>>8,m[_*4+1]=v&255,m[_*4+2]=Math.round((E*.5+.5)*255),m[_*4+3]=Math.round((O*.5+.5)*255);let k=Math.min(Math.max(t+(f-1)*r,s),l),A=Math.min(Math.max(n+(d-1)*r,c),u),j=a?.paint,M=a?.paint2,N=j?[j[_*4],j[_*4+1],j[_*4+2],j[_*4+3],...M?[M[_*4],M[_*4+1],M[_*4+2],M[_*4+3]]:[]]:e.paint(k,A,i[_],D);o&&(N=o(k,A,i[_],D,N));for(let e=0;e<4;e++)h[_*4+e]=Math.round(Math.min(Math.max(N[e]??0,0),1)*255),g[_*4+e]=Math.round(Math.min(Math.max(N[e+4]??0,0),1)*255);(_+1)%32==0&&(yield .4+.6*(_+1)/4489)}return{heights:m,paint:h,paint2:g,min:Number.isFinite(d)?d:e.minHeight,max:Number.isFinite(f)?f:e.maxHeight}}function ne(e,t,n,r){let i=w[e];for(let[e,a]of[[i.a,n],[i.b,r]]){let n=e[0]*t[0]+e[1]*t[1]+e[2]*t[2],r=e[0]-t[0]*n,i=e[1]-t[1]*n,o=e[2]-t[2]*n,s=Math.hypot(r,i,o)||1;a[0]=r/s,a[1]=i/s,a[2]=o/s}}function re(e,t){let{u0:n,v0:r,span:i}=A(e.levels,t),a=i/64,o=new Float32Array(13467),s=[0,0,0];for(let e=0;e<67;e++)for(let i=0;i<67;i++){E(t.face,n+(i-1)*a,r+(e-1)*a,s);let c=(e*67+i)*3;o[c]=s[0],o[c+1]=s[1],o[c+2]=s[2]}let c=e.provider.sample({world:e.world,seed:e.seed,version:e.version,radius:e.radius,directions:o,count:4489});return c instanceof Promise?c.then(n=>ie(e,t,o,n.heights,n.paint)):ie(e,t,o,c.heights,c.paint)}function ie(e,t,n,r,i){let a=1/0,o=-1/0;for(let e=1;e<=65;e++)for(let t=1;t<=65;t++){let n=r[e*67+t];a=Math.min(a,n),o=Math.max(o,n)}let s=Math.max(e.maxHeight-e.minHeight,1e-6),c=new Uint8Array(17956),l=new Uint8Array(17956),u=new Uint8Array(17956),d=(t,i,a)=>{let o=Math.min(Math.max(t,0),66),s=Math.min(Math.max(i,0),66)*67+o,c=e.radius+r[s];a[0]=n[s*3]*c,a[1]=n[s*3+1]*c,a[2]=n[s*3+2]*c},f=[0,0,0],p=[0,0,0],m=[0,0,0],h=[0,0,0],g=[0,0,0],_=[0,0,0],v=e.paint?.()??null,y=v?ae(v,n,i):null;for(let a=0;a<67;a++)for(let o=0;o<67;o++){let u=a*67+o,v=Math.round(Math.min(Math.max((r[u]-e.minHeight)/s,0),1)*65535);d(o-1,a,f),d(o+1,a,p),d(o,a-1,m),d(o,a+1,h);let b=[p[0]-f[0],p[1]-f[1],p[2]-f[2]],x=[h[0]-m[0],h[1]-m[1],h[2]-m[2]],S=b[1]*x[2]-b[2]*x[1],C=b[2]*x[0]-b[0]*x[2],w=b[0]*x[1]-b[1]*x[0],T=[n[u*3],n[u*3+1],n[u*3+2]],E=Math.hypot(S,C,w)||1;S/=E,C/=E,w/=E,S*T[0]+C*T[1]+w*T[2]<0&&(S=-S,C=-C,w=-w),ne(t.face,T,g,_);let D=S*g[0]+C*g[1]+w*g[2],O=S*_[0]+C*_[1]+w*_[2],k=S*T[0]+C*T[1]+w*T[2];E=Math.hypot(D,k,O)||1,c[u*4]=v>>8,c[u*4+1]=v&255,c[u*4+2]=Math.round((D/E*.5+.5)*255),c[u*4+3]=Math.round((O/E*.5+.5)*255);let A=0,j=0,M=0,N=0;if(y){let e=y(o,a);A=e[0],j=e[1],M=e[2],N=e[3]}else if(i)A=i[u*4],j=i[u*4+1],M=i[u*4+2],N=i[u*4+3];else{let e=Math.min(Math.max((.9-k/E)*6,0),1);A=1-e,N=e}l[u*4]=Math.round(Math.min(Math.max(A,0),1)*255),l[u*4+1]=Math.round(Math.min(Math.max(j,0),1)*255),l[u*4+2]=Math.round(Math.min(Math.max(M,0),1)*255),l[u*4+3]=Math.round(Math.min(Math.max(N,0),1)*255)}return{heights:c,paint:l,paint2:u,min:Number.isFinite(a)?a:e.minHeight,max:Number.isFinite(o)?o:e.maxHeight}}function ae(e,t,n){let r=Array(81);for(let i=0;i<9;i++)for(let a=0;a<9;a++){let o=1+a*8,s=(1+i*8)*67+o,c=n?[n[s*4],n[s*4+1],n[s*4+2],n[s*4+3]]:[1,0,0,0],l=e(t[s*3],t[s*3+1],t[s*3+2],c);r[i*9+a]=[l[0]??0,l[1]??0,l[2]??0,l[3]??0]}return(e,t)=>{let n=Math.min(Math.max((e-1)/8,0),8),i=Math.min(Math.max((t-1)/8,0),8),a=Math.min(Math.floor(n),7),o=Math.min(Math.floor(i),7),s=n-a,c=i-o,l=r[o*9+a],u=r[o*9+a+1],d=r[(o+1)*9+a],f=r[(o+1)*9+a+1],p=[0,0,0,0];for(let e=0;e<4;e++)p[e]=(l[e]*(1-s)+u[e]*s)*(1-c)+(d[e]*(1-s)+f[e]*s)*c;return p}}let P=e=>e*Math.PI/4,oe=e=>P(e),F=1.5;var se=class{constructor(e,t){this.face=e,this.planet=t,this.tiles_=new Map}facts(){return this.planet()}directionAt(e,t){let n=this.facts(),r=P(n?.radius??1);return E(this.face,e/r,t/r)}planeOf(e,t,n){let r=this.facts(),i=O(this.face,e,t,n);if(!r||!i)return null;let a=P(r.radius);return{x:i.u*a,z:i.v*a}}frameAt(e,t){let n=this.directionAt(e,t),r=[0,0,0],i=[0,0,0];return ne(this.face,n,r,i),{dir:n,eu:r,ev:i}}world(e,t,n){let r=this.facts(),i=this.directionAt(e,n),a=r.radius+t;return[r.centre[0]+i[0]*a,r.centre[1]+i[1]*a,r.centre[2]+i[2]*a]}tile(e,t){let n=Math.floor(e/48),r=Math.floor(t/48),i=`${n},${r}`,a=this.tiles_.get(i);if(a)return this.tiles_.delete(i),this.tiles_.set(i,a),a;let o=this.facts();if(!o?.sampleMany)return null;let s=new Float32Array(3675);for(let e=0;e<35;e++)for(let t=0;t<35;t++){let i=this.directionAt(n*48+(t-1)*F,r*48+(e-1)*F);s[(e*35+t)*3]=i[0],s[(e*35+t)*3+1]=i[1],s[(e*35+t)*3+2]=i[2]}let c=o.sampleMany(s,1225);if(!c)return null;let l={x0:n*48-F,z0:r*48-F,n:35,heights:c.heights,paint:c.paint,fields:c.fields,fieldCount:o.fieldNames.length};return this.tiles_.set(i,l),this.tiles_.size>6e3&&this.tiles_.delete(this.tiles_.keys().next().value),l}cellOf(e,t,n){let r=(t-e.x0)/F,i=(n-e.z0)/F,a=Math.min(Math.max(Math.floor(r),0),e.n-2),o=Math.min(Math.max(Math.floor(i),0),e.n-2);return{i:a,j:o,fx:Math.min(Math.max(r-a,0),1),fz:Math.min(Math.max(i-o,0),1)}}heightAt(e,t){let n=this.tile(e,t);if(!n)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=n.n,c=n.heights,l=c[i*s+r],u=c[i*s+r+1],d=c[(i+1)*s+r],f=c[(i+1)*s+r+1];return(l+(u-l)*a)*(1-o)+(d+(f-d)*a)*o}paintAt(e,t){let n=this.tile(e,t);if(!n?.paint)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=(i+ +(o>.5))*n.n+r+ +(a>.5);return[n.paint[s*4],n.paint[s*4+1],n.paint[s*4+2],n.paint[s*4+3]]}fieldsAt(e,t){let n=this.tile(e,t);if(!n?.fields||n.fieldCount===0)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=n.fieldCount,c=n.n,l=[];for(let e=0;e<s;e++){let t=n.fields[(i*c+r)*s+e],u=n.fields[(i*c+r+1)*s+e],d=n.fields[((i+1)*c+r)*s+e],f=n.fields[((i+1)*c+r+1)*s+e];l.push((t+(u-t)*a)*(1-o)+(d+(f-d)*a)*o)}return l}ground(e,t){let n=this.heightAt(e,t);if(n===null)return null;let r=F,i=this.heightAt(e-r,t),a=this.heightAt(e+r,t),o=this.heightAt(e,t-r),s=this.heightAt(e,t+r);if(i===null||a===null||o===null||s===null)return{y:n,up:1,normal:[0,1,0]};let c=-(a-i)/3,l=-(s-o)/3,u=Math.hypot(c,1,l);return{y:n,up:1/u,normal:[c/u,1/u,l/u]}}worldNormal(e,t,n){let r=this.frameAt(t,n);return[e[0]*r.eu[0]+e[1]*r.dir[0]+e[2]*r.ev[0],e[0]*r.eu[1]+e[1]*r.dir[1]+e[2]*r.ev[1],e[0]*r.eu[2]+e[1]*r.dir[2]+e[2]*r.ev[2]]}environment(){return{ground:(e,t)=>this.ground(e,t),space:(e,t)=>{let n=this.facts(),r=this.directionAt(e,t);return[r[0]*n.radius,r[1]*n.radius,r[2]*n.radius]}}}zoneOnFace(e){let t=this.facts(),n=e.shape;if(!t||n.y===void 0)return null;let r=n.x-t.centre[0],i=n.y-t.centre[1],a=n.z-t.centre[2],o=Math.hypot(r,i,a);if(o<1e-9)return null;let s=this.planeOf(r/o,i/o,a/o),c=oe(t.radius),l=(n.type===`circle`?n.radius:Math.hypot(n.halfX,n.halfZ))+e.falloff;if(!s||Math.abs(s.x)>c+l||Math.abs(s.z)>c+l)return null;if(n.type===`circle`)return{...e,shape:{type:`circle`,x:s.x,z:s.z,radius:n.radius}};let u=this.frameAt(s.x,s.z),d=n.facing??[Math.cos(n.yaw??0),0,Math.sin(n.yaw??0)],f=Math.atan2(d[0]*u.ev[0]+d[1]*u.ev[1]+d[2]*u.ev[2],d[0]*u.eu[0]+d[1]*u.eu[1]+d[2]*u.eu[2]);return{...e,shape:{type:`rect`,x:s.x,z:s.z,halfX:n.halfX,halfZ:n.halfZ,yaw:f}}}sourcesOnFace(e,t){let n=this.facts(),r=[];if(!n)return r;let i=oe(n.radius);for(let a of e){let e=a.x-n.centre[0],o=(a.y??0)-n.centre[1],s=a.z-n.centre[2],c=Math.hypot(e,o,s);if(c<1e-9)continue;let l=this.planeOf(e/c,o/c,s/c);l&&Math.abs(l.x)<=i+t&&Math.abs(l.z)<=i+t&&r.push(l)}return r}};function ce(e,t){if(!Number.isFinite(t))return 0;let n=Math.max(e.blend??0,1e-9),r=e=>{if(e<=0)return 1;if(e>=n)return 0;let t=1-e/n;return t*t*(3-2*t)};return r(e.min===void 0?-1:e.min-t)*r(e.max===void 0?-1:t-e.max)}function le(e){if(!e||!Array.isArray(e.size)||e.size.length!==2||e.size.some(e=>!Number.isFinite(e)||e<=0))throw Error(`grounding.size: two positive model dimensions`);if(![3,5,7,9].includes(e.samples??5))throw Error(`grounding.samples: 3, 5, 7 or 9`);if(![`highest`,`lowest`,`mean`,`center`].includes(e.mode??`highest`))throw Error(`grounding.mode: highest, lowest, mean or center`);if(e.maxRelief!==void 0&&(!Number.isFinite(e.maxRelief)||e.maxRelief<0))throw Error(`grounding.maxRelief: a nonnegative world distance`);if(e.offset!==void 0&&!Number.isFinite(e.offset))throw Error(`grounding.offset: a finite model distance`)}function ue(e,t,n,r,i,a,o={}){if(le(a),![t,n,r,i].every(Number.isFinite)||i<=0)throw Error(`grounding transform: finite position, yaw and positive scale`);let s=a.samples??5,c=Math.cos(r),l=Math.sin(r),u=1/0,d=-1/0,f=0,p=0;for(let r=0;r<s;r++)for(let m=0;m<s;m++){let h=(m/(s-1)-.5)*a.size[0]*i,g=(r/(s-1)-.5)*a.size[1]*i,_=t+h*c+g*l,v=n-h*l+g*c,y=e.ground(_,v);if(!y||!Number.isFinite(y.y)||!Number.isFinite(y.up))return{ok:!1,reason:`noGround`};if(y.up<(o.minUp??0))return{ok:!1,reason:`slope`};let b=e.waterDepth?.(_,v,y.y)??0;if(!Number.isFinite(b))return{ok:!1,reason:`noGround`};if(b>(o.waterDepth??0))return{ok:!1,reason:`water`};u=Math.min(u,y.y),d=Math.max(d,y.y),f+=y.y,m===(s-1)/2&&r===(s-1)/2&&(p=y.y)}let m=d-u,h=f/(s*s);if(m>(a.maxRelief??1/0))return{ok:!1,reason:`relief`};let g={highest:d,lowest:u,mean:h,center:p}[a.mode??`highest`]+(a.offset??0)*i;return{ok:!0,fit:{y:g,min:u,max:d,mean:h,relief:m,supportDepth:Math.max(0,g-u),buriedDepth:Math.max(0,d-g),samples:s*s}}}let de=4e4;function fe(e){let t=I(e.anchor,e.anchor.scale?.[1]??1);for(let n of e.members??[])t=Math.max(t,(n.ring?.[1]??0)+I(n,n.scale?.[1]??1));return t}function I(e,t){return Math.max(e.footprint*(e.scaleFootprint?Math.abs(t):1),e.grounding?Math.hypot(...e.grounding.size)*Math.abs(t)/2:0)}let L=(e,t,n)=>e?e[0]+(e[1]-e[0])*t:n;var R=class{constructor(e,t,n,r,i){this.rules=e,this.env=t,this.zones=n,this.seed=r,this.world=i,this.recipes_=new Map,this.layers_=[],this.viable_=new Map,this.groups_=new Map,this.worldHash_=m(i)^r;for(let t of e.recipes)this.recipes_.set(t.id,t);for(let t of e.layers){let n=new Set;for(let r of e.biomes)for(let e of r.recipes)e.layer===t.id&&n.add(e.recipe);let r=0;for(let e of n){let t=this.recipes_.get(e);t&&(r=Math.max(r,fe(t)))}this.layers_.push({def:t,hash:m(t.id),maxRadius:r,recipes:n})}}invalidate(){this.viable_.clear(),this.groups_.clear()}layerIndex(e){return this.layers_.findIndex(t=>t.def.id===e)}biomeWeights(e,t){let n=[],r=0;for(let i of this.rules.biomes){let a=this.biomeWeight(i,e,t);a>0&&(n.push({biome:i.id,weight:a}),r+=a)}for(let{zone:i,weight:a}of this.zones.at(e,t)){if(!i.biome)continue;for(let e of n)e.weight*=1-a;r=r*(1-a)+a;let e=n.find(e=>e.biome===i.biome);e?e.weight+=a:n.push({biome:i.biome,weight:a});break}if(r<=0)return[];for(let e of n)e.weight/=r;return n.filter(e=>e.weight>0).sort((e,t)=>t.weight-e.weight||(e.biome<t.biome?-1:1))}biomeAt(e,t){return this.biomeWeights(e,t)[0]?.biome??null}paint(e,t,n){let r=n.length,i=this.biomeWeights(e,t);for(let{biome:e}of i)r=Math.max(r,this.rules.biomes.find(t=>t.id===e)?.paint?.length??0);let a=Array.from({length:r},(e,t)=>n[t]??0);for(let{biome:e,weight:t}of i){let i=this.rules.biomes.find(t=>t.id===e);if(!i?.paint)continue;let o=t*Math.min(Math.max(i.paintStrength??1,0),1);for(let e=0;e<r;e++)a[e]=a[e]+((i.paint[e]??0)-(n[e]??0))*o}let o=a.reduce((e,t)=>e+t,0)||1;return a.map(e=>e/o)}groupsIn(e,t,n,r,i){let a=this.layerIndex(e);if(a<0)return[];let o=this.layers_[a].def.spacing,s=[];for(let e=Math.floor(n/o);e<=Math.floor(i/o);e++)for(let c=Math.floor(t/o);c<=Math.floor(r/o);c++){let o=this.group(a,c,e);typeof o!=`string`&&o.x>=t&&o.x<r&&o.z>=n&&o.z<i&&s.push(o)}return s}placementsIn(e,t,n,r,i){let a=[];for(let o of this.layers_)if(!(i&&!i.includes(o.def.id)))for(let i of this.groupsIn(o.def.id,e,t,n,r))a.push(i.anchor,...i.members);return a}stats(e,t,n,r,i){let a={placed:0,noBiome:0,density:0,noGround:0,slope:0,water:0,relief:0,zone:0,occupied:0,conflict:0},o=this.layerIndex(e);if(o<0)return a;let s=this.layers_[o].def.spacing;for(let e=Math.floor(n/s);e<Math.ceil(i/s);e++)for(let n=Math.floor(t/s);n<Math.ceil(r/s);n++){let t=this.group(o,n,e);typeof t==`string`?a[t]++:a.placed++}return a}explain(e,t){let n=this.layers_.map((n,r)=>{let i=Math.floor(e/n.def.spacing),a=Math.floor(t/n.def.spacing),o=this.group(r,i,a),s=this.viable(r,i,a);return{layer:n.def.id,cell:[i,a],group:typeof o==`string`?null:o.id,rejected:typeof o==`string`?o:null,detail:s.ok?void 0:s.detail}});return{fields:this.env.sample(e,t),biomes:this.biomeWeights(e,t),zones:this.zones.at(e,t).map(({zone:e,weight:t})=>({id:e.id,kind:e.kind,weight:t})),layers:n}}group(e,t,n){let r=`${e}:${t},${n}`,i=this.groups_.get(r);if(i!==void 0)return i;this.groups_.size>de&&this.groups_.clear();let a=this.makeGroup(e,t,n);return this.groups_.set(r,a),a}makeGroup(e,t,n){let r=this.viable(e,t,n);if(!r.ok)return r.reason;let i=r.candidate,a=this.layers_[e],o=a.def.spacing,s=Math.ceil((i.radius+a.maxRadius)/o);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(a===0&&r===0)continue;let o=this.viable(e,t+a,n+r);if(!o.ok)continue;let s=o.candidate;if((s.priority>i.priority||s.priority===i.priority&&(s.gz<n||s.gz===n&&s.gx<t))&&Math.hypot(s.x-i.x,s.z-i.z)<i.radius+s.radius)return`conflict`}let c=`${a.def.id}@${a.def.version??1}:${t},${n}`,l=i.recipe,u=i.anchor,d=[],f=[u];for(let[r,o]of(l.members??[]).entries()){let s=(e,i)=>p(this.worldHash_,a.hash,t,n,1e3+r*37+e,i),u=o.count?o.count[0]+Math.floor(s(0,0)*(o.count[1]-o.count[0]+1)):1;for(let t=0;t<u;t++){if(o.chance!==void 0&&s(1,t)>=o.chance)continue;let n=L(o.arc,s(2,t),s(2,t)*360)*Math.PI/180,r=L(o.ring,s(3,t),0),u=i.x+Math.cos(n)*r,p=i.z+Math.sin(n)*r,m=this.env.sample(u,p),h=this.place(c,a.def,l,o,t,u,p,i.biome,m,s(4,t));typeof h!=`string`&&this.zones.excluding(u,p,h.footprint,this.tagsOf(a.def,l,o),this.seed)===null&&this.occupied(e,u,p,h.footprint)===null&&(f.some(e=>Math.hypot(e.x-u,e.z-p)<e.footprint+h.footprint)||(d.push(h),f.push(h)))}}return{id:c,layer:a.def.id,x:i.x,z:i.z,radius:i.radius,priority:i.priority,anchor:u,members:d}}place(e,t,n,r,i,a,o,s,c,l){let u=this.standing(c,r);if(u)return u;let d=p(this.worldHash_,m(e),m(r.id),i,7),f=(l||d)*Math.PI*2,h=L(r.scale,p(this.worldHash_,m(e),i,11),1),g;if(r.grounding){let e=ue(this.env.inputs,a,o,f,h,r.grounding,r);if(!e.ok)return e.reason;g=e.fit}let _=this.env.inputs.ground(a,o),v=_?.up??1,y=_?.normal??[0,v,Math.sqrt(Math.max(0,1-v*v))];return{id:`${e}/${n.id}@${n.version}/${r.id}.${i}`,group:e,layer:t.id,recipe:n.id,recipeVersion:n.version,member:r.id,biome:s,zone:this.zones.at(a,o)[0]?.zone.id??null,x:a,y:g?.y??c.height,z:o,yaw:f,scale:h,normal:y,attach:r.attach??`upright`,mesh:typeof r.mesh==`number`?r.mesh:0,material:typeof r.material==`number`?r.material:0,plant:r.plant??null,interactive:r.interactive??null,footprint:I(r,h),canopy:(r.canopy??r.footprint)*(r.scaleFootprint?Math.abs(h):1),far:r.far??null,...g?{grounding:g}:{}}}standing(e,t){return Number.isFinite(e.height)?e.up<(t.minUp??0)?`slope`:e.waterDepth>(t.waterDepth??0)?`water`:null:`noGround`}tagsOf(e,t,n){return[e.id,t.id,n.interactive?`interactive`:`decor`,...t.tags??[],...n.tags??[]]}viable(e,t,n){let r=`${e}:${t},${n}`,i=this.viable_.get(r);if(i)return i;this.viable_.size>de&&this.viable_.clear();let a=this.makeViable(e,t,n);return this.viable_.set(r,a),a}makeViable(e,t,n){let r=this.layers_[e],i=r.def.spacing,a=e=>p(this.worldHash_,r.hash,t,n,e),o=(t+a(1))*i,s=(n+a(2))*i,c=this.biomeWeights(o,s);if(c.length===0)return{ok:!1,reason:`noBiome`};let l=a(3),u=c[c.length-1].biome;for(let e of c){if(l<e.weight){u=e.biome;break}l-=e.weight}let d=(this.rules.biomes.find(e=>e.id===u)?.recipes??[]).filter(e=>e.layer===r.def.id&&this.recipes_.has(e.recipe)),f=a(4),m=null;for(let e of d){if(f<e.density){m=this.recipes_.get(e.recipe);break}f-=e.density}if(!m)return{ok:!1,reason:`density`};let h=this.env.sample(o,s),g=`${r.def.id}@${r.def.version??1}:${t},${n}`,_=this.place(g,r.def,m,m.anchor,0,o,s,u,h,0);if(typeof _==`string`)return{ok:!1,reason:_};let v=this.zones.excluding(o,s,_.footprint,this.tagsOf(r.def,m,m.anchor),this.seed);if(v)return{ok:!1,reason:`zone`,detail:v.id};let y=this.occupied(e,o,s,_.footprint);return y?{ok:!1,reason:`occupied`,detail:y}:{ok:!0,candidate:{gx:t,gz:n,x:o,z:s,priority:a(5),biome:u,recipe:m,radius:fe(m),anchor:_}}}occupied(e,t,n,r){for(let i=0;i<e;i++){let e=this.layers_[i];if(e.def.occupies===!1)continue;let a=e.def.spacing,o=r+e.maxRadius;for(let e=Math.floor((n-o)/a);e<=Math.floor((n+o)/a);e++)for(let s=Math.floor((t-o)/a);s<=Math.floor((t+o)/a);s++){let a=this.group(i,s,e);if(typeof a!=`string`){for(let e of[a.anchor,...a.members])if(Math.hypot(e.x-t,e.z-n)<e.footprint+r)return e.id}}}return null}biomeWeight(e,t,n){let r=e.transition??0,i=t,a=n;if(r>0){let o=m(e.id)^this.worldHash_;i+=(v(t/r,n/r,o,2)-.5)*2*r,a+=(v(t/r,n/r,o+1,2)-.5)*2*r}let o=this.env.sample(i,a),s=e.weight??1;for(let t of e.conditions)if(s*=ce(t,o[t.field]??NaN),s<=0)return 0;return s}};function pe(e){return e.layers.some(e=>(e.farSpacing??1)>1)?{...e,layers:e.layers.map(e=>(e.farSpacing??1)>1?{...e,spacing:e.spacing*e.farSpacing}:e)}:null}function me(e,t){let n={};t.layers.forEach((t,r)=>{n[`paint.${t}`]=(t,n)=>e.paintAt(t,n)?.[r]??0}),t.fieldNames.forEach((t,r)=>{n[t]=(t,n)=>e.fieldsAt(t,n)?.[r]??0});let r=new y({seed:t.seed,noise:t.rules.noise,fields:{...n,...t.rules.fields},...e.environment(),waterDepth:(e,n,r)=>t.seaLevel-r,overrides:(e,n)=>{let r=[];for(let{zone:i,weight:a}of t.zones.at(e,n))for(let[e,t]of Object.entries(i.fields??{}))r.push({field:e,value:t,weight:a});return r}}),i=`${t.world}#${e.face}`;return{plan:new R(t.rules,r,t.zones,t.seed,i),farPlan:t.farRules?new R(t.farRules,r,t.zones,t.seed,i):null}}function he(e){let t={};e.ground&&e.layers.forEach((n,r)=>{t[`paint.${n}`]=(t,n)=>e.ground.paintAt(t,n)?.[r]??0});let n=new y({seed:e.seed,noise:e.rules.noise,fields:{...t,...e.rules.fields},ground:(t,n)=>{if(e.ground){let r=e.ground.heightAt(t,n);if(r===null)return null;let i=e.ground.normalAt(t,n)??[0,1,0];return{y:r,up:i[1],normal:i}}return{y:e.flatY,up:1,normal:[0,1,0]}},waterDepth:(t,n,r)=>e.water?.depthAt(t,n,r)??null,shoreDistance:(t,n)=>e.water?.shoreAt(t,n)??null,overrides:(t,n)=>{let r=[];for(let{zone:i,weight:a}of e.zones.at(t,n))for(let[e,t]of Object.entries(i.fields??{}))r.push({field:e,value:t,weight:a});return r}});return{plan:new R(e.rules,n,e.zones,e.seed,e.world),farPlan:e.farRules?new R(e.farRules,n,e.zones,e.seed,e.world):null}}var ge=class{constructor(e,t){this.source=e,this.cell=t}node(e,t){let n=e*this.cell,r=t*this.cell,i=this.source.bounds;return i&&(n=Math.min(Math.max(n,i[0]),i[2]),r=Math.min(Math.max(r,i[1]),i[3])),this.source.height(n,r)}covers(e,t){let n=this.source.bounds;return!n||e>=n[0]&&e<=n[2]&&t>=n[1]&&t<=n[3]}height(e,t){let n=this.corners(e,t);if(!n)return null;let[r,i,a,o,s,c]=n;return s+c<=1?r+(i-r)*s+(a-r)*c:o+(a-o)*(1-s)+(i-o)*(1-c)}normal(e,t){let n=this.corners(e,t);if(!n)return null;let[r,i,a,o,s,c]=n,l=(s+c<=1?i-r:o-a)/this.cell,u=(s+c<=1?a-r:o-i)/this.cell,d=Math.hypot(l,1,u);return[-l/d,1/d,-u/d]}tile(e,t){let n=new Float32Array(3267);for(let r=0;r<=32;r++)for(let i=0;i<=32;i++){let a=this.node(e*32+i,t*32+r);if(a===null)return null;let o=(r*33+i)*3;n[o]=i*this.cell,n[o+1]=a,n[o+2]=r*this.cell}let r=new Uint32Array(6144),i=0;for(let e=0;e<32;e++)for(let t=0;t<32;t++){let n=e*33+t,a=n+1,o=n+33,s=o+1;r.set([n,o,a,a,o,s],i),i+=6}return{x0:e*32*this.cell,z0:t*32*this.cell,positions:n,indices:r}}raycast(e,t,n,r,i,a,o){let s=Math.hypot(r,i,a);if(s<=0)return null;r/=s,i/=s,a/=s;let c=this.cell,l=Math.floor(e/c),u=Math.floor(n/c),d=r>0?1:-1,f=a>0?1:-1,p=r===0?1/0:Math.abs(c/r),m=a===0?1/0:Math.abs(c/a),h=r===0?1/0:((r>0?(l+1)*c:l*c)-e)/r,g=a===0?1/0:((a>0?(u+1)*c:u*c)-n)/a,_=0;for(let s=0;s<1e6&&_<=o;s++){let s=this.node(l,u),v=this.node(l+1,u),y=this.node(l,u+1),b=this.node(l+1,u+1);if(s===null||v===null||y===null||b===null)return null;let x=l*c,S=u*c;for(let l of[[[x,s,S],[x,y,S+c],[x+c,v,S]],[[x+c,v,S],[x,y,S+c],[x+c,b,S+c]]]){let s=_e(e,t,n,r,i,a,l[0],l[1],l[2]);if(s&&s.t<=o&&this.covers(e+r*s.t,n+a*s.t))return{distance:s.t,point:[e+r*s.t,t+i*s.t,n+a*s.t],normal:s.n}}if(h<g?(_=h,h+=p,l+=d):(_=g,g+=m,u+=f),r===0&&a===0)break}return null}corners(e,t){if(!this.covers(e,t))return null;let n=e/this.cell,r=t/this.cell,i=Math.floor(n),a=Math.floor(r),o=this.node(i,a),s=this.node(i+1,a),c=this.node(i,a+1),l=this.node(i+1,a+1);return o===null||s===null||c===null||l===null?null:[o,s,c,l,n-i,r-a]}};function _e(e,t,n,r,i,a,o,s,c){let l=s[0]-o[0],u=s[1]-o[1],d=s[2]-o[2],f=c[0]-o[0],p=c[1]-o[1],m=c[2]-o[2],h=i*m-a*p,g=a*f-r*m,_=r*p-i*f,v=l*h+u*g+d*_;if(Math.abs(v)<1e-12)return null;let y=1/v,b=e-o[0],x=t-o[1],S=n-o[2],C=(b*h+x*g+S*_)*y;if(C<-1e-9||C>1+1e-9)return null;let w=x*d-S*u,T=S*l-b*d,E=b*u-x*l,D=(r*w+i*T+a*E)*y;if(D<-1e-9||C+D>1+1e-9)return null;let O=(f*w+p*T+m*E)*y;if(O<0)return null;let k=u*m-d*p,A=d*f-l*m,j=l*p-u*f;A<0&&(k=-k,A=-A,j=-j);let M=Math.hypot(k,A,j)||1;return{t:O,n:[k/M,A/M,j/M]}}function ve(e,t,n,r){let i=e.height(n-t.x,r-t.z);return i===null?null:t.y+i}function ye(e,t,n,r){return e.normal(n-t.x,r-t.z)}function be(e,t,n,r,i){let a=r-n.x,o=i-n.z,s=t.height(a,o),c=t.normal(a,o);return s===null||!c?null:e.paint(a,o,s,c[1])}var xe=class{constructor(e,t,n){this.base=e,this.dx=t,this.dz=n,this.infinite=e.infinite,this.bounds=e.bounds,this.minHeight=e.minHeight,this.maxHeight=e.maxHeight}height(e,t){return this.base.height(e+this.dx,t+this.dz)}normal(e,t){return this.base.normal(e+this.dx,t+this.dz)}paint(e,t,n,r){return this.base.paint(e+this.dx,t+this.dz,n,r)}};function z(e){let t=e.source.kind===`field`?a.fromData(e.source.data):o.fromData(e.source.data);return e.shift?new xe(t,e.shift.x,e.shift.z):t}var Se=class{constructor(e){this.source_=z(e),this.surface_=new ge(this.source_,e.cell),this.origin_=e.origin}heightAt(e,t){return ve(this.surface_,this.origin_,e,t)}normalAt(e,t){return ye(this.surface_,this.origin_,e,t)}paintAt(e,t){return be(this.source_,this.surface_,this.origin_,e,t)}},Ce=class{constructor(e){this.data=e}lerp(e,t){let{minX:n,minZ:r,sizeX:i,sizeZ:a,nx:o,nz:s}=this.data.grid;if(o<2||s<2)return null;let c=(e-n)/i,l=(t-r)/a;if(c<0||c>1||l<0||l>1)return null;let u=c*(o-1),d=l*(s-1),f=Math.min(Math.floor(u),o-2),p=Math.min(Math.floor(d),s-2),m=u-f,h=d-p,g=p*o+f,_=e=>(e[g]*(1-m)+e[g+1]*m)*(1-h)+(e[g+o]*(1-m)+e[g+o+1]*m)*h;return{height:_(this.data.height),shore:_(this.data.shore)}}depthAt(e,t,n){let r=this.lerp(e,t);return r?r.shore>0?r.height-n:null:this.data.ocean?this.data.ocean.level-n:null}shoreAt(e,t){let n=this.lerp(e,t);return n?-n.shore:this.data.ocean?-1e6:null}};let B={Position:0,Color:1,TexCoord0:2,Normal:3,Tangent:4,Joints:5,Weights:6,TexCoord1:7};new Set(Object.values(B));let V={Float32:0,UNorm8:1,UInt16:2};function we(e){return e===V.UNorm8?1:e===V.UInt16?2:4}function Te(e){let t=[],n=0;for(let r of e)t.push({...r,offset:n}),n+=r.components*we(r.type),n=n+3&-4;return{channels:t,vertexStride:n}}function Ee(e){let t=e|0;return()=>{t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}function De(e,t){let n=Ee(Math.imul(e.seed|0,73856093)^Math.imul(e.cellKey|0,19349663)^2654435769),r=[];for(let i=0;i<e.count;i++){let i=e.centerX+(n()-.5)*e.size,a=e.centerZ+(n()-.5)*e.size,o=n()*Math.PI*2,s=e.minScale+(e.maxScale-e.minScale)*n(),c=n(),l=.7+.3*n(),u=t(i,a);!u||u.up<e.minUp||u.y<e.heightMin||u.y>e.heightMax||r.push({x:i-e.centerX,y:u.y,z:a-e.centerZ,yaw:o,scale:s,phase:c,shade:l})}return r}let H=()=>({pos:[],uv:[],color:[],nrm:[],idx:[]});function U(e,t,n,r,i,a,o,s,c,l,u,d){return e.pos.push(t,n,r),e.uv.push(i,a),e.color.push(o,s,c,1),e.nrm.push(l,u,d),e.pos.length/3-1}function W(e){let{channels:t,vertexStride:n}=Te([{semantic:B.Position,components:3,type:V.Float32},{semantic:B.TexCoord0,components:2,type:V.Float32},{semantic:B.Color,components:4,type:V.UNorm8},{semantic:B.Normal,components:3,type:V.Float32}]),r=e.pos.length/3,i=new Uint8Array(Math.max(1,r)*n),a=new DataView(i.buffer),o=t[0].offset,s=t[1].offset,c=t[2].offset,l=t[3].offset,u=[1/0,1/0,1/0],d=[-1/0,-1/0,-1/0];for(let t=0;t<r;t++){let r=t*n;for(let n=0;n<3;n++){let i=e.pos[t*3+n];a.setFloat32(r+o+n*4,i,!0),a.setFloat32(r+l+n*4,e.nrm[t*3+n],!0),i<u[n]&&(u[n]=i),i>d[n]&&(d[n]=i)}a.setFloat32(r+s,e.uv[t*2],!0),a.setFloat32(r+s+4,e.uv[t*2+1],!0);for(let n=0;n<4;n++)a.setUint8(r+c+n,Math.round(Math.min(Math.max(e.color[t*4+n],0),1)*255))}return r===0&&(u.fill(0),d.fill(0)),{channels:t,vertexStride:n,vertexCount:r,vertices:i,indices:new Uint32Array(e.idx),aabbMin:u,aabbMax:d}}function Oe(e,t){let n=H(),r=Math.max(1,Math.floor(t.segments)),i=Math.max(1,Math.floor(t.thin)),a=Math.sqrt(i);for(let o=0;o<e.length;o+=i){let i=e[o],s=t.height*i.scale*(a>1?1.1:1),c=t.width*i.scale*a*.5,l=Math.cos(i.yaw),u=Math.sin(i.yaw),d=u,f=l;n.pos.length/3;let p=[];for(let e=0;e<=r;e++){let a=e/r,o=e===r?0:c*(1-a*.85),m=a*a*s*.12,h=i.y+a*s,g=i.x+d*m,_=i.z+f*m,v=t.paint?G(t.paint,a,i.shade):[a,i.phase,i.shade*(.55+.45*a)],y=.65,b=d*.75,x=f*.75,S=U(n,g-l*o,h,_+u*o,0,a,v[0],v[1],v[2],b,y,x);if(e===r){p.push(S,S);continue}let C=U(n,g+l*o,h,_-u*o,1,a,v[0],v[1],v[2],b,y,x);p.push(S,C)}for(let e=0;e<r;e++){let t=p[e*2],r=p[e*2+1],i=p[e*2+2],a=p[e*2+3];n.idx.push(t,r,i),a!==i&&n.idx.push(r,a,i)}}return W(n)}function G(e,t,n){let r=n*(.55+.45*t);return[(e.base[0]+(e.tip[0]-e.base[0])*t)*r,(e.base[1]+(e.tip[1]-e.base[1])*t)*r,(e.base[2]+(e.tip[2]-e.base[2])*t)*r]}function K(e,t,n){let r=e.channels.find(e=>e.semantic===t);if(!r||r.type!==V.Float32||r.components<n)return()=>!1;let i=new DataView(e.vertices.buffer,e.vertices.byteOffset,e.vertices.byteLength);return(t,a)=>{for(let o=0;o<n;o++)a[o]=i.getFloat32(t*e.vertexStride+r.offset+o*4,!0);return!0}}function ke(e,t,n){let r=H(),i=K(e,B.Position,3),a=K(e,B.Normal,3),o=K(e,B.TexCoord0,2),s=e.aabbMin[1],c=Math.max(1e-6,e.aabbMax[1]-e.aabbMin[1]),l=[0,0,0],u=[0,1,0],d=[0,0];for(let f of t){let t=r.pos.length/3,p=Math.cos(f.yaw),m=Math.sin(f.yaw),h=f.up?Ae(f.up):null,g=[0,0,0],_=[0,0,0];for(let t=0;t<e.vertexCount;t++){i(t,l),a(t,u)||(u[0]=0,u[1]=1,u[2]=0),o(t,d)||(d[0]=0,d[1]=0);let e=Math.min(Math.max((l[1]-s)/c,0),1),v=l[0]*f.scale,y=l[1]*f.scale,b=l[2]*f.scale,x=n?G(n,e,f.shade):[e,f.phase,f.shade*(.6+.4*e)];g[0]=v*p+b*m,g[1]=y,g[2]=-v*m+b*p,_[0]=u[0]*p+u[2]*m,_[1]=u[1],_[2]=-u[0]*m+u[2]*p,h&&(h(g),h(_)),U(r,f.x+g[0],f.y+g[1],f.z+g[2],d[0],d[1],x[0],x[1],x[2],_[0],_[1],_[2])}for(let n of e.indices)r.idx.push(t+n)}return W(r)}function Ae(e){let t=Math.hypot(e[0],e[1],e[2])||1,n=e[0]/t,r=e[1]/t,i=e[2]/t,a=Math.hypot(i,n);if(a<1e-6)return null;let o=i/a,s=-n/a,c=r,l=1-c;return e=>{let[t,n,r]=e,i=o*t+s*r;e[0]=t*c+-s*n*a+o*i*l,e[1]=n*c+(s*t-o*r)*a,e[2]=r*c+o*n*a+s*i*l}}function je(e,t,n,r,i,a=!1){let o=H();for(let s of e){let e=t*s.scale*.5,c=n*s.scale;for(let t of[0,Math.PI/2]){let n=s.yaw+t,l=Math.cos(n),u=Math.sin(n),d=i?G(i,0,s.shade):[0,s.phase,s.shade*.6],f=i?G(i,1,s.shade):[1,s.phase,s.shade];if(a){let t=c*.1,n=r.v0+(r.v1-r.v0)*.1,i=(r.u0+r.u1)/2,a=U(o,s.x-l*e,s.y+t,s.z+u*e,r.u0,n,d[0],d[1],d[2],0,1,0),p=U(o,s.x+l*e,s.y+t,s.z-u*e,r.u1,n,d[0],d[1],d[2],0,1,0),m=U(o,s.x,s.y+c,s.z,i,r.v1,f[0],f[1],f[2],0,1,0);o.idx.push(a,p,m);continue}let p=U(o,s.x-l*e,s.y,s.z+u*e,r.u0,r.v0,d[0],d[1],d[2],0,1,0),m=U(o,s.x+l*e,s.y,s.z-u*e,r.u1,r.v0,d[0],d[1],d[2],0,1,0),h=U(o,s.x+l*e,s.y+c,s.z-u*e,r.u1,r.v1,f[0],f[1],f[2],0,1,0),g=U(o,s.x-l*e,s.y+c,s.z+u*e,r.u0,r.v1,f[0],f[1],f[2],0,1,0);o.idx.push(p,m,h,p,h,g)}}return W(o)}function Me(e,t,n){let r=(t-e.originX)/e.sizeX,i=(n-e.originZ)/e.sizeZ;if(!(r>=0&&r<=1&&i>=0&&i<=1))return 0;let a=Math.min(r*e.width-.5,e.width-1),o=Math.min(i*e.height-.5,e.height-1),s=Math.max(Math.floor(a),0),c=Math.max(Math.floor(o),0),l=Math.min(s+1,e.width-1),u=Math.min(c+1,e.height-1),d=Math.min(Math.max(a-s,0),1),f=Math.min(Math.max(o-c,0),1),p=(t,n)=>e.values[n*e.width+t];return((p(s,c)*(1-d)+p(l,c)*d)*(1-f)+(p(s,u)*(1-d)+p(l,u)*d)*f)/255}function Ne(e,t,n){let r=Math.imul(Math.floor(e*64)|0,374761393)^Math.imul(Math.floor(t*64)|0,668265263)^Math.imul(n|0,2246822519);return r=Math.imul(r^r>>>13,1274126177),((r^r>>>16)>>>0)/4294967296}function Pe(e,t){return(n,r)=>{if(t.zones?.excluding(n,r,Math.max(0,e.zonePadding),e.tags,e.seed)||t.density&&Ne(n,r,e.seed)>=Me(t.density,n,r))return null;let i=t.ground?t.ground.heightAt(n,r):t.flatY;if(i===null)return null;let a=t.water?.depthAt(n,r,i);if(a!=null&&a>e.waterDepth)return null;if(!t.ground)return{y:i,up:1};let o=t.ground.normalAt(n,r);return{y:i,up:o?o[1]:1}}}function Fe(e,t,n){let r=De({centerX:e.centerX,centerZ:e.centerZ,size:e.size,count:e.count,seed:e.seed,cellKey:e.cellKey,minScale:e.minScale,maxScale:e.maxScale,minUp:e.minUp,heightMin:e.heightMin,heightMax:e.heightMax},Pe(e,t));if(r.length===0)return[];for(let t of r)t.y-=e.baseY;if(e.look.kind===`mesh`){if(!n)throw Error(`a cell of copies needs the mesh it copies`);let t=Math.max(n.aabbMax[0]-n.aabbMin[0],n.aabbMax[2]-n.aabbMin[2]);return[ke(n,r,e.paint),je(r,t,n.aabbMax[1]-n.aabbMin[1],e.look.card,e.paint,e.look.tent)]}let i={height:e.look.bladeHeight,width:e.look.bladeWidth,paint:e.paint};return[Oe(r,{...i,segments:3,thin:1}),Oe(r,{...i,segments:1,thin:3})]}function Ie(e){let t=[];for(let n of e)t.push(n.vertices.buffer,n.indices.buffer);return t}let q=new Map,Le=new Map,J=e=>{let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(t).then(e=>e.default).finally(()=>URL.revokeObjectURL(t))};function Re(e,t){let n=Le.get(e);return n||(n=t(e),Le.set(e,n)),n}function ze(e){let t=new C;for(let n of e.zones)t.set(n);return{face:null,ground:e.ground?{source:z(e.ground),origin:e.ground.origin}:null,...he({rules:e.rules,farRules:pe(e.rules),seed:e.seed,world:e.world,zones:t,ground:e.ground?new Se(e.ground):null,flatY:e.flatY,water:e.water?new Ce(e.water):null,layers:e.layers})}}async function Be(e,t){let n=await Re(e.provider.source,t),r={centre:e.centre,radius:e.radius,gravity:0,height:null,paint:null,layers:e.layers,fieldNames:e.fieldNames,fieldsAt:null,sampleMany:(t,r)=>{let i=n.sample({world:e.provider.world,seed:e.provider.seed,version:e.provider.version,radius:e.radius,directions:t,count:r});if(i instanceof Promise)throw Error(`a provider used in a worker must answer at once`);return i}},i=new se(e.face,()=>r),a=new C;for(let t of e.zones)a.set(t);return{face:i,...me(i,{rules:e.rules,farRules:pe(e.rules),seed:e.seed,world:e.world,seaLevel:e.seaLevel,layers:e.layers,fieldNames:e.fieldNames,zones:a})}}async function Y(e,t,n){let r=q.get(e);if(!r){if(!t)throw Error(`the plan ${e} is not known to this worker`);r=`plane`in t?ze(t):await Be(t,n),q.set(e,r),q.size>24&&q.delete(q.keys().next().value)}return r}async function X(e,t=J){let n=await Y(e.key,e.spec,t);return(e.far&&n.farPlan?n.farPlan:n.plan).placementsIn(e.x0,e.z0,e.x1,e.z1,[e.layer])}async function Ve(e,t=J){let n=await Re(e.provider.source,t),r=null;if(e.paintKeys){let n=e.paintKeys,i=await Promise.all(n.map((n,r)=>Y(n,e.specs[r],t)));r=(e,t,n,r)=>{let a=i[D(e,t,n).face],o=a.face.planeOf(e,t,n);return o?a.plan.paint(o.x,o.z,r):r}}let i=await re({provider:n,world:e.provider.world,seed:e.provider.seed,version:e.provider.version,radius:e.radius,levels:e.levels,minHeight:e.minHeight,maxHeight:e.maxHeight,...r?{paint:()=>r}:{}},e.node);return{result:i,transfer:[i.heights.buffer,i.paint.buffer,i.paint2.buffer]}}async function He(e,t=J){let n=await Y(e.key,e.spec,t),r=n.ground;if(!r)throw Error(`the plan ${e.key} has no ground to make a page of`);let{origin:i}=r,a=await j(r.source,e.x0,e.z0,e.size,e.paint?(e,t,r,a,o)=>n.plan.paint(e+i.x,t+i.z,o):void 0);return{result:a,transfer:[a.heights.buffer,a.paint.buffer,a.paint2.buffer]}}let Z=new Map,Q=new Map;function $(e){let t=Z.get(e.key);if(!t){if(!e.around)throw Error(`what the foliage ${e.key} grows against is not known to this worker`);let n=new C;for(let t of e.around.zones)n.set(t);t={ground:e.around.ground?new Se(e.around.ground):null,flatY:e.around.flatY,water:e.around.water?new Ce(e.around.water):null,zones:n,density:e.around.density??null},Z.set(e.key,t),Z.size>8&&Z.delete(Z.keys().next().value)}let n=null;if(e.sourceKey!==void 0&&(e.source&&(Q.set(e.sourceKey,e.source),Q.size>8&&Q.delete(Q.keys().next().value)),n=Q.get(e.sourceKey)??null,!n))throw Error(`the mesh ${e.sourceKey} is not known to this worker`);let r=Fe(e.cell,t,n);return{result:r,transfer:Ie(r)}}return typeof self<`u`&&typeof self.importScripts==`function`&&(self.onmessage=e=>{let t=e.data,n=e=>self.postMessage({id:t.id,error:e instanceof Error?e.message:String(e)});if(t.type===`page`)Ve(t).then(e=>self.postMessage({id:t.id,result:e.result},e.transfer),n);else if(t.type===`groundPage`)He(t).then(e=>self.postMessage({id:t.id,result:e.result},e.transfer),n);else if(t.type===`foliageCell`)try{let e=$(t);self.postMessage({id:t.id,result:e.result},e.transfer)}catch(e){n(e)}else X(t).then(e=>self.postMessage({id:t.id,result:e}),n)}),e.foliageCell=$,e.groundPage=He,e.page=Ve,e.placements=X,e})({});";
+export const PLAN_WORKER_SOURCE = "(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=(e,t,n)=>{let r=Math.min(Math.max((n-e)/(t-e||1e-6),0),1);return r*r*(3-2*r)};function n(e,n,r){let i=t(r.rockSlope-.08,r.rockSlope+.08,1-n),a=t(r.snowHeight-.06,r.snowHeight+.06,e)*(1-i*.85),o=t(r.dirtHeight-.15,r.dirtHeight+.15,e)*(1-a)*(1-i),s=(1-i)*(1-a)*(1-o),c=s+o+a+i||1;return[s/c,o/c,a/c,i/c]}function r(e,t,n){let r=Math.min(Math.max(t,0),1)*(e.width-1),i=Math.min(Math.max(n,0),1)*(e.height-1),a=Math.min(Math.floor(r),e.width-2),o=Math.min(Math.floor(i),e.height-2),s=r-a,c=i-o,l=(t,n)=>e.data[n*e.width+t],u=l(a,o)+(l(a+1,o)-l(a,o))*s;return u+(l(a,o+1)+(l(a+1,o+1)-l(a,o+1))*s-u)*c}function i(e,t,n,i,a,o){let s=1/(e.width-1),c=1/(e.height-1),l=(r(e,t+s,n)-r(e,t-s,n))*o/(2*s*i),u=(r(e,t,n+c)-r(e,t,n-c))*o/(2*c*a),d=Math.hypot(l,1,u);return[-l/d,1/d,-u/d]}var a=class e{constructor(e,t,n,r,i=[0,t.height],a=null){this.field=e,this.data=t,this.splat=n,this.flow=r,this.splat2=a,this.infinite=!1,this.bounds=[-t.sizeX/2,-t.sizeZ/2,t.sizeX/2,t.sizeZ/2],[this.minHeight,this.maxHeight]=i}ensureSplats(e){let t=this.field,r=Math.min(t.width,1024),i=Math.min(t.height,1024);if(!this.splat){let e=new Uint8Array(r*i*4),t=this.data.sizeX,a=this.data.sizeZ;for(let o=0;o<i;o++)for(let s=0;s<r;s++){let c=(s/(r-1)-.5)*t,l=(o/(i-1)-.5)*a,u=this.height(c,l)??this.minHeight,d=this.normal(c,l),f=n((u-this.minHeight)/this.span,d?d[1]:1,this.data);for(let t=0;t<4;t++)e[(o*r+s)*4+t]=Math.round(f[t]*255)}this.splat={width:r,height:i,pixels:e}}return e&&!this.splat2&&(this.splat2={width:this.splat.width,height:this.splat.height,pixels:new Uint8Array(this.splat.width*this.splat.height*4)}),{a:this.splat,b:this.splat2}}splats(){return{a:this.splat,b:this.splat2}}get span(){return Math.max(this.maxHeight-this.minHeight,1e-6)}toData(){let e=this.data;return{field:this.field,params:{sizeX:e.sizeX,sizeZ:e.sizeZ,height:e.height,rockSlope:e.rockSlope,dirtHeight:e.dirtHeight,snowHeight:e.snowHeight},splat:this.splat,splat2:this.splat2,flow:this.flow,range:[this.minHeight,this.maxHeight]}}static fromData(t){return new e(t.field,t.params,t.splat,t.flow,t.range,t.splat2)}height(e,t){let n=e/this.data.sizeX+.5,i=t/this.data.sizeZ+.5;return n<0||n>1||i<0||i>1?null:this.minHeight+r(this.field,n,i)*this.span}normal(e,t){let n=e/this.data.sizeX+.5,r=t/this.data.sizeZ+.5;return n<0||n>1||r<0||r>1?null:i(this.field,n,r,this.data.sizeX,this.data.sizeZ,this.span)}paint(e,t,r,i){let a=Math.min(Math.max(e/this.data.sizeX+.5,0),1),o=Math.min(Math.max(t/this.data.sizeZ+.5,0),1),s=[...n((r-this.minHeight)/this.span,i,this.data)],c=e=>{if(!e)return[0,0,0,0];let t=Math.round(a*(e.width-1)),n=(Math.round(o*(e.height-1))*e.width+t)*4;return[e.pixels[n]/255,e.pixels[n+1]/255,e.pixels[n+2]/255,e.pixels[n+3]/255]};if(this.splat||this.splat2){let e=[...c(this.splat),...this.splat2?c(this.splat2):[]],t=e.reduce((e,t)=>e+t,0);t>.001&&(s=e.map(e=>e/t))}if(this.flow){let e=Math.round(a*(this.field.width-1)),t=Math.round(o*(this.field.height-1)),n=d(.45,.85,this.flow[t*this.field.width+e])*.8*s[0];s[0]-=n,s[1]+=n}return s}},o=class e{constructor(e){this.p=e,this.infinite=!0,this.bounds=null,this.minHeight=0,this.maxHeight=e.height}toData(){return{...this.p}}static fromData(t){return new e(t)}height(e,t){return this.sample(e,t)[0]*this.p.height}normal(e,t){let[,n,r]=this.sample(e,t),i=n*this.p.height,a=r*this.p.height,o=Math.hypot(i,1,a);return[-i/o,1/o,-a/o]}paint(e,t,r,i){return n(r/Math.max(this.p.height,1e-6),i,this.p)}sample(e,t){let n=this.p,r=Math.max(n.frequency,1e-6)/Math.max(n.sizeX,1e-6),i=e*r,a=t*r,o=Math.min(Math.max(n.warp,0),1);o>0&&(i+=(u(i+5.2,a+1.3,n.seed+7001)[0]*2-1)*o*.5,a+=(u(i+8.3,a+2.8,n.seed+7003)[0]*2-1)*o*.5);let l=Math.max(1,Math.min(8,Math.floor(n.octaves))),d=Math.min(Math.max(n.erosion,0),4),f=1,p=1,m=0,h=0,g=0,_=0,v=0,y=0;for(let e=0;e<l;e++){let[t,r,o]=u(i*p,a*p,n.seed+e*101),l=t,b=r*p,x=o*p;if(n.ridged>0){let e=t*2-1,r=Math.sqrt(e*e+s*s),i=(r-s)/c,a=e/r/c*2;l=t*(1-n.ridged)+(1-i)*n.ridged,b=b*(1-n.ridged)-a*b*n.ridged,x=x*(1-n.ridged)-a*x*n.ridged}v+=b*f,y+=x*f;let S=d>0?1/(1+d*(v*v+y*y)*.25):1;m+=l*f*S,g+=b*f*S,_+=x*f*S,h+=f,f*=n.persistence,p*=2}return[m/h,g/h*r,_/h*r]}};let s=.06,c=Math.sqrt(1.0036)-s;function l(e,t,n){let r=Math.imul(e,374761393)+Math.imul(t,668265263)+Math.imul(n|0,2147483647)|0;return r=Math.imul(r^r>>>13,1274126177),r=(r^r>>>16)>>>0,r/4294967295}function u(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=e-r,o=t-i,s=a*a*(3-2*a),c=o*o*(3-2*o),u=6*a*(1-a),d=6*o*(1-o),f=l(r,i,n),p=l(r+1,i,n),m=l(r,i+1,n),h=l(r+1,i+1,n),g=p-f,_=m-f,v=f-p-m+h;return[f+g*s+_*c+v*s*c,(g+v*c)*u,(_+v*s)*d]}function d(e,t,n){let r=Math.min(Math.max((n-e)/(t-e||1e-6),0),1);return r*r*(3-2*r)}let f={moisture:{scale:900,octaves:4},temperature:{scale:2400,octaves:3},rock:{scale:500,octaves:4}};function p(...e){let t=-1640531527;for(let n of e)t=Math.imul(t^(n|0),2246822507),t=t^t>>>13|0,t=Math.imul(t,3266489909),t=t^t>>>16|0;return(t>>>0)/4294967296}function m(e){let t=-2128831035;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return t|0}function h(e,t,n,r,i){let a=0,o=0,s=1,c=1;for(let l=0;l<i;l++)a+=_(e*c,t*c,n*c,r+l*131)*s,o+=s,s*=.5,c*=2;return a/o}function g(e,t,n,r){return p(e,t,n,r)}function _(e,t,n,r){let i=Math.floor(e),a=Math.floor(t),o=Math.floor(n),s=e-i,c=t-a,l=n-o,u=s*s*(3-2*s),d=c*c*(3-2*c),f=l*l*(3-2*l),p=(e,t,n)=>g(i+e,a+t,o+n,r),m=p(0,0,0)+(p(1,0,0)-p(0,0,0))*u,h=p(0,1,0)+(p(1,1,0)-p(0,1,0))*u,_=p(0,0,1)+(p(1,0,1)-p(0,0,1))*u,v=p(0,1,1)+(p(1,1,1)-p(0,1,1))*u,y=m+(h-m)*d;return y+(_+(v-_)*d-y)*f}function v(e,t,n,r){let i=0,a=0,o=1,s=1;for(let c=0;c<r;c++)i+=u(e*s,t*s,n+c*131)[0]*o,a+=o,o*=.5,s*=2;return i/a}var y=class{constructor(e){this.inputs=e,this.seeds_={},this.noise_={...f};for(let[t,n]of Object.entries(e.noise??{}))n&&(this.noise_[t]=n);for(let t of Object.keys(this.noise_))this.seeds_[t]=e.seed*7919^m(t)}sample(e,t){let n={},r=(e,t)=>{let r=!1,i=0;Object.defineProperty(n,e,{enumerable:!0,configurable:!0,get:()=>(r||=(i=t(),!0),i),set:e=>{i=e,r=!0}})},i,a=()=>i===void 0?i=this.inputs.ground(e,t):i;r(`height`,()=>a()?.y??NaN),r(`up`,()=>a()?.up??1),r(`slope`,()=>1-(a()?.up??1)),r(`waterDepth`,()=>{let n=a();return n&&this.inputs.waterDepth?this.inputs.waterDepth(e,t,n.y)??-1/0:-1/0}),r(`shoreDistance`,()=>this.inputs.shoreDistance?.(e,t)??1/0);for(let[n,i]of Object.entries(this.noise_)){let a=Math.max(i.scale,1e-6),o=Math.max(1,i.octaves??3);this.inputs.space?r(n,()=>{let r=this.inputs.space(e,t);return h(r[0]/a,r[1]/a,r[2]/a,this.seeds_[n],o)}):r(n,()=>v(e/a,t/a,this.seeds_[n],o))}for(let[i,a]of Object.entries(this.inputs.fields??{}))r(i,()=>a(e,t,n));for(let r of this.inputs.overrides?.(e,t)??[]){let e=n[r.field]??r.value;n[r.field]=e+(r.value-e)*Math.min(Math.max(r.weight,0),1)}return n}};function b(e,t,n){if(e.type===`circle`)return Math.hypot(t-e.x,n-e.z)-e.radius;let r=Math.cos(-(e.yaw??0)),i=Math.sin(-(e.yaw??0)),a=t-e.x,o=n-e.z,s=Math.abs(a*r-o*i)-e.halfX,c=Math.abs(a*i+o*r)-e.halfZ;return Math.hypot(Math.max(s,0),Math.max(c,0))+Math.min(Math.max(s,c),0)}function x(e,t){if(t<=0)return 1;if(e.falloff<=0||t>=e.falloff)return 0;let n=1-t/e.falloff;return n*n*(3-2*n)}function S(e){let t=e.shape,n=(t.type===`circle`?t.radius:Math.hypot(t.halfX,t.halfZ))+Math.max(e.falloff,0);return[t.x-n,t.z-n,t.x+n,t.z+n]}var C=class{constructor(){this.zones_=new Map,this.listeners_=new Set,this.revision=0,this.onChange=null}subscribe(e){return this.listeners_.add(e),()=>{this.listeners_.delete(e)}}changed(e){let t=S(e);this.onChange?.(t,e);for(let n of this.listeners_)n(t,e)}set(e){let t=this.zones_.get(e.id);t&&JSON.stringify(t)===JSON.stringify(e)||(this.zones_.set(e.id,e),this.revision++,t&&this.changed(t),this.changed(e))}delete(e){let t=this.zones_.get(e);t&&(this.zones_.delete(e),this.revision++,this.changed(t))}get(e){return this.zones_.get(e)}all(){return this.zones_.values()}at(e,t,n=0){let r=[];for(let i of this.zones_.values()){let a=x(i,b(i.shape,e,t)-n);a>0&&r.push({zone:i,weight:a})}return r.sort((e,t)=>t.zone.priority-e.zone.priority||(e.zone.id<t.zone.id?-1:1))}excluding(e,t,n,r,i){for(let{zone:a,weight:o}of this.at(e,t,n))if(a.excludes.some(e=>e===`*`||r.includes(e))&&(o>=1||p(i,m(a.id),Math.floor(e*16),Math.floor(t*16))<o))return a;return null}};let w=[{normal:[1,0,0],a:[0,0,-1],b:[0,1,0]},{normal:[-1,0,0],a:[0,0,1],b:[0,1,0]},{normal:[0,1,0],a:[1,0,0],b:[0,0,-1]},{normal:[0,-1,0],a:[1,0,0],b:[0,0,1]},{normal:[0,0,1],a:[1,0,0],b:[0,1,0]},{normal:[0,0,-1],a:[-1,0,0],b:[0,1,0]}],T=Math.PI/4;function E(e,t,n,r=[0,0,0]){let i=w[e],a=Math.tan(t*T),o=Math.tan(n*T),s=i.normal[0]+a*i.a[0]+o*i.b[0],c=i.normal[1]+a*i.a[1]+o*i.b[1],l=i.normal[2]+a*i.a[2]+o*i.b[2],u=Math.hypot(s,c,l);return r[0]=s/u,r[1]=c/u,r[2]=l/u,r}function D(e,t,n){let r=Math.abs(e),i=Math.abs(t),a=Math.abs(n),o;o=r>=i&&r>=a?e>=0?0:1:i>=a?t>=0?2:3:n>=0?4:5;let s=w[o],c=e*s.normal[0]+t*s.normal[1]+n*s.normal[2],l=e*s.a[0]+t*s.a[1]+n*s.a[2],u=e*s.b[0]+t*s.b[1]+n*s.b[2];return{face:o,u:Math.atan(l/c)/T,v:Math.atan(u/c)/T}}function O(e,t,n,r){let i=w[e],a=t*i.normal[0]+n*i.normal[1]+r*i.normal[2];if(a<=1e-6)return null;let o=t*i.a[0]+n*i.a[1]+r*i.a[2],s=t*i.b[0]+n*i.b[1]+r*i.b[2];return{u:Math.atan(o/a)/T,v:Math.atan(s/a)/T}}let k=(e,t)=>2/2**(e-1-t);function A(e,t){let n=k(e,t.level);return{u0:-1+t.ix*n,v0:-1+t.iz*n,span:n}}function j(e,t,n,r,i){let a=r/64;if(e.region){let r=e.region(t-a,n-a,a,67);return r instanceof Promise?r.then(r=>ee(e,t,n,a,r.heights,r,i)):ee(e,t,n,a,r.heights,r,i)}return N(M(e,t,n,r,i))}function*M(e,t,n,r,i){let a=r/64,o=new Float32Array(4489),[s,c,l,u]=e.bounds??[-1/0,-1/0,1/0,1/0];for(let r=0;r<o.length;r++){let i=r%67,d=Math.floor(r/67),f=Math.min(Math.max(t+(i-1)*a,s),l),p=Math.min(Math.max(n+(d-1)*a,c),u);o[r]=e.height(f,p)??e.minHeight,(r+1)%32==0&&(yield .4*(r+1)/o.length)}return yield .4,yield*te(e,t,n,a,o,void 0,i)}function N(e){for(;;){let t=e.next();if(t.done)return t.value}}function ee(e,t,n,r,i,a,o){return N(te(e,t,n,r,i,a,o))}function*te(e,t,n,r,i,a,o){let[s,c,l,u]=e.bounds??[-1/0,-1/0,1/0,1/0],d=1/0,f=-1/0;for(let e=1;e<=65;e++)for(let t=1;t<=65;t++){let n=i[e*67+t];d=Math.min(d,n),f=Math.max(f,n)}let p=Math.max(e.maxHeight-e.minHeight,1e-6),m=new Uint8Array(17956),h=new Uint8Array(17956),g=new Uint8Array(17956);for(let d=0;d<67;d++)for(let f=0;f<67;f++){let _=d*67+f,v=Math.round(Math.min(Math.max((i[_]-e.minHeight)/p,0),1)*65535),y=i[d*67+Math.max(f-1,0)],b=i[d*67+Math.min(f+1,66)],x=i[Math.max(d-1,0)*67+f],S=i[Math.min(d+1,66)*67+f],C=(b-y)/(2*r),w=(S-x)/(2*r),T=Math.hypot(C,1,w),E=-C/T,D=1/T,O=-w/T;m[_*4]=v>>8,m[_*4+1]=v&255,m[_*4+2]=Math.round((E*.5+.5)*255),m[_*4+3]=Math.round((O*.5+.5)*255);let k=Math.min(Math.max(t+(f-1)*r,s),l),A=Math.min(Math.max(n+(d-1)*r,c),u),j=a?.paint,M=a?.paint2,N=j?[j[_*4],j[_*4+1],j[_*4+2],j[_*4+3],...M?[M[_*4],M[_*4+1],M[_*4+2],M[_*4+3]]:[]]:e.paint(k,A,i[_],D);o&&(N=o(k,A,i[_],D,N));for(let e=0;e<4;e++)h[_*4+e]=Math.round(Math.min(Math.max(N[e]??0,0),1)*255),g[_*4+e]=Math.round(Math.min(Math.max(N[e+4]??0,0),1)*255);(_+1)%32==0&&(yield .4+.6*(_+1)/4489)}return{heights:m,paint:h,paint2:g,min:Number.isFinite(d)?d:e.minHeight,max:Number.isFinite(f)?f:e.maxHeight}}function ne(e,t,n,r){let i=w[e];for(let[e,a]of[[i.a,n],[i.b,r]]){let n=e[0]*t[0]+e[1]*t[1]+e[2]*t[2],r=e[0]-t[0]*n,i=e[1]-t[1]*n,o=e[2]-t[2]*n,s=Math.hypot(r,i,o)||1;a[0]=r/s,a[1]=i/s,a[2]=o/s}}function re(e,t){let{u0:n,v0:r,span:i}=A(e.levels,t),a=i/64,o=new Float32Array(13467),s=[0,0,0];for(let e=0;e<67;e++)for(let i=0;i<67;i++){E(t.face,n+(i-1)*a,r+(e-1)*a,s);let c=(e*67+i)*3;o[c]=s[0],o[c+1]=s[1],o[c+2]=s[2]}let c=e.provider.sample({world:e.world,seed:e.seed,version:e.version,radius:e.radius,directions:o,count:4489});return c instanceof Promise?c.then(n=>ie(e,t,o,n.heights,n.paint)):ie(e,t,o,c.heights,c.paint)}function ie(e,t,n,r,i){let a=1/0,o=-1/0;for(let e=1;e<=65;e++)for(let t=1;t<=65;t++){let n=r[e*67+t];a=Math.min(a,n),o=Math.max(o,n)}let s=Math.max(e.maxHeight-e.minHeight,1e-6),c=new Uint8Array(17956),l=new Uint8Array(17956),u=new Uint8Array(17956),d=(t,i,a)=>{let o=Math.min(Math.max(t,0),66),s=Math.min(Math.max(i,0),66)*67+o,c=e.radius+r[s];a[0]=n[s*3]*c,a[1]=n[s*3+1]*c,a[2]=n[s*3+2]*c},f=[0,0,0],p=[0,0,0],m=[0,0,0],h=[0,0,0],g=[0,0,0],_=[0,0,0],v=e.paint?.()??null,y=v?ae(v,n,i):null;for(let a=0;a<67;a++)for(let o=0;o<67;o++){let u=a*67+o,v=Math.round(Math.min(Math.max((r[u]-e.minHeight)/s,0),1)*65535);d(o-1,a,f),d(o+1,a,p),d(o,a-1,m),d(o,a+1,h);let b=[p[0]-f[0],p[1]-f[1],p[2]-f[2]],x=[h[0]-m[0],h[1]-m[1],h[2]-m[2]],S=b[1]*x[2]-b[2]*x[1],C=b[2]*x[0]-b[0]*x[2],w=b[0]*x[1]-b[1]*x[0],T=[n[u*3],n[u*3+1],n[u*3+2]],E=Math.hypot(S,C,w)||1;S/=E,C/=E,w/=E,S*T[0]+C*T[1]+w*T[2]<0&&(S=-S,C=-C,w=-w),ne(t.face,T,g,_);let D=S*g[0]+C*g[1]+w*g[2],O=S*_[0]+C*_[1]+w*_[2],k=S*T[0]+C*T[1]+w*T[2];E=Math.hypot(D,k,O)||1,c[u*4]=v>>8,c[u*4+1]=v&255,c[u*4+2]=Math.round((D/E*.5+.5)*255),c[u*4+3]=Math.round((O/E*.5+.5)*255);let A=0,j=0,M=0,N=0;if(y){let e=y(o,a);A=e[0],j=e[1],M=e[2],N=e[3]}else if(i)A=i[u*4],j=i[u*4+1],M=i[u*4+2],N=i[u*4+3];else{let e=Math.min(Math.max((.9-k/E)*6,0),1);A=1-e,N=e}l[u*4]=Math.round(Math.min(Math.max(A,0),1)*255),l[u*4+1]=Math.round(Math.min(Math.max(j,0),1)*255),l[u*4+2]=Math.round(Math.min(Math.max(M,0),1)*255),l[u*4+3]=Math.round(Math.min(Math.max(N,0),1)*255)}return{heights:c,paint:l,paint2:u,min:Number.isFinite(a)?a:e.minHeight,max:Number.isFinite(o)?o:e.maxHeight}}function ae(e,t,n){let r=Array(81);for(let i=0;i<9;i++)for(let a=0;a<9;a++){let o=1+a*8,s=(1+i*8)*67+o,c=n?[n[s*4],n[s*4+1],n[s*4+2],n[s*4+3]]:[1,0,0,0],l=e(t[s*3],t[s*3+1],t[s*3+2],c);r[i*9+a]=[l[0]??0,l[1]??0,l[2]??0,l[3]??0]}return(e,t)=>{let n=Math.min(Math.max((e-1)/8,0),8),i=Math.min(Math.max((t-1)/8,0),8),a=Math.min(Math.floor(n),7),o=Math.min(Math.floor(i),7),s=n-a,c=i-o,l=r[o*9+a],u=r[o*9+a+1],d=r[(o+1)*9+a],f=r[(o+1)*9+a+1],p=[0,0,0,0];for(let e=0;e<4;e++)p[e]=(l[e]*(1-s)+u[e]*s)*(1-c)+(d[e]*(1-s)+f[e]*s)*c;return p}}let P=e=>e*Math.PI/4,oe=e=>P(e),F=1.5;var se=class{constructor(e,t){this.face=e,this.planet=t,this.tiles_=new Map}facts(){return this.planet()}directionAt(e,t){let n=this.facts(),r=P(n?.radius??1);return E(this.face,e/r,t/r)}planeOf(e,t,n){let r=this.facts(),i=O(this.face,e,t,n);if(!r||!i)return null;let a=P(r.radius);return{x:i.u*a,z:i.v*a}}frameAt(e,t){let n=this.directionAt(e,t),r=[0,0,0],i=[0,0,0];return ne(this.face,n,r,i),{dir:n,eu:r,ev:i}}world(e,t,n){let r=this.facts(),i=this.directionAt(e,n),a=r.radius+t;return[r.centre[0]+i[0]*a,r.centre[1]+i[1]*a,r.centre[2]+i[2]*a]}tile(e,t){let n=Math.floor(e/48),r=Math.floor(t/48),i=`${n},${r}`,a=this.tiles_.get(i);if(a)return this.tiles_.delete(i),this.tiles_.set(i,a),a;let o=this.facts();if(!o?.sampleMany)return null;let s=new Float32Array(3675);for(let e=0;e<35;e++)for(let t=0;t<35;t++){let i=this.directionAt(n*48+(t-1)*F,r*48+(e-1)*F);s[(e*35+t)*3]=i[0],s[(e*35+t)*3+1]=i[1],s[(e*35+t)*3+2]=i[2]}let c=o.sampleMany(s,1225);if(!c)return null;let l={x0:n*48-F,z0:r*48-F,n:35,heights:c.heights,paint:c.paint,fields:c.fields,fieldCount:o.fieldNames.length};return this.tiles_.set(i,l),this.tiles_.size>6e3&&this.tiles_.delete(this.tiles_.keys().next().value),l}cellOf(e,t,n){let r=(t-e.x0)/F,i=(n-e.z0)/F,a=Math.min(Math.max(Math.floor(r),0),e.n-2),o=Math.min(Math.max(Math.floor(i),0),e.n-2);return{i:a,j:o,fx:Math.min(Math.max(r-a,0),1),fz:Math.min(Math.max(i-o,0),1)}}heightAt(e,t){let n=this.tile(e,t);if(!n)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=n.n,c=n.heights,l=c[i*s+r],u=c[i*s+r+1],d=c[(i+1)*s+r],f=c[(i+1)*s+r+1];return(l+(u-l)*a)*(1-o)+(d+(f-d)*a)*o}paintAt(e,t){let n=this.tile(e,t);if(!n?.paint)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=(i+ +(o>.5))*n.n+r+ +(a>.5);return[n.paint[s*4],n.paint[s*4+1],n.paint[s*4+2],n.paint[s*4+3]]}fieldsAt(e,t){let n=this.tile(e,t);if(!n?.fields||n.fieldCount===0)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=n.fieldCount,c=n.n,l=[];for(let e=0;e<s;e++){let t=n.fields[(i*c+r)*s+e],u=n.fields[(i*c+r+1)*s+e],d=n.fields[((i+1)*c+r)*s+e],f=n.fields[((i+1)*c+r+1)*s+e];l.push((t+(u-t)*a)*(1-o)+(d+(f-d)*a)*o)}return l}ground(e,t){let n=this.heightAt(e,t);if(n===null)return null;let r=F,i=this.heightAt(e-r,t),a=this.heightAt(e+r,t),o=this.heightAt(e,t-r),s=this.heightAt(e,t+r);if(i===null||a===null||o===null||s===null)return{y:n,up:1,normal:[0,1,0]};let c=-(a-i)/3,l=-(s-o)/3,u=Math.hypot(c,1,l);return{y:n,up:1/u,normal:[c/u,1/u,l/u]}}worldNormal(e,t,n){let r=this.frameAt(t,n);return[e[0]*r.eu[0]+e[1]*r.dir[0]+e[2]*r.ev[0],e[0]*r.eu[1]+e[1]*r.dir[1]+e[2]*r.ev[1],e[0]*r.eu[2]+e[1]*r.dir[2]+e[2]*r.ev[2]]}environment(){return{ground:(e,t)=>this.ground(e,t),space:(e,t)=>{let n=this.facts(),r=this.directionAt(e,t);return[r[0]*n.radius,r[1]*n.radius,r[2]*n.radius]}}}zoneOnFace(e){let t=this.facts(),n=e.shape;if(!t||n.y===void 0)return null;let r=n.x-t.centre[0],i=n.y-t.centre[1],a=n.z-t.centre[2],o=Math.hypot(r,i,a);if(o<1e-9)return null;let s=this.planeOf(r/o,i/o,a/o),c=oe(t.radius),l=(n.type===`circle`?n.radius:Math.hypot(n.halfX,n.halfZ))+e.falloff;if(!s||Math.abs(s.x)>c+l||Math.abs(s.z)>c+l)return null;if(n.type===`circle`)return{...e,shape:{type:`circle`,x:s.x,z:s.z,radius:n.radius}};let u=this.frameAt(s.x,s.z),d=n.facing??[Math.cos(n.yaw??0),0,Math.sin(n.yaw??0)],f=Math.atan2(d[0]*u.ev[0]+d[1]*u.ev[1]+d[2]*u.ev[2],d[0]*u.eu[0]+d[1]*u.eu[1]+d[2]*u.eu[2]);return{...e,shape:{type:`rect`,x:s.x,z:s.z,halfX:n.halfX,halfZ:n.halfZ,yaw:f}}}sourcesOnFace(e,t){let n=this.facts(),r=[];if(!n)return r;let i=oe(n.radius);for(let a of e){let e=a.x-n.centre[0],o=(a.y??0)-n.centre[1],s=a.z-n.centre[2],c=Math.hypot(e,o,s);if(c<1e-9)continue;let l=this.planeOf(e/c,o/c,s/c);l&&Math.abs(l.x)<=i+t&&Math.abs(l.z)<=i+t&&r.push(l)}return r}};function ce(e,t){if(!Number.isFinite(t))return 0;let n=Math.max(e.blend??0,1e-9),r=e=>{if(e<=0)return 1;if(e>=n)return 0;let t=1-e/n;return t*t*(3-2*t)};return r(e.min===void 0?-1:e.min-t)*r(e.max===void 0?-1:t-e.max)}function le(e){if(!e||!Array.isArray(e.size)||e.size.length!==2||e.size.some(e=>!Number.isFinite(e)||e<=0))throw Error(`grounding.size: two positive model dimensions`);if(![3,5,7,9].includes(e.samples??5))throw Error(`grounding.samples: 3, 5, 7 or 9`);if(![`highest`,`lowest`,`mean`,`center`].includes(e.mode??`highest`))throw Error(`grounding.mode: highest, lowest, mean or center`);if(e.maxRelief!==void 0&&(!Number.isFinite(e.maxRelief)||e.maxRelief<0))throw Error(`grounding.maxRelief: a nonnegative world distance`);if(e.offset!==void 0&&!Number.isFinite(e.offset))throw Error(`grounding.offset: a finite model distance`)}function ue(e,t,n,r,i,a,o={}){if(le(a),![t,n,r,i].every(Number.isFinite)||i<=0)throw Error(`grounding transform: finite position, yaw and positive scale`);let s=a.samples??5,c=Math.cos(r),l=Math.sin(r),u=1/0,d=-1/0,f=0,p=0;for(let r=0;r<s;r++)for(let m=0;m<s;m++){let h=(m/(s-1)-.5)*a.size[0]*i,g=(r/(s-1)-.5)*a.size[1]*i,_=t+h*c+g*l,v=n-h*l+g*c,y=e.ground(_,v);if(!y||!Number.isFinite(y.y)||!Number.isFinite(y.up))return{ok:!1,reason:`noGround`};if(y.up<(o.minUp??0))return{ok:!1,reason:`slope`};let b=e.waterDepth?.(_,v,y.y)??0;if(!Number.isFinite(b))return{ok:!1,reason:`noGround`};if(b>(o.waterDepth??0))return{ok:!1,reason:`water`};u=Math.min(u,y.y),d=Math.max(d,y.y),f+=y.y,m===(s-1)/2&&r===(s-1)/2&&(p=y.y)}let m=d-u,h=f/(s*s);if(m>(a.maxRelief??1/0))return{ok:!1,reason:`relief`};let g={highest:d,lowest:u,mean:h,center:p}[a.mode??`highest`]+(a.offset??0)*i;return{ok:!0,fit:{y:g,min:u,max:d,mean:h,relief:m,supportDepth:Math.max(0,g-u),buriedDepth:Math.max(0,d-g),samples:s*s}}}let de=4e4;function I(e){let t=L(e.anchor,e.anchor.scale?.[1]??1);for(let n of e.members??[])t=Math.max(t,(n.ring?.[1]??0)+L(n,n.scale?.[1]??1));return t}function L(e,t){return Math.max(e.footprint*(e.scaleFootprint?Math.abs(t):1),e.grounding?Math.hypot(...e.grounding.size)*Math.abs(t)/2:0)}let R=(e,t,n)=>e?e[0]+(e[1]-e[0])*t:n;var z=class{constructor(e,t,n,r,i){this.rules=e,this.env=t,this.zones=n,this.seed=r,this.world=i,this.recipes_=new Map,this.layers_=[],this.viable_=new Map,this.groups_=new Map,this.worldHash_=m(i)^r;for(let t of e.recipes)this.recipes_.set(t.id,t);for(let t of e.layers){let n=new Set;for(let r of e.biomes)for(let e of r.recipes)e.layer===t.id&&n.add(e.recipe);let r=0;for(let e of n){let t=this.recipes_.get(e);t&&(r=Math.max(r,I(t)))}this.layers_.push({def:t,hash:m(t.id),maxRadius:r,recipes:n})}}invalidate(){this.viable_.clear(),this.groups_.clear()}layerIndex(e){return this.layers_.findIndex(t=>t.def.id===e)}biomeWeights(e,t){let n=[],r=0;for(let i of this.rules.biomes){let a=this.biomeWeight(i,e,t);a>0&&(n.push({biome:i.id,weight:a}),r+=a)}for(let{zone:i,weight:a}of this.zones.at(e,t)){if(!i.biome)continue;for(let e of n)e.weight*=1-a;r=r*(1-a)+a;let e=n.find(e=>e.biome===i.biome);e?e.weight+=a:n.push({biome:i.biome,weight:a});break}if(r<=0)return[];for(let e of n)e.weight/=r;return n.filter(e=>e.weight>0).sort((e,t)=>t.weight-e.weight||(e.biome<t.biome?-1:1))}biomeAt(e,t){return this.biomeWeights(e,t)[0]?.biome??null}paint(e,t,n){let r=n.length,i=this.biomeWeights(e,t);for(let{biome:e}of i)r=Math.max(r,this.rules.biomes.find(t=>t.id===e)?.paint?.length??0);let a=Array.from({length:r},(e,t)=>n[t]??0);for(let{biome:e,weight:t}of i){let i=this.rules.biomes.find(t=>t.id===e);if(!i?.paint)continue;let o=t*Math.min(Math.max(i.paintStrength??1,0),1);for(let e=0;e<r;e++)a[e]=a[e]+((i.paint[e]??0)-(n[e]??0))*o}let o=a.reduce((e,t)=>e+t,0)||1;return a.map(e=>e/o)}groupsIn(e,t,n,r,i){let a=this.layerIndex(e);if(a<0)return[];let o=this.layers_[a].def.spacing,s=[];for(let e=Math.floor(n/o);e<=Math.floor(i/o);e++)for(let c=Math.floor(t/o);c<=Math.floor(r/o);c++){let o=this.group(a,c,e);typeof o!=`string`&&o.x>=t&&o.x<r&&o.z>=n&&o.z<i&&s.push(o)}return s}placementsIn(e,t,n,r,i){let a=[];for(let o of this.layers_)if(!(i&&!i.includes(o.def.id)))for(let i of this.groupsIn(o.def.id,e,t,n,r))a.push(i.anchor,...i.members);return a}stats(e,t,n,r,i){let a={placed:0,noBiome:0,density:0,noGround:0,slope:0,water:0,relief:0,zone:0,occupied:0,conflict:0},o=this.layerIndex(e);if(o<0)return a;let s=this.layers_[o].def.spacing;for(let e=Math.floor(n/s);e<Math.ceil(i/s);e++)for(let n=Math.floor(t/s);n<Math.ceil(r/s);n++){let t=this.group(o,n,e);typeof t==`string`?a[t]++:a.placed++}return a}explain(e,t){let n=this.layers_.map((n,r)=>{let i=Math.floor(e/n.def.spacing),a=Math.floor(t/n.def.spacing),o=this.group(r,i,a),s=this.viable(r,i,a);return{layer:n.def.id,cell:[i,a],group:typeof o==`string`?null:o.id,rejected:typeof o==`string`?o:null,detail:s.ok?void 0:s.detail}});return{fields:this.env.sample(e,t),biomes:this.biomeWeights(e,t),zones:this.zones.at(e,t).map(({zone:e,weight:t})=>({id:e.id,kind:e.kind,weight:t})),layers:n}}group(e,t,n){let r=`${e}:${t},${n}`,i=this.groups_.get(r);if(i!==void 0)return i;this.groups_.size>de&&this.groups_.clear();let a=this.makeGroup(e,t,n);return this.groups_.set(r,a),a}makeGroup(e,t,n){let r=this.viable(e,t,n);if(!r.ok)return r.reason;let i=r.candidate,a=this.layers_[e],o=a.def.spacing,s=Math.ceil((i.radius+a.maxRadius)/o);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(a===0&&r===0)continue;let o=this.viable(e,t+a,n+r);if(!o.ok)continue;let s=o.candidate;if((s.priority>i.priority||s.priority===i.priority&&(s.gz<n||s.gz===n&&s.gx<t))&&Math.hypot(s.x-i.x,s.z-i.z)<i.radius+s.radius)return`conflict`}let c=`${a.def.id}@${a.def.version??1}:${t},${n}`,l=i.recipe,u=i.anchor,d=[],f=[u];for(let[r,o]of(l.members??[]).entries()){let s=(e,i)=>p(this.worldHash_,a.hash,t,n,1e3+r*37+e,i),u=o.count?o.count[0]+Math.floor(s(0,0)*(o.count[1]-o.count[0]+1)):1;for(let t=0;t<u;t++){if(o.chance!==void 0&&s(1,t)>=o.chance)continue;let n=R(o.arc,s(2,t),s(2,t)*360)*Math.PI/180,r=R(o.ring,s(3,t),0),u=i.x+Math.cos(n)*r,p=i.z+Math.sin(n)*r,m=this.env.sample(u,p),h=this.place(c,a.def,l,o,t,u,p,i.biome,m,s(4,t));typeof h!=`string`&&this.zones.excluding(u,p,h.footprint,this.tagsOf(a.def,l,o),this.seed)===null&&this.occupied(e,u,p,h.footprint)===null&&(f.some(e=>Math.hypot(e.x-u,e.z-p)<e.footprint+h.footprint)||(d.push(h),f.push(h)))}}return{id:c,layer:a.def.id,x:i.x,z:i.z,radius:i.radius,priority:i.priority,anchor:u,members:d}}place(e,t,n,r,i,a,o,s,c,l){let u=this.standing(c,r);if(u)return u;let d=p(this.worldHash_,m(e),m(r.id),i,7),f=(l||d)*Math.PI*2,h=R(r.scale,p(this.worldHash_,m(e),i,11),1),g;if(r.grounding){let e=ue(this.env.inputs,a,o,f,h,r.grounding,r);if(!e.ok)return e.reason;g=e.fit}let _=this.env.inputs.ground(a,o),v=_?.up??1,y=_?.normal??[0,v,Math.sqrt(Math.max(0,1-v*v))];return{id:`${e}/${n.id}@${n.version}/${r.id}.${i}`,group:e,layer:t.id,recipe:n.id,recipeVersion:n.version,member:r.id,biome:s,zone:this.zones.at(a,o)[0]?.zone.id??null,x:a,y:g?.y??c.height,z:o,yaw:f,scale:h,normal:y,attach:r.attach??`upright`,mesh:typeof r.mesh==`number`?r.mesh:0,material:typeof r.material==`number`?r.material:0,plant:r.plant??null,interactive:r.interactive??null,footprint:L(r,h),canopy:(r.canopy??r.footprint)*(r.scaleFootprint?Math.abs(h):1),far:r.far??null,...g?{grounding:g}:{}}}standing(e,t){return Number.isFinite(e.height)?e.up<(t.minUp??0)?`slope`:e.waterDepth>(t.waterDepth??0)?`water`:null:`noGround`}tagsOf(e,t,n){return[e.id,t.id,n.interactive?`interactive`:`decor`,...t.tags??[],...n.tags??[]]}viable(e,t,n){let r=`${e}:${t},${n}`,i=this.viable_.get(r);if(i)return i;this.viable_.size>de&&this.viable_.clear();let a=this.makeViable(e,t,n);return this.viable_.set(r,a),a}makeViable(e,t,n){let r=this.layers_[e],i=r.def.spacing,a=e=>p(this.worldHash_,r.hash,t,n,e),o=(t+a(1))*i,s=(n+a(2))*i,c=this.biomeWeights(o,s);if(c.length===0)return{ok:!1,reason:`noBiome`};let l=a(3),u=c[c.length-1].biome;for(let e of c){if(l<e.weight){u=e.biome;break}l-=e.weight}let d=(this.rules.biomes.find(e=>e.id===u)?.recipes??[]).filter(e=>e.layer===r.def.id&&this.recipes_.has(e.recipe)),f=a(4),m=null;for(let e of d){if(f<e.density){m=this.recipes_.get(e.recipe);break}f-=e.density}if(!m)return{ok:!1,reason:`density`};let h=this.env.sample(o,s),g=`${r.def.id}@${r.def.version??1}:${t},${n}`,_=this.place(g,r.def,m,m.anchor,0,o,s,u,h,0);if(typeof _==`string`)return{ok:!1,reason:_};let v=this.zones.excluding(o,s,_.footprint,this.tagsOf(r.def,m,m.anchor),this.seed);if(v)return{ok:!1,reason:`zone`,detail:v.id};let y=this.occupied(e,o,s,_.footprint);return y?{ok:!1,reason:`occupied`,detail:y}:{ok:!0,candidate:{gx:t,gz:n,x:o,z:s,priority:a(5),biome:u,recipe:m,radius:I(m),anchor:_}}}occupied(e,t,n,r){for(let i=0;i<e;i++){let e=this.layers_[i];if(e.def.occupies===!1)continue;let a=e.def.spacing,o=r+e.maxRadius;for(let e=Math.floor((n-o)/a);e<=Math.floor((n+o)/a);e++)for(let s=Math.floor((t-o)/a);s<=Math.floor((t+o)/a);s++){let a=this.group(i,s,e);if(typeof a!=`string`){for(let e of[a.anchor,...a.members])if(Math.hypot(e.x-t,e.z-n)<e.footprint+r)return e.id}}}return null}biomeWeight(e,t,n){let r=e.transition??0,i=t,a=n;if(r>0){let o=m(e.id)^this.worldHash_;i+=(v(t/r,n/r,o,2)-.5)*2*r,a+=(v(t/r,n/r,o+1,2)-.5)*2*r}let o=this.env.sample(i,a),s=e.weight??1;for(let t of e.conditions)if(s*=ce(t,o[t.field]??NaN),s<=0)return 0;return s}};function fe(e){return e.layers.some(e=>(e.farSpacing??1)>1)?{...e,layers:e.layers.map(e=>(e.farSpacing??1)>1?{...e,spacing:e.spacing*e.farSpacing}:e)}:null}function pe(e,t){let n={};t.layers.forEach((t,r)=>{n[`paint.${t}`]=(t,n)=>e.paintAt(t,n)?.[r]??0}),t.fieldNames.forEach((t,r)=>{n[t]=(t,n)=>e.fieldsAt(t,n)?.[r]??0});let r=new y({seed:t.seed,noise:t.rules.noise,fields:{...n,...t.rules.fields},...e.environment(),waterDepth:(e,n,r)=>t.seaLevel-r,overrides:(e,n)=>{let r=[];for(let{zone:i,weight:a}of t.zones.at(e,n))for(let[e,t]of Object.entries(i.fields??{}))r.push({field:e,value:t,weight:a});return r}}),i=`${t.world}#${e.face}`;return{plan:new z(t.rules,r,t.zones,t.seed,i),farPlan:t.farRules?new z(t.farRules,r,t.zones,t.seed,i):null}}function me(e){let t={};e.ground&&e.layers.forEach((n,r)=>{t[`paint.${n}`]=(t,n)=>e.ground.paintAt(t,n)?.[r]??0});let n=new y({seed:e.seed,noise:e.rules.noise,fields:{...t,...e.rules.fields},ground:(t,n)=>{if(e.ground){let r=e.ground.heightAt(t,n);if(r===null)return null;let i=e.ground.normalAt(t,n)??[0,1,0];return{y:r,up:i[1],normal:i}}return{y:e.flatY,up:1,normal:[0,1,0]}},waterDepth:(t,n,r)=>e.water?.depthAt(t,n,r)??null,shoreDistance:(t,n)=>e.water?.shoreAt(t,n)??null,overrides:(t,n)=>{let r=[];for(let{zone:i,weight:a}of e.zones.at(t,n))for(let[e,t]of Object.entries(i.fields??{}))r.push({field:e,value:t,weight:a});return r}});return{plan:new z(e.rules,n,e.zones,e.seed,e.world),farPlan:e.farRules?new z(e.farRules,n,e.zones,e.seed,e.world):null}}var he=class{constructor(e,t){this.source=e,this.cell=t}node(e,t){let n=e*this.cell,r=t*this.cell,i=this.source.bounds;return i&&(n=Math.min(Math.max(n,i[0]),i[2]),r=Math.min(Math.max(r,i[1]),i[3])),this.source.height(n,r)}covers(e,t){let n=this.source.bounds;return!n||e>=n[0]&&e<=n[2]&&t>=n[1]&&t<=n[3]}height(e,t){let n=this.corners(e,t);if(!n)return null;let[r,i,a,o,s,c]=n;return s+c<=1?r+(i-r)*s+(a-r)*c:o+(a-o)*(1-s)+(i-o)*(1-c)}normal(e,t){let n=this.corners(e,t);if(!n)return null;let[r,i,a,o,s,c]=n,l=(s+c<=1?i-r:o-a)/this.cell,u=(s+c<=1?a-r:o-i)/this.cell,d=Math.hypot(l,1,u);return[-l/d,1/d,-u/d]}tile(e,t){let n=new Float32Array(3267);for(let r=0;r<=32;r++)for(let i=0;i<=32;i++){let a=this.node(e*32+i,t*32+r);if(a===null)return null;let o=(r*33+i)*3;n[o]=i*this.cell,n[o+1]=a,n[o+2]=r*this.cell}let r=new Uint32Array(6144),i=0;for(let e=0;e<32;e++)for(let t=0;t<32;t++){let n=e*33+t,a=n+1,o=n+33,s=o+1;r.set([n,o,a,a,o,s],i),i+=6}return{x0:e*32*this.cell,z0:t*32*this.cell,positions:n,indices:r}}raycast(e,t,n,r,i,a,o){let s=Math.hypot(r,i,a);if(s<=0)return null;r/=s,i/=s,a/=s;let c=this.cell,l=Math.floor(e/c),u=Math.floor(n/c),d=r>0?1:-1,f=a>0?1:-1,p=r===0?1/0:Math.abs(c/r),m=a===0?1/0:Math.abs(c/a),h=r===0?1/0:((r>0?(l+1)*c:l*c)-e)/r,g=a===0?1/0:((a>0?(u+1)*c:u*c)-n)/a,_=0;for(let s=0;s<1e6&&_<=o;s++){let s=this.node(l,u),v=this.node(l+1,u),y=this.node(l,u+1),b=this.node(l+1,u+1);if(s===null||v===null||y===null||b===null)return null;let x=l*c,S=u*c;for(let l of[[[x,s,S],[x,y,S+c],[x+c,v,S]],[[x+c,v,S],[x,y,S+c],[x+c,b,S+c]]]){let s=ge(e,t,n,r,i,a,l[0],l[1],l[2]);if(s&&s.t<=o&&this.covers(e+r*s.t,n+a*s.t))return{distance:s.t,point:[e+r*s.t,t+i*s.t,n+a*s.t],normal:s.n}}if(h<g?(_=h,h+=p,l+=d):(_=g,g+=m,u+=f),r===0&&a===0)break}return null}corners(e,t){if(!this.covers(e,t))return null;let n=e/this.cell,r=t/this.cell,i=Math.floor(n),a=Math.floor(r),o=this.node(i,a),s=this.node(i+1,a),c=this.node(i,a+1),l=this.node(i+1,a+1);return o===null||s===null||c===null||l===null?null:[o,s,c,l,n-i,r-a]}};function ge(e,t,n,r,i,a,o,s,c){let l=s[0]-o[0],u=s[1]-o[1],d=s[2]-o[2],f=c[0]-o[0],p=c[1]-o[1],m=c[2]-o[2],h=i*m-a*p,g=a*f-r*m,_=r*p-i*f,v=l*h+u*g+d*_;if(Math.abs(v)<1e-12)return null;let y=1/v,b=e-o[0],x=t-o[1],S=n-o[2],C=(b*h+x*g+S*_)*y;if(C<-1e-9||C>1+1e-9)return null;let w=x*d-S*u,T=S*l-b*d,E=b*u-x*l,D=(r*w+i*T+a*E)*y;if(D<-1e-9||C+D>1+1e-9)return null;let O=(f*w+p*T+m*E)*y;if(O<0)return null;let k=u*m-d*p,A=d*f-l*m,j=l*p-u*f;A<0&&(k=-k,A=-A,j=-j);let M=Math.hypot(k,A,j)||1;return{t:O,n:[k/M,A/M,j/M]}}function _e(e,t,n,r){let i=e.height(n-t.x,r-t.z);return i===null?null:t.y+i}function ve(e,t,n,r){return e.normal(n-t.x,r-t.z)}function ye(e,t,n,r,i){let a=r-n.x,o=i-n.z,s=t.height(a,o),c=t.normal(a,o);return s===null||!c?null:e.paint(a,o,s,c[1])}var be=class{constructor(e,t,n){this.base=e,this.dx=t,this.dz=n,this.infinite=e.infinite,this.bounds=e.bounds,this.minHeight=e.minHeight,this.maxHeight=e.maxHeight}height(e,t){return this.base.height(e+this.dx,t+this.dz)}normal(e,t){return this.base.normal(e+this.dx,t+this.dz)}paint(e,t,n,r){return this.base.paint(e+this.dx,t+this.dz,n,r)}};function B(e){let t=e.source.kind===`field`?a.fromData(e.source.data):o.fromData(e.source.data);return e.shift?new be(t,e.shift.x,e.shift.z):t}var xe=class{constructor(e){this.source_=B(e),this.surface_=new he(this.source_,e.cell),this.origin_=e.origin}heightAt(e,t){return _e(this.surface_,this.origin_,e,t)}normalAt(e,t){return ve(this.surface_,this.origin_,e,t)}paintAt(e,t){return ye(this.source_,this.surface_,this.origin_,e,t)}},Se=class{constructor(e){this.data=e}lerp(e,t){let{minX:n,minZ:r,sizeX:i,sizeZ:a,nx:o,nz:s}=this.data.grid;if(o<2||s<2)return null;let c=(e-n)/i,l=(t-r)/a;if(c<0||c>1||l<0||l>1)return null;let u=c*(o-1),d=l*(s-1),f=Math.min(Math.floor(u),o-2),p=Math.min(Math.floor(d),s-2),m=u-f,h=d-p,g=p*o+f,_=e=>(e[g]*(1-m)+e[g+1]*m)*(1-h)+(e[g+o]*(1-m)+e[g+o+1]*m)*h;return{height:_(this.data.height),shore:_(this.data.shore)}}depthAt(e,t,n){let r=this.lerp(e,t);return r?r.shore>0?r.height-n:null:this.data.ocean?this.data.ocean.level-n:null}shoreAt(e,t){let n=this.lerp(e,t);return n?-n.shore:this.data.ocean?-1e6:null}};let V={Position:0,Color:1,TexCoord0:2,Normal:3,Tangent:4,Joints:5,Weights:6,TexCoord1:7};new Set(Object.values(V));let H={Float32:0,UNorm8:1,UInt16:2};function Ce(e){return e===H.UNorm8?1:e===H.UInt16?2:4}function we(e){let t=[],n=0;for(let r of e)t.push({...r,offset:n}),n+=r.components*Ce(r.type),n=n+3&-4;return{channels:t,vertexStride:n}}function Te(e){let t=e|0;return()=>{t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}function Ee(e,t){let n=Te(Math.imul(e.seed|0,73856093)^Math.imul(e.cellKey|0,19349663)^2654435769),r=[];for(let i=0;i<e.count;i++){let i=e.centerX+(n()-.5)*e.size,a=e.centerZ+(n()-.5)*e.size,o=n()*Math.PI*2,s=e.minScale+(e.maxScale-e.minScale)*n(),c=n(),l=.7+.3*n(),u=t(i,a);!u||u.up<e.minUp||u.y<e.heightMin||u.y>e.heightMax||r.push({x:i-e.centerX,y:u.y,z:a-e.centerZ,yaw:o,scale:s,phase:c,shade:l})}return r}let De=e=>e===void 0?1:Math.min(Math.max(Math.round(e),0),3)/3,U=(e=1)=>({alpha:e,pos:[],uv:[],color:[],nrm:[],idx:[]});function W(e,t,n,r,i,a,o,s,c,l,u,d){return e.pos.push(t,n,r),e.uv.push(i,a),e.color.push(o,s,c,e.alpha),e.nrm.push(l,u,d),e.pos.length/3-1}function G(e){let{channels:t,vertexStride:n}=we([{semantic:V.Position,components:3,type:H.Float32},{semantic:V.TexCoord0,components:2,type:H.Float32},{semantic:V.Color,components:4,type:H.UNorm8},{semantic:V.Normal,components:3,type:H.Float32}]),r=e.pos.length/3,i=new Uint8Array(Math.max(1,r)*n),a=new DataView(i.buffer),o=t[0].offset,s=t[1].offset,c=t[2].offset,l=t[3].offset,u=[1/0,1/0,1/0],d=[-1/0,-1/0,-1/0];for(let t=0;t<r;t++){let r=t*n;for(let n=0;n<3;n++){let i=e.pos[t*3+n];a.setFloat32(r+o+n*4,i,!0),a.setFloat32(r+l+n*4,e.nrm[t*3+n],!0),i<u[n]&&(u[n]=i),i>d[n]&&(d[n]=i)}a.setFloat32(r+s,e.uv[t*2],!0),a.setFloat32(r+s+4,e.uv[t*2+1],!0);for(let n=0;n<4;n++)a.setUint8(r+c+n,Math.round(Math.min(Math.max(e.color[t*4+n],0),1)*255))}return r===0&&(u.fill(0),d.fill(0)),{channels:t,vertexStride:n,vertexCount:r,vertices:i,indices:new Uint32Array(e.idx),aabbMin:u,aabbMax:d}}function Oe(e,t){let n=U(De(t.band)),r=Math.max(1,Math.floor(t.segments)),i=Math.max(1,Math.floor(t.thin)),a=Math.sqrt(i);for(let o=0;o<e.length;o+=i){let i=e[o],s=t.height*i.scale*(a>1?1.1:1),c=t.width*i.scale*a*.5,l=Math.cos(i.yaw),u=Math.sin(i.yaw),d=u,f=l;n.pos.length/3;let p=[];for(let e=0;e<=r;e++){let a=e/r,o=e===r?0:c*(1-a*.85),m=a*a*s*.12,h=i.y+a*s,g=i.x+d*m,_=i.z+f*m,v=t.paint?K(t.paint,a,i.shade):[a,i.phase,i.shade*(.55+.45*a)],y=.65,b=d*.75,x=f*.75,S=W(n,g-l*o,h,_+u*o,0,a,v[0],v[1],v[2],b,y,x);if(e===r){p.push(S,S);continue}let C=W(n,g+l*o,h,_-u*o,1,a,v[0],v[1],v[2],b,y,x);p.push(S,C)}for(let e=0;e<r;e++){let t=p[e*2],r=p[e*2+1],i=p[e*2+2],a=p[e*2+3];n.idx.push(t,r,i),a!==i&&n.idx.push(r,a,i)}}return G(n)}function K(e,t,n){let r=n*(.55+.45*t);return[(e.base[0]+(e.tip[0]-e.base[0])*t)*r,(e.base[1]+(e.tip[1]-e.base[1])*t)*r,(e.base[2]+(e.tip[2]-e.base[2])*t)*r]}function q(e,t,n){let r=e.channels.find(e=>e.semantic===t);if(!r||r.type!==H.Float32||r.components<n)return()=>!1;let i=new DataView(e.vertices.buffer,e.vertices.byteOffset,e.vertices.byteLength);return(t,a)=>{for(let o=0;o<n;o++)a[o]=i.getFloat32(t*e.vertexStride+r.offset+o*4,!0);return!0}}function ke(e,t,n,r){let i=U(De(r)),a=q(e,V.Position,3),o=q(e,V.Normal,3),s=q(e,V.TexCoord0,2),c=e.aabbMin[1],l=Math.max(1e-6,e.aabbMax[1]-e.aabbMin[1]),u=[0,0,0],d=[0,1,0],f=[0,0];for(let r of t){let t=i.pos.length/3,p=Math.cos(r.yaw),m=Math.sin(r.yaw),h=r.up?je(r.up):null,g=[0,0,0],_=[0,0,0];for(let t=0;t<e.vertexCount;t++){a(t,u),o(t,d)||(d[0]=0,d[1]=1,d[2]=0),s(t,f)||(f[0]=0,f[1]=0);let e=Math.min(Math.max((u[1]-c)/l,0),1),v=u[0]*r.scale,y=u[1]*r.scale,b=u[2]*r.scale,x=n?K(n,e,r.shade):[e,r.phase,r.shade*(.6+.4*e)];g[0]=v*p+b*m,g[1]=y,g[2]=-v*m+b*p,_[0]=d[0]*p+d[2]*m,_[1]=d[1],_[2]=-d[0]*m+d[2]*p,h&&(h(g),h(_)),W(i,r.x+g[0],r.y+g[1],r.z+g[2],f[0],f[1],x[0],x[1],x[2],_[0],_[1],_[2])}for(let n of e.indices)i.idx.push(t+n)}return G(i)}function Ae(e,t,n,r=1.25){let i=Math.min(Math.max(t,.001),1);if(i>=1)return e;let a=Math.min(Math.sqrt(1/i),Math.max(n,1)),o=[];for(let t of e)t.phase<i*r&&o.push({...t,scale:t.scale*a});return o}function je(e){let t=Math.hypot(e[0],e[1],e[2])||1,n=e[0]/t,r=e[1]/t,i=e[2]/t,a=Math.hypot(i,n);if(a<1e-6)return null;let o=i/a,s=-n/a,c=r,l=1-c;return e=>{let[t,n,r]=e,i=o*t+s*r;e[0]=t*c+-s*n*a+o*i*l,e[1]=n*c+(s*t-o*r)*a,e[2]=r*c+o*n*a+s*i*l}}function Me(e,t,n,r,i,a=!1){let o=U();for(let s of e){let e=t*s.scale*.5,c=n*s.scale;for(let t of[0,Math.PI/2]){let n=s.yaw+t,l=Math.cos(n),u=Math.sin(n),d=i?K(i,0,s.shade):[0,s.phase,s.shade*.6],f=i?K(i,1,s.shade):[1,s.phase,s.shade];if(a){let t=c*.1,n=r.v0+(r.v1-r.v0)*.1,i=(r.u0+r.u1)/2,a=W(o,s.x-l*e,s.y+t,s.z+u*e,r.u0,n,d[0],d[1],d[2],0,1,0),p=W(o,s.x+l*e,s.y+t,s.z-u*e,r.u1,n,d[0],d[1],d[2],0,1,0),m=W(o,s.x,s.y+c,s.z,i,r.v1,f[0],f[1],f[2],0,1,0);o.idx.push(a,p,m);continue}let p=W(o,s.x-l*e,s.y,s.z+u*e,r.u0,r.v0,d[0],d[1],d[2],0,1,0),m=W(o,s.x+l*e,s.y,s.z-u*e,r.u1,r.v0,d[0],d[1],d[2],0,1,0),h=W(o,s.x+l*e,s.y+c,s.z-u*e,r.u1,r.v1,f[0],f[1],f[2],0,1,0),g=W(o,s.x-l*e,s.y+c,s.z+u*e,r.u0,r.v1,f[0],f[1],f[2],0,1,0);o.idx.push(p,m,h,p,h,g)}}return G(o)}function Ne(e,t,n){let r=(t-e.originX)/e.sizeX,i=(n-e.originZ)/e.sizeZ;if(!(r>=0&&r<=1&&i>=0&&i<=1))return 0;let a=Math.min(r*e.width-.5,e.width-1),o=Math.min(i*e.height-.5,e.height-1),s=Math.max(Math.floor(a),0),c=Math.max(Math.floor(o),0),l=Math.min(s+1,e.width-1),u=Math.min(c+1,e.height-1),d=Math.min(Math.max(a-s,0),1),f=Math.min(Math.max(o-c,0),1),p=(t,n)=>e.values[n*e.width+t];return((p(s,c)*(1-d)+p(l,c)*d)*(1-f)+(p(s,u)*(1-d)+p(l,u)*d)*f)/255}function Pe(e,t,n){let r=Math.imul(Math.floor(e*64)|0,374761393)^Math.imul(Math.floor(t*64)|0,668265263)^Math.imul(n|0,2246822519);return r=Math.imul(r^r>>>13,1274126177),((r^r>>>16)>>>0)/4294967296}function Fe(e,t){return(n,r)=>{if(t.zones?.excluding(n,r,Math.max(0,e.zonePadding),e.tags,e.seed)||t.density&&Pe(n,r,e.seed)>=Ne(t.density,n,r))return null;let i=t.ground?t.ground.heightAt(n,r):t.flatY;if(i===null)return null;let a=t.water?.depthAt(n,r,i);if(a!=null&&a>e.waterDepth)return null;if(!t.ground)return{y:i,up:1};let o=t.ground.normalAt(n,r);return{y:i,up:o?o[1]:1}}}function Ie(e,t,n){let r=Ee({centerX:e.centerX,centerZ:e.centerZ,size:e.size,count:e.count,seed:e.seed,cellKey:e.cellKey,minScale:e.minScale,maxScale:e.maxScale,minUp:e.minUp,heightMin:e.heightMin,heightMax:e.heightMax},Fe(e,t));if(r.length===0)return[];for(let t of r)t.y-=e.baseY;let i=Math.min(Math.max(Math.floor(e.far.levels),1),3),a=t=>Math.min(Math.max(e.far.keep,.01),1)**+t,o=t=>Math.min(Math.sqrt(1/a(t)),Math.max(e.far.grow,1)),s=e.far.only??null,c=s===null?void 0:s,l=t=>{let i=t===0?r:Ae(r,a(t),e.far.grow);return i.length===0?null:ke(n,i,e.paint,c)},u=t=>{if(e.look.kind!==`grass`)return null;let n={height:e.look.bladeHeight,width:e.look.bladeWidth,paint:e.paint,band:c};if(t===0)return Oe(r,{...n,segments:3,thin:1});let i=Ae(r,a(t),1);return i.length===0?null:Oe(i,{...n,height:n.height*1.1,width:n.width*o(t),segments:1,thin:1})};if(e.look.kind===`mesh`&&!n)throw Error(`a cell of copies needs the mesh it copies`);let d=e.look.kind===`mesh`?l:u;if(s!==null){let e=d(Math.min(Math.max(Math.floor(s),0),i));return e?[e]:[]}if(e.look.kind===`mesh`&&e.far.cards){let t=Math.max(n.aabbMax[0]-n.aabbMin[0],n.aabbMax[2]-n.aabbMin[2]);return[l(0),Me(r,t,n.aabbMax[1]-n.aabbMin[1],e.look.card,e.paint,e.look.tent)]}let f=[];for(let e=0;e<=i;e++){let t=d(e);if(!t)break;f.push(t)}return f}function Le(e){let t=[];for(let n of e)t.push(n.vertices.buffer,n.indices.buffer);return t}let J=new Map,Re=new Map,Y=e=>{let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(t).then(e=>e.default).finally(()=>URL.revokeObjectURL(t))};function ze(e,t){let n=Re.get(e);return n||(n=t(e),Re.set(e,n)),n}function Be(e){let t=new C;for(let n of e.zones)t.set(n);return{face:null,ground:e.ground?{source:B(e.ground),origin:e.ground.origin}:null,...me({rules:e.rules,farRules:fe(e.rules),seed:e.seed,world:e.world,zones:t,ground:e.ground?new xe(e.ground):null,flatY:e.flatY,water:e.water?new Se(e.water):null,layers:e.layers})}}async function Ve(e,t){let n=await ze(e.provider.source,t),r={centre:e.centre,radius:e.radius,gravity:0,height:null,paint:null,layers:e.layers,fieldNames:e.fieldNames,fieldsAt:null,sampleMany:(t,r)=>{let i=n.sample({world:e.provider.world,seed:e.provider.seed,version:e.provider.version,radius:e.radius,directions:t,count:r});if(i instanceof Promise)throw Error(`a provider used in a worker must answer at once`);return i}},i=new se(e.face,()=>r),a=new C;for(let t of e.zones)a.set(t);return{face:i,...pe(i,{rules:e.rules,farRules:fe(e.rules),seed:e.seed,world:e.world,seaLevel:e.seaLevel,layers:e.layers,fieldNames:e.fieldNames,zones:a})}}async function X(e,t,n){let r=J.get(e);if(!r){if(!t)throw Error(`the plan ${e} is not known to this worker`);r=`plane`in t?Be(t):await Ve(t,n),J.set(e,r),J.size>24&&J.delete(J.keys().next().value)}return r}async function He(e,t=Y){let n=await X(e.key,e.spec,t);return(e.far&&n.farPlan?n.farPlan:n.plan).placementsIn(e.x0,e.z0,e.x1,e.z1,[e.layer])}async function Ue(e,t=Y){let n=await ze(e.provider.source,t),r=null;if(e.paintKeys){let n=e.paintKeys,i=await Promise.all(n.map((n,r)=>X(n,e.specs[r],t)));r=(e,t,n,r)=>{let a=i[D(e,t,n).face],o=a.face.planeOf(e,t,n);return o?a.plan.paint(o.x,o.z,r):r}}let i=await re({provider:n,world:e.provider.world,seed:e.provider.seed,version:e.provider.version,radius:e.radius,levels:e.levels,minHeight:e.minHeight,maxHeight:e.maxHeight,...r?{paint:()=>r}:{}},e.node);return{result:i,transfer:[i.heights.buffer,i.paint.buffer,i.paint2.buffer]}}async function We(e,t=Y){let n=await X(e.key,e.spec,t),r=n.ground;if(!r)throw Error(`the plan ${e.key} has no ground to make a page of`);let{origin:i}=r,a=await j(r.source,e.x0,e.z0,e.size,e.paint?(e,t,r,a,o)=>n.plan.paint(e+i.x,t+i.z,o):void 0);return{result:a,transfer:[a.heights.buffer,a.paint.buffer,a.paint2.buffer]}}let Z=new Map,Q=new Map;function $(e){let t=Z.get(e.key);if(!t){if(!e.around)throw Error(`what the foliage ${e.key} grows against is not known to this worker`);let n=new C;for(let t of e.around.zones)n.set(t);t={ground:e.around.ground?new xe(e.around.ground):null,flatY:e.around.flatY,water:e.around.water?new Se(e.around.water):null,zones:n,density:e.around.density??null},Z.set(e.key,t),Z.size>8&&Z.delete(Z.keys().next().value)}let n=null;if(e.sourceKey!==void 0&&(e.source&&(Q.set(e.sourceKey,e.source),Q.size>8&&Q.delete(Q.keys().next().value)),n=Q.get(e.sourceKey)??null,!n))throw Error(`the mesh ${e.sourceKey} is not known to this worker`);let r=Ie(e.cell,t,n);return{result:r,transfer:Le(r)}}return typeof self<`u`&&typeof self.importScripts==`function`&&(self.onmessage=e=>{let t=e.data,n=e=>self.postMessage({id:t.id,error:e instanceof Error?e.message:String(e)});if(t.type===`page`)Ue(t).then(e=>self.postMessage({id:t.id,result:e.result},e.transfer),n);else if(t.type===`groundPage`)We(t).then(e=>self.postMessage({id:t.id,result:e.result},e.transfer),n);else if(t.type===`foliageCell`)try{let e=$(t);self.postMessage({id:t.id,result:e.result},e.transfer)}catch(e){n(e)}else He(t).then(e=>self.postMessage({id:t.id,result:e}),n)}),e.foliageCell=$,e.groundPage=We,e.page=Ue,e.placements=He,e})({});";
diff --git a/sdk/tests/foliage-far-versions.test.ts b/sdk/tests/foliage-far-versions.test.ts
new file mode 100644
index 000000000..f37f2af77
--- /dev/null
+++ b/sdk/tests/foliage-far-versions.test.ts
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A Foliage cell's far versions: the same plants, fewer and larger, chosen by each plant's own number so the version that takes
+ * over at a distance holds exactly the plants the shader still draws there.
+ */
+import { describe, expect, it } from 'vitest';
+import { rankedPlants, type Plant } from '../src/foliage/builder';
+import { buildFoliageCell, type CellSurroundings, type FoliageCellSpec } from '../src/foliage/cellBuild';
+import { MeshChannel } from '../src/asset/meshFormat';
+import type { MeshData } from '../src/asset/meshFormat';
+
+const plants: Plant[] = Array.from({ length: 1000 }, (_, i) => ({ x: i, y: 0, z: 0, yaw: 0, scale: 1, phase: ((i * 0.6180339887) % 1), shade: 1 }));
+const around: CellSurroundings = { ground: null, flatY: 0, water: null, zones: null };
+const spec = (far: FoliageCellSpec['far']): FoliageCellSpec => ({
+ centerX: 0, centerZ: 0, size: 10, count: 600, seed: 5, cellKey: 7, minScale: 1, maxScale: 1, minUp: 0, heightMin: -10, heightMax: 10,
+ waterDepth: 0, zonePadding: 0, tags: ['foliage', 'grass'], baseY: 0, paint: null, far, look: { kind: 'grass', bladeHeight: 1, bladeWidth: 0.1 },
+});
+const alphaOf = (mesh: MeshData): number => mesh.vertices[mesh.channels.find((c) => c.semantic === MeshChannel.Color)!.offset + 3]!;
+
+describe('the plants a far version keeps', () => {
+ it('are those whose own number is under the share, with the slack the switch needs, each grown to cover what was left out', () => {
+ const half = rankedPlants(plants, 0.5, 4, 1);
+ expect(half.length).toBeGreaterThan(470);
+ expect(half.length).toBeLessThan(530);
+ for (const p of half) expect(plants[p.x]!.phase).toBeLessThan(0.5);
+ expect(half[0]!.scale).toBeCloseTo(Math.SQRT2, 9);
+ // With slack, a few more: none of them a plant the share itself would not reach by a quarter.
+ const slack = rankedPlants(plants, 0.5, 4);
+ expect(slack.length).toBeGreaterThan(half.length);
+ for (const p of slack) expect(plants[p.x]!.phase).toBeLessThan(0.625);
+ });
+
+ it('are a part of what the version before it kept: nothing comes back further out', () => {
+ const a = new Set(rankedPlants(plants, 0.5, 4).map((p) => p.x)), b = rankedPlants(plants, 0.25, 4);
+ for (const p of b) expect(a.has(p.x)).toBe(true);
+ expect(rankedPlants(plants, 1, 4)).toBe(plants);
+ });
+
+ it('are grown no more than the most allowed', () => {
+ expect(rankedPlants(plants, 0.01, 3)[0]!.scale).toBe(3);
+ expect(rankedPlants(plants, 0.25, 1)[0]!.scale).toBe(1);
+ });
+});
+
+describe('a cell of grass', () => {
+ it('holds its near version and each far one, fewer blades in each, where one entity picks among them', () => {
+ const meshes = buildFoliageCell(spec({ levels: 3, keep: 0.5, grow: 4, cards: false }), around, null);
+ expect(meshes).toHaveLength(4);
+ for (let i = 1; i < meshes.length; i++) expect(meshes[i]!.indices.length).toBeLessThan(meshes[i - 1]!.indices.length);
+ // No band: a version drawn by a LODGroup is drawn wherever it is picked.
+ for (const m of meshes) expect(alphaOf(m)).toBe(255);
+ });
+
+ it('is one version alone, marked with its band, where each version is a layer of its own', () => {
+ const far = { levels: 3, keep: 0.5, grow: 4, cards: false };
+ const all = buildFoliageCell(spec(far), around, null);
+ for (let level = 0; level <= 3; level++) {
+ const one = buildFoliageCell(spec({ ...far, only: level }), around, null);
+ expect(one).toHaveLength(1);
+ expect(one[0]!.vertexCount).toBe(all[level]!.vertexCount);
+ expect(alphaOf(one[0]!)).toBe([0, 85, 170, 255][level]);
+ }
+ });
+
+ it('has no far version past the last plant, and none at all where nothing grows', () => {
+ const few = { ...spec({ levels: 3, keep: 0.1, grow: 4, cards: false }), count: 6 };
+ const meshes = buildFoliageCell(few, around, null);
+ expect(meshes.length).toBeGreaterThanOrEqual(1);
+ expect(meshes.length).toBeLessThan(4);
+ expect(buildFoliageCell({ ...few, far: { ...few.far, only: 3 } }, around, null)).toEqual([]);
+ expect(buildFoliageCell({ ...few, heightMin: 5 }, around, null)).toEqual([]);
+ });
+});