A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
perf(streaming): a generated world is there in a second instead of thirty - terrain pages are made on the workers, the frame's budget is shared among what streams, and what stands by the player gets more of it
yhh1ff981980020
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 5268fcc2a..116f35202 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1604,10 +1604,14 @@ texelsPerUnit: numberactive: BakeProgress[]budgetMs: numberclear: (owner: object) => void-hasTime: () => boolean+frameBudgetMs: number+hasTime: (owner?: object) => booleanmark: (owner: object, label: string, progress: number) => void+priorityExtraMs: numberrun: <T>(label: string, job: WorkJob<T>) => { done: Promise<T>; cancel: () => void; }step: (now?: () => number) => void+urge: (owner: object, urgent: boolean) => void+urgent: booleanstatic new (): Bakesstatic prototype: Bakes```@@ -8361,7 +8365,7 @@ remove: (id: string) => voidset: <T>(id: string, def: ChunkLayer<T>) => voidstateAt: (id: string, x: number, z: number) => ChunkState | nullstatus: (id: string) => ChunkLayerStatus | null-step: (hasTime: () => boolean) => void+step: (hasTime: () => boolean) => booleansuspended: booleanstatic new (): ProceduralChunksstatic prototype: ProceduralChunks@@ -11655,6 +11659,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal modifiers_: Map<string, TerrainModifier>+@internal pager_: TerrainPager | null@internal paint_: Repaint | null@internal remake_: (b: readonly [number, number, number, number]) => void@internal revision_: number@@ -11676,6 +11681,7 @@ pending: numberraycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | nullrepaint: () => voidsetModifier: (modifier: TerrainModifier) => void+setPager: (pager: TerrainPager | null) => voidsetPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrains@@ -13803,6 +13809,7 @@ baking: booleanbodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | nulldepthAt: (x: number, z: number, y: number) => number | nulldisturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean+empty: booleanheightAt: (x: number, z: number) => number | nullquality: WaterQualityqueryData: () => WaterQueryData | nulldiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex ab7d62c5a..d80edc7f9 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1604,10 +1604,14 @@ texelsPerUnit: numberactive: BakeProgress[]budgetMs: numberclear: (owner: object) => void-hasTime: () => boolean+frameBudgetMs: number+hasTime: (owner?: object) => booleanmark: (owner: object, label: string, progress: number) => void+priorityExtraMs: numberrun: <T>(label: string, job: WorkJob<T>) => { done: Promise<T>; cancel: () => void; }step: (now?: () => number) => void+urge: (owner: object, urgent: boolean) => void+urgent: booleanstatic new (): Bakesstatic prototype: Bakes```@@ -8568,7 +8572,7 @@ remove: (id: string) => voidset: <T>(id: string, def: ChunkLayer<T>) => voidstateAt: (id: string, x: number, z: number) => ChunkState | nullstatus: (id: string) => ChunkLayerStatus | null-step: (hasTime: () => boolean) => void+step: (hasTime: () => boolean) => booleansuspended: booleanstatic new (): ProceduralChunksstatic prototype: ProceduralChunks@@ -11877,6 +11881,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal modifiers_: Map<string, TerrainModifier>+@internal pager_: TerrainPager | null@internal paint_: Repaint | null@internal remake_: (b: readonly [number, number, number, number]) => void@internal revision_: number@@ -11898,6 +11903,7 @@ pending: numberraycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | nullrepaint: () => voidsetModifier: (modifier: TerrainModifier) => void+setPager: (pager: TerrainPager | null) => voidsetPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrains@@ -14025,6 +14031,7 @@ baking: booleanbodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | nulldepthAt: (x: number, z: number, y: number) => number | nulldisturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean+empty: booleanheightAt: (x: number, z: number) => number | nullquality: WaterQualityqueryData: () => WaterQueryData | nulldiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex d7a9618ba..4418a4694 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1599,10 +1599,14 @@ texelsPerUnit: numberactive: BakeProgress[]budgetMs: numberclear: (owner: object) => void-hasTime: () => boolean+frameBudgetMs: number+hasTime: (owner?: object) => booleanmark: (owner: object, label: string, progress: number) => void+priorityExtraMs: numberrun: <T>(label: string, job: WorkJob<T>) => { done: Promise<T>; cancel: () => void; }step: (now?: () => number) => void+urge: (owner: object, urgent: boolean) => void+urgent: booleanstatic new (): Bakesstatic prototype: Bakes```@@ -8356,7 +8360,7 @@ remove: (id: string) => voidset: <T>(id: string, def: ChunkLayer<T>) => voidstateAt: (id: string, x: number, z: number) => ChunkState | nullstatus: (id: string) => ChunkLayerStatus | null-step: (hasTime: () => boolean) => void+step: (hasTime: () => boolean) => booleansuspended: booleanstatic new (): ProceduralChunksstatic prototype: ProceduralChunks@@ -11650,6 +11654,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal modifiers_: Map<string, TerrainModifier>+@internal pager_: TerrainPager | null@internal paint_: Repaint | null@internal remake_: (b: readonly [number, number, number, number]) => void@internal revision_: number@@ -11671,6 +11676,7 @@ pending: numberraycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | nullrepaint: () => voidsetModifier: (modifier: TerrainModifier) => void+setPager: (pager: TerrainPager | null) => voidsetPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrains@@ -13798,6 +13804,7 @@ baking: booleanbodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | nulldepthAt: (x: number, z: number, y: number) => number | nulldisturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean+empty: booleanheightAt: (x: number, z: number) => number | nullquality: WaterQualityqueryData: () => WaterQueryData | nulldiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex db2b1eea7..127b2be71 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1599,10 +1599,14 @@ texelsPerUnit: numberactive: BakeProgress[]budgetMs: numberclear: (owner: object) => void-hasTime: () => boolean+frameBudgetMs: number+hasTime: (owner?: object) => booleanmark: (owner: object, label: string, progress: number) => void+priorityExtraMs: numberrun: <T>(label: string, job: WorkJob<T>) => { done: Promise<T>; cancel: () => void; }step: (now?: () => number) => void+urge: (owner: object, urgent: boolean) => void+urgent: booleanstatic new (): Bakesstatic prototype: Bakes```@@ -8653,7 +8657,7 @@ remove: (id: string) => voidset: <T>(id: string, def: ChunkLayer<T>) => voidstateAt: (id: string, x: number, z: number) => ChunkState | nullstatus: (id: string) => ChunkLayerStatus | null-step: (hasTime: () => boolean) => void+step: (hasTime: () => boolean) => booleansuspended: booleanstatic new (): ProceduralChunksstatic prototype: ProceduralChunks@@ -11947,6 +11951,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal modifiers_: Map<string, TerrainModifier>+@internal pager_: TerrainPager | null@internal paint_: Repaint | null@internal remake_: (b: readonly [number, number, number, number]) => void@internal revision_: number@@ -11968,6 +11973,7 @@ pending: numberraycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | nullrepaint: () => voidsetModifier: (modifier: TerrainModifier) => void+setPager: (pager: TerrainPager | null) => voidsetPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrains@@ -14101,6 +14107,7 @@ baking: booleanbodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | nulldepthAt: (x: number, z: number, y: number) => number | nulldisturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean+empty: booleanheightAt: (x: number, z: number) => number | nullquality: WaterQualityqueryData: () => WaterQueryData | nulldiff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.mdindex 1914e7a0f..5b9e1510f 100644--- a/sdk/etc/terrain.api.md+++ b/sdk/etc/terrain.api.md@@ -629,6 +629,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal modifiers_: Map<string, TerrainModifier>+@internal pager_: TerrainPager | null@internal paint_: Repaint | null@internal remake_: (b: readonly [number, number, number, number]) => void@internal revision_: number@@ -650,6 +651,7 @@ pending: numberraycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | nullrepaint: () => voidsetModifier: (modifier: TerrainModifier) => void+setPager: (pager: TerrainPager | null) => voidsetPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrainsdiff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.mdindex f85e8f232..3e978796e 100644--- a/sdk/etc/water.api.md+++ b/sdk/etc/water.api.md@@ -232,6 +232,7 @@ baking: booleanbodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | nulldepthAt: (x: number, z: number, y: number) => number | nulldisturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean+empty: booleanheightAt: (x: number, z: number) => number | nullquality: WaterQualityqueryData: () => WaterQueryData | nulldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 588d1c9ff..d90af997c 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1599,10 +1599,14 @@ texelsPerUnit: numberactive: BakeProgress[]budgetMs: numberclear: (owner: object) => void-hasTime: () => boolean+frameBudgetMs: number+hasTime: (owner?: object) => booleanmark: (owner: object, label: string, progress: number) => void+priorityExtraMs: numberrun: <T>(label: string, job: WorkJob<T>) => { done: Promise<T>; cancel: () => void; }step: (now?: () => number) => void+urge: (owner: object, urgent: boolean) => void+urgent: booleanstatic new (): Bakesstatic prototype: Bakes```@@ -8363,7 +8367,7 @@ remove: (id: string) => voidset: <T>(id: string, def: ChunkLayer<T>) => voidstateAt: (id: string, x: number, z: number) => ChunkState | nullstatus: (id: string) => ChunkLayerStatus | null-step: (hasTime: () => boolean) => void+step: (hasTime: () => boolean) => booleansuspended: booleanstatic new (): ProceduralChunksstatic prototype: ProceduralChunks@@ -11657,6 +11661,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal modifiers_: Map<string, TerrainModifier>+@internal pager_: TerrainPager | null@internal paint_: Repaint | null@internal remake_: (b: readonly [number, number, number, number]) => void@internal revision_: number@@ -11678,6 +11683,7 @@ pending: numberraycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, maxDistance: number) => { distance: number; point: { x: number; y: number; z: number; }; normal: { x: number; y: number; z: number; }; entity: Entity; } | nullrepaint: () => voidsetModifier: (modifier: TerrainModifier) => void+setPager: (pager: TerrainPager | null) => voidsetPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrains@@ -13805,6 +13811,7 @@ baking: booleanbodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | nulldepthAt: (x: number, z: number, y: number) => number | nulldisturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean+empty: booleanheightAt: (x: number, z: number) => number | nullquality: WaterQualityqueryData: () => WaterQueryData | nulldiff --git a/sdk/src/foliage/plantGrowth.ts b/sdk/src/foliage/plantGrowth.tsindex a18039312..218606fb8 100644--- a/sdk/src/foliage/plantGrowth.ts+++ b/sdk/src/foliage/plantGrowth.ts@@ -277,7 +277,7 @@ export class PlantGrowth {step(app: App): void {const bakes = bakesOf(app);let first = true;- while (this.queue.length > 0 && (first || bakes.hasTime())) {+ while (this.queue.length > 0 && (first || bakes.hasTime(this))) {first = false;const piece = this.queue.shift()!;if (piece.cell.dead) continue;diff --git a/sdk/src/residency/chunks.ts b/sdk/src/residency/chunks.tsindex a73a826af..b754e231c 100644--- a/sdk/src/residency/chunks.ts+++ b/sdk/src/residency/chunks.ts@@ -194,7 +194,7 @@ export class ProceduralChunks {* One frame: releases what no source is near, then makes what is wanted, nearest first across every layer: the chunks a source* stands in at once, and the rest while `hasTime` says so (an `async` layer's, all of them).*/- step(hasTime: () => boolean): void {+ step(hasTime: () => boolean): boolean {const world = this.suspended ? [] : this.sources_();const wanted: { layer: Layer<unknown>; cx: number; cz: number; dist: number }[] = [];for (const layer of this.layers_.values()) {@@ -239,12 +239,19 @@ export class ProceduralChunks {for (const c of layer.chunks.values()) if (c.making) n++;inFlight.set(layer, n);}+ let nearLeft = false;+ let spent = false;for (const w of wanted) {// A layer whose chunks are answered later (off the main thread) takes no time from the frame: it is not held to the frame's budget.- if (w.dist > 0 && !w.layer.def.async && !hasTime()) continue;+ // Once the frame has said no it is not asked again for every chunk still wanted: there can be a thousand of them.+ if (w.dist > 0 && !w.layer.def.async && (spent || (spent = !hasTime()))) {+ if (w.dist <= Math.max(w.layer.def.sizeX, w.layer.def.sizeZ)) nearLeft = true;+ continue;+ }if ((inFlight.get(w.layer) ?? 0) >= MAX_IN_FLIGHT) continue;if (this.make(w.layer, w.cx, w.cz)) inFlight.set(w.layer, (inFlight.get(w.layer) ?? 0) + 1);}+ return nearLeft;}/** Makes one chunk; true when it is now being answered later. */@@ -373,7 +380,8 @@ export function chunksOf(app: App): ProceduralChunks {const bakes = bakesOf(app);const shown = new Set<object>();app.addSystemToSchedule(Schedule.PostUpdate, defineSystem([], () => {- app.measureFrameScope('chunks.step', () => chunks.step(() => bakes.hasTime()));+ // Chunks beside a source that are still to be made here are a hole the player is standing next to: the frame gives more.+ app.measureFrameScope('chunks.step', () => bakes.urge(chunks, chunks.step(() => bakes.hasTime(chunks))));const now = new Set<object>();for (const p of chunks.progress_()) { bakes.mark(p.owner, p.label, p.progress); now.add(p.owner); }for (const owner of shown) if (!now.has(owner)) bakes.clear(owner);diff --git a/sdk/src/runtime/bakes.ts b/sdk/src/runtime/bakes.tsindex 7adb6d6ee..6d07d01a5 100644--- a/sdk/src/runtime/bakes.ts+++ b/sdk/src/runtime/bakes.ts@@ -12,6 +12,16 @@* The frame's budget is one, and it is here: the jobs and the work stepped elsewhere (pages made, chunks of the world built)* spend the same milliseconds. The jobs run first each frame; when the rest could not finish the frame before, the jobs leave* them half of it.+ *+ * What is left is SHARED among the work stepped elsewhere, not taken by whichever system runs first. Each asks under its own+ * name (`hasTime(owner)`) and is given an equal part of what remains when it starts; what one does not use passes to those+ * after it. Without that the ground's far pages, asked first each frame, took every millisecond for half a minute while the+ * trees beside the player waited for a turn that never came.+ *+ * And the budget is not one number. Work that the player would SEE missing (the chunk they stand in, the page under their+ * feet) says so (`urge`), and while any does the frame gives `priorityExtraMs` more: a few frames run slower so that the+ * world is there, where a steady budget would keep the frame rate and show the hole. This is the main thread's part only —+ * putting made things in the world. Making them is for workers, which no budget here slows.*/import type { App } from '../app/app';import { defineResource } from '../ecs/resource';@@ -34,12 +44,25 @@ interface Running {fail: (error: unknown) => void;}+/** Who asks when a caller names nobody: every such caller is one owner, and shares one turn. */+const SHARED = {};+/** The jobs an App is running. Read {@link Bakes.active} for what to show. */export class Bakes {/** How long, in milliseconds, all the work spread over frames may take of one frame between it. */budgetMs = 8;- /** When this frame's budget runs out, on the clock `step` was given. */- private deadline_ = -Infinity;+ /** How much more a frame gives while work that would be seen missing is still to do (see `urge`). */+ priorityExtraMs = 12;+ /** What this frame's work stepped elsewhere may still take, after the jobs and whoever went before. */+ private left_ = 0;+ /** Who asked for time this frame, in the order they first did, and who asked the frame before. */+ private readonly turns_ = new Map<object, { start: number; last: number; allowance: number }>();+ private waiting_ = new Set<object>();+ private open_: { start: number; last: number; allowance: number } | null = null;+ /** How long one piece of each owner's work has been taking, smoothed. */+ private readonly piece_ = new WeakMap<object, number>();+ /** Whose remaining work would be seen missing. */+ private readonly urgent_ = new Set<object>();private clock_: () => number = () => performance.now();/** Whether work stepped elsewhere ran out of time, this frame and the one before. */private starved_ = false;@@ -71,6 +94,7 @@ export class Bakes {clear(owner: object): void {this.marks_.delete(owner);+ this.urgent_.delete(owner);}/** Every piece of work in hand now. Empty when the engine is idle. */@@ -82,24 +106,74 @@ export class Bakes {}/**- * Whether work stepped elsewhere may go on this frame. Such work does what it must at once (what stands right by the player)- * whatever this says, and stops when it says no; saying no is remembered, so the jobs leave it more of the next frame.+ * Whether `owner`'s work stepped elsewhere may go on this frame. Such work does what it must at once (what stands right by the+ * player) whatever this says, and stops when it says no; saying no is remembered, so the jobs leave it more of the next frame.+ *+ * The first time an owner asks in a frame it is given its part: what the frame has left, divided among it and those that asked+ * the frame before and have not had their turn yet. An owner that asks alone has all of it.*/- hasTime(): boolean {- if (this.clock_() < this.deadline_) return true;+ hasTime(owner: object = SHARED): boolean {+ const now = this.clock_();+ let turn = this.turns_.get(owner);+ if (!turn) {+ // Whoever went before is done for this frame: what it took comes off what is left.+ if (this.open_) this.left_ -= this.open_.last - this.open_.start;+ this.waiting_.delete(owner);+ turn = { start: now, last: now, allowance: Math.max(0, this.left_) / (this.waiting_.size + 1) };+ this.turns_.set(owner, turn);+ this.open_ = turn;+ }+ else {+ // What one piece of this owner's work takes, from the time between its asks: a piece is not started that would run past+ // the owner's part. Asking only "is there time left" let a stepper whose pieces take as long as the budget start a second+ // and a third, and a frame meant to give 8 ms gave 21.+ // The LONGEST lately, let down slowly, and not the mean: an owner's pieces are not alike (a cell of grass is 8 ms, a chunk+ // with nothing in it is none), and a mean pulled down by the empty ones lets the next full one through.+ const piece = now - turn.last;+ const known = this.piece_.get(owner);+ this.piece_.set(owner, known === undefined ? piece : Math.max(piece, known * 0.9));+ }+ const first = turn.last === turn.start && now === turn.start;+ turn.last = now;+ // The first piece of a turn is always given: a part smaller than one piece would otherwise never make anything.+ if (first ? turn.allowance > 0 : now - turn.start + (this.piece_.get(owner) ?? 0) <= turn.allowance) return true;this.starved_ = true;return false;}+ /**+ * Says whether what `owner` still has to do would be seen missing by the player: the chunk they stand in, the ground under them.+ * While any owner says so the frame's budget is larger by `priorityExtraMs`. Say false when it is done, or it is held for good.+ */+ urge(owner: object, urgent: boolean): void {+ if (urgent) this.urgent_.add(owner);+ else this.urgent_.delete(owner);+ }++ /** Whether something the player would see missing is still being made: what a loading screen waits for. */+ get urgent(): boolean {+ return this.urgent_.size > 0;+ }++ /** What this frame may spend: the steady budget, and the extra while something urgent is outstanding. */+ get frameBudgetMs(): number {+ return this.budgetMs + (this.urgent_.size > 0 ? this.priorityExtraMs : 0);+ }+/** Starts the frame's budget and steps the jobs for their part of it, oldest first; a job that finishes or throws settles its promise. */step(now: () => number = () => performance.now()): void {this.clock_ = now;this.starvedBefore_ = this.starved_;this.starved_ = false;const start = now();- this.deadline_ = start + this.budgetMs;+ const budget = this.frameBudgetMs;+ // Those that asked last frame are expected again: each new turn is sized by how many of them are still to come.+ this.waiting_ = new Set(this.turns_.keys());+ this.turns_.clear();+ this.open_ = null;+ this.left_ = budget;if (this.running_.size === 0) return;- const end = start + (this.starvedBefore_ ? this.budgetMs / 2 : this.budgetMs);+ const end = start + (this.starvedBefore_ ? budget / 2 : budget);for (const r of [...this.running_]) {// Every job advances at least once a frame, so a long one cannot starve those behind it.do {@@ -120,6 +194,7 @@ export class Bakes {} while (now() < end);if (now() >= end) break;}+ this.left_ = budget - (now() - start);}}diff --git a/sdk/src/runtime/planWorkerBundle.generated.ts b/sdk/src/runtime/planWorkerBundle.generated.tsindex be50bb8f3..8e1ec7c41 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){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 M(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=>N(e,t,o,n.heights,n.paint)):N(e,t,o,c.heights,c.paint)}function N(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?P(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),j(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,M=0,N=0,P=0;if(y){let e=y(o,a);A=e[0],M=e[1],N=e[2],P=e[3]}else if(i)A=i[u*4],M=i[u*4+1],N=i[u*4+2],P=i[u*4+3];else{let e=Math.min(Math.max((.9-k/E)*6,0),1);A=1-e,P=e}l[u*4]=Math.round(Math.min(Math.max(A,0),1)*255),l[u*4+1]=Math.round(Math.min(Math.max(M,0),1)*255),l[u*4+2]=Math.round(Math.min(Math.max(N,0),1)*255),l[u*4+3]=Math.round(Math.min(Math.max(P,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 P(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 F=e=>e*Math.PI/4,I=e=>F(e),L=1.5;var R=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=F(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=F(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 j(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)*L,r*48+(e-1)*L);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-L,z0:r*48-L,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)/L,i=(n-e.z0)/L,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=L,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=I(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=I(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 z(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 ee(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 te(e,t,n,r,i,a,o={}){if(ee(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 B=4e4;function V(e){let t=H(e.anchor,e.anchor.scale?.[1]??1);for(let n of e.members??[])t=Math.max(t,(n.ring?.[1]??0)+H(n,n.scale?.[1]??1));return t}function H(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 U=(e,t,n)=>e?e[0]+(e[1]-e[0])*t:n;var W=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,V(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>B&&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=U(o.arc,s(2,t),s(2,t)*360)*Math.PI/180,r=U(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=U(r.scale,p(this.worldHash_,m(e),i,11),1),g;if(r.grounding){let e=te(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:H(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>B&&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:V(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*=z(t,o[t.field]??NaN),s<=0)return 0;return s}};function G(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 K(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 W(t.rules,r,t.zones,t.seed,i),farPlan:t.farRules?new W(t.farRules,r,t.zones,t.seed,i):null}}function ne(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 W(e.rules,n,e.zones,e.seed,e.world),farPlan:e.farRules?new W(e.farRules,n,e.zones,e.seed,e.world):null}}var re=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=ie(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 ie(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 ae(e,t,n,r){let i=e.height(n-t.x,r-t.z);return i===null?null:t.y+i}function oe(e,t,n,r){return e.normal(n-t.x,r-t.z)}function se(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 ce=class{constructor(e){this.source_=e.source.kind===`field`?a.fromData(e.source.data):o.fromData(e.source.data),this.surface_=new re(this.source_,e.cell),this.origin_=e.origin}heightAt(e,t){return ae(this.surface_,this.origin_,e,t)}normalAt(e,t){return oe(this.surface_,this.origin_,e,t)}paintAt(e,t){return se(this.source_,this.surface_,this.origin_,e,t)}},le=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 q=new Map,J=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 X(e,t){let n=J.get(e);return n||(n=t(e),J.set(e,n)),n}function ue(e){let t=new C;for(let n of e.zones)t.set(n);return{face:null,...ne({rules:e.rules,farRules:G(e.rules),seed:e.seed,world:e.world,zones:t,ground:e.ground?new ce(e.ground):null,flatY:e.flatY,water:e.water?new le(e.water):null,layers:e.layers})}}async function de(e,t){let n=await X(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 R(e.face,()=>r),a=new C;for(let t of e.zones)a.set(t);return{face:i,...K(i,{rules:e.rules,farRules:G(e.rules),seed:e.seed,world:e.world,seaLevel:e.seaLevel,layers:e.layers,fieldNames:e.fieldNames,zones:a})}}async function Z(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?ue(t):await de(t,n),q.set(e,r),q.size>24&&q.delete(q.keys().next().value)}return r}async function Q(e,t=Y){let n=await Z(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 $(e,t=Y){let n=await X(e.provider.source,t),r=null;if(e.paintKeys){let n=e.paintKeys,i=await Promise.all(n.map((n,r)=>Z(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 M({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]}}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)});t.type===`page`?$(t).then(e=>self.postMessage({id:t.id,result:e.result},e.transfer),n):Q(t).then(e=>self.postMessage({id:t.id,result:e}),n)}),e.page=$,e.placements=Q,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=>P(e,t,n,a,r.heights,r,i)):P(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*F(e,t,n,a,o,void 0,i)}function N(e){for(;;){let t=e.next();if(t.done)return t.value}}function P(e,t,n,r,i,a,o){return N(F(e,t,n,r,i,a,o))}function*F(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 I(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 ee(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=>L(e,t,o,n.heights,n.paint)):L(e,t,o,c.heights,c.paint)}function L(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?te(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),I(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 te(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 R=e=>e*Math.PI/4,z=e=>R(e),B=1.5;var ne=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=R(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=R(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 I(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)*B,r*48+(e-1)*B);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-B,z0:r*48-B,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)/B,i=(n-e.z0)/B,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=B,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=z(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=z(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 re(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 ie(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 ae(e,t,n,r,i,a,o={}){if(ie(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 V=4e4;function H(e){let t=U(e.anchor,e.anchor.scale?.[1]??1);for(let n of e.members??[])t=Math.max(t,(n.ring?.[1]??0)+U(n,n.scale?.[1]??1));return t}function U(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 W=(e,t,n)=>e?e[0]+(e[1]-e[0])*t:n;var G=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,H(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>V&&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=W(o.arc,s(2,t),s(2,t)*360)*Math.PI/180,r=W(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=W(r.scale,p(this.worldHash_,m(e),i,11),1),g;if(r.grounding){let e=ae(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:U(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>V&&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:H(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*=re(t,o[t.field]??NaN),s<=0)return 0;return s}};function K(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 oe(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 G(t.rules,r,t.zones,t.seed,i),farPlan:t.farRules?new G(t.farRules,r,t.zones,t.seed,i):null}}function se(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 G(e.rules,n,e.zones,e.seed,e.world),farPlan:e.farRules?new G(e.farRules,n,e.zones,e.seed,e.world):null}}var ce=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=le(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 le(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 ue(e,t,n,r){let i=e.height(n-t.x,r-t.z);return i===null?null:t.y+i}function de(e,t,n,r){return e.normal(n-t.x,r-t.z)}function fe(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 pe=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 q(e){let t=e.source.kind===`field`?a.fromData(e.source.data):o.fromData(e.source.data);return e.shift?new pe(t,e.shift.x,e.shift.z):t}var me=class{constructor(e){this.source_=q(e),this.surface_=new ce(this.source_,e.cell),this.origin_=e.origin}heightAt(e,t){return ue(this.surface_,this.origin_,e,t)}normalAt(e,t){return de(this.surface_,this.origin_,e,t)}paintAt(e,t){return fe(this.source_,this.surface_,this.origin_,e,t)}},he=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 J=new Map,Y=new Map,X=e=>{let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(t).then(e=>e.default).finally(()=>URL.revokeObjectURL(t))};function Z(e,t){let n=Y.get(e);return n||(n=t(e),Y.set(e,n)),n}function ge(e){let t=new C;for(let n of e.zones)t.set(n);return{face:null,ground:e.ground?{source:q(e.ground),origin:e.ground.origin}:null,...se({rules:e.rules,farRules:K(e.rules),seed:e.seed,world:e.world,zones:t,ground:e.ground?new me(e.ground):null,flatY:e.flatY,water:e.water?new he(e.water):null,layers:e.layers})}}async function _e(e,t){let n=await Z(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 ne(e.face,()=>r),a=new C;for(let t of e.zones)a.set(t);return{face:i,...oe(i,{rules:e.rules,farRules:K(e.rules),seed:e.seed,world:e.world,seaLevel:e.seaLevel,layers:e.layers,fieldNames:e.fieldNames,zones:a})}}async function Q(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?ge(t):await _e(t,n),J.set(e,r),J.size>24&&J.delete(J.keys().next().value)}return r}async function $(e,t=X){let n=await Q(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=X){let n=await Z(e.provider.source,t),r=null;if(e.paintKeys){let n=e.paintKeys,i=await Promise.all(n.map((n,r)=>Q(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 ee({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 ye(e,t=X){let n=await Q(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]}}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)});t.type===`page`?ve(t).then(e=>self.postMessage({id:t.id,result:e.result},e.transfer),n):t.type===`groundPage`?ye(t).then(e=>self.postMessage({id:t.id,result:e.result},e.transfer),n):$(t).then(e=>self.postMessage({id:t.id,result:e}),n)}),e.groundPage=ye,e.page=ve,e.placements=$,e})({});";diff --git a/sdk/src/terrain/groundQuery.ts b/sdk/src/terrain/groundQuery.tsindex b009cd47c..e4f568497 100644--- a/sdk/src/terrain/groundQuery.ts+++ b/sdk/src/terrain/groundQuery.ts@@ -9,7 +9,7 @@* alone, so a worker given the data (`GroundData`) answers as the terrain does, and what a world is laid out from does not depend on which of them* was asked.*/-import { FieldSource, NoiseSource, type FieldSourceData, type NoiseParams, type TerrainSource } from './source';+import { FieldSource, NoiseSource, type FieldSourceData, type LayerWeights, type NoiseParams, type TerrainSource } from './source';import { TerrainSurface } from './surface';/** Where a terrain stands, in the world. */@@ -39,6 +39,36 @@ export interface GroundData {/** The lattice's cell, in the terrain's units. */cell: number;source: { kind: 'field'; data: FieldSourceData } | { kind: 'noise'; data: NoiseParams };+ /**+ * How far from the terrain's own space the source is read. The engine's noise as a PROVIDER is the world's ground, the same+ * wherever a terrain stands on it, so its terrain reads it at its own position; absent, the source is the terrain's own.+ */+ shift?: { x: number; z: number };+}++/** A source read a fixed distance from where it is asked: a terrain's window on ground that belongs to the world. */+class ShiftedSource implements TerrainSource {+ readonly infinite: boolean;+ readonly bounds: TerrainSource['bounds'];+ readonly minHeight: number;+ readonly maxHeight: number;++ constructor(private readonly base: TerrainSource, private readonly dx: number, private readonly dz: number) {+ this.infinite = base.infinite;+ this.bounds = base.bounds;+ this.minHeight = base.minHeight;+ this.maxHeight = base.maxHeight;+ }++ height(x: number, z: number): number | null { return this.base.height(x + this.dx, z + this.dz); }+ normal(x: number, z: number): [number, number, number] | null { return this.base.normal(x + this.dx, z + this.dz); }+ paint(x: number, z: number, h: number, ny: number): LayerWeights { return this.base.paint(x + this.dx, z + this.dz, h, ny); }+}++/** The source `data` describes, in the terrain's own space: what a terrain made of the same data reads its pages and its points from. */+export function groundSourceOf(data: GroundData): TerrainSource {+ const base = data.source.kind === 'field' ? FieldSource.fromData(data.source.data) : NoiseSource.fromData(data.source.data);+ return data.shift ? new ShiftedSource(base, data.shift.x, data.shift.z) : base;}/** The ground of a terrain from its data. */@@ -48,7 +78,7 @@ export class GroundQuery {private readonly origin_: GroundOrigin;constructor(data: GroundData) {- this.source_ = data.source.kind === 'field' ? FieldSource.fromData(data.source.data) : NoiseSource.fromData(data.source.data);+ this.source_ = groundSourceOf(data);this.surface_ = new TerrainSurface(this.source_, data.cell);this.origin_ = data.origin;}diff --git a/sdk/src/terrain/planetPlugin.ts b/sdk/src/terrain/planetPlugin.tsindex d7de136b7..d1739858f 100644--- a/sdk/src/terrain/planetPlugin.ts+++ b/sdk/src/terrain/planetPlugin.ts@@ -538,7 +538,7 @@ export class PlanetPlugin implements Plugin {built.wanted.delete(key);made++;// The frame's one budget, shared with the bakes and the chunks of the world; at least one page a frame.- if (!bakes.hasTime()) break;+ if (!bakes.hasTime(built)) break;}bakes.mark(built, 'Building the planet', made === 0 ? 0 : 1 - built.wanted.size / (built.wanted.size + made));}diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex 330d1b713..f5265455b 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -42,7 +42,7 @@ import { paintWeights } from './paint';export { paintWeights };import { GroundEdit } from './groundEdit';-import { FieldSource, ModifiedSource, NoiseSource, type TerrainModifier, type TerrainSource } from './source';+import { FieldSource, ModifiedSource, NoiseSource, type NoiseParams, type TerrainModifier, type TerrainSource } from './source';import { levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './quadtree';import { makePage, makePageJob, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage, type Repaint } from './pages';import { noiseProvider, ProviderSource, terrainProvider, terrainProvidersRevision, TerrainUnavailable, type TerrainProvider } from './provider';@@ -194,6 +194,12 @@ const MAX_LAYERS = 8;const collisionLayerOf = (entity: Entity): string => `terrain-collision:${entity}`;const tileKey = (entity: Entity, tx: number, tz: number): string => `terrain:${entity}:${tx}:${tz}`;+/**+ * Makes the page of the square (x0, z0) to (x0 + size, z0 + size) of a terrain's own space somewhere else, painted as the terrain would+ * paint it; null when it cannot make this one.+ */+export type TerrainPager = (x0: number, z0: number, size: number) => Promise<PageImage> | null;+/** Pages asked at once of a provider that answers later. */const PAGES_IN_FLIGHT = 16;@@ -221,6 +227,8 @@ interface Built {wanted: Map<string, TerrainNode>;/** Pages asked of a provider that answers later, by key: the frame's budget is not spent waiting for them. */asked: Set<string>;+ /** The workers failed one of this terrain's pages: it makes its own. */+ pagerFailed?: boolean;/** A synchronous source's page paused inside sampling/painting, rather than blocking a whole frame. */pageWork?: { key: string; epoch: number; edits: number; job: Generator<number, PageImage, void>; image?: PageImage };pending: boolean;@@ -304,8 +312,9 @@ export class Terrains {}/**- * The ground as data a worker can rebuild it from, when it can be: one terrain, made, of a field or of noise, with nothing laid over it. Null otherwise- * (a provider's ground, a modified one, several terrains, one still being made), when what is laid out over it must ask here.+ * The ground as data a worker can rebuild it from, when it can be: one terrain, made, of a field or of noise (the engine's own noise provider+ * included, whose ground is its parameters), with nothing laid over it. Null otherwise (a game's provider, a modified ground, several terrains,+ * one still being made), when what is laid out over it must ask here.*/groundData(): GroundData | null {const world = this.app_?.world;@@ -318,6 +327,15 @@ export class Terrains {const origin = { x: t.worldPosition.x, y: t.worldPosition.y, z: t.worldPosition.z };if (base instanceof FieldSource) return { origin, cell: built.surface.cell, source: { kind: 'field', data: base.toData() } };if (base instanceof NoiseSource) return { origin, cell: built.surface.cell, source: { kind: 'noise', data: base.toData() } };+ // The engine's noise as a provider: the same function, read at the world's position and not the terrain's own.+ if (base instanceof ProviderSource && base.provider.id === NOISE_PROVIDER) {+ const d = built.data;+ const params: NoiseParams = {+ seed: d.seed, frequency: d.frequency, octaves: d.octaves, persistence: d.persistence, ridged: d.ridged, warp: d.warp, erosion: d.erosion,+ sizeX: d.sizeX, height: d.height, rockSlope: d.rockSlope, dirtHeight: d.dirtHeight, snowHeight: d.snowHeight,+ };+ return { origin, cell: built.surface.cell, source: { kind: 'noise', data: params }, shift: { x: origin.x, z: origin.z } };+ }return null;}@@ -522,6 +540,18 @@ export class Terrains {this.repaint();}+ /** @internal Who makes the ground's pages off the main thread, if anyone does. */+ pager_: TerrainPager | null = null;++ /**+ * Hands the making of pages to `pager` (or back to the terrain, with null). A world that paints the ground has the plan the paint is+ * read from on its workers already, and a page painted there costs the frame nothing; painted here it is tens of milliseconds a page.+ * The pager answers null for a page it cannot make (its plan is no longer the ground's), and the terrain makes that one itself.+ */+ setPager(pager: TerrainPager | null): void {+ this.pager_ = pager;+ }+/** Makes every page again, for a paint that changed what it answers. */repaint(): void {for (const built of this.built_.values()) {@@ -982,12 +1012,54 @@ export class TerrainPlugin implements Plugin {this.place(app, entity, built, drawn);}- /** Makes the wanted pages, coarse and near first, for as long as the frame can spare. */+ /** Makes the wanted pages, coarse and near first: asked of the workers where a pager can make them, else made here for as long as the frame can spare. */private makePages(app: App, built: Built, source: TerrainSource, eye: [number, number, number], at: { x: number; y: number; z: number }): void {- const paint = app.getResource(TerrainsRes).paint_;+ const terrains = app.getResource(TerrainsRes);+ const paint = terrains.paint_;const repaint: Repaint | undefined = paint ? (x, z, h, ny, w) => paint(x + at.x, z + at.z, h + at.y, ny, w) : undefined;const bakes = bakesOf(app);- if (built.wanted.size === 0) { built.pageWork = undefined; bakes.mark(built, 'Building the terrain', 1); return; }+ if (built.wanted.size === 0) { built.pageWork = undefined; bakes.mark(built, 'Building the terrain', 1); bakes.urge(built, false); return; }+ // How far along: the pages there are, of those and the ones still wanted. (It was the pages made THIS frame, which read 0% for half a minute.)+ const progress = (): number => built.table.size / (built.table.size + built.wanted.size);+ // The page under the eye is the ground the player is standing on drawn too coarse: the frame gives more until it is made.+ bakes.urge(built, [...built.wanted.values()].some((n) => n.level === 0+ && eye[0] >= n.x0 && eye[0] < n.x0 + n.size && eye[2] >= n.z0 && eye[2] < n.z0 + n.size));+ const pager = built.pagerFailed ? null : terrains.pager_;+ if (pager) {+ const sorted = [...built.wanted.values()].sort((a, b) => b.level - a.level+ || Math.hypot(a.x0 + a.size / 2 - eye[0], a.z0 + a.size / 2 - eye[2]) - Math.hypot(b.x0 + b.size / 2 - eye[0], b.z0 + b.size / 2 - eye[2]));+ const epoch = built.epoch, edits = built.edits;+ let refused = false;+ for (const node of sorted) {+ const key = nodeKey(node.level, node.ix, node.iz);+ if (built.asked.has(key)) continue;+ if (built.asked.size >= PAGES_IN_FLIGHT) break;+ const image = pager(node.x0, node.z0, node.size);+ if (!image) { refused = true; break; }+ built.asked.add(key);+ void image.then((img) => {+ built.asked.delete(key);+ // Thrown away if the ground or its paint changed while it was being made: the page is wanted again, and asked again.+ if (built.epoch !== epoch || built.edits !== edits || !built.heights) return;+ const page = built.table.claim(key, img.min, img.max);+ if (!page) return;+ const [ox, oy] = built.table.origin(page.slot);+ updateTextureSubregion(app.wasmModule, built.heights, ox, oy, PAGE_SIDE, PAGE_SIDE, img.heights);+ updateTextureSubregion(app.wasmModule, built.paint, ox, oy, PAGE_SIDE, PAGE_SIDE, img.paint);+ if (built.paint2) updateTextureSubregion(app.wasmModule, built.paint2, ox, oy, PAGE_SIDE, PAGE_SIDE, img.paint2);+ }, (e) => {+ built.asked.delete(key);+ // A worker that cannot make this ground's pages will not make the next one either: the terrain makes its own from here.+ if (!built.pagerFailed) log.warn('terrain', 'the workers failed a page; the terrain makes its pages on the main thread from here', e);+ built.pagerFailed = true;+ });+ }+ if (!refused) {+ built.pageWork = undefined;+ bakes.mark(built, 'Building the terrain', progress());+ return;+ }+ }if (built.pageWork && (built.pageWork.epoch !== built.epoch || built.pageWork.edits !== built.edits || !built.wanted.has(built.pageWork.key))) built.pageWork = undefined;const order = [...built.wanted.values()].sort((a, b) => b.level - a.level|| Math.hypot(a.x0 + a.size / 2 - eye[0], a.z0 + a.size / 2 - eye[2]) - Math.hypot(b.x0 + b.size / 2 - eye[0], b.z0 + b.size / 2 - eye[2]));@@ -1021,8 +1093,8 @@ export class TerrainPlugin implements Plugin {if (!store(work.key, work.image)) break;built.wanted.delete(work.key); built.pageWork = undefined; made++;}- } while (bakes.hasTime());- bakes.mark(built, 'Building the terrain', made === 0 ? 0 : 1 - built.wanted.size / (built.wanted.size + made));+ } while (bakes.hasTime(built));+ bakes.mark(built, 'Building the terrain', progress());return;}for (const node of order) {@@ -1046,9 +1118,9 @@ export class TerrainPlugin implements Plugin {built.wanted.delete(key);made++;// The frame's one budget, shared with the bakes and the chunks of the world; at least one page a frame.- if (!bakes.hasTime()) break;+ if (!bakes.hasTime(built)) break;}- bakes.mark(built, 'Building the terrain', made === 0 ? 0 : 1 - built.wanted.size / (built.wanted.size + made));+ bakes.mark(built, 'Building the terrain', progress());}/** Puts a node entity on each node drawn (reusing the ones it had), and takes the rest away. */diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.tsindex 2cde1f384..43b7ac978 100644--- a/sdk/src/water/waterPlugin.ts+++ b/sdk/src/water/waterPlugin.ts@@ -158,6 +158,14 @@ export class Waters {return this.field_?.query().data ?? null;}+ /**+ * Whether there is no water to ask about: nothing is baked, so `depthAt` answers null everywhere. A world laid out with no water at+ * all is laid out the same here and on a worker, which "no data to hand over" alone does not say.+ */+ get empty(): boolean {+ return this.field_ === null;+ }+/** How deep the water stands at rest over the world height `y` at (x, z): above zero under water, null where there is none. */depthAt(x: number, z: number, y: number): number | null {return this.field_?.query().depthAt(x, z, y) ?? null;diff --git a/sdk/src/worldgen/planWorker.ts b/sdk/src/worldgen/planWorker.tsindex 4ddc2edfc..83c6d6e85 100644--- a/sdk/src/worldgen/planWorker.ts+++ b/sdk/src/worldgen/planWorker.ts@@ -20,14 +20,15 @@ import { Zones } from './zones';import { PlanetFace } from './planetSurface';import { farRulesOf, makeFacePlan } from './facePlan';import { makePlanePlan } from './planePlan';-import { GroundQuery, type GroundData } from '../terrain/groundQuery';+import { GroundQuery, groundSourceOf, type GroundData } from '../terrain/groundQuery';+import type { TerrainSource } from '../terrain/source';import { WaterQuery, type WaterQueryData } from '../water/waterQuery';import type { PlanetFacts } from '../terrain/planetQuery';import type { PlanetProvider } from '../terrain/planetProvider';import type { PlanetPainter } from '../terrain/planetQuery';import { faceOf, type SphereNode } from '../terrain/sphere';import { makePlanetPage, type PlanetPageSource } from '../terrain/planetPages';-import type { PageImage } from '../terrain/pages';+import { makePage, type PageImage } from '../terrain/pages';/** What a plan is made from: everything the main thread knew when it made its own. */export interface PlanSpec {@@ -74,7 +75,11 @@ export interface PlacementsRequest {z1: number;}-interface Made { plan: WorldPlan; farPlan: WorldPlan | null; face: PlanetFace | null }+interface Made {+ plan: WorldPlan; farPlan: WorldPlan | null; face: PlanetFace | null;+ /** A plane's ground as its terrain reads it (in the terrain's own space) and where that terrain stands: what its pages are made from. */+ ground?: { source: TerrainSource; origin: { x: number; y: number; z: number } } | null;+}/** The plans kept, newest last, and the providers loaded (by the text of their source). */const plans = new Map<string, Made>();@@ -100,6 +105,7 @@ function makePlane(spec: PlaneSpec): Made {for (const z of spec.zones) zones.set(z);return {face: null,+ ground: spec.ground ? { source: groundSourceOf(spec.ground), origin: spec.ground.origin } : null,...makePlanePlan({rules: spec.rules, farRules: farRulesOf(spec.rules), seed: spec.seed, world: spec.world, zones,ground: spec.ground ? new GroundQuery(spec.ground) : null, flatY: spec.flatY, water: spec.water ? new WaterQuery(spec.water) : null, layers: spec.layers,@@ -178,13 +184,43 @@ export async function page(r: PageRequest, load: ProviderLoader = blobLoader): Preturn { result: image, transfer: [image.heights.buffer as ArrayBuffer, image.paint.buffer as ArrayBuffer, image.paint2.buffer as ArrayBuffer] };}+/** A page of a plane's terrain to make: the square of the terrain's own space, and the plan whose biomes paint it. */+export interface GroundPageRequest {+ id: number;+ type: 'groundPage';+ /** Names the plan, as a placements question does; a worker that has not seen it is sent `spec` with it. */+ key: string;+ spec?: PlaneSpec;+ x0: number;+ z0: number;+ size: number;+ /** Whether the world has the last word on the ground's paint. */+ paint: boolean;+}++/**+ * The page of a terrain's node, as the terrain would make it: the same source, sampled at the same points, painted by the same plan.+ * The paint is the part worth leaving the main thread for: a world's biomes are read at every sample, tens of milliseconds a page.+ * @internal+ */+export async function groundPage(r: GroundPageRequest, load: ProviderLoader = blobLoader): Promise<{ result: PageImage; transfer: ArrayBuffer[] }> {+ const made = await planFor(r.key, r.spec, load);+ const ground = made.ground;+ if (!ground) throw new Error(`the plan ${r.key} has no ground to make a page of`);+ const { origin } = ground;+ // The terrain hands its repaint world positions, and so does this.+ const image = await makePage(ground.source, r.x0, r.z0, r.size, r.paint ? (x, z, _h, _ny, w) => made.plan.paint(x + origin.x, z + origin.z, w) : undefined);+ return { result: image, transfer: [image.heights.buffer as ArrayBuffer, image.paint.buffer as ArrayBuffer, image.paint2.buffer as ArrayBuffer] };+}+// The worker's loop. Absent where this file is imported as a module (a test), where `self` is not a worker's scope.-declare const self: { onmessage: ((e: { data: PlacementsRequest | PageRequest }) => void) | null; postMessage(m: unknown, transfer?: ArrayBuffer[]): void } | undefined;+declare const self: { onmessage: ((e: { data: PlacementsRequest | PageRequest | GroundPageRequest }) => void) | null; postMessage(m: unknown, transfer?: ArrayBuffer[]): void } | undefined;if (typeof self !== 'undefined' && typeof (self as { importScripts?: unknown }).importScripts === 'function') {self.onmessage = (e) => {const m = e.data;const fail = (err: unknown): void => self!.postMessage({ id: m.id, error: err instanceof Error ? err.message : String(err) });if ((m as { type?: string }).type === 'page') page(m as PageRequest).then((r) => self!.postMessage({ id: m.id, result: r.result }, r.transfer), fail);+ else if ((m as { type?: string }).type === 'groundPage') groundPage(m as GroundPageRequest).then((r) => self!.postMessage({ id: m.id, result: r.result }, r.transfer), fail);else placements(m as PlacementsRequest).then((result) => self!.postMessage({ id: m.id, result }), fail);};}diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.tsindex 82a728d6e..8247abdf9 100644--- a/sdk/src/worldgen/worldgenPlugin.ts+++ b/sdk/src/worldgen/worldgenPlugin.ts@@ -43,7 +43,8 @@ import { makePlanePlan } from './planePlan';import type { WaterQueryData } from '../water/waterQuery';import type { JobPool } from '../runtime/jobs';import { firstSend, forgetSent, planPool } from '../runtime/planPool';-import type { PlacementsRequest, PlanSpec, PlaneSpec } from './planWorker';+import type { GroundPageRequest, PlacementsRequest, PlanSpec, PlaneSpec } from './planWorker';+import type { PageImage } from '../terrain/pages';import { FaceZones, faceHalf, planetFaces, type PlanetFace } from './planetSurface';import { expandPlants, type PlantSet } from './plants';import { WorldPlan, type Placement } from './plan';@@ -176,6 +177,9 @@ interface BuiltWorld {listeners: (() => void)[];levelled: Set<string>;paint: Terrains['paint_'];+ /** The maker of the ground's pages this world handed its terrain, and the plan it was made for. */+ pager?: Terrains['pager_'];+ pagerKey?: string;/** Zones that level their ground and wait for it to be known. */levelling: Set<string>;/** The rules' plants as kinds, and their parts once the assets are in hand (null while they are being loaded, or when the rules have no plants). */@@ -226,7 +230,7 @@ interface PlacedChunk {}/** The water, as worldgen asks it (the water module is optional: read by name, not imported). */-interface WaterQuery { depthAt(x: number, z: number, y: number): number | null; shoreAt?(x: number, z: number): number | null; queryData?(): WaterQueryData | null; revision_: number; baking: boolean }+interface WaterQuery { depthAt(x: number, z: number, y: number): number | null; shoreAt?(x: number, z: number): number | null; queryData?(): WaterQueryData | null; readonly empty?: boolean; revision_: number; baking: boolean }function waterOf(app: App): WaterQuery | null {const w = (app as unknown as { getResourceByName?: (name: string) => unknown }).getResourceByName?.('Waters') as Partial<WaterQuery> | undefined;@@ -708,11 +712,15 @@ export class WorldGenPlugin implements Plugin {*/private awayOnPlane(app: App, gens: WorldGens, entity: Entity, built: BuiltWorld, terrains: Terrains | null, water: WaterQuery | null, waiting: boolean): Unit['away'] | undefined {const pool = planPool();- if (!pool || waiting || built.data.surface !== WorldSurface.Plane) return undefined;+ // The ground's pages go where the plan is: a world that paints the ground has its biomes read on the workers, or here when they cannot have the plan.+ const mine = built.paint !== null && terrains?.paint_ === built.paint;+ const none = (): undefined => { if (mine && terrains && built.pager && terrains.pager_ === built.pager) terrains.setPager(null); built.pager = null; built.pagerKey = undefined; return undefined; };+ if (!pool || waiting || built.data.surface !== WorldSurface.Plane) return none();const ground = terrains && terrains.built_.size > 0 ? terrains.groundData() : null;- if (terrains && terrains.built_.size > 0 && !ground) return undefined;+ if (terrains && terrains.built_.size > 0 && !ground) return none();const waterData = water ? water.queryData?.() ?? null : null;- if (water && !waterData && water.queryData) return undefined;+ // Water that cannot be handed over keeps the plan here; water there is none of is handed over as none.+ if (water && !waterData && water.queryData && !water.empty) return none();const zones = gens.zones(built.data.world);const key = `${built.signature}:plane:t${terrains?.revision_ ?? 0}:w${water?.revision_ ?? 0}:z${zones.revision}`;const flatY = (app.world.tryGet(entity, Transform) as TransformData | null)?.worldPosition.y ?? 0;@@ -720,9 +728,27 @@ export class WorldGenPlugin implements Plugin {plane: true, rules: { ...built.rules!, fields: undefined, plants: undefined } as WorldRules, seed: built.data.seed, world: built.data.world,ground, flatY, water: waterData, layers: terrains ? terrains.layerNames() : [], zones: [...zones.all()],});+ // The same key and the same workers as the placements: a worker that has laid a square out has the plan a page of it is painted from.+ const workerAt = (x: number, z: number): number => Math.abs((Math.floor(x / 256) * 73856093) ^ (Math.floor(z / 256) * 19349663)) % pool.size;+ if (mine && terrains && ground && built.pagerKey !== key) {+ const origin = ground.origin;+ built.pagerKey = key;+ built.pager = (x0, z0, size) => {+ // Asked for a ground that has changed since (a modifier laid on it, another terrain): not this plan's to make.+ if (built.pagerKey !== key || terrains.groundData() === null) return null;+ const worker = workerAt(x0 + origin.x, z0 + origin.z);+ const first = firstSend(worker, key);+ const request: GroundPageRequest = { id: 0, type: 'groundPage', key, x0, z0, size, paint: true, ...(first ? { spec: spec() } : {}) };+ return pool.run<PageImage>(worker, request as unknown as Record<string, unknown>).catch((e: unknown) => {+ forgetSent(worker, key);+ throw e;+ });+ };+ terrains.setPager(built.pager);+ }return (layer, far, x0, z0, x1, z1) => {// Squares are spread over the workers by where they are, so neighbours share a worker and what it has worked out.- const worker = Math.abs((Math.floor(x0 / 256) * 73856093) ^ (Math.floor(z0 / 256) * 19349663)) % pool.size;+ const worker = workerAt(x0, z0);const first = firstSend(worker, key);const request: PlacementsRequest = { id: 0, key, layer, far, x0, z0, x1, z1, ...(first ? { spec: spec() } : {}) };return pool.run<Placement[]>(worker, request as unknown as Record<string, unknown>).catch((e: unknown) => {@@ -1009,6 +1035,8 @@ export class WorldGenPlugin implements Plugin {const remaining = [...gens.built_.values()].reverse().find(other => !other.retired && other.paint);terrains.setPaint(remaining?.paint ?? null);}+ if (terrains && built.pager && terrains.pager_ === built.pager) terrains.setPager(null);+ built.pager = null;built.paint = null;built.assets.release();}diff --git a/sdk/tests/bakes.test.ts b/sdk/tests/bakes.test.tsindex 679b31e63..2f4afd3f0 100644--- a/sdk/tests/bakes.test.ts+++ b/sdk/tests/bakes.test.ts@@ -50,3 +50,164 @@ describe('jobs spread over frames', () => {expect(finish(counting(5))).toBe('done');});});++/** A clock the test moves by hand. */+const manual = () => { let t = 0; return { now: () => t, spend: (ms: number) => { t += ms; } }; };++/** Works in 1 ms pieces for as long as it is given time, as the engine's steppers do: one piece whatever it is told (what stands by the+ * player is made at once), then while it may. Returns how many it got through, which is that first piece and its part of the frame. */+const work = (bakes: Bakes, owner: object, clock: { spend(ms: number): void }, max = 1000): number => {+ let done = 0;+ do { clock.spend(1); done++; } while (done < max && bakes.hasTime(owner));+ return done;+};++// The ground's far pages, asked first each frame, took the whole budget for half a minute while the chunks and the plants+// beside the player had none of it.+describe('the frame budget is shared', () => {+ it('gives each of those that asked the frame before an equal part, whoever runs first', () => {+ const bakes = new Bakes();+ bakes.budgetMs = 9;+ const clock = manual();+ const terrain = {}, chunks = {}, plants = {};+ // The first frame nobody is known yet, so the first to ask is given all of it.+ bakes.step(clock.now);+ expect(work(bakes, terrain, clock)).toBe(1 + 9);+ work(bakes, chunks, clock); work(bakes, plants, clock);+ // From then on each is expected, and the three share.+ for (let frame = 0; frame < 3; frame++) {+ bakes.step(clock.now);+ expect([work(bakes, terrain, clock), work(bakes, chunks, clock), work(bakes, plants, clock)]).toEqual([1 + 3, 1 + 3, 1 + 3]);+ }+ });++ it('passes on what one does not use to those after it', () => {+ const bakes = new Bakes();+ bakes.budgetMs = 9;+ const clock = manual();+ const terrain = {}, chunks = {}, plants = {};+ bakes.step(clock.now);+ work(bakes, terrain, clock); work(bakes, chunks, clock); work(bakes, plants, clock);+ bakes.step(clock.now);+ // The terrain has two pieces left to make and is done as soon as it has asked: the other two share nearly all of the frame,+ // where a third each would have left three milliseconds unused. The chunks have 4.5 ms and stop at 4, a fifth piece not+ // fitting; the plants have the 5 that leaves.+ expect(work(bakes, terrain, clock, 2)).toBe(2);+ expect(work(bakes, chunks, clock)).toBe(1 + 4);+ expect(work(bakes, plants, clock)).toBe(1 + 5);+ });++ it('gives all of it back to one that is left asking alone', () => {+ const bakes = new Bakes();+ bakes.budgetMs = 8;+ const clock = manual();+ const terrain = {}, chunks = {};+ bakes.step(clock.now);+ work(bakes, terrain, clock); work(bakes, chunks, clock);+ bakes.step(clock.now);+ expect(work(bakes, terrain, clock)).toBe(1 + 4);+ // The chunks are done and do not ask: the frame after, the terrain is alone.+ bakes.step(clock.now);+ expect(work(bakes, terrain, clock)).toBe(1 + 8);+ });++ it('never gives the work stepped elsewhere more than the frame has, however many ask', () => {+ const bakes = new Bakes();+ bakes.budgetMs = 8;+ const clock = manual();+ const owners = [{}, {}, {}, {}, {}];+ bakes.step(clock.now);+ for (const o of owners) work(bakes, o, clock);+ for (let frame = 0; frame < 4; frame++) {+ bakes.step(clock.now);+ const before = clock.now();+ for (const o of owners) work(bakes, o, clock);+ // Each does one piece whatever it is told, so five owners may run a piece each past their part.+ expect(clock.now() - before).toBeLessThanOrEqual(8 + owners.length);+ }+ });+});++describe('a piece that would not fit', () => {+ // A cell of grass takes about as long to build as the whole steady budget. Asked only whether time was left, its stepper+ // built two or three a frame.+ it('is left for the next frame once the owner has had its one', () => {+ const bakes = new Bakes();+ bakes.budgetMs = 8;+ const clock = manual();+ const grass = {};+ const cells = (): number => { let made = 0; while (bakes.hasTime(grass)) { clock.spend(8); made++; } return made; };+ bakes.step(clock.now);+ // The first frame it is not known how long a cell takes: the second ask finds time gone already.+ expect(cells()).toBe(1);+ for (let frame = 0; frame < 4; frame++) { bakes.step(clock.now); expect(cells()).toBe(1); }+ });++ it('still gives one piece to an owner whose part is smaller than a piece', () => {+ const bakes = new Bakes();+ bakes.budgetMs = 8;+ const clock = manual();+ const grass = {}, others = [{}, {}, {}];+ const cells = (): number => { let made = 0; while (bakes.hasTime(grass)) { clock.spend(8); made++; } return made; };+ // The first frame nobody is expected, and whoever asks first has all of it.+ bakes.step(clock.now);+ for (const o of others) work(bakes, o, clock);+ cells();+ for (let frame = 0; frame < 4; frame++) {+ bakes.step(clock.now);+ for (const o of others) work(bakes, o, clock);+ // A quarter of the frame is 2 ms and a cell is 8: one is made all the same, or none ever would be.+ expect(cells()).toBe(1);+ }+ });++ it('fits as many small pieces as the part holds', () => {+ const bakes = new Bakes();+ bakes.budgetMs = 8;+ const clock = manual();+ const pages = {};+ const made = (): number => { let n = 0; while (bakes.hasTime(pages)) { clock.spend(2); n++; } return n; };+ bakes.step(clock.now); made();+ bakes.step(clock.now);+ expect(made()).toBe(4);+ });+});++describe('work the player would see missing', () => {+ it('is given more of the frame until it says it is done', () => {+ const bakes = new Bakes();+ bakes.budgetMs = 8;+ bakes.priorityExtraMs = 12;+ const clock = manual();+ const chunks = {};+ expect(bakes.urgent).toBe(false);+ bakes.urge(chunks, true);+ expect(bakes.urgent).toBe(true);+ bakes.step(clock.now);+ expect(work(bakes, chunks, clock)).toBe(1 + 20);+ bakes.urge(chunks, false);+ bakes.step(clock.now);+ expect(work(bakes, chunks, clock)).toBe(1 + 8);+ // An owner that goes away does not hold the frame at the larger budget.+ bakes.urge(chunks, true);+ bakes.clear(chunks);+ expect(bakes.frameBudgetMs).toBe(8);+ });+});++describe('an owner whose pieces are not alike', () => {+ it('is held to its longest piece lately, not to a mean the empty ones pull down', () => {+ const bakes = new Bakes();+ bakes.budgetMs = 8;+ const clock = manual();+ const chunks = {};+ // Five chunks wanted a frame: empty ones that cost nothing, and cells of grass at 8 ms each.+ const frame = (costs: number[]): number => { let spent = 0; for (const c of costs) { if (!bakes.hasTime(chunks)) break; clock.spend(c); spent += c; } return spent; };+ bakes.step(clock.now); frame([0, 0, 8, 0, 0]);+ for (let f = 0; f < 6; f++) {+ bakes.step(clock.now);+ // One cell of grass a frame, whatever stands before it in the list.+ expect(frame([0, 0, 8, 8, 8])).toBe(8);+ }+ });+});diff --git a/sdk/tests/worldgen-worker.test.ts b/sdk/tests/worldgen-worker.test.tsindex 7c9e8d10f..b16df95b0 100644--- a/sdk/tests/worldgen-worker.test.ts+++ b/sdk/tests/worldgen-worker.test.ts@@ -4,9 +4,13 @@ import { describe, expect, it } from 'vitest';import type { PlanetFacts } from '../src/terrain/planetQuery';import { PlanetFace, FaceZones } from '../src/worldgen/planetSurface';import { farRulesOf, makeFacePlan } from '../src/worldgen/facePlan';-import { page, placements, type PageRequest, type PlacementsRequest, type PlanSpec, type PlaneSpec } from '../src/worldgen/planWorker';+import { groundPage, page, placements, type GroundPageRequest, type PageRequest, type PlacementsRequest, type PlanSpec, type PlaneSpec } from '../src/worldgen/planWorker';import { makePlanePlan } from '../src/worldgen/planePlan';-import { GroundQuery, type GroundData } from '../src/terrain/groundQuery';+import { GroundQuery, groundSourceOf, type GroundData } from '../src/terrain/groundQuery';+import { makePageJob, type PageImage } from '../src/terrain/pages';+import { noiseProvider, ProviderSource } from '../src/terrain/provider';+import { ModifiedSource } from '../src/terrain/source';+import { paintWeights } from '../src/terrain/paint';import { WaterQuery, type WaterQueryData } from '../src/water/waterQuery';import { Zones } from '../src/worldgen/zones';import { makePlanetPage } from '../src/terrain/planetPages';@@ -160,3 +164,61 @@ describe('a flat world planned in a worker', () => {}});});++// A terrain's pages cost the frame tens of milliseconds each once a world's biomes paint them, so they are made where the plan is.+// What comes back has to be the page the terrain would have made itself, byte for byte: a seam between a page made here and one+// made there is a line across the ground.+describe("a terrain's pages made in a worker", () => {+ const params = { seed: 5, frequency: 6, octaves: 4, persistence: 0.5, ridged: 0.3, warp: 0.35, erosion: 1, sizeX: 400, height: 60, rockSlope: 0.5, dirtHeight: 0.4, snowHeight: 0.9 };+ // The engine's noise as a provider is the world's ground: a terrain standing at (120, 3, -30) reads it there.+ const origin = { x: 120, y: 3, z: -30 };+ const ground: GroundData = { origin, cell: 2, source: { kind: 'noise', data: params }, shift: { x: origin.x, z: origin.z } };+ const paintRules: WorldRules = { ...rules, biomes: [{ ...rules.biomes![0]!, conditions: [{ field: 'height', min: -100, max: 100 }], paint: { grass: 0.2, dirt: 0.8 } } as never] };+ const planeSpec: PlaneSpec = { plane: true, rules: paintRules, seed: 9, world: 'w', ground, flatY: 0, water: null, layers: ['grass', 'dirt', 'snow', 'rock'], zones: [] };++ /** The terrain's own source for that ground, as terrainPlugin makes it, and the page it makes on the main thread. */+ const here = (x0: number, z0: number, size: number, paint: boolean): PageImage => {+ const provider = noiseProvider(() => params);+ const base = new ProviderSource(provider, 'w', params.seed, 1, origin.x, origin.z, 2, (h, ny) => paintWeights(h / Math.max(params.height, 1e-6), ny, params));+ const source = new ModifiedSource(base, () => [], origin, 2);+ const { plan } = makePlanePlan({+ rules: paintRules, farRules: farRulesOf(paintRules), seed: 9, world: 'w', zones: new Zones(), ground: new GroundQuery(ground), flatY: 0, water: null, layers: planeSpec.layers,+ });+ const job = makePageJob(source, x0, z0, size, paint ? (x, z, _h, _ny, w) => plan.paint(x + origin.x, z + origin.z, w) : undefined);+ for (;;) { const next = job.next(); if (next.done) return next.value; }+ };++ it("reads the same ground as the terrain standing on a provider's world", () => {+ const provider = noiseProvider(() => params);+ const base = new ProviderSource(provider, 'w', params.seed, 1, origin.x, origin.z, 2, () => [1, 0, 0, 0]);+ const away = groundSourceOf(ground);+ for (const [x, z] of [[0, 0], [17.5, -3], [-400, 912.25], [3000, -2000]] as const) {+ expect(away.height(x, z)).toBe(base.height(x, z));+ }+ // And it is not the terrain's own noise read at its own origin, which is other ground.+ expect(groundSourceOf({ ...ground, shift: undefined }).height(17.5, -3)).not.toBe(base.height(17.5, -3));+ });++ it('are the pages the terrain makes, at every level, painted by the world or not', async () => {+ let k = 0;+ for (const [x0, z0, size] of [[0, 0, 128], [-256, 128, 128], [-2048, 0, 2048], [4096, -4096, 4096]] as const) {+ for (const paint of [true, false]) {+ const request: GroundPageRequest = { id: 1, type: 'groundPage', key: `ground${paint}`, ...(k++ < 2 ? { spec: structuredClone(planeSpec) } : {}), x0, z0, size, paint };+ const away = await groundPage(request, loader);+ const mine = here(x0, z0, size, paint);+ expect(away.result.min).toBe(mine.min);+ expect(away.result.max).toBe(mine.max);+ expect(Buffer.from(away.result.heights).equals(Buffer.from(mine.heights))).toBe(true);+ expect(Buffer.from(away.result.paint).equals(Buffer.from(mine.paint))).toBe(true);+ expect(Buffer.from(away.result.paint2).equals(Buffer.from(mine.paint2))).toBe(true);+ // Handed back, not copied: three buffers a page.+ expect(away.transfer).toHaveLength(3);+ }+ }+ });++ it('says so when its plan has no ground to make a page of', async () => {+ const request: GroundPageRequest = { id: 1, type: 'groundPage', key: 'flat', spec: { ...structuredClone(planeSpec), ground: null }, x0: 0, z0: 0, size: 128, paint: true };+ await expect(groundPage(request, loader)).rejects.toThrow(/no ground/);+ });+});