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): world rules as a .esworld asset, checked on load, shipped with what they name and rebuilt on edit
yhhb5ba9cf88ed1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 25919475f..7f64e663f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,7 @@ published separately; it ships inside the editor.- **Rays against the terrain, anywhere.** `Terrains.raycast(origin, direction, maxDistance)` meets the ground's triangles exactly (the ones collision and `heightAt` use) wherever the ray goes, with no physics world and no collision tile there, for a line of sight, a pick or a landing spot.- **Far versions for generated decoration.** A recipe member can name its far version (`far`: crossed cards, or a tent for a conifer, showing a rectangle of its texture), drawn past its layer's `lodDistance`, and decoration that leans with the ground (`attach: 'align'`) now leans in its merged mesh too.- **Terrain modifiers, and zones that level their ground.** `Terrains.setModifier` lays a change over the ground (`flattenModifier` levels a circle or a turned box, blending back over its edge) that what is drawn, the queries, rays and collision all follow, remaking only the pages and collision tiles it reaches; `heightBeneathAt` reads the ground as it was made. A `WorldZone` with `flatten` levels its plot to the ground's height at its centre.+- **World rules as a file, with an editor.** A WorldGen's `rules` can name a `.esworld` file: the biomes, recipes and layers as data, checked as they are read (a missing recipe or layer fails the world with where it went wrong), followed by the cook like a material so the meshes and materials it names ship with the scene, and watched so a saved edit lays the world out again. The editor opens it in a World Rules editor that lists the biomes, recipes and layers, edits each with a form, and says whether the engine would take the rules as they stand.- **How far a place is from the water.** `Waters.shoreAt(x, z)` gives the distance across the ground to the water's edge (above zero on dry land, below on the water), and generated worlds read it as the `shoreDistance` field, so a beach or a band of reeds can follow the shore.- **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.diff --git a/desktop b/desktopindex 63edf20d1..00c2fc6b6 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 63edf20d13c6d871237516bb30059bbc2def6a01+Subproject commit 00c2fc6b6c283d7269fca8f680a207718fb68d90diff --git a/docs/WORLD_GENERATION_PLAN.md b/docs/WORLD_GENERATION_PLAN.mdindex 9aae555db..3fdf0c11a 100644--- a/docs/WORLD_GENERATION_PLAN.md+++ b/docs/WORLD_GENERATION_PLAN.md@@ -60,7 +60,8 @@- 后续已补:装饰远景版本(成员 `far` 卡片 + 层 `lodDistance`,LODGroup 切换);贴地装饰合并时随法线倾斜。- 后续已补:有限整地——地形修改器(`Terrains.setModifier`,世界空间函数,所有读取方一致,仅重做触及的页与碰撞块),区域 `flatten` 压平(地面未知时挂起重试)。- 后续已补:陆地离岸距离——`Waters.shoreAt` 与环境场 `shoreDistance`(陆上为到水边距离,水中为负)。- - 仍欠:配方编辑器、可达性/安全落点等验收由游戏用查询接口实现(引擎可后续提供寻路连通查询)。+ - 后续已补:规则即资源——`.esworld` 文件(加载时校验、引用的网格材质随场景打包、修改后世界自动重建)与编辑器里的世界规则编辑器(群落/配方/布置层表单,实时显示引擎是否接受)。+ - 仍欠:可达性/安全落点等验收由游戏用查询接口实现(引擎可后续提供寻路连通查询)。- 验收:林地建房后草木不穿地板;采集后卸载重进不重生;同种子不同加载顺序结果相同;安全落点、早期资源、入口可达。## 水域补充diff --git a/docs/astro/src/content/docs/world/generation.mdx b/docs/astro/src/content/docs/world/generation.mdxindex ea3bc8e3d..8ed70f689 100644--- a/docs/astro/src/content/docs/world/generation.mdx+++ b/docs/astro/src/content/docs/world/generation.mdx@@ -15,7 +15,7 @@ them, what is reserved for a home or a road. The **artists** make the recipes: a| Field | What it does ||---|---|-| `rules` | The rules the world is laid out by, as the game registered them with `registerWorldRules`. |+| `rules` | The rules the world is laid out by: a `.esworld` file, or the id of rules the game registered 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. |@@ -25,6 +25,15 @@ see [procedural chunks](/docs/world/streaming/#procedural-chunks).## Rules+Rules are data: biomes, the recipes that stand in them and the layers they are placed in. Keep them in a **`.esworld` file** (in the+editor, **New → New World Rules**, or open one from the content browser) and name it in the WorldGen's `rules`. The editor lists the+file's biomes, recipes and layers, edits each with a form (meshes and materials picked like any asset), and says under them whether+the engine would take the rules as they stand. Saving the file lays the open world out by it again, in the editor and in a running+game. The file is the JSON of what `registerWorldRules` takes, checked as it is read: a file that names a recipe or layer it does not+have, or leaves out what a world needs, fails the WorldGen with where it went wrong.++Rules can also be registered from code, which is how a game adds fields of its own (functions are not data):+```tsimport { registerWorldRules } from 'esengine/worldgen';@@ -142,8 +151,9 @@ game's own: the zone it reserves keeps generation out of its ground.## 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`:+A `.esworld` file is followed like a material: the meshes and materials it names ship with the scene that names it. Rules registered+from code name theirs where a scene does not reference them, 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 } } }@@ -153,6 +163,7 @@ Declare the folders they live in always included, in `.esengine/asset-groups.jso- **Decoration is merged a chunk at a time, not GPU-instanced.** The renderer's instance records are written each frame, which for afield of thousands of plants would upload megabytes a frame; merged static meshes upload nothing, and the chunks bound their memory.-- **Rules are code.** Recipes are plain data and can be read from JSON, but there is no editor for them yet.+- **A game's own fields are code.** A rules file uses the built-in fields and the ones zones set; a field computed by the game is+ registered with the rules from code.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.mdxindex d2cde365d..4318aa379 100644--- a/docs/astro/src/content/docs/zh-cn/world/generation.mdx+++ b/docs/astro/src/content/docs/zh-cn/world/generation.mdx@@ -11,7 +11,7 @@ description: 按规则在探索时布置世界——由环境场得出群落、| 字段 | 作用 ||---|---|-| `rules` | 布置这个世界的规则,即游戏用 `registerWorldRules` 注册的名字。 |+| `rules` | 布置这个世界的规则:一个 `.esworld` 文件,或游戏用 `registerWorldRules` 注册的规则标识。 || `version` | 这个世界生成时使用的规则版本。存档会保留它;规则里已没有这个版本时,世界失败(状态里说明原因),而不是布置出另一个世界。 || `world`、`seed` | 游戏给这个世界(星球、关卡)起的名字,以及它的种子。换一个种子就是同一套规则下的另一个世界。 || `paintGround` | 群落是否给地形上色。 |@@ -20,6 +20,10 @@ description: 按规则在探索时布置世界——由环境场得出群落、## 规则+规则是数据:群落、群落里生长的配方,以及它们所在的布置层。把它们放在一个 **`.esworld` 文件**里(编辑器里 **新建 → 新建世界规则**,或在内容浏览器里打开),并在 WorldGen 的 `rules` 里引用它。编辑器列出文件里的群落、配方和布置层,用表单编辑每一项(网格和材质像其他资源一样选取),并在下方说明引擎是否接受当前的规则。保存文件后,打开的世界会按它重新布置,编辑器里和运行中的游戏都是如此。文件就是 `registerWorldRules` 接受内容的 JSON,读取时会校验:引用了文件里不存在的配方或布置层、或缺少世界必需的内容时,WorldGen 失败并指出出错的位置。++规则也可以从代码注册,游戏自定义的环境场就是这样加入的(函数不是数据):+```tsimport { registerWorldRules } from 'esengine/worldgen';@@ -117,7 +121,7 @@ gens.diffs().load(saved); // 以及读回## 打包-配方在代码里按路径引用网格和材质,场景不引用它们,所以打包时会被剔除。在 `.esengine/asset-groups.json` 里把它们所在的文件夹声明为始终包含:+`.esworld` 文件像材质一样被跟随:它引用的网格和材质会随引用它的场景一起打包。从代码注册的规则引用的资源场景并不引用,打包时会被剔除;在 `.esengine/asset-groups.json` 里把它们所在的文件夹声明为始终包含:```json{ "version": "1.0", "groups": { "recipes": { "folder": "assets/models", "mode": "local", "alwaysInclude": true } } }@@ -126,6 +130,6 @@ gens.diffs().load(saved); // 以及读回## 限制- **装饰按区块合并绘制,而不是 GPU 实例化。** 渲染器的实例记录每帧重写,成千上万株植物每帧要上传数兆字节;合并的静态网格每帧不上传任何东西,内存由区块驻留限制住。-- **规则是代码。** 配方是普通数据,可以从 JSON 读取,但还没有编辑器。+- **游戏自定义的环境场是代码。** 规则文件使用内置环境场和区域设置的环境场;由游戏计算的环境场要随规则从代码注册。参见 **Generated World** 示例(`examples/worldgen`)。diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex a2809e8f4..1ae25897f 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -7704,7 +7704,7 @@"key": "rules","type": "string","default": "empty",- "doc": "The rules the world is laid out by, as the game registered them with registerWorldRules."+ "doc": "The rules the world is laid out by: a .esworld file, or the id of rules the game registered with registerWorldRules."},{"key": "version",@@ -7846,6 +7846,12 @@"type": "string","default": "empty","doc": "A biome the zone holds over its area; empty holds none."+ },+ {+ "key": "flatten",+ "type": "boolean",+ "default": "false",+ "doc": "Level the terrain under the zone to the ground's height at its centre, blending back over its falloff: a plot to build on."}],"animatable": [diff --git a/examples/worldgen/.esengine/asset-groups.json b/examples/worldgen/.esengine/asset-groups.jsondeleted file mode 100644index cd240b2f1..000000000--- a/examples/worldgen/.esengine/asset-groups.json+++ /dev/null@@ -1,15 +0,0 @@-{- "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/assets/scenes/main.esscene b/examples/worldgen/assets/scenes/main.essceneindex 50754b9ab..6ba53ba24 100644--- a/examples/worldgen/assets/scenes/main.esscene+++ b/examples/worldgen/assets/scenes/main.esscene@@ -261,7 +261,7 @@{"type": "WorldGen","data": {- "rules": "worldgen-demo:wilds",+ "rules": "assets/worlds/wilds.esworld","version": 1,"world": "demo","seed": 7,diff --git a/examples/worldgen/assets/worlds/wilds.esworld b/examples/worldgen/assets/worlds/wilds.esworldnew file mode 100644index 000000000..e910132f9--- /dev/null+++ b/examples/worldgen/assets/worlds/wilds.esworld@@ -0,0 +1,360 @@+{+ "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": "assets/models/pine.esmesh",+ "material": "assets/materials/pine.esmaterial",+ "scale": [+ 1.4,+ 1.8+ ],+ "footprint": 10,+ "canopy": 35,+ "minUp": 0.82,+ "far": {+ "u0": 0.2,+ "v0": 0.22,+ "u1": 0.8,+ "v1": 0.95,+ "tent": true+ }+ },+ "members": [+ {+ "id": "pine",+ "mesh": "assets/models/pine.esmesh",+ "material": "assets/materials/pine.esmaterial",+ "count": [+ 3,+ 6+ ],+ "ring": [+ 45,+ 110+ ],+ "scale": [+ 0.9,+ 1.3+ ],+ "footprint": 8,+ "canopy": 25,+ "minUp": 0.8,+ "far": {+ "u0": 0.2,+ "v0": 0.22,+ "u1": 0.8,+ "v1": 0.95,+ "tent": true+ }+ },+ {+ "id": "sapling",+ "mesh": "assets/models/pine.esmesh",+ "material": "assets/materials/pine.esmaterial",+ "count": [+ 2,+ 5+ ],+ "ring": [+ 110,+ 170+ ],+ "scale": [+ 0.35,+ 0.6+ ],+ "footprint": 4,+ "minUp": 0.8,+ "chance": 0.8,+ "far": {+ "u0": 0.2,+ "v0": 0.22,+ "u1": 0.8,+ "v1": 0.95,+ "tent": true+ }+ },+ {+ "id": "stone",+ "mesh": "assets/models/rock.esmesh",+ "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": "assets/models/pine.esmesh",+ "material": "assets/materials/pine.esmaterial",+ "scale": [+ 0.8,+ 1.4+ ],+ "footprint": 8,+ "minUp": 0.8,+ "far": {+ "u0": 0.2,+ "v0": 0.22,+ "u1": 0.8,+ "v1": 0.95,+ "tent": true+ }+ }+ },+ {+ "id": "outcrop",+ "version": 1,+ "tags": [+ "rock"+ ],+ "anchor": {+ "id": "boulder",+ "mesh": "assets/models/rock.esmesh",+ "material": "assets/materials/stone.esmaterial",+ "scale": [+ 4,+ 6.5+ ],+ "footprint": 26,+ "attach": "align"+ },+ "members": [+ {+ "id": "rock",+ "mesh": "assets/models/rock.esmesh",+ "material": "assets/materials/stone.esmaterial",+ "count": [+ 2,+ 4+ ],+ "ring": [+ 32,+ 60+ ],+ "scale": [+ 1.6,+ 3+ ],+ "footprint": 12,+ "attach": "align"+ },+ {+ "id": "scree",+ "mesh": "assets/models/rock.esmesh",+ "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": "assets/models/rock.esmesh",+ "material": "assets/materials/stone.esmaterial",+ "scale": [+ 0.6,+ 1.4+ ],+ "footprint": 6,+ "attach": "align"+ }+ },+ {+ "id": "copper",+ "version": 1,+ "tags": [+ "ore"+ ],+ "anchor": {+ "id": "vein",+ "mesh": "assets/models/rock.esmesh",+ "material": "assets/materials/copper.esmaterial",+ "interactive": "copper",+ "scale": [+ 1.2,+ 1.8+ ],+ "footprint": 10,+ "attach": "align"+ }+ }+ ],+ "layers": [+ {+ "id": "groups",+ "spacing": 260,+ "drawDistance": 4200,+ "lodDistance": 1400,+ "chunkSize": 512+ },+ {+ "id": "resources",+ "spacing": 220,+ "drawDistance": 2400,+ "chunkSize": 512+ },+ {+ "id": "detail",+ "spacing": 90,+ "drawDistance": 2400,+ "lodDistance": 1200,+ "chunkSize": 384+ }+ ]+}diff --git a/examples/worldgen/assets/worlds/wilds.esworld.meta b/examples/worldgen/assets/worlds/wilds.esworld.metanew file mode 100644index 000000000..8158210ab--- /dev/null+++ b/examples/worldgen/assets/worlds/wilds.esworld.meta@@ -0,0 +1,6 @@+{+ "uuid": "68f0824e-8b9c-4e6d-acff-10f21406f160",+ "version": "2.0",+ "type": "world-rules",+ "importer": {}+}diff --git a/examples/worldgen/src/main.ts b/examples/worldgen/src/main.tsindex bb37ad40a..6c355451f 100644--- a/examples/worldgen/src/main.ts+++ b/examples/worldgen/src/main.ts@@ -1,60 +1,9 @@// 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.+// The rules are a project file (assets/worlds/wilds.esworld) the scene's WorldGen names; 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';-/** A pine far off: a tent of cards showing the tree's part of its colour strip. */-const PINE_FAR = { u0: 0.2, v0: 0.22, u1: 0.8, v1: 0.95, tent: true };--/**- * 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, far: PINE_FAR },- 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, far: PINE_FAR },- { 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, far: PINE_FAR },- { 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, far: PINE_FAR } },- { 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, lodDistance: 1400, chunkSize: 512 },- { id: 'resources', spacing: 220, drawDistance: 2400, chunkSize: 512 },- { id: 'detail', spacing: 90, drawDistance: 2400, lodDistance: 1200, chunkSize: 384 },- ],-};-registerWorldRules(rules);+import { WorldGenRes } from 'esengine/worldgen';const KEYS = ['W A S D walk Q E turn',diff --git a/examples/worldgen/tools/build.mjs b/examples/worldgen/tools/build.mjsindex eba0b9075..e22678270 100644--- a/examples/worldgen/tools/build.mjs+++ b/examples/worldgen/tools/build.mjs@@ -3,9 +3,9 @@/*** @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:+ * The ground textures, the pine and its colour strip are the Wilds example's (made there from numbers); the rock, the rules and the+ * scene are made here. The world itself is not in the scene: the scene names the rules (assets/worlds/wilds.esworld) 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*@@ -136,6 +136,64 @@ function materials() {});}+// ── the rules ─────────────────────────────────────────────────────────────────────────────────────────────────────────────++const PINE = 'assets/models/pine.esmesh', ROCK = 'assets/models/rock.esmesh';+/** A pine far off: a tent of cards showing the tree's part of its colour strip. */+const PINE_FAR = { u0: 0.2, v0: 0.22, u1: 0.8, v1: 0.95, tent: true };++/**+ * 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 = {+ 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, far: PINE_FAR },+ 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, far: PINE_FAR },+ { 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, far: PINE_FAR },+ { 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, far: PINE_FAR } },+ { 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, lodDistance: 1400, chunkSize: 512 },+ { id: 'resources', spacing: 220, drawDistance: 2400, chunkSize: 512 },+ { id: 'detail', spacing: 90, drawDistance: 2400, lodDistance: 1200, chunkSize: 384 },+ ],+};++/** The rules as the file the scene's WorldGen names: biomes, recipes and layers, with the meshes and materials they place by path. */+function rules() {+ write('assets/worlds/wilds.esworld', `${JSON.stringify(RULES, null, 2)}\n`);+ meta('assets/worlds/wilds.esworld', 'world-rules');+}+function scene() {const ground = new NoiseSource(GROUND);const home = { x: 0, z: 0 };@@ -183,7 +241,7 @@ function scene() {]),entity(5, 'World', [{ type: 'Transform', data: {} },- { type: 'WorldGen', data: { rules: 'worldgen-demo:wilds', version: 1, world: 'demo', seed: 7, paintGround: true } },+ { type: 'WorldGen', data: { rules: 'assets/worlds/wilds.esworld', 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', [@@ -215,4 +273,5 @@ for (const name of ['grass', 'dirt', 'snow', 'rock', 'pine']) borrow(`assets/texborrow('assets/models/pine.esmesh');rock();materials();+rules();scene();diff --git a/pipeline/src/assets/addressableManifest.ts b/pipeline/src/assets/addressableManifest.tsindex f71befb42..f052229ee 100644--- a/pipeline/src/assets/addressableManifest.ts+++ b/pipeline/src/assets/addressableManifest.ts@@ -38,7 +38,7 @@ interface FlatManifest {const ADDRESSABLE_TYPE: Record<string, string> = {texture: 'texture', material: 'material', audio: 'audio', 'bitmap-font': 'bitmap-font',prefab: 'prefab', spine: 'spine',- scene: 'json', 'anim-clip': 'json', tilemap: 'json', timeline: 'json', json: 'json', 'sound-event': 'json', shader: 'text',+ scene: 'json', 'anim-clip': 'json', tilemap: 'json', timeline: 'json', json: 'json', 'sound-event': 'json', 'world-rules': 'json', shader: 'text',};export const addrType = (editorType: string): string => ADDRESSABLE_TYPE[editorType] ?? 'binary';diff --git a/pipeline/src/assets/assetDb.ts b/pipeline/src/assets/assetDb.tsindex 0caa7d5d6..05284ccf8 100644--- a/pipeline/src/assets/assetDb.ts+++ b/pipeline/src/assets/assetDb.ts@@ -234,7 +234,7 @@ const JSON_REF_TYPES = new Set(['scene', 'prefab', 'material', 'tileset', 'tilemap', 'animclip', 'animation', 'statemachine', 'behaviortree','scriptgraph','environment', 'animatorcontroller', 'avatar',- 'json', 'sound-event',+ 'json', 'sound-event', 'world-rules',]);/**diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex cae19e419..87c7bebcd 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -3639,7 +3639,7 @@ Step = 15```| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'world-rules' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown'```diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex bb48b6b7c..4377bb324 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -3647,7 +3647,7 @@ Step = 15```| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'world-rules' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown'```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex f27dc462d..0bb86cc97 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -3634,7 +3634,7 @@ Step = 15```| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'world-rules' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown'```diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 39af13f09..df4d324fa 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -3634,7 +3634,7 @@ Step = 15```| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'world-rules' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown'```diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex c3e6903b1..ae52e8849 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -3634,7 +3634,7 @@ Step = 15```| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'world-rules' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown'```diff --git a/sdk/etc/worldgen.api.md b/sdk/etc/worldgen.api.mdindex 94c2774ed..bfdec4bb6 100644--- a/sdk/etc/worldgen.api.md+++ b/sdk/etc/worldgen.api.md@@ -1,7 +1,7 @@# 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+Symbols: 0 public · 0 beta · 46 experimental · 0 deprecated## BiomeCondition — interface @experimental```@@ -269,6 +269,16 @@ recipes: readonly Recipe[]versions: readonly number[]```+## WorldRulesAssetLoader — class @experimental+```+extensions: string[]+load: (path: string, ctx: LoadContext) => Promise<WorldRules>+type: "world-rules"+unload: () => void+static new (): WorldRulesAssetLoader+static prototype: WorldRulesAssetLoader+```+## WorldZone — const @experimental```ComponentDef<WorldZoneData>@@ -346,6 +356,16 @@ static prototype: Zones(s: string): number```+## isRulesFile — function @experimental+```+(ref: string): boolean+```++## parseWorldRules — function @experimental+```+(json: unknown, file?: string): WorldRules+```+## registerWorldRules — function @experimental```(rules: WorldRules): voiddiff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.tsindex 67fa7c143..bd8e7cd22 100644--- a/sdk/src/assetTypes.ts+++ b/sdk/src/assetTypes.ts@@ -9,7 +9,7 @@ export type AddressableAssetType =export type EditorAssetType =| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'world-rules' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown';@@ -78,6 +78,8 @@ const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [{ extensions: ['estileset'], contentType: 'json', editorType: 'tileset', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },{ extensions: ['estimeline'], contentType: 'json', editorType: 'timeline', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },{ extensions: ['esaudioevent'], contentType: 'json', editorType: 'sound-event', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },+ // World rules (WorldRulesAssetLoader): biomes, recipes and layers as data, naming the meshes and materials they place by path.+ { extensions: ['esworld'], contentType: 'json', editorType: 'world-rules', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },// Locale string table (LocaleAssetLoader → Localization.addCatalog) — one locale per file.{ extensions: ['eslocale'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },// State machine (registerFsm / FsmAssetLoader) — data-driven FSM definition.diff --git a/sdk/src/worldgen/index.ts b/sdk/src/worldgen/index.tsindex 871142cf9..75135cd95 100644--- a/sdk/src/worldgen/index.ts+++ b/sdk/src/worldgen/index.ts@@ -8,6 +8,7 @@ export {registerWorldRules, worldRules, bandWeight,type WorldRules, type BiomeDef, type BiomeCondition, type BiomeRecipe, type Recipe, type RecipeMember, type PlacementLayer,} from './rules';+export { parseWorldRules, isRulesFile, WorldRulesAssetLoader } from './rulesAsset';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';diff --git a/sdk/src/worldgen/rulesAsset.ts b/sdk/src/worldgen/rulesAsset.tsnew file mode 100644index 000000000..529df103a--- /dev/null+++ b/sdk/src/worldgen/rulesAsset.ts@@ -0,0 +1,115 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file rulesAsset.ts+ * @brief World rules as a project file (`.esworld`): biomes, recipes and layers as data, which artists and designers edit and a+ * package carries with every mesh and material they name.+ *+ * @details The file is the rules' JSON: what `registerWorldRules` takes, less the fields made by code (a game's own fields stay in+ * code). Meshes and materials are named by their project paths, so the cook follows them from the file as it follows a+ * material's textures. A file that does not say what rules need is refused with where it went wrong, rather than laying out+ * a world from half of it.+ */+import type { AssetLoader, LoadContext } from '../asset/AssetLoader';+import type { BiomeDef, PlacementLayer, Recipe, RecipeMember, WorldRules } from './rules';++/** Whether a WorldGen's `rules` names a file rather than rules registered by code. */+export function isRulesFile(ref: string): boolean {+ return ref.endsWith('.esworld') || ref.startsWith('@uuid:');+}++const fail = (where: string, what: string): never => { throw new Error(`${where}: ${what}`); };++function num(v: unknown, where: string, min = -Infinity): number {+ if (typeof v !== 'number' || !Number.isFinite(v) || v < min) fail(where, `a number${min > -Infinity ? ` of at least ${min}` : ''}, not ${JSON.stringify(v)}`);+ return v as number;+}++function str(v: unknown, where: string): string {+ if (typeof v !== 'string' || v.length === 0) fail(where, `a name, not ${JSON.stringify(v)}`);+ return v as string;+}++function range(v: unknown, where: string): [number, number] | undefined {+ if (v === undefined) return undefined;+ if (!Array.isArray(v) || v.length !== 2) fail(where, 'two numbers, [least, most]');+ const a = num((v as unknown[])[0], where), b = num((v as unknown[])[1], where);+ if (b < a) fail(where, 'the least is more than the most');+ return [a, b];+}++function member(v: unknown, where: string): RecipeMember {+ if (!v || typeof v !== 'object') fail(where, 'a member, an object');+ const m = v as Record<string, unknown>;+ const mesh = m.mesh;+ if (typeof mesh !== 'string' && typeof mesh !== 'number') fail(`${where}.mesh`, 'a mesh path');+ return {+ ...(m as object),+ id: str(m.id, `${where}.id`),+ mesh: mesh as string | number,+ footprint: num(m.footprint, `${where}.footprint`, 0),+ count: range(m.count, `${where}.count`),+ ring: range(m.ring, `${where}.ring`),+ arc: range(m.arc, `${where}.arc`),+ scale: range(m.scale, `${where}.scale`),+ } as RecipeMember;+}++/** Rules from a file's JSON, checked; throws naming the first thing a world could not be laid out from. */+export function parseWorldRules(json: unknown, file = 'world rules'): WorldRules {+ if (!json || typeof json !== 'object') fail(file, 'an object');+ const r = json as Record<string, unknown>;+ const id = str(r.id, `${file}.id`);+ if (!Array.isArray(r.versions) || r.versions.length === 0) fail(`${file}.versions`, 'the versions it can make, at least one');+ const versions = (r.versions as unknown[]).map((v, i) => num(v, `${file}.versions[${i}]`, 1));+ if (!Array.isArray(r.recipes)) fail(`${file}.recipes`, 'a list');+ const recipes: Recipe[] = (r.recipes as unknown[]).map((v, i) => {+ const where = `${file}.recipes[${i}]`;+ const o = (v ?? {}) as Record<string, unknown>;+ return {+ ...(o as object),+ id: str(o.id, `${where}.id`), version: num(o.version, `${where}.version`, 1),+ anchor: member(o.anchor, `${where}.anchor`),+ members: Array.isArray(o.members) ? (o.members as unknown[]).map((m, k) => member(m, `${where}.members[${k}]`)) : undefined,+ } as Recipe;+ });+ if (!Array.isArray(r.layers) || r.layers.length === 0) fail(`${file}.layers`, 'at least one layer');+ const layers: PlacementLayer[] = (r.layers as unknown[]).map((v, i) => {+ const where = `${file}.layers[${i}]`;+ const o = (v ?? {}) as Record<string, unknown>;+ return {+ ...(o as object),+ id: str(o.id, `${where}.id`), spacing: num(o.spacing, `${where}.spacing`, 1e-6), drawDistance: num(o.drawDistance, `${where}.drawDistance`, 0),+ } as PlacementLayer;+ });+ const recipeIds = new Set(recipes.map((x) => x.id)), layerIds = new Set(layers.map((x) => x.id));+ if (!Array.isArray(r.biomes)) fail(`${file}.biomes`, 'a list');+ const biomes: BiomeDef[] = (r.biomes as unknown[]).map((v, i) => {+ const where = `${file}.biomes[${i}]`;+ const o = (v ?? {}) as Record<string, unknown>;+ if (!Array.isArray(o.conditions)) fail(`${where}.conditions`, 'a list (empty holds everywhere)');+ if (!Array.isArray(o.recipes)) fail(`${where}.recipes`, 'a list');+ for (const [k, br] of (o.recipes as Record<string, unknown>[]).entries()) {+ if (!recipeIds.has(br.recipe as string)) fail(`${where}.recipes[${k}].recipe`, `no recipe ${JSON.stringify(br.recipe)} in the file`);+ if (!layerIds.has(br.layer as string)) fail(`${where}.recipes[${k}].layer`, `no layer ${JSON.stringify(br.layer)} in the file`);+ num(br.density, `${where}.recipes[${k}].density`, 0);+ }+ return { ...(o as object), id: str(o.id, `${where}.id`) } as BiomeDef;+ });+ return { id, versions, biomes, recipes, layers, ...(r.noise ? { noise: r.noise as WorldRules['noise'] } : {}) };+}++/** Loads `.esworld` files as checked world rules. */+export class WorldRulesAssetLoader implements AssetLoader<WorldRules> {+ readonly type = 'world-rules';+ readonly extensions = ['.esworld'];++ async load(path: string, ctx: LoadContext): Promise<WorldRules> {+ const text = await ctx.loadText(ctx.catalog.getBuildPath(path));+ return parseWorldRules(JSON.parse(text), path);+ }++ unload(): void {+ // Rules are plain data; the meshes they name are loaded and held by the world that lays them out.+ }+}diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.tsindex 0a514ef1f..ca0cb8b82 100644--- a/sdk/src/worldgen/worldgenPlugin.ts+++ b/sdk/src/worldgen/worldgenPlugin.ts@@ -37,6 +37,7 @@ import { WorldPlan, type Placement } from './plan';import { worldRules, worldRulesRevision, type PlacementLayer, type RecipeMember, type WorldRules } from './rules';import { Zones, type ZoneDef } from './zones';import { PlacementDiffs } from './diffs';+import { isRulesFile } from './rulesAsset';/** The fields of the `WorldGen` component. @experimental */export interface WorldGenData {@@ -59,7 +60,7 @@ export const WorldGen: ComponentDef<WorldGenData> = defineComponent<WorldGenDatarules: '', 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.' },+ rules: { tooltip: 'The rules the world is laid out by: a .esworld file, or the id of rules the game registered 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.' },@@ -225,6 +226,9 @@ export const WorldGenRes = defineResource<WorldGens>(new WorldGens(), 'WorldGensexport class WorldGenPlugin implements Plugin {name = 'worldgen';+ /** Stops listening for edited rules files. */+ private watching_: (() => void) | null = null;+/** Each mesh's geometry, read once, for drawing it merged. */private readonly meshData_ = new Map<number, MeshData | null | Promise<MeshData | null>>();@@ -249,6 +253,8 @@ export class WorldGenPlugin implements Plugin {}cleanup(app?: App): void {+ this.watching_?.();+ this.watching_ = null;if (!app?.hasResource(WorldGenRes)) return;const gens = app.getResource(WorldGenRes);for (const entity of [...gens.built_.keys()]) this.drop(app, gens, entity);@@ -257,22 +263,59 @@ export class WorldGenPlugin implements Plugin {/** 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(), levelling: new Set() };+ // Rules in a project file are read first, then made like rules registered by code.+ if (isRulesFile(data.rules)) {+ if (!app.hasResource(Assets)) {+ built.failure = `the world rules file ${data.rules} cannot be read without an asset system: register its rules in code instead`;+ log.error('worldgen', built.failure);+ return built;+ }+ const assets = app.getResource(Assets);+ // A rules file edited and saved is read again, and the world laid out by it again (its old chunks kept until then).+ if (!this.watching_) {+ this.watching_ = assets.onInvalidate(({ ref }) => {+ const changed = assets.resolveLoadPath(ref);+ for (const b of gens.built_.values()) if (isRulesFile(b.data.rules) && assets.resolveLoadPath(b.data.rules) === changed) b.signature = '';+ });+ }+ void assets.load<WorldRules>('world-rules', data.rules).then((rules) => {+ if (gens.built_.get(entity) !== built) return;+ this.adopt(app, gens, entity, built, rules, had);+ }, (e: unknown) => {+ if (gens.built_.get(entity) !== built) return;+ built.failure = `the world rules file ${data.rules} could not be read: ${e instanceof Error ? e.message : String(e)}`;+ log.error('worldgen', built.failure);+ });+ return built;+ }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(', ')})`;+ if (!rules) {+ built.failure = `no world rules ${data.rules || '(none named)'} are registered`;+ log.error('worldgen', `the world ${data.world} cannot be laid out: ${built.failure}`);+ for (const l of had?.rules?.layers ?? []) chunksOf(app).remove(layerIdOf(entity, l.id));+ return built;+ }+ this.adopt(app, gens, entity, built, rules, had);+ return built;+ }++ /** Takes a WorldGen's rules, once they are known: checks the version, and makes the plan (loading what the recipes name first). */+ private adopt(app: App, gens: WorldGens, entity: Entity, built: BuiltWorld, rules: WorldRules, had: BuiltWorld | undefined): void {+ const data = built.data;+ 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;+ return;}// 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));+ 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!);+ const refs = assetRefsOf(rules);if (refs.length > 0 && app.hasResource(Assets)) {- void this.resolve(app, rules!, refs).then((resolved) => {+ 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);@@ -280,10 +323,9 @@ export class WorldGenPlugin implements Plugin {built.failure = `the recipes' assets could not be loaded: ${e instanceof Error ? e.message : String(e)}`;log.error('worldgen', built.failure);});- return built;+ return;}- this.plan(app, gens, entity, built, rules!);- return built;+ this.plan(app, gens, entity, built, rules);}/** Loads the meshes and materials `refs` name, and gives back the rules with each path replaced by its handle. */diff --git a/sdk/src/worldgen/worldgenSupport.ts b/sdk/src/worldgen/worldgenSupport.tsindex 0e89164ee..cc0c3b193 100644--- a/sdk/src/worldgen/worldgenSupport.ts+++ b/sdk/src/worldgen/worldgenSupport.ts@@ -6,8 +6,11 @@* A call, not a file's side effect — see tilemap/tilemapSupport.ts.*/import { addEntryPlugin } from '../runtime/entryPlugins';+import { addAssetLoader } from '../asset/optionalLoaders';import { WorldGenPlugin } from './worldgenPlugin';+import { WorldRulesAssetLoader } from './rulesAsset';export function registerWorldGenSupport(): void {addEntryPlugin('worldgen', () => new WorldGenPlugin());+ addAssetLoader('worldgen', () => new WorldRulesAssetLoader());}diff --git a/sdk/tests/worldgen-rules-asset.test.ts b/sdk/tests/worldgen-rules-asset.test.tsnew file mode 100644index 000000000..be0b35717--- /dev/null+++ b/sdk/tests/worldgen-rules-asset.test.ts@@ -0,0 +1,40 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file World rules as a project file: checked when read, refused with where they went wrong.+ */+import { describe, expect, it } from 'vitest';+import { isRulesFile, parseWorldRules } from '../src/worldgen/rulesAsset';++const good = {+ id: 'game:wilds', versions: [1],+ biomes: [{ id: 'forest', conditions: [{ field: 'moisture', min: 0.5 }], recipes: [{ recipe: 'grove', layer: 'groups', density: 0.7 }] }],+ recipes: [{ id: 'grove', version: 1, anchor: { id: 'oak', mesh: 'assets/models/oak.esmesh', footprint: 8 },+ members: [{ id: 'sapling', mesh: 'assets/models/oak.esmesh', count: [2, 4], ring: [10, 20], footprint: 2 }] }],+ layers: [{ id: 'groups', spacing: 100, drawDistance: 2000 }],+};++describe('a world rules file', () => {+ it('reads as the rules code would register', () => {+ const rules = parseWorldRules(JSON.parse(JSON.stringify(good)), 'wilds.esworld');+ expect(rules.id).toBe('game:wilds');+ expect(rules.recipes[0]!.members![0]!.count).toEqual([2, 4]);+ expect(rules.layers[0]!.spacing).toBe(100);+ });++ it('is refused with where it went wrong', () => {+ const bad = (patch: (r: any) => void) => { const r = JSON.parse(JSON.stringify(good)); patch(r); return () => parseWorldRules(r, 'wilds.esworld'); };+ expect(bad((r) => { r.versions = []; })).toThrow(/wilds\.esworld\.versions/);+ expect(bad((r) => { r.biomes[0].recipes[0].recipe = 'nothing'; })).toThrow(/no recipe "nothing"/);+ expect(bad((r) => { r.biomes[0].recipes[0].layer = 'nowhere'; })).toThrow(/no layer "nowhere"/);+ expect(bad((r) => { r.recipes[0].anchor.footprint = -1; })).toThrow(/anchor\.footprint/);+ expect(bad((r) => { r.recipes[0].members[0].count = [4, 2]; })).toThrow(/count/);+ expect(bad((r) => { r.layers[0].spacing = 0; })).toThrow(/spacing/);+ });++ it('is told apart from rules registered by code', () => {+ expect(isRulesFile('assets/worlds/wilds.esworld')).toBe(true);+ expect(isRulesFile('@uuid:0b0c8d64-4a3e-4b55-9b1b-2b0f5a0d8f21')).toBe(true);+ expect(isRulesFile('game:wilds')).toBe(false);+ });+});diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.jsindex cd0f287e1..aba5b2d91 100644--- a/tools/assetMetaTable.js+++ b/tools/assetMetaTable.js@@ -98,6 +98,7 @@ export const EXT_TO_TYPE = Object.freeze({'.esavatar': 'avatar','.eslocale': 'locale','.esaudioevent': 'sound-event',+ '.esworld': 'world-rules','.inputmap': 'inputmap',// Fonts'.fnt': 'bitmapFont',diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjsindex 6d654813a..d4493a8f7 100644--- a/tools/check-corpus-authoring.mjs+++ b/tools/check-corpus-authoring.mjs@@ -65,6 +65,7 @@ const NOT_INSTANCE_FORMATS = {'.estimeline': 'a timeline: tracks over time, addressed to entities the scene owns','.esanim': 'a clip: curves over time','.esaudioevent': 'an audio event definition; source instances belong to scenes',+ '.esworld': 'world rules: biomes, recipes and layers as data; the WorldGen that names the file belongs to a scene','.esavatar': 'how one rig spells the joints another rig\'s clips name','.esmaterial': 'a material: shader + uniform values','.esshader': 'shader source',diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex b67df1d1b..e04c322cd 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2796,4 +2796,8 @@ export const NOTED = {{"note":"Terrain modifiers, and zones that level their ground."},"feat(water): how far a dry place is from the water's edge, as a query and a field generated worlds read":{"note":"How far a place is from the water."},+ "feat(worldgen): world rules as a .esworld asset, checked on load, shipped with what they name and rebuilt on edit":+ {"note":"World rules as a file, with an editor."},+ "feat(editor): world rules editor for .esworld files":+ {"note":"World rules as a file, with an editor."},};