Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(worldgen): a flat world over a terrain and its water is worked out on worker threads

yhhe86d8b190929
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 303b1a379..43437fb8d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ published separately; it ships inside the editor.
### Added
- **A generated world on worker threads.** A planet provider can give the engine its generator as `workerSource` (the text of a self-contained module), and the world's placements and the planet's pages (heights, normals, and the paint by the biomes) are then worked out by a pool of workers (`runtime/jobs.ts`), byte for byte what the main thread works out, while the main thread only puts each answer in the world as it arrives. Laying out a planet's world no longer costs the frame: 2 to 8 frames a second while it was laid out became 60.
+- **A flat world's generation on worker threads too.** Laying out a `WorldGen` over a `Terrain` (a field or noise ground, with its baked water) is worked out by the same pool of workers, from the ground and the water handed over as data, byte for byte what the main thread works out. Stopping the terrain-water example no longer leaves the editor at 2 frames a second: it is back at 60.
- **A planet's sea and sky.** `Planet.sea` draws a translucent, lit sphere at `seaLevel` in which the ground that dips below it stands, and `skyAtmosphere` takes the planet's radius and centre (`u_planetRadius`, `u_planetX/Y/Z`, as `heightFog` does) to work the sky out in the frame of the ground the camera stands on, so the horizon, the sun and the haze follow it round.
- **A generated world on a planet.** A `WorldGen` with `surface` Planet, on a `Planet`'s entity, lays the world out over the cube's six faces, each as a plane of metres, by the same rules a flat world has: biomes over fields, recipes and layers. A direction is planned by the face it falls on; what is placed is taken to the planet and stands along its up. The fields are the planet's own (height, slope, noise in three dimensions with no seam between faces, `paint.<layer>`, and the fields a planet provider names with `fields`), the biomes paint the ground too, and `seaLevel` and `WorldZone`s work over a planet.
- **A planet pulls and answers.** `Planet.gravity` pulls every dynamic 3D body toward the centre of the nearest planet that pulls (the world's gravity is taken off the body and the planet's put on, as a force each fixed step), and the `PlanetRegistryRes` resource answers `up`, `altitude`, `groundHeight`, `groundPoint` and `nearest` for what stands, aims or falls on a round world.
diff --git a/docs/ASYNC_WORLDGEN_PLAN.md b/docs/ASYNC_WORLDGEN_PLAN.md
index c1e2f1390..73d9d6e6f 100644
--- a/docs/ASYNC_WORLDGEN_PLAN.md
+++ b/docs/ASYNC_WORLDGEN_PLAN.md
@@ -29,7 +29,9 @@
已完成第 1、2 步在星球上的部分:`runtime/jobs.ts`(作业池)、`worldgen/planWorker.ts`(放置规划与星球页面,打包成文本 `runtime/planWorkerBundle.generated.ts`,由 `sdk/scripts/build-worker.mjs` 生成并有测试守新鲜度)、`PlanetProvider.workerSource`(提供器的自包含模块文本,星邻由 `tools/build-provider-worker.mjs` 生成)。提交一侧:结果到达即放入世界,不排队、不限量;标为 `async` 的块层不受帧时间约束。实测星邻球面世界铺设期间:此前 2–8 帧,现在 60 帧(p95 33 ms,最差 33 ms);`chunks.step` 44 ms → 2.3 ms,`PlanetSystem` 133 ms → 1.7 ms。worker 的结果与主线程逐字节一致(`tests/worldgen-worker.test.ts`)。
-未做:平面地形(`Terrain`)上的 `WorldGen`(需要水体烘焙场可转移)、碰撞三角网、没有 Worker 时的主线程路径仍是分帧。
+平面地形(`Terrain`)上的 `WorldGen` 也已上 worker:地面(场或噪声源,上面没有叠加修改器)与烘焙后的水体以数据发给 worker(`GroundData`、`WaterQueryData`,规划代码同一份 `planePlan.ts`);不满足时(高度图以外的源、叠加修改器、水体未烘焙完)仍在主线程规划。`examples/terrain-water` 停止运行后 2 帧 → 60 帧。
+
+未做:碰撞三角网、没有 Worker 时的主线程路径仍是分帧。
## 先后
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index efeb98357..ebb5ea1d4 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -4075,6 +4075,8 @@ maxHeight: number
minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => LayerWeights
+toData: () => FieldSourceData
+static fromData: (d: FieldSourceData) => FieldSource
static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number], splat2?: Splat | null): FieldSource
static prototype: FieldSource
```
@@ -6001,6 +6003,8 @@ minHeight: 0
normal: (x: number, z: number) => [number, number, number]
paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
sample: (x: number, z: number) => [number, number, number]
+toData: () => NoiseParams
+static fromData: (p: NoiseParams) => NoiseSource
static new (p: NoiseParams): NoiseSource
static prototype: NoiseSource
```
@@ -10305,6 +10309,7 @@ areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
+groundData: () => GroundData | null
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
@@ -11967,6 +11972,7 @@ grid: ZoneGrid
height: Float32Array<ArrayBufferLike>
ocean: ZoneOcean | null
owner: Int32Array<ArrayBufferLike>
+query: () => WaterQuery
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
@@ -12045,6 +12051,7 @@ depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
+queryData: () => WaterQueryData | null
rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
shoreAt: (x: number, z: number) => number | null
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index c9310e818..aec219714 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -4083,6 +4083,8 @@ maxHeight: number
minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => LayerWeights
+toData: () => FieldSourceData
+static fromData: (d: FieldSourceData) => FieldSource
static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number], splat2?: Splat | null): FieldSource
static prototype: FieldSource
```
@@ -6199,6 +6201,8 @@ minHeight: 0
normal: (x: number, z: number) => [number, number, number]
paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
sample: (x: number, z: number) => [number, number, number]
+toData: () => NoiseParams
+static fromData: (p: NoiseParams) => NoiseSource
static new (p: NoiseParams): NoiseSource
static prototype: NoiseSource
```
@@ -10518,6 +10522,7 @@ areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
+groundData: () => GroundData | null
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
@@ -12180,6 +12185,7 @@ grid: ZoneGrid
height: Float32Array<ArrayBufferLike>
ocean: ZoneOcean | null
owner: Int32Array<ArrayBufferLike>
+query: () => WaterQuery
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
@@ -12258,6 +12264,7 @@ depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
+queryData: () => WaterQueryData | null
rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
shoreAt: (x: number, z: number) => number | null
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index f7ba92a27..63fa5c0a0 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -4070,6 +4070,8 @@ maxHeight: number
minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => LayerWeights
+toData: () => FieldSourceData
+static fromData: (d: FieldSourceData) => FieldSource
static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number], splat2?: Splat | null): FieldSource
static prototype: FieldSource
```
@@ -5996,6 +5998,8 @@ minHeight: 0
normal: (x: number, z: number) => [number, number, number]
paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
sample: (x: number, z: number) => [number, number, number]
+toData: () => NoiseParams
+static fromData: (p: NoiseParams) => NoiseSource
static new (p: NoiseParams): NoiseSource
static prototype: NoiseSource
```
@@ -10300,6 +10304,7 @@ areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
+groundData: () => GroundData | null
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
@@ -11962,6 +11967,7 @@ grid: ZoneGrid
height: Float32Array<ArrayBufferLike>
ocean: ZoneOcean | null
owner: Int32Array<ArrayBufferLike>
+query: () => WaterQuery
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
@@ -12040,6 +12046,7 @@ depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
+queryData: () => WaterQueryData | null
rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
shoreAt: (x: number, z: number) => number | null
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index ce4387a54..492f8e049 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -4070,6 +4070,8 @@ maxHeight: number
minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => LayerWeights
+toData: () => FieldSourceData
+static fromData: (d: FieldSourceData) => FieldSource
static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number], splat2?: Splat | null): FieldSource
static prototype: FieldSource
```
@@ -6289,6 +6291,8 @@ minHeight: 0
normal: (x: number, z: number) => [number, number, number]
paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
sample: (x: number, z: number) => [number, number, number]
+toData: () => NoiseParams
+static fromData: (p: NoiseParams) => NoiseSource
static new (p: NoiseParams): NoiseSource
static prototype: NoiseSource
```
@@ -10593,6 +10597,7 @@ areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
+groundData: () => GroundData | null
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
@@ -12261,6 +12266,7 @@ grid: ZoneGrid
height: Float32Array<ArrayBufferLike>
ocean: ZoneOcean | null
owner: Int32Array<ArrayBufferLike>
+query: () => WaterQuery
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
@@ -12339,6 +12345,7 @@ depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
+queryData: () => WaterQueryData | null
rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
shoreAt: (x: number, z: number) => number | null
diff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.md
index 283c83b1c..ddbe6766d 100644
--- a/sdk/etc/terrain.api.md
+++ b/sdk/etc/terrain.api.md
@@ -33,6 +33,8 @@ maxHeight: number
minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => LayerWeights
+toData: () => FieldSourceData
+static fromData: (d: FieldSourceData) => FieldSource
static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number], splat2?: Splat | null): FieldSource
static prototype: FieldSource
```
@@ -107,6 +109,8 @@ minHeight: 0
normal: (x: number, z: number) => [number, number, number]
paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
sample: (x: number, z: number) => [number, number, number]
+toData: () => NoiseParams
+static fromData: (p: NoiseParams) => NoiseSource
static new (p: NoiseParams): NoiseSource
static prototype: NoiseSource
```
@@ -551,6 +555,7 @@ areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
+groundData: () => GroundData | null
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
diff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.md
index 495ed446a..3057bb23e 100644
--- a/sdk/etc/water.api.md
+++ b/sdk/etc/water.api.md
@@ -154,6 +154,7 @@ grid: ZoneGrid
height: Float32Array<ArrayBufferLike>
ocean: ZoneOcean | null
owner: Int32Array<ArrayBufferLike>
+query: () => WaterQuery
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
@@ -232,6 +233,7 @@ depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
+queryData: () => WaterQueryData | null
rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
shoreAt: (x: number, z: number) => number | null
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 0db6c7afe..8adf4f722 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -4070,6 +4070,8 @@ maxHeight: number
minHeight: number
normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => LayerWeights
+toData: () => FieldSourceData
+static fromData: (d: FieldSourceData) => FieldSource
static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null, range?: readonly [number, number], splat2?: Splat | null): FieldSource
static prototype: FieldSource
```
@@ -6003,6 +6005,8 @@ minHeight: 0
normal: (x: number, z: number) => [number, number, number]
paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
sample: (x: number, z: number) => [number, number, number]
+toData: () => NoiseParams
+static fromData: (p: NoiseParams) => NoiseSource
static new (p: NoiseParams): NoiseSource
static prototype: NoiseSource
```
@@ -10307,6 +10311,7 @@ areaBounds: () => [number, number, number, number] | null
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
+groundData: () => GroundData | null
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
@@ -11969,6 +11974,7 @@ grid: ZoneGrid
height: Float32Array<ArrayBufferLike>
ocean: ZoneOcean | null
owner: Int32Array<ArrayBufferLike>
+query: () => WaterQuery
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
@@ -12047,6 +12053,7 @@ depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
+queryData: () => WaterQueryData | null
rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
shoreAt: (x: number, z: number) => number | null
diff --git a/sdk/src/runtime/planWorkerBundle.generated.ts b/sdk/src/runtime/planWorkerBundle.generated.ts
index ca5c1aefe..fb82f71e4 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`}),Math.sqrt(1.0036)-.06;function t(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 n(e,n,r){let i=Math.floor(e),a=Math.floor(n),o=e-i,s=n-a,c=o*o*(3-2*o),l=s*s*(3-2*s),u=6*o*(1-o),d=6*s*(1-s),f=t(i,a,r),p=t(i+1,a,r),m=t(i,a+1,r),h=t(i+1,a+1,r),g=p-f,_=m-f,v=f-p-m+h;return[f+g*c+_*l+v*c*l,(g+v*l)*u,(_+v*c)*d]}let r={moisture:{scale:900,octaves:4},temperature:{scale:2400,octaves:3},rock:{scale:500,octaves:4}};function i(...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 a(e){let t=-2128831035;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return t|0}function o(e,t,n,r,i){let a=0,o=0,s=1,l=1;for(let u=0;u<i;u++)a+=c(e*l,t*l,n*l,r+u*131)*s,o+=s,s*=.5,l*=2;return a/o}function s(e,t,n,r){return i(e,t,n,r)}function c(e,t,n,r){let i=Math.floor(e),a=Math.floor(t),o=Math.floor(n),c=e-i,l=t-a,u=n-o,d=c*c*(3-2*c),f=l*l*(3-2*l),p=u*u*(3-2*u),m=(e,t,n)=>s(i+e,a+t,o+n,r),h=m(0,0,0)+(m(1,0,0)-m(0,0,0))*d,g=m(0,1,0)+(m(1,1,0)-m(0,1,0))*d,_=m(0,0,1)+(m(1,0,1)-m(0,0,1))*d,v=m(0,1,1)+(m(1,1,1)-m(0,1,1))*d,y=h+(g-h)*f;return y+(_+(v-_)*f-y)*p}function l(e,t,r,i){let a=0,o=0,s=1,c=1;for(let l=0;l<i;l++)a+=n(e*c,t*c,r+l*131)[0]*s,o+=s,s*=.5,c*=2;return a/o}var u=class{constructor(e){this.inputs=e,this.seeds_={},this.noise_={...r};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^a(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),s=Math.max(1,i.octaves??3);this.inputs.space?r(n,()=>{let r=this.inputs.space(e,t);return o(r[0]/a,r[1]/a,r[2]/a,this.seeds_[n],s)}):r(n,()=>l(e/a,t/a,this.seeds_[n],s))}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 d(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 f(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 p(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 m=class{constructor(){this.zones_=new Map,this.revision=0,this.onChange=null}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.onChange?.(p(t),t),this.onChange?.(p(e),e))}delete(e){let t=this.zones_.get(e);t&&(this.zones_.delete(e),this.revision++,this.onChange?.(p(t),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=f(i,d(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,o){for(let{zone:s,weight:c}of this.at(e,t,n))if(s.excludes.some(e=>e===`*`||r.includes(e))&&(c>=1||i(o,a(s.id),Math.floor(e*16),Math.floor(t*16))<c))return s;return null}};let h=[{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]}],g=Math.PI/4;function _(e,t,n,r=[0,0,0]){let i=h[e],a=Math.tan(t*g),o=Math.tan(n*g),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 v(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=h[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)/g,v:Math.atan(u/c)/g}}function y(e,t,n,r){let i=h[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)/g,v:Math.atan(s/a)/g}}let b=(e,t)=>2/2**(e-1-t);function x(e,t){let n=b(e,t.level);return{u0:-1+t.ix*n,v0:-1+t.iz*n,span:n}}function S(e,t,n,r){let i=h[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 C(e,t){let{u0:n,v0:r,span:i}=x(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++){_(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=>w(e,t,o,n.heights,n.paint)):w(e,t,o,c.heights,c.paint)}function w(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?T(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]],C=b[1]*x[2]-b[2]*x[1],w=b[2]*x[0]-b[0]*x[2],T=b[0]*x[1]-b[1]*x[0],E=[n[u*3],n[u*3+1],n[u*3+2]],D=Math.hypot(C,w,T)||1;C/=D,w/=D,T/=D,C*E[0]+w*E[1]+T*E[2]<0&&(C=-C,w=-w,T=-T),S(t.face,E,g,_);let O=C*g[0]+w*g[1]+T*g[2],k=C*_[0]+w*_[1]+T*_[2],A=C*E[0]+w*E[1]+T*E[2];D=Math.hypot(O,A,k)||1,c[u*4]=v>>8,c[u*4+1]=v&255,c[u*4+2]=Math.round((O/D*.5+.5)*255),c[u*4+3]=Math.round((k/D*.5+.5)*255);let j=0,M=0,N=0,P=0;if(y){let e=y(o,a);j=e[0],M=e[1],N=e[2],P=e[3]}else if(i)j=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-A/D)*6,0),1);j=1-e,P=e}l[u*4]=Math.round(Math.min(Math.max(j,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 T(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 E=e=>e*Math.PI/4,D=e=>E(e),O=1.5;var k=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=E(n?.radius??1);return _(this.face,e/r,t/r)}planeOf(e,t,n){let r=this.facts(),i=y(this.face,e,t,n);if(!r||!i)return null;let a=E(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 S(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)*O,r*48+(e-1)*O);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-O,z0:r*48-O,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)/O,i=(n-e.z0)/O,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=O,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=D(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=D(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 A(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)}let j=4e4;function M(e){let t=e.anchor.footprint;for(let n of e.members??[])t=Math.max(t,(n.ring?.[1]??0)+n.footprint);return t}let N=(e,t,n)=>e?e[0]+(e[1]-e[0])*t:n;var P=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_=a(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,M(t)))}this.layers_.push({def:t,hash:a(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,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>j&&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 a=r.candidate,o=this.layers_[e],s=o.def.spacing,c=Math.ceil((a.radius+o.maxRadius)/s);for(let r=-c;r<=c;r++)for(let i=-c;i<=c;i++){if(i===0&&r===0)continue;let o=this.viable(e,t+i,n+r);if(!o.ok)continue;let s=o.candidate;if((s.priority>a.priority||s.priority===a.priority&&(s.gz<n||s.gz===n&&s.gx<t))&&Math.hypot(s.x-a.x,s.z-a.z)<a.radius+s.radius)return`conflict`}let l=`${o.def.id}@${o.def.version??1}:${t},${n}`,u=a.recipe,d=this.place(l,o.def,u,u.anchor,0,a.x,a.z,a.biome,a.fields,0),f=[],p=[d];for(let[r,s]of(u.members??[]).entries()){let c=(e,a)=>i(this.worldHash_,o.hash,t,n,1e3+r*37+e,a),d=s.count?s.count[0]+Math.floor(c(0,0)*(s.count[1]-s.count[0]+1)):1;for(let t=0;t<d;t++){if(s.chance!==void 0&&c(1,t)>=s.chance)continue;let n=N(s.arc,c(2,t),c(2,t)*360)*Math.PI/180,r=N(s.ring,c(3,t),0),i=a.x+Math.cos(n)*r,d=a.z+Math.sin(n)*r,m=this.env.sample(i,d);if(this.standing(m,s)!==null||this.zones.excluding(i,d,s.footprint,this.tagsOf(o.def,u,s),this.seed)!==null||this.occupied(e,i,d,s.footprint)!==null||p.some(e=>Math.hypot(e.x-i,e.z-d)<e.footprint+s.footprint))continue;let h=this.place(l,o.def,u,s,t,i,d,a.biome,m,c(4,t));h&&(f.push(h),p.push(h))}}return{id:l,layer:o.def.id,x:a.x,z:a.z,radius:a.radius,priority:a.priority,anchor:d,members:f}}place(e,t,n,r,o,s,c,l,u,d){if(!Number.isFinite(u.height))return null;let f=i(this.worldHash_,a(e),a(r.id),o,7),p=this.env.inputs.ground(s,c),m=p?.up??1,h=p?.normal??[0,m,Math.sqrt(Math.max(0,1-m*m))];return{id:`${e}/${n.id}@${n.version}/${r.id}.${o}`,group:e,layer:t.id,recipe:n.id,recipeVersion:n.version,member:r.id,biome:l,zone:this.zones.at(s,c)[0]?.zone.id??null,x:s,y:u.height,z:c,yaw:(d||f)*Math.PI*2,scale:N(r.scale,i(this.worldHash_,a(e),o,11),1),normal:h,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:r.footprint,canopy:r.canopy??r.footprint,far:r.far??null}}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>j&&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],a=r.def.spacing,o=e=>i(this.worldHash_,r.hash,t,n,e),s=(t+o(1))*a,c=(n+o(2))*a,l=this.biomeWeights(s,c);if(l.length===0)return{ok:!1,reason:`noBiome`};let u=o(3),d=l[l.length-1].biome;for(let e of l){if(u<e.weight){d=e.biome;break}u-=e.weight}let f=(this.rules.biomes.find(e=>e.id===d)?.recipes??[]).filter(e=>e.layer===r.def.id&&this.recipes_.has(e.recipe)),p=o(4),m=null;for(let e of f){if(p<e.density){m=this.recipes_.get(e.recipe);break}p-=e.density}if(!m)return{ok:!1,reason:`density`};let h=this.env.sample(s,c),g=this.standing(h,m.anchor);if(g)return{ok:!1,reason:g};let _=this.zones.excluding(s,c,m.anchor.footprint,this.tagsOf(r.def,m,m.anchor),this.seed);if(_)return{ok:!1,reason:`zone`,detail:_.id};let v=this.occupied(e,s,c,m.anchor.footprint);return v?{ok:!1,reason:`occupied`,detail:v}:{ok:!0,candidate:{gx:t,gz:n,x:s,z:c,priority:o(5),biome:d,recipe:m,radius:M(m),fields:h}}}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,o=n;if(r>0){let s=a(e.id)^this.worldHash_;i+=(l(t/r,n/r,s,2)-.5)*2*r,o+=(l(t/r,n/r,s+1,2)-.5)*2*r}let s=this.env.sample(i,o),c=e.weight??1;for(let t of e.conditions)if(c*=A(t,s[t.field]??NaN),c<=0)return 0;return c}};function F(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 I(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 u({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 P(t.rules,r,t.zones,t.seed,i),farPlan:t.farRules?new P(t.farRules,r,t.zones,t.seed,i):null}}let L=new Map,R=new Map,z=e=>{let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(t).then(e=>e.default).finally(()=>URL.revokeObjectURL(t))};function B(e,t){let n=R.get(e);return n||(n=t(e),R.set(e,n)),n}async function V(e,t){let n=await B(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 k(e.face,()=>r),a=new m;for(let t of e.zones)a.set(t);return{face:i,...I(i,{rules:e.rules,farRules:F(e.rules),seed:e.seed,world:e.world,seaLevel:e.seaLevel,layers:e.layers,fieldNames:e.fieldNames,zones:a})}}async function H(e,t,n){let r=L.get(e);if(!r){if(!t)throw Error(`the plan ${e} is not known to this worker`);r=await V(t,n),L.set(e,r),L.size>24&&L.delete(L.keys().next().value)}return r}async function U(e,t=z){let n=await H(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 W(e,t=z){let n=await B(e.provider.source,t),r=null;if(e.paintKeys){let n=e.paintKeys,i=await Promise.all(n.map((n,r)=>H(n,e.specs[r],t)));r=(e,t,n,r)=>{let a=i[v(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 C({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`?W(t).then(e=>self.postMessage({id:t.id,result:e.result},e.transfer),n):U(t).then(e=>self.postMessage({id:t.id,result:e}),n)}),e.page=W,e.placements=U,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}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.revision=0,this.onChange=null}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.onChange?.(S(t),t),this.onChange?.(S(e),e))}delete(e){let t=this.zones_.get(e);t&&(this.zones_.delete(e),this.revision++,this.onChange?.(S(t),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)}let B=4e4;function V(e){let t=e.anchor.footprint;for(let n of e.members??[])t=Math.max(t,(n.ring?.[1]??0)+n.footprint);return t}let H=(e,t,n)=>e?e[0]+(e[1]-e[0])*t:n;var U=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,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=this.place(c,a.def,l,l.anchor,0,i.x,i.z,i.biome,i.fields,0),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=H(o.arc,s(2,t),s(2,t)*360)*Math.PI/180,r=H(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);if(this.standing(m,o)!==null||this.zones.excluding(u,p,o.footprint,this.tagsOf(a.def,l,o),this.seed)!==null||this.occupied(e,u,p,o.footprint)!==null||f.some(e=>Math.hypot(e.x-u,e.z-p)<e.footprint+o.footprint))continue;let h=this.place(c,a.def,l,o,t,u,p,i.biome,m,s(4,t));h&&(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){if(!Number.isFinite(c.height))return null;let u=p(this.worldHash_,m(e),m(r.id),i,7),d=this.env.inputs.ground(a,o),f=d?.up??1,h=d?.normal??[0,f,Math.sqrt(Math.max(0,1-f*f))];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:c.height,z:o,yaw:(l||u)*Math.PI*2,scale:H(r.scale,p(this.worldHash_,m(e),i,11),1),normal:h,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:r.footprint,canopy:r.canopy??r.footprint,far:r.far??null}}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=this.standing(h,m.anchor);if(g)return{ok:!1,reason:g};let _=this.zones.excluding(o,s,m.anchor.footprint,this.tagsOf(r.def,m,m.anchor),this.seed);if(_)return{ok:!1,reason:`zone`,detail:_.id};let v=this.occupied(e,o,s,m.anchor.footprint);return v?{ok:!1,reason:`occupied`,detail:v}:{ok:!0,candidate:{gx:t,gz:n,x:o,z:s,priority:a(5),biome:u,recipe:m,radius:V(m),fields:h}}}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 W(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 G(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 U(t.rules,r,t.zones,t.seed,i),farPlan:t.farRules?new U(t.farRules,r,t.zones,t.seed,i):null}}function K(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 U(e.rules,n,e.zones,e.seed,e.world),farPlan:e.farRules?new U(e.farRules,n,e.zones,e.seed,e.world):null}}var ee=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=te(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 te(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 ne(e,t,n,r){let i=e.height(n-t.x,r-t.z);return i===null?null:t.y+i}function re(e,t,n,r){return e.normal(n-t.x,r-t.z)}function ie(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 ae=class{constructor(e){this.source_=e.source.kind===`field`?a.fromData(e.source.data):o.fromData(e.source.data),this.surface_=new ee(this.source_,e.cell),this.origin_=e.origin}heightAt(e,t){return ne(this.surface_,this.origin_,e,t)}normalAt(e,t){return re(this.surface_,this.origin_,e,t)}paintAt(e,t){return ie(this.source_,this.surface_,this.origin_,e,t)}},oe=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 se(e){let t=new C;for(let n of e.zones)t.set(n);return{face:null,...K({rules:e.rules,farRules:W(e.rules),seed:e.seed,world:e.world,zones:t,ground:e.ground?new ae(e.ground):null,flatY:e.flatY,water:e.water?new oe(e.water):null,layers:e.layers})}}async function ce(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,...G(i,{rules:e.rules,farRules:W(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?se(t):await ce(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})({});";
diff --git a/sdk/src/terrain/groundQuery.ts b/sdk/src/terrain/groundQuery.ts
new file mode 100644
index 000000000..b009cd47c
--- /dev/null
+++ b/sdk/src/terrain/groundQuery.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file groundQuery.ts
+ * @brief What the ground says at a world point, from the ground's own data: the same answers on the main thread and on a worker.
+ *
+ * @details A terrain answers three questions at a point: how high, which way it faces, how it is painted. They are the ground's surface (the lattice of
+ * triangles, surface.ts) and its source (the field or the noise), shifted by where the terrain stands. Everything here is a function of that data
+ * 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 { TerrainSurface } from './surface';
+
+/** Where a terrain stands, in the world. */
+export interface GroundOrigin { x: number; y: number; z: number }
+
+/** The world height of the ground at (x, z) on a surface standing at `origin`, or null off it. */
+export function groundHeightAt(surface: TerrainSurface, origin: GroundOrigin, x: number, z: number): number | null {
+ const h = surface.height(x - origin.x, z - origin.z);
+ return h === null ? null : origin.y + h;
+}
+
+/** The ground's unit normal at (x, z), or null off the ground. */
+export function groundNormalAt(surface: TerrainSurface, origin: GroundOrigin, x: number, z: number): [number, number, number] | null {
+ return surface.normal(x - origin.x, z - origin.z);
+}
+
+/** The weights of the ground's layers at (x, z), or null off the ground. */
+export function groundPaintAt(source: TerrainSource, surface: TerrainSurface, origin: GroundOrigin, x: number, z: number): readonly number[] | null {
+ const lx = x - origin.x, lz = z - origin.z;
+ const h = surface.height(lx, lz), n = surface.normal(lx, lz);
+ return h === null || !n ? null : source.paint(lx, lz, h, n[1]);
+}
+
+/** A terrain's ground as data a worker can rebuild it from. */
+export interface GroundData {
+ origin: GroundOrigin;
+ /** The lattice's cell, in the terrain's units. */
+ cell: number;
+ source: { kind: 'field'; data: FieldSourceData } | { kind: 'noise'; data: NoiseParams };
+}
+
+/** The ground of a terrain from its data. */
+export class GroundQuery {
+ private readonly source_: TerrainSource;
+ private readonly surface_: TerrainSurface;
+ private readonly origin_: GroundOrigin;
+
+ constructor(data: GroundData) {
+ this.source_ = data.source.kind === 'field' ? FieldSource.fromData(data.source.data) : NoiseSource.fromData(data.source.data);
+ this.surface_ = new TerrainSurface(this.source_, data.cell);
+ this.origin_ = data.origin;
+ }
+
+ heightAt(x: number, z: number): number | null { return groundHeightAt(this.surface_, this.origin_, x, z); }
+ normalAt(x: number, z: number): [number, number, number] | null { return groundNormalAt(this.surface_, this.origin_, x, z); }
+ paintAt(x: number, z: number): readonly number[] | null { return groundPaintAt(this.source_, this.surface_, this.origin_, x, z); }
+}
diff --git a/sdk/src/terrain/source.ts b/sdk/src/terrain/source.ts
index c2d20cd60..22a976768 100644
--- a/sdk/src/terrain/source.ts
+++ b/sdk/src/terrain/source.ts
@@ -48,6 +48,16 @@ export type LayerWeights = readonly number[];
/** The pixels of a splatmap, as the terrain read them. */
export interface Splat { width: number; height: number; pixels: Uint8Array }
+/** What an area's ground is made of, as plain data a worker can rebuild it from. */
+export interface FieldSourceData {
+ field: Heightfield;
+ params: Pick<TerrainData, 'sizeX' | 'sizeZ' | 'height' | 'rockSlope' | 'dirtHeight' | 'snowHeight'>;
+ splat: Splat | null;
+ splat2: Splat | null;
+ flow: Float32Array | null;
+ range: [number, number];
+}
+
/**
* An area's ground: a field of heights (0 to 1 over `range`, from 0 to `height` by default), centred on the terrain, with its splatmap
* and where its rain ran.
@@ -74,6 +84,19 @@ export class FieldSource implements TerrainSource {
return Math.max(this.maxHeight - this.minHeight, 1e-6);
}
+ /** The ground as data (its arrays are shared, not copied): `FieldSource.fromData` makes the same ground from it. */
+ toData(): FieldSourceData {
+ const d = this.data;
+ return {
+ field: this.field, params: { sizeX: d.sizeX, sizeZ: d.sizeZ, height: d.height, rockSlope: d.rockSlope, dirtHeight: d.dirtHeight, snowHeight: d.snowHeight },
+ splat: this.splat, splat2: this.splat2, flow: this.flow, range: [this.minHeight, this.maxHeight],
+ };
+ }
+
+ static fromData(d: FieldSourceData): FieldSource {
+ return new FieldSource(d.field, d.params, d.splat, d.flow, d.range, d.splat2);
+ }
+
height(x: number, z: number): number | null {
const u = x / this.data.sizeX + 0.5, v = z / this.data.sizeZ + 0.5;
if (u < 0 || u > 1 || v < 0 || v > 1) return null;
@@ -131,6 +154,15 @@ export class NoiseSource implements TerrainSource {
this.maxHeight = p.height;
}
+ /** The ground as data: `NoiseSource.fromData` makes the same ground from it. */
+ toData(): NoiseParams {
+ return { ...this.p };
+ }
+
+ static fromData(p: NoiseParams): NoiseSource {
+ return new NoiseSource(p);
+ }
+
height(x: number, z: number): number {
return this.sample(x, z)[0] * this.p.height;
}
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
index bbac93464..64f0bd1a2 100644
--- a/sdk/src/terrain/terrainPlugin.ts
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -41,7 +41,7 @@ import { findGroundPath, type ReachOptions, type ReachResult } from './reach';
import { paintWeights } from './paint';
export { paintWeights };
-import { FieldSource, ModifiedSource, type TerrainModifier, type TerrainSource } from './source';
+import { FieldSource, ModifiedSource, NoiseSource, type TerrainModifier, type TerrainSource } from './source';
import { levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './quadtree';
import { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage, type Repaint } from './pages';
import { noiseProvider, ProviderSource, terrainProvider, terrainProvidersRevision, TerrainUnavailable, type TerrainProvider } from './provider';
@@ -49,6 +49,7 @@ import { buildPatchMesh } from './patch';
import { isMiniGame } from '../platform';
import { packLayers, type LayerImage, type LayerSource, type TerrainLayerDef } from './layers';
import { TerrainSurface, TILE_CELLS, type SurfaceTile } from './surface';
+import { groundHeightAt, groundNormalAt, groundPaintAt, type GroundData } from './groundQuery';
import { collisionGeometryOf } from '../runtime/collisionGeometry';
import { chunksOf, ProceduralChunksRes } from '../residency/chunks';
import { movers } from './movers';
@@ -247,8 +248,8 @@ export class Terrains {
if (!built.surface || !world.valid(entity)) continue;
const t = world.tryGet(entity, Transform) as TransformData | null;
if (!t) continue;
- const h = built.surface.height(x - t.worldPosition.x, z - t.worldPosition.z);
- if (h !== null) return t.worldPosition.y + h;
+ const h = groundHeightAt(built.surface, t.worldPosition, x, z);
+ if (h !== null) return h;
}
return null;
}
@@ -265,10 +266,8 @@ export class Terrains {
if (!source || !surface || !world.valid(entity)) continue;
const t = world.tryGet(entity, Transform) as TransformData | null;
if (!t) continue;
- const lx = x - t.worldPosition.x, lz = z - t.worldPosition.z;
- const h = surface.height(lx, lz), n = surface.normal(lx, lz);
- if (h === null || !n) continue;
- return source.paint(lx, lz, h, n[1]);
+ const w = groundPaintAt(source, surface, t.worldPosition, x, z);
+ if (w) return w;
}
return null;
}
@@ -295,6 +294,24 @@ export class Terrains {
return out;
}
+ /**
+ * 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.
+ */
+ groundData(): GroundData | null {
+ const world = this.app_?.world;
+ if (!world || this.built_.size !== 1 || this.modifiers_.size > 0) return null;
+ const [entity, built] = [...this.built_][0]!;
+ if (built.failure || built.loading || !built.surface || !built.source || !world.valid(entity)) return null;
+ const t = world.tryGet(entity, Transform) as TransformData | null;
+ if (!t) return null;
+ const base = built.source instanceof ModifiedSource ? built.source.base : built.source;
+ 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() } };
+ return null;
+ }
+
/** The names of the terrain's layers, in the order `paintAt` weighs them: the layer files' names, or grass, dirt, snow and rock without any. */
layerNames(): string[] {
for (const built of this.built_.values()) {
@@ -329,7 +346,7 @@ export class Terrains {
if (!surface || !world.valid(entity)) continue;
const t = world.tryGet(entity, Transform) as TransformData | null;
if (!t) continue;
- const n = surface.normal(x - t.worldPosition.x, z - t.worldPosition.z);
+ const n = groundNormalAt(surface, t.worldPosition, x, z);
if (n) return n;
}
return null;
diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.ts
index a3b5b84d7..70e897d38 100644
--- a/sdk/src/water/waterPlugin.ts
+++ b/sdk/src/water/waterPlugin.ts
@@ -14,6 +14,7 @@
* The waves are the ones the Water shader draws: `waves.ts` is the same formula, and {@link Waters.sample} answers from the same field, so
* a floating object, a camera under the surface and a splash all read the surface that is on the screen.
*/
+import type { WaterQueryData } from './waterQuery';
import { riverBedModifiers } from './riverBed';
import type { App, Plugin } from '../app/app';
import { defineSystem, Schedule } from '../ecs/system';
@@ -152,10 +153,14 @@ export class Waters {
/** Whether a bake is in hand: what is placed by the water waits for it. */
baking = false;
+ /** The baked water as data a worker can answer `depthAt` and `shoreAt` from, or null where none is baked. */
+ queryData(): WaterQueryData | null {
+ return this.field_?.query().data ?? 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 {
- const s = this.field_?.sample(x, z);
- return s ? s.height - y : null;
+ return this.field_?.query().depthAt(x, z, y) ?? null;
}
/**
@@ -215,11 +220,7 @@ export class Waters {
* water (how far in from its shore). Past the zone's region it is the open sea's, deep in; null where no water is baked at all.
*/
shoreAt(x: number, z: number): number | null {
- const field = this.field_;
- if (!field) return null;
- const at = field.at(x, z);
- if (at) return -at.shore;
- return field.ocean ? -1e6 : null;
+ return this.field_?.query().shoreAt(x, z) ?? null;
}
private bodyIdOf(entity: Entity): string {
diff --git a/sdk/src/water/waterQuery.ts b/sdk/src/water/waterQuery.ts
new file mode 100644
index 000000000..ea5329fb3
--- /dev/null
+++ b/sdk/src/water/waterQuery.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file waterQuery.ts
+ * @brief What a world is laid out by in the water: how deep it stands over a height, and how far a point is from the shore.
+ *
+ * @details A part of a baked water field that is a function of three arrays, so a worker given them answers as the main thread does. Its own file so that a
+ * worker carries these few lines and not the baking of water.
+ */
+
+/** The grid a zone is baked over. */
+export interface ZoneGrid { minX: number; minZ: number; sizeX: number; sizeZ: number; nx: number; nz: number }
+
+/** How far a texel is from a shore when it is the open sea's: past any shore, deep in. */
+export const DEEP = 1e6;
+
+/** The part of a baked water field that a world is laid out by, as data a worker can be given. */
+export interface WaterQueryData {
+ grid: ZoneGrid;
+ /** The surface's height at rest, and the distance from the shore (above zero in the water), at each texel. */
+ height: Float32Array;
+ shore: Float32Array;
+ /** The open sea past the region, if the zone has one. */
+ ocean: { level: number } | null;
+}
+
+/** How deep water stands at a point and how far it is from the shore: what a world is laid out by, from the field's own numbers. */
+export class WaterQuery {
+ constructor(readonly data: WaterQueryData) {}
+
+ private lerp(x: number, z: number): { height: number; shore: number } | null {
+ const { minX, minZ, sizeX, sizeZ, nx, nz } = this.data.grid;
+ if (nx < 2 || nz < 2) return null;
+ const u = (x - minX) / sizeX, v = (z - minZ) / sizeZ;
+ if (u < 0 || u > 1 || v < 0 || v > 1) return null;
+ const fx = u * (nx - 1), fz = v * (nz - 1);
+ const i = Math.min(Math.floor(fx), nx - 2), j = Math.min(Math.floor(fz), nz - 2);
+ const tx = fx - i, tz = fz - j, k = j * nx + i;
+ const at = (a: Float32Array): number => (a[k]! * (1 - tx) + a[k + 1]! * tx) * (1 - tz) + (a[k + nx]! * (1 - tx) + a[k + nx + 1]! * tx) * tz;
+ return { height: at(this.data.height), shore: at(this.data.shore) };
+ }
+
+ /** 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 {
+ const inside = this.lerp(x, z);
+ if (inside) return inside.shore > 0 ? inside.height - y : null;
+ return this.data.ocean ? this.data.ocean.level - y : null;
+ }
+
+ /** How far (x, z) is from the water's edge: above zero on dry land, below in the water, deep in the open sea past the region; null where no water is baked. */
+ shoreAt(x: number, z: number): number | null {
+ const inside = this.lerp(x, z);
+ if (inside) return -inside.shore;
+ return this.data.ocean ? -DEEP : null;
+ }
+}
+
diff --git a/sdk/src/water/zone.ts b/sdk/src/water/zone.ts
index 3a7600a84..8cbb417e6 100644
--- a/sdk/src/water/zone.ts
+++ b/sdk/src/water/zone.ts
@@ -19,6 +19,7 @@
*
* The field is in the world's own frame on the xz plane: bodies may be turned about their up, not tilted.
*/
+import { DEEP, WaterQuery, type WaterQueryData, type ZoneGrid } from './waterQuery';
import { defineComponent, type ComponentDef } from '../ecs/component';
import { polygonSdf, shoreDamp, type Point2 } from './shore';
@@ -116,7 +117,7 @@ export type ZoneBody = ZoneOcean | ZoneLake | ZoneRiver;
export type ZoneGround = (x: number, z: number) => number | null;
/** The region a field is baked over, in world units, and its grid. */
-export interface ZoneGrid { minX: number; minZ: number; sizeX: number; sizeZ: number; nx: number; nz: number }
+export type { ZoneGrid } from './waterQuery';
/** What the field encodes its numbers over, which the shader decodes with: see {@link WaterField.encode}. */
export interface ZoneRanges { heightMin: number; heightSpan: number; shore: number; amp: number; flow: number; depth: number }
@@ -150,7 +151,7 @@ export function currentShare(width: number, widest: number): number {
}
/** The depth over ground nothing is known of. */
-const DEEP = 1e6;
+
/** The gentlest slope a depth is turned into a distance by: flatter ground than this is deep water or dry land a long way from a shore. */
const MIN_SLOPE = 0.01;
/** The slopes a shore goes from a beach (waves wash up it) to rock (they burst on it) over. */
@@ -347,6 +348,13 @@ export class WaterField {
return { key: o.key, height: o.level, amp: o.waveHeight, calm: 1, swell: o.waveHeight, flowX: 0, flowZ: 0, shore: DEEP, depth: DEEP, surf: DEEP, still: 1, exposure: o.exposure ?? 1 };
}
+ /** The part of the field a world is laid out by (how deep water stands over a height, how far a point is from the shore), as a query over this field's own arrays. */
+ query(): WaterQuery {
+ return this.query_ ??= new WaterQuery({ grid: this.grid, height: this.height, shore: this.shore, ocean: this.ocean ? { level: this.ocean.level } : null });
+ }
+
+ private query_: WaterQuery | null = null;
+
/** The ranges the encoding spans, from what the field holds; the shore distance reaches `shoreReach` at least (as far out as the surf is drawn). */
ranges(shoreReach = 0): ZoneRanges {
const r = this.ranges_ ??= this.measure();
diff --git a/sdk/src/worldgen/planWorker.ts b/sdk/src/worldgen/planWorker.ts
index 6d73cb741..4ddc2edfc 100644
--- a/sdk/src/worldgen/planWorker.ts
+++ b/sdk/src/worldgen/planWorker.ts
@@ -19,6 +19,9 @@ import type { ZoneDef } from './zones';
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 { WaterQuery, type WaterQueryData } from '../water/waterQuery';
import type { PlanetFacts } from '../terrain/planetQuery';
import type { PlanetProvider } from '../terrain/planetProvider';
import type { PlanetPainter } from '../terrain/planetQuery';
@@ -43,12 +46,26 @@ export interface PlanSpec {
provider: { source: string; seed: number; version: number; world: string };
}
+/** What a plan on a plane is made from: the ground and the water as data, the rules and the zones. */
+export interface PlaneSpec {
+ plane: true;
+ rules: WorldRules;
+ seed: number;
+ world: string;
+ /** The ground, or null for a world flat at `flatY`. */
+ ground: GroundData | null;
+ flatY: number;
+ water: WaterQueryData | null;
+ layers: string[];
+ zones: ZoneDef[];
+}
+
/** A question: the square of the face's plane, and whether it is the far plan's. */
export interface PlacementsRequest {
id: number;
/** Names the plan; a worker that has not seen it is sent `spec` with it. */
key: string;
- spec?: PlanSpec;
+ spec?: PlanSpec | PlaneSpec;
layer: string;
far: boolean;
x0: number;
@@ -57,7 +74,7 @@ export interface PlacementsRequest {
z1: number;
}
-interface Made { plan: WorldPlan; farPlan: WorldPlan | null; face: PlanetFace }
+interface Made { plan: WorldPlan; farPlan: WorldPlan | null; face: PlanetFace | null }
/** The plans kept, newest last, and the providers loaded (by the text of their source). */
const plans = new Map<string, Made>();
@@ -78,6 +95,18 @@ function providerOf(source: string, load: ProviderLoader): Promise<PlanetProvide
return p;
}
+function makePlane(spec: PlaneSpec): Made {
+ const zones = new Zones();
+ for (const z of spec.zones) zones.set(z);
+ return {
+ face: 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,
+ }),
+ };
+}
+
async function makeFor(spec: PlanSpec, load: ProviderLoader): Promise<Made> {
const provider = await providerOf(spec.provider.source, load);
const facts: PlanetFacts = {
@@ -98,11 +127,11 @@ async function makeFor(spec: PlanSpec, load: ProviderLoader): Promise<Made> {
}
/** The plan for `key`: the one this worker kept, or one made from `spec`. */
-async function planFor(key: string, spec: PlanSpec | null | undefined, load: ProviderLoader): Promise<Made> {
+async function planFor(key: string, spec: PlanSpec | PlaneSpec | null | undefined, load: ProviderLoader): Promise<Made> {
let made = plans.get(key);
if (!made) {
if (!spec) throw new Error(`the plan ${key} is not known to this worker`);
- made = await makeFor(spec, load);
+ made = 'plane' in spec ? makePlane(spec) : await makeFor(spec, load);
plans.set(key, made);
if (plans.size > PLANS_KEPT) plans.delete(plans.keys().next().value!);
}
@@ -140,7 +169,7 @@ export async function page(r: PageRequest, load: ProviderLoader = blobLoader): P
const made = await Promise.all(keys.map((k, f) => planFor(k, r.specs[f], load)));
painter = (dx, dy, dz, base) => {
const m = made[faceOf(dx, dy, dz).face]!;
- const at = m.face.planeOf(dx, dy, dz);
+ const at = m.face!.planeOf(dx, dy, dz);
return at ? m.plan.paint(at.x, at.z, base) : base;
};
}
diff --git a/sdk/src/worldgen/planePlan.ts b/sdk/src/worldgen/planePlan.ts
new file mode 100644
index 000000000..b6d3a0e6d
--- /dev/null
+++ b/sdk/src/worldgen/planePlan.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file planePlan.ts
+ * @brief The plan of a world on a plane (a terrain of x and z), made the same way on the main thread and on a worker.
+ *
+ * @details A plane's plan reads the ground (its height, its normal, how it is painted) and the water (how deep it stands, how far a point is from the shore).
+ * Both are asked through two small interfaces, so the main thread can give it the terrain and the water it has and a worker the same answers rebuilt
+ * from the data they were sent: one function makes the plan, and where it is made is not part of what it places.
+ */
+import { Environment } from './fields';
+import { WorldPlan } from './plan';
+import type { WorldRules } from './rules';
+import type { Zones } from './zones';
+
+/** What the plan asks of the ground. */
+export interface GroundLike {
+ heightAt(x: number, z: number): number | null;
+ normalAt(x: number, z: number): [number, number, number] | null;
+ paintAt(x: number, z: number): readonly number[] | null;
+}
+
+/** What the plan asks of the water. */
+export interface WaterLike {
+ depthAt(x: number, z: number, y: number): number | null;
+ shoreAt(x: number, z: number): number | null;
+}
+
+/** What a plane's plan is made from. */
+export interface PlanePlanInputs {
+ rules: WorldRules;
+ farRules: WorldRules | null;
+ seed: number;
+ world: string;
+ /** The ground, or null where there is none: the world is then flat at `flatY`. */
+ ground: GroundLike | null;
+ flatY: number;
+ water: WaterLike | null;
+ /** The names of the ground's layers, whose paint is a field each (`paint.<name>`). */
+ layers: readonly string[];
+ zones: Zones;
+}
+
+/** A plane's plan, and the far one. */
+export function makePlanePlan(i: PlanePlanInputs): { plan: WorldPlan; farPlan: WorldPlan | null } {
+ // The ground's paint is a field for each of its layers, `paint.grass` for a layer file grass.esterrainlayer: how much of the ground there is that.
+ const paintFields: Record<string, (x: number, z: number) => number> = {};
+ if (i.ground) i.layers.forEach((name, k) => { paintFields[`paint.${name}`] = (x, z) => i.ground!.paintAt(x, z)?.[k] ?? 0; });
+ const env = new Environment({
+ seed: i.seed, noise: i.rules.noise, fields: { ...paintFields, ...i.rules.fields },
+ ground: (x, z) => {
+ if (i.ground) {
+ const y = i.ground.heightAt(x, z);
+ if (y === null) return null;
+ const n = i.ground.normalAt(x, z) ?? [0, 1, 0];
+ return { y, up: n[1], normal: n };
+ }
+ // No terrain: the world is flat at the WorldGen's own height.
+ return { y: i.flatY, up: 1, normal: [0, 1, 0] };
+ },
+ waterDepth: (x, z, y) => i.water?.depthAt(x, z, y) ?? null,
+ shoreDistance: (x, z) => i.water?.shoreAt(x, z) ?? null,
+ overrides: (x, z) => {
+ const out: { field: string; value: number; weight: number }[] = [];
+ for (const { zone, weight } of i.zones.at(x, z)) for (const [field, value] of Object.entries(zone.fields ?? {})) out.push({ field, value, weight });
+ return out;
+ },
+ });
+ return {
+ plan: new WorldPlan(i.rules, env, i.zones, i.seed, i.world),
+ farPlan: i.farRules ? new WorldPlan(i.farRules, env, i.zones, i.seed, i.world) : null,
+ };
+}
diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.ts
index 347b8e51a..e57761099 100644
--- a/sdk/src/worldgen/worldgenPlugin.ts
+++ b/sdk/src/worldgen/worldgenPlugin.ts
@@ -37,9 +37,11 @@ import { PlanetRegistryRes, type PlanetFacts } from '../terrain/planetQuery';
import { faceOf } from '../terrain/sphere';
import { Environment } from './fields';
import { farRulesOf, makeFacePlan } from './facePlan';
+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 } from './planWorker';
+import type { PlacementsRequest, PlanSpec, PlaneSpec } from './planWorker';
import { FaceZones, faceHalf, planetFaces, type PlanetFace } from './planetSurface';
import { expandPlants, type PlantSet } from './plants';
import { WorldPlan, type Placement } from './plan';
@@ -214,7 +216,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; 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; 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;
@@ -448,36 +450,16 @@ export class WorldGenPlugin implements Plugin {
if (data.surface === WorldSurface.Planet) { this.planPlanet(app, gens, entity, built, rules); return; }
const terrains = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;
const zones = gens.zones(data.world);
- // The terrain's paint is a field for each of its layers, `paint.grass` for a layer file grass.esterrainlayer: how much of the ground there is that.
- const paintFields: Record<string, (x: number, z: number) => number> = {};
- if (terrains) terrains.layerNames().forEach((name, i) => { paintFields[`paint.${name}`] = (x, z) => terrains.paintAt(x, z)?.[i] ?? 0; });
- const env = new Environment({
- seed: data.seed, noise: rules.noise, fields: { ...paintFields, ...rules.fields },
- ground: (x, z) => {
- if (terrains && terrains.built_.size > 0) {
- const y = terrains.heightAt(x, z);
- if (y === null) return null;
- const n = terrains.normalAt(x, z) ?? [0, 1, 0];
- return { y, up: n[1], normal: n };
- }
- // No terrain: the world is flat at the WorldGen's own height.
- const t = app.world.tryGet(entity, Transform) as TransformData | null;
- return { y: t?.worldPosition.y ?? 0, up: 1, normal: [0, 1, 0] };
- },
- waterDepth: (x, z, y) => waterOf(app)?.depthAt(x, z, y) ?? null,
- shoreDistance: (x, z) => waterOf(app)?.shoreAt?.(x, z) ?? null,
- overrides: (x, z) => {
- const out: { field: string; value: number; weight: number }[] = [];
- for (const { zone, weight } of zones.at(x, z)) for (const [field, value] of Object.entries(zone.fields ?? {})) out.push({ field, value, weight });
- return out;
- },
+ const t0 = app.world.tryGet(entity, Transform) as TransformData | null;
+ const made = makePlanePlan({
+ rules, farRules: farRulesOf(rules), seed: data.seed, world: data.world, zones,
+ ground: terrains && terrains.built_.size > 0 ? terrains : null, flatY: t0?.worldPosition.y ?? 0,
+ water: { depthAt: (x, z, y) => waterOf(app)?.depthAt(x, z, y) ?? null, shoreAt: (x, z) => waterOf(app)?.shoreAt?.(x, z) ?? null },
+ layers: terrains ? terrains.layerNames() : [],
});
- built.plan = new WorldPlan(rules, env, zones, data.seed, data.world);
+ built.plan = made.plan;
const plan = built.plan;
- const sparse = rules.layers.some((l) => (l.farSpacing ?? 1) > 1);
- built.farPlan = sparse
- ? new WorldPlan({ ...rules, layers: rules.layers.map((l) => (l.farSpacing ?? 1) > 1 ? { ...l, spacing: l.spacing * l.farSpacing! } : l) }, env, zones, data.seed, data.world)
- : null;
+ built.farPlan = made.farPlan;
// A zone that changes, or a placement a player changes, makes again only the chunks it reaches.
zones.onChange = (bounds, zone) => {
plan.invalidate();
@@ -641,9 +623,41 @@ export class WorldGenPlugin implements Plugin {
this.publishUnit(app, gens, entity, built, {
key: '', plan, farPlan: built.farPlan, face: null, bounds: terrains?.areaBounds() ?? null,
known: (x, z) => !terrains || terrains.groundKnownAt(x, z),
+ away: this.awayOnPlane(app, gens, entity, built, terrains, water, waiting),
}, ground, waiting);
}
+ /**
+ * What lays a plane's world out on workers, when the ground and the water can be handed to them as data (a terrain of a field or of noise, with nothing laid over it;
+ * water that is baked): the chunks are spread over the workers, and a worker is sent the plan the first time it is asked a square of it. Null when they cannot, and
+ * the world is laid out here.
+ */
+ 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;
+ const ground = terrains && terrains.built_.size > 0 ? terrains.groundData() : null;
+ if (terrains && terrains.built_.size > 0 && !ground) return undefined;
+ const waterData = water ? water.queryData?.() ?? null : null;
+ if (water && !waterData && water.queryData) return undefined;
+ 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;
+ const spec = (): PlaneSpec => ({
+ 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()],
+ });
+ 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 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) => {
+ forgetSent(worker, key);
+ throw e;
+ });
+ };
+ }
+
/** The name of a face's plan for workers: what it was made from, so a plan made from other rules, zones or sea is a new one. */
private planKey(built: BuiltWorld, unit: FaceUnit): string {
return `${built.signature}:f${unit.face.face}:z${unit.zones.zones.revision}`;
diff --git a/sdk/tests/worldgen-worker.test.ts b/sdk/tests/worldgen-worker.test.ts
index 77f1bbafc..7c9e8d10f 100644
--- a/sdk/tests/worldgen-worker.test.ts
+++ b/sdk/tests/worldgen-worker.test.ts
@@ -4,7 +4,11 @@ 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 } from '../src/worldgen/planWorker';
+import { page, placements, 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 { WaterQuery, type WaterQueryData } from '../src/water/waterQuery';
+import { Zones } from '../src/worldgen/zones';
import { makePlanetPage } from '../src/terrain/planetPages';
import { faceOf } from '../src/terrain/sphere';
import { PLAN_WORKER_SOURCE } from '../src/runtime/planWorkerBundle.generated';
@@ -126,3 +130,33 @@ describe('a planet\'s world planned in a worker', () => {
expect(createJobPool(PLAN_WORKER_SOURCE)).toBeNull();
});
});
+
+describe('a flat world planned in a worker', () => {
+ const ground: GroundData = {
+ origin: { x: 0, y: 2, z: 0 }, cell: 2,
+ source: { kind: 'noise', data: { seed: 5, frequency: 6, octaves: 3, persistence: 0.5, ridged: 0, warp: 0, erosion: 0, sizeX: 400, height: 30, rockSlope: 0.7, dirtHeight: 0.3, snowHeight: 0.9 } },
+ };
+ const n = 16;
+ const water: WaterQueryData = {
+ grid: { minX: -200, minZ: -200, sizeX: 400, sizeZ: 400, nx: n, nz: n },
+ height: new Float32Array(n * n).fill(8),
+ shore: Float32Array.from({ length: n * n }, (_, i) => Math.sin(i * 0.37) * 6),
+ ocean: null,
+ };
+ const flatRules: WorldRules = { ...rules, biomes: [{ ...rules.biomes![0]!, conditions: [{ field: 'height', min: -100, max: 100 }, { field: 'shoreDistance', max: 4 }] }] };
+ const planeSpec: PlaneSpec = { plane: true, rules: flatRules, seed: 9, world: 'w', ground, flatY: 0, water, layers: ['grass', 'dirt', 'snow', 'rock'], zones: [] };
+
+ it('places exactly what the main thread places from the same ground and water', async () => {
+ const { plan, farPlan } = makePlanePlan({
+ rules: flatRules, farRules: farRulesOf(flatRules), seed: 9, world: 'w', zones: new Zones(), ground: new GroundQuery(ground), flatY: 0,
+ water: new WaterQuery(water), layers: planeSpec.layers,
+ });
+ for (const far of [false, true]) {
+ const request: PlacementsRequest = { id: 1, key: `plane${far}`, spec: structuredClone(planeSpec), layer: 'cover', far, x0: -60, z0: -40, x1: 60, z1: 80 };
+ const away = await placements(request, loader);
+ const here = (far && farPlan ? farPlan : plan).placementsIn(-60, -40, 60, 80, ['cover']);
+ expect(away.length).toBeGreaterThan(5);
+ expect(JSON.parse(JSON.stringify(away))).toEqual(JSON.parse(JSON.stringify(here)));
+ }
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index bb0b1c9ae..63c41d54a 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2920,6 +2920,8 @@ export const NOTED = {
{"internal":"The worker threads of this release, with no frame slicing."},
"feat(worldgen): a planet's world and pages are worked out on worker threads":
{"note":"A generated world on worker threads."},
+ "feat(worldgen): a flat world over a terrain and its water is worked out on worker threads":
+ {"note":"A flat world's generation on worker threads too."},
"perf(chunks): the chunk and plant growth steps are measured as scopes, and the plan to move generation to worker threads":
{"internal":"Profiler scopes and a design note."},
"feat(terrain): a planet has a sea and a sky that follows the ground the camera stands on":