A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(worldgen): biomes, zones and layered recipes lay a world out as it is explored, with stable ids and kept changes
yhh6118acb21a1a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3aa0d671a..1a746f32e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,7 @@ published separately; it ships inside the editor.- **Terrain from a generator the game names, versioned.** Infinite ground is now made by a terrain provider: a function of the world position that samples whole regions (heights, and paint if it has its own), the same on every machine, and that may answer later from a worker or a server. `Terrain.provider`, `world` and `generatorVersion` name it; `registerTerrainProvider` adds a game's own, and the engine's noise is `estella:noise` version 1. A terrain whose provider is missing, whose version its provider no longer has, or whose heightmap cannot be read fails with a reason in `Terrains.status` and answers nothing, instead of growing noise in its place.- **Terrain collision, the same ground that is drawn.** 3D bodies and characters now collide with a `Terrain`: it is built in tiles round everything that moves on it (`collision`, `collisionDistance`, `collisionLayer`, `friction`), the tile under a body at once, and kept through a rebuild until the new ground replaces it. What is collided with, what `Terrains.heightAt` and `normalAt` answer and the finest level drawn near the eye are now one set of triangles, so a ray, a query and the picture agree wherever the camera is; `Terrains.collisionReadyAt` says when the ground under a point is ready. Any system that makes static geometry while the game runs can hand it to the 3D world through the new `CollisionGeometry` resource.- **Procedural chunks, with one owner and one budget.** What a game makes as it runs is now chunks of layers in `ProceduralChunks` (`chunksOf(app)`): each layer says how it is cut, how far round the streaming sources it is wanted and how a chunk is made, published and released, and the chunks are made nearest first within the frame's budget (the one `Bakes.budgetMs`, shared with the bakes and the terrain's pages), released with everything they published past the unload radius, and made again when the layer's generation changes, the old version staying until the new one replaces it; an answer for an older generation is thrown away. `status` and `stateAt` say where they stand. Terrain collision and foliage cells are layers: plants now grow round the eye out to `drawDistance` and are let go past it, and a changed field or ground regrows them without blinking out.+- **Generated worlds.** The new `esengine/worldgen` lays a world out by a game's rules as it is explored: biomes weighed from fields (the terrain's height and slope, the water's depth, seeded moisture, temperature and rock, and a game's own), mixed at their edges and painting the terrain; recipes an artist composes (an anchor and members round it, with footprint apart from canopy) placed in layers, big things first, each keeping clear of what was placed before it; and `WorldZone`s (a home, a road, a building) that keep out what they name and hold a biome, fading at their edge. The same seed lays out the same world in whatever order its chunks are made, every placement has an id that outlives rules added later, interactive ones are entities with a `PlacedObject`, and what players change (`diffs().remove(id)`) is kept apart and laid over before anything is shown. `plan().explain(x, z)` says why anything stands or does not. A new example, Generated World, walks through one.- **A vertex hook can hand the fragment a colour.** What a material's vertex hook leaves in `es_vertexColor` is now the colour its fragment receives (times the instance's tint), on both backends.- **Bakes run over frames, with progress.** Work that used to hold a frame until it was done (a terrain worn by rain, a water zone baked, terrain chunks built, plants grown) is now spread over frames within a budget, and listed with its progress in the new `Bakes` resource (`bakesOf(app).active`). The editor's status bar shows it as a bar, for the edit world and for the game running in Play, and a game can show it on a loading screen. Plants wait for the ground and the water they stand on instead of being grown twice.- **Eroded and warped terrain.** `Terrain.erosion` wears the ground with rain (a heightmap's as well as the noise's): gullies down the slopes, sharper ridges, silt in the valleys, and dirt painted where the water ran; the same seed wears the same ground. `Terrain.warp` bends the noise by noise of its own for winding valleys and bent ridges. `erodeHeightfield` and `erosionJob` do the same for a tool.@@ -41,6 +42,7 @@ published separately; it ships inside the editor.### Fixed+- **Ridged ground without end has no steps.** Infinite noise ground that was both ridged and worn broke into terraces with sheer walls where a ridge's fold turned; the crest is now rounded over a few hundredths, so the ground is continuous.- **The running game's resolution can be chosen.** A picker beside Play shows the target screen and stays usable while the game runs (it used to sit in a menu that was disabled in Play), with Free Aspect, the project's design resolution, the device presets and portrait or landscape; the choice is kept per project. ([#100](https://github.com/esengine/estella/issues/100))- **Terrain skirts and surf films no longer show as streaks.** The skirt under a terrain chunk's edge, seen where two levels of detail part, took the relief bump meant for the ground and lit as a bright line; it now draws without it. The surf running up dry ground no longer stretches into a wall between two waters' heights.- **Ripples and surf on calm water.** The ripples a zone keeps fade out toward the edge of their window instead of stopping on a line across a lake, a breaker only whitens when it is steep for its length (a lake laps, the sea breaks), and foam seen from under the water is a faint shadow instead of a white sheet.diff --git a/desktop b/desktopindex 1252b3638..63edf20d1 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 1252b36388930bd49cfb8f17114f12ab8135a0d1+Subproject commit 63edf20d13c6d871237516bb30059bbc2def6a01diff --git a/docs/WORLD_GENERATION_PLAN.md b/docs/WORLD_GENERATION_PLAN.mdindex 575ca2acd..e4228f96d 100644--- a/docs/WORLD_GENERATION_PLAN.md+++ b/docs/WORLD_GENERATION_PLAN.md@@ -48,7 +48,16 @@- 跨块:组合按锚点所在块唯一归属,邻块读取足够边界,结果与加载顺序无关。- 持久:保存采集、移除、建造、有限整地的差异,重载时先叠加差异再分布可见物;装饰可合并绘制,可交互对象独立身份。- 调试:群落图、保留区、组边界、拒绝原因与统计。-- 当前状态:植被只有高度/坡度/水深筛选与随机种子;未开始。+- 当前状态:第一版已完成,模块 `esengine/worldgen`(`sdk/src/worldgen/`),示例 `examples/worldgen`,文档 `world/generation`。+ - 环境场(`fields.ts`):地形 height/up/slope、水深 waterDepth、带种子噪声 moisture/temperature/rock,游戏自定义场,区域局部覆盖。+ - 群落(`rules.ts`、`plan.ts`):软区间条件相乘的连续权重、`transition` 噪声扰动边界、按权重抽样混合、地表四层绘制映射(`Terrains.setPaint`),区域可强制群落。+ - 区域(`zones.ts`、`WorldZone` 组件):圆/旋转矩形、类型、优先级、边缘衰减(边缘按权重确定性稀疏)、按标签排除;运行时 `zones().set` 增删只重建触及的区块;编辑器视口画轮廓。+ - 配方与分层:锚点+成员(环距、角度、数量、缩放、占地与树冠分开、直立/贴地、坡度、水深、概率);层按顺序先大后小,抖动网格候选 + 随机优先级邻域仲裁(与加载顺序无关),后层避开前层占地;组合归锚点所在区块。+ - 身份与持久(`diffs.ts`):ID = 层@版本:网格/配方@版本/成员.序号;`remove/change/toJSON/load`,叠加于发布前,只重建对应区块;后加层或配方不改变已有 ID 与位置(有测试)。+ - 发布:T-03 区块层;装饰按区块按种类合并网格;可交互物为独立实体带 `PlacedObject{id, kind}`,`objectOf(id)`;生成实体带 `RuntimeOnly` 不进存档;服务端只生成可交互实体。+ - 调试:`explain(x,z)`(场、群落权重、区域、各层候选与拒绝原因)、`stats`、`biomeWeights`、`placementsIn`。+ - 测试:`sdk/tests/worldgen-plan.test.ts`、`worldgen-plugin.test.ts`。+ - 仍欠:有限整地(区域压平地面)、陆地离岸距离场、装饰远景版本与 GPU 实例化、贴地装饰合并时按直立绘制、配方编辑器、可达性/安全落点等验收由游戏用查询接口实现(引擎可后续提供寻路连通查询)。- 验收:林地建房后草木不穿地板;采集后卸载重进不重生;同种子不同加载顺序结果相同;安全落点、早期资源、入口可达。## 水域补充@@ -74,6 +83,8 @@## 引擎自身待办(同日会话记录)+- 俯视(正下方)相机时视点下方地形出现一块轴对齐暗方块,疑为第一级阴影级联自阴影;平视无此问题(`examples/worldgen` 用 `WORLDGEN_TOP=1` 复现)。+- 植被改为真正的 GPU 实例化(与 T-03/T-04 的放置输出一起设计)。- 雨天/阴天时 CPU 渲染提交阻塞约 45 ms(GPU 计时或同步读回导致),需定位。- 编辑器三维视图套用后处理(天空/雾)后画面上下翻转;改动已撤回,需修呈现路径。diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjsindex ebd86044e..1411a6fd2 100644--- a/docs/astro/astro.config.mjs+++ b/docs/astro/astro.config.mjs@@ -297,6 +297,7 @@ export default defineConfig({{ label: 'Tilemaps', translations: { 'zh-CN': '瓦片地图' }, slug: 'world/tilemaps' },{ label: 'Particles', translations: { 'zh-CN': '粒子' }, slug: 'world/particles' },{ label: 'World Streaming', translations: { 'zh-CN': '世界流送' }, slug: 'world/streaming' },+ { label: 'Generated Worlds', translations: { 'zh-CN': '生成世界' }, slug: 'world/generation' },],},{diff --git a/docs/astro/src/content/docs/world/generation.mdx b/docs/astro/src/content/docs/world/generation.mdxnew file mode 100644index 000000000..d432bf218--- /dev/null+++ b/docs/astro/src/content/docs/world/generation.mdx@@ -0,0 +1,158 @@+---+title: Generated Worlds+description: Lay a world out by rules as it is explored — biomes from fields, groups composed by recipe, zones kept clear, stable ids and the players' changes kept apart.+---++A world scattered at random points reads as noise: trees, flowers and rocks with no shape between them. `esengine/worldgen` lays a+world out the way a designer would — continuous biomes, groups an artist composed, clearings and roads kept open, big things before+small — and does it as the world is explored, the same on every machine and in whatever order its pieces are asked for.++The work is split three ways. The **engine** samples the fields, weighs the biomes, places groups layer by layer, keeps zones clear,+gives every placement a stable id and streams it all in chunks. The **game** writes the rules: which biomes there are, what stands in+them, what is reserved for a home or a road. The **artists** make the recipes: a grove, a rock group, a strip of reeds along a shore.++## The WorldGen component++| Field | What it does |+|---|---|+| `rules` | The rules the world is laid out by, as the game registered them with `registerWorldRules`. |+| `version` | The version of the rules the world was made with. A saved world keeps it; rules that no longer have it fail the world (its status says why) rather than laying out another one. |+| `world`, `seed` | The world (a planet, a level) as the game names it, and its seed. Another seed lays out another world by the same rules. |+| `paintGround` | Whether the biomes paint the terrain. |++What the rules place is published as the entity's children, round the [streaming sources](/docs/world/streaming/) (or the camera):+see [procedural chunks](/docs/world/streaming/#procedural-chunks).++## Rules++```ts+import { registerWorldRules } from 'esengine/worldgen';++registerWorldRules({+ id: 'mygame:wilds',+ versions: [1],+ biomes: [+ { id: 'forest', conditions: [{ field: 'moisture', min: 0.52, blend: 0.08 }, { field: 'up', min: 0.82, blend: 0.05 }],+ transition: 120, paint: [0.55, 0.45, 0, 0], paintStrength: 0.5,+ recipes: [{ recipe: 'grove', layer: 'groups', density: 0.75 }] },+ // …+ ],+ recipes: [+ { id: 'grove', version: 1, tags: ['tree'],+ anchor: { id: 'elder', mesh: 'assets/models/pine.esmesh', material: 'assets/materials/pine.esmaterial', scale: [1.4, 1.8], footprint: 10, canopy: 35 },+ members: [+ { id: 'pine', mesh: 'assets/models/pine.esmesh', count: [3, 6], ring: [45, 110], scale: [0.9, 1.3], footprint: 8 },+ { id: 'sapling', mesh: 'assets/models/pine.esmesh', count: [2, 5], ring: [110, 170], scale: [0.35, 0.6], footprint: 4, chance: 0.8 },+ ] },+ ],+ layers: [+ { id: 'groups', spacing: 260, drawDistance: 4200, chunkSize: 512 },+ { id: 'detail', spacing: 90, drawDistance: 2400 },+ ],+});+```++### Fields++Every decision is made from **fields**: numbers read at any world position. `height`, `up` (how much the ground faces up) and `slope`+come from the terrain's surface, `waterDepth` from the water; `moisture`, `temperature` and `rock` are seeded noise, slow across the+world (their scales are the rules' `noise`). A game adds fields of its own with `fields: { name: (x, z, at) => number }`, reading the+built-in ones from `at`. A zone can set any field over its area.++### Biomes++A biome is a weight over the fields: each condition a band of one field (`min`, `max`) whose edges fade over `blend`, multiplied+together. Where several biomes hold their weights are mixed — a candidate takes a biome by the weights at its place, so two forests+meet in a mixed band instead of a line — and `transition` makes the edge wander by that many world units of noise. `paint` (grass,+dirt, snow, rock) pulls the terrain's own paint toward the biome's by its weight and `paintStrength`. A biome lists its recipes, each+with the layer it is placed in and the share of that layer's candidates it takes.++### Recipes++A recipe is a group: an **anchor** and **members** placed round it. Each member says its mesh and material (asset paths, or handles+already loaded), how many (`count`), how far from the anchor and at what angles (`ring`, `arc`), its `scale`, the ground it takes+(`footprint`: a trunk) apart from how far it spreads overhead (`canopy`: a crown), whether it stands upright or leans with the+ground (`attach`), how steep (`minUp`) and how deep in water (`waterDepth`) it may stand, and the `chance` it is placed at all. A+member that cannot stand (no ground, too steep, under water, kept out by a zone, on something placed before it) is left out; the+group stands.++`version` is part of every placement's id: bump it when a recipe places something else.++### Layers++Layers are passes, in order: big things first. Each takes one candidate a cell of a grid `spacing` apart, jittered, with a priority+drawn for it. Of two candidates whose groups would overlap, the higher priority stands; every candidate keeps clear of the footprints+of the layers before it, so a fern does not grow through a trunk and a stone does not sit inside a boulder. A layer is published in+chunks of `chunkSize` out to `drawDistance`. `occupies: false` makes a layer that later ones may overlap (ground cover).++## Zones++A zone plans an area by hand: a home, a road, a landing site, a building's footprint, a view kept open.++| Field | What it does |+|---|---|+| `kind` | What it is for, in the game's own words. |+| `shape`, `radius`, `sizeX`, `sizeZ` | A circle, or a box turned with the entity about the vertical. The editor draws its outline. |+| `falloff` | Over how many world units past the outline it fades out: what it excludes thins there instead of stopping on a line. |+| `priority` | Where zones overlap, the higher holds the biome. |+| `excludes` | The tags of what it keeps out, separated by commas: a layer, a recipe, a recipe's or member's tags, `decor`, `interactive`; `*` is everything. |+| `biome` | A biome it holds over its area. |++A game adds zones as it plans and as the player builds:++```ts+const gens = app.getResource(WorldGenRes);+gens.zones().set({ id: 'house 1', kind: 'building', shape: { type: 'rect', x, z, halfX: 40, halfZ: 30, yaw },+ falloff: 12, priority: 20, excludes: ['*'] });+```++Only the chunks the zone reaches are made again, each keeping its old version until the new one replaces it.++## Interactive placements and changes++A member with `interactive` (`'ore'`, `'tree'`) is an entity of its own, carrying a `PlacedObject` with its placement id and kind;+everything else is decoration, drawn merged, a mesh a chunk for each kind. `gens.objectOf(id)` finds the entity of a placement.++Ids are made of the layer, the grid cell, the recipe and the member, with their versions (`groups@1:12,-3/grove@1/pine.2`) — never a+position in a list — so they do not change with the order chunks are made in, or when a layer or a recipe is added later.++What a player changes is kept apart from the generated world and laid over it before anything is shown:++```ts+gens.diffs().remove(id); // felled, mined: gone for good+gens.diffs().change(id, { yaw: 1.2 }); // moved, turned, scaled+save(gens.diffs().toJSON()); // what a save stores+gens.diffs().load(saved); // and reads back+```++A felled tree stays felled when its chunk is let go and made again, and after a save is read back. What the player builds is the+game's own: the zone it reserves keeps generation out of its ground.++## Asking the plan++`gens.plan()` answers for anywhere, loaded or not, the same as what is published — what a server, a minimap or a placement check reads:++- `placementsIn(x0, z0, x1, z1, layers?)` — every placement whose group stands in the square.+- `biomeAt(x, z)`, `biomeWeights(x, z)` — the biome there, and every biome's weight.+- `explain(x, z)` — everything that decided what stands there: the fields, the biomes, the zones, and each layer's candidate in that+ cell with why it was rejected (`noBiome`, `density`, `noGround`, `slope`, `water`, `zone`, `occupied`, `conflict`).+- `stats(layer, x0, z0, x1, z1)` — how many candidates stood, and why the rest did not.++## Shipping++Recipes name their meshes and materials by path in code, which a scene does not reference, so a package would leave them out.+Declare the folders they live in always included, in `.esengine/asset-groups.json`:++```json+{ "version": "1.0", "groups": { "recipes": { "folder": "assets/models", "mode": "local", "alwaysInclude": true } } }+```++## Limits++- **No terraforming yet.** A zone keeps generation out of its ground; it does not flatten it.+- **No distance from the shore on land.** `waterDepth` says how deep water stands; a field of how far a dry place is from water is a+ game's own for now.+- **Decoration is drawn whole to `drawDistance`.** It has no far version, and aligned decoration is drawn upright.+- **Rules are code.** Recipes are plain data and can be read from JSON, but there is no editor for them yet.++See the **Generated World** example (`examples/worldgen`).diff --git a/docs/astro/src/content/docs/zh-cn/world/generation.mdx b/docs/astro/src/content/docs/zh-cn/world/generation.mdxnew file mode 100644index 000000000..0bc1d6797--- /dev/null+++ b/docs/astro/src/content/docs/zh-cn/world/generation.mdx@@ -0,0 +1,132 @@+---+title: 生成世界+description: 按规则在探索时布置世界——由环境场得出群落、按配方成组、保留区留空、稳定身份,玩家的改变单独保存。+---++在随机点上散布出来的世界看起来像噪声:树、花、石头之间没有任何形状。`esengine/worldgen` 按设计师的方式布置世界——连续的群落、美术组合好的成组物件、留出的空地和道路、先大后小——并且在世界被探索时才生成,在每台机器上一样,不管各部分以什么顺序被请求。++工作分三方。**引擎**采样环境场、计算群落权重、逐层放置成组物件、让保留区留空、给每个放置物稳定的身份,并按区块流送。**游戏**写规则:有哪些群落、群落里长什么、哪里留给家园或道路。**美术**做配方:一片树林、一组岩石、一条沿岸的芦苇带。++## WorldGen 组件++| 字段 | 作用 |+|---|---|+| `rules` | 布置这个世界的规则,即游戏用 `registerWorldRules` 注册的名字。 |+| `version` | 这个世界生成时使用的规则版本。存档会保留它;规则里已没有这个版本时,世界失败(状态里说明原因),而不是布置出另一个世界。 |+| `world`、`seed` | 游戏给这个世界(星球、关卡)起的名字,以及它的种子。换一个种子就是同一套规则下的另一个世界。 |+| `paintGround` | 群落是否给地形上色。 |++规则放置的东西作为这个实体的子实体发布,围绕[流送源](/docs/zh-cn/world/streaming/)(或摄像机):见[程序化区块](/docs/zh-cn/world/streaming/#程序化区块)。++## 规则++```ts+import { registerWorldRules } from 'esengine/worldgen';++registerWorldRules({+ id: 'mygame:wilds',+ versions: [1],+ biomes: [+ { id: 'forest', conditions: [{ field: 'moisture', min: 0.52, blend: 0.08 }, { field: 'up', min: 0.82, blend: 0.05 }],+ transition: 120, paint: [0.55, 0.45, 0, 0], paintStrength: 0.5,+ recipes: [{ recipe: 'grove', layer: 'groups', density: 0.75 }] },+ // …+ ],+ recipes: [+ { id: 'grove', version: 1, tags: ['tree'],+ anchor: { id: 'elder', mesh: 'assets/models/pine.esmesh', material: 'assets/materials/pine.esmaterial', scale: [1.4, 1.8], footprint: 10, canopy: 35 },+ members: [+ { id: 'pine', mesh: 'assets/models/pine.esmesh', count: [3, 6], ring: [45, 110], scale: [0.9, 1.3], footprint: 8 },+ { id: 'sapling', mesh: 'assets/models/pine.esmesh', count: [2, 5], ring: [110, 170], scale: [0.35, 0.6], footprint: 4, chance: 0.8 },+ ] },+ ],+ layers: [+ { id: 'groups', spacing: 260, drawDistance: 4200, chunkSize: 512 },+ { id: 'detail', spacing: 90, drawDistance: 2400 },+ ],+});+```++### 环境场++每个决定都来自**环境场**:在任意世界位置读到的数值。`height`、`up`(地面朝上的程度)和 `slope` 来自地形的地表,`waterDepth` 来自水体;`moisture`、`temperature` 和 `rock` 是带种子的噪声,在世界尺度上缓慢变化(尺度在规则的 `noise` 里设)。游戏可以用 `fields: { name: (x, z, at) => number }` 加入自己的场,并从 `at` 读取内置场。区域可以在它的范围内设置任意场的值。++### 群落++群落是环境场上的权重:每个条件是某个场的一段区间(`min`、`max`),边缘在 `blend` 范围内衰减,各条件相乘。几个群落同时成立时它们的权重混合——候选点按所在位置的权重选择群落,所以两个群落相接处是一条混合带而不是一条线——`transition` 让边缘按这么多世界单位的噪声摆动。`paint`(草、土、雪、岩)按群落权重和 `paintStrength` 把地形原本的上色拉向群落的上色。群落列出它的配方,以及每个配方所在的层和它占该层候选点的比例。++### 配方++配方是一个组:一个**锚点**和围绕它放置的**成员**。每个成员说明它的网格和材质(资源路径,或已加载的句柄)、数量(`count`)、离锚点多远和在什么角度(`ring`、`arc`)、`scale`、它在地面上占的范围(`footprint`:树干),与它在头顶伸展的范围(`canopy`:树冠)分开记录;它是直立还是随地面倾斜(`attach`)、允许多陡(`minUp`)和多深的水里站立(`waterDepth`),以及被放置的概率 `chance`。站不住的成员(没有地面、太陡、在水下、被区域排除、压在先放的东西上)会被省去,组仍然成立。++`version` 是每个放置物 ID 的一部分:配方放置的东西变了就把它加一。++### 层++层是按顺序进行的几遍布置:先大后小。每层在间距为 `spacing` 的网格里每格取一个抖动后的候选点,并为它抽一个优先级。两个候选点的组会重叠时,优先级高的成立;每个候选点都避开前面各层的占地,所以蕨类不会长穿树干,石头不会嵌进巨石里。一层以 `chunkSize` 大小的区块发布到 `drawDistance`。`occupies: false` 让后面的层可以和它重叠(地被)。++## 区域++区域是手工规划的一块地方:家园、道路、落点、建筑占地、保留的视线。++| 字段 | 作用 |+|---|---|+| `kind` | 它的用途,用游戏自己的词。 |+| `shape`、`radius`、`sizeX`、`sizeZ` | 圆形,或随实体绕竖直轴旋转的矩形。编辑器会画出它的轮廓。 |+| `falloff` | 在轮廓外多少世界单位内逐渐消失:被排除的东西在这里变稀,而不是停在一条线上。 |+| `priority` | 区域重叠时,高的决定群落。 |+| `excludes` | 它排除的东西的标签,逗号分隔:层、配方、配方或成员的标签、`decor`、`interactive`;`*` 表示全部。 |+| `biome` | 它在范围内强制的群落。 |++游戏在规划时和玩家建造时添加区域:++```ts+const gens = app.getResource(WorldGenRes);+gens.zones().set({ id: 'house 1', kind: 'building', shape: { type: 'rect', x, z, halfX: 40, halfZ: 30, yaw },+ falloff: 12, priority: 20, excludes: ['*'] });+```++只有区域触及的区块会重新生成,每个区块的旧版本保留到新版本替换它为止。++## 可交互的放置物与变化++带 `interactive`(如 `'ore'`、`'tree'`)的成员是独立的实体,带有记录放置 ID 与类型的 `PlacedObject`;其余都是装饰,按区块、按种类合并成一个网格绘制。`gens.objectOf(id)` 找到某个放置物对应的实体。++ID 由层、网格坐标、配方和成员以及它们的版本组成(`groups@1:12,-3/grove@1/pine.2`)——从不是列表里的序号——所以它不随区块生成的顺序变化,之后新增层或配方时也不变。++玩家做的改变与生成的世界分开保存,在显示任何东西之前叠加上去:++```ts+gens.diffs().remove(id); // 砍倒、开采:永久消失+gens.diffs().change(id, { yaw: 1.2 }); // 移动、旋转、缩放+save(gens.diffs().toJSON()); // 存档保存的内容+gens.diffs().load(saved); // 以及读回+```++砍倒的树在它的区块被释放再生成后、以及存档读回后都保持砍倒。玩家建造的东西属于游戏自己:它占用的区域让生成避开那块地。++## 查询规划++`gens.plan()` 对任何地方都能回答,不管是否已加载,结果与发布出来的一致——服务器、小地图或放置检查读的就是它:++- `placementsIn(x0, z0, x1, z1, layers?)`——组锚点位于该方块内的所有放置物。+- `biomeAt(x, z)`、`biomeWeights(x, z)`——那里的群落,以及每个群落的权重。+- `explain(x, z)`——决定那里站着什么的一切:环境场、群落、区域,以及每层在那一格的候选点和它被拒绝的原因(`noBiome`、`density`、`noGround`、`slope`、`water`、`zone`、`occupied`、`conflict`)。+- `stats(layer, x0, z0, x1, z1)`——多少候选点成立,其余为什么没有。++## 打包++配方在代码里按路径引用网格和材质,场景不引用它们,所以打包时会被剔除。在 `.esengine/asset-groups.json` 里把它们所在的文件夹声明为始终包含:++```json+{ "version": "1.0", "groups": { "recipes": { "folder": "assets/models", "mode": "local", "alwaysInclude": true } } }+```++## 限制++- **还不能整地。** 区域让生成避开它的地面,但不会把地面压平。+- **陆地上没有离岸距离。** `waterDepth` 说明水有多深;干燥的地方离水多远,目前由游戏自己提供场。+- **装饰完整绘制到 `drawDistance`。** 它没有远景版本,随地面倾斜的装饰按直立绘制。+- **规则是代码。** 配方是普通数据,可以从 JSON 读取,但还没有编辑器。++参见 **Generated World** 示例(`examples/worldgen`)。diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex 198515c11..30184e6bf 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -83,6 +83,9 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {DecalProjector: { category: 'graphics', summary: 'Prints this entity\'s material onto what its box covers — the surface is cut to the box and drawn again, so a decal is lit and shadowed as the surface under it.', doc: 'graphics/lighting', anchor: 'baked-light', anchorZh: '烘焙光照' },StreamedWorld: { category: 'world', summary: 'Declares the scene a streamed world and how big the cook cuts its cells.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },WorldPersistent: { category: 'world', summary: 'Keeps an entity\'s whole subtree out of the partition — it belongs to the persistent world.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },+ WorldGen: { category: 'world', summary: 'A generated world: names the game\'s rules (biomes, recipes, layers), their version, the world and its seed; what the rules place is laid out round the streaming sources.', doc: 'world/generation', anchor: 'the-worldgen-component', anchorZh: 'worldgen-组件' },+ WorldZone: { category: 'world', summary: 'An area of a generated world planned by hand: kept clear of what it excludes, held to a biome, its edge fading out.', doc: 'world/generation', anchor: 'zones', anchorZh: '区域' },+ PlacedObject: { category: 'world', summary: 'Written by a generated world on what the game interacts with (ore, a tree to fell): its stable placement id and kind.', doc: 'world/generation', anchor: 'interactive-placements-and-changes', anchorZh: '可交互的放置物与变化' },WorldStreamingSource: { category: 'world', summary: 'Asks for the places near it to exist; several sources are unioned.', doc: 'world/streaming', anchor: 'asking-for-places-streaming-sources', anchorZh: '请求地方存在流送源' },SpriteMask: { category: 'graphics', summary: "Turns this entity's Sprite into a stencil that cuts the sprites drawn after it — a window, or a hole.", doc: 'graphics/sprites', anchor: 'sprite-masks', anchorZh: '精灵遮罩' },SortingGroup: { category: 'graphics', summary: 'Makes an entity and its whole subtree sort as one unit — the group states the layer and order, members state their place inside it.', doc: 'graphics/sprites', anchor: 'sorting-groups', anchorZh: '排序组' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex a14bc9305..1c8b7ac5b 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -3626,6 +3626,22 @@"fields": [],"tag": true},+ {+ "name": "PlacedObject",+ "source": "ts",+ "fields": [+ {+ "key": "id",+ "type": "string",+ "default": "empty"+ },+ {+ "key": "kind",+ "type": "string",+ "default": "empty"+ }+ ]+ },{"name": "PlanarReflection","source": "cpp",@@ -7668,6 +7684,48 @@"motorSpeed"]},+ {+ "name": "WorldGen",+ "source": "ts",+ "fields": [+ {+ "key": "rules",+ "type": "string",+ "default": "empty",+ "doc": "The rules the world is laid out by, as the game registered them with registerWorldRules."+ },+ {+ "key": "version",+ "type": "number",+ "default": "1",+ "doc": "The version of the rules the world was made with. A version the rules no longer have fails the world rather than laying out another one.",+ "range": "≥ 1, step 1"+ },+ {+ "key": "world",+ "type": "string",+ "default": "empty",+ "doc": "The world (a planet, a level) as the game names it."+ },+ {+ "key": "seed",+ "type": "number",+ "default": "1",+ "doc": "Another seed lays out another world by the same rules.",+ "range": "step 1"+ },+ {+ "key": "paintGround",+ "type": "boolean",+ "default": "true",+ "doc": "Whether the biomes paint the terrain."+ }+ ],+ "animatable": [+ "version",+ "seed"+ ]+ },{"name": "WorldPersistent","source": "ts",@@ -7710,6 +7768,82 @@"loadRadius","unloadRadius"]+ },+ {+ "name": "WorldZone",+ "source": "ts",+ "fields": [+ {+ "key": "kind",+ "type": "string",+ "default": "\"reserve\"",+ "doc": "What the zone is for (home, road, landing, building, resource, view): the game's own words."+ },+ {+ "key": "shape",+ "type": "enum",+ "default": "Circle",+ "values": [+ "Circle",+ "Box"+ ]+ },+ {+ "key": "radius",+ "type": "number",+ "default": "10",+ "doc": "The circle's radius, in world units.",+ "range": "≥ 0"+ },+ {+ "key": "sizeX",+ "type": "number",+ "default": "20",+ "doc": "The box's size along its own x.",+ "range": "≥ 0"+ },+ {+ "key": "sizeZ",+ "type": "number",+ "default": "20",+ "doc": "The box's size along its own z.",+ "range": "≥ 0"+ },+ {+ "key": "falloff",+ "type": "number",+ "default": "4",+ "doc": "Over how many world units past the outline the zone fades out: what it keeps out thins there.",+ "range": "≥ 0"+ },+ {+ "key": "priority",+ "type": "number",+ "default": "0",+ "doc": "Where zones overlap, the higher priority holds the biome.",+ "range": "step 1"+ },+ {+ "key": "excludes",+ "type": "string",+ "default": "\"*\"",+ "doc": "The tags of what the zone keeps out, separated by commas (a layer, a recipe, its tags, decor, interactive); * keeps out everything; empty keeps nothing out."+ },+ {+ "key": "biome",+ "type": "string",+ "default": "empty",+ "doc": "A biome the zone holds over its area; empty holds none."+ }+ ],+ "animatable": [+ "shape",+ "radius",+ "sizeX",+ "sizeZ",+ "falloff",+ "priority"+ ]}]}diff --git a/examples/README.md b/examples/README.mdindex c9ca942b4..16cf2cc52 100644--- a/examples/README.md+++ b/examples/README.md@@ -41,6 +41,7 @@ for your own game.| **render-texture** | Rendering | Render-to-texture — a live minimap painted with the `Draw` API into a `RenderTexture`, resolution cycling on R. || **drawing-demo** | Rendering | The three drawing tiers — immediate `Draw` radar overlay, retained `Graphics` vector star, procedural `Mesh2D` ribbon. || **wilds** | Rendering | A lake under mountains at dusk — a generated `Terrain` from a heightmap, `Water` with measured depth and shore foam, `Foliage` grass and pines swaying in the wind, and clouds that cast shadows. Everything is made from numbers by `tools/build.mjs`. |+| **worldgen** | Rendering | A world laid out by rules as you walk through it — `WorldGen` biomes, groves and rock groups composed by recipe, copper to mine, `WorldZone`s keeping a home and a road clear, over ground without end. || **video-playback** | Rendering | Play a video on a Sprite with the declarative `Video` component — "a Sprite whose texture is alive". || **tilemap-demo** | Tilemap | Two scenes: a Tiled `.tmj` import and an engine-native `.estileset` — multi-tileset, parallax, animated water, per-tile collision. || **ui-controls** | UI | Every built-in widget, authored in the scene: button, toggle, toggle group, slider, progress, dropdown, text input, a modal and a scroll view. |diff --git a/examples/worldgen/.esengine/asset-groups.json b/examples/worldgen/.esengine/asset-groups.jsonnew file mode 100644index 000000000..cd240b2f1--- /dev/null+++ b/examples/worldgen/.esengine/asset-groups.json@@ -0,0 +1,15 @@+{+ "version": "1.0",+ "groups": {+ "recipe-models": {+ "folder": "assets/models",+ "mode": "local",+ "alwaysInclude": true+ },+ "recipe-materials": {+ "folder": "assets/materials",+ "mode": "local",+ "alwaysInclude": true+ }+ }+}diff --git a/examples/worldgen/README.md b/examples/worldgen/README.mdnew file mode 100644index 000000000..9432e9c23--- /dev/null+++ b/examples/worldgen/README.md@@ -0,0 +1,22 @@+# Generated World++A world laid out by rules as you walk through it: the ground goes on for ever, the biomes follow moisture and stone, pines stand in+groves round an elder tree, rocks lie in groups with their scree, copper crops out where the stone does, and a home clearing and a+road are kept open.++- **`Terrain`** is ground without end from the engine's noise provider (`estella:noise`, version 1).+- **`WorldGen`** names the rules in `src/main.ts`: three biomes, five recipes and three layers (groups, resources, detail). The engine+ lays them out round the camera in chunks, nearest first, and lets them go behind it.+- **`WorldZone`**s plan by hand: the home keeps everything out and holds the meadow; the road keeps out trees and rocks.+- **Keys:** W A S D walk, Q E turn, M mines the nearest copper (a change the world keeps), B builds a house in front of you (a zone+ that keeps the wild out of its ground).++The ground textures and the pine are the Wilds example's; the rock and the scene are made by `tools/build.mjs`:++```+node build-tools/cli.js sdk+node examples/worldgen/tools/build.mjs+```++`WORLDGEN_TOP=1` writes the scene with the camera looking straight down on the home, to see how the world is laid out.+`.esengine/asset-groups.json` ships the models and materials the recipes name by path, which no scene references.diff --git a/examples/worldgen/assets/materials/copper.esmaterial b/examples/worldgen/assets/materials/copper.esmaterialnew file mode 100644index 000000000..554093180--- /dev/null+++ b/examples/worldgen/assets/materials/copper.esmaterial@@ -0,0 +1,27 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:foliage",+ "blendMode": 0,+ "depthTest": true,+ "depthWrite": true,+ "cull": 0,+ "properties": {+ "u_baseColor": {+ "r": 0.32,+ "g": 0.16,+ "b": 0.08,+ "a": 1+ },+ "u_tipColor": {+ "r": 0.85,+ "g": 0.48,+ "b": 0.22,+ "a": 1+ },+ "u_windStrength": 0,+ "u_flutter": 0,+ "u_translucency": 0,+ "u_roughness": 0.55+ }+}diff --git a/examples/worldgen/assets/materials/copper.esmaterial.meta b/examples/worldgen/assets/materials/copper.esmaterial.metanew file mode 100644index 000000000..1e843b925--- /dev/null+++ b/examples/worldgen/assets/materials/copper.esmaterial.meta@@ -0,0 +1,6 @@+{+ "uuid": "15d41c58-7f82-4ff6-9b0d-4f6c3f169d91",+ "version": "2.0",+ "type": "material",+ "importer": {}+}diff --git a/examples/worldgen/assets/materials/grass.esmaterial b/examples/worldgen/assets/materials/grass.esmaterialnew file mode 100644index 000000000..387b427a1--- /dev/null+++ b/examples/worldgen/assets/materials/grass.esmaterial@@ -0,0 +1,29 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:foliage",+ "blendMode": 0,+ "depthTest": true,+ "depthWrite": true,+ "cull": 0,+ "properties": {+ "u_baseColor": {+ "r": 0.1,+ "g": 0.22,+ "b": 0.05,+ "a": 1+ },+ "u_tipColor": {+ "r": 0.5,+ "g": 0.66,+ "b": 0.2,+ "a": 1+ },+ "u_windStrength": 3,+ "u_windSpeed": 1.3,+ "u_windDirection": 30,+ "u_gustScale": 0.012,+ "u_flutter": 0.35,+ "u_translucency": 0.5+ }+}diff --git a/examples/worldgen/assets/materials/grass.esmaterial.meta b/examples/worldgen/assets/materials/grass.esmaterial.metanew file mode 100644index 000000000..aa980712e--- /dev/null+++ b/examples/worldgen/assets/materials/grass.esmaterial.meta@@ -0,0 +1,6 @@+{+ "uuid": "93bc2985-002a-430a-8c58-296958f92471",+ "version": "2.0",+ "type": "material",+ "importer": {}+}diff --git a/examples/worldgen/assets/materials/pine.esmaterial b/examples/worldgen/assets/materials/pine.esmaterialnew file mode 100644index 000000000..a4b582cd8--- /dev/null+++ b/examples/worldgen/assets/materials/pine.esmaterial@@ -0,0 +1,32 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:foliage",+ "blendMode": 0,+ "depthTest": true,+ "depthWrite": true,+ "cull": 0,+ "properties": {+ "u_albedo": "assets/textures/pine.png",+ "u_useTexture": 1,+ "u_baseColor": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "u_tipColor": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "u_windStrength": 0.9,+ "u_windSpeed": 0.9,+ "u_windDirection": 30,+ "u_gustScale": 0.006,+ "u_flutter": 0.1,+ "u_translucency": 0.15,+ "u_roughness": 0.9+ }+}diff --git a/examples/worldgen/assets/materials/pine.esmaterial.meta b/examples/worldgen/assets/materials/pine.esmaterial.metanew file mode 100644index 000000000..43bf0b475--- /dev/null+++ b/examples/worldgen/assets/materials/pine.esmaterial.meta@@ -0,0 +1,6 @@+{+ "uuid": "86949029-5487-4c1a-b685-1d0186a047dd",+ "version": "2.0",+ "type": "material",+ "importer": {}+}diff --git a/examples/worldgen/assets/materials/stone.esmaterial b/examples/worldgen/assets/materials/stone.esmaterialnew file mode 100644index 000000000..c15f1b564--- /dev/null+++ b/examples/worldgen/assets/materials/stone.esmaterial@@ -0,0 +1,27 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:foliage",+ "blendMode": 0,+ "depthTest": true,+ "depthWrite": true,+ "cull": 0,+ "properties": {+ "u_baseColor": {+ "r": 0.26,+ "g": 0.25,+ "b": 0.23,+ "a": 1+ },+ "u_tipColor": {+ "r": 0.52,+ "g": 0.5,+ "b": 0.46,+ "a": 1+ },+ "u_windStrength": 0,+ "u_flutter": 0,+ "u_translucency": 0,+ "u_roughness": 0.95+ }+}diff --git a/examples/worldgen/assets/materials/stone.esmaterial.meta b/examples/worldgen/assets/materials/stone.esmaterial.metanew file mode 100644index 000000000..62a2191cb--- /dev/null+++ b/examples/worldgen/assets/materials/stone.esmaterial.meta@@ -0,0 +1,6 @@+{+ "uuid": "352c283e-533b-4088-908e-ee5902dcbc2b",+ "version": "2.0",+ "type": "material",+ "importer": {}+}diff --git a/examples/worldgen/assets/materials/terrain.esmaterial b/examples/worldgen/assets/materials/terrain.esmaterialnew file mode 100644index 000000000..3d76a8750--- /dev/null+++ b/examples/worldgen/assets/materials/terrain.esmaterial@@ -0,0 +1,46 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:terrain",+ "blendMode": 0,+ "depthTest": true,+ "depthWrite": true,+ "cull": 0,+ "properties": {+ "u_layer0": "assets/textures/grass.png",+ "u_layer1": "assets/textures/dirt.png",+ "u_layer2": "assets/textures/snow.png",+ "u_layer3": "assets/textures/rock.png",+ "u_tint0": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "u_tint1": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "u_tint2": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "u_tint3": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "u_tile0": 60,+ "u_tile1": 70,+ "u_tile2": 90,+ "u_tile3": 120,+ "u_macroVariation": 0.5,+ "u_sharpness": 2.2,+ "u_roughness": 0.93+ }+}diff --git a/examples/worldgen/assets/materials/terrain.esmaterial.meta b/examples/worldgen/assets/materials/terrain.esmaterial.metanew file mode 100644index 000000000..6585c1fae--- /dev/null+++ b/examples/worldgen/assets/materials/terrain.esmaterial.meta@@ -0,0 +1,6 @@+{+ "uuid": "cfbf2490-40e0-4cb1-9e34-6b2fba3f8470",+ "version": "2.0",+ "type": "material",+ "importer": {}+}diff --git a/examples/worldgen/assets/models/pine.esmesh b/examples/worldgen/assets/models/pine.esmeshnew file mode 100644index 000000000..8835e07e1Binary files /dev/null and b/examples/worldgen/assets/models/pine.esmesh differdiff --git a/examples/worldgen/assets/models/pine.esmesh.meta b/examples/worldgen/assets/models/pine.esmesh.metanew file mode 100644index 000000000..f7194ee9b--- /dev/null+++ b/examples/worldgen/assets/models/pine.esmesh.meta@@ -0,0 +1,6 @@+{+ "uuid": "a223e2ba-d1ae-4f05-ba4d-e50cf35b47eb",+ "version": "2.0",+ "type": "mesh",+ "importer": {}+}diff --git a/examples/worldgen/assets/models/rock.esmesh b/examples/worldgen/assets/models/rock.esmeshnew file mode 100644index 000000000..62afc8ed7Binary files /dev/null and b/examples/worldgen/assets/models/rock.esmesh differdiff --git a/examples/worldgen/assets/models/rock.esmesh.meta b/examples/worldgen/assets/models/rock.esmesh.metanew file mode 100644index 000000000..e3ab4062f--- /dev/null+++ b/examples/worldgen/assets/models/rock.esmesh.meta@@ -0,0 +1,6 @@+{+ "uuid": "d306658b-5d1f-474c-bf17-7e4943fb9d95",+ "version": "2.0",+ "type": "mesh",+ "importer": {}+}diff --git a/examples/worldgen/assets/scenes/main.esscene b/examples/worldgen/assets/scenes/main.esscenenew file mode 100644index 000000000..50754b9ab--- /dev/null+++ b/examples/worldgen/assets/scenes/main.esscene@@ -0,0 +1,409 @@+{+ "version": 4,+ "name": "Generated World",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 40,+ "y": 478.3989412207621,+ "z": 620+ },+ "rotation": {+ "x": -0.09983341664682815,+ "y": 0,+ "z": 0,+ "w": 0.9950041652780257+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 0,+ "fov": 55,+ "nearPlane": 2,+ "farPlane": 20000,+ "isActive": true,+ "priority": 0+ }+ },+ {+ "type": "PostProcessVolume",+ "data": {+ "isGlobal": true,+ "priority": 0,+ "weight": 1,+ "effects": [+ {+ "type": "skyAtmosphere",+ "enabled": true,+ "uniforms": {+ "u_intensity": 1.05,+ "u_haze": 1.1,+ "u_sunBrightness": 40,+ "u_clouds": 0.45,+ "u_cloudShadow": 0.6,+ "u_unitsPerKm": 1000,+ "u_windSpeed": 0.03+ }+ },+ {+ "type": "gtao",+ "enabled": true,+ "uniforms": {+ "u_radius": 60,+ "u_intensity": 1+ }+ },+ {+ "type": "heightFog",+ "enabled": true,+ "colors": {+ "u_fogColor": {+ "r": 0.62,+ "g": 0.72,+ "b": 0.84,+ "a": 1+ },+ "u_sunColor": {+ "r": 1,+ "g": 0.86,+ "b": 0.62,+ "a": 1+ }+ },+ "uniforms": {+ "u_density": 0.0001,+ "u_heightFalloff": 0.0012,+ "u_baseHeight": 0,+ "u_inscatter": 0.6,+ "u_skyFog": 0.5,+ "u_volumetric": 0.4,+ "u_volumeRange": 4000+ }+ },+ {+ "type": "taa",+ "enabled": true,+ "uniforms": {+ "u_blend": 0.1+ }+ },+ {+ "type": "autoExposure",+ "enabled": true,+ "uniforms": {+ "u_bias": -0.1,+ "u_minEV": -2,+ "u_maxEV": 2+ }+ },+ {+ "type": "colorGrade",+ "enabled": true,+ "uniforms": {+ "u_contrast": 1.06,+ "u_saturation": 1.1+ }+ },+ {+ "type": "fxaa",+ "enabled": true,+ "uniforms": {+ "u_intensity": 1+ }+ }+ ]+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Clock",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "TimeOfDay",+ "data": {+ "hour": 15.5,+ "daySeconds": 0,+ "latitude": 45,+ "declination": 15,+ "north": 0,+ "drive": 31+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "Sun",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Light",+ "data": {+ "type": 1,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "intensity": 3,+ "enabled": true,+ "meshShadows": true,+ "shadowExtent": 2500,+ "shadowStrength": 1,+ "sourceAngle": 0.5+ }+ }+ ]+ },+ {+ "id": 3,+ "name": "Sky",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Light",+ "data": {+ "type": 2,+ "color": {+ "r": 0.8,+ "g": 0.88,+ "b": 1,+ "a": 1+ },+ "intensity": 0.55,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 4,+ "name": "Ground",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Terrain",+ "data": {+ "extent": 1,+ "provider": "estella:noise",+ "world": "demo",+ "generatorVersion": 1,+ "seed": 4,+ "frequency": 3,+ "octaves": 5,+ "persistence": 0.5,+ "ridged": 0.3,+ "warp": 0.35,+ "erosion": 1,+ "sizeX": 4200,+ "height": 520,+ "rockSlope": 0.34,+ "dirtHeight": 0.55,+ "snowHeight": 0.86,+ "cellSize": 4,+ "detail": 1.4,+ "drawDistance": 9000,+ "material": "assets/materials/terrain.esmaterial"+ }+ }+ ]+ },+ {+ "id": 5,+ "name": "World",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "WorldGen",+ "data": {+ "rules": "worldgen-demo:wilds",+ "version": 1,+ "world": "demo",+ "seed": 7,+ "paintGround": true+ }+ }+ ]+ },+ {+ "id": 6,+ "name": "Home",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "WorldZone",+ "data": {+ "kind": "home",+ "shape": 0,+ "radius": 130,+ "falloff": 70,+ "priority": 10,+ "excludes": "*",+ "biome": "meadow"+ }+ }+ ]+ },+ {+ "id": 7,+ "name": "Road",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 520,+ "y": 0,+ "z": -40+ },+ "rotation": {+ "x": 0,+ "y": 0.14943813247359922,+ "z": 0,+ "w": 0.9887710779360422+ }+ }+ },+ {+ "type": "WorldZone",+ "data": {+ "kind": "road",+ "shape": 1,+ "sizeX": 900,+ "sizeZ": 36,+ "falloff": 24,+ "priority": 5,+ "excludes": "tree,rock",+ "biome": ""+ }+ }+ ]+ },+ {+ "id": 9,+ "name": "Canvas",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Canvas",+ "data": {+ "designResolution": {+ "x": 1480,+ "y": 920+ },+ "scaleMode": 2+ }+ },+ {+ "type": "UINode",+ "data": {}+ }+ ]+ },+ {+ "id": 8,+ "name": "Meadow",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 40,+ "y": 0,+ "z": 320+ }+ }+ },+ {+ "type": "Foliage",+ "data": {+ "material": "assets/materials/grass.esmaterial",+ "sizeX": 700,+ "sizeZ": 700,+ "cellSize": 35,+ "count": 1300,+ "seed": 3,+ "minScale": 0.7,+ "maxScale": 1.3,+ "minUp": 0.8,+ "heightMin": -1000,+ "heightMax": 1000,+ "bladeHeight": 40,+ "bladeWidth": 4,+ "lodDistance": 180,+ "drawDistance": 520+ }+ }+ ]+ }+ ]+}diff --git a/examples/worldgen/assets/scenes/main.esscene.meta b/examples/worldgen/assets/scenes/main.esscene.metanew file mode 100644index 000000000..17c867c90--- /dev/null+++ b/examples/worldgen/assets/scenes/main.esscene.meta@@ -0,0 +1,6 @@+{+ "uuid": "7562542d-1608-4c34-988f-e29970daff55",+ "version": "2.0",+ "type": "scene",+ "importer": {}+}diff --git a/examples/worldgen/assets/textures/dirt.png b/examples/worldgen/assets/textures/dirt.pngnew file mode 100644index 000000000..7f0b45481Binary files /dev/null and b/examples/worldgen/assets/textures/dirt.png differdiff --git a/examples/worldgen/assets/textures/dirt.png.meta b/examples/worldgen/assets/textures/dirt.png.metanew file mode 100644index 000000000..a1b0fc474--- /dev/null+++ b/examples/worldgen/assets/textures/dirt.png.meta@@ -0,0 +1,8 @@+{+ "uuid": "35fc90ae-06b9-4732-87a0-54a1dab01d93",+ "version": "2.0",+ "type": "texture",+ "importer": {+ "wrapMode": "repeat"+ }+}diff --git a/examples/worldgen/assets/textures/grass.png b/examples/worldgen/assets/textures/grass.pngnew file mode 100644index 000000000..4faefd158Binary files /dev/null and b/examples/worldgen/assets/textures/grass.png differdiff --git a/examples/worldgen/assets/textures/grass.png.meta b/examples/worldgen/assets/textures/grass.png.metanew file mode 100644index 000000000..3cc548d60--- /dev/null+++ b/examples/worldgen/assets/textures/grass.png.meta@@ -0,0 +1,8 @@+{+ "uuid": "84f9a3a9-95c2-47da-9a9f-85c71f5bcf1b",+ "version": "2.0",+ "type": "texture",+ "importer": {+ "wrapMode": "repeat"+ }+}diff --git a/examples/worldgen/assets/textures/pine.png b/examples/worldgen/assets/textures/pine.pngnew file mode 100644index 000000000..90a41eccbBinary files /dev/null and b/examples/worldgen/assets/textures/pine.png differdiff --git a/examples/worldgen/assets/textures/pine.png.meta b/examples/worldgen/assets/textures/pine.png.metanew file mode 100644index 000000000..a9014ae4f--- /dev/null+++ b/examples/worldgen/assets/textures/pine.png.meta@@ -0,0 +1,6 @@+{+ "uuid": "2b7f0aa9-e978-44a9-bbc4-a60b771fcb3f",+ "version": "2.0",+ "type": "texture",+ "importer": {}+}diff --git a/examples/worldgen/assets/textures/rock.png b/examples/worldgen/assets/textures/rock.pngnew file mode 100644index 000000000..e782f73b0Binary files /dev/null and b/examples/worldgen/assets/textures/rock.png differdiff --git a/examples/worldgen/assets/textures/rock.png.meta b/examples/worldgen/assets/textures/rock.png.metanew file mode 100644index 000000000..2a97fbc61--- /dev/null+++ b/examples/worldgen/assets/textures/rock.png.meta@@ -0,0 +1,8 @@+{+ "uuid": "4716058b-e26e-4151-8ac4-a222ee061435",+ "version": "2.0",+ "type": "texture",+ "importer": {+ "wrapMode": "repeat"+ }+}diff --git a/examples/worldgen/assets/textures/snow.png b/examples/worldgen/assets/textures/snow.pngnew file mode 100644index 000000000..34a3897f4Binary files /dev/null and b/examples/worldgen/assets/textures/snow.png differdiff --git a/examples/worldgen/assets/textures/snow.png.meta b/examples/worldgen/assets/textures/snow.png.metanew file mode 100644index 000000000..ab4bf9d2f--- /dev/null+++ b/examples/worldgen/assets/textures/snow.png.meta@@ -0,0 +1,8 @@+{+ "uuid": "9b5d7702-7c02-41de-a5ce-512ae091e50c",+ "version": "2.0",+ "type": "texture",+ "importer": {+ "wrapMode": "repeat"+ }+}diff --git a/examples/worldgen/project.esproject b/examples/worldgen/project.esprojectnew file mode 100644index 000000000..8e84b88b2--- /dev/null+++ b/examples/worldgen/project.esproject@@ -0,0 +1,19 @@+{+ "formatVersion": "1",+ "name": "Generated World",+ "description": "A world laid out by rules as you look at it — biomes from moisture and stone, groves and rock groups composed by recipe, copper to mine, a home clearing and a road kept open.",+ "tag": "3D",+ "version": "0.1.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 1480,+ "height": 920+ },+ "spineVersion": "none",+ "features": {+ "rendering": {+ "colorSpace": "linear",+ "outputTransform": "neutral"+ }+ }+}diff --git a/examples/worldgen/src/main.ts b/examples/worldgen/src/main.tsnew file mode 100644index 000000000..4ca0bb0dc--- /dev/null+++ b/examples/worldgen/src/main.ts@@ -0,0 +1,139 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+// The rules the scene's WorldGen names, as a game's would be; mining and building are changes the world keeps.+import { addPlugin, defineSystem, GetWorld, Res, Query, Mut, Input, Time, Transform, Camera, Text, Name, BakesRes,+ spawnUIEntity, UIPositionType, px, type Entity } from 'esengine';+import { registerWorldRules, WorldGenRes, type WorldRules } from 'esengine/worldgen';++const PINE = 'assets/models/pine.esmesh', ROCK = 'assets/models/rock.esmesh';++/**+ * Three biomes by the fields (moisture, rock, how steep), each with its recipes: groves of pines with saplings round a tall one in+ * the forest, a scatter of single pines on the meadow's edge, rock groups where the stone comes up, and copper to mine near rock.+ */+const rules: WorldRules = {+ id: 'worldgen-demo:wilds',+ versions: [1],+ biomes: [+ { id: 'forest', conditions: [{ field: 'moisture', min: 0.52, blend: 0.08 }, { field: 'up', min: 0.82, blend: 0.05 }],+ transition: 120, paint: [0.55, 0.45, 0, 0], paintStrength: 0.5,+ recipes: [{ recipe: 'grove', layer: 'groups', density: 0.75 }, { recipe: 'lone pine', layer: 'detail', density: 0.25 }] },+ { id: 'meadow', conditions: [{ field: 'moisture', max: 0.52, blend: 0.08 }, { field: 'rock', max: 0.58, blend: 0.06 }],+ transition: 120, paint: [1, 0, 0, 0], paintStrength: 0.45,+ recipes: [{ recipe: 'lone pine', layer: 'detail', density: 0.04 }, { recipe: 'stones', layer: 'detail', density: 0.03 }] },+ { id: 'rocky', conditions: [{ field: 'rock', min: 0.58, blend: 0.06 }, { field: 'moisture', max: 0.52, blend: 0.08 }],+ transition: 80, paint: [0.15, 0.35, 0, 0.5], paintStrength: 0.6,+ recipes: [{ recipe: 'outcrop', layer: 'groups', density: 0.6 }, { recipe: 'copper', layer: 'resources', density: 0.5 }] },+ ],+ recipes: [+ { id: 'grove', version: 1, tags: ['tree'],+ anchor: { id: 'elder', mesh: PINE, material: 'assets/materials/pine.esmaterial', scale: [1.4, 1.8], footprint: 10, canopy: 35, minUp: 0.82 },+ members: [+ { id: 'pine', mesh: PINE, material: 'assets/materials/pine.esmaterial', count: [3, 6], ring: [45, 110], scale: [0.9, 1.3], footprint: 8, canopy: 25, minUp: 0.8 },+ { id: 'sapling', mesh: PINE, material: 'assets/materials/pine.esmaterial', count: [2, 5], ring: [110, 170], scale: [0.35, 0.6], footprint: 4, minUp: 0.8, chance: 0.8 },+ { id: 'stone', mesh: ROCK, material: 'assets/materials/stone.esmaterial', count: [0, 2], ring: [20, 60], scale: [0.8, 1.6], footprint: 6, tags: ['rock'] },+ ] },+ { id: 'lone pine', version: 1, tags: ['tree'],+ anchor: { id: 'pine', mesh: PINE, material: 'assets/materials/pine.esmaterial', scale: [0.8, 1.4], footprint: 8, minUp: 0.8 } },+ { id: 'outcrop', version: 1, tags: ['rock'],+ anchor: { id: 'boulder', mesh: ROCK, material: 'assets/materials/stone.esmaterial', scale: [4, 6.5], footprint: 26, attach: 'align' },+ members: [+ { id: 'rock', mesh: ROCK, material: 'assets/materials/stone.esmaterial', count: [2, 4], ring: [32, 60], scale: [1.6, 3], footprint: 12, attach: 'align' },+ { id: 'scree', mesh: ROCK, material: 'assets/materials/stone.esmaterial', count: [4, 9], ring: [50, 95], scale: [0.4, 0.9], footprint: 4, attach: 'align' },+ ] },+ { id: 'stones', version: 1, tags: ['rock'],+ anchor: { id: 'stone', mesh: ROCK, material: 'assets/materials/stone.esmaterial', scale: [0.6, 1.4], footprint: 6, attach: 'align' } },+ { id: 'copper', version: 1, tags: ['ore'],+ anchor: { id: 'vein', mesh: ROCK, material: 'assets/materials/copper.esmaterial', interactive: 'copper', scale: [1.2, 1.8], footprint: 10, attach: 'align' } },+ ],+ layers: [+ { id: 'groups', spacing: 260, drawDistance: 4200, chunkSize: 512 },+ { id: 'resources', spacing: 220, drawDistance: 2400, chunkSize: 512 },+ { id: 'detail', spacing: 90, drawDistance: 2400, chunkSize: 384 },+ ],+};+registerWorldRules(rules);++const KEYS = [+ 'W A S D walk Q E turn',+ 'M mine the nearest copper',+ 'B build a house in front of you (keeps the wild out of it)',+];++addPlugin({+ name: 'worldgen-showcase',+ build(app) {+ let hud: Entity | null = null;+ let status: Entity | null = null;+ let notice = '';+ let noticeUntil = 0;+ let built = 0;+ const say = (text: string, now: number): void => { notice = text; noticeUntil = now + 3; };++ app.addSystem(defineSystem([GetWorld(), Res(Input), Res(Time), Query(Mut(Transform), Camera)], (world, input, time, cameras) => {+ const now = time.elapsed;+ if (hud === null) {+ const canvas = world.findEntityByName('Canvas');+ if (canvas !== null) {+ const panel = { position: UIPositionType.Absolute, insetLeft: px(20), insetTop: px(18), width: px(470), pointerEvents: 0 };+ hud = spawnUIEntity({ world, parent: canvas, node: { ...panel, height: px(80) },+ visual: { color: { r: 0.02, g: 0.05, b: 0.08, a: 0.55 } },+ text: { content: `GENERATED WORLD\n${KEYS.join('\n')}`, fontSize: 13, color: { r: 0.9, g: 0.94, b: 0.97, a: 1 }, align: 0 } });+ world.insert(hud, Name, { value: 'Keys' });+ status = spawnUIEntity({ world, parent: canvas, node: { ...panel, insetTop: px(104), height: px(64) },+ visual: { color: { r: 0.02, g: 0.05, b: 0.08, a: 0.55 } },+ text: { content: '', fontSize: 13, color: { r: 0.62, g: 0.86, b: 0.95, a: 1 }, align: 0 } });+ world.insert(status, Name, { value: 'Status' });+ }+ }+ const gens = app.hasResource(WorldGenRes) ? app.getResource(WorldGenRes) : null;+ const plan = gens?.plan() ?? null;+ const eye = [...cameras][0]?.[1] ?? null;+ if (!eye) return;++ // Walking: along the ground plane, the camera's height following the ground under it.+ const q = eye.rotation;+ let yaw = Math.atan2(2 * (q.w * q.y + q.x * q.z), 1 - 2 * (q.y * q.y + q.x * q.x));+ const pitch = -0.2;+ const turn = (input.isKeyDown('KeyE') ? -1 : 0) + (input.isKeyDown('KeyQ') ? 1 : 0);+ yaw += turn * time.delta * 0.9;+ const fx = -Math.sin(yaw), fz = -Math.cos(yaw);+ const walk = (input.isKeyDown('KeyW') ? 1 : 0) - (input.isKeyDown('KeyS') ? 1 : 0);+ const side = (input.isKeyDown('KeyD') ? 1 : 0) - (input.isKeyDown('KeyA') ? 1 : 0);+ const speed = 420 * time.delta;+ const x = eye.position.x + (fx * walk - fz * side) * speed, z = eye.position.z + (fz * walk + fx * side) * speed;+ const ground = plan?.env.sample(x, z).height;+ const y = Number.isFinite(ground) ? ground! + 180 : eye.position.y;+ if (walk || side || turn) {+ const cy = Math.cos(yaw / 2), sy = Math.sin(yaw / 2), cp = Math.cos(pitch / 2), sp = Math.sin(pitch / 2);+ eye.position = { x, y: eye.position.y + (y - eye.position.y) * Math.min(1, time.delta * 4), z };+ eye.rotation = { x: cy * sp, y: sy * cp, z: -sy * sp, w: cy * cp };+ }++ if (gens && plan && input.isKeyPressed('KeyM')) {+ // The nearest copper within reach; mining it is a change to the world, kept by its placement id.+ const reach = 600;+ const near = plan.placementsIn(x - reach, z - reach, x + reach, z + reach, ['resources'])+ .filter((p) => p.interactive === 'copper' && !gens.diffs().isRemoved(p.id))+ .sort((a, b) => Math.hypot(a.x - x, a.z - z) - Math.hypot(b.x - x, b.z - z))[0];+ if (near) { gens.diffs().remove(near.id); say(`Mined ${near.id}`, now); } else say('No copper within reach', now);+ }+ if (gens && input.isKeyPressed('KeyB')) {+ const at = { x: x + fx * 260, z: z + fz * 260 };+ gens.zones().set({ id: `house ${++built}`, kind: 'building', shape: { type: 'rect', x: at.x, z: at.z, halfX: 40, halfZ: 30, yaw },+ falloff: 12, priority: 20, excludes: ['*'] });+ say(`House ${built} built: the wild is kept out of its ground`, now);+ }++ if (status !== null && plan) {+ const biome = plan.biomeAt(x, z) ?? '—';+ const bakes = app.hasResource(BakesRes) ? app.getResource(BakesRes).active : [];+ const making = bakes.length ? `\n${bakes.map((b) => `${b.label} ${Math.round(b.progress * 100)}%`).join(' ')}` : '';+ const line = now < noticeUntil ? `\n${notice}` : '';+ const content = `Biome: ${biome} Mined: ${gens!.diffs().toJSON().removed.length} Houses: ${built}${making}${line}`;+ const text = world.get(status, Text);+ if (text.content !== content) world.insert(status, Text, { ...text, content });+ }+ }, { name: 'WorldGenShowcase' }));+ },+});diff --git a/examples/worldgen/tools/build.mjs b/examples/worldgen/tools/build.mjsnew file mode 100644index 000000000..e0d701087--- /dev/null+++ b/examples/worldgen/tools/build.mjs@@ -0,0 +1,216 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file build.mjs — writes the Generated World project's assets and scene.+ *+ * The ground textures, the pine and its colour strip are the Wilds example's (made there from numbers); the rock is made here. The+ * world itself is not in the scene: the scene names the rules (src/main.ts) and the zones, and the engine lays the world out from them+ * as the camera goes. Run it after changing a number:+ *+ * node examples/worldgen/tools/build.mjs+ *+ * It needs the SDK built (`node build-tools/cli.js sdk`), for the mesh format and the terrain's own noise.+ */+import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs';+import { randomUUID } from 'node:crypto';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const PROJECT = path.resolve(HERE, '..');+const WILDS = path.resolve(PROJECT, '../wilds');+const { MeshChannel, MeshChannelType, packChannels, encodeMesh, NoiseSource } =+ await import(new URL('../../../sdk/dist/index.node.js', import.meta.url).href);++/** The ground, in one table: the scene's units are the Wilds', a pine about ninety of them tall. */+const GROUND = {+ seed: 4, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.3, warp: 0.35, erosion: 1, sizeX: 4200, height: 520,+ rockSlope: 0.34, dirtHeight: 0.55, snowHeight: 0.86,+};++function write(rel, data) {+ const file = path.join(PROJECT, rel);+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(file, data);+}++/** The `.meta` an asset carries once the editor has seen it: a stable name for the file. */+function meta(rel, type, importer = {}) {+ write(`${rel}.meta`, `${JSON.stringify({ uuid: randomUUID(), version: '2.0', type, importer }, null, 2)}\n`);+}++/** One of the Wilds' assets, with its import settings. */+function borrow(rel) {+ mkdirSync(path.dirname(path.join(PROJECT, rel)), { recursive: true });+ copyFileSync(path.join(WILDS, rel), path.join(PROJECT, rel));+ copyFileSync(path.join(WILDS, `${rel}.meta`), path.join(PROJECT, `${rel}.meta`));+}++/** Positions, uvs and normals as an .esmesh, its colour white. */+function mesh(rel, pos, uv, nrm, idx) {+ const { channels, vertexStride } = packChannels([+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },+ ]);+ const count = pos.length / 3;+ const vertices = new Uint8Array(count * vertexStride);+ const view = new DataView(vertices.buffer);+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];+ for (let i = 0; i < count; i++) {+ const at = i * vertexStride;+ for (let k = 0; k < 3; k++) {+ view.setFloat32(at + channels[0].offset + k * 4, pos[i * 3 + k], true);+ view.setFloat32(at + channels[3].offset + k * 4, nrm[i * 3 + k], true);+ min[k] = Math.min(min[k], pos[i * 3 + k]);+ max[k] = Math.max(max[k], pos[i * 3 + k]);+ }+ view.setFloat32(at + channels[1].offset, uv[i * 2], true);+ view.setFloat32(at + channels[1].offset + 4, uv[i * 2 + 1], true);+ view.setUint32(at + channels[2].offset, 0xffffffff, true);+ }+ write(rel, Buffer.from(encodeMesh({ channels, vertexStride, vertexCount: count, vertices, indices: new Uint32Array(idx), aabbMin: min, aabbMax: max })));+ meta(rel, 'mesh');+}++/** A rock: a sphere of faceted, flat-shaded faces pushed in and out, squat, about ten units across, its foot a little below the ground. */+function rock() {+ const STACKS = 6, SLICES = 9;+ const bump = (i, j) => 0.75 + 0.5 * (((Math.sin(i * 12.9898 + j * 78.233) * 43758.5453) % 1 + 1) % 1);+ const point = (i, j) => {+ const v = i / STACKS, a = ((j % SLICES) / SLICES) * Math.PI * 2, phi = v * Math.PI;+ const r = 5 * (i === 0 || i === STACKS ? 1 : bump(i, j % SLICES));+ return [Math.sin(phi) * Math.cos(a) * r, Math.cos(phi) * r * 0.62 + 1.2, Math.sin(phi) * Math.sin(a) * r];+ };+ const pos = [], uv = [], nrm = [], idx = [];+ const face = (a, b, c) => {+ const u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], w = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];+ const n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]];+ const len = Math.hypot(...n) || 1;+ for (const p of [a, b, c]) {+ pos.push(...p);+ uv.push(0.5, Math.min(Math.max((p[1] + 2) / 6, 0), 1));+ nrm.push(n[0] / len, n[1] / len, n[2] / len);+ idx.push(pos.length / 3 - 1);+ }+ };+ for (let i = 0; i < STACKS; i++) for (let j = 0; j < SLICES; j++) {+ const a = point(i, j), b = point(i, j + 1), c = point(i + 1, j), d = point(i + 1, j + 1);+ // Outward from above: down the stack, then round.+ face(a, b, c);+ face(b, d, c);+ }+ mesh('assets/models/rock.esmesh', pos, uv, nrm, idx);+}++function material(name, shader, properties) {+ write(`assets/materials/${name}.esmaterial`, `${JSON.stringify({ version: '1.0', type: 'material', shader, blendMode: 0, depthTest: true, depthWrite: true, cull: 0, properties }, null, 2)}\n`);+ meta(`assets/materials/${name}.esmaterial`, 'material');+}++function materials() {+ material('terrain', 'builtin:terrain', {+ u_layer0: 'assets/textures/grass.png', u_layer1: 'assets/textures/dirt.png', u_layer2: 'assets/textures/snow.png', u_layer3: 'assets/textures/rock.png',+ u_tint0: { r: 1, g: 1, b: 1, a: 1 }, u_tint1: { r: 1, g: 1, b: 1, a: 1 }, u_tint2: { r: 1, g: 1, b: 1, a: 1 }, u_tint3: { r: 1, g: 1, b: 1, a: 1 },+ u_tile0: 60, u_tile1: 70, u_tile2: 90, u_tile3: 120, u_macroVariation: 0.5, u_sharpness: 2.2, u_roughness: 0.93,+ });+ material('grass', 'builtin:foliage', {+ u_baseColor: { r: 0.1, g: 0.22, b: 0.05, a: 1 }, u_tipColor: { r: 0.5, g: 0.66, b: 0.2, a: 1 },+ u_windStrength: 3, u_windSpeed: 1.3, u_windDirection: 30, u_gustScale: 0.012, u_flutter: 0.35, u_translucency: 0.5,+ });+ material('pine', 'builtin:foliage', {+ u_albedo: 'assets/textures/pine.png', u_useTexture: 1, u_baseColor: { r: 1, g: 1, b: 1, a: 1 }, u_tipColor: { r: 1, g: 1, b: 1, a: 1 },+ u_windStrength: 0.9, u_windSpeed: 0.9, u_windDirection: 30, u_gustScale: 0.006, u_flutter: 0.1, u_translucency: 0.15, u_roughness: 0.9,+ });+ // Stone and ore stand still: the Foliage shader with no wind, its colour from the foot of the rock to its top.+ material('stone', 'builtin:foliage', {+ u_baseColor: { r: 0.26, g: 0.25, b: 0.23, a: 1 }, u_tipColor: { r: 0.52, g: 0.5, b: 0.46, a: 1 },+ u_windStrength: 0, u_flutter: 0, u_translucency: 0, u_roughness: 0.95,+ });+ material('copper', 'builtin:foliage', {+ u_baseColor: { r: 0.32, g: 0.16, b: 0.08, a: 1 }, u_tipColor: { r: 0.85, g: 0.48, b: 0.22, a: 1 },+ u_windStrength: 0, u_flutter: 0, u_translucency: 0, u_roughness: 0.55,+ });+}++function scene() {+ const ground = new NoiseSource(GROUND);+ const home = { x: 0, z: 0 };+ const eye = { x: home.x + 40, z: home.z + 620 };+ const eyeY = ground.height(eye.x, eye.z) + 180;+ const pitch = -0.2;+ const entity = (id, name, components) => ({ id, name, parent: null, children: [], visible: true, components });+ const white = { r: 1, g: 1, b: 1, a: 1 };+ const post = [+ { type: 'skyAtmosphere', enabled: true, uniforms: { u_intensity: 1.05, u_haze: 1.1, u_sunBrightness: 40, u_clouds: 0.45, u_cloudShadow: 0.6, u_unitsPerKm: 1000, u_windSpeed: 0.03 } },+ { type: 'gtao', enabled: true, uniforms: { u_radius: 60, u_intensity: 1 } },+ { type: 'heightFog', enabled: true, colors: { u_fogColor: { r: 0.62, g: 0.72, b: 0.84, a: 1 }, u_sunColor: { r: 1, g: 0.86, b: 0.62, a: 1 } },+ uniforms: { u_density: 0.0001, u_heightFalloff: 0.0012, u_baseHeight: 0, u_inscatter: 0.6, u_skyFog: 0.5, u_volumetric: 0.4, u_volumeRange: 4000 } },+ { type: 'taa', enabled: true, uniforms: { u_blend: 0.1 } },+ { type: 'autoExposure', enabled: true, uniforms: { u_bias: -0.1, u_minEV: -2, u_maxEV: 2 } },+ { type: 'colorGrade', enabled: true, uniforms: { u_contrast: 1.06, u_saturation: 1.1 } },+ { type: 'fxaa', enabled: true, uniforms: { u_intensity: 1 } },+ ];+ const entities = [+ entity(0, 'Camera', [+ // WORLDGEN_TOP=1 looks straight down on the home from high up, to see how the world is laid out.+ { type: 'Transform', data: process.env.WORLDGEN_TOP+ ? { position: { x: home.x, y: 2600, z: home.z }, rotation: { x: -0.7071, y: 0, z: 0, w: 0.7071 } }+ : { position: { x: eye.x, y: eyeY, z: eye.z }, rotation: { x: Math.sin(pitch / 2), y: 0, z: 0, w: Math.cos(pitch / 2) } } },+ { type: 'Camera', data: { projectionType: 0, fov: 55, nearPlane: 2, farPlane: 20000, isActive: true, priority: 0 } },+ { type: 'PostProcessVolume', data: { isGlobal: true, priority: 0, weight: 1, effects: post } },+ ]),+ entity(1, 'Clock', [+ { type: 'Transform', data: {} },+ { type: 'TimeOfDay', data: { hour: 15.5, daySeconds: 0, latitude: 45, declination: 15, north: 0, drive: 31 } },+ ]),+ entity(2, 'Sun', [+ { type: 'Transform', data: {} },+ { type: 'Light', data: { type: 1, color: white, intensity: 3, enabled: true, meshShadows: true, shadowExtent: 2500, shadowStrength: 1, sourceAngle: 0.5 } },+ ]),+ entity(3, 'Sky', [+ { type: 'Transform', data: {} },+ { type: 'Light', data: { type: 2, color: { r: 0.8, g: 0.88, b: 1, a: 1 }, intensity: 0.55, enabled: true } },+ ]),+ entity(4, 'Ground', [+ { type: 'Transform', data: {} },+ { type: 'Terrain', data: {+ extent: 1, provider: 'estella:noise', world: 'demo', generatorVersion: 1, ...GROUND, cellSize: 4, detail: 1.4, drawDistance: 9000,+ material: 'assets/materials/terrain.esmaterial' } },+ ]),+ entity(5, 'World', [+ { type: 'Transform', data: {} },+ { type: 'WorldGen', data: { rules: 'worldgen-demo:wilds', version: 1, world: 'demo', seed: 7, paintGround: true } },+ ]),+ // The home: a clearing kept free of everything, held to meadow, its edge thinning out over sixty units.+ entity(6, 'Home', [+ { type: 'Transform', data: { position: { x: home.x, y: 0, z: home.z } } },+ { type: 'WorldZone', data: { kind: 'home', shape: 0, radius: 130, falloff: 70, priority: 10, excludes: '*', biome: 'meadow' } },+ ]),+ // The road out of it: kept free of trees and rocks, so the ground and the grass run on along it.+ entity(7, 'Road', [+ { type: 'Transform', data: { position: { x: home.x + 520, y: 0, z: home.z - 40 }, rotation: { x: 0, y: Math.sin(0.15), z: 0, w: Math.cos(0.15) } } },+ { type: 'WorldZone', data: { kind: 'road', shape: 1, sizeX: 900, sizeZ: 36, falloff: 24, priority: 5, excludes: 'tree,rock', biome: '' } },+ ]),+ entity(9, 'Canvas', [+ { type: 'Transform', data: {} },+ { type: 'Canvas', data: { designResolution: { x: 1480, y: 920 }, scaleMode: 2 } },+ { type: 'UINode', data: {} },+ ]),+ entity(8, 'Meadow', [+ { type: 'Transform', data: { position: { x: eye.x, y: 0, z: eye.z - 300 } } },+ { type: 'Foliage', data: {+ material: 'assets/materials/grass.esmaterial', sizeX: 700, sizeZ: 700, cellSize: 35, count: 1300, seed: 3, minScale: 0.7, maxScale: 1.3, minUp: 0.8,+ heightMin: -1000, heightMax: 1000, bladeHeight: 40, bladeWidth: 4, lodDistance: 180, drawDistance: 520 } },+ ]),+ ];+ write('assets/scenes/main.esscene', `${JSON.stringify({ version: 4, name: 'Generated World', entities }, null, 1)}\n`);+ meta('assets/scenes/main.esscene', 'scene');+}++for (const name of ['grass', 'dirt', 'snow', 'rock', 'pine']) borrow(`assets/textures/${name}.png`);+borrow('assets/models/pine.esmesh');+rock();+materials();+scene();diff --git a/examples/worldgen/tsconfig.json b/examples/worldgen/tsconfig.jsonnew file mode 100644index 000000000..65be65e96--- /dev/null+++ b/examples/worldgen/tsconfig.json@@ -0,0 +1,112 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "paths": {+ "esengine": [+ "./.esengine/sdk/index.d.ts"+ ],+ "esengine/spine": [+ "./.esengine/sdk/spine/index.d.ts"+ ],+ "esengine/tilemap": [+ "./.esengine/sdk/tilemap/index.d.ts"+ ],+ "esengine/terrain": [+ "./.esengine/sdk/terrain/index.d.ts"+ ],+ "esengine/timeline": [+ "./.esengine/sdk/timeline/index.d.ts"+ ],+ "esengine/fx-basic": [+ "./.esengine/sdk/fx-basic/index.d.ts"+ ],+ "esengine/fx-atmosphere": [+ "./.esengine/sdk/fx-atmosphere/index.d.ts"+ ],+ "esengine/fx-lighting": [+ "./.esengine/sdk/fx-lighting/index.d.ts"+ ],+ "esengine/foliage": [+ "./.esengine/sdk/foliage/index.d.ts"+ ],+ "esengine/spline": [+ "./.esengine/sdk/spline/index.d.ts"+ ],+ "esengine/character-shaders": [+ "./.esengine/sdk/character-shaders/index.d.ts"+ ],+ "esengine/logic": [+ "./.esengine/sdk/logic/index.d.ts"+ ],+ "esengine/debug-channel": [+ "./.esengine/sdk/debug-channel/index.d.ts"+ ],+ "esengine/ai": [+ "./.esengine/sdk/ai/index.d.ts"+ ],+ "esengine/replication": [+ "./.esengine/sdk/net/replication/index.d.ts"+ ],+ "esengine/gameplay": [+ "./.esengine/sdk/gameplay/index.d.ts"+ ],+ "esengine/dragonbones": [+ "./.esengine/sdk/dragonbones/index.d.ts"+ ],+ "esengine/physics": [+ "./.esengine/sdk/physics/index.d.ts"+ ],+ "esengine/physics3d": [+ "./.esengine/sdk/physics3d/index.d.ts"+ ],+ "esengine/douyin": [+ "./.esengine/sdk/douyin/index.d.ts"+ ],+ "esengine/kuaishou": [+ "./.esengine/sdk/kuaishou/index.d.ts"+ ],+ "esengine/bilibili": [+ "./.esengine/sdk/bilibili/index.d.ts"+ ],+ "esengine/quickgame": [+ "./.esengine/sdk/quickgame/index.d.ts"+ ],+ "esengine/alipay": [+ "./.esengine/sdk/alipay/index.d.ts"+ ],+ "esengine/huawei": [+ "./.esengine/sdk/huawei/index.d.ts"+ ],+ "esengine/openpaas": [+ "./.esengine/sdk/openpaas/index.d.ts"+ ],+ "estella-plugin-*": [+ "./.esengine/packages/*"+ ],+ "esengine/wasm": [+ "./.esengine/sdk/wasm.d.ts"+ ],+ "esengine/water": [+ "./.esengine/sdk/water/index.d.ts"+ ],+ "esengine/worldgen": [+ "./.esengine/sdk/worldgen/index.d.ts"+ ]+ }+ },+ "include": [+ "src/**/*"+ ],+ "exclude": [+ "node_modules"+ ]+}diff --git a/pipeline/src/bundle/engineSubpaths.ts b/pipeline/src/bundle/engineSubpaths.tsindex 9ae85b0c7..69cb1615a 100644--- a/pipeline/src/bundle/engineSubpaths.ts+++ b/pipeline/src/bundle/engineSubpaths.ts@@ -18,6 +18,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {'esengine/fx-atmosphere': 'fx-atmosphere/index.js','esengine/fx-lighting': 'fx-lighting/index.js','esengine/foliage': 'foliage/index.js',+ 'esengine/worldgen': 'worldgen/index.js','esengine/water': 'water/index.js','esengine/spline': 'spline/index.js','esengine/character-shaders': 'character-shaders/index.js',diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.tsindex 86cfc2198..335329636 100644--- a/pipeline/src/project/targetSupport.ts+++ b/pipeline/src/project/targetSupport.ts@@ -27,7 +27,7 @@ import { NATIVE_PLATFORMS, type ExportPlatform } from './platforms';/** An engine subsystem a build target may lack. */export type Subsystem =- | 'text' | 'tilemap' | 'terrain' | 'foliage' | 'water' | 'spline' | 'characterShaders' | 'timeline' | 'fxBasic' | 'fxAtmosphere' | 'fxLighting' | 'particles' | 'postprocess' | 'physics' | 'physics3d'+ | 'text' | 'tilemap' | 'terrain' | 'foliage' | 'worldgen' | 'water' | 'spline' | 'characterShaders' | 'timeline' | 'fxBasic' | 'fxAtmosphere' | 'fxLighting' | 'particles' | 'postprocess' | 'physics' | 'physics3d'| 'spine' | 'dragonbones' | 'video' | 'ai' | 'logic' | 'replication' | 'gameplay';/**@@ -46,6 +46,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>fxAtmosphere: ['Weather', 'TimeOfDay'],fxLighting: [],foliage: ['Foliage'],+ worldgen: ['WorldGen', 'WorldZone'],water: ['WaterBody', 'WaterZone', 'Floating'],spline: ['Spline'],// Hair, Skin and Eye are shaders, not components: a character's materials are what name them (see SHADER_SUBSYSTEM).@@ -111,6 +112,7 @@ export const SUBSYSTEM_LABEL: Readonly<Record<Subsystem, string>> = {fxAtmosphere: 'Post-process effects (sky, fog, rain)',fxLighting: 'Post-process effects (occlusion, reflections, exposure)',foliage: 'Foliage',+ worldgen: 'Generated worlds (biomes, zones, placement)',water: 'Water',spline: 'Splines',characterShaders: 'Character shaders (hair, skin, eye)',@@ -144,6 +146,7 @@ export const SUBSYSTEM_INSTALL: Readonly<Record<Subsystem, string>> = {fxAtmosphere: 'esengine/fx-atmosphere',fxLighting: 'esengine/fx-lighting',foliage: 'esengine/foliage',+ worldgen: 'esengine/worldgen',water: 'esengine/water',spline: 'esengine/spline',characterShaders: 'esengine/character-shaders',diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex ac714ebef..4e6272b82 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1794 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1825 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1625,6 +1625,32 @@ p2y: number| { kind: 'virtual'; id: string }```+## BiomeCondition — interface @experimental+```+blend: number | undefined+field: string+max: number | undefined+min: number | undefined+```++## BiomeDef — interface @experimental+```+conditions: readonly BiomeCondition[]+id: string+paint: readonly [number, number, number, number] | undefined+paintStrength: number | undefined+recipes: readonly BiomeRecipe[]+transition: number | undefined+weight: number | undefined+```++## BiomeRecipe — interface @experimental+```+density: number+layer: string+recipe: string+```+## BitmapText — const @experimental```BuiltinComponentDef<BitmapTextData>@@ -4589,6 +4615,18 @@ static prototype: GridLayoutProvider(x: number, z: number) => { y: number; up: number } | null```+## Group — interface @experimental+```+anchor: Placement+id: string+layer: string+members: Placement[]+priority: number+radius: number+x: number+z: number+```+## HdrFormat — interface @experimental```effective: string@@ -6492,6 +6530,82 @@ LayoutWorld & Pick<World, 'getAllEntities'>Pick<World, 'getCppRegistry' | 'getWasmModule'>```+## PlacedObject — const @experimental+```+ComponentDef<PlacedObjectData>+```++## PlacedObjectData — interface @experimental+```+id: string+kind: string+```++## Placement — interface @experimental+```+attach: "upright" | "align"+biome: string+canopy: number+footprint: number+group: string+id: string+interactive: string | null+layer: string+material: number+member: string+mesh: number+normal: [number, number, number]+recipe: string+recipeVersion: number+scale: number+x: number+y: number+yaw: number+z: number+zone: string | null+```++## PlacementChange — interface @experimental+```+scale: number | undefined+x: number | undefined+y: number | undefined+yaw: number | undefined+z: number | undefined+```++## PlacementDiffs — class @experimental+```+change: (id: string, change: PlacementChange) => void+changeOf: (id: string) => PlacementChange | undefined+isRemoved: (id: string) => boolean+load: (data: PlacementDiffsData) => void+onChange: ((id: string) => void) | null+remove: (id: string) => void+restore: (id: string) => void+revision: number+toJSON: () => PlacementDiffsData+static new (): PlacementDiffs+static prototype: PlacementDiffs+```++## PlacementDiffsData — interface @experimental+```+changed: Record<string, PlacementChange>+removed: string[]+version: 1+```++## PlacementLayer — interface @experimental+```+chunkSize: number | undefined+drawDistance: number+id: string+occupies: boolean | undefined+spacing: number+version: number | undefined+```+## PlanarReflection — const @experimental```BuiltinComponentDef<PlanarReflectionData>@@ -7141,6 +7255,7 @@ pending: PendingSystemEntry[]@internal sources_: () => ChunkSource[]clear: () => voidhas: (id: string) => boolean+invalidate: (id: string, x0: number, z0: number, x1: number, z1: number) => voidpending: numberremove: (id: string) => voidset: <T>(id: string, def: ChunkLayer<T>) => void@@ -7489,6 +7604,34 @@ get: () => Tsubscribe: (fn: (value: T) => void) => () => void```+## Recipe — interface @experimental+```+anchor: RecipeMember+id: string+members: readonly RecipeMember[] | undefined+tags: readonly string[] | undefined+version: number+```++## RecipeMember — interface @experimental+```+arc: readonly [number, number] | undefined+attach: "upright" | "align" | undefined+canopy: number | undefined+chance: number | undefined+count: readonly [number, number] | undefined+footprint: number+id: string+interactive: string | undefined+material: string | number | undefined+mesh: string | number+minUp: number | undefined+ring: readonly [number, number] | undefined+scale: readonly [number, number] | undefined+tags: readonly string[] | undefined+waterDepth: number | undefined+```+## ReflectionAxis — enum @experimental```X = 0@@ -7522,6 +7665,11 @@ FixedRate = 1OnDemand = 2```+## Rejection — type @experimental+```+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+```+## ReliableOrderedTransport — interface @experimental```delivery: "reliable-ordered"@@ -9901,12 +10049,16 @@ static prototype: TerrainUnavailable```@internal app_: App | null@internal built_: Map<number, Built>+@internal paint_: Repaint | null@internal revision_: numbercollisionReadyAt: (x: number, z: number) => boolean+groundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | nullpending: number+repaint: () => void+setPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrainsstatic prototype: Terrains@@ -11911,6 +12063,55 @@ x: numberz: number```+## WorldGen — const @experimental+```+ComponentDef<WorldGenData>+```++## WorldGenData — interface @experimental+```+paintGround: boolean+rules: string+seed: number+version: number+world: string+```++## WorldGenPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): WorldGenPlugin+static prototype: WorldGenPlugin+```++## WorldGenRes — const @experimental+```+ResourceDef<WorldGens>+```++## WorldGenStatus — interface @experimental+```+layers: Record<string, ChunkLayerStatus>+reason: string | undefined+state: "failed" | "ready" | "loading"+```++## WorldGens — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, BuiltWorld>+@internal objects_: Map<string, number>+diffs: (world?: string) => PlacementDiffs+objectOf: (id: string) => Entity | null+plan: (entity?: Entity) => WorldPlan | null+status: (entity: Entity) => WorldGenStatus | null+zones: (world?: string) => Zones+static new (): WorldGens+static prototype: WorldGens+```+## WorldManifest — interface @experimental```cellSize: number@@ -11935,6 +12136,27 @@ warnings: string[]ComponentDef<{}>```+## WorldPlan — class @experimental+```+biomeAt: (x: number, z: number) => string | null+biomeWeights: (x: number, z: number) => { biome: string; weight: number; }[]+env: Environment+explain: (x: number, z: number) => { fields: FieldValues; biomes: { biome: string; weight: number; }[]; zones: { id: string; kind: string; weight: number; }[]; layers: { layer: string; cell: [number, number]; group: string | null; rejected: Rejection | null; detail?: string; }[]; }+group: (li: number, gx: number, gz: number) => Group | Rejection+groupsIn: (layer: string, x0: number, z0: number, x1: number, z1: number) => Group[]+invalidate: () => void+layerIndex: (id: string) => number+paint: (x: number, z: number, base: readonly [number, number, number, number]) => [number, number, number, number]+placementsIn: (x0: number, z0: number, x1: number, z1: number, layers?: readonly string[]) => Placement[]+rules: WorldRules+seed: number+stats: (layer: string, x0: number, z0: number, x1: number, z1: number) => Record<"placed" | Rejection, number>+world: string+zones: Zones+static new (rules: WorldRules, env: Environment, zones: Zones, seed: number, world: string): WorldPlan+static prototype: WorldPlan+```+## WorldRay — interface @experimental```dir: Vec3@@ -11983,6 +12205,17 @@ unloadCount: numberunloadingCells: string[]```+## WorldRules — interface @experimental+```+biomes: readonly BiomeDef[]+fields: Record<string, FieldFn> | undefined+id: string+layers: readonly PlacementLayer[]+noise: Partial<Record<string, NoiseField>> | undefined+recipes: readonly Recipe[]+versions: readonly number[]+```+## WorldSnapshot — interface @experimental```selected: SnapshotEntity | null@@ -12071,11 +12304,66 @@ BuiltinComponentDef<TransformData>TransformData```+## WorldZone — const @experimental+```+ComponentDef<WorldZoneData>+```++## WorldZoneData — interface @experimental+```+biome: string+excludes: string+falloff: number+kind: string+priority: number+radius: number+shape: number+sizeX: number+sizeZ: number+```+## WrapMode — type @experimental```(typeof WrapMode)[keyof typeof WrapMode]```+## ZoneDef — interface @experimental+```+biome: string | undefined+excludes: readonly string[]+falloff: number+fields: Readonly<Record<string, number>> | undefined+id: string+kind: string+priority: number+shape: ZoneShape+```++## ZoneShape — type @experimental+```+| { type: 'circle'; x: number; z: number; radius: number }+ | { type: 'rect'; x: number; z: number; halfX: number; halfZ: number; yaw?: number }+```++## ZoneShapeKind — const @experimental+```+{ readonly Circle: 0; readonly Box: 1; }+```++## Zones — class @experimental+```+all: () => IterableIterator<ZoneDef>+at: (x: number, z: number, reach?: number) => { zone: ZoneDef; weight: number; }[]+delete: (id: string) => void+excluding: (x: number, z: number, radius: number, tags: readonly string[], seed: number) => ZoneDef | null+get: (id: string) => ZoneDef | undefined+onChange: ((bounds: [number, number, number, number], zone: ZoneDef) => void) | null+revision: number+set: (zone: ZoneDef) => void+static new (): Zones+static prototype: Zones+```+## acquireWebGPUDevice — function @beta```(requested: RenderBackendRequest, onError?: (message: string) => void): Promise<WebGPUBootResult>@@ -13923,7 +14211,7 @@ Logger## makePage — function @experimental```-(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>+(source: TerrainSource, x0: number, z0: number, size: number, repaint?: Repaint): PageImage | Promise<PageImage>```## makeWidgetInteractable — function @experimental@@ -14586,6 +14874,11 @@ PrefabsPlugin(name: string, preset: WeatherPreset): number```+## registerWorldRules — function @experimental+```+(rules: WorldRules): void+```+## registryEntityFields — function @experimental```(): (componentType: string) => readonly string[]@@ -15606,6 +15899,11 @@ Plugin(axis: WorldAxis): Vec3```+## worldGenPlugin — const @experimental+```+Plugin+```+## worldManifestPath — function @experimental```(sceneName: string): string@@ -15626,6 +15924,11 @@ PluginSystemDef```+## worldRules — function @experimental+```+(id: string): WorldRules | undefined+```+## worldSnapshot — function @experimental```(app: App, selectedId: number | null, withTree: boolean, opts?: WorldSnapshotOptions): WorldSnapshotdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 8e2764eac..f21b598e4 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 1813 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 1844 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1625,6 +1625,32 @@ p2y: number| { kind: 'virtual'; id: string }```+## BiomeCondition — interface @experimental+```+blend: number | undefined+field: string+max: number | undefined+min: number | undefined+```++## BiomeDef — interface @experimental+```+conditions: readonly BiomeCondition[]+id: string+paint: readonly [number, number, number, number] | undefined+paintStrength: number | undefined+recipes: readonly BiomeRecipe[]+transition: number | undefined+weight: number | undefined+```++## BiomeRecipe — interface @experimental+```+density: number+layer: string+recipe: string+```+## BitmapText — const @experimental```BuiltinComponentDef<BitmapTextData>@@ -4597,6 +4623,18 @@ static prototype: GridLayoutProvider(x: number, z: number) => { y: number; up: number } | null```+## Group — interface @experimental+```+anchor: Placement+id: string+layer: string+members: Placement[]+priority: number+radius: number+x: number+z: number+```+## HdrFormat — interface @experimental```effective: string@@ -6695,6 +6733,82 @@ LayoutWorld & Pick<World, 'getAllEntities'>Pick<World, 'getCppRegistry' | 'getWasmModule'>```+## PlacedObject — const @experimental+```+ComponentDef<PlacedObjectData>+```++## PlacedObjectData — interface @experimental+```+id: string+kind: string+```++## Placement — interface @experimental+```+attach: "upright" | "align"+biome: string+canopy: number+footprint: number+group: string+id: string+interactive: string | null+layer: string+material: number+member: string+mesh: number+normal: [number, number, number]+recipe: string+recipeVersion: number+scale: number+x: number+y: number+yaw: number+z: number+zone: string | null+```++## PlacementChange — interface @experimental+```+scale: number | undefined+x: number | undefined+y: number | undefined+yaw: number | undefined+z: number | undefined+```++## PlacementDiffs — class @experimental+```+change: (id: string, change: PlacementChange) => void+changeOf: (id: string) => PlacementChange | undefined+isRemoved: (id: string) => boolean+load: (data: PlacementDiffsData) => void+onChange: ((id: string) => void) | null+remove: (id: string) => void+restore: (id: string) => void+revision: number+toJSON: () => PlacementDiffsData+static new (): PlacementDiffs+static prototype: PlacementDiffs+```++## PlacementDiffsData — interface @experimental+```+changed: Record<string, PlacementChange>+removed: string[]+version: 1+```++## PlacementLayer — interface @experimental+```+chunkSize: number | undefined+drawDistance: number+id: string+occupies: boolean | undefined+spacing: number+version: number | undefined+```+## PlanarReflection — const @experimental```BuiltinComponentDef<PlanarReflectionData>@@ -7344,6 +7458,7 @@ pending: PendingSystemEntry[]@internal sources_: () => ChunkSource[]clear: () => voidhas: (id: string) => boolean+invalidate: (id: string, x0: number, z0: number, x1: number, z1: number) => voidpending: numberremove: (id: string) => voidset: <T>(id: string, def: ChunkLayer<T>) => void@@ -7702,6 +7817,34 @@ get: () => Tsubscribe: (fn: (value: T) => void) => () => void```+## Recipe — interface @experimental+```+anchor: RecipeMember+id: string+members: readonly RecipeMember[] | undefined+tags: readonly string[] | undefined+version: number+```++## RecipeMember — interface @experimental+```+arc: readonly [number, number] | undefined+attach: "upright" | "align" | undefined+canopy: number | undefined+chance: number | undefined+count: readonly [number, number] | undefined+footprint: number+id: string+interactive: string | undefined+material: string | number | undefined+mesh: string | number+minUp: number | undefined+ring: readonly [number, number] | undefined+scale: readonly [number, number] | undefined+tags: readonly string[] | undefined+waterDepth: number | undefined+```+## ReflectionAxis — enum @experimental```X = 0@@ -7735,6 +7878,11 @@ FixedRate = 1OnDemand = 2```+## Rejection — type @experimental+```+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+```+## ReliableOrderedTransport — interface @experimental```delivery: "reliable-ordered"@@ -10114,12 +10262,16 @@ static prototype: TerrainUnavailable```@internal app_: App | null@internal built_: Map<number, Built>+@internal paint_: Repaint | null@internal revision_: numbercollisionReadyAt: (x: number, z: number) => boolean+groundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | nullpending: number+repaint: () => void+setPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrainsstatic prototype: Terrains@@ -12124,6 +12276,55 @@ x: numberz: number```+## WorldGen — const @experimental+```+ComponentDef<WorldGenData>+```++## WorldGenData — interface @experimental+```+paintGround: boolean+rules: string+seed: number+version: number+world: string+```++## WorldGenPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): WorldGenPlugin+static prototype: WorldGenPlugin+```++## WorldGenRes — const @experimental+```+ResourceDef<WorldGens>+```++## WorldGenStatus — interface @experimental+```+layers: Record<string, ChunkLayerStatus>+reason: string | undefined+state: "failed" | "ready" | "loading"+```++## WorldGens — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, BuiltWorld>+@internal objects_: Map<string, number>+diffs: (world?: string) => PlacementDiffs+objectOf: (id: string) => Entity | null+plan: (entity?: Entity) => WorldPlan | null+status: (entity: Entity) => WorldGenStatus | null+zones: (world?: string) => Zones+static new (): WorldGens+static prototype: WorldGens+```+## WorldManifest — interface @experimental```cellSize: number@@ -12148,6 +12349,27 @@ warnings: string[]ComponentDef<{}>```+## WorldPlan — class @experimental+```+biomeAt: (x: number, z: number) => string | null+biomeWeights: (x: number, z: number) => { biome: string; weight: number; }[]+env: Environment+explain: (x: number, z: number) => { fields: FieldValues; biomes: { biome: string; weight: number; }[]; zones: { id: string; kind: string; weight: number; }[]; layers: { layer: string; cell: [number, number]; group: string | null; rejected: Rejection | null; detail?: string; }[]; }+group: (li: number, gx: number, gz: number) => Group | Rejection+groupsIn: (layer: string, x0: number, z0: number, x1: number, z1: number) => Group[]+invalidate: () => void+layerIndex: (id: string) => number+paint: (x: number, z: number, base: readonly [number, number, number, number]) => [number, number, number, number]+placementsIn: (x0: number, z0: number, x1: number, z1: number, layers?: readonly string[]) => Placement[]+rules: WorldRules+seed: number+stats: (layer: string, x0: number, z0: number, x1: number, z1: number) => Record<"placed" | Rejection, number>+world: string+zones: Zones+static new (rules: WorldRules, env: Environment, zones: Zones, seed: number, world: string): WorldPlan+static prototype: WorldPlan+```+## WorldRay — interface @experimental```dir: Vec3@@ -12196,6 +12418,17 @@ unloadCount: numberunloadingCells: string[]```+## WorldRules — interface @experimental+```+biomes: readonly BiomeDef[]+fields: Record<string, FieldFn> | undefined+id: string+layers: readonly PlacementLayer[]+noise: Partial<Record<string, NoiseField>> | undefined+recipes: readonly Recipe[]+versions: readonly number[]+```+## WorldSnapshot — interface @experimental```selected: SnapshotEntity | null@@ -12284,11 +12517,66 @@ BuiltinComponentDef<TransformData>TransformData```+## WorldZone — const @experimental+```+ComponentDef<WorldZoneData>+```++## WorldZoneData — interface @experimental+```+biome: string+excludes: string+falloff: number+kind: string+priority: number+radius: number+shape: number+sizeX: number+sizeZ: number+```+## WrapMode — type @experimental```(typeof WrapMode)[keyof typeof WrapMode]```+## ZoneDef — interface @experimental+```+biome: string | undefined+excludes: readonly string[]+falloff: number+fields: Readonly<Record<string, number>> | undefined+id: string+kind: string+priority: number+shape: ZoneShape+```++## ZoneShape — type @experimental+```+| { type: 'circle'; x: number; z: number; radius: number }+ | { type: 'rect'; x: number; z: number; halfX: number; halfZ: number; yaw?: number }+```++## ZoneShapeKind — const @experimental+```+{ readonly Circle: 0; readonly Box: 1; }+```++## Zones — class @experimental+```+all: () => IterableIterator<ZoneDef>+at: (x: number, z: number, reach?: number) => { zone: ZoneDef; weight: number; }[]+delete: (id: string) => void+excluding: (x: number, z: number, radius: number, tags: readonly string[], seed: number) => ZoneDef | null+get: (id: string) => ZoneDef | undefined+onChange: ((bounds: [number, number, number, number], zone: ZoneDef) => void) | null+revision: number+set: (zone: ZoneDef) => void+static new (): Zones+static prototype: Zones+```+## acquireWebGPUDevice — function @beta```(requested: RenderBackendRequest, onError?: (message: string) => void): Promise<WebGPUBootResult>@@ -14186,7 +14474,7 @@ Logger## makePage — function @experimental```-(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>+(source: TerrainSource, x0: number, z0: number, size: number, repaint?: Repaint): PageImage | Promise<PageImage>```## makeWidgetInteractable — function @experimental@@ -14849,6 +15137,11 @@ PrefabsPlugin(name: string, preset: WeatherPreset): number```+## registerWorldRules — function @experimental+```+(rules: WorldRules): void+```+## registryEntityFields — function @experimental```(): (componentType: string) => readonly string[]@@ -15869,6 +16162,11 @@ Plugin(axis: WorldAxis): Vec3```+## worldGenPlugin — const @experimental+```+Plugin+```+## worldManifestPath — function @experimental```(sceneName: string): string@@ -15889,6 +16187,11 @@ PluginSystemDef```+## worldRules — function @experimental+```+(id: string): WorldRules | undefined+```+## worldSnapshot — function @experimental```(app: App, selectedId: number | null, withTree: boolean, opts?: WorldSnapshotOptions): WorldSnapshotdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex ab783d320..f516eab80 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 161 beta · 1793 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1824 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1620,6 +1620,32 @@ p2y: number| { kind: 'virtual'; id: string }```+## BiomeCondition — interface @experimental+```+blend: number | undefined+field: string+max: number | undefined+min: number | undefined+```++## BiomeDef — interface @experimental+```+conditions: readonly BiomeCondition[]+id: string+paint: readonly [number, number, number, number] | undefined+paintStrength: number | undefined+recipes: readonly BiomeRecipe[]+transition: number | undefined+weight: number | undefined+```++## BiomeRecipe — interface @experimental+```+density: number+layer: string+recipe: string+```+## BitmapText — const @experimental```BuiltinComponentDef<BitmapTextData>@@ -4584,6 +4610,18 @@ static prototype: GridLayoutProvider(x: number, z: number) => { y: number; up: number } | null```+## Group — interface @experimental+```+anchor: Placement+id: string+layer: string+members: Placement[]+priority: number+radius: number+x: number+z: number+```+## HdrFormat — interface @experimental```effective: string@@ -6487,6 +6525,82 @@ LayoutWorld & Pick<World, 'getAllEntities'>Pick<World, 'getCppRegistry' | 'getWasmModule'>```+## PlacedObject — const @experimental+```+ComponentDef<PlacedObjectData>+```++## PlacedObjectData — interface @experimental+```+id: string+kind: string+```++## Placement — interface @experimental+```+attach: "upright" | "align"+biome: string+canopy: number+footprint: number+group: string+id: string+interactive: string | null+layer: string+material: number+member: string+mesh: number+normal: [number, number, number]+recipe: string+recipeVersion: number+scale: number+x: number+y: number+yaw: number+z: number+zone: string | null+```++## PlacementChange — interface @experimental+```+scale: number | undefined+x: number | undefined+y: number | undefined+yaw: number | undefined+z: number | undefined+```++## PlacementDiffs — class @experimental+```+change: (id: string, change: PlacementChange) => void+changeOf: (id: string) => PlacementChange | undefined+isRemoved: (id: string) => boolean+load: (data: PlacementDiffsData) => void+onChange: ((id: string) => void) | null+remove: (id: string) => void+restore: (id: string) => void+revision: number+toJSON: () => PlacementDiffsData+static new (): PlacementDiffs+static prototype: PlacementDiffs+```++## PlacementDiffsData — interface @experimental+```+changed: Record<string, PlacementChange>+removed: string[]+version: 1+```++## PlacementLayer — interface @experimental+```+chunkSize: number | undefined+drawDistance: number+id: string+occupies: boolean | undefined+spacing: number+version: number | undefined+```+## PlanarReflection — const @experimental```BuiltinComponentDef<PlanarReflectionData>@@ -7136,6 +7250,7 @@ pending: PendingSystemEntry[]@internal sources_: () => ChunkSource[]clear: () => voidhas: (id: string) => boolean+invalidate: (id: string, x0: number, z0: number, x1: number, z1: number) => voidpending: numberremove: (id: string) => voidset: <T>(id: string, def: ChunkLayer<T>) => void@@ -7484,6 +7599,34 @@ get: () => Tsubscribe: (fn: (value: T) => void) => () => void```+## Recipe — interface @experimental+```+anchor: RecipeMember+id: string+members: readonly RecipeMember[] | undefined+tags: readonly string[] | undefined+version: number+```++## RecipeMember — interface @experimental+```+arc: readonly [number, number] | undefined+attach: "upright" | "align" | undefined+canopy: number | undefined+chance: number | undefined+count: readonly [number, number] | undefined+footprint: number+id: string+interactive: string | undefined+material: string | number | undefined+mesh: string | number+minUp: number | undefined+ring: readonly [number, number] | undefined+scale: readonly [number, number] | undefined+tags: readonly string[] | undefined+waterDepth: number | undefined+```+## ReflectionAxis — enum @experimental```X = 0@@ -7517,6 +7660,11 @@ FixedRate = 1OnDemand = 2```+## Rejection — type @experimental+```+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+```+## ReliableOrderedTransport — interface @experimental```delivery: "reliable-ordered"@@ -9896,12 +10044,16 @@ static prototype: TerrainUnavailable```@internal app_: App | null@internal built_: Map<number, Built>+@internal paint_: Repaint | null@internal revision_: numbercollisionReadyAt: (x: number, z: number) => boolean+groundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | nullpending: number+repaint: () => void+setPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrainsstatic prototype: Terrains@@ -11906,6 +12058,55 @@ x: numberz: number```+## WorldGen — const @experimental+```+ComponentDef<WorldGenData>+```++## WorldGenData — interface @experimental+```+paintGround: boolean+rules: string+seed: number+version: number+world: string+```++## WorldGenPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): WorldGenPlugin+static prototype: WorldGenPlugin+```++## WorldGenRes — const @experimental+```+ResourceDef<WorldGens>+```++## WorldGenStatus — interface @experimental+```+layers: Record<string, ChunkLayerStatus>+reason: string | undefined+state: "failed" | "ready" | "loading"+```++## WorldGens — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, BuiltWorld>+@internal objects_: Map<string, number>+diffs: (world?: string) => PlacementDiffs+objectOf: (id: string) => Entity | null+plan: (entity?: Entity) => WorldPlan | null+status: (entity: Entity) => WorldGenStatus | null+zones: (world?: string) => Zones+static new (): WorldGens+static prototype: WorldGens+```+## WorldManifest — interface @experimental```cellSize: number@@ -11930,6 +12131,27 @@ warnings: string[]ComponentDef<{}>```+## WorldPlan — class @experimental+```+biomeAt: (x: number, z: number) => string | null+biomeWeights: (x: number, z: number) => { biome: string; weight: number; }[]+env: Environment+explain: (x: number, z: number) => { fields: FieldValues; biomes: { biome: string; weight: number; }[]; zones: { id: string; kind: string; weight: number; }[]; layers: { layer: string; cell: [number, number]; group: string | null; rejected: Rejection | null; detail?: string; }[]; }+group: (li: number, gx: number, gz: number) => Group | Rejection+groupsIn: (layer: string, x0: number, z0: number, x1: number, z1: number) => Group[]+invalidate: () => void+layerIndex: (id: string) => number+paint: (x: number, z: number, base: readonly [number, number, number, number]) => [number, number, number, number]+placementsIn: (x0: number, z0: number, x1: number, z1: number, layers?: readonly string[]) => Placement[]+rules: WorldRules+seed: number+stats: (layer: string, x0: number, z0: number, x1: number, z1: number) => Record<"placed" | Rejection, number>+world: string+zones: Zones+static new (rules: WorldRules, env: Environment, zones: Zones, seed: number, world: string): WorldPlan+static prototype: WorldPlan+```+## WorldRay — interface @experimental```dir: Vec3@@ -11978,6 +12200,17 @@ unloadCount: numberunloadingCells: string[]```+## WorldRules — interface @experimental+```+biomes: readonly BiomeDef[]+fields: Record<string, FieldFn> | undefined+id: string+layers: readonly PlacementLayer[]+noise: Partial<Record<string, NoiseField>> | undefined+recipes: readonly Recipe[]+versions: readonly number[]+```+## WorldSnapshot — interface @experimental```selected: SnapshotEntity | null@@ -12066,11 +12299,66 @@ BuiltinComponentDef<TransformData>TransformData```+## WorldZone — const @experimental+```+ComponentDef<WorldZoneData>+```++## WorldZoneData — interface @experimental+```+biome: string+excludes: string+falloff: number+kind: string+priority: number+radius: number+shape: number+sizeX: number+sizeZ: number+```+## WrapMode — type @experimental```(typeof WrapMode)[keyof typeof WrapMode]```+## ZoneDef — interface @experimental+```+biome: string | undefined+excludes: readonly string[]+falloff: number+fields: Readonly<Record<string, number>> | undefined+id: string+kind: string+priority: number+shape: ZoneShape+```++## ZoneShape — type @experimental+```+| { type: 'circle'; x: number; z: number; radius: number }+ | { type: 'rect'; x: number; z: number; halfX: number; halfZ: number; yaw?: number }+```++## ZoneShapeKind — const @experimental+```+{ readonly Circle: 0; readonly Box: 1; }+```++## Zones — class @experimental+```+all: () => IterableIterator<ZoneDef>+at: (x: number, z: number, reach?: number) => { zone: ZoneDef; weight: number; }[]+delete: (id: string) => void+excluding: (x: number, z: number, radius: number, tags: readonly string[], seed: number) => ZoneDef | null+get: (id: string) => ZoneDef | undefined+onChange: ((bounds: [number, number, number, number], zone: ZoneDef) => void) | null+revision: number+set: (zone: ZoneDef) => void+static new (): Zones+static prototype: Zones+```+## acquireWebGPUDevice — function @beta```(requested: RenderBackendRequest, onError?: (message: string) => void): Promise<WebGPUBootResult>@@ -13923,7 +14211,7 @@ Logger## makePage — function @experimental```-(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>+(source: TerrainSource, x0: number, z0: number, size: number, repaint?: Repaint): PageImage | Promise<PageImage>```## makeWidgetInteractable — function @experimental@@ -14591,6 +14879,11 @@ PrefabsPlugin(name: string, preset: WeatherPreset): number```+## registerWorldRules — function @experimental+```+(rules: WorldRules): void+```+## registryEntityFields — function @experimental```(): (componentType: string) => readonly string[]@@ -15611,6 +15904,11 @@ Plugin(axis: WorldAxis): Vec3```+## worldGenPlugin — const @experimental+```+Plugin+```+## worldManifestPath — function @experimental```(sceneName: string): string@@ -15631,6 +15929,11 @@ PluginSystemDef```+## worldRules — function @experimental+```+(id: string): WorldRules | undefined+```+## worldSnapshot — function @experimental```(app: App, selectedId: number | null, withTree: boolean, opts?: WorldSnapshotOptions): WorldSnapshotdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex c41486c82..8f3bbabd1 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1815 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1846 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1620,6 +1620,32 @@ p2y: number| { kind: 'virtual'; id: string }```+## BiomeCondition — interface @experimental+```+blend: number | undefined+field: string+max: number | undefined+min: number | undefined+```++## BiomeDef — interface @experimental+```+conditions: readonly BiomeCondition[]+id: string+paint: readonly [number, number, number, number] | undefined+paintStrength: number | undefined+recipes: readonly BiomeRecipe[]+transition: number | undefined+weight: number | undefined+```++## BiomeRecipe — interface @experimental+```+density: number+layer: string+recipe: string+```+## BitmapText — const @experimental```BuiltinComponentDef<BitmapTextData>@@ -4584,6 +4610,18 @@ static prototype: GridLayoutProvider(x: number, z: number) => { y: number; up: number } | null```+## Group — interface @experimental+```+anchor: Placement+id: string+layer: string+members: Placement[]+priority: number+radius: number+x: number+z: number+```+## HdrFormat — interface @experimental```effective: string@@ -6780,6 +6818,82 @@ LayoutWorld & Pick<World, 'getAllEntities'>Pick<World, 'getCppRegistry' | 'getWasmModule'>```+## PlacedObject — const @experimental+```+ComponentDef<PlacedObjectData>+```++## PlacedObjectData — interface @experimental+```+id: string+kind: string+```++## Placement — interface @experimental+```+attach: "upright" | "align"+biome: string+canopy: number+footprint: number+group: string+id: string+interactive: string | null+layer: string+material: number+member: string+mesh: number+normal: [number, number, number]+recipe: string+recipeVersion: number+scale: number+x: number+y: number+yaw: number+z: number+zone: string | null+```++## PlacementChange — interface @experimental+```+scale: number | undefined+x: number | undefined+y: number | undefined+yaw: number | undefined+z: number | undefined+```++## PlacementDiffs — class @experimental+```+change: (id: string, change: PlacementChange) => void+changeOf: (id: string) => PlacementChange | undefined+isRemoved: (id: string) => boolean+load: (data: PlacementDiffsData) => void+onChange: ((id: string) => void) | null+remove: (id: string) => void+restore: (id: string) => void+revision: number+toJSON: () => PlacementDiffsData+static new (): PlacementDiffs+static prototype: PlacementDiffs+```++## PlacementDiffsData — interface @experimental+```+changed: Record<string, PlacementChange>+removed: string[]+version: 1+```++## PlacementLayer — interface @experimental+```+chunkSize: number | undefined+drawDistance: number+id: string+occupies: boolean | undefined+spacing: number+version: number | undefined+```+## PlanarReflection — const @experimental```BuiltinComponentDef<PlanarReflectionData>@@ -7429,6 +7543,7 @@ pending: PendingSystemEntry[]@internal sources_: () => ChunkSource[]clear: () => voidhas: (id: string) => boolean+invalidate: (id: string, x0: number, z0: number, x1: number, z1: number) => voidpending: numberremove: (id: string) => voidset: <T>(id: string, def: ChunkLayer<T>) => void@@ -7777,6 +7892,34 @@ get: () => Tsubscribe: (fn: (value: T) => void) => () => void```+## Recipe — interface @experimental+```+anchor: RecipeMember+id: string+members: readonly RecipeMember[] | undefined+tags: readonly string[] | undefined+version: number+```++## RecipeMember — interface @experimental+```+arc: readonly [number, number] | undefined+attach: "upright" | "align" | undefined+canopy: number | undefined+chance: number | undefined+count: readonly [number, number] | undefined+footprint: number+id: string+interactive: string | undefined+material: string | number | undefined+mesh: string | number+minUp: number | undefined+ring: readonly [number, number] | undefined+scale: readonly [number, number] | undefined+tags: readonly string[] | undefined+waterDepth: number | undefined+```+## ReflectionAxis — enum @experimental```X = 0@@ -7810,6 +7953,11 @@ FixedRate = 1OnDemand = 2```+## Rejection — type @experimental+```+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+```+## ReliableOrderedTransport — interface @experimental```delivery: "reliable-ordered"@@ -10189,12 +10337,16 @@ static prototype: TerrainUnavailable```@internal app_: App | null@internal built_: Map<number, Built>+@internal paint_: Repaint | null@internal revision_: numbercollisionReadyAt: (x: number, z: number) => boolean+groundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | nullpending: number+repaint: () => void+setPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrainsstatic prototype: Terrains@@ -12205,6 +12357,55 @@ x: numberz: number```+## WorldGen — const @experimental+```+ComponentDef<WorldGenData>+```++## WorldGenData — interface @experimental+```+paintGround: boolean+rules: string+seed: number+version: number+world: string+```++## WorldGenPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): WorldGenPlugin+static prototype: WorldGenPlugin+```++## WorldGenRes — const @experimental+```+ResourceDef<WorldGens>+```++## WorldGenStatus — interface @experimental+```+layers: Record<string, ChunkLayerStatus>+reason: string | undefined+state: "failed" | "ready" | "loading"+```++## WorldGens — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, BuiltWorld>+@internal objects_: Map<string, number>+diffs: (world?: string) => PlacementDiffs+objectOf: (id: string) => Entity | null+plan: (entity?: Entity) => WorldPlan | null+status: (entity: Entity) => WorldGenStatus | null+zones: (world?: string) => Zones+static new (): WorldGens+static prototype: WorldGens+```+## WorldManifest — interface @experimental```cellSize: number@@ -12229,6 +12430,27 @@ warnings: string[]ComponentDef<{}>```+## WorldPlan — class @experimental+```+biomeAt: (x: number, z: number) => string | null+biomeWeights: (x: number, z: number) => { biome: string; weight: number; }[]+env: Environment+explain: (x: number, z: number) => { fields: FieldValues; biomes: { biome: string; weight: number; }[]; zones: { id: string; kind: string; weight: number; }[]; layers: { layer: string; cell: [number, number]; group: string | null; rejected: Rejection | null; detail?: string; }[]; }+group: (li: number, gx: number, gz: number) => Group | Rejection+groupsIn: (layer: string, x0: number, z0: number, x1: number, z1: number) => Group[]+invalidate: () => void+layerIndex: (id: string) => number+paint: (x: number, z: number, base: readonly [number, number, number, number]) => [number, number, number, number]+placementsIn: (x0: number, z0: number, x1: number, z1: number, layers?: readonly string[]) => Placement[]+rules: WorldRules+seed: number+stats: (layer: string, x0: number, z0: number, x1: number, z1: number) => Record<"placed" | Rejection, number>+world: string+zones: Zones+static new (rules: WorldRules, env: Environment, zones: Zones, seed: number, world: string): WorldPlan+static prototype: WorldPlan+```+## WorldRay — interface @experimental```dir: Vec3@@ -12277,6 +12499,17 @@ unloadCount: numberunloadingCells: string[]```+## WorldRules — interface @experimental+```+biomes: readonly BiomeDef[]+fields: Record<string, FieldFn> | undefined+id: string+layers: readonly PlacementLayer[]+noise: Partial<Record<string, NoiseField>> | undefined+recipes: readonly Recipe[]+versions: readonly number[]+```+## WorldSnapshot — interface @experimental```selected: SnapshotEntity | null@@ -12365,11 +12598,66 @@ BuiltinComponentDef<TransformData>TransformData```+## WorldZone — const @experimental+```+ComponentDef<WorldZoneData>+```++## WorldZoneData — interface @experimental+```+biome: string+excludes: string+falloff: number+kind: string+priority: number+radius: number+shape: number+sizeX: number+sizeZ: number+```+## WrapMode — type @experimental```(typeof WrapMode)[keyof typeof WrapMode]```+## ZoneDef — interface @experimental+```+biome: string | undefined+excludes: readonly string[]+falloff: number+fields: Readonly<Record<string, number>> | undefined+id: string+kind: string+priority: number+shape: ZoneShape+```++## ZoneShape — type @experimental+```+| { type: 'circle'; x: number; z: number; radius: number }+ | { type: 'rect'; x: number; z: number; halfX: number; halfZ: number; yaw?: number }+```++## ZoneShapeKind — const @experimental+```+{ readonly Circle: 0; readonly Box: 1; }+```++## Zones — class @experimental+```+all: () => IterableIterator<ZoneDef>+at: (x: number, z: number, reach?: number) => { zone: ZoneDef; weight: number; }[]+delete: (id: string) => void+excluding: (x: number, z: number, radius: number, tags: readonly string[], seed: number) => ZoneDef | null+get: (id: string) => ZoneDef | undefined+onChange: ((bounds: [number, number, number, number], zone: ZoneDef) => void) | null+revision: number+set: (zone: ZoneDef) => void+static new (): Zones+static prototype: Zones+```+## acquireWebGPUDevice — function @beta```(requested: RenderBackendRequest, onError?: (message: string) => void): Promise<WebGPUBootResult>@@ -14232,7 +14520,7 @@ Logger## makePage — function @experimental```-(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>+(source: TerrainSource, x0: number, z0: number, size: number, repaint?: Repaint): PageImage | Promise<PageImage>```## makeWidgetInteractable — function @experimental@@ -14895,6 +15183,11 @@ PrefabsPlugin(name: string, preset: WeatherPreset): number```+## registerWorldRules — function @experimental+```+(rules: WorldRules): void+```+## registryEntityFields — function @experimental```(): (componentType: string) => readonly string[]@@ -15915,6 +16208,11 @@ Plugin(axis: WorldAxis): Vec3```+## worldGenPlugin — const @experimental+```+Plugin+```+## worldManifestPath — function @experimental```(sceneName: string): string@@ -15935,6 +16233,11 @@ PluginSystemDef```+## worldRules — function @experimental+```+(id: string): WorldRules | undefined+```+## worldSnapshot — function @experimental```(app: App, selectedId: number | null, withTree: boolean, opts?: WorldSnapshotOptions): WorldSnapshotdiff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.mdindex b9ed151c3..2a9e6e5ce 100644--- a/sdk/etc/terrain.api.md+++ b/sdk/etc/terrain.api.md@@ -276,12 +276,16 @@ static prototype: TerrainUnavailable```@internal app_: App | null@internal built_: Map<number, Built>+@internal paint_: Repaint | null@internal revision_: numbercollisionReadyAt: (x: number, z: number) => boolean+groundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | nullpending: number+repaint: () => void+setPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrainsstatic prototype: Terrains@@ -324,7 +328,7 @@ ResourceDef<Terrains>## makePage — function @experimental```-(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>+(source: TerrainSource, x0: number, z0: number, size: number, repaint?: Repaint): PageImage | Promise<PageImage>```## nodeKey — function @experimentaldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 41583b60e..142c3793a 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1806 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1837 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1620,6 +1620,32 @@ p2y: number| { kind: 'virtual'; id: string }```+## BiomeCondition — interface @experimental+```+blend: number | undefined+field: string+max: number | undefined+min: number | undefined+```++## BiomeDef — interface @experimental+```+conditions: readonly BiomeCondition[]+id: string+paint: readonly [number, number, number, number] | undefined+paintStrength: number | undefined+recipes: readonly BiomeRecipe[]+transition: number | undefined+weight: number | undefined+```++## BiomeRecipe — interface @experimental+```+density: number+layer: string+recipe: string+```+## BitmapText — const @experimental```BuiltinComponentDef<BitmapTextData>@@ -4584,6 +4610,18 @@ static prototype: GridLayoutProvider(x: number, z: number) => { y: number; up: number } | null```+## Group — interface @experimental+```+anchor: Placement+id: string+layer: string+members: Placement[]+priority: number+radius: number+x: number+z: number+```+## HdrFormat — interface @experimental```effective: string@@ -6494,6 +6532,82 @@ LayoutWorld & Pick<World, 'getAllEntities'>Pick<World, 'getCppRegistry' | 'getWasmModule'>```+## PlacedObject — const @experimental+```+ComponentDef<PlacedObjectData>+```++## PlacedObjectData — interface @experimental+```+id: string+kind: string+```++## Placement — interface @experimental+```+attach: "upright" | "align"+biome: string+canopy: number+footprint: number+group: string+id: string+interactive: string | null+layer: string+material: number+member: string+mesh: number+normal: [number, number, number]+recipe: string+recipeVersion: number+scale: number+x: number+y: number+yaw: number+z: number+zone: string | null+```++## PlacementChange — interface @experimental+```+scale: number | undefined+x: number | undefined+y: number | undefined+yaw: number | undefined+z: number | undefined+```++## PlacementDiffs — class @experimental+```+change: (id: string, change: PlacementChange) => void+changeOf: (id: string) => PlacementChange | undefined+isRemoved: (id: string) => boolean+load: (data: PlacementDiffsData) => void+onChange: ((id: string) => void) | null+remove: (id: string) => void+restore: (id: string) => void+revision: number+toJSON: () => PlacementDiffsData+static new (): PlacementDiffs+static prototype: PlacementDiffs+```++## PlacementDiffsData — interface @experimental+```+changed: Record<string, PlacementChange>+removed: string[]+version: 1+```++## PlacementLayer — interface @experimental+```+chunkSize: number | undefined+drawDistance: number+id: string+occupies: boolean | undefined+spacing: number+version: number | undefined+```+## PlanarReflection — const @experimental```BuiltinComponentDef<PlanarReflectionData>@@ -7143,6 +7257,7 @@ pending: PendingSystemEntry[]@internal sources_: () => ChunkSource[]clear: () => voidhas: (id: string) => boolean+invalidate: (id: string, x0: number, z0: number, x1: number, z1: number) => voidpending: numberremove: (id: string) => voidset: <T>(id: string, def: ChunkLayer<T>) => void@@ -7491,6 +7606,34 @@ get: () => Tsubscribe: (fn: (value: T) => void) => () => void```+## Recipe — interface @experimental+```+anchor: RecipeMember+id: string+members: readonly RecipeMember[] | undefined+tags: readonly string[] | undefined+version: number+```++## RecipeMember — interface @experimental+```+arc: readonly [number, number] | undefined+attach: "upright" | "align" | undefined+canopy: number | undefined+chance: number | undefined+count: readonly [number, number] | undefined+footprint: number+id: string+interactive: string | undefined+material: string | number | undefined+mesh: string | number+minUp: number | undefined+ring: readonly [number, number] | undefined+scale: readonly [number, number] | undefined+tags: readonly string[] | undefined+waterDepth: number | undefined+```+## ReflectionAxis — enum @experimental```X = 0@@ -7524,6 +7667,11 @@ FixedRate = 1OnDemand = 2```+## Rejection — type @experimental+```+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+```+## ReliableOrderedTransport — interface @experimental```delivery: "reliable-ordered"@@ -9903,12 +10051,16 @@ static prototype: TerrainUnavailable```@internal app_: App | null@internal built_: Map<number, Built>+@internal paint_: Repaint | null@internal revision_: numbercollisionReadyAt: (x: number, z: number) => boolean+groundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | nullpending: number+repaint: () => void+setPaint: (paint: Repaint | null) => voidstatus: (entity: Entity) => TerrainStatus | nullstatic new (): Terrainsstatic prototype: Terrains@@ -11937,6 +12089,55 @@ x: numberz: number```+## WorldGen — const @experimental+```+ComponentDef<WorldGenData>+```++## WorldGenData — interface @experimental+```+paintGround: boolean+rules: string+seed: number+version: number+world: string+```++## WorldGenPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): WorldGenPlugin+static prototype: WorldGenPlugin+```++## WorldGenRes — const @experimental+```+ResourceDef<WorldGens>+```++## WorldGenStatus — interface @experimental+```+layers: Record<string, ChunkLayerStatus>+reason: string | undefined+state: "failed" | "ready" | "loading"+```++## WorldGens — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, BuiltWorld>+@internal objects_: Map<string, number>+diffs: (world?: string) => PlacementDiffs+objectOf: (id: string) => Entity | null+plan: (entity?: Entity) => WorldPlan | null+status: (entity: Entity) => WorldGenStatus | null+zones: (world?: string) => Zones+static new (): WorldGens+static prototype: WorldGens+```+## WorldManifest — interface @experimental```cellSize: number@@ -11961,6 +12162,27 @@ warnings: string[]ComponentDef<{}>```+## WorldPlan — class @experimental+```+biomeAt: (x: number, z: number) => string | null+biomeWeights: (x: number, z: number) => { biome: string; weight: number; }[]+env: Environment+explain: (x: number, z: number) => { fields: FieldValues; biomes: { biome: string; weight: number; }[]; zones: { id: string; kind: string; weight: number; }[]; layers: { layer: string; cell: [number, number]; group: string | null; rejected: Rejection | null; detail?: string; }[]; }+group: (li: number, gx: number, gz: number) => Group | Rejection+groupsIn: (layer: string, x0: number, z0: number, x1: number, z1: number) => Group[]+invalidate: () => void+layerIndex: (id: string) => number+paint: (x: number, z: number, base: readonly [number, number, number, number]) => [number, number, number, number]+placementsIn: (x0: number, z0: number, x1: number, z1: number, layers?: readonly string[]) => Placement[]+rules: WorldRules+seed: number+stats: (layer: string, x0: number, z0: number, x1: number, z1: number) => Record<"placed" | Rejection, number>+world: string+zones: Zones+static new (rules: WorldRules, env: Environment, zones: Zones, seed: number, world: string): WorldPlan+static prototype: WorldPlan+```+## WorldRay — interface @experimental```dir: Vec3@@ -12009,6 +12231,17 @@ unloadCount: numberunloadingCells: string[]```+## WorldRules — interface @experimental+```+biomes: readonly BiomeDef[]+fields: Record<string, FieldFn> | undefined+id: string+layers: readonly PlacementLayer[]+noise: Partial<Record<string, NoiseField>> | undefined+recipes: readonly Recipe[]+versions: readonly number[]+```+## WorldSnapshot — interface @experimental```selected: SnapshotEntity | null@@ -12097,11 +12330,66 @@ BuiltinComponentDef<TransformData>TransformData```+## WorldZone — const @experimental+```+ComponentDef<WorldZoneData>+```++## WorldZoneData — interface @experimental+```+biome: string+excludes: string+falloff: number+kind: string+priority: number+radius: number+shape: number+sizeX: number+sizeZ: number+```+## WrapMode — type @experimental```(typeof WrapMode)[keyof typeof WrapMode]```+## ZoneDef — interface @experimental+```+biome: string | undefined+excludes: readonly string[]+falloff: number+fields: Readonly<Record<string, number>> | undefined+id: string+kind: string+priority: number+shape: ZoneShape+```++## ZoneShape — type @experimental+```+| { type: 'circle'; x: number; z: number; radius: number }+ | { type: 'rect'; x: number; z: number; halfX: number; halfZ: number; yaw?: number }+```++## ZoneShapeKind — const @experimental+```+{ readonly Circle: 0; readonly Box: 1; }+```++## Zones — class @experimental+```+all: () => IterableIterator<ZoneDef>+at: (x: number, z: number, reach?: number) => { zone: ZoneDef; weight: number; }[]+delete: (id: string) => void+excluding: (x: number, z: number, radius: number, tags: readonly string[], seed: number) => ZoneDef | null+get: (id: string) => ZoneDef | undefined+onChange: ((bounds: [number, number, number, number], zone: ZoneDef) => void) | null+revision: number+set: (zone: ZoneDef) => void+static new (): Zones+static prototype: Zones+```+## acquireWebGPUDevice — function @beta```(requested: RenderBackendRequest, onError?: (message: string) => void): Promise<WebGPUBootResult>@@ -13959,7 +14247,7 @@ Logger## makePage — function @experimental```-(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>+(source: TerrainSource, x0: number, z0: number, size: number, repaint?: Repaint): PageImage | Promise<PageImage>```## makeWidgetInteractable — function @experimental@@ -14622,6 +14910,11 @@ PrefabsPlugin(name: string, preset: WeatherPreset): number```+## registerWorldRules — function @experimental+```+(rules: WorldRules): void+```+## registryEntityFields — function @experimental```(): (componentType: string) => readonly string[]@@ -15647,6 +15940,11 @@ MiniGameProfile(axis: WorldAxis): Vec3```+## worldGenPlugin — const @experimental+```+Plugin+```+## worldManifestPath — function @experimental```(sceneName: string): string@@ -15667,6 +15965,11 @@ PluginSystemDef```+## worldRules — function @experimental+```+(id: string): WorldRules | undefined+```+## worldSnapshot — function @experimental```(app: App, selectedId: number | null, withTree: boolean, opts?: WorldSnapshotOptions): WorldSnapshotdiff --git a/sdk/etc/worldgen.api.md b/sdk/etc/worldgen.api.mdnew file mode 100644index 000000000..a1d49b715--- /dev/null+++ b/sdk/etc/worldgen.api.md@@ -0,0 +1,372 @@+# API surface — esengine/worldgen++<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->+Symbols: 0 public · 0 beta · 43 experimental · 0 deprecated++## BiomeCondition — interface @experimental+```+blend: number | undefined+field: string+max: number | undefined+min: number | undefined+```++## BiomeDef — interface @experimental+```+conditions: readonly BiomeCondition[]+id: string+paint: readonly [number, number, number, number] | undefined+paintStrength: number | undefined+recipes: readonly BiomeRecipe[]+transition: number | undefined+weight: number | undefined+```++## BiomeRecipe — interface @experimental+```+density: number+layer: string+recipe: string+```++## Environment — class @experimental+```+inputs: EnvironmentInputs+sample: (x: number, z: number) => FieldValues+static new (inputs: EnvironmentInputs): Environment+static prototype: Environment+```++## EnvironmentInputs — interface @experimental+```+fields: Record<string, FieldFn> | undefined+ground: (x: number, z: number) => { y: number; up: number; normal?: [number, number, number]; } | null+noise: Partial<Record<string, NoiseField>> | undefined+overrides: ((x: number, z: number) => { field: string; value: number; weight: number; }[]) | undefined+seed: number+waterDepth: ((x: number, z: number, y: number) => number | null) | undefined+```++## FieldFn — type @experimental+```+(x: number, z: number, at: Readonly<FieldValues>) => number+```++## FieldValues — type @experimental+```+Record<string, number>+```++## Group — interface @experimental+```+anchor: Placement+id: string+layer: string+members: Placement[]+priority: number+radius: number+x: number+z: number+```++## NoiseField — interface @experimental+```+octaves: number | undefined+scale: number+```++## PlacedObject — const @experimental+```+ComponentDef<PlacedObjectData>+```++## PlacedObjectData — interface @experimental+```+id: string+kind: string+```++## Placement — interface @experimental+```+attach: "upright" | "align"+biome: string+canopy: number+footprint: number+group: string+id: string+interactive: string | null+layer: string+material: number+member: string+mesh: number+normal: [number, number, number]+recipe: string+recipeVersion: number+scale: number+x: number+y: number+yaw: number+z: number+zone: string | null+```++## PlacementChange — interface @experimental+```+scale: number | undefined+x: number | undefined+y: number | undefined+yaw: number | undefined+z: number | undefined+```++## PlacementDiffs — class @experimental+```+change: (id: string, change: PlacementChange) => void+changeOf: (id: string) => PlacementChange | undefined+isRemoved: (id: string) => boolean+load: (data: PlacementDiffsData) => void+onChange: ((id: string) => void) | null+remove: (id: string) => void+restore: (id: string) => void+revision: number+toJSON: () => PlacementDiffsData+static new (): PlacementDiffs+static prototype: PlacementDiffs+```++## PlacementDiffsData — interface @experimental+```+changed: Record<string, PlacementChange>+removed: string[]+version: 1+```++## PlacementLayer — interface @experimental+```+chunkSize: number | undefined+drawDistance: number+id: string+occupies: boolean | undefined+spacing: number+version: number | undefined+```++## Recipe — interface @experimental+```+anchor: RecipeMember+id: string+members: readonly RecipeMember[] | undefined+tags: readonly string[] | undefined+version: number+```++## RecipeMember — interface @experimental+```+arc: readonly [number, number] | undefined+attach: "upright" | "align" | undefined+canopy: number | undefined+chance: number | undefined+count: readonly [number, number] | undefined+footprint: number+id: string+interactive: string | undefined+material: string | number | undefined+mesh: string | number+minUp: number | undefined+ring: readonly [number, number] | undefined+scale: readonly [number, number] | undefined+tags: readonly string[] | undefined+waterDepth: number | undefined+```++## Rejection — type @experimental+```+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+```++## WorldGen — const @experimental+```+ComponentDef<WorldGenData>+```++## WorldGenData — interface @experimental+```+paintGround: boolean+rules: string+seed: number+version: number+world: string+```++## WorldGenPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): WorldGenPlugin+static prototype: WorldGenPlugin+```++## WorldGenRes — const @experimental+```+ResourceDef<WorldGens>+```++## WorldGenStatus — interface @experimental+```+layers: Record<string, ChunkLayerStatus>+reason: string | undefined+state: "failed" | "ready" | "loading"+```++## WorldGens — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, BuiltWorld>+@internal objects_: Map<string, number>+diffs: (world?: string) => PlacementDiffs+objectOf: (id: string) => Entity | null+plan: (entity?: Entity) => WorldPlan | null+status: (entity: Entity) => WorldGenStatus | null+zones: (world?: string) => Zones+static new (): WorldGens+static prototype: WorldGens+```++## WorldPlan — class @experimental+```+biomeAt: (x: number, z: number) => string | null+biomeWeights: (x: number, z: number) => { biome: string; weight: number; }[]+env: Environment+explain: (x: number, z: number) => { fields: FieldValues; biomes: { biome: string; weight: number; }[]; zones: { id: string; kind: string; weight: number; }[]; layers: { layer: string; cell: [number, number]; group: string | null; rejected: Rejection | null; detail?: string; }[]; }+group: (li: number, gx: number, gz: number) => Group | Rejection+groupsIn: (layer: string, x0: number, z0: number, x1: number, z1: number) => Group[]+invalidate: () => void+layerIndex: (id: string) => number+paint: (x: number, z: number, base: readonly [number, number, number, number]) => [number, number, number, number]+placementsIn: (x0: number, z0: number, x1: number, z1: number, layers?: readonly string[]) => Placement[]+rules: WorldRules+seed: number+stats: (layer: string, x0: number, z0: number, x1: number, z1: number) => Record<"placed" | Rejection, number>+world: string+zones: Zones+static new (rules: WorldRules, env: Environment, zones: Zones, seed: number, world: string): WorldPlan+static prototype: WorldPlan+```++## WorldRules — interface @experimental+```+biomes: readonly BiomeDef[]+fields: Record<string, FieldFn> | undefined+id: string+layers: readonly PlacementLayer[]+noise: Partial<Record<string, NoiseField>> | undefined+recipes: readonly Recipe[]+versions: readonly number[]+```++## WorldZone — const @experimental+```+ComponentDef<WorldZoneData>+```++## WorldZoneData — interface @experimental+```+biome: string+excludes: string+falloff: number+kind: string+priority: number+radius: number+shape: number+sizeX: number+sizeZ: number+```++## ZoneDef — interface @experimental+```+biome: string | undefined+excludes: readonly string[]+falloff: number+fields: Readonly<Record<string, number>> | undefined+id: string+kind: string+priority: number+shape: ZoneShape+```++## ZoneShape — type @experimental+```+| { type: 'circle'; x: number; z: number; radius: number }+ | { type: 'rect'; x: number; z: number; halfX: number; halfZ: number; yaw?: number }+```++## ZoneShapeKind — const @experimental+```+{ readonly Circle: 0; readonly Box: 1; }+```++## Zones — class @experimental+```+all: () => IterableIterator<ZoneDef>+at: (x: number, z: number, reach?: number) => { zone: ZoneDef; weight: number; }[]+delete: (id: string) => void+excluding: (x: number, z: number, radius: number, tags: readonly string[], seed: number) => ZoneDef | null+get: (id: string) => ZoneDef | undefined+onChange: ((bounds: [number, number, number, number], zone: ZoneDef) => void) | null+revision: number+set: (zone: ZoneDef) => void+static new (): Zones+static prototype: Zones+```++## bandWeight — function @experimental+```+(c: BiomeCondition, v: number): number+```++## fbm — function @experimental+```+(x: number, z: number, seed: number, octaves: number): number+```++## hash01 — function @experimental+```+(...v: number[]): number+```++## hashString — function @experimental+```+(s: string): number+```++## registerWorldRules — function @experimental+```+(rules: WorldRules): void+```++## worldGenPlugin — const @experimental+```+Plugin+```++## worldRules — function @experimental+```+(id: string): WorldRules | undefined+```++## zoneBounds — function @experimental+```+(zone: ZoneDef): [number, number, number, number]+```++## zoneDistance — function @experimental+```+(shape: ZoneShape, x: number, z: number): number+```++## zoneWeight — function @experimental+```+(zone: ZoneDef, d: number): number+```+diff --git a/sdk/package.json b/sdk/package.jsonindex 470390874..1ae605d3d 100644--- a/sdk/package.json+++ b/sdk/package.json@@ -23,6 +23,7 @@"./dist/fx-atmosphere/index.js","./dist/fx-lighting/index.js","./dist/foliage/index.js",+ "./dist/worldgen/index.js","./dist/water/index.js","./dist/spline/index.js","./dist/character-shaders/index.js",@@ -105,6 +106,10 @@"import": "./dist/foliage/index.js","types": "./dist/foliage/index.d.ts"},+ "./worldgen": {+ "import": "./dist/worldgen/index.js",+ "types": "./dist/worldgen/index.d.ts"+ },"./water": {"import": "./dist/water/index.js","types": "./dist/water/index.d.ts"diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.jsindex 073063a12..0a32a92d2 100644--- a/sdk/rolldown.config.js+++ b/sdk/rolldown.config.js@@ -103,6 +103,7 @@ export default defineConfig(['fx-atmosphere/index': 'src/postprocess/fxAtmosphere.ts','fx-lighting/index': 'src/postprocess/fxLighting.ts','foliage/index': 'src/foliage/index.ts',+ 'worldgen/index': 'src/worldgen/index.ts','water/index': 'src/water/index.ts','spline/index': 'src/spline/index.ts','character-shaders/index': 'src/character/index.ts',diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex f0991b43b..858b71adc 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -801,6 +801,18 @@ export {export {Foliage, FoliageField, FoliageRes, FoliagePlugin, foliagePlugin, type FoliageData,} from './foliage/foliagePlugin';+// Generated worlds are an optional module too (`esengine/worldgen`).+export {+ WorldGen, WorldZone, PlacedObject, ZoneShapeKind, WorldGens, WorldGenRes, WorldGenPlugin, worldGenPlugin,+ type WorldGenData, type WorldZoneData, type PlacedObjectData, type WorldGenStatus,+} from './worldgen/worldgenPlugin';+export {+ registerWorldRules, worldRules,+ type WorldRules, type BiomeDef, type BiomeCondition, type BiomeRecipe, type Recipe, type RecipeMember, type PlacementLayer,+} from './worldgen/rules';+export { WorldPlan, type Placement, type Group, type Rejection } from './worldgen/plan';+export { Zones, type ZoneDef, type ZoneShape } from './worldgen/zones';+export { PlacementDiffs, type PlacementChange, type PlacementDiffsData } from './worldgen/diffs';// Splines and water are optional modules too (`esengine/spline`, `esengine/water`).export { Bakes, BakesRes, bakesOf, finish, type WorkJob, type BakeProgress } from './runtime/bakes';export { CollisionGeometry, CollisionGeometryRes, collisionGeometryOf, type CollisionPiece } from './runtime/collisionGeometry';diff --git a/sdk/src/platform/nativeModuleRegistry.ts b/sdk/src/platform/nativeModuleRegistry.tsindex 0794eaa97..0bd2616b4 100644--- a/sdk/src/platform/nativeModuleRegistry.ts+++ b/sdk/src/platform/nativeModuleRegistry.ts@@ -30,6 +30,7 @@ import * as FxBasicModule from '../postprocess/fxBasic';import * as FxAtmosphereModule from '../postprocess/fxAtmosphere';import * as FxLightingModule from '../postprocess/fxLighting';import * as FoliageModule from '../foliage';+import * as WorldGenModule from '../worldgen';import * as WaterModule from '../water';import * as SplineModule from '../spline';import * as CharacterShadersModule from '../character';@@ -58,6 +59,7 @@ export const NATIVE_MODULE_NAMESPACES: Readonly<Record<string, unknown>> = {'esengine/fx-atmosphere': FxAtmosphereModule,'esengine/fx-lighting': FxLightingModule,'esengine/foliage': FoliageModule,+ 'esengine/worldgen': WorldGenModule,'esengine/water': WaterModule,'esengine/spline': SplineModule,'esengine/character-shaders': CharacterShadersModule,diff --git a/sdk/src/residency/chunks.ts b/sdk/src/residency/chunks.tsindex 470167bfe..9135abddf 100644--- a/sdk/src/residency/chunks.ts+++ b/sdk/src/residency/chunks.ts@@ -98,6 +98,9 @@ const MAX_IN_FLIGHT = 8;const keyOf = (cx: number, cz: number): string => `${cx},${cz}`;+/** What a published chunk's generation is set to when it is made out of date by hand: no layer's generation. */+const OUTDATED = Symbol('outdated') as unknown as string;+/** The procedural chunks of every layer. Read {@link ProceduralChunks.status} for where they stand. */export class ProceduralChunks {private readonly layers_ = new Map<string, Layer<unknown>>();@@ -152,6 +155,25 @@ export class ProceduralChunks {return n;}+ /**+ * Makes the published chunks of layer `id` that touch the world square [x0, x1] by [z0, z1] again, each keeping its old version+ * until the new one replaces it: what changed there (a zone, a felled tree) changed only them.+ */+ invalidate(id: string, x0: number, z0: number, x1: number, z1: number): void {+ const layer = this.layers_.get(id);+ if (!layer) return;+ const d = layer.def;+ const cx0 = Math.floor((x0 - d.originX) / d.sizeX), cx1 = Math.floor((x1 - d.originX) / d.sizeX);+ const cz0 = Math.floor((z0 - d.originZ) / d.sizeZ), cz1 = Math.floor((z1 - d.originZ) / d.sizeZ);+ for (const c of layer.chunks.values()) {+ if (c.cx < cx0 || c.cx > cx1 || c.cz < cz0 || c.cz > cz1) continue;+ if (c.value !== null) c.publishedFor = OUTDATED;+ c.failedFor = null;+ c.making?.abort.abort();+ c.making = null;+ }+ }+/** Lets go of every chunk of every layer. */clear(): void {for (const id of [...this.layers_.keys()]) this.remove(id);diff --git a/sdk/src/runtime/optionalPlugins.ts b/sdk/src/runtime/optionalPlugins.tsindex 2c49717e3..d3bd64c71 100644--- a/sdk/src/runtime/optionalPlugins.ts+++ b/sdk/src/runtime/optionalPlugins.ts@@ -26,6 +26,7 @@ import { registerLightingEffectSources } from '../postprocess/sources/lighting';import { registerTimelineSupport } from '../timeline/timelineSupport';import { registerTerrainSupport } from '../terrain/terrainSupport';import { registerFoliageSupport } from '../foliage/foliageSupport';+import { registerWorldGenSupport } from '../worldgen/worldgenSupport';import { registerWaterSupport } from '../water/waterSupport';import { registerSplineSupport } from '../spline/splineSupport';import { registerCharacterShaders } from '../character/characterSupport';@@ -47,6 +48,7 @@ export function installOptionalPlugins(): void {registerLightingEffectSources();registerTerrainSupport();registerFoliageSupport();+ registerWorldGenSupport();registerWaterSupport();registerSplineSupport();registerCharacterShaders();diff --git a/sdk/src/terrain/pages.ts b/sdk/src/terrain/pages.tsindex 173c5d4c2..8b4879f03 100644--- a/sdk/src/terrain/pages.ts+++ b/sdk/src/terrain/pages.ts@@ -36,13 +36,15 @@ export interface PageImage { heights: Uint8Array; paint: Uint8Array; min: number/*** Samples a node's page from `source`: square (x0, z0) to (x0 + size, z0 + size) in the terrain's space. Heights are encoded over* the source's range. Off an area's edge the ground is its nearest edge's, so the pages there are whole. A source that samples regions- * (a provider) is asked for the page's whole grid at once, and may answer later.+ * (a provider) is asked for the page's whole grid at once, and may answer later. `repaint`, given, has the last word on each sample's+ * paint (a world's biomes), from the paint the source gave it.*/-export function makePage(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage> {+export function makePage(source: TerrainSource, x0: number, z0: number, size: number, repaint?: Repaint): PageImage | Promise<PageImage> {const n = PAGE_SIDE, step = size / PAGE_TEXELS;if (source.region) {const got = source.region(x0 - step, z0 - step, step, n);- return got instanceof Promise ? got.then((r) => encodePage(source, x0, z0, step, r.heights, r.paint)) : encodePage(source, x0, z0, step, got.heights, got.paint);+ return got instanceof Promise ? got.then((r) => encodePage(source, x0, z0, step, r.heights, r.paint, repaint))+ : encodePage(source, x0, z0, step, got.heights, got.paint, repaint);}const h = new Float32Array(n * n);const [bx0, bz0, bx1, bz1] = source.bounds ?? [-Infinity, -Infinity, Infinity, Infinity];@@ -50,11 +52,14 @@ export function makePage(source: TerrainSource, x0: number, z0: number, size: nuconst x = Math.min(Math.max(x0 + (i - 1) * step, bx0), bx1), z = Math.min(Math.max(z0 + (j - 1) * step, bz0), bz1);h[j * n + i] = source.height(x, z) ?? source.minHeight;}- return encodePage(source, x0, z0, step, h);+ return encodePage(source, x0, z0, step, h, undefined, repaint);}+/** The paint of a sample at (x, z) in the terrain's space, `h` high and facing `ny` up, from what it would otherwise be. */+export type Repaint = (x: number, z: number, h: number, ny: number, w: [number, number, number, number]) => [number, number, number, number];+/** Encodes a page's samples (row by row, one past each edge): heights and normals into one image, the paint into the other. */-function encodePage(source: TerrainSource, x0: number, z0: number, step: number, h: Float32Array, given?: Float32Array): PageImage {+function encodePage(source: TerrainSource, x0: number, z0: number, step: number, h: Float32Array, given?: Float32Array, repaint?: Repaint): PageImage {const n = PAGE_SIDE;const [bx0, bz0, bx1, bz1] = source.bounds ?? [-Infinity, -Infinity, Infinity, Infinity];let min = Infinity, max = -Infinity;@@ -74,7 +79,8 @@ function encodePage(source: TerrainSource, x0: number, z0: number, step: number,heights[k * 4 + 2] = Math.round((nx * 0.5 + 0.5) * 255);heights[k * 4 + 3] = Math.round((nz * 0.5 + 0.5) * 255);const x = Math.min(Math.max(x0 + (i - 1) * step, bx0), bx1), z = Math.min(Math.max(z0 + (j - 1) * step, bz0), bz1);- const w = given ? [given[k * 4]!, given[k * 4 + 1]!, given[k * 4 + 2]!, given[k * 4 + 3]!] : source.paint(x, z, h[k]!, ny);+ let w: [number, number, number, number] = given ? [given[k * 4]!, given[k * 4 + 1]!, given[k * 4 + 2]!, given[k * 4 + 3]!] : source.paint(x, z, h[k]!, ny);+ if (repaint) w = repaint(x, z, h[k]!, ny, w);for (let c = 0; c < 4; c++) paint[k * 4 + c] = Math.round(Math.min(Math.max(w[c]!, 0), 1) * 255);}return { heights, paint, min: Number.isFinite(min) ? min : source.minHeight, max: Number.isFinite(max) ? max : source.maxHeight };diff --git a/sdk/src/terrain/provider.ts b/sdk/src/terrain/provider.tsindex 8785ebaf0..fee9def73 100644--- a/sdk/src/terrain/provider.ts+++ b/sdk/src/terrain/provider.ts@@ -53,10 +53,20 @@ export interface TerrainProvider {}const providers_ = new Map<string, TerrainProvider>();+let revision_ = 0;-/** Makes `provider` available to every Terrain that names it. A second provider under the same id replaces the first. */+/**+ * Makes `provider` available to every Terrain that names it. A second provider under the same id replaces the first. A terrain that+ * named one not yet registered (a script registers it after the scene loaded) is made once it is.+ */export function registerTerrainProvider(provider: TerrainProvider): void {providers_.set(provider.id, provider);+ revision_++;+}++/** @internal Bumped on every registration, so a terrain whose provider was missing asks again. */+export function terrainProvidersRevision(): number {+ return revision_;}/** The provider registered under `id`, if any. */diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex de43b35ab..76f53e2be 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -39,8 +39,8 @@ import type { Color, Entity } from '../types';import { erosionJob, heightfieldFromPixels, proceduralHeightfield } from './heightfield';import { FieldSource, 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 } from './pages';-import { noiseProvider, ProviderSource, terrainProvider, TerrainUnavailable } from './provider';+import { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage, type Repaint } from './pages';+import { noiseProvider, ProviderSource, terrainProvider, terrainProvidersRevision, TerrainUnavailable } from './provider';import { buildPatchMesh } from './patch';import { TerrainSurface, TILE_CELLS, type SurfaceTile } from './surface';import { collisionGeometryOf } from '../runtime/collisionGeometry';@@ -253,6 +253,24 @@ export class Terrains {return null;}+ /**+ * Whether the ground at (x, z) is known: false while a terrain that covers it is still being made, or its provider has not answered+ * there yet; true where it is known, and where no terrain is (there is no ground to wait for).+ */+ groundKnownAt(x: number, z: number): boolean {+ const world = this.app_?.world;+ if (!world) return true;+ for (const [entity, built] of this.built_) {+ if (built.failure || !world.valid(entity)) continue;+ if (built.loading || !built.surface) return false;+ const t = world.tryGet(entity, Transform) as TransformData | null;+ if (!t) continue;+ const lx = x - t.worldPosition.x, lz = z - t.worldPosition.z;+ if (built.surface.covers(lx, lz)) return built.surface.height(lx, lz) !== null;+ }+ return true;+ }+/** Whether the ground under (x, z) is built for collision: what a game waits on before it drops something there. */collisionReadyAt(x: number, z: number): boolean {const app = this.app_;@@ -275,6 +293,24 @@ export class Terrains {return { state: built.loading || !built.source ? 'loading' : 'ready' };}+ /** @internal What has the last word on the ground's paint, in world space (a world's biomes), if anything does. */+ paint_: Repaint | null = null;++ /**+ * Gives the ground's paint to `paint` (or back to the terrains, with null): at each sample, in world space, it is handed the paint+ * the terrain made and returns the paint to draw. The pages already made are made again.+ */+ setPaint(paint: Repaint | null): void {+ if (paint === this.paint_) return;+ this.paint_ = paint;+ this.repaint();+ }++ /** Makes every page again, for a paint that changed what it answers. */+ repaint(): void {+ for (const built of this.built_.values()) built.table.clear();+ }+/** @internal Bumped whenever a terrain's ground changes, so what stands on it knows to stand again. */revision_ = 0;@@ -299,7 +335,8 @@ export const TerrainsRes = defineResource<Terrains>(new Terrains(), 'Terrains');function signatureOf(data: TerrainData): string {const { layerColor0: _a, layerColor1: _b, layerColor2: _c, layerColor3: _d, detail: _e, drawDistance: _f,collision: _g, collisionDistance: _h, collisionLayer: _i, friction: _j, ...shape } = data;- return JSON.stringify(shape);+ // A game's own provider is read again when one is registered under its name.+ return `${JSON.stringify(shape)}${data.extent === TerrainExtent.Infinite && data.provider !== NOISE_PROVIDER ? `#${terrainProvidersRevision()}` : ''}`;}/** Where what collides with the ground is: every moving 3D body and every character. */@@ -592,7 +629,7 @@ export class TerrainPlugin implements Plugin {if (covered.has(nodeKey(up.level, up.ix, up.iz))) { drawn.delete(key); break; }}}- this.makePages(app, built, source, eyeAt);+ this.makePages(app, built, source, eyeAt, t.worldPosition);const set = (name: string, value: Parameters<typeof Material.setUniform>[2]): void => { Material.setUniform(built.instance, name, value); };set('u_heightRange', { x: source.minHeight, y: Math.max(source.maxHeight - source.minHeight, 1e-6) });@@ -608,7 +645,9 @@ export class TerrainPlugin implements Plugin {}/** Makes the wanted pages, coarse and near first, for as long as the frame can spare. */- private makePages(app: App, built: Built, source: TerrainSource, eye: [number, number, number]): void {+ private makePages(app: App, built: Built, source: TerrainSource, eye: [number, number, number], at: { x: number; y: number; z: number }): void {+ const paint = app.getResource(TerrainsRes).paint_;+ const repaint: Repaint | undefined = paint ? (x, z, h, ny, w) => paint(x + at.x, z + at.z, h + at.y, ny, w) : undefined;const bakes = bakesOf(app);if (built.wanted.size === 0) { bakes.mark(built, 'Building the terrain', 1); return; }const order = [...built.wanted.values()].sort((a, b) => b.level - a.level@@ -627,7 +666,7 @@ export class TerrainPlugin implements Plugin {const key = nodeKey(node.level, node.ix, node.iz);if (built.asked.has(key)) continue;if (source.region && built.asked.size >= PAGES_IN_FLIGHT) break;- const image = makePage(source, node.x0, node.z0, node.size);+ const image = makePage(source, node.x0, node.z0, node.size, repaint);if (image instanceof Promise) {// A provider answering later: its page is stored when it lands, if the terrain is still the one that asked.built.asked.add(key);diff --git a/sdk/src/worldgen/diffs.ts b/sdk/src/worldgen/diffs.tsnew file mode 100644index 000000000..126abaf01--- /dev/null+++ b/sdk/src/worldgen/diffs.ts@@ -0,0 +1,74 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file diffs.ts+ * @brief What the players changed in a generated world, kept apart from it: what was taken away and what was moved.+ *+ * @details The world is made again from its rules every time a chunk comes near; what a player did is laid over it before anything is+ * shown, so a felled tree stays felled after its chunk is let go and made again, and after a save is read back. Changes are+ * kept by placement id, which does not change with the order things are made in or with rules added later. What a player+ * builds is not a change to the generated world: it is the game's own, and the zone it reserves keeps generation out of it.+ */++/** Where and how a placement was moved: any of its position, its turn and its scale. */+export interface PlacementChange { x?: number; y?: number; z?: number; yaw?: number; scale?: number }++/** A world's changes, as a save stores them. */+export interface PlacementDiffsData { version: 1; removed: string[]; changed: Record<string, PlacementChange> }++export class PlacementDiffs {+ private readonly removed_ = new Set<string>();+ private readonly changed_ = new Map<string, PlacementChange>();+ revision = 0;+ /** Told the id of every placement that changed, so only its chunk is made again. */+ onChange: ((id: string) => void) | null = null;++ /** Takes a placement out of the world for good (felled, mined, picked up). */+ remove(id: string): void {+ if (this.removed_.has(id)) return;+ this.removed_.add(id);+ this.changed();+ this.onChange?.(id);+ }++ /** Puts a removed placement back (it grew again). */+ restore(id: string): void {+ if (!this.removed_.delete(id)) return;+ this.changed();+ this.onChange?.(id);+ }++ /** Moves, turns or scales a placement. */+ change(id: string, change: PlacementChange): void {+ this.changed_.set(id, { ...this.changed_.get(id), ...change });+ this.changed();+ this.onChange?.(id);+ }++ isRemoved(id: string): boolean {+ return this.removed_.has(id);+ }++ changeOf(id: string): PlacementChange | undefined {+ return this.changed_.get(id);+ }++ toJSON(): PlacementDiffsData {+ return { version: 1, removed: [...this.removed_].sort(), changed: Object.fromEntries([...this.changed_].sort(([a], [b]) => (a < b ? -1 : 1))) };+ }++ /** Replaces every change with a save's. */+ load(data: PlacementDiffsData): void {+ const touched = new Set([...this.removed_, ...this.changed_.keys(), ...data.removed, ...Object.keys(data.changed)]);+ this.removed_.clear();+ this.changed_.clear();+ for (const id of data.removed) this.removed_.add(id);+ for (const [id, c] of Object.entries(data.changed)) this.changed_.set(id, { ...c });+ this.changed();+ for (const id of touched) this.onChange?.(id);+ }++ private changed(): void {+ this.revision++;+ }+}diff --git a/sdk/src/worldgen/fields.ts b/sdk/src/worldgen/fields.tsnew file mode 100644index 000000000..8603ceffd--- /dev/null+++ b/sdk/src/worldgen/fields.ts@@ -0,0 +1,105 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file fields.ts+ * @brief The environment a world is laid out by: numbers read anywhere in it, the same for the same seed on every machine.+ *+ * @details A field is a function of the world position. The ground's (`height`, `up`, `slope`) and the water's (`waterDepth`) are+ * read from the terrain and the water; `moisture`, `temperature` and `rock` are seeded noise, slow across the world; a game+ * adds fields of its own. A zone may set a field over its area, blended in by its weight, so a designer can make a wet hollow+ * or a dry clearing by hand. Nothing here depends on what is loaded or in what order it was asked.+ */+import { noised } from '../terrain/source';++/** The fields at one place, by name. `height` is NaN where there is no ground. */+export type FieldValues = Record<string, number>;++/** A field of the game's own: a number at (x, z), read after the built-in ones (which it may read from `at`). */+export type FieldFn = (x: number, z: number, at: Readonly<FieldValues>) => number;++/** A seeded noise field: `scale` world units to a feature, `octaves` layers of detail. */+export interface NoiseField { scale: number; octaves?: number }++/** Where the environment comes from. */+export interface EnvironmentInputs {+ seed: number;+ /** The ground's height, how much it faces up and (if known) its normal at (x, z), or null where there is none. */+ ground(x: number, z: number): { y: number; up: number; normal?: [number, number, number] } | null;+ /** How deep water stands over the world height `y` at (x, z): above zero under water, null where there is none. */+ waterDepth?(x: number, z: number, y: number): number | null;+ /** The noise fields; absent ones keep their defaults (moisture 900, temperature 2400, rock 500 world units). */+ noise?: Partial<Record<string, NoiseField>>;+ /** Fields of the game's own. */+ fields?: Record<string, FieldFn>;+ /** Fields set by hand over an area: the value, and how much of it holds at (x, z) (0 to 1). */+ overrides?(x: number, z: number): { field: string; value: number; weight: number }[];+}++const DEFAULT_NOISE: Record<string, NoiseField> = {+ moisture: { scale: 900, octaves: 4 },+ temperature: { scale: 2400, octaves: 3 },+ rock: { scale: 500, octaves: 4 },+};++/** A stable 32-bit hash of integers, as a number in [0, 1). */+export function hash01(...v: number[]): number {+ let h = 0x9e3779b9 | 0;+ for (const n of v) {+ h = Math.imul(h ^ (n | 0), 0x85ebca6b);+ h = (h ^ (h >>> 13)) | 0;+ h = Math.imul(h, 0xc2b2ae35);+ h = (h ^ (h >>> 16)) | 0;+ }+ return (h >>> 0) / 4294967296;+}++/** A stable hash of a string, for mixing a name into a seed. */+export function hashString(s: string): number {+ let h = 0x811c9dc5 | 0;+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193);+ return h | 0;+}++/** Fractal value noise, 0 to 1. */+export function fbm(x: number, z: number, seed: number, octaves: number): number {+ let sum = 0, norm = 0, amp = 1, freq = 1;+ for (let o = 0; o < octaves; o++) {+ sum += noised(x * freq, z * freq, seed + o * 131)[0] * amp;+ norm += amp;+ amp *= 0.5;+ freq *= 2;+ }+ return sum / norm;+}++/** Samples the environment. */+export class Environment {+ private readonly noise_: Record<string, NoiseField>;+ private readonly seeds_: Record<string, number> = {};++ constructor(readonly inputs: EnvironmentInputs) {+ this.noise_ = { ...DEFAULT_NOISE };+ for (const [name, f] of Object.entries(inputs.noise ?? {})) if (f) this.noise_[name] = f;+ for (const name of Object.keys(this.noise_)) this.seeds_[name] = (inputs.seed * 7919) ^ hashString(name);+ }++ /** Every field at (x, z). */+ sample(x: number, z: number): FieldValues {+ const g = this.inputs.ground(x, z);+ const at: FieldValues = {+ height: g ? g.y : NaN,+ up: g ? g.up : 1,+ slope: g ? 1 - g.up : 0,+ waterDepth: g && this.inputs.waterDepth ? this.inputs.waterDepth(x, z, g.y) ?? -Infinity : -Infinity,+ };+ for (const [name, f] of Object.entries(this.noise_)) {+ at[name] = fbm(x / Math.max(f.scale, 1e-6), z / Math.max(f.scale, 1e-6), this.seeds_[name]!, Math.max(1, f.octaves ?? 3));+ }+ for (const [name, f] of Object.entries(this.inputs.fields ?? {})) at[name] = f(x, z, at);+ for (const o of this.inputs.overrides?.(x, z) ?? []) {+ const base = at[o.field] ?? o.value;+ at[o.field] = base + (o.value - base) * Math.min(Math.max(o.weight, 0), 1);+ }+ return at;+ }+}diff --git a/sdk/src/worldgen/index.ts b/sdk/src/worldgen/index.tsnew file mode 100644index 000000000..871142cf9--- /dev/null+++ b/sdk/src/worldgen/index.ts@@ -0,0 +1,21 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+export {+ WorldGen, WorldZone, PlacedObject, ZoneShapeKind, WorldGens, WorldGenRes, WorldGenPlugin, worldGenPlugin,+ type WorldGenData, type WorldZoneData, type PlacedObjectData, type WorldGenStatus,+} from './worldgenPlugin';+export {+ registerWorldRules, worldRules, bandWeight,+ type WorldRules, type BiomeDef, type BiomeCondition, type BiomeRecipe, type Recipe, type RecipeMember, type PlacementLayer,+} from './rules';+export { WorldPlan, type Placement, type Group, type Rejection } from './plan';+export { Zones, zoneDistance, zoneWeight, zoneBounds, type ZoneDef, type ZoneShape } from './zones';+export { PlacementDiffs, type PlacementChange, type PlacementDiffsData } from './diffs';+export {+ Environment, fbm, hash01, hashString, type FieldValues, type FieldFn, type NoiseField, type EnvironmentInputs,+} from './fields';++// Importing this subpath INSTALLS generated worlds — see tilemap/index.ts. Their ground is the terrain's when the scene has one.+import { registerWorldGenSupport } from './worldgenSupport';++registerWorldGenSupport();diff --git a/sdk/src/worldgen/plan.ts b/sdk/src/worldgen/plan.tsnew file mode 100644index 000000000..29186128d--- /dev/null+++ b/sdk/src/worldgen/plan.ts@@ -0,0 +1,374 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file plan.ts+ * @brief Where everything in a world stands: biomes from the fields, groups from the recipes, layer by layer, the same whatever is+ * asked first.+ *+ * @details Every answer is a function of the world position, the seed and the rules, so a chunk placed before its neighbour and one+ * placed after it agree, and a server and a client agree.+ *+ * - Each layer has one candidate a cell of a grid `spacing` apart, jittered, with a priority drawn for it. A candidate takes+ * a biome by the weights there (so a border mixes), a recipe of that biome by its density, and must have ground, not be+ * too steep or under water, not be kept out by a zone, and keep clear of the footprints of the layers before it.+ * - Of two candidates of a layer whose groups would overlap, the one with the higher priority stands. Each candidate looks+ * only at its neighbours, so nothing depends on the order chunks are made in.+ * - A group's members are placed round its anchor and checked the same way; a member that cannot stand is left out.+ * - A group belongs to the chunk its anchor stands in, members and all, so a group across a chunk's edge is neither cut nor+ * placed twice.+ * - Ids are made of the layer, the grid cell, the recipe and the member, with their versions: never a position in a list.+ */+import { Environment, fbm, hash01, hashString, type FieldValues } from './fields';+import { bandWeight, type BiomeDef, type PlacementLayer, type Recipe, type RecipeMember, type WorldRules } from './rules';+import type { Zones } from './zones';++/** One thing placed. */+export interface Placement {+ /** Stable across loads, load orders and rule additions: what a save records. */+ id: string;+ /** The group it belongs to (its anchor's group). */+ group: string;+ layer: string;+ recipe: string;+ recipeVersion: number;+ member: string;+ biome: string;+ /** The highest-priority zone it stands in, if any. */+ zone: string | null;+ x: number;+ y: number;+ z: number;+ yaw: number;+ scale: number;+ /** The ground's normal under it, which an aligned one leans with. */+ normal: [number, number, number];+ attach: 'upright' | 'align';+ mesh: number;+ material: number;+ interactive: string | null;+ footprint: number;+ canopy: number;+}++/** Why a candidate or a member did not stand. */+export type Rejection = 'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict';++export interface Group {+ id: string;+ layer: string;+ x: number;+ z: number;+ /** How far its members reach from its anchor, footprints included. */+ radius: number;+ priority: number;+ anchor: Placement;+ members: Placement[];+}++interface Candidate {+ gx: number;+ gz: number;+ x: number;+ z: number;+ priority: number;+ biome: string;+ recipe: Recipe;+ radius: number;+ fields: FieldValues;+}++type Viable = { ok: true; candidate: Candidate } | { ok: false; reason: Rejection; detail?: string };++/** Entries a cache holds before it is emptied: a source walking for ever does not grow it without end. */+const CACHE_LIMIT = 40000;++function groupRadius(recipe: Recipe): number {+ let r = recipe.anchor.footprint;+ for (const m of recipe.members ?? []) r = Math.max(r, (m.ring?.[1] ?? 0) + m.footprint);+ return r;+}++const lerp = (range: readonly [number, number] | undefined, t: number, fallback: number): number =>+ range ? range[0] + (range[1] - range[0]) * t : fallback;++/** One world's plan. */+export class WorldPlan {+ private readonly worldHash_: number;+ private readonly recipes_ = new Map<string, Recipe>();+ private readonly layers_: { def: PlacementLayer; hash: number; maxRadius: number; recipes: Set<string> }[] = [];+ private readonly viable_ = new Map<string, Viable>();+ private readonly groups_ = new Map<string, Group | Rejection>();++ constructor(readonly rules: WorldRules, readonly env: Environment, readonly zones: Zones, readonly seed: number, readonly world: string) {+ this.worldHash_ = hashString(world) ^ seed;+ for (const r of rules.recipes) this.recipes_.set(r.id, r);+ for (const def of rules.layers) {+ const recipes = new Set<string>();+ for (const b of rules.biomes) for (const br of b.recipes) if (br.layer === def.id) recipes.add(br.recipe);+ let maxRadius = 0;+ for (const id of recipes) { const r = this.recipes_.get(id); if (r) maxRadius = Math.max(maxRadius, groupRadius(r)); }+ this.layers_.push({ def, hash: hashString(def.id), maxRadius, recipes });+ }+ }++ /** Forgets what was worked out: the ground, the water or the zones changed. */+ invalidate(): void {+ this.viable_.clear();+ this.groups_.clear();+ }++ /** The layer's index by id, or -1. */+ layerIndex(id: string): number {+ return this.layers_.findIndex((l) => l.def.id === id);+ }++ /** The weight of every biome that holds at (x, z), summing to 1 (empty where none does), heaviest first. */+ biomeWeights(x: number, z: number): { biome: string; weight: number }[] {+ const out: { biome: string; weight: number }[] = [];+ let sum = 0;+ for (const b of this.rules.biomes) {+ const w = this.biomeWeight(b, x, z);+ if (w > 0) { out.push({ biome: b.id, weight: w }); sum += w; }+ }+ // A zone that holds a biome takes the place over by its weight.+ for (const { zone, weight } of this.zones.at(x, z)) {+ if (!zone.biome) continue;+ for (const o of out) o.weight *= 1 - weight;+ sum = sum * (1 - weight) + weight;+ const had = out.find((o) => o.biome === zone.biome);+ if (had) had.weight += weight; else out.push({ biome: zone.biome, weight });+ break;+ }+ if (sum <= 0) return [];+ for (const o of out) o.weight /= sum;+ return out.filter((o) => o.weight > 0).sort((a, b) => b.weight - a.weight || (a.biome < b.biome ? -1 : 1));+ }++ /** The biome that holds most at (x, z), or null. */+ biomeAt(x: number, z: number): string | null {+ return this.biomeWeights(x, z)[0]?.biome ?? null;+ }++ /** The ground's paint at (x, z): `base` (grass, dirt, snow, rock) pulled toward each biome's paint by its weight and strength. */+ paint(x: number, z: number, base: readonly [number, number, number, number]): [number, number, number, number] {+ const out: [number, number, number, number] = [base[0], base[1], base[2], base[3]];+ for (const { biome, weight } of this.biomeWeights(x, z)) {+ const b = this.rules.biomes.find((d) => d.id === biome);+ if (!b?.paint) continue;+ const k = weight * Math.min(Math.max(b.paintStrength ?? 1, 0), 1);+ for (let c = 0; c < 4; c++) out[c] = out[c]! + (b.paint[c]! - base[c]!) * k;+ }+ const sum = out[0] + out[1] + out[2] + out[3] || 1;+ return [out[0] / sum, out[1] / sum, out[2] / sum, out[3] / sum];+ }++ /** The groups of layer `layer` whose anchors stand in [x0, x1) by [z0, z1). */+ groupsIn(layer: string, x0: number, z0: number, x1: number, z1: number): Group[] {+ const li = this.layerIndex(layer);+ if (li < 0) return [];+ const s = this.layers_[li]!.def.spacing;+ const out: Group[] = [];+ for (let gz = Math.floor(z0 / s); gz <= Math.floor(z1 / s); gz++) for (let gx = Math.floor(x0 / s); gx <= Math.floor(x1 / s); gx++) {+ const g = this.group(li, gx, gz);+ if (typeof g !== 'string' && g.x >= x0 && g.x < x1 && g.z >= z0 && g.z < z1) out.push(g);+ }+ return out;+ }++ /** Every placement of the given layers (all, by default) whose group's anchor stands in the square. */+ placementsIn(x0: number, z0: number, x1: number, z1: number, layers?: readonly string[]): Placement[] {+ const out: Placement[] = [];+ for (const l of this.layers_) {+ if (layers && !layers.includes(l.def.id)) continue;+ for (const g of this.groupsIn(l.def.id, x0, z0, x1, z1)) out.push(g.anchor, ...g.members);+ }+ return out;+ }++ /** How many candidates of a layer in the square stood, and why the rest did not. */+ stats(layer: string, x0: number, z0: number, x1: number, z1: number): Record<'placed' | Rejection, number> {+ const counts = { placed: 0, noBiome: 0, density: 0, noGround: 0, slope: 0, water: 0, zone: 0, occupied: 0, conflict: 0 };+ const li = this.layerIndex(layer);+ if (li < 0) return counts;+ const s = this.layers_[li]!.def.spacing;+ for (let gz = Math.floor(z0 / s); gz < Math.ceil(z1 / s); gz++) for (let gx = Math.floor(x0 / s); gx < Math.ceil(x1 / s); gx++) {+ const g = this.group(li, gx, gz);+ if (typeof g === 'string') counts[g]++; else counts.placed++;+ }+ return counts;+ }++ /** Everything that decided what stands at (x, z): the fields, the biomes, the zones, and each layer's candidate in that cell. */+ explain(x: number, z: number): {+ fields: FieldValues; biomes: { biome: string; weight: number }[]; zones: { id: string; kind: string; weight: number }[];+ layers: { layer: string; cell: [number, number]; group: string | null; rejected: Rejection | null; detail?: string }[];+ } {+ const layers = this.layers_.map((l, li) => {+ const gx = Math.floor(x / l.def.spacing), gz = Math.floor(z / l.def.spacing);+ const g = this.group(li, gx, gz);+ const v = this.viable(li, gx, gz);+ return {+ layer: l.def.id, cell: [gx, gz] as [number, number], group: typeof g === 'string' ? null : g.id,+ rejected: typeof g === 'string' ? g : null, detail: v.ok ? undefined : v.detail,+ };+ });+ return {+ fields: this.env.sample(x, z), biomes: this.biomeWeights(x, z),+ zones: this.zones.at(x, z).map(({ zone, weight }) => ({ id: zone.id, kind: zone.kind, weight })), layers,+ };+ }++ /** The group of layer `li` in grid cell (gx, gz), or why there is none. */+ group(li: number, gx: number, gz: number): Group | Rejection {+ const key = `${li}:${gx},${gz}`;+ const had = this.groups_.get(key);+ if (had !== undefined) return had;+ if (this.groups_.size > CACHE_LIMIT) this.groups_.clear();+ const made = this.makeGroup(li, gx, gz);+ this.groups_.set(key, made);+ return made;+ }++ private makeGroup(li: number, gx: number, gz: number): Group | Rejection {+ const v = this.viable(li, gx, gz);+ if (!v.ok) return v.reason;+ const c = v.candidate;+ const layer = this.layers_[li]!;+ const s = layer.def.spacing;+ // Of overlapping groups the higher priority stands; ties go to the lower cell, so every pair is settled one way.+ const reach = Math.ceil((c.radius + layer.maxRadius) / s);+ for (let dz = -reach; dz <= reach; dz++) for (let dx = -reach; dx <= reach; dx++) {+ if (dx === 0 && dz === 0) continue;+ const n = this.viable(li, gx + dx, gz + dz);+ if (!n.ok) continue;+ const o = n.candidate;+ const wins = o.priority > c.priority || (o.priority === c.priority && (o.gz < gz || (o.gz === gz && o.gx < gx)));+ if (wins && Math.hypot(o.x - c.x, o.z - c.z) < c.radius + o.radius) return 'conflict';+ }+ const groupId = `${layer.def.id}@${layer.def.version ?? 1}:${gx},${gz}`;+ const r = c.recipe;+ const anchor = this.place(groupId, layer.def, r, r.anchor, 0, c.x, c.z, c.biome, c.fields, 0)!;+ const members: Placement[] = [];+ const taken: Placement[] = [anchor];+ for (const [mi, m] of (r.members ?? []).entries()) {+ const h = (salt: number, k: number) => hash01(this.worldHash_, layer.hash, gx, gz, 1000 + mi * 37 + salt, k);+ const count = m.count ? m.count[0] + Math.floor(h(0, 0) * (m.count[1] - m.count[0] + 1)) : 1;+ for (let k = 0; k < count; k++) {+ if (m.chance !== undefined && h(1, k) >= m.chance) continue;+ const angle = lerp(m.arc, h(2, k), h(2, k) * 360) * Math.PI / 180;+ const dist = lerp(m.ring, h(3, k), 0);+ const x = c.x + Math.cos(angle) * dist, z = c.z + Math.sin(angle) * dist;+ const f = this.env.sample(x, z);+ if (this.standing(f, m) !== null) continue;+ if (this.zones.excluding(x, z, m.footprint, this.tagsOf(layer.def, r, m), this.seed) !== null) continue;+ if (this.occupied(li, x, z, m.footprint) !== null) continue;+ if (taken.some((t) => Math.hypot(t.x - x, t.z - z) < t.footprint + m.footprint)) continue;+ const p = this.place(groupId, layer.def, r, m, k, x, z, c.biome, f, h(4, k));+ if (!p) continue;+ members.push(p);+ taken.push(p);+ }+ }+ return { id: groupId, layer: layer.def.id, x: c.x, z: c.z, radius: c.radius, priority: c.priority, anchor, members };+ }++ private place(group: string, layer: PlacementLayer, r: Recipe, m: RecipeMember, k: number, x: number, z: number,+ biome: string, f: FieldValues, turn: number): Placement | null {+ if (!Number.isFinite(f.height!)) return null;+ const h = hash01(this.worldHash_, hashString(group), hashString(m.id), k, 7);+ const g = this.env.inputs.ground(x, z);+ const up = g?.up ?? 1;+ const n = g?.normal ?? [0, up, Math.sqrt(Math.max(0, 1 - up * up))];+ return {+ id: `${group}/${r.id}@${r.version}/${m.id}.${k}`, group, layer: layer.id, recipe: r.id, recipeVersion: r.version, member: m.id,+ biome, zone: this.zones.at(x, z)[0]?.zone.id ?? null,+ x, y: f.height!, z, yaw: (turn || h) * Math.PI * 2, scale: lerp(m.scale, hash01(this.worldHash_, hashString(group), k, 11), 1),+ normal: n, attach: m.attach ?? 'upright', mesh: typeof m.mesh === 'number' ? m.mesh : 0,+ material: typeof m.material === 'number' ? m.material : 0, interactive: m.interactive ?? null,+ footprint: m.footprint, canopy: m.canopy ?? m.footprint,+ };+ }++ /** Why a member cannot stand on the place whose fields are `f`, or null if it can. */+ private standing(f: FieldValues, m: RecipeMember): Rejection | null {+ if (!Number.isFinite(f.height!)) return 'noGround';+ if (f.up! < (m.minUp ?? 0)) return 'slope';+ if (f.waterDepth! > (m.waterDepth ?? 0)) return 'water';+ return null;+ }++ private tagsOf(layer: PlacementLayer, r: Recipe, m: RecipeMember): string[] {+ return [layer.id, r.id, m.interactive ? 'interactive' : 'decor', ...(r.tags ?? []), ...(m.tags ?? [])];+ }++ /** The candidate of layer `li` in cell (gx, gz) if it may stand before its own layer's overlaps are settled, or why not. */+ private viable(li: number, gx: number, gz: number): Viable {+ const key = `${li}:${gx},${gz}`;+ const had = this.viable_.get(key);+ if (had) return had;+ if (this.viable_.size > CACHE_LIMIT) this.viable_.clear();+ const made = this.makeViable(li, gx, gz);+ this.viable_.set(key, made);+ return made;+ }++ private makeViable(li: number, gx: number, gz: number): Viable {+ const layer = this.layers_[li]!;+ const s = layer.def.spacing;+ const h = (salt: number) => hash01(this.worldHash_, layer.hash, gx, gz, salt);+ const x = (gx + h(1)) * s, z = (gz + h(2)) * s;+ const weights = this.biomeWeights(x, z);+ if (weights.length === 0) return { ok: false, reason: 'noBiome' };+ // A biome by its weight here, so where two meet their recipes mix rather than stopping on a line.+ let u = h(3), biome = weights[weights.length - 1]!.biome;+ for (const w of weights) { if (u < w.weight) { biome = w.biome; break; } u -= w.weight; }+ const def = this.rules.biomes.find((b) => b.id === biome);+ const choices = (def?.recipes ?? []).filter((br) => br.layer === layer.def.id && this.recipes_.has(br.recipe));+ let v = h(4), recipe: Recipe | null = null;+ for (const br of choices) { if (v < br.density) { recipe = this.recipes_.get(br.recipe)!; break; } v -= br.density; }+ if (!recipe) return { ok: false, reason: 'density' };+ const f = this.env.sample(x, z);+ const why = this.standing(f, recipe.anchor);+ if (why) return { ok: false, reason: why };+ const zone = this.zones.excluding(x, z, recipe.anchor.footprint, this.tagsOf(layer.def, recipe, recipe.anchor), this.seed);+ if (zone) return { ok: false, reason: 'zone', detail: zone.id };+ const blocker = this.occupied(li, x, z, recipe.anchor.footprint);+ if (blocker) return { ok: false, reason: 'occupied', detail: blocker };+ return { ok: true, candidate: { gx, gz, x, z, priority: h(5), biome, recipe, radius: groupRadius(recipe), fields: f } };+ }++ /** The id of a placement of an earlier layer whose footprint a footprint of `radius` at (x, z) would overlap, or null. */+ private occupied(li: number, x: number, z: number, radius: number): string | null {+ for (let lj = 0; lj < li; lj++) {+ const l = this.layers_[lj]!;+ if (l.def.occupies === false) continue;+ const s = l.def.spacing, reach = radius + l.maxRadius;+ for (let gz = Math.floor((z - reach) / s); gz <= Math.floor((z + reach) / s); gz++) {+ for (let gx = Math.floor((x - reach) / s); gx <= Math.floor((x + reach) / s); gx++) {+ const g = this.group(lj, gx, gz);+ if (typeof g === 'string') continue;+ for (const p of [g.anchor, ...g.members]) if (Math.hypot(p.x - x, p.z - z) < p.footprint + radius) return p.id;+ }+ }+ }+ return null;+ }++ private biomeWeight(b: BiomeDef, x: number, z: number): number {+ // The edge wanders: the fields are read a little way off, by noise of the biome's own.+ const t = b.transition ?? 0;+ let sx = x, sz = z;+ if (t > 0) {+ const k = hashString(b.id) ^ this.worldHash_;+ sx += (fbm(x / t, z / t, k, 2) - 0.5) * 2 * t;+ sz += (fbm(x / t, z / t, k + 1, 2) - 0.5) * 2 * t;+ }+ const f = this.env.sample(sx, sz);+ let w = b.weight ?? 1;+ for (const c of b.conditions) {+ w *= bandWeight(c, f[c.field] ?? NaN);+ if (w <= 0) return 0;+ }+ return w;+ }+}diff --git a/sdk/src/worldgen/rules.ts b/sdk/src/worldgen/rules.tsnew file mode 100644index 000000000..cea2d8d73--- /dev/null+++ b/sdk/src/worldgen/rules.ts@@ -0,0 +1,139 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file rules.ts+ * @brief What a game says its worlds are made of: biomes, the recipes that stand in them, and the layers they are placed in.+ *+ * @details The engine places; the game rules; the artists make the recipes. A rule set is registered under an id and named by a+ * `WorldGen` component with its version, as a terrain names its provider, and a saved world keeps the version it was made+ * with.+ *+ * - A biome is a weight over the fields: each condition a band of one field with soft edges, multiplied. Where several hold+ * their weights are mixed, its edge wanders by `transition` world units of noise so no border is ruled, and it says how+ * the ground is painted and which recipes stand in it, in which layer and how densely.+ * - A recipe is a group an artist composed: an anchor (a big tree, a main rock) and members placed round it within ranges+ * (a ring of distances, an arc of angles, a count, a scale), each with its footprint (what it takes on the ground: a+ * trunk) apart from its canopy, how it stands on the ground and how steep it may stand, and whether it may be left out.+ * - A layer is a pass of placement: big things first. Each takes its candidates on a jittered grid `spacing` apart, keeps+ * clear of the footprints of the layers before it, and is published in chunks out to `drawDistance`.+ */+import type { FieldFn, NoiseField } from './fields';++/** A band of one field with soft edges: full weight between `min` and `max`, fading to none over `blend` past each. */+export interface BiomeCondition { field: string; min?: number; max?: number; blend?: number }++/** What stands in a biome: a recipe, the layer it is placed in, and the share of that layer's candidates it takes (0 to 1). */+export interface BiomeRecipe { recipe: string; layer: string; density: number }++export interface BiomeDef {+ id: string;+ conditions: readonly BiomeCondition[];+ /** A multiplier on its weight, to favour it where it ties. */+ weight?: number;+ /** How far its edge wanders, in world units. */+ transition?: number;+ /** How the ground is painted where it holds: grass, dirt, snow, rock; and how much of the ground's own paint it replaces. */+ paint?: readonly [number, number, number, number];+ paintStrength?: number;+ recipes: readonly BiomeRecipe[];+}++/** One kind of thing in a recipe. */+export interface RecipeMember {+ /** Stable within the recipe: part of every placement's id. */+ id: string;+ /** The mesh it is drawn with, and the material: an asset path (as a recipe file names them) or a handle already loaded. */+ mesh: number | string;+ material?: number | string;+ /** What a game interacts with it as (ore, tree to fell); absent, it is decoration and drawn merged with its chunk. */+ interactive?: string;+ /** How many of it (the anchor is always one). */+ count?: readonly [number, number];+ /** How far from the anchor and at what angles (degrees, from +x toward +z), for a member. */+ ring?: readonly [number, number];+ arc?: readonly [number, number];+ scale?: readonly [number, number];+ /** What it takes on the ground (a trunk): nothing else stands within it. */+ footprint: number;+ /** How far it spreads overhead (a crown), for what is kept clear of view; the footprint when absent. */+ canopy?: number;+ /** Upright, or leaning with the ground. */+ attach?: 'upright' | 'align';+ /** The least the ground may face up for it to stand (0 to 1). */+ minUp?: number;+ /** How deep in water it may stand (reeds); 0 keeps it on dry ground. */+ waterDepth?: number;+ /** The chance it is placed at all, for a member that may be left out. */+ chance?: number;+ /** Tags a zone may keep it out by, beside its recipe's. */+ tags?: readonly string[];+}++export interface Recipe {+ id: string;+ /** Bumped when the recipe changes what it places: part of every placement's id. */+ version: number;+ tags?: readonly string[];+ anchor: RecipeMember;+ members?: readonly RecipeMember[];+}++export interface PlacementLayer {+ id: string;+ /** Bumped when the layer's placement changes: part of every placement's id. */+ version?: number;+ /** The distance between candidates: about the distance between groups where the layer is full. */+ spacing: number;+ /** How far from the streaming sources the layer is published, and the side of its chunks. */+ drawDistance: number;+ chunkSize?: number;+ /** Whether later layers keep clear of its footprints (default true). */+ occupies?: boolean;+}++/** A game's rules for laying out a world. */+export interface WorldRules {+ id: string;+ /** The versions it can still make; a world names one. */+ versions: readonly number[];+ biomes: readonly BiomeDef[];+ recipes: readonly Recipe[];+ /** In order: each keeps clear of the layers before it. */+ layers: readonly PlacementLayer[];+ noise?: Partial<Record<string, NoiseField>>;+ fields?: Record<string, FieldFn>;+}++const rules_ = new Map<string, WorldRules>();+let revision_ = 0;++/**+ * Makes `rules` available to every WorldGen that names them; a second set under the same id replaces the first. A WorldGen waiting+ * for its rules (a script registers them after the scene loaded) is laid out once they are here.+ */+export function registerWorldRules(rules: WorldRules): void {+ rules_.set(rules.id, rules);+ revision_++;+}++/** @internal Bumped on every registration, so what named rules that were missing asks again. */+export function worldRulesRevision(): number {+ return revision_;+}++export function worldRules(id: string): WorldRules | undefined {+ return rules_.get(id);+}++/** The weight of a soft band at `v`. */+export function bandWeight(c: BiomeCondition, v: number): number {+ if (!Number.isFinite(v)) return 0;+ const blend = Math.max(c.blend ?? 0, 1e-9);+ const edge = (d: number): number => {+ if (d <= 0) return 1;+ if (d >= blend) return 0;+ const t = 1 - d / blend;+ return t * t * (3 - 2 * t);+ };+ return edge(c.min !== undefined ? c.min - v : -1) * edge(c.max !== undefined ? v - c.max : -1);+}diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.tsnew file mode 100644index 000000000..2c640d05b--- /dev/null+++ b/sdk/src/worldgen/worldgenPlugin.ts@@ -0,0 +1,560 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file worldgenPlugin.ts+ * @brief A generated world in the scene: a `WorldGen` names the game's rules, `WorldZone`s plan it, and what the rules place is+ * published in chunks round the streaming sources.+ *+ * @details One plan (plan.ts) a WorldGen, read from the terrain's surface and the water, and laid over by the world's changes+ * (diffs.ts) before anything is shown. Each of the rules' layers is a layer of procedural chunks (residency/chunks.ts), so+ * it is made nearest first within the frame's budget, let go past its `drawDistance`, and made again with its old chunk kept+ * until then when the ground or the water changes; a zone or a change touches only the chunks it reaches.+ *+ * - Decoration is drawn merged: a mesh a chunk for each kind of plant or stone in it.+ * - What a game interacts with is an entity of its own, carrying a `PlacedObject` with its placement id and kind, so the+ * game can find it, act on it and record what it did (`diffs.remove(id)` when it is felled).+ * - The ground is painted by the biomes, when the WorldGen says so.+ *+ * A server without a renderer makes the plan and the interactive entities, and nothing that is only drawn.+ */+import type { App, Plugin } from '../app/app';+import { defineSystem, Schedule } from '../ecs/system';+import { defineResource } from '../ecs/resource';+import {+ defineComponent, MeshRenderer, RuntimeOnly, Transform,+ type ComponentDef, type MeshRendererData, type TransformData,+} from '../ecs/component';+import { Assets } from '../asset/AssetPlugin';+import type { MeshData } from '../asset/meshFormat';+import { log } from '../util/logger';+import type { Entity } from '../types';+import { TerrainsRes } from '../terrain/terrainPlugin';+import { buildInstancedMesh, type Plant } from '../foliage/builder';+import { chunksOf, ProceduralChunksRes, type ChunkLayerStatus } from '../residency/chunks';+import { Environment } from './fields';+import { WorldPlan, type Placement } from './plan';+import { worldRules, worldRulesRevision, type RecipeMember, type WorldRules } from './rules';+import { Zones, type ZoneDef } from './zones';+import { PlacementDiffs } from './diffs';++/** The fields of the `WorldGen` component. @experimental */+export interface WorldGenData {+ /** The rules the world is laid out by, as the game registered them, and the version of them the world was made with. */+ rules: string;+ version: number;+ /** The world (a planet, a level) as the game names it, and its seed. */+ world: string;+ seed: number;+ /** Whether the biomes paint the terrain. */+ paintGround: boolean;+}++/**+ * A generated world: the rules it is laid out by. Presence is the opt-in; what the rules place is published as its children.+ *+ * @experimental+ */+export const WorldGen: ComponentDef<WorldGenData> = defineComponent<WorldGenData>('WorldGen', {+ rules: '', version: 1, world: '', seed: 1, paintGround: true,+}, {+ fields: {+ rules: { tooltip: 'The rules the world is laid out by, as the game registered them with registerWorldRules.' },+ version: { min: 1, step: 1, tooltip: 'The version of the rules the world was made with. A version the rules no longer have fails the world rather than laying out another one.' },+ world: { tooltip: 'The world (a planet, a level) as the game names it.' },+ seed: { step: 1, tooltip: 'Another seed lays out another world by the same rules.' },+ paintGround: { tooltip: 'Whether the biomes paint the terrain.' },+ },+});++/** How a `WorldZone` is shaped. */+export const ZoneShapeKind = { Circle: 0, Box: 1 } as const;++/** The fields of the `WorldZone` component. @experimental */+export interface WorldZoneData {+ /** What the zone is for (home, road, landing, building, resource, view): the game's own words. */+ kind: string;+ shape: number;+ radius: number;+ sizeX: number;+ sizeZ: number;+ /** Over how many world units past its outline it fades out. */+ falloff: number;+ priority: number;+ /** The tags of what it keeps out, separated by commas; `*` keeps out everything. */+ excludes: string;+ /** A biome it holds over its area; empty holds none. */+ biome: string;+}++/**+ * An area of a generated world planned by hand: kept clear, held to a biome, or both. It follows its entity's position and its turn+ * about the vertical.+ *+ * @experimental+ */+export const WorldZone: ComponentDef<WorldZoneData> = defineComponent<WorldZoneData>('WorldZone', {+ kind: 'reserve', shape: ZoneShapeKind.Circle, radius: 10, sizeX: 20, sizeZ: 20, falloff: 4, priority: 0, excludes: '*', biome: '',+}, {+ fields: {+ kind: { tooltip: 'What the zone is for (home, road, landing, building, resource, view): the game\'s own words.' },+ shape: { enum: [{ label: 'Circle', value: ZoneShapeKind.Circle }, { label: 'Box', value: ZoneShapeKind.Box }] },+ radius: { min: 0, shownWhen: { field: 'shape', values: [ZoneShapeKind.Circle] }, tooltip: 'The circle\'s radius, in world units.' },+ sizeX: { min: 0, shownWhen: { field: 'shape', values: [ZoneShapeKind.Box] }, tooltip: 'The box\'s size along its own x.' },+ sizeZ: { min: 0, shownWhen: { field: 'shape', values: [ZoneShapeKind.Box] }, tooltip: 'The box\'s size along its own z.' },+ falloff: { min: 0, tooltip: 'Over how many world units past the outline the zone fades out: what it keeps out thins there.' },+ priority: { step: 1, tooltip: 'Where zones overlap, the higher priority holds the biome.' },+ excludes: { tooltip: 'The tags of what the zone keeps out, separated by commas (a layer, a recipe, its tags, decor, interactive); * keeps out everything; empty keeps nothing out.' },+ biome: { tooltip: 'A biome the zone holds over its area; empty holds none.' },+ },+});++/** The fields of the `PlacedObject` component. @experimental */+export interface PlacedObjectData {+ /** The placement's id: what a save records when the game changes it. */+ id: string;+ /** What the game interacts with it as. */+ kind: string;+}++/**+ * Marks an entity a generated world placed for the game to interact with. Written by the engine; a scene does not author it.+ *+ * @experimental+ */+export const PlacedObject: ComponentDef<PlacedObjectData> = defineComponent<PlacedObjectData>('PlacedObject', { id: '', kind: '' });++/** Where a WorldGen stands: being made, ready, or failed (with why); and each of its layers' chunks. */+export interface WorldGenStatus {+ state: 'loading' | 'ready' | 'failed';+ reason?: string;+ layers: Record<string, ChunkLayerStatus>;+}++interface BuiltWorld {+ signature: string;+ data: WorldGenData;+ rules: WorldRules | null;+ plan: WorldPlan | null;+ failure: string | null;+ /** The terrain's and the water's revisions the plan was read from. */+ ground: string;+ /** The zones' revision the authored zones were last synced at. */+ authored: Set<string>;+}++/** A chunk of a layer: what it places (its decoration merged by mesh, its interactive placements), and what it put in the world. */+interface PlacedChunk {+ decor: { mesh: number; material: number; data: MeshData; origin: [number, number, number] }[];+ objects: Placement[];+ entities: Entity[];+ meshes: number[];+}++/** 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; 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;+ return w && typeof w.depthAt === 'function' ? w as WaterQuery : null;+}++const layerIdOf = (entity: Entity, layer: string): string => `worldgen:${entity}:${layer}`;+const zoneIdOf = (entity: Entity): string => `zone:${entity}`;++/** Run-time access to the generated worlds. */+export class WorldGens {+ /** @internal */ readonly built_ = new Map<Entity, BuiltWorld>();+ /** @internal */ app_: App | null = null;+ private readonly zones_ = new Map<string, Zones>();+ private readonly diffs_ = new Map<string, PlacementDiffs>();+ /** @internal The interactive entity of each placement id published now. */+ readonly objects_ = new Map<string, Entity>();++ /** The zones of a world (by its name), which a game adds to as it plans and builds. Shared by every WorldGen of that world. */+ zones(world = this.first_()?.data.world ?? ''): Zones {+ let z = this.zones_.get(world);+ if (!z) { z = new Zones(); this.zones_.set(world, z); }+ return z;+ }++ /** The changes made to a world (by its name), which a save stores and reads back. */+ diffs(world = this.first_()?.data.world ?? ''): PlacementDiffs {+ let d = this.diffs_.get(world);+ if (!d) { d = new PlacementDiffs(); this.diffs_.set(world, d); }+ return d;+ }++ /** A WorldGen's plan, or the first one's: what stands where, asked of anywhere, loaded or not. Null until it is made or if it failed. */+ plan(entity?: Entity): WorldPlan | null {+ return (entity !== undefined ? this.built_.get(entity) : this.first_())?.plan ?? null;+ }++ /** The interactive entity standing for placement `id`, or null where its chunk is not published or the placement is removed. */+ objectOf(id: string): Entity | null {+ return this.objects_.get(id) ?? null;+ }++ status(entity: Entity): WorldGenStatus | null {+ const built = this.built_.get(entity);+ if (!built) return null;+ const layers: Record<string, ChunkLayerStatus> = {};+ const chunks = this.app_?.hasResource(ProceduralChunksRes) ? this.app_.getResource(ProceduralChunksRes) : null;+ for (const l of built.rules?.layers ?? []) {+ const s = chunks?.status(layerIdOf(entity, l.id));+ if (s) layers[l.id] = s;+ }+ if (built.failure) return { state: 'failed', reason: built.failure, layers };+ return { state: built.plan ? 'ready' : 'loading', layers };+ }++ private first_(): BuiltWorld | undefined {+ return this.built_.values().next().value;+ }+}++/** The resource the plugin installs. @experimental */+export const WorldGenRes = defineResource<WorldGens>(new WorldGens(), 'WorldGens');++export class WorldGenPlugin implements Plugin {+ name = 'worldgen';++ /** Each mesh's geometry, read once, for drawing it merged. */+ private readonly meshData_ = new Map<number, MeshData | null | Promise<MeshData | null>>();++ build(app: App): void {+ const gens = new WorldGens();+ gens.app_ = app;+ app.insertResource(WorldGenRes, gens);+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ this.sweep(app, gens);+ for (const entity of app.world.getEntitiesWithComponents([WorldGen, Transform])) {+ const data = app.world.get(entity, WorldGen) as WorldGenData;+ const signature = `${JSON.stringify(data)}#${worldRulesRevision()}`;+ let built = gens.built_.get(entity);+ if (!built || built.signature !== signature) {+ built = this.make(app, gens, entity, data, built);+ gens.built_.set(entity, built);+ }+ this.syncZones(app, gens, entity, built);+ this.publish(app, gens, entity, built);+ }+ }, { name: 'WorldGenSystem' }));+ }++ cleanup(app?: App): void {+ if (!app?.hasResource(WorldGenRes)) return;+ const gens = app.getResource(WorldGenRes);+ for (const entity of [...gens.built_.keys()]) this.drop(app, gens, entity);+ }++ /** A WorldGen's rules and plan, or why it has none. */+ private make(app: App, gens: WorldGens, entity: Entity, data: WorldGenData, had: BuiltWorld | undefined): BuiltWorld {+ const built: BuiltWorld = { signature: `${JSON.stringify(data)}#${worldRulesRevision()}`, data: { ...data }, rules: null, plan: null, failure: null, ground: '', authored: had?.authored ?? new Set() };+ const rules = worldRules(data.rules);+ if (!rules) built.failure = `no world rules ${data.rules || '(none named)'} are registered`;+ else if (!rules.versions.includes(data.version)) built.failure = `the world rules ${rules.id} have no version ${data.version} (they have ${rules.versions.join(', ')})`;+ else built.rules = rules;+ if (built.failure) {+ log.error('worldgen', `the world ${data.world} cannot be laid out: ${built.failure}`);+ // A world that cannot be laid out shows nothing of the one before it.+ for (const l of had?.rules?.layers ?? []) chunksOf(app).remove(layerIdOf(entity, l.id));+ return built;+ }+ // Layers the new rules no longer have are let go; the ones they keep keep their chunks until they are made again.+ for (const l of had?.rules?.layers ?? []) if (!rules!.layers.some((n) => n.id === l.id)) chunksOf(app).remove(layerIdOf(entity, l.id));+ // Recipes name their meshes and materials by path: with a renderer they are loaded first, and the plan is made with them.+ const refs = assetRefsOf(rules!);+ if (refs.length > 0 && app.hasResource(Assets)) {+ void this.resolve(app, rules!, refs).then((resolved) => {+ if (gens.built_.get(entity) !== built) return;+ built.rules = resolved;+ this.plan(app, gens, entity, built, resolved);+ }, (e: unknown) => {+ built.failure = `the recipes' assets could not be loaded: ${e instanceof Error ? e.message : String(e)}`;+ log.error('worldgen', built.failure);+ });+ return built;+ }+ this.plan(app, gens, entity, built, rules!);+ return built;+ }++ /** Loads the meshes and materials `refs` name, and gives back the rules with each path replaced by its handle. */+ private async resolve(app: App, rules: WorldRules, refs: { kind: 'mesh' | 'material'; ref: string }[]): Promise<WorldRules> {+ const assets = app.getResource(Assets);+ const handles = new Map<string, number>();+ await Promise.all(refs.map(async ({ kind, ref }) => {+ const handle = kind === 'mesh' ? (await assets.load<{ handle: number }>('mesh', ref)).handle : (await assets.loadMaterial(ref)).handle;+ handles.set(`${kind}:${ref}`, handle);+ }));+ const member = (m: RecipeMember): RecipeMember => ({+ ...m,+ mesh: typeof m.mesh === 'string' ? handles.get(`mesh:${m.mesh}`) ?? 0 : m.mesh,+ material: typeof m.material === 'string' ? handles.get(`material:${m.material}`) ?? 0 : m.material,+ });+ return { ...rules, recipes: rules.recipes.map((r) => ({ ...r, anchor: member(r.anchor), members: r.members?.map(member) })) };+ }++ /** Makes a WorldGen's plan from its rules, and what keeps it current. */+ private plan(app: App, gens: WorldGens, entity: Entity, built: BuiltWorld, rules: WorldRules): void {+ const data = built.data;+ const terrains = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;+ const zones = gens.zones(data.world);+ const env = new Environment({+ seed: data.seed, noise: rules.noise, fields: 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,+ 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;+ },+ });+ built.plan = new WorldPlan(rules, env, zones, data.seed, data.world);+ const plan = built.plan;+ // A zone that changes, or a placement a player changes, makes again only the chunks it reaches.+ zones.onChange = (bounds, zone) => {+ plan.invalidate();+ const chunks = chunksOf(app);+ for (const l of rules.layers) {+ // A group kept out lets a neighbour it had beaten stand, which may beat its own: a few cells round are made again.+ const reach = l.spacing * 3;+ chunks.invalidate(layerIdOf(entity, l.id), bounds[0] - reach, bounds[1] - reach, bounds[2] + reach, bounds[3] + reach);+ }+ // A zone that holds a biome or sets a field changes the ground's paint under it.+ if (terrains && data.paintGround && (zone.biome || zone.fields)) terrains.repaint();+ };+ gens.diffs(data.world).onChange = (id) => {+ const at = this.anchorOf(plan, id);+ if (at) chunksOf(app).invalidate(layerIdOf(entity, at.layer), at.x, at.z, at.x, at.z);+ };+ if (terrains) terrains.setPaint(data.paintGround ? this.painter(plan) : null);+ }++ /** The ground's paint by a plan's biomes. */+ private painter(plan: WorldPlan) {+ return (x: number, z: number, _h: number, _ny: number, w: [number, number, number, number]) => plan.paint(x, z, w);+ }++ /** Where the group of placement `id` is anchored, from the layer and grid cell its id names. */+ private anchorOf(plan: WorldPlan, id: string): { layer: string; x: number; z: number } | null {+ const m = /^(.+)@\d+:(-?\d+),(-?\d+)\//.exec(id);+ if (!m) return null;+ const li = plan.layerIndex(m[1]!);+ if (li < 0) return null;+ const g = plan.group(li, Number(m[2]), Number(m[3]));+ return typeof g === 'string' ? null : { layer: m[1]!, x: g.x, z: g.z };+ }++ /** Puts the authored `WorldZone`s into their world's zones. */+ private syncZones(app: App, gens: WorldGens, _entity: Entity, built: BuiltWorld): void {+ const zones = gens.zones(built.data.world);+ const seen = new Set<string>();+ for (const e of app.world.getEntitiesWithComponents([WorldZone, Transform])) {+ const z = app.world.get(e, WorldZone) as WorldZoneData;+ const t = app.world.get(e, Transform) as TransformData;+ const p = t.worldPosition, q = t.worldRotation;+ const yaw = Math.atan2(2 * (q.w * q.y + q.x * q.z), 1 - 2 * (q.y * q.y + q.z * q.z));+ const def: ZoneDef = {+ id: zoneIdOf(e), kind: z.kind, falloff: z.falloff, priority: z.priority,+ shape: z.shape === ZoneShapeKind.Box+ ? { type: 'rect', x: p.x, z: p.z, halfX: z.sizeX / 2, halfZ: z.sizeZ / 2, yaw: -yaw }+ : { type: 'circle', x: p.x, z: p.z, radius: z.radius },+ excludes: z.excludes.split(',').map((s) => s.trim()).filter(Boolean),+ ...(z.biome ? { biome: z.biome } : {}),+ };+ zones.set(def);+ seen.add(def.id);+ }+ for (const id of built.authored) if (!seen.has(id)) zones.delete(id);+ built.authored = seen;+ }++ /** Hands each of the rules' layers to the chunks, made from the plan. */+ private publish(app: App, gens: WorldGens, entity: Entity, built: BuiltWorld): void {+ const plan = built.plan, rules = built.rules;+ if (!plan || !rules) return;+ const terrains = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;+ const water = waterOf(app);+ // What the plan read the ground and the water from: when either changes everything is read again.+ const ground = `${terrains?.revision_ ?? 0}:${water?.revision_ ?? 0}`;+ if (ground !== built.ground) { plan.invalidate(); built.ground = ground; }+ const waiting = !!terrains?.loading || !!water?.baking;+ const diffs = gens.diffs(built.data.world);+ const rendering = app.hasResource(Assets);+ const chunks = chunksOf(app);+ for (const layer of rules.layers) {+ const size = layer.chunkSize ?? 64;+ chunks.set<PlacedChunk>(layerIdOf(entity, layer.id), {+ label: 'Laying out the world',+ originX: 0, originZ: 0, sizeX: size, sizeZ: size, extent: null,+ loadRadius: layer.drawDistance, unloadRadius: layer.drawDistance + size,+ generation: `${built.signature}:${ground}`,+ make: (cx, cz) => {+ const x0 = cx * size, z0 = cz * size;+ if (waiting || (terrains && ![[x0, z0], [x0 + size, z0], [x0, z0 + size], [x0 + size, z0 + size]].every(([x, z]) => terrains.groundKnownAt(x!, z!)))) return null;+ return this.chunk(app, plan, diffs, layer.id, x0, z0, size, rendering);+ },+ publish: (_cx, _cz, value) => this.place(app, gens, entity, value),+ release: (_cx, _cz, value) => this.unplace(app, gens, value),+ });+ }+ }++ /** What one chunk of a layer places: its decoration merged by mesh, and its interactive placements, with the changes laid over. */+ private chunk(app: App, plan: WorldPlan, diffs: PlacementDiffs, layer: string, x0: number, z0: number, size: number,+ rendering: boolean): PlacedChunk | Promise<PlacedChunk> {+ const placements: Placement[] = [];+ for (const p of plan.placementsIn(x0, z0, x0 + size, z0 + size, [layer])) {+ if (diffs.isRemoved(p.id)) continue;+ const c = diffs.changeOf(p.id);+ placements.push(c ? { ...p, ...c } : p);+ }+ const objects = placements.filter((p) => p.interactive !== null);+ const decor = rendering ? placements.filter((p) => p.interactive === null && p.mesh) : [];+ const meshes = [...new Set(decor.map((p) => p.mesh))];+ const finish = (): PlacedChunk => {+ const out: PlacedChunk = { decor: [], objects, entities: [], meshes: [] };+ const byKind = new Map<string, Placement[]>();+ for (const p of decor) {+ const k = `${p.mesh}:${p.material}`;+ let list = byKind.get(k);+ if (!list) byKind.set(k, list = []);+ list.push(p);+ }+ const origin: [number, number, number] = [x0 + size / 2, 0, z0 + size / 2];+ for (const list of byKind.values()) {+ const source = this.meshData_.get(list[0]!.mesh);+ if (!source || source instanceof Promise) continue;+ const plants: Plant[] = list.map((p, i) => ({+ x: p.x - origin[0], y: p.y, z: p.z - origin[2], yaw: p.yaw, scale: p.scale, phase: (i * 0.618) % 1, shade: 1,+ }));+ out.decor.push({ mesh: list[0]!.mesh, material: list[0]!.material, data: buildInstancedMesh(source, plants), origin });+ }+ return out;+ };+ const missing = meshes.filter((m) => !this.meshData_.has(m) || this.meshData_.get(m) instanceof Promise);+ if (missing.length === 0) return finish();+ const assets = app.getResource(Assets);+ return Promise.all(missing.map((m) => {+ let got = this.meshData_.get(m);+ if (got === undefined) {+ const read = assets.readMeshData(m).catch(() => null).then((d) => {+ if (!d) log.warn('worldgen', `the geometry of mesh ${m} cannot be read, so what it draws is left out`);+ this.meshData_.set(m, d);+ return d;+ });+ this.meshData_.set(m, read);+ got = read;+ }+ return got;+ })).then(finish);+ }++ /** Puts a chunk in the world: a mesh a kind of decoration, an entity an interactive placement. */+ private place(app: App, gens: WorldGens, parent: Entity, chunk: PlacedChunk): void {+ const world = app.world;+ if (!world.valid(parent)) return;+ const base = (world.get(parent, Transform) as TransformData).worldPosition;+ const assets = app.hasResource(Assets) ? app.getResource(Assets) : null;+ for (const d of chunk.decor) {+ const handle = assets?.createMesh(d.data) ?? 0;+ if (!handle) continue;+ chunk.meshes.push(handle);+ const e = world.spawn('WorldGenDecor');+ // Made again from the rules whenever its chunk is: a scene or a save never holds it.+ world.insert(e, RuntimeOnly);+ world.insert(e, Transform, { position: { x: d.origin[0] - base.x, y: -base.y, z: d.origin[2] - base.z } });+ world.insert(e, MeshRenderer, {+ mesh: handle, material: d.material, lit: true, opaque: true, cullBackfaces: false, color: { r: 1, g: 1, b: 1, a: 1 },+ } as Partial<MeshRendererData>);+ world.setParent(e, parent);+ chunk.entities.push(e);+ }+ for (const p of chunk.objects) {+ const e = world.spawn(`${p.interactive} ${p.id}`);+ world.insert(e, RuntimeOnly);+ world.insert(e, Transform, {+ position: { x: p.x - base.x, y: p.y - base.y, z: p.z - base.z },+ rotation: orientation(p),+ scale: { x: p.scale, y: p.scale, z: p.scale },+ });+ if (assets && p.mesh) {+ world.insert(e, MeshRenderer, {+ mesh: p.mesh, material: p.material, lit: true, opaque: true, color: { r: 1, g: 1, b: 1, a: 1 },+ } as Partial<MeshRendererData>);+ }+ world.insert(e, PlacedObject, { id: p.id, kind: p.interactive! });+ world.setParent(e, parent);+ chunk.entities.push(e);+ gens.objects_.set(p.id, e);+ }+ }++ private unplace(app: App, gens: WorldGens, chunk: PlacedChunk): void {+ const mine = new Set(chunk.entities);+ for (const p of chunk.objects) if (mine.has(gens.objects_.get(p.id)!)) gens.objects_.delete(p.id);+ for (const e of chunk.entities) if (app.world.valid(e)) app.world.despawn(e);+ const assets = app.hasResource(Assets) ? app.getResource(Assets) : null;+ for (const h of chunk.meshes) assets?.releaseBuiltMesh(h);+ chunk.entities.length = 0;+ chunk.meshes.length = 0;+ }++ private drop(app: App, gens: WorldGens, entity: Entity): void {+ const built = gens.built_.get(entity);+ if (app.hasResource(ProceduralChunksRes)) {+ for (const l of built?.rules?.layers ?? []) app.getResource(ProceduralChunksRes).remove(layerIdOf(entity, l.id));+ }+ if (built && app.hasResource(TerrainsRes)) app.getResource(TerrainsRes).setPaint(null);+ gens.built_.delete(entity);+ }++ private sweep(app: App, gens: WorldGens): void {+ for (const entity of [...gens.built_.keys()]) {+ if (app.world.valid(entity) && app.world.has(entity, WorldGen)) continue;+ this.drop(app, gens, entity);+ }+ }+}++/** The meshes and materials a rule set's recipes name by path. */+function assetRefsOf(rules: WorldRules): { kind: 'mesh' | 'material'; ref: string }[] {+ const seen = new Map<string, { kind: 'mesh' | 'material'; ref: string }>();+ for (const r of rules.recipes) for (const m of [r.anchor, ...(r.members ?? [])]) {+ if (typeof m.mesh === 'string' && m.mesh) seen.set(`mesh:${m.mesh}`, { kind: 'mesh', ref: m.mesh });+ if (typeof m.material === 'string' && m.material) seen.set(`material:${m.material}`, { kind: 'material', ref: m.material });+ }+ return [...seen.values()];+}++/** A placement's turn: about the vertical, and leaning with the ground when it is aligned. */+function orientation(p: Placement): { x: number; y: number; z: number; w: number } {+ const half = p.yaw / 2;+ const yawQ = { x: 0, y: Math.sin(half), z: 0, w: Math.cos(half) };+ if (p.attach !== 'align') return yawQ;+ // The turn that takes up to the normal, after the yaw.+ const [nx, ny, nz] = p.normal;+ const ax = nz, az = -nx, s = Math.hypot(ax, az);+ if (s < 1e-6) return yawQ;+ const angle = Math.acos(Math.min(Math.max(ny, -1), 1)) / 2;+ const tilt = { x: (ax / s) * Math.sin(angle), y: 0, z: (az / s) * Math.sin(angle), w: Math.cos(angle) };+ return {+ x: tilt.w * yawQ.x + tilt.x * yawQ.w + tilt.y * yawQ.z - tilt.z * yawQ.y,+ y: tilt.w * yawQ.y - tilt.x * yawQ.z + tilt.y * yawQ.w + tilt.z * yawQ.x,+ z: tilt.w * yawQ.z + tilt.x * yawQ.y - tilt.y * yawQ.x + tilt.z * yawQ.w,+ w: tilt.w * yawQ.w - tilt.x * yawQ.x - tilt.y * yawQ.y - tilt.z * yawQ.z,+ };+}++export const worldGenPlugin: Plugin = new WorldGenPlugin();diff --git a/sdk/src/worldgen/worldgenSupport.ts b/sdk/src/worldgen/worldgenSupport.tsnew file mode 100644index 000000000..0e89164ee--- /dev/null+++ b/sdk/src/worldgen/worldgenSupport.ts@@ -0,0 +1,13 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file worldgenSupport.ts — what a build that ships generated worlds tells the core.+ *+ * A call, not a file's side effect — see tilemap/tilemapSupport.ts.+ */+import { addEntryPlugin } from '../runtime/entryPlugins';+import { WorldGenPlugin } from './worldgenPlugin';++export function registerWorldGenSupport(): void {+ addEntryPlugin('worldgen', () => new WorldGenPlugin());+}diff --git a/sdk/src/worldgen/zones.ts b/sdk/src/worldgen/zones.tsnew file mode 100644index 000000000..8a216fd14--- /dev/null+++ b/sdk/src/worldgen/zones.ts@@ -0,0 +1,114 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file zones.ts+ * @brief Areas a world is planned by: a home, a road, a landing site, a building's footprint, a view kept open.+ *+ * @details A zone has a shape, a kind, a priority and an edge that fades over `falloff` world units. Over its area it can keep out what+ * is placed (everything, or what carries one of the tags it names), hold a biome, and set fields; at its edge each of those+ * fades, and what it keeps out thins rather than stopping on a line. Where zones overlap the higher priority holds the biome.+ * A game adds zones as it plans (a reserved home) and as the player builds; authored ones come from `WorldZone` components.+ */+import { hash01, hashString } from './fields';++/** A zone's outline: a circle, or a rectangle turned by `yaw` radians about the vertical. */+export type ZoneShape =+ | { type: 'circle'; x: number; z: number; radius: number }+ | { type: 'rect'; x: number; z: number; halfX: number; halfZ: number; yaw?: number };++export interface ZoneDef {+ /** Stable: what a placement records as the zone it stands in or was kept out by. */+ id: string;+ /** What the zone is for (home, road, landing, building, resource, view): a game's own words. */+ kind: string;+ shape: ZoneShape;+ /** Over how many world units past its outline it fades out. */+ falloff: number;+ priority: number;+ /** The tags of what it keeps out; `*` keeps out everything. */+ excludes: readonly string[];+ /** A biome it holds over its area, if any. */+ biome?: string;+ /** Fields it sets over its area. */+ fields?: Readonly<Record<string, number>>;+}++/** How far (x, z) is outside a zone's outline: negative inside. */+export function zoneDistance(shape: ZoneShape, x: number, z: number): number {+ if (shape.type === 'circle') return Math.hypot(x - shape.x, z - shape.z) - shape.radius;+ const c = Math.cos(-(shape.yaw ?? 0)), s = Math.sin(-(shape.yaw ?? 0));+ const dx = x - shape.x, dz = z - shape.z;+ const lx = Math.abs(dx * c - dz * s) - shape.halfX, lz = Math.abs(dx * s + dz * c) - shape.halfZ;+ return Math.hypot(Math.max(lx, 0), Math.max(lz, 0)) + Math.min(Math.max(lx, lz), 0);+}++/** How much of a zone holds at a point `d` outside its outline: 1 inside, fading smoothly to 0 at `falloff`. */+export function zoneWeight(zone: ZoneDef, d: number): number {+ if (d <= 0) return 1;+ if (zone.falloff <= 0 || d >= zone.falloff) return 0;+ const t = 1 - d / zone.falloff;+ return t * t * (3 - 2 * t);+}++/** The square a zone reaches, its edge included: [minX, minZ, maxX, maxZ]. */+export function zoneBounds(zone: ZoneDef): [number, number, number, number] {+ const s = zone.shape;+ const r = (s.type === 'circle' ? s.radius : Math.hypot(s.halfX, s.halfZ)) + Math.max(zone.falloff, 0);+ return [s.x - r, s.z - r, s.x + r, s.z + r];+}++/** The zones of one world. */+export class Zones {+ private readonly zones_ = new Map<string, ZoneDef>();+ /** Bumped on every change. */+ revision = 0;+ /** Told the area every change touched (the zone's old and new bounds) and the zone there, so only what stands there is placed again. */+ onChange: ((bounds: [number, number, number, number], zone: ZoneDef) => void) | null = null;++ set(zone: ZoneDef): void {+ const had = this.zones_.get(zone.id);+ if (had && JSON.stringify(had) === JSON.stringify(zone)) return;+ this.zones_.set(zone.id, zone);+ this.revision++;+ if (had) this.onChange?.(zoneBounds(had), had);+ this.onChange?.(zoneBounds(zone), zone);+ }++ delete(id: string): void {+ const had = this.zones_.get(id);+ if (!had) return;+ this.zones_.delete(id);+ this.revision++;+ this.onChange?.(zoneBounds(had), had);+ }++ get(id: string): ZoneDef | undefined {+ return this.zones_.get(id);+ }++ all(): IterableIterator<ZoneDef> {+ return this.zones_.values();+ }++ /** The zones that hold at (x, z), with how much, highest priority first. */+ at(x: number, z: number, reach = 0): { zone: ZoneDef; weight: number }[] {+ const out: { zone: ZoneDef; weight: number }[] = [];+ for (const zone of this.zones_.values()) {+ const w = zoneWeight(zone, zoneDistance(zone.shape, x, z) - reach);+ if (w > 0) out.push({ zone, weight: w });+ }+ return out.sort((a, b) => b.zone.priority - a.zone.priority || (a.zone.id < b.zone.id ? -1 : 1));+ }++ /**+ * The zone that keeps out something of radius `radius` carrying `tags` at (x, z), or null. Inside a zone it is kept out; in its+ * edge it is kept out with the zone's weight there, by a draw fixed for that place, so the edge thins instead of ending on a line.+ */+ excluding(x: number, z: number, radius: number, tags: readonly string[], seed: number): ZoneDef | null {+ for (const { zone, weight } of this.at(x, z, radius)) {+ if (!zone.excludes.some((t) => t === '*' || tags.includes(t))) continue;+ if (weight >= 1 || hash01(seed, hashString(zone.id), Math.floor(x * 16), Math.floor(z * 16)) < weight) return zone;+ }+ return null;+ }+}diff --git a/sdk/tests/worldgen-plan.test.ts b/sdk/tests/worldgen-plan.test.tsnew file mode 100644index 000000000..c214a2f67--- /dev/null+++ b/sdk/tests/worldgen-plan.test.ts@@ -0,0 +1,151 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A world's plan: biomes, zones and layered groups, the same whatever is asked first, and ids that outlive rules added later.+ */+import { describe, expect, it } from 'vitest';+import { Environment } from '../src/worldgen/fields';+import { WorldPlan, type Placement } from '../src/worldgen/plan';+import type { WorldRules } from '../src/worldgen/rules';+import { Zones, zoneDistance } from '../src/worldgen/zones';+import { PlacementDiffs } from '../src/worldgen/diffs';+import { NoiseSource, type NoiseParams } from '../src/terrain/source';++const terrain: NoiseParams = { seed: 5, frequency: 3, octaves: 4, persistence: 0.5, ridged: 0.2, warp: 0, erosion: 0, sizeX: 800, height: 60,+ rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88 };+const ground = new NoiseSource(terrain);++const rules: WorldRules = {+ id: 'test:world', versions: [1],+ biomes: [+ { id: 'forest', conditions: [{ field: 'moisture', min: 0.5, blend: 0.1 }], transition: 30, paint: [1, 0, 0, 0],+ recipes: [{ recipe: 'grove', layer: 'groups', density: 0.8 }, { recipe: 'fern', layer: 'detail', density: 0.6 }] },+ { id: 'rocks', conditions: [{ field: 'moisture', max: 0.5, blend: 0.1 }], transition: 30, paint: [0, 0, 0, 1],+ recipes: [{ recipe: 'boulders', layer: 'groups', density: 0.5 }, { recipe: 'ore', layer: 'detail', density: 0.2 }] },+ ],+ recipes: [+ { id: 'grove', version: 1, tags: ['tree'], anchor: { id: 'oak', mesh: 1, footprint: 0.8, canopy: 4, minUp: 0.8 },+ members: [{ id: 'sapling', mesh: 2, count: [2, 4], ring: [3, 6], scale: [0.5, 0.8], footprint: 0.4, minUp: 0.8 },+ { id: 'stump', mesh: 3, chance: 0.4, ring: [2, 3], footprint: 0.5 }] },+ { id: 'boulders', version: 1, tags: ['rock'], anchor: { id: 'main', mesh: 4, footprint: 2 },+ members: [{ id: 'pebble', mesh: 5, count: [3, 6], ring: [2.5, 5], footprint: 0.3 }] },+ { id: 'fern', version: 1, anchor: { id: 'fern', mesh: 6, footprint: 0.3 } },+ { id: 'ore', version: 1, anchor: { id: 'copper', mesh: 7, footprint: 0.6, interactive: 'ore' } },+ ],+ layers: [+ { id: 'groups', spacing: 14, drawDistance: 200 },+ { id: 'detail', spacing: 3, drawDistance: 80 },+ ],+};++const plan = (r: WorldRules = rules, zones = new Zones()) => new WorldPlan(r, new Environment({+ seed: 9, ground: (x, z) => ({ y: ground.height(x, z), up: ground.normal(x, z)[1] }),+ waterDepth: (_x, _z, y) => 4 - y,+}), zones, 9, 'planet');++const ids = (ps: Placement[]) => ps.map((p) => p.id).sort();++describe('a world plan', () => {+ it('places the same things whatever order its chunks are asked in, each group by exactly one chunk', () => {+ const chunk = 64;+ const cells = [] as [number, number][];+ for (let cz = -2; cz < 2; cz++) for (let cx = -2; cx < 2; cx++) cells.push([cx, cz]);+ const run = (order: [number, number][]) => {+ const p = plan();+ const out: Placement[] = [];+ for (const [cx, cz] of order) out.push(...p.placementsIn(cx * chunk, cz * chunk, (cx + 1) * chunk, (cz + 1) * chunk));+ return out;+ };+ const forward = run(cells), backward = run([...cells].reverse());+ expect(ids(forward)).toEqual(ids(backward));+ expect(new Set(ids(forward)).size).toBe(forward.length);+ const whole = plan().placementsIn(-128, -128, 128, 128);+ expect(ids(whole)).toEqual(ids(forward));+ expect(forward.some((p) => p.layer === 'groups')).toBe(true);+ expect(forward.some((p) => p.layer === 'detail')).toBe(true);+ });++ it('never lets two footprints overlap, within a layer or across layers', () => {+ const all = plan().placementsIn(-100, -100, 100, 100);+ for (let i = 0; i < all.length; i++) for (let j = i + 1; j < all.length; j++) {+ const a = all[i]!, b = all[j]!;+ expect(Math.hypot(a.x - b.x, a.z - b.z)).toBeGreaterThanOrEqual(a.footprint + b.footprint - 1e-9);+ }+ });++ it('keeps the ids, places and choices of earlier layers when a later layer or recipe is added', () => {+ const more: WorldRules = {+ ...rules,+ recipes: [...rules.recipes, { id: 'flowers', version: 1, anchor: { id: 'daisy', mesh: 8, footprint: 0.2 } }],+ biomes: rules.biomes.map((b) => ({ ...b, recipes: [...b.recipes, { recipe: 'flowers', layer: 'flowers', density: 0.5 }] })),+ layers: [...rules.layers, { id: 'flowers', spacing: 2, drawDistance: 40 }],+ };+ const before = plan().placementsIn(-64, -64, 64, 64);+ const after = plan(more).placementsIn(-64, -64, 64, 64, ['groups', 'detail']);+ expect(after).toEqual(before);+ });++ it('keeps out what a zone excludes, thins it over the zone\'s edge, and leaves the rest of the world as it was', () => {+ const zones = new Zones();+ const open = plan(undefined, zones).placementsIn(-64, -64, 64, 64);+ zones.set({ id: 'home', kind: 'home', shape: { type: 'circle', x: 0, z: 0, radius: 20 }, falloff: 10, priority: 5, excludes: ['*'] });+ const homed = plan(undefined, zones).placementsIn(-64, -64, 64, 64);+ for (const p of homed) expect(zoneDistance({ type: 'circle', x: 0, z: 0, radius: 20 }, p.x, p.z)).toBeGreaterThan(-1e-9);+ // Far from the home every placement stands where it did, under its id.+ const far = (ps: Placement[]) => ids(ps.filter((p) => Math.hypot(p.x, p.z) > 60));+ expect(far(homed)).toEqual(far(open));+ expect(homed.length).toBeLessThan(open.length);+ });++ it('keeps only what a zone names out of it, and holds the biome a zone says', () => {+ const zones = new Zones();+ zones.set({ id: 'mine', kind: 'resource', shape: { type: 'rect', x: 0, z: 0, halfX: 30, halfZ: 30 }, falloff: 0, priority: 1,+ excludes: ['tree'], biome: 'rocks' });+ const p = plan(undefined, zones);+ expect(p.biomeAt(0, 0)).toBe('rocks');+ const inside = p.placementsIn(-30, -30, 30, 30).filter((q) => Math.abs(q.x) < 25 && Math.abs(q.z) < 25);+ expect(inside.every((q) => q.recipe !== 'grove')).toBe(true);+ expect(inside.some((q) => q.recipe === 'boulders' || q.recipe === 'ore')).toBe(true);+ });++ it('mixes biomes whose weights sum to one, and paints the ground by them', () => {+ const p = plan();+ let mixed = 0;+ for (let x = -400; x < 400; x += 7) {+ const w = p.biomeWeights(x, 13);+ if (w.length === 0) continue;+ expect(w.reduce((s, b) => s + b.weight, 0)).toBeCloseTo(1, 9);+ if (w.length > 1) mixed++;+ const paint = p.paint(x, 13, [0.25, 0.25, 0.25, 0.25]);+ expect(paint.reduce((s, v) => s + v, 0)).toBeCloseTo(1, 9);+ }+ expect(mixed).toBeGreaterThan(0);+ });++ it('says why nothing stands where it does not', () => {+ const p = plan();+ const stats = p.stats('detail', -50, -50, 50, 50);+ expect(stats.placed).toBeGreaterThan(0);+ expect(stats.occupied + stats.conflict + stats.density).toBeGreaterThan(0);+ const why = p.explain(10, 10);+ expect(why.biomes.length).toBeGreaterThan(0);+ expect(why.layers.map((l) => l.layer)).toEqual(['groups', 'detail']);+ expect(Number.isFinite(why.fields.moisture)).toBe(true);+ });+});++describe('placement diffs', () => {+ it('round-trip through a save, and say which placements changed', () => {+ const diffs = new PlacementDiffs();+ const told: string[] = [];+ diffs.onChange = (id) => told.push(id);+ diffs.remove('groups@1:3,4/grove@1/oak.0');+ diffs.change('detail@1:9,9/ore@1/copper.0', { yaw: 1 });+ const saved = JSON.parse(JSON.stringify(diffs.toJSON()));+ const back = new PlacementDiffs();+ back.load(saved);+ expect(back.isRemoved('groups@1:3,4/grove@1/oak.0')).toBe(true);+ expect(back.changeOf('detail@1:9,9/ore@1/copper.0')).toEqual({ yaw: 1 });+ expect(told).toEqual(['groups@1:3,4/grove@1/oak.0', 'detail@1:9,9/ore@1/copper.0']);+ });+});diff --git a/sdk/tests/worldgen-plugin.test.ts b/sdk/tests/worldgen-plugin.test.tsnew file mode 100644index 000000000..224fb4ed2--- /dev/null+++ b/sdk/tests/worldgen-plugin.test.ts@@ -0,0 +1,127 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A generated world in a running app with no renderer (a server): interactive placements are entities with stable ids, a+ * player's change outlives its chunk, zones keep their ground clear, and unknown rules fail loudly.+ */+import { describe, expect, it } from 'vitest';+import { App } from '../src/app/app';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { setEditorMode, setPlayMode } from '../src/ecs/env';+import { Transform } from '../src/ecs/component';+import { createMockModule } from './mocks/wasm';+import { WorldStreamingSource } from '../src/residency/components';+import {+ PlacedObject, WorldGen, WorldGenPlugin, WorldGenRes, WorldZone, ZoneShapeKind, type PlacedObjectData,+} from '../src/worldgen/worldgenPlugin';+import { registerWorldRules, type WorldRules } from '../src/worldgen/rules';+import type { Entity } from '../src/types';++const rules: WorldRules = {+ id: 'test:ores', versions: [1],+ biomes: [{ id: 'plain', conditions: [], recipes: [{ recipe: 'ore', layer: 'ores', density: 0.7 }] }],+ recipes: [{ id: 'ore', version: 1, anchor: { id: 'copper', mesh: 0, footprint: 1, interactive: 'ore' } }],+ layers: [{ id: 'ores', spacing: 10, drawDistance: 60, chunkSize: 32 }],+};+registerWorldRules(rules);++const boot = () => {+ setDefaultContext(new AppContext());+ setEditorMode(false);+ setPlayMode(false);+ const app = App.new();+ const module = createMockModule();+ app.connectCpp(module.getRegistry(), module);+ app.addPlugin(new WorldGenPlugin());+ return app;+};+// The mock engine composes no transforms: an entity without a parent is given its world pose as well.+const placed = (x: number, y: number, z: number) => ({ position: { x, y, z }, worldPosition: { x, y, z } });+const tick = async (app: App, n = 1) => { for (let i = 0; i < n; i++) { app.tick(1 / 60); await new Promise((r) => setTimeout(r, 0)); } };+const objects = (app: App) => app.world.getEntitiesWithComponents([PlacedObject]).map((e) => (app.world.get(e, PlacedObject) as PlacedObjectData).id);++const world = (app: App, data: Record<string, unknown> = {}): { gen: Entity; source: Entity } => {+ const gen = app.world.spawn();+ app.world.insert(gen, Transform, placed(0, 0, 0));+ app.world.insert(gen, WorldGen, { ...WorldGen._default, rules: 'test:ores', world: 'planet', seed: 3, ...data });+ const source = app.world.spawn();+ app.world.insert(source, Transform, placed(0, 0, 0));+ app.world.insert(source, WorldStreamingSource, { ...WorldStreamingSource._default });+ return { gen, source };+};++describe('a generated world with no renderer', () => {+ it('stands its interactive placements as entities with the plan\'s ids, round the source and no further', async () => {+ const app = boot();+ const { gen } = world(app);+ await tick(app, 30);+ const gens = app.getResource(WorldGenRes);+ expect(gens.status(gen)!.state).toBe('ready');+ const ids = objects(app);+ expect(ids.length).toBeGreaterThan(5);+ expect(new Set(ids).size).toBe(ids.length);+ const plan = gens.plan(gen)!;+ const near = plan.placementsIn(-30, -30, 30, 30).map((p) => p.id);+ for (const id of near) expect(ids).toContain(id);+ for (const id of ids) expect(gens.objectOf(id)).not.toBeNull();+ });++ it('keeps a felled placement felled when its chunk is let go and made again, and forgets nothing else', async () => {+ const app = boot();+ const { source } = world(app);+ await tick(app, 30);+ const gens = app.getResource(WorldGenRes);+ const before = objects(app);+ const felled = before[0]!;+ gens.diffs('planet').remove(felled);+ await tick(app, 5);+ expect(objects(app)).not.toContain(felled);+ expect(objects(app).length).toBe(before.length - 1);+ // Walk away until it is let go, and come back.+ app.world.insert(source, Transform, placed(5000, 0, 0));+ await tick(app, 30);+ expect(objects(app)).not.toContain(before[1]);+ app.world.insert(source, Transform, placed(0, 0, 0));+ await tick(app, 30);+ expect(objects(app).sort()).toEqual(before.filter((id) => id !== felled).sort());+ // And from a save read back into a fresh world.+ const saved = JSON.parse(JSON.stringify(gens.diffs('planet').toJSON()));+ const again = boot();+ world(again);+ again.getResource(WorldGenRes).diffs('planet').load(saved);+ await tick(again, 30);+ expect(objects(again).sort()).toEqual(objects(app).sort());+ });++ it('keeps a zone clear of what it excludes, and only the chunks it reaches change', async () => {+ const app = boot();+ world(app);+ await tick(app, 30);+ const plan = app.getResource(WorldGenRes).plan()!;+ const before = objects(app);+ const home = app.world.spawn();+ app.world.insert(home, Transform, placed(0, 0, 0));+ app.world.insert(home, WorldZone, { ...WorldZone._default, kind: 'home', shape: ZoneShapeKind.Circle, radius: 12, falloff: 0, excludes: '*' });+ await tick(app, 10);+ const after = objects(app);+ expect(after.length).toBeLessThan(before.length);+ for (const id of after) {+ const p = plan.placementsIn(-100, -100, 100, 100).find((q) => q.id === id)!;+ expect(Math.hypot(p.x, p.z)).toBeGreaterThan(12);+ }+ // What stood well away from the home stands there still, under the same id.+ const far = (ids: string[]) => ids.filter((id) => { const p = plan.placementsIn(-100, -100, 100, 100).find((q) => q.id === id); return p && Math.hypot(p.x, p.z) > 50; });+ expect(far(after).sort()).toEqual(far(before).sort());+ });++ it('fails, and places nothing, for rules it does not know or a version they do not have', async () => {+ const app = boot();+ const { gen } = world(app, { rules: 'test:nowhere' });+ const old = world(app, { version: 7 }).gen;+ await tick(app, 10);+ const gens = app.getResource(WorldGenRes);+ expect(gens.status(gen)).toMatchObject({ state: 'failed' });+ expect(gens.status(old)!.reason).toMatch(/version 7/);+ expect(objects(app)).toHaveLength(0);+ });+});diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjsindex f67173b84..6d654813a 100644--- a/tools/check-corpus-authoring.mjs+++ b/tools/check-corpus-authoring.mjs@@ -120,6 +120,7 @@ const DISPOSITION = {// — derived: a system writes them; authored, they would be a bug —RuntimeOnly: ['derived', 'tags a world-only entity a system re-derives; scene serialization skips tagged entities, so authoring one would delete it on save'],NetGhost: ['derived', 'replication tags a remote proxy with it; the authority writes it, never the scene'],+ PlacedObject: ['derived', 'a generated world writes it on what it places for the game to interact with; authored, it would name a placement no rule made'],SceneOwner: ['derived', 'scene loading records which scene an entity came from; authoring it would claim an ownership the loader never granted'],// — code-only: an example demonstrates it from TypeScript, honestly —diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjsindex 125bf916d..47756d568 100644--- a/tools/check-gizmo-coverage.mjs+++ b/tools/check-gizmo-coverage.mjs@@ -129,6 +129,9 @@ const DISPOSITION = {'Foliage.drawDistance': ['no-place', 'a distance from the camera past which nothing is drawn'],'Foliage.waterDepth': ['no-place', 'how deep under the water a plant may stand, not a region of the entity'],'WaterBody.shoreWidth': ['no-place', 'a distance in from a body\'s shore over which the waves come to full height, not a region of the entity'],+ 'WorldZone.radius': 'extent',+ 'WorldZone.sizeX': 'extent',+ 'WorldZone.sizeZ': 'extent','WaterZone.sizeX': 'extent','WaterZone.sizeZ': 'extent','WaterZone.cellSize': ['no-place', 'the cell size of the finest ring of the surface\'s mesh, not a region of the entity'],diff --git a/tools/lib/sdkProgram.mjs b/tools/lib/sdkProgram.mjsindex b7bff0081..0ec4d11d0 100644--- a/tools/lib/sdkProgram.mjs+++ b/tools/lib/sdkProgram.mjs@@ -65,6 +65,7 @@ export const ENTRIES = {'fx-atmosphere': 'src/postprocess/fxAtmosphere.ts','fx-lighting': 'src/postprocess/fxLighting.ts','foliage': 'src/foliage/index.ts',+ 'worldgen': 'src/worldgen/index.ts','water': 'src/water/index.ts','spline': 'src/spline/index.ts','character-shaders': 'src/character/index.ts',diff --git a/tools/nativeScriptModules.js b/tools/nativeScriptModules.jsindex ac2c6af12..9f082e7c9 100644--- a/tools/nativeScriptModules.js+++ b/tools/nativeScriptModules.js@@ -71,6 +71,7 @@ export const MODULES = {'esengine/fx-atmosphere': { disposition: 'native-subpath' },'esengine/fx-lighting': { disposition: 'native-subpath' },'esengine/foliage': { disposition: 'native-subpath' },+ 'esengine/worldgen': { disposition: 'native-subpath' },'esengine/water': { disposition: 'native-subpath' },'esengine/spline': { disposition: 'native-subpath' },'esengine/character-shaders': { disposition: 'native-subpath' },diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 13930d438..4f4197ce7 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2770,4 +2770,10 @@ export const NOTED = {{"note":"The running game's resolution can be chosen."},"feat(residency): procedural chunks have one owner and the frame one budget; terrain collision and foliage cells are chunk layers":{"note":"Procedural chunks, with one owner and one budget."},+ "fix(terrain): a ridge's crest is rounded, so ridged ground worn by its noise is continuous":+ {"note":"Ridged ground without end has no steps."},+ "build(sdk): a shared declaration chunk named after an index module carries its hash":+ {"internal":"Declaration bundling: a second shared chunk named index was written as index.d2.ts, which TypeScript does not read as declarations."},+ "feat(worldgen): biomes, zones and layered recipes lay a world out as it is explored, with stable ids and kept changes":+ {"note":"Generated worlds."},};