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(voxel): ground that is a volume, carved while the game runs, with collision that follows and saves by chunk
yhh4410b2bc3e2f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c96149411..c5d53f07b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **Ground that is a volume.** The optional `esengine/voxel` module adds `VoxelTerrain`, beside the height-field Terrain: it holds caves and overhangs, and can be carved, filled and painted with a sphere, a box or a capsule while the game runs. Only the chunks an edit reached are made again, with their collision, and a save holds only what was changed, chunk by chunk. A sleeping body is now woken when the collision under it changes, on a Terrain as well, where before it stayed in the air.- **What stands on the ground can blend into it.** The `builtin:ground-blend` material fades a rock or a foundation into whatever is behind it, on both backends, with nothing baked, and can bring a second layer up from the ground or paint one with vertex colours. `RoadDecal` lays a mesh along a Spline over a terrain with soft edges. The `snowCover` post effect and a Snow weather lay snow on whatever faces the sky, terrain and meshes alike.- **GPU particles can hit things, tell each other, and drag trails.** `collisionMode: Depth` collides with what the camera sees, `Sdf` with `ParticleCollider` spheres, boxes and capsules that need no physics (and run on the CPU too). A GPU emitter's births, deaths and collisions go to a buffer: a `gpuSimulation` child spawns from it in its own kernel, with no trip to the CPU, and `collisionEvents` read back to the game a frame or two late. `trailEnabled` now works on the GPU.- **Plants can be touched, felled and harvested.** A `FoliageContact` on a character parts `Foliage` grass around it, on both backends. A kind in `PlacedFoliage` or `WorldRules.plants` with an `interaction` leans away with any material, becomes an entity with a physics capsule while something is near, and can be damaged, felled and harvested through `PlantInteractionRes`, with stumps, regrowth and `saveState` / `loadState`; what became of a plant outlasts its chunk.diff --git a/desktop b/desktopindex a507f07fe..4dd611bd1 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit a507f07fe7ed416a0f8b15a382bb1e2f20cdf0b3+Subproject commit 4dd611bd18ea5d3218c56077314d27b409176fe4diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjsindex bcdf301f1..2e08db611 100644--- a/docs/astro/astro.config.mjs+++ b/docs/astro/astro.config.mjs@@ -299,6 +299,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: 'Voxel Terrain', translations: { 'zh-CN': '体积地形' }, slug: 'world/voxel-terrain' },{ label: 'Generated Worlds', translations: { 'zh-CN': '生成世界' }, slug: 'world/generation' },],},diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdxindex 24f670125..4d868e28c 100644--- a/docs/astro/src/content/docs/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/graphics/terrain.mdx@@ -333,6 +333,8 @@ Such a material is drawn after a copy of the opaque scene is taken, the way wate## Limits+- **It is a height for each place.** A cave, an overhang or a hole needs [Voxel Terrain](/docs/world/voxel-terrain/), a separate ground that is a volume.+- **Collision is the finest level.** Far off the ground is drawn coarser than it collides, which is unseen from where anything collideswith it; only what moves gets ground to hit, within `collisionDistance`.- **Paint is as fine as the pages.** Layer weights are sampled with the heights, two to a cell, so a splatmap finer than that near thediff --git a/docs/astro/src/content/docs/world/voxel-terrain.mdx b/docs/astro/src/content/docs/world/voxel-terrain.mdxnew file mode 100644index 000000000..1e025bb7c--- /dev/null+++ b/docs/astro/src/content/docs/world/voxel-terrain.mdx@@ -0,0 +1,97 @@+---+title: Voxel Terrain+description: Ground that is a volume, so it can hold caves and overhangs — carved while the game runs, with its collision following and its changes saved chunk by chunk.+---++A [Terrain](/docs/graphics/terrain/) has one height for each place, so it cannot hold a cave, an overhang or a hole. A `VoxelTerrain` stores a signed distance at every point of a 3D grid, so it can. Use it where the ground itself is what the game changes: mining, survival, a world that can be blown apart. It stands beside Terrain and does not replace it, and it is an optional module (`esengine/voxel`) that a game without one does not carry.++## Add one++Put a `VoxelTerrain` on an entity. Its position places the volume; its rotation and scale do not apply. With nothing else set you get hills with tunnels through them, soil over rock, and pockets of ore.++| Field | What it does |+|---|---|+| `cellSize` | The side of a cell, the finest thing the ground can show. Half the size is eight times the cells. |+| `chunkCells` | How many cells a chunk has a side. Smaller makes less again for each edit and draws more meshes. |+| `minY`, `maxY` | How far down and up the volume goes from the entity. It is closed at both ends: nothing digs through its floor or builds past its top. |+| `seed`, `surfaceHeight`, `hillHeight`, `hillScale` | The stock ground's hills. |+| `caveWidth`, `caveScale` | How wide its tunnels are and how far apart. `caveWidth` at `0` has none. |+| `soilDepth`, `oreAmount` | How deep the soil goes, and how much of the rock is ore. |+| `drawDistance`, `castShadows` | How far from the eye it is drawn, and whether it casts shadows. |+| `collision`, `collisionDistance`, `collisionLayer`, `friction` | Whether 3D bodies and characters collide with it, and how far round each one it is built. |+| `color0`..`color3`, `map0`..`map3`, `tile` | Each material's colour and picture, and the length of one repeat in the world. Pictures are laid from the three sides by world position, since a surface found afterwards has no uv. |+| `material` | A material on the `builtin:voxel-ground` shader, in place of the stock one. |++The four materials are `VoxelMaterial.Topsoil`, `Soil`, `Rock` and `Ore`.++## Dig++Everything goes through the `VoxelTerrains` resource, and places are in the world.++```ts+import { VoxelTerrain, VoxelTerrainsRes, VoxelMaterial } from 'esengine/voxel';++const voxels = app.getResource(VoxelTerrainsRes);++// What the player is looking at.+const hit = voxels.raycast(eye, forward, 8);+if (hit) {+ const dug = voxels.carve(hit.entity, { kind: 'sphere', center: hit.point, radius: 1.5 }, {+ keep: (material) => material === VoxelMaterial.Ore && !hasPick,+ });+ inventory.add('stone', dug.removed[VoxelMaterial.Rock]);+}+```++`carve` answers with how much of each material came out, in cubic world units, which is what a miner carries away. Shapes are `sphere`, `box` and `capsule`, the last being how to cut a tunnel in one call.++| Call | What it does |+|---|---|+| `carve(entity, shape, options)` | Takes a shape out. |+| `fill(entity, shape, material, options)` | Fills a shape with a material. |+| `edit(entity, shape, 'paint', { material })` | Changes the material inside a shape, and not its form. |+| `raycast(origin, direction, maxDistance)` | Where a ray first meets any volume: the point, the normal, the material and the entity. |+| `distanceAt(entity, at)`, `materialAt(entity, at)` | What is at a place. Below zero is solid. |+| `onEdit(listener)` | Hears every edit that changed something: how to keep a navmesh or a quest in step. |+| `collisionReadyAt(entity, x, z)` | Whether the ground there is built for collision, to wait on before dropping something. |+| `status(entity)` | Chunks and triangles drawn, chunks held and edited, and what the last remake cost. |++`smooth` in the options melts the shape's edge into what it meets, in world units, and `keep` names the materials an edit cannot change.++Only the chunks an edit reached are made again, and collision with them; the old mesh stays until the new one is ready, and at least one chunk is made each frame. A body resting on what was dug out is woken and falls.++## Make your own ground++`setSource` replaces the stock hills with a function of the place. It must answer the same for the same place, because a chunk nothing changed is let go and asked for again.++```ts+voxels.setSource(entity, (x, y, z, out) => {+ out.distance = y - Math.sin(x * 0.1) * 4; // below zero is solid; near the surface it should be about true+ out.material = VoxelMaterial.Rock;+});+```++`heightVoxelSource` gives a body to any height field, so `heightVoxelSource((x, z) => terrains.heightAt(x, z))` makes a volume of a Terrain's own ground.++## Save++A save holds only the chunks that were edited, as plain JSON. A world without end costs what the player changed in it.++```ts+const whole = voxels.serialize(entity); // every edited chunk+const delta = voxels.serialize(entity, true); // only those changed since the last such call+voxels.restore(entity, whole); // put it back: all else returns to the source+voxels.restore(entity, delta, true); // lay chunks over what is there+```++The seed or source must be the one the save was made with. A save cut from another grid (another `cellSize` or `chunkCells`) is refused and changes nothing: `restore` answers `false`. A chunk that cannot be read is left as it was, with a warning.++## Limits++- **No levels of detail.** Every chunk within `drawDistance` is drawn at full detail. The stock ground at `drawDistance` 96 and `cellSize` 1 is about 170 chunks and 240 000 triangles, so far views cost more than a [Terrain](/docs/graphics/terrain/) does.+- **No brush in the editor.** The volume is drawn while a scene is laid out, but changes are made from code at run time.+- **It does not cut a hole in a Terrain.** The two are separate grounds. To dig into a Terrain's shape, make a volume of it with `heightVoxelSource` and draw that instead.+- **Edited chunks are held in memory whole,** about 35 KB each at the default 24 cells, for as long as the game runs.+- **Navigation does not follow by itself.** Use `onEdit` to rebuild what a game needs.+- **Pictures have no normal maps,** and four materials is the most a volume has. A custom `material` must be on the Voxel Ground shader, or the vertex colours that say which material a place is will read as a tint.+- **Not measured on a device.** On a desktop, an edit reaching three chunks with collision takes about 4 ms of the frame, up to 8 ms. A first edit in ground no one has read yet also has to make it: about 3 ms for each chunk.diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdxindex 04fcb2eff..7ad168a07 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx@@ -257,6 +257,7 @@ registerPlanetProvider({## 限制+- **每个位置只有一个高度。** 洞穴、悬垂和孔洞需要[体积地形](/docs/zh-cn/world/voxel-terrain/),它是独立的体积地面。- **Ground Blend 淡出成身后看到的东西。** 身后没有贴近的东西时(比如岩石侧面背后是远处的山谷),就没有接缝要藏,也不会藏。紧贴在 Ground Blend 物体身后的墙和地面一样算贴近。两个这样的物体不会互相融合,因为它们都不在对方读取的拷贝里。它需要浮点渲染目标,没有时就是普通的 Model。- **`snowCover` 是铺在画面上的。** 它没有厚度,不会让边缘变圆,也埋不住石头,并且只作用于相机看到的部分。- **碰撞按最细一级。** 远处的地面画得比碰撞粗,但碰撞发生的地方看不出来;只有运动的物体在 `collisionDistance` 内才有可碰的地面。diff --git a/docs/astro/src/content/docs/zh-cn/world/voxel-terrain.mdx b/docs/astro/src/content/docs/zh-cn/world/voxel-terrain.mdxnew file mode 100644index 000000000..62b1a393c--- /dev/null+++ b/docs/astro/src/content/docs/zh-cn/world/voxel-terrain.mdx@@ -0,0 +1,97 @@+---+title: 体积地形+description: 地面是一个体积,所以能有洞穴和悬垂结构;游戏运行时可以开挖,碰撞随之更新,改动按块存档。+---++[Terrain](/docs/zh-cn/graphics/terrain/) 每个位置只有一个高度,所以表现不了洞穴、悬垂和孔洞。`VoxelTerrain` 在三维网格的每个点上存一个有符号距离,所以可以。适合地面本身就是玩法的游戏:采矿、生存、可破坏世界。它和 Terrain 并存,不替换 Terrain;它是可选模块(`esengine/voxel`),不用它的游戏不会带上它。++## 添加++给实体加上 `VoxelTerrain`。实体的位置决定体积的位置,旋转和缩放不起作用。什么都不设置时,你会得到带隧道的丘陵,土壤在岩石之上,岩石里有矿脉。++| 字段 | 作用 |+|---|---|+| `cellSize` | 格子边长,也是地面能表现的最小尺度。边长减半,格子数变成八倍。 |+| `chunkCells` | 一个块每边的格子数。越小,每次编辑重建得越少,绘制的网格越多。 |+| `minY`、`maxY` | 体积从实体向下、向上延伸多远。两端封闭:挖不穿底,也建不过顶。 |+| `seed`、`surfaceHeight`、`hillHeight`、`hillScale` | 默认地面的丘陵。 |+| `caveWidth`、`caveScale` | 隧道的宽度和间距。`caveWidth` 为 `0` 时没有隧道。 |+| `soilDepth`、`oreAmount` | 土壤深度,以及岩石里矿的比例。 |+| `drawDistance`、`castShadows` | 离视点多远内绘制,以及是否投射阴影。 |+| `collision`、`collisionDistance`、`collisionLayer`、`friction` | 3D 刚体和角色是否与它碰撞,以及围绕它们构建碰撞的范围。 |+| `color0`..`color3`、`map0`..`map3`、`tile` | 每种材质的颜色和贴图,以及贴图在世界中一次重复的长度。贴图按世界位置从三个方向投射,因为事后提取的表面没有 uv。 |+| `material` | 使用 `builtin:voxel-ground` 着色器的材质,用来替换默认材质。 |++四种材质是 `VoxelMaterial.Topsoil`、`Soil`、`Rock` 和 `Ore`。++## 开挖++所有操作都通过 `VoxelTerrains` 资源,位置都是世界坐标。++```ts+import { VoxelTerrain, VoxelTerrainsRes, VoxelMaterial } from 'esengine/voxel';++const voxels = app.getResource(VoxelTerrainsRes);++// 玩家看着的地方。+const hit = voxels.raycast(eye, forward, 8);+if (hit) {+ const dug = voxels.carve(hit.entity, { kind: 'sphere', center: hit.point, radius: 1.5 }, {+ keep: (material) => material === VoxelMaterial.Ore && !hasPick,+ });+ inventory.add('stone', dug.removed[VoxelMaterial.Rock]);+}+```++`carve` 返回每种材质被挖走多少,单位是立方世界单位,也就是矿工能带走的量。形状有 `sphere`、`box` 和 `capsule`,用 `capsule` 一次调用就能挖出一条隧道。++| 调用 | 作用 |+|---|---|+| `carve(entity, shape, options)` | 挖掉一个形状。 |+| `fill(entity, shape, material, options)` | 用某种材质填充一个形状。 |+| `edit(entity, shape, 'paint', { material })` | 改变形状内的材质,不改变外形。 |+| `raycast(origin, direction, maxDistance)` | 射线最先碰到哪个体积:点、法线、材质和实体。 |+| `distanceAt(entity, at)`、`materialAt(entity, at)` | 某个位置是什么。小于零是实心。 |+| `onEdit(listener)` | 监听每一次产生变化的编辑,用来同步导航网格或任务。 |+| `collisionReadyAt(entity, x, z)` | 那里的碰撞是否已构建,放东西之前可以等它。 |+| `status(entity)` | 绘制的块数和三角形数、持有和编辑过的块数,以及上次重建的耗时。 |++选项里的 `smooth` 让形状边缘融入相邻部分,单位是世界单位;`keep` 指定这次编辑不能改变的材质。++只有编辑波及的块和它们的碰撞会重建;新网格就绪前旧网格保持不变,每帧至少重建一块。原本压在被挖部分上的物体会被唤醒并掉落。++## 自定义地面++`setSource` 用一个关于位置的函数替换默认丘陵。相同位置必须返回相同结果,因为没有改动过的块会被释放,之后再重新询问。++```ts+voxels.setSource(entity, (x, y, z, out) => {+ out.distance = y - Math.sin(x * 0.1) * 4; // 小于零是实心;靠近表面时应大致等于真实距离+ out.material = VoxelMaterial.Rock;+});+```++`heightVoxelSource` 能给任意高度场一个实体,所以 `heightVoxelSource((x, z) => terrains.heightAt(x, z))` 可以把 Terrain 自己的地面变成体积。++## 存档++存档只包含编辑过的块,是普通 JSON。无尽世界的存档大小只取决于玩家改了多少。++```ts+const whole = voxels.serialize(entity); // 所有编辑过的块+const delta = voxels.serialize(entity, true); // 只有上次这样调用之后改动的块+voxels.restore(entity, whole); // 恢复:其余部分回到生成源的样子+voxels.restore(entity, delta, true); // 把这些块叠加到现有内容上+```++种子或生成源必须和存档时相同。来自其他网格(`cellSize` 或 `chunkCells` 不同)的存档会被拒绝且不做任何改动,`restore` 返回 `false`。读不了的块保持原样并给出警告。++## 限制++- **没有 LOD。** `drawDistance` 内的块都是全精度绘制。默认地面在 `drawDistance` 96、`cellSize` 1 时约 170 块、24 万三角形,远景开销比 [Terrain](/docs/zh-cn/graphics/terrain/) 高。+- **编辑器里没有笔刷。** 布置场景时体积会被绘制,但改动只能在运行时用代码完成。+- **不能在 Terrain 上开洞。** 两者是各自独立的地面。想挖 Terrain 的形状,用 `heightVoxelSource` 生成体积,并改为绘制体积。+- **编辑过的块完整保存在内存里,** 默认 24 格时每块约 35 KB,游戏运行期间一直保留。+- **导航不会自动更新。** 用 `onEdit` 重建游戏需要的部分。+- **贴图没有法线贴图,** 一个体积最多四种材质。自定义 `material` 必须使用 Voxel Ground 着色器,否则表示材质权重的顶点色会被当成染色。+- **没有在真机上测过。** 在桌面上,一次波及三块且带碰撞的编辑约占帧时间 4 ms,最高 8 ms。如果是第一次编辑还没读取过的地面,还要加上生成开销:每块约 3 ms。diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 34409d43d..03917785e 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 178,- "experimental": 2939,+ "experimental": 2965,"deprecated": 3},- "total": 3232,+ "total": 3258,"subsystems": [{"id": "mobile-controls",@@ -381,6 +381,18 @@"Foliage"]},+ {+ "id": "voxel",+ "title": "Voxel terrain",+ "titleZh": "体积地形",+ "tier": "experimental",+ "why": "carving, the skin, collision and saves are checked against the real solver and on both backends, but it has no levels of detail or editor brush, and nothing has been measured on a device",+ "whyZh": "开挖、网格、碰撞和存档都用真实求解器和两个后端检查过,但还没有 LOD 和编辑器笔刷,也没有在真机上测过",+ "entry": [+ "VoxelTerrain",+ "VoxelTerrains"+ ]+ },{"id": "spline","title": "Splines",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex 67bce6418..0c0d7c57f 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -194,6 +194,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {PlatformerController2D: { category: 'physics', summary: 'Runs and jumps a CharacterController2D from the keyboard or a game, with coyote time, a jump buffer and dropping through one-way platforms.', doc: 'gameplay/physics', anchor: 'platformer-controller' },FoliageContact: { category: 'physics', summary: 'Something plants feel: grass parts around it, shrubs lean away, and placed plants near it become entities with colliders.', doc: 'graphics/foliage', anchor: 'touching-plants' },PlantProxy: { category: 'physics', summary: 'The entity standing in for a placed plant while something is near it, which a ray or a collision finds.', doc: 'graphics/foliage', anchor: 'touching-plants' },+ VoxelTerrain: { category: 'world', summary: 'Ground that is a volume, so it can hold caves and overhangs, and be carved while the game runs.', doc: 'world/voxel-terrain' },RoadDecal: { category: 'world', summary: 'Lays the entity\'s mesh along a Spline and over the ground, its edges fading into what it lies on.', doc: 'graphics/terrain', anchor: 'blending-what-stands-on-the-ground' },OneWayPlatform2D: { category: 'physics', summary: 'Makes a collider solid from one side only, so a body passes up through it and lands on top.', doc: 'gameplay/physics', anchor: 'one-way-platforms', anchorZh: '单向平台' },DistanceJoint2D: { category: 'physics', summary: 'Holds two bodies a fixed (or spring-limited) distance apart.', doc: 'gameplay/physics', anchor: 'joints', anchorZh: '关节' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 7256f85e8..2cd9543c8 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -9628,6 +9628,233 @@"handle"]},+ {+ "name": "VoxelTerrain",+ "source": "ts",+ "fields": [+ {+ "key": "cellSize",+ "type": "number",+ "default": "1",+ "doc": "The side of a cell: the finest thing the ground can show. Half the size is eight times the cells.",+ "range": "≥ 0.05"+ },+ {+ "key": "chunkCells",+ "type": "number",+ "default": "24",+ "doc": "How many cells a chunk has a side. Smaller makes less again for each edit and draws more meshes.",+ "range": "8–64, step 1",+ "advanced": true+ },+ {+ "key": "minY",+ "type": "number",+ "default": "-48",+ "doc": "How far down the volume goes from the entity. Nothing digs through its floor."+ },+ {+ "key": "maxY",+ "type": "number",+ "default": "48",+ "doc": "How far up the volume goes from the entity. Nothing is built past it."+ },+ {+ "key": "seed",+ "type": "number",+ "default": "1",+ "doc": "Another seed is another ground. A save holds what was changed in the ground this seed makes.",+ "range": "step 1"+ },+ {+ "key": "surfaceHeight",+ "type": "number",+ "default": "8",+ "doc": "Where the ground lies on average, from the entity."+ },+ {+ "key": "hillHeight",+ "type": "number",+ "default": "14",+ "doc": "How far the hills rise and fall from it.",+ "range": "≥ 0"+ },+ {+ "key": "hillScale",+ "type": "number",+ "default": "60",+ "doc": "How wide the hills are.",+ "range": "≥ 1"+ },+ {+ "key": "caveWidth",+ "type": "number",+ "default": "2.5",+ "doc": "How wide the tunnels through the ground are. 0 has none.",+ "range": "≥ 0"+ },+ {+ "key": "caveScale",+ "type": "number",+ "default": "36",+ "doc": "How far apart the tunnels are.",+ "range": "≥ 1"+ },+ {+ "key": "soilDepth",+ "type": "number",+ "default": "5",+ "doc": "How deep the soil goes before rock.",+ "range": "≥ 0"+ },+ {+ "key": "oreAmount",+ "type": "number",+ "default": "0.06",+ "doc": "How much of the rock is ore.",+ "range": "0–1, step 0.01"+ },+ {+ "key": "drawDistance",+ "type": "number",+ "default": "96",+ "doc": "How far from the eye the ground is drawn.",+ "range": "≥ 1"+ },+ {+ "key": "castShadows",+ "type": "boolean",+ "default": "true",+ "doc": "Whether the ground casts shadows."+ },+ {+ "key": "collision",+ "type": "boolean",+ "default": "true",+ "doc": "Whether 3D bodies and characters collide with the ground."+ },+ {+ "key": "collisionDistance",+ "type": "number",+ "default": "32",+ "doc": "How far round each moving body and character the ground is built for collision.",+ "range": "≥ 1"+ },+ {+ "key": "collisionLayer",+ "type": "number",+ "default": "0",+ "doc": "The collision layer the ground is in (0 to 15).",+ "range": "0–15, step 1",+ "advanced": true+ },+ {+ "key": "friction",+ "type": "number",+ "default": "0.6",+ "doc": "How much the ground holds what slides on it.",+ "range": "≥ 0",+ "advanced": true+ },+ {+ "key": "material",+ "type": "Asset<material>",+ "default": "none",+ "doc": "A material on the Voxel Ground shader. Empty uses the stock one, with the colours and pictures below."+ },+ {+ "key": "color0",+ "type": "Color",+ "default": "#4d6b33"+ },+ {+ "key": "color1",+ "type": "Color",+ "default": "#5c452e"+ },+ {+ "key": "color2",+ "type": "Color",+ "default": "#6b6966"+ },+ {+ "key": "color3",+ "type": "Color",+ "default": "#b88c40"+ },+ {+ "key": "map0",+ "type": "Asset<texture>",+ "default": "none",+ "doc": "Laid from the three sides by world position."+ },+ {+ "key": "map1",+ "type": "Asset<texture>",+ "default": "none",+ "doc": "Laid from the three sides by world position."+ },+ {+ "key": "map2",+ "type": "Asset<texture>",+ "default": "none",+ "doc": "Laid from the three sides by world position."+ },+ {+ "key": "map3",+ "type": "Asset<texture>",+ "default": "none",+ "doc": "Laid from the three sides by world position."+ },+ {+ "key": "tile",+ "type": "number",+ "default": "8",+ "doc": "How long one repeat of the pictures is in the world.",+ "range": "≥ 0.01"+ }+ ],+ "animatable": [+ "cellSize",+ "chunkCells",+ "minY",+ "maxY",+ "seed",+ "surfaceHeight",+ "hillHeight",+ "hillScale",+ "caveWidth",+ "caveScale",+ "soilDepth",+ "oreAmount",+ "drawDistance",+ "collisionDistance",+ "collisionLayer",+ "friction",+ "material",+ "color0.r",+ "color0.g",+ "color0.b",+ "color0.a",+ "color1.r",+ "color1.g",+ "color1.b",+ "color1.a",+ "color2.r",+ "color2.g",+ "color2.b",+ "color2.a",+ "color3.r",+ "color3.g",+ "color3.b",+ "color3.a",+ "map0",+ "map1",+ "map2",+ "map3",+ "tile"+ ]+ },{"name": "WaterBody","source": "ts",diff --git a/pipeline/src/bundle/engineSubpaths.ts b/pipeline/src/bundle/engineSubpaths.tsindex 96073b4a9..8e91f3950 100644--- a/pipeline/src/bundle/engineSubpaths.ts+++ b/pipeline/src/bundle/engineSubpaths.ts@@ -21,6 +21,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {'esengine/worldgen': 'worldgen/index.js','esengine/water': 'water/index.js','esengine/spline': 'spline/index.js',+ 'esengine/voxel': 'voxel/index.js','esengine/rig2d': 'rig2d/index.js','esengine/imported-scene': 'imported-scene/index.js','esengine/character-shaders': 'character-shaders/index.js',diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.tsindex ddbcc9dc8..19a3c87ae 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' | 'worldgen' | 'water' | 'spline' | 'rig2d' | 'importedScene' | 'characterShaders' | 'timeline' | 'fxBasic' | 'fxAtmosphere' | 'fxLighting' | 'particles' | 'postprocess' | 'physics' | 'physics3d'+ | 'text' | 'tilemap' | 'terrain' | 'foliage' | 'worldgen' | 'water' | 'spline' | 'voxel' | 'rig2d' | 'importedScene' | 'characterShaders' | 'timeline' | 'fxBasic' | 'fxAtmosphere' | 'fxLighting' | 'particles' | 'postprocess' | 'physics' | 'physics3d'| 'spine' | 'dragonbones' | 'video' | 'ai' | 'logic' | 'replication' | 'gameplay';/**@@ -49,6 +49,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>worldgen: ['WorldGen', 'WorldZone'],water: ['WaterBody', 'WaterZone', 'Floating'],spline: ['Spline', 'PathFollower', 'TerrainBand2D', 'RoadDecal'],+ voxel: ['VoxelTerrain'],rig2d: ['Bone2D', 'IK2D', 'BoneConstraint2D'],importedScene: ['NodeVisibility', 'ParticleModelUnits'],// Hair, Skin and Eye are shaders, not components: a character's materials are what name them (see SHADER_SUBSYSTEM).@@ -100,7 +101,7 @@ export const POST_PROCESS_EFFECT_GROUP: Readonly<Record<string, Subsystem>> = {* uses the module that ships it — with no component in a scene to say so (a Water material on a plain mesh, a character's Hair).*/export const SHADER_SUBSYSTEM: Readonly<Record<string, Subsystem>> = {- 'builtin:water': 'water', 'builtin:terrain': 'terrain', 'builtin:foliage': 'foliage',+ 'builtin:water': 'water', 'builtin:terrain': 'terrain', 'builtin:foliage': 'foliage', 'builtin:voxel-ground': 'voxel','builtin:hair': 'characterShaders', 'builtin:skin': 'characterShaders', 'builtin:eye': 'characterShaders',};@@ -117,6 +118,7 @@ export const SUBSYSTEM_LABEL: Readonly<Record<Subsystem, string>> = {worldgen: 'Generated worlds (biomes, zones, placement)',water: 'Water',spline: 'Splines',+ voxel: 'Voxel terrain',rig2d: '2D rig constraints',importedScene: 'Imported scene (node visibility, particle units)',characterShaders: 'Character shaders (hair, skin, eye)',@@ -153,6 +155,7 @@ export const SUBSYSTEM_INSTALL: Readonly<Record<Subsystem, string>> = {worldgen: 'esengine/worldgen',water: 'esengine/water',spline: 'esengine/spline',+ voxel: 'esengine/voxel',rig2d: 'esengine/rig2d',importedScene: 'esengine/imported-scene',characterShaders: 'esengine/character-shaders',diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 8b2df0346..759b30002 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 · 166 beta · 2072 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2096 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -12833,6 +12833,11 @@ uvOffset: { x: number; y: number; }uvScale: { x: number; y: number; }```+## VOXEL_MATERIALS — const @experimental+```+4+```+## ValidatePrefabOptions — interface @experimental```instanceOverrides: readonly PrefabOverride[] | undefined@@ -13086,6 +13091,209 @@ returnSpeed: number | undefinedworld: World```+## VoxelEditEvent — interface @experimental+```+entity: number+op: VoxelOp+result: VoxelEditResult+shape: VoxelShape+```++## VoxelEditOptions — interface @experimental+```+keep: ((material: number) => boolean) | undefined+material: number | undefined+smooth: number | undefined+```++## VoxelEditResult — interface @experimental+```+added: number+chunks: number+removed: number[]+```++## VoxelField — class @experimental+```+apply: (shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult+cellSize: number+chunk: (cx: number, cy: number, cz: number) => VoxelChunk+chunkCells: number+distanceAt: (x: number, y: number, z: number) => number+held: { chunks: number; edited: number; }+materialAt: (x: number, y: number, z: number) => number+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance: number) => VoxelHit | null+restore: (data: VoxelFieldData, merge?: boolean, skipped?: string[]) => boolean+rowMax: number+rowMin: number+serialize: (changedOnly?: boolean) => VoxelFieldData+side: number+takeDirty: () => VoxelChunk[]+trim: (keep?: (chunk: VoxelChunk) => boolean) => void+static new (options: VoxelFieldOptions): VoxelField+static prototype: VoxelField+```++## VoxelFieldData — interface @experimental+```+cellSize: number+chunkCells: number+chunks: Record<string, string>+version: 1+```++## VoxelFieldOptions — interface @experimental+```+cached: number | undefined+cellSize: number+chunkCells: number+maxY: number+minY: number+source: VoxelSource+```++## VoxelHit — interface @experimental+```+distance: number+material: number+normal: VoxelPoint+point: VoxelPoint+```++## VoxelMaterial — const @experimental+```+{ readonly Topsoil: 0; readonly Soil: 1; readonly Rock: 2; readonly Ore: 3; }+```++## VoxelNoiseParams — interface @experimental+```+caveScale: number+caveWidth: number+cellSize: number | undefined+hillHeight: number+hillScale: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+```++## VoxelOp — type @experimental+```+'subtract' | 'add' | 'paint'+```++## VoxelPlugin — class @experimental+```+activeWhen: ComponentDef<VoxelTerrainData>[]+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): VoxelPlugin+static prototype: VoxelPlugin+```++## VoxelPoint — interface @experimental+```+x: number+y: number+z: number+```++## VoxelSample — interface @experimental+```+distance: number+material: number+```++## VoxelShape — type @experimental+```+| { kind: 'sphere'; center: VoxelPoint; radius: number }+ | { kind: 'box'; center: VoxelPoint; halfExtents: VoxelPoint }+ | { kind: 'capsule'; from: VoxelPoint; to: VoxelPoint; radius: number }+```++## VoxelSource — type @experimental+```+(x: number, y: number, z: number, out: VoxelSample) => void+```++## VoxelTerrain — const @experimental+```+ComponentDef<VoxelTerrainData>+```++## VoxelTerrainData — interface @experimental+```+castShadows: boolean+caveScale: number+caveWidth: number+cellSize: number+chunkCells: number+collision: boolean+collisionDistance: number+collisionLayer: number+color0: Color+color1: Color+color2: Color+color3: Color+drawDistance: number+friction: number+hillHeight: number+hillScale: number+map0: number+map1: number+map2: number+map3: number+material: number+maxY: number+minY: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+tile: number+```++## VoxelTerrainStatus — interface @experimental+```+collidingChunks: number+drawnChunks: number+editedChunks: number+heldChunks: number+lastRebuildMs: number+triangles: number+waitingChunks: number+```++## VoxelTerrains — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, Built>+@internal ensure_: ((entity: Entity) => Built | null) | null+@internal sourceIds_: Map<VoxelSource, number>+@internal sources_: Map<number, VoxelSource>+carve: (entity: Entity, shape: VoxelShape, options?: VoxelEditOptions) => VoxelEditResult | null+collisionReadyAt: (entity: Entity, x: number, z: number) => boolean+distanceAt: (entity: Entity, at: VoxelPoint) => number | null+edit: (entity: Entity, shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult | null+fill: (entity: Entity, shape: VoxelShape, material?: number, options?: VoxelEditOptions) => VoxelEditResult | null+materialAt: (entity: Entity, at: VoxelPoint) => number | null+onEdit: (listener: (event: VoxelEditEvent) => void) => () => void+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance?: number) => (VoxelHit & { entity: Entity; }) | null+restore: (entity: Entity, data: VoxelFieldData, merge?: boolean) => boolean+serialize: (entity: Entity, changedOnly?: boolean) => VoxelFieldData | null+setSource: (entity: Entity, source: VoxelSource | null) => void+status: (entity: Entity) => VoxelTerrainStatus | null+static new (): VoxelTerrains+static prototype: VoxelTerrains+```++## VoxelTerrainsRes — const @experimental+```+ResourceDef<VoxelTerrains>+```+## WAVE_SET — const @experimental```readonly (readonly [number, number, number, number])[]@@ -15530,6 +15738,11 @@ Plugin() => Plugin[]```+## heightVoxelSource — function @experimental+```+(heightAt: (x: number, z: number) => number | null, material?: (depth: number, sample: VoxelSample) => void): VoxelSource+```+## heightfieldFromPixels — function @experimental```(width: number, height: number, pixels: ArrayLike<number>, format?: number, wide?: ArrayLike<number>): Heightfield@@ -16050,6 +16263,11 @@ MeshRendererPlugin(params: (seed: number) => NoiseParams): TerrainProvider```+## noiseVoxelSource — function @experimental+```+(params: VoxelNoiseParams): VoxelSource+```+## noised — function @experimental```(x: number, y: number, seed: number): [number, number, number]@@ -17765,6 +17983,11 @@ SystemDefVideoPlugin```+## voxelPlugin — const @experimental+```+VoxelPlugin+```+## warmShaders — function @experimental```(app: App, options?: ShaderWarmupOptions): Promise<ShaderWarmup>diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 87cba80c0..281c0118e 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 · 171 beta · 2091 experimental · 3 deprecated+Symbols: 115 public · 171 beta · 2115 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -13049,6 +13049,11 @@ uvOffset: { x: number; y: number; }uvScale: { x: number; y: number; }```+## VOXEL_MATERIALS — const @experimental+```+4+```+## ValidatePrefabOptions — interface @experimental```instanceOverrides: readonly PrefabOverride[] | undefined@@ -13302,6 +13307,209 @@ returnSpeed: number | undefinedworld: World```+## VoxelEditEvent — interface @experimental+```+entity: number+op: VoxelOp+result: VoxelEditResult+shape: VoxelShape+```++## VoxelEditOptions — interface @experimental+```+keep: ((material: number) => boolean) | undefined+material: number | undefined+smooth: number | undefined+```++## VoxelEditResult — interface @experimental+```+added: number+chunks: number+removed: number[]+```++## VoxelField — class @experimental+```+apply: (shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult+cellSize: number+chunk: (cx: number, cy: number, cz: number) => VoxelChunk+chunkCells: number+distanceAt: (x: number, y: number, z: number) => number+held: { chunks: number; edited: number; }+materialAt: (x: number, y: number, z: number) => number+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance: number) => VoxelHit | null+restore: (data: VoxelFieldData, merge?: boolean, skipped?: string[]) => boolean+rowMax: number+rowMin: number+serialize: (changedOnly?: boolean) => VoxelFieldData+side: number+takeDirty: () => VoxelChunk[]+trim: (keep?: (chunk: VoxelChunk) => boolean) => void+static new (options: VoxelFieldOptions): VoxelField+static prototype: VoxelField+```++## VoxelFieldData — interface @experimental+```+cellSize: number+chunkCells: number+chunks: Record<string, string>+version: 1+```++## VoxelFieldOptions — interface @experimental+```+cached: number | undefined+cellSize: number+chunkCells: number+maxY: number+minY: number+source: VoxelSource+```++## VoxelHit — interface @experimental+```+distance: number+material: number+normal: VoxelPoint+point: VoxelPoint+```++## VoxelMaterial — const @experimental+```+{ readonly Topsoil: 0; readonly Soil: 1; readonly Rock: 2; readonly Ore: 3; }+```++## VoxelNoiseParams — interface @experimental+```+caveScale: number+caveWidth: number+cellSize: number | undefined+hillHeight: number+hillScale: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+```++## VoxelOp — type @experimental+```+'subtract' | 'add' | 'paint'+```++## VoxelPlugin — class @experimental+```+activeWhen: ComponentDef<VoxelTerrainData>[]+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): VoxelPlugin+static prototype: VoxelPlugin+```++## VoxelPoint — interface @experimental+```+x: number+y: number+z: number+```++## VoxelSample — interface @experimental+```+distance: number+material: number+```++## VoxelShape — type @experimental+```+| { kind: 'sphere'; center: VoxelPoint; radius: number }+ | { kind: 'box'; center: VoxelPoint; halfExtents: VoxelPoint }+ | { kind: 'capsule'; from: VoxelPoint; to: VoxelPoint; radius: number }+```++## VoxelSource — type @experimental+```+(x: number, y: number, z: number, out: VoxelSample) => void+```++## VoxelTerrain — const @experimental+```+ComponentDef<VoxelTerrainData>+```++## VoxelTerrainData — interface @experimental+```+castShadows: boolean+caveScale: number+caveWidth: number+cellSize: number+chunkCells: number+collision: boolean+collisionDistance: number+collisionLayer: number+color0: Color+color1: Color+color2: Color+color3: Color+drawDistance: number+friction: number+hillHeight: number+hillScale: number+map0: number+map1: number+map2: number+map3: number+material: number+maxY: number+minY: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+tile: number+```++## VoxelTerrainStatus — interface @experimental+```+collidingChunks: number+drawnChunks: number+editedChunks: number+heldChunks: number+lastRebuildMs: number+triangles: number+waitingChunks: number+```++## VoxelTerrains — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, Built>+@internal ensure_: ((entity: Entity) => Built | null) | null+@internal sourceIds_: Map<VoxelSource, number>+@internal sources_: Map<number, VoxelSource>+carve: (entity: Entity, shape: VoxelShape, options?: VoxelEditOptions) => VoxelEditResult | null+collisionReadyAt: (entity: Entity, x: number, z: number) => boolean+distanceAt: (entity: Entity, at: VoxelPoint) => number | null+edit: (entity: Entity, shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult | null+fill: (entity: Entity, shape: VoxelShape, material?: number, options?: VoxelEditOptions) => VoxelEditResult | null+materialAt: (entity: Entity, at: VoxelPoint) => number | null+onEdit: (listener: (event: VoxelEditEvent) => void) => () => void+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance?: number) => (VoxelHit & { entity: Entity; }) | null+restore: (entity: Entity, data: VoxelFieldData, merge?: boolean) => boolean+serialize: (entity: Entity, changedOnly?: boolean) => VoxelFieldData | null+setSource: (entity: Entity, source: VoxelSource | null) => void+status: (entity: Entity) => VoxelTerrainStatus | null+static new (): VoxelTerrains+static prototype: VoxelTerrains+```++## VoxelTerrainsRes — const @experimental+```+ResourceDef<VoxelTerrains>+```+## WAVE_SET — const @experimental```readonly (readonly [number, number, number, number])[]@@ -15786,6 +15994,11 @@ Plugin() => Plugin[]```+## heightVoxelSource — function @experimental+```+(heightAt: (x: number, z: number) => number | null, material?: (depth: number, sample: VoxelSample) => void): VoxelSource+```+## heightfieldFromPixels — function @experimental```(width: number, height: number, pixels: ArrayLike<number>, format?: number, wide?: ArrayLike<number>): Heightfield@@ -16316,6 +16529,11 @@ MeshRendererPlugin(params: (seed: number) => NoiseParams): TerrainProvider```+## noiseVoxelSource — function @experimental+```+(params: VoxelNoiseParams): VoxelSource+```+## noised — function @experimental```(x: number, y: number, seed: number): [number, number, number]@@ -18031,6 +18249,11 @@ SystemDefVideoPlugin```+## voxelPlugin — const @experimental+```+VoxelPlugin+```+## warmShaders — function @experimental```(app: App, options?: ShaderWarmupOptions): Promise<ShaderWarmup>diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex b7f129df1..577a9bb7a 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 · 168 beta · 2071 experimental · 3 deprecated+Symbols: 115 public · 168 beta · 2095 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -12828,6 +12828,11 @@ uvOffset: { x: number; y: number; }uvScale: { x: number; y: number; }```+## VOXEL_MATERIALS — const @experimental+```+4+```+## ValidatePrefabOptions — interface @experimental```instanceOverrides: readonly PrefabOverride[] | undefined@@ -13081,6 +13086,209 @@ returnSpeed: number | undefinedworld: World```+## VoxelEditEvent — interface @experimental+```+entity: number+op: VoxelOp+result: VoxelEditResult+shape: VoxelShape+```++## VoxelEditOptions — interface @experimental+```+keep: ((material: number) => boolean) | undefined+material: number | undefined+smooth: number | undefined+```++## VoxelEditResult — interface @experimental+```+added: number+chunks: number+removed: number[]+```++## VoxelField — class @experimental+```+apply: (shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult+cellSize: number+chunk: (cx: number, cy: number, cz: number) => VoxelChunk+chunkCells: number+distanceAt: (x: number, y: number, z: number) => number+held: { chunks: number; edited: number; }+materialAt: (x: number, y: number, z: number) => number+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance: number) => VoxelHit | null+restore: (data: VoxelFieldData, merge?: boolean, skipped?: string[]) => boolean+rowMax: number+rowMin: number+serialize: (changedOnly?: boolean) => VoxelFieldData+side: number+takeDirty: () => VoxelChunk[]+trim: (keep?: (chunk: VoxelChunk) => boolean) => void+static new (options: VoxelFieldOptions): VoxelField+static prototype: VoxelField+```++## VoxelFieldData — interface @experimental+```+cellSize: number+chunkCells: number+chunks: Record<string, string>+version: 1+```++## VoxelFieldOptions — interface @experimental+```+cached: number | undefined+cellSize: number+chunkCells: number+maxY: number+minY: number+source: VoxelSource+```++## VoxelHit — interface @experimental+```+distance: number+material: number+normal: VoxelPoint+point: VoxelPoint+```++## VoxelMaterial — const @experimental+```+{ readonly Topsoil: 0; readonly Soil: 1; readonly Rock: 2; readonly Ore: 3; }+```++## VoxelNoiseParams — interface @experimental+```+caveScale: number+caveWidth: number+cellSize: number | undefined+hillHeight: number+hillScale: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+```++## VoxelOp — type @experimental+```+'subtract' | 'add' | 'paint'+```++## VoxelPlugin — class @experimental+```+activeWhen: ComponentDef<VoxelTerrainData>[]+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): VoxelPlugin+static prototype: VoxelPlugin+```++## VoxelPoint — interface @experimental+```+x: number+y: number+z: number+```++## VoxelSample — interface @experimental+```+distance: number+material: number+```++## VoxelShape — type @experimental+```+| { kind: 'sphere'; center: VoxelPoint; radius: number }+ | { kind: 'box'; center: VoxelPoint; halfExtents: VoxelPoint }+ | { kind: 'capsule'; from: VoxelPoint; to: VoxelPoint; radius: number }+```++## VoxelSource — type @experimental+```+(x: number, y: number, z: number, out: VoxelSample) => void+```++## VoxelTerrain — const @experimental+```+ComponentDef<VoxelTerrainData>+```++## VoxelTerrainData — interface @experimental+```+castShadows: boolean+caveScale: number+caveWidth: number+cellSize: number+chunkCells: number+collision: boolean+collisionDistance: number+collisionLayer: number+color0: Color+color1: Color+color2: Color+color3: Color+drawDistance: number+friction: number+hillHeight: number+hillScale: number+map0: number+map1: number+map2: number+map3: number+material: number+maxY: number+minY: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+tile: number+```++## VoxelTerrainStatus — interface @experimental+```+collidingChunks: number+drawnChunks: number+editedChunks: number+heldChunks: number+lastRebuildMs: number+triangles: number+waitingChunks: number+```++## VoxelTerrains — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, Built>+@internal ensure_: ((entity: Entity) => Built | null) | null+@internal sourceIds_: Map<VoxelSource, number>+@internal sources_: Map<number, VoxelSource>+carve: (entity: Entity, shape: VoxelShape, options?: VoxelEditOptions) => VoxelEditResult | null+collisionReadyAt: (entity: Entity, x: number, z: number) => boolean+distanceAt: (entity: Entity, at: VoxelPoint) => number | null+edit: (entity: Entity, shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult | null+fill: (entity: Entity, shape: VoxelShape, material?: number, options?: VoxelEditOptions) => VoxelEditResult | null+materialAt: (entity: Entity, at: VoxelPoint) => number | null+onEdit: (listener: (event: VoxelEditEvent) => void) => () => void+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance?: number) => (VoxelHit & { entity: Entity; }) | null+restore: (entity: Entity, data: VoxelFieldData, merge?: boolean) => boolean+serialize: (entity: Entity, changedOnly?: boolean) => VoxelFieldData | null+setSource: (entity: Entity, source: VoxelSource | null) => void+status: (entity: Entity) => VoxelTerrainStatus | null+static new (): VoxelTerrains+static prototype: VoxelTerrains+```++## VoxelTerrainsRes — const @experimental+```+ResourceDef<VoxelTerrains>+```+## WAVE_SET — const @experimental```readonly (readonly [number, number, number, number])[]@@ -15525,6 +15733,11 @@ Plugin() => Plugin[]```+## heightVoxelSource — function @experimental+```+(heightAt: (x: number, z: number) => number | null, material?: (depth: number, sample: VoxelSample) => void): VoxelSource+```+## heightfieldFromPixels — function @experimental```(width: number, height: number, pixels: ArrayLike<number>, format?: number, wide?: ArrayLike<number>): Heightfield@@ -16055,6 +16268,11 @@ NodePlatformAdapter(params: (seed: number) => NoiseParams): TerrainProvider```+## noiseVoxelSource — function @experimental+```+(params: VoxelNoiseParams): VoxelSource+```+## noised — function @experimental```(x: number, y: number, seed: number): [number, number, number]@@ -17770,6 +17988,11 @@ SystemDefVideoPlugin```+## voxelPlugin — const @experimental+```+VoxelPlugin+```+## warmShaders — function @experimental```(app: App, options?: ShaderWarmupOptions): Promise<ShaderWarmup>diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex c757b105b..571a273c8 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 · 166 beta · 2093 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2117 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -13124,6 +13124,11 @@ uvOffset: { x: number; y: number; }uvScale: { x: number; y: number; }```+## VOXEL_MATERIALS — const @experimental+```+4+```+## ValidatePrefabOptions — interface @experimental```instanceOverrides: readonly PrefabOverride[] | undefined@@ -13383,6 +13388,209 @@ returnSpeed: number | undefinedworld: World```+## VoxelEditEvent — interface @experimental+```+entity: number+op: VoxelOp+result: VoxelEditResult+shape: VoxelShape+```++## VoxelEditOptions — interface @experimental+```+keep: ((material: number) => boolean) | undefined+material: number | undefined+smooth: number | undefined+```++## VoxelEditResult — interface @experimental+```+added: number+chunks: number+removed: number[]+```++## VoxelField — class @experimental+```+apply: (shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult+cellSize: number+chunk: (cx: number, cy: number, cz: number) => VoxelChunk+chunkCells: number+distanceAt: (x: number, y: number, z: number) => number+held: { chunks: number; edited: number; }+materialAt: (x: number, y: number, z: number) => number+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance: number) => VoxelHit | null+restore: (data: VoxelFieldData, merge?: boolean, skipped?: string[]) => boolean+rowMax: number+rowMin: number+serialize: (changedOnly?: boolean) => VoxelFieldData+side: number+takeDirty: () => VoxelChunk[]+trim: (keep?: (chunk: VoxelChunk) => boolean) => void+static new (options: VoxelFieldOptions): VoxelField+static prototype: VoxelField+```++## VoxelFieldData — interface @experimental+```+cellSize: number+chunkCells: number+chunks: Record<string, string>+version: 1+```++## VoxelFieldOptions — interface @experimental+```+cached: number | undefined+cellSize: number+chunkCells: number+maxY: number+minY: number+source: VoxelSource+```++## VoxelHit — interface @experimental+```+distance: number+material: number+normal: VoxelPoint+point: VoxelPoint+```++## VoxelMaterial — const @experimental+```+{ readonly Topsoil: 0; readonly Soil: 1; readonly Rock: 2; readonly Ore: 3; }+```++## VoxelNoiseParams — interface @experimental+```+caveScale: number+caveWidth: number+cellSize: number | undefined+hillHeight: number+hillScale: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+```++## VoxelOp — type @experimental+```+'subtract' | 'add' | 'paint'+```++## VoxelPlugin — class @experimental+```+activeWhen: ComponentDef<VoxelTerrainData>[]+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): VoxelPlugin+static prototype: VoxelPlugin+```++## VoxelPoint — interface @experimental+```+x: number+y: number+z: number+```++## VoxelSample — interface @experimental+```+distance: number+material: number+```++## VoxelShape — type @experimental+```+| { kind: 'sphere'; center: VoxelPoint; radius: number }+ | { kind: 'box'; center: VoxelPoint; halfExtents: VoxelPoint }+ | { kind: 'capsule'; from: VoxelPoint; to: VoxelPoint; radius: number }+```++## VoxelSource — type @experimental+```+(x: number, y: number, z: number, out: VoxelSample) => void+```++## VoxelTerrain — const @experimental+```+ComponentDef<VoxelTerrainData>+```++## VoxelTerrainData — interface @experimental+```+castShadows: boolean+caveScale: number+caveWidth: number+cellSize: number+chunkCells: number+collision: boolean+collisionDistance: number+collisionLayer: number+color0: Color+color1: Color+color2: Color+color3: Color+drawDistance: number+friction: number+hillHeight: number+hillScale: number+map0: number+map1: number+map2: number+map3: number+material: number+maxY: number+minY: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+tile: number+```++## VoxelTerrainStatus — interface @experimental+```+collidingChunks: number+drawnChunks: number+editedChunks: number+heldChunks: number+lastRebuildMs: number+triangles: number+waitingChunks: number+```++## VoxelTerrains — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, Built>+@internal ensure_: ((entity: Entity) => Built | null) | null+@internal sourceIds_: Map<VoxelSource, number>+@internal sources_: Map<number, VoxelSource>+carve: (entity: Entity, shape: VoxelShape, options?: VoxelEditOptions) => VoxelEditResult | null+collisionReadyAt: (entity: Entity, x: number, z: number) => boolean+distanceAt: (entity: Entity, at: VoxelPoint) => number | null+edit: (entity: Entity, shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult | null+fill: (entity: Entity, shape: VoxelShape, material?: number, options?: VoxelEditOptions) => VoxelEditResult | null+materialAt: (entity: Entity, at: VoxelPoint) => number | null+onEdit: (listener: (event: VoxelEditEvent) => void) => () => void+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance?: number) => (VoxelHit & { entity: Entity; }) | null+restore: (entity: Entity, data: VoxelFieldData, merge?: boolean) => boolean+serialize: (entity: Entity, changedOnly?: boolean) => VoxelFieldData | null+setSource: (entity: Entity, source: VoxelSource | null) => void+status: (entity: Entity) => VoxelTerrainStatus | null+static new (): VoxelTerrains+static prototype: VoxelTerrains+```++## VoxelTerrainsRes — const @experimental+```+ResourceDef<VoxelTerrains>+```+## WAVE_SET — const @experimental```readonly (readonly [number, number, number, number])[]@@ -15832,6 +16040,11 @@ Plugin() => Plugin[]```+## heightVoxelSource — function @experimental+```+(heightAt: (x: number, z: number) => number | null, material?: (depth: number, sample: VoxelSample) => void): VoxelSource+```+## heightfieldFromPixels — function @experimental```(width: number, height: number, pixels: ArrayLike<number>, format?: number, wide?: ArrayLike<number>): Heightfield@@ -16362,6 +16575,11 @@ MeshRendererPlugin(params: (seed: number) => NoiseParams): TerrainProvider```+## noiseVoxelSource — function @experimental+```+(params: VoxelNoiseParams): VoxelSource+```+## noised — function @experimental```(x: number, y: number, seed: number): [number, number, number]@@ -18077,6 +18295,11 @@ SystemDefVideoPlugin```+## voxelPlugin — const @experimental+```+VoxelPlugin+```+## warmShaders — function @experimental```(app: App, options?: ShaderWarmupOptions): Promise<ShaderWarmup>diff --git a/sdk/etc/voxel.api.md b/sdk/etc/voxel.api.mdnew file mode 100644index 000000000..bbd68c59d--- /dev/null+++ b/sdk/etc/voxel.api.md@@ -0,0 +1,241 @@+# API surface — esengine/voxel++<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->+Symbols: 0 public · 0 beta · 26 experimental · 0 deprecated++## VOXEL_MATERIALS — const @experimental+```+4+```++## VoxelEditEvent — interface @experimental+```+entity: number+op: VoxelOp+result: VoxelEditResult+shape: VoxelShape+```++## VoxelEditOptions — interface @experimental+```+keep: ((material: number) => boolean) | undefined+material: number | undefined+smooth: number | undefined+```++## VoxelEditResult — interface @experimental+```+added: number+chunks: number+removed: number[]+```++## VoxelField — class @experimental+```+apply: (shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult+cellSize: number+chunk: (cx: number, cy: number, cz: number) => VoxelChunk+chunkCells: number+distanceAt: (x: number, y: number, z: number) => number+held: { chunks: number; edited: number; }+materialAt: (x: number, y: number, z: number) => number+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance: number) => VoxelHit | null+restore: (data: VoxelFieldData, merge?: boolean, skipped?: string[]) => boolean+rowMax: number+rowMin: number+serialize: (changedOnly?: boolean) => VoxelFieldData+side: number+takeDirty: () => VoxelChunk[]+trim: (keep?: (chunk: VoxelChunk) => boolean) => void+static new (options: VoxelFieldOptions): VoxelField+static prototype: VoxelField+```++## VoxelFieldData — interface @experimental+```+cellSize: number+chunkCells: number+chunks: Record<string, string>+version: 1+```++## VoxelFieldOptions — interface @experimental+```+cached: number | undefined+cellSize: number+chunkCells: number+maxY: number+minY: number+source: VoxelSource+```++## VoxelHit — interface @experimental+```+distance: number+material: number+normal: VoxelPoint+point: VoxelPoint+```++## VoxelMaterial — const @experimental+```+{ readonly Topsoil: 0; readonly Soil: 1; readonly Rock: 2; readonly Ore: 3; }+```++## VoxelNoiseParams — interface @experimental+```+caveScale: number+caveWidth: number+cellSize: number | undefined+hillHeight: number+hillScale: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+```++## VoxelOp — type @experimental+```+'subtract' | 'add' | 'paint'+```++## VoxelPlugin — class @experimental+```+activeWhen: ComponentDef<VoxelTerrainData>[]+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): VoxelPlugin+static prototype: VoxelPlugin+```++## VoxelPoint — interface @experimental+```+x: number+y: number+z: number+```++## VoxelSample — interface @experimental+```+distance: number+material: number+```++## VoxelShape — type @experimental+```+| { kind: 'sphere'; center: VoxelPoint; radius: number }+ | { kind: 'box'; center: VoxelPoint; halfExtents: VoxelPoint }+ | { kind: 'capsule'; from: VoxelPoint; to: VoxelPoint; radius: number }+```++## VoxelSource — type @experimental+```+(x: number, y: number, z: number, out: VoxelSample) => void+```++## VoxelSurface — interface @experimental+```+indices: Uint32Array<ArrayBufferLike>+normals: Float32Array<ArrayBufferLike>+positions: Float32Array<ArrayBufferLike>+weights: Uint8Array<ArrayBufferLike>+```++## VoxelTerrain — const @experimental+```+ComponentDef<VoxelTerrainData>+```++## VoxelTerrainData — interface @experimental+```+castShadows: boolean+caveScale: number+caveWidth: number+cellSize: number+chunkCells: number+collision: boolean+collisionDistance: number+collisionLayer: number+color0: Color+color1: Color+color2: Color+color3: Color+drawDistance: number+friction: number+hillHeight: number+hillScale: number+map0: number+map1: number+map2: number+map3: number+material: number+maxY: number+minY: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+tile: number+```++## VoxelTerrainStatus — interface @experimental+```+collidingChunks: number+drawnChunks: number+editedChunks: number+heldChunks: number+lastRebuildMs: number+triangles: number+waitingChunks: number+```++## VoxelTerrains — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, Built>+@internal ensure_: ((entity: Entity) => Built | null) | null+@internal sourceIds_: Map<VoxelSource, number>+@internal sources_: Map<number, VoxelSource>+carve: (entity: Entity, shape: VoxelShape, options?: VoxelEditOptions) => VoxelEditResult | null+collisionReadyAt: (entity: Entity, x: number, z: number) => boolean+distanceAt: (entity: Entity, at: VoxelPoint) => number | null+edit: (entity: Entity, shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult | null+fill: (entity: Entity, shape: VoxelShape, material?: number, options?: VoxelEditOptions) => VoxelEditResult | null+materialAt: (entity: Entity, at: VoxelPoint) => number | null+onEdit: (listener: (event: VoxelEditEvent) => void) => () => void+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance?: number) => (VoxelHit & { entity: Entity; }) | null+restore: (entity: Entity, data: VoxelFieldData, merge?: boolean) => boolean+serialize: (entity: Entity, changedOnly?: boolean) => VoxelFieldData | null+setSource: (entity: Entity, source: VoxelSource | null) => void+status: (entity: Entity) => VoxelTerrainStatus | null+static new (): VoxelTerrains+static prototype: VoxelTerrains+```++## VoxelTerrainsRes — const @experimental+```+ResourceDef<VoxelTerrains>+```++## heightVoxelSource — function @experimental+```+(heightAt: (x: number, z: number) => number | null, material?: (depth: number, sample: VoxelSample) => void): VoxelSource+```++## noiseVoxelSource — function @experimental+```+(params: VoxelNoiseParams): VoxelSource+```++## surfaceNets — function @experimental+```+(distances: Int8Array, materials: Uint8Array, cells: number, cellSize: number): VoxelSurface | null+```++## voxelPlugin — const @experimental+```+VoxelPlugin+```+diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 2ca137bcc..516520b9c 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 · 166 beta · 2084 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2108 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -12835,6 +12835,11 @@ uvOffset: { x: number; y: number; }uvScale: { x: number; y: number; }```+## VOXEL_MATERIALS — const @experimental+```+4+```+## ValidatePrefabOptions — interface @experimental```instanceOverrides: readonly PrefabOverride[] | undefined@@ -13088,6 +13093,209 @@ returnSpeed: number | undefinedworld: World```+## VoxelEditEvent — interface @experimental+```+entity: number+op: VoxelOp+result: VoxelEditResult+shape: VoxelShape+```++## VoxelEditOptions — interface @experimental+```+keep: ((material: number) => boolean) | undefined+material: number | undefined+smooth: number | undefined+```++## VoxelEditResult — interface @experimental+```+added: number+chunks: number+removed: number[]+```++## VoxelField — class @experimental+```+apply: (shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult+cellSize: number+chunk: (cx: number, cy: number, cz: number) => VoxelChunk+chunkCells: number+distanceAt: (x: number, y: number, z: number) => number+held: { chunks: number; edited: number; }+materialAt: (x: number, y: number, z: number) => number+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance: number) => VoxelHit | null+restore: (data: VoxelFieldData, merge?: boolean, skipped?: string[]) => boolean+rowMax: number+rowMin: number+serialize: (changedOnly?: boolean) => VoxelFieldData+side: number+takeDirty: () => VoxelChunk[]+trim: (keep?: (chunk: VoxelChunk) => boolean) => void+static new (options: VoxelFieldOptions): VoxelField+static prototype: VoxelField+```++## VoxelFieldData — interface @experimental+```+cellSize: number+chunkCells: number+chunks: Record<string, string>+version: 1+```++## VoxelFieldOptions — interface @experimental+```+cached: number | undefined+cellSize: number+chunkCells: number+maxY: number+minY: number+source: VoxelSource+```++## VoxelHit — interface @experimental+```+distance: number+material: number+normal: VoxelPoint+point: VoxelPoint+```++## VoxelMaterial — const @experimental+```+{ readonly Topsoil: 0; readonly Soil: 1; readonly Rock: 2; readonly Ore: 3; }+```++## VoxelNoiseParams — interface @experimental+```+caveScale: number+caveWidth: number+cellSize: number | undefined+hillHeight: number+hillScale: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+```++## VoxelOp — type @experimental+```+'subtract' | 'add' | 'paint'+```++## VoxelPlugin — class @experimental+```+activeWhen: ComponentDef<VoxelTerrainData>[]+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): VoxelPlugin+static prototype: VoxelPlugin+```++## VoxelPoint — interface @experimental+```+x: number+y: number+z: number+```++## VoxelSample — interface @experimental+```+distance: number+material: number+```++## VoxelShape — type @experimental+```+| { kind: 'sphere'; center: VoxelPoint; radius: number }+ | { kind: 'box'; center: VoxelPoint; halfExtents: VoxelPoint }+ | { kind: 'capsule'; from: VoxelPoint; to: VoxelPoint; radius: number }+```++## VoxelSource — type @experimental+```+(x: number, y: number, z: number, out: VoxelSample) => void+```++## VoxelTerrain — const @experimental+```+ComponentDef<VoxelTerrainData>+```++## VoxelTerrainData — interface @experimental+```+castShadows: boolean+caveScale: number+caveWidth: number+cellSize: number+chunkCells: number+collision: boolean+collisionDistance: number+collisionLayer: number+color0: Color+color1: Color+color2: Color+color3: Color+drawDistance: number+friction: number+hillHeight: number+hillScale: number+map0: number+map1: number+map2: number+map3: number+material: number+maxY: number+minY: number+oreAmount: number+seed: number+soilDepth: number+surfaceHeight: number+tile: number+```++## VoxelTerrainStatus — interface @experimental+```+collidingChunks: number+drawnChunks: number+editedChunks: number+heldChunks: number+lastRebuildMs: number+triangles: number+waitingChunks: number+```++## VoxelTerrains — class @experimental+```+@internal app_: App | null+@internal built_: Map<number, Built>+@internal ensure_: ((entity: Entity) => Built | null) | null+@internal sourceIds_: Map<VoxelSource, number>+@internal sources_: Map<number, VoxelSource>+carve: (entity: Entity, shape: VoxelShape, options?: VoxelEditOptions) => VoxelEditResult | null+collisionReadyAt: (entity: Entity, x: number, z: number) => boolean+distanceAt: (entity: Entity, at: VoxelPoint) => number | null+edit: (entity: Entity, shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions) => VoxelEditResult | null+fill: (entity: Entity, shape: VoxelShape, material?: number, options?: VoxelEditOptions) => VoxelEditResult | null+materialAt: (entity: Entity, at: VoxelPoint) => number | null+onEdit: (listener: (event: VoxelEditEvent) => void) => () => void+raycast: (origin: VoxelPoint, direction: VoxelPoint, maxDistance?: number) => (VoxelHit & { entity: Entity; }) | null+restore: (entity: Entity, data: VoxelFieldData, merge?: boolean) => boolean+serialize: (entity: Entity, changedOnly?: boolean) => VoxelFieldData | null+setSource: (entity: Entity, source: VoxelSource | null) => void+status: (entity: Entity) => VoxelTerrainStatus | null+static new (): VoxelTerrains+static prototype: VoxelTerrains+```++## VoxelTerrainsRes — const @experimental+```+ResourceDef<VoxelTerrains>+```+## WAVE_SET — const @experimental```readonly (readonly [number, number, number, number])[]@@ -15558,6 +15766,11 @@ Plugin() => Plugin[]```+## heightVoxelSource — function @experimental+```+(heightAt: (x: number, z: number) => number | null, material?: (depth: number, sample: VoxelSample) => void): VoxelSource+```+## heightfieldFromPixels — function @experimental```(width: number, height: number, pixels: ArrayLike<number>, format?: number, wide?: ArrayLike<number>): Heightfield@@ -16088,6 +16301,11 @@ MeshRendererPlugin(params: (seed: number) => NoiseParams): TerrainProvider```+## noiseVoxelSource — function @experimental+```+(params: VoxelNoiseParams): VoxelSource+```+## noised — function @experimental```(x: number, y: number, seed: number): [number, number, number]@@ -17803,6 +18021,11 @@ SystemDefVideoPlugin```+## voxelPlugin — const @experimental+```+VoxelPlugin+```+## warmShaders — function @experimental```(app: App, options?: ShaderWarmupOptions): Promise<ShaderWarmup>diff --git a/sdk/package.json b/sdk/package.jsonindex 7b86fe758..624b66811 100644--- a/sdk/package.json+++ b/sdk/package.json@@ -26,6 +26,7 @@"./dist/worldgen/index.js","./dist/water/index.js","./dist/spline/index.js",+ "./dist/voxel/index.js","./dist/rig2d/index.js","./dist/imported-scene/index.js","./dist/character-shaders/index.js",@@ -121,6 +122,10 @@"import": "./dist/spline/index.js","types": "./dist/spline/index.d.ts"},+ "./voxel": {+ "import": "./dist/voxel/index.js",+ "types": "./dist/voxel/index.d.ts"+ },"./rig2d": {"import": "./dist/rig2d/index.js","types": "./dist/rig2d/index.d.ts"diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.jsindex ba4fcfd6d..13e751f81 100644--- a/sdk/rolldown.config.js+++ b/sdk/rolldown.config.js@@ -112,6 +112,7 @@ export default defineConfig(['worldgen/index': 'src/worldgen/index.ts','water/index': 'src/water/index.ts','spline/index': 'src/spline/index.ts',+ 'voxel/index': 'src/voxel/index.ts','rig2d/index': 'src/rig2d/index.ts','imported-scene/index': 'src/imported-scene/index.ts','character-shaders/index': 'src/character/index.ts',diff --git a/sdk/rollup.config.js b/sdk/rollup.config.jsindex b08117eb9..4cb08036c 100644--- a/sdk/rollup.config.js+++ b/sdk/rollup.config.js@@ -34,6 +34,7 @@ export default ['worldgen/index': 'src/worldgen/index.ts','water/index': 'src/water/index.ts','spline/index': 'src/spline/index.ts',+ 'voxel/index': 'src/voxel/index.ts','rig2d/index': 'src/rig2d/index.ts','imported-scene/index': 'src/imported-scene/index.ts','character-shaders/index': 'src/character/index.ts',diff --git a/sdk/src/app/pluginSets.ts b/sdk/src/app/pluginSets.tsindex ae8112ebe..165bafcdc 100644--- a/sdk/src/app/pluginSets.ts+++ b/sdk/src/app/pluginSets.ts@@ -71,7 +71,7 @@ export const presentationBasePlugins = (): Plugin[] => [*/export const PLUGIN_BUILD_ORDER: readonly string[] = ['Diagnostics', 'timer', 'velocity', 'lifecycle', 'animation', 'audio', 'video',- 'importedScene', 'particle', 'trail', 'springBone', 'meshRenderer', 'staticBatch', 'compositeBatch', 'impostor', 'textureStreaming', 'terrain', 'foliage', 'spline', 'water', 'floating', 'underwater', 'tilemap', 'postProcess', 'timeline',+ 'importedScene', 'particle', 'trail', 'springBone', 'meshRenderer', 'staticBatch', 'compositeBatch', 'impostor', 'textureStreaming', 'terrain', 'voxel', 'foliage', 'spline', 'water', 'floating', 'underwater', 'tilemap', 'postProcess', 'timeline','gameplay','perception', 'fsm', 'bt', 'scriptGraph', 'nav', 'eventBinding', 'replication','services',diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 32a5a272d..0e845299a 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -836,6 +836,15 @@ export { WorldPlan, type Placement, type Group, type Rejection } from './worldgeexport { 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 {+ VoxelTerrain, VoxelTerrains, VoxelTerrainsRes, VoxelPlugin, voxelPlugin,+ type VoxelTerrainData, type VoxelTerrainStatus, type VoxelEditEvent,+} from './voxel/voxelPlugin';+export {+ VOXEL_MATERIALS, VoxelField,+ type VoxelEditOptions, type VoxelEditResult, type VoxelFieldData, type VoxelFieldOptions, type VoxelHit, type VoxelOp, type VoxelPoint, type VoxelSample, type VoxelShape, type VoxelSource,+} from './voxel/field';+export { heightVoxelSource, noiseVoxelSource, VoxelMaterial, type VoxelNoiseParams } from './voxel/source';export { Bone2D, IK2D, BoneConstraint2D, BoneConstraintKind, type Bone2DData, type IK2DData, type BoneConstraint2DData } from './rig2d/rig2dPlugin';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/physics3d/Physics3DSystem.ts b/sdk/src/physics3d/Physics3DSystem.tsindex ab5d25814..03b1b2537 100644--- a/sdk/src/physics3d/Physics3DSystem.ts+++ b/sdk/src/physics3d/Physics3DSystem.ts@@ -282,8 +282,34 @@ function addTriangles(module: Physics3DWasmModule, entity: Entity,}}+/** How far past a changed piece a resting body may stand and still have been resting on it, in world units. */+const PIECE_WAKE_MARGIN = 4;++/**+ * Wakes what may have rested on a piece that has just changed or gone. A solver does not look again at what sleeps, so a body whose ground was+ * dug out from under it would stay in the air. A force too small to matter is what both solvers wake a body for.+ */+function wakeOn(app: App, module: Physics3DWasmModule, bodies: BodyMap, piece: CollisionPiece, ppu: number): void {+ if (!module._physics3d_addForce || bodies.size === 0) return;+ const [ox, oy, oz] = piece.origin, p = piece.positions;+ let x0 = Infinity, y0 = Infinity, z0 = Infinity, x1 = -Infinity, y1 = -Infinity, z1 = -Infinity;+ for (let i = 0; i < p.length; i += 3) {+ x0 = Math.min(x0, p[i]!); y0 = Math.min(y0, p[i + 1]!); z0 = Math.min(z0, p[i + 2]!);+ x1 = Math.max(x1, p[i]!); y1 = Math.max(y1, p[i + 1]!); z1 = Math.max(z1, p[i + 2]!);+ }+ const m = PIECE_WAKE_MARGIN;+ for (const [entity, id] of bodies) {+ if (!app.world.valid(entity) || !app.world.has(entity, RigidBody3D) || !app.world.has(entity, Transform)) continue;+ if ((app.world.get(entity, RigidBody3D) as RigidBody3DData).bodyType !== MOTION.Dynamic) continue;+ const at = (app.world.get(entity, Transform) as TransformData).worldPosition;+ const x = at.x - ox, y = at.y - oy, z = at.z - oz;+ if (x < x0 - m || x > x1 + m || y < y0 - m || y > y1 + m || z < z0 - m || z > z1 + m) continue;+ module._physics3d_addForce(id, 0, -1e-6, 0, at.x / ppu, at.y / ppu, at.z / ppu);+ }+}+/** Follows the app's collision geometry: a static mesh body a piece, built again when its piece is replaced, removed with it. */-function syncPieces(module: Physics3DWasmModule, geometry: CollisionGeometry | null, pieces: PieceMap, ppu: number): void {+function syncPieces(app: App, module: Physics3DWasmModule, geometry: CollisionGeometry | null, pieces: PieceMap, bodies: BodyMap, ppu: number): void {if (!geometry && pieces.size === 0) return;const live = new Set<string>();if (geometry) {@@ -291,7 +317,10 @@ function syncPieces(module: Physics3DWasmModule, geometry: CollisionGeometry | nlive.add(key);const had = pieces.get(key);if (had?.piece === piece) continue;- if (had) module._physics3d_removeBody(had.id);+ if (had) {+ module._physics3d_removeBody(had.id);+ wakeOn(app, module, bodies, had.piece, ppu);+ }const [ox, oy, oz] = piece.origin;const id = addTriangles(module, piece.owner, piece.positions, piece.indices,ox / ppu, oy / ppu, oz / ppu, { x: 0, y: 0, z: 0, w: 1 }, ppu, piece.layer, piece.friction, piece.restitution);@@ -302,6 +331,7 @@ function syncPieces(module: Physics3DWasmModule, geometry: CollisionGeometry | nfor (const [key, had] of pieces) {if (live.has(key)) continue;module._physics3d_removeBody(had.id);+ wakeOn(app, module, bodies, had.piece, ppu);pieces.delete(key);}}@@ -385,7 +415,7 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,poses.delete(entity);}- syncPieces(module, geometry, pieces, ppu);+ syncPieces(app, module, geometry, pieces, bodies, ppu);// Characters have just written local poses of their own, and a body may be// parented to one.diff --git a/sdk/src/platform/nativeModuleRegistry.ts b/sdk/src/platform/nativeModuleRegistry.tsindex 2bea57788..b4eedea18 100644--- a/sdk/src/platform/nativeModuleRegistry.ts+++ b/sdk/src/platform/nativeModuleRegistry.ts@@ -33,6 +33,7 @@ import * as FoliageModule from '../foliage';import * as WorldGenModule from '../worldgen';import * as WaterModule from '../water';import * as SplineModule from '../spline';+import * as VoxelModule from '../voxel';import * as Rig2DModule from '../rig2d';import * as ImportedSceneModule from '../imported-scene';import * as CharacterShadersModule from '../character';@@ -65,6 +66,7 @@ export const NATIVE_MODULE_NAMESPACES: Readonly<Record<string, unknown>> = {'esengine/worldgen': WorldGenModule,'esengine/water': WaterModule,'esengine/spline': SplineModule,+ 'esengine/voxel': VoxelModule,'esengine/rig2d': Rig2DModule,'esengine/imported-scene': ImportedSceneModule,'esengine/character-shaders': CharacterShadersModule,diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.tsindex 435ea0fd5..c9388d75a 100644--- a/sdk/src/render/builtinShaders.ts+++ b/sdk/src/render/builtinShaders.ts@@ -459,7 +459,8 @@ void main() {// The shading a glTF material says beyond its base colour. Those channels are// per-material constants and per-material samplers, which is what a material has// and a component does not — a MeshRenderer's per-object attributes are full.-const MODEL = `#pragma shader "Model"+/** The Model shader's source, for what is derived from it in an optional module. */+export const MODEL = `#pragma shader "Model"#pragma version 300 es#pragma domain Lit#pragma switch ES_SPECULAR_GLOSSINESSdiff --git a/sdk/src/runtime/optionalPlugins.ts b/sdk/src/runtime/optionalPlugins.tsindex 37cf8e5ed..ee0c93d5c 100644--- a/sdk/src/runtime/optionalPlugins.ts+++ b/sdk/src/runtime/optionalPlugins.ts@@ -29,6 +29,7 @@ import { registerFoliageSupport } from '../foliage/foliageSupport';import { registerWorldGenSupport } from '../worldgen/worldgenSupport';import { registerWaterSupport } from '../water/waterSupport';import { registerSplineSupport } from '../spline/splineSupport';+import { registerVoxelSupport } from '../voxel/voxelSupport';import { registerRig2DSupport } from '../rig2d/rig2dSupport';import { registerImportedSceneSupport } from '../imported-scene/importedSceneSupport';import { registerCharacterShaders } from '../character/characterSupport';@@ -53,6 +54,7 @@ export function installOptionalPlugins(): void {registerWorldGenSupport();registerWaterSupport();registerSplineSupport();+ registerVoxelSupport();registerRig2DSupport();registerImportedSceneSupport();registerCharacterShaders();diff --git a/sdk/src/voxel/field.ts b/sdk/src/voxel/field.tsnew file mode 100644index 000000000..44d38c156--- /dev/null+++ b/sdk/src/voxel/field.ts@@ -0,0 +1,481 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file field.ts+ * @brief The ground as a volume: a signed distance at every point of a grid, cut into chunks, that can be carved and filled.+ *+ * @details Below zero is solid. A height field has one answer per column, so it cannot hold a cave or an overhang; this has one per point.+ * A chunk keeps its own copy of a margin one sample wide round it, so that it can be meshed alone and two chunks still agree where+ * they meet. Only what was edited has to be kept: the rest is the source's answer, made again when it is next needed, which is what+ * lets a world without end cost what the player changed in it. Distances are stored in a byte, clamped to a few cells: a+ * surface needs to know its distance only close by.+ */++/** How many layers of material a volume has. */+export const VOXEL_MATERIALS = 4;++/** How many cells a stored distance reaches. */+const RANGE_CELLS = 4;++/** What a place in the volume is. @experimental */+export interface VoxelSample {+ /** How far to the surface, in world units: below zero is solid. Near the surface it should be about true; far from it, only the sign counts. */+ distance: number;+ /** Which of the volume's materials it is, 0 to 3. */+ material: number;+}++/** Says what is at a place, relative to the volume's entity, into `out`. The same place must always get the same answer. @experimental */+export type VoxelSource = (x: number, y: number, z: number, out: VoxelSample) => void;++/** @experimental */+export interface VoxelPoint { x: number; y: number; z: number }++/** A shape to carve with or fill by, in the coordinates of the field. @experimental */+export type VoxelShape =+ | { kind: 'sphere'; center: VoxelPoint; radius: number }+ | { kind: 'box'; center: VoxelPoint; halfExtents: VoxelPoint }+ | { kind: 'capsule'; from: VoxelPoint; to: VoxelPoint; radius: number };++/** @experimental */+export type VoxelOp = 'subtract' | 'add' | 'paint';++/** @experimental */+export interface VoxelEditOptions {+ /** What `add` fills with and `paint` paints. Defaults to 0. */+ material?: number;+ /** How far the shape's edge melts into what it meets, in world units. 0 keeps it sharp. */+ smooth?: number;+ /** Materials this edit cannot change, by a function of the material: stone a pick cannot break. */+ keep?: (material: number) => boolean;+}++/** What an edit did. @experimental */+export interface VoxelEditResult {+ /** The volume taken out of each material, in cubic world units: what a miner carries away. */+ removed: number[];+ /** The volume added, in cubic world units. */+ added: number;+ /** How many chunks changed. */+ chunks: number;+}++/** Where a ray met a volume. @experimental */+export interface VoxelHit {+ point: VoxelPoint;+ normal: VoxelPoint;+ distance: number;+ material: number;+}++/** A volume's changes, as a save stores them, chunk by chunk. Plain JSON. @experimental */+export interface VoxelFieldData {+ version: 1;+ cellSize: number;+ chunkCells: number;+ /** By `cx,cy,cz`: its distances and materials, run-length coded, in base64. */+ chunks: Record<string, string>;+}++export interface VoxelFieldOptions {+ cellSize: number;+ chunkCells: number;+ minY: number;+ maxY: number;+ source: VoxelSource;+ /** How many chunks nothing edited are held once read, so a ray or a dig does not ask the source again. Defaults to 64. */+ cached?: number;+}++/** One chunk: `(cells + 2)` samples a side, from -1 to `cells`. */+export interface VoxelChunk {+ readonly cx: number;+ readonly cy: number;+ readonly cz: number;+ readonly key: string;+ distances: Int8Array | null;+ materials: Uint8Array | null;+ edited: boolean;+ /** Whether any sample is solid and any is not. Known once it has been read. */+ surfaced: boolean;+ revision: number;+ savedRevision: number;+ touched: number;+}++export const chunkKey = (cx: number, cy: number, cz: number): string => `${cx},${cy},${cz}`;++const clampByte = (v: number): number => (v > 127 ? 127 : v < -127 ? -127 : Math.round(v));+const smoothMax = (a: number, b: number, k: number): number => {+ if (k <= 0) return Math.max(a, b);+ const h = Math.max(k - Math.abs(a - b), 0) / k;+ return Math.max(a, b) + h * h * k * 0.25;+};+const smoothMin = (a: number, b: number, k: number): number => -smoothMax(-a, -b, k);++function shapeDistance(shape: VoxelShape, x: number, y: number, z: number): number {+ if (shape.kind === 'sphere') return Math.hypot(x - shape.center.x, y - shape.center.y, z - shape.center.z) - shape.radius;+ if (shape.kind === 'box') {+ const dx = Math.abs(x - shape.center.x) - shape.halfExtents.x, dy = Math.abs(y - shape.center.y) - shape.halfExtents.y, dz = Math.abs(z - shape.center.z) - shape.halfExtents.z;+ return Math.hypot(Math.max(dx, 0), Math.max(dy, 0), Math.max(dz, 0)) + Math.min(Math.max(dx, dy, dz), 0);+ }+ const ax = shape.to.x - shape.from.x, ay = shape.to.y - shape.from.y, az = shape.to.z - shape.from.z;+ const px = x - shape.from.x, py = y - shape.from.y, pz = z - shape.from.z;+ const length2 = ax * ax + ay * ay + az * az;+ const t = length2 > 0 ? Math.min(1, Math.max(0, (px * ax + py * ay + pz * az) / length2)) : 0;+ return Math.hypot(px - ax * t, py - ay * t, pz - az * t) - shape.radius;+}++function shapeBounds(shape: VoxelShape): [number, number, number, number, number, number] {+ if (shape.kind === 'sphere') {+ const { center: c, radius: r } = shape;+ return [c.x - r, c.y - r, c.z - r, c.x + r, c.y + r, c.z + r];+ }+ if (shape.kind === 'box') {+ const { center: c, halfExtents: h } = shape;+ return [c.x - h.x, c.y - h.y, c.z - h.z, c.x + h.x, c.y + h.y, c.z + h.z];+ }+ const { from: a, to: b, radius: r } = shape;+ return [Math.min(a.x, b.x) - r, Math.min(a.y, b.y) - r, Math.min(a.z, b.z) - r, Math.max(a.x, b.x) + r, Math.max(a.y, b.y) + r, Math.max(a.z, b.z) + r];+}++const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';++function toBase64(bytes: Uint8Array): string {+ const parts: string[] = [];+ for (let i = 0; i < bytes.length; i += 3) {+ const a = bytes[i]!, b = bytes[i + 1] ?? 0, c = bytes[i + 2] ?? 0;+ parts.push(BASE64[a >> 2]!, BASE64[((a & 3) << 4) | (b >> 4)]!,+ i + 1 < bytes.length ? BASE64[((b & 15) << 2) | (c >> 6)]! : '=', i + 2 < bytes.length ? BASE64[c & 63]! : '=');+ }+ return parts.join('');+}++function fromBase64(text: string): Uint8Array | null {+ if (text.length % 4 !== 0) return null;+ const pad = text.endsWith('==') ? 2 : text.endsWith('=') ? 1 : 0;+ const out = new Uint8Array(text.length / 4 * 3 - pad);+ let n = 0;+ for (let i = 0; i < text.length; i += 4) {+ const v = [0, 1, 2, 3].map((k) => (text[i + k] === '=' ? 0 : BASE64.indexOf(text[i + k]!)));+ if (v.some((x) => x < 0)) return null;+ if (n < out.length) out[n++] = (v[0]! << 2) | (v[1]! >> 4);+ if (n < out.length) out[n++] = ((v[1]! & 15) << 4) | (v[2]! >> 2);+ if (n < out.length) out[n++] = ((v[2]! & 3) << 6) | v[3]!;+ }+ return out;+}++/** Runs of (count 1..255, byte). Below ground and in the air a chunk is long runs, and a save is mostly these. */+function runLength(input: Uint8Array, out: number[]): void {+ for (let i = 0; i < input.length;) {+ let run = 1;+ while (run < 255 && i + run < input.length && input[i + run] === input[i]) run++;+ out.push(run, input[i]!);+ i += run;+ }+}++function unRunLength(input: Uint8Array, target: Uint8Array): boolean {+ let at = 0;+ for (let i = 0; i + 1 < input.length; i += 2) {+ const run = input[i]!;+ if (at + run > target.length) return false;+ target.fill(input[i + 1]!, at, at + run);+ at += run;+ }+ return at === target.length;+}++export class VoxelField {+ readonly cellSize: number;+ readonly chunkCells: number;+ readonly side: number;+ readonly rowMin: number;+ readonly rowMax: number;+ private readonly floorY_: number;+ private readonly ceilingY_: number;+ /** The world distance a stored byte's 127 stands for. */+ private readonly range_: number;+ private readonly source_: VoxelSource;+ private readonly cached_: number;+ private readonly chunks_ = new Map<string, VoxelChunk>();+ private readonly dirty_ = new Set<VoxelChunk>();+ private readonly sample_: VoxelSample = { distance: 0, material: 0 };+ private clock_ = 0;++ constructor(options: VoxelFieldOptions) {+ this.cellSize = Math.max(options.cellSize, 1e-3);+ this.chunkCells = Math.max(4, Math.min(64, Math.floor(options.chunkCells)));+ this.side = this.chunkCells + 2;+ const span = this.cellSize * this.chunkCells;+ this.floorY_ = options.minY + this.cellSize;+ this.ceilingY_ = options.maxY - this.cellSize;+ this.rowMin = Math.floor(options.minY / span);+ this.rowMax = Math.max(this.rowMin, Math.ceil(options.maxY / span) - 1);+ this.range_ = this.cellSize * RANGE_CELLS;+ this.source_ = options.source;+ this.cached_ = options.cached ?? 64;+ }++ /** The chunk, holding its samples. Asks the source when nothing holds them. */+ chunk(cx: number, cy: number, cz: number): VoxelChunk {+ const key = chunkKey(cx, cy, cz);+ let chunk = this.chunks_.get(key);+ if (!chunk) {+ chunk = { cx, cy, cz, key, distances: null, materials: null, edited: false, surfaced: false, revision: 0, savedRevision: 0, touched: 0 };+ this.chunks_.set(key, chunk);+ }+ if (!chunk.distances) this.generate_(chunk);+ chunk.touched = ++this.clock_;+ return chunk;+ }++ private generate_(chunk: VoxelChunk): void {+ const n = this.chunkCells, s = this.side, cell = this.cellSize, scale = 127 / this.range_;+ const distances = new Int8Array(s * s * s), materials = new Uint8Array(s * s * s);+ const out = this.sample_;+ let i = 0, solid = 0;+ for (let z = -1; z <= n; z++) {+ const wz = (chunk.cz * n + z) * cell;+ for (let y = -1; y <= n; y++) {+ const wy = (chunk.cy * n + y) * cell;+ for (let x = -1; x <= n; x++, i++) {+ out.distance = 1;+ out.material = 0;+ this.source_((chunk.cx * n + x) * cell, wy, wz, out);+ // Closed at both ends: a floor nothing digs through, and nothing standing past the top of what is built.+ const d = Math.min(Math.max(out.distance, wy - this.ceilingY_), wy - this.floorY_);+ const byte = clampByte(d * scale);+ distances[i] = byte;+ materials[i] = out.material;+ if (byte < 0) solid++;+ }+ }+ }+ chunk.distances = distances;+ chunk.materials = materials;+ chunk.surfaced = solid > 0 && solid < i;+ }++ /** Lets go of what the source can make again, oldest first, past the number to hold. What `keep` names stays and is not counted: asking the source again is what a dig must not wait on. */+ trim(keep?: (chunk: VoxelChunk) => boolean): void {+ const free = [...this.chunks_.values()].filter((c) => !c.edited && c.distances && !keep?.(c));+ if (free.length <= this.cached_) return;+ free.sort((a, b) => a.touched - b.touched);+ for (let i = 0; i < free.length - this.cached_; i++) {+ if (!this.dirty_.has(free[i]!)) this.chunks_.delete(free[i]!.key);+ }+ }++ /** The chunks changed since this was last asked. */+ takeDirty(): VoxelChunk[] {+ const out = [...this.dirty_];+ this.dirty_.clear();+ return out;+ }++ /** Carves, fills or paints with a shape. Everything it reaches, the margins of the chunks round it included, changes together. */+ apply(shape: VoxelShape, op: VoxelOp, options: VoxelEditOptions = {}): VoxelEditResult {+ const cell = this.cellSize, n = this.chunkCells, s = this.side;+ const k = Math.max(options.smooth ?? 0, 0);+ const margin = op === 'paint' ? cell : this.range_ + k;+ const b = shapeBounds(shape);+ const g0 = [b[0] - margin, b[1] - margin, b[2] - margin].map((v) => Math.floor(v / cell));+ const g1 = [b[3] + margin, b[4] + margin, b[5] + margin].map((v) => Math.ceil(v / cell));+ const first = (g: number): number => Math.ceil((g - n) / n);+ const last = (g: number): number => Math.floor((g + 1) / n);+ const material = Math.max(0, Math.min(VOXEL_MATERIALS - 1, Math.floor(options.material ?? 0)));+ const removed = new Array<number>(VOXEL_MATERIALS).fill(0);+ let added = 0, touched = 0;+ const scale = 127 / this.range_, unit = this.range_ / 127, volume = cell * cell * cell;+ for (let cz = first(g0[2]!); cz <= last(g1[2]!); cz++) {+ for (let cy = Math.max(first(g0[1]!), this.rowMin); cy <= Math.min(last(g1[1]!), this.rowMax); cy++) {+ for (let cx = first(g0[0]!); cx <= last(g1[0]!); cx++) {+ const chunk = this.chunk(cx, cy, cz);+ const distances = chunk.distances!, materials = chunk.materials!;+ let changed = false;+ const zFrom = Math.max(-1, g0[2]! - cz * n), zTo = Math.min(n, g1[2]! - cz * n);+ const yFrom = Math.max(-1, g0[1]! - cy * n), yTo = Math.min(n, g1[1]! - cy * n);+ const xFrom = Math.max(-1, g0[0]! - cx * n), xTo = Math.min(n, g1[0]! - cx * n);+ for (let z = zFrom; z <= zTo; z++) {+ const wz = (cz * n + z) * cell;+ for (let y = yFrom; y <= yTo; y++) {+ const wy = (cy * n + y) * cell;+ if (op === 'subtract' ? wy <= this.floorY_ : op === 'add' && wy >= this.ceilingY_) continue;+ for (let x = xFrom; x <= xTo; x++) {+ const i = (x + 1) + (y + 1) * s + (z + 1) * s * s;+ const held = materials[i]!, before = distances[i]!;+ if (options.keep?.(held) && before < 0) continue;+ const d = shapeDistance(shape, (cx * n + x) * cell, wy, wz);+ if (op === 'paint') {+ if (d < 0 && before < 0 && held !== material) { materials[i] = material; changed = true; }+ continue;+ }+ const was = before * unit;+ const after = clampByte((op === 'subtract' ? smoothMax(was, -d, k) : smoothMin(was, d, k)) * scale);+ if (after === before) continue;+ distances[i] = after;+ changed = true;+ const owned = x >= 0 && x < n && y >= 0 && y < n && z >= 0 && z < n;+ if (before < 0 && after >= 0 && owned) removed[held]! += volume;+ if (before >= 0 && after < 0) {+ materials[i] = material;+ if (owned) added += volume;+ }+ }+ }+ }+ if (changed) {+ chunk.edited = true;+ chunk.revision++;+ this.refreshSurfaced_(chunk);+ this.dirty_.add(chunk);+ touched++;+ }+ }+ }+ }+ return { removed, added, chunks: touched };+ }++ private refreshSurfaced_(chunk: VoxelChunk): void {+ const d = chunk.distances!;+ let solid = 0;+ for (let i = 0; i < d.length; i++) if (d[i]! < 0) solid++;+ chunk.surfaced = solid > 0 && solid < d.length;+ }++ private at_(gx: number, gy: number, gz: number): number {+ const n = this.chunkCells, s = this.side;+ const cy = Math.floor(gy / n);+ if (cy < this.rowMin) return -this.range_;+ if (cy > this.rowMax) return this.range_;+ const cx = Math.floor(gx / n), cz = Math.floor(gz / n);+ const chunk = this.chunk(cx, cy, cz);+ return chunk.distances![(gx - cx * n + 1) + (gy - cy * n + 1) * s + (gz - cz * n + 1) * s * s]! * (this.range_ / 127);+ }++ /** The signed distance at a place, read between the samples. */+ distanceAt(x: number, y: number, z: number): number {+ const cell = this.cellSize;+ const fx = x / cell, fy = y / cell, fz = z / cell;+ const gx = Math.floor(fx), gy = Math.floor(fy), gz = Math.floor(fz);+ const tx = fx - gx, ty = fy - gy, tz = fz - gz;+ const lerp = (a: number, b: number, t: number): number => a + (b - a) * t;+ const row = (dy: number, dz: number): number => lerp(this.at_(gx, gy + dy, gz + dz), this.at_(gx + 1, gy + dy, gz + dz), tx);+ return lerp(lerp(row(0, 0), row(1, 0), ty), lerp(row(0, 1), row(1, 1), ty), tz);+ }++ /** The material of the deepest solid sample round a place, or -1 where all round it is air. */+ materialAt(x: number, y: number, z: number): number {+ const cell = this.cellSize, n = this.chunkCells, s = this.side;+ const gx = Math.floor(x / cell), gy = Math.floor(y / cell), gz = Math.floor(z / cell);+ let best = -1, deepest = 0;+ for (let k = 0; k < 8; k++) {+ const ax = gx + (k & 1), ay = gy + ((k >> 1) & 1), az = gz + ((k >> 2) & 1);+ const cy = Math.floor(ay / n);+ if (cy < this.rowMin || cy > this.rowMax) continue;+ const cx = Math.floor(ax / n), cz = Math.floor(az / n);+ const chunk = this.chunk(cx, cy, cz);+ const i = (ax - cx * n + 1) + (ay - cy * n + 1) * s + (az - cz * n + 1) * s * s;+ if (chunk.distances![i]! < deepest) { deepest = chunk.distances![i]!; best = chunk.materials![i]!; }+ }+ return best;+ }++ /** Where a ray from `origin` first meets something solid, within `maxDistance`. `direction` need not be of any length. */+ raycast(origin: VoxelPoint, direction: VoxelPoint, maxDistance: number): VoxelHit | null {+ const length = Math.hypot(direction.x, direction.y, direction.z);+ if (!(length > 0)) return null;+ const dx = direction.x / length, dy = direction.y / length, dz = direction.z / length;+ const at = (t: number): number => this.distanceAt(origin.x + dx * t, origin.y + dy * t, origin.z + dz * t);+ let before = 0, t = 0, d = at(0);+ if (d < 0) return this.hit_(origin, dx, dy, dz, 0);+ while (t < maxDistance) {+ before = t;+ t = Math.min(maxDistance, t + Math.max(d * 0.75, this.cellSize * 0.25));+ d = at(t);+ if (d < 0) {+ let lo = before, hi = t;+ for (let i = 0; i < 12; i++) {+ const mid = (lo + hi) * 0.5;+ if (at(mid) < 0) hi = mid; else lo = mid;+ }+ return this.hit_(origin, dx, dy, dz, hi);+ }+ }+ return null;+ }++ private hit_(o: VoxelPoint, dx: number, dy: number, dz: number, t: number): VoxelHit {+ const x = o.x + dx * t, y = o.y + dy * t, z = o.z + dz * t, e = this.cellSize * 0.5;+ const nx = this.distanceAt(x + e, y, z) - this.distanceAt(x - e, y, z);+ const ny = this.distanceAt(x, y + e, z) - this.distanceAt(x, y - e, z);+ const nz = this.distanceAt(x, y, z + e) - this.distanceAt(x, y, z - e);+ const len = Math.hypot(nx, ny, nz) || 1;+ return { point: { x, y, z }, normal: { x: nx / len, y: ny / len, z: nz / len }, distance: t, material: Math.max(0, this.materialAt(x, y, z)) };+ }++ /** What the save holds: every chunk edited, or only those changed since the last call that asked for `changedOnly`. */+ serialize(changedOnly = false): VoxelFieldData {+ const chunks: Record<string, string> = {};+ for (const chunk of this.chunks_.values()) {+ if (!chunk.edited || (changedOnly && chunk.revision === chunk.savedRevision)) continue;+ const bytes: number[] = [];+ runLength(new Uint8Array(chunk.distances!.buffer), bytes);+ runLength(chunk.materials!, bytes);+ chunks[chunk.key] = toBase64(Uint8Array.from(bytes));+ chunk.savedRevision = chunk.revision;+ }+ return { version: 1, cellSize: this.cellSize, chunkCells: this.chunkCells, chunks };+ }++ /**+ * Puts saved chunks back over the volume. With `merge` those not named stay as they are; otherwise they go back to the source. A save cut from another grid cannot+ * be read and changes nothing: false. A chunk that cannot be read is left as it was, and named in `skipped`.+ */+ restore(data: VoxelFieldData, merge = false, skipped?: string[]): boolean {+ if (data?.version !== 1 || data.cellSize !== this.cellSize || data.chunkCells !== this.chunkCells) return false;+ if (!merge) {+ for (const chunk of [...this.chunks_.values()]) {+ if (!chunk.edited || data.chunks[chunk.key] !== undefined) continue;+ chunk.distances = null;+ chunk.materials = null;+ chunk.edited = false;+ chunk.revision++;+ this.generate_(chunk);+ this.dirty_.add(chunk);+ }+ }+ const total = this.side ** 3;+ for (const [key, text] of Object.entries(data.chunks)) {+ const place = key.split(',').map(Number);+ const bytes = fromBase64(text);+ if (place.length !== 3 || place.some((v) => !Number.isInteger(v)) || !bytes) { skipped?.push(key); continue; }+ const distances = new Int8Array(total), materials = new Uint8Array(total);+ let split = 0, count = 0;+ while (split + 1 < bytes.length && count < total) { count += bytes[split]!; split += 2; }+ if (count !== total || !unRunLength(bytes.subarray(0, split), new Uint8Array(distances.buffer)) || !unRunLength(bytes.subarray(split), materials)) { skipped?.push(key); continue; }+ const chunk = this.chunk(place[0]!, place[1]!, place[2]!);+ chunk.distances = distances;+ chunk.materials = materials;+ chunk.edited = true;+ chunk.revision++;+ chunk.savedRevision = chunk.revision;+ this.refreshSurfaced_(chunk);+ this.dirty_.add(chunk);+ }+ return true;+ }++ /** How many chunks are held with their samples, and how many of those were edited. */+ get held(): { chunks: number; edited: number } {+ let chunks = 0, edited = 0;+ for (const c of this.chunks_.values()) {+ if (c.distances) chunks++;+ if (c.edited) edited++;+ }+ return { chunks, edited };+ }+}diff --git a/sdk/src/voxel/index.ts b/sdk/src/voxel/index.tsnew file mode 100644index 000000000..a311d1f4d--- /dev/null+++ b/sdk/src/voxel/index.ts@@ -0,0 +1,17 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+export {+ VoxelTerrain, VoxelTerrains, VoxelTerrainsRes, VoxelPlugin, voxelPlugin,+ type VoxelTerrainData, type VoxelTerrainStatus, type VoxelEditEvent,+} from './voxelPlugin';+export {+ VOXEL_MATERIALS, VoxelField,+ type VoxelEditOptions, type VoxelEditResult, type VoxelFieldData, type VoxelFieldOptions, type VoxelHit, type VoxelOp, type VoxelPoint, type VoxelSample, type VoxelShape, type VoxelSource,+} from './field';+export { heightVoxelSource, noiseVoxelSource, VoxelMaterial, type VoxelNoiseParams } from './source';+export { surfaceNets, type VoxelSurface } from './surfaceNets';++// Importing this subpath INSTALLS volumes — see tilemap/index.ts.+import { registerVoxelSupport } from './voxelSupport';++registerVoxelSupport();diff --git a/sdk/src/voxel/source.ts b/sdk/src/voxel/source.tsnew file mode 100644index 000000000..3ad069627--- /dev/null+++ b/sdk/src/voxel/source.ts@@ -0,0 +1,94 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file source.ts+ * @brief What a volume is before anyone digs in it: hills with caves through them, or any height field given a body.+ */+import type { VoxelSample, VoxelSource } from './field';++/** The material of each part of the stock ground. @experimental */+export const VoxelMaterial = { Topsoil: 0, Soil: 1, Rock: 2, Ore: 3 } as const;++function hash3(x: number, y: number, z: number, seed: number): number {+ let h = Math.imul(x, 0x8da6b343) ^ Math.imul(y, 0xd8163841) ^ Math.imul(z, 0xcb1ab31f) ^ Math.imul(seed, 0x165667b1);+ h = Math.imul(h ^ (h >>> 13), 0x5bd1e995);+ return ((h ^ (h >>> 15)) >>> 0) / 4294967295;+}++/** Smooth noise from -1 to 1 with features about a unit across. */+function noise3(x: number, y: number, z: number, seed: number): number {+ const ix = Math.floor(x), iy = Math.floor(y), iz = Math.floor(z);+ const fx = x - ix, fy = y - iy, fz = z - iz;+ const u = fx * fx * (3 - 2 * fx), v = fy * fy * (3 - 2 * fy), w = fz * fz * (3 - 2 * fz);+ const lerp = (a: number, b: number, t: number): number => a + (b - a) * t;+ const at = (dx: number, dy: number, dz: number): number => hash3(ix + dx, iy + dy, iz + dz, seed);+ return lerp(+ lerp(lerp(at(0, 0, 0), at(1, 0, 0), u), lerp(at(0, 1, 0), at(1, 1, 0), u), v),+ lerp(lerp(at(0, 0, 1), at(1, 0, 1), u), lerp(at(0, 1, 1), at(1, 1, 1), u), v), w) * 2 - 1;+}++/** @experimental */+export interface VoxelNoiseParams {+ seed: number;+ /** Where the ground lies on average, relative to the volume's entity. */+ surfaceHeight: number;+ /** How far the hills rise and fall from it, and how wide they are, in world units. */+ hillHeight: number;+ hillScale: number;+ /** How wide the tunnels are, in world units; 0 has none. */+ caveWidth: number;+ /** How far apart the tunnels are, in world units. */+ caveScale: number;+ /** How deep the soil goes before rock, in world units. */+ soilDepth: number;+ /** The share of the rock that is ore, 0 to 1. */+ oreAmount: number;+ /** The side of the volume's cells. The corners a vertex reads reach about two cells in, so topsoil thinner than that shows soil through in a pattern. Defaults to 1. */+ cellSize?: number;+}++/** Hills, with tunnels where two sheets of noise cross, soil over rock, and pockets of ore. @experimental */+export function noiseVoxelSource(params: VoxelNoiseParams): VoxelSource {+ const { seed, surfaceHeight, hillHeight, soilDepth, caveWidth } = params;+ const hills = 1 / Math.max(params.hillScale, 1e-3), caves = 1 / Math.max(params.caveScale, 1e-3);+ const topsoil = Math.max(soilDepth * 0.25, (params.cellSize ?? 1) * 2.5);+ const oreAt = params.oreAmount > 0 ? 0.7 - Math.min(params.oreAmount, 1) * 1.4 : 2;+ let lastX = NaN, lastZ = NaN, lastHeight = 0;+ return (x, y, z, out) => {+ if (x !== lastX || z !== lastZ) {+ lastX = x;+ lastZ = z;+ lastHeight = surfaceHeight + hillHeight * (noise3(x * hills, 0, z * hills, seed) * 0.7+ + noise3(x * hills * 2.3, 7.5, z * hills * 2.3, seed + 1) * 0.3);+ }+ const above = y - lastHeight;+ let distance = above;+ if (caveWidth > 0 && above < caveWidth) {+ const a = noise3(x * caves, y * caves, z * caves, seed + 2), b = noise3(x * caves, y * caves, z * caves, seed + 3);+ // Where both sheets are near zero is a line through the ground: distance from it, in about world units.+ const tunnel = (Math.hypot(a, b) * params.caveScale * 0.5) - caveWidth;+ distance = Math.max(above, -tunnel);+ }+ out.distance = distance;+ const depth = -above;+ if (depth < topsoil) out.material = VoxelMaterial.Topsoil;+ else if (depth < Math.max(soilDepth, topsoil)) out.material = VoxelMaterial.Soil;+ else out.material = noise3(x * caves * 3, y * caves * 3, z * caves * 3, seed + 4) > oreAt ? VoxelMaterial.Ore : VoxelMaterial.Rock;+ };+}++/**+ * A body under a height field: solid below `heightAt`, so a Terrain's own ground, or any other, can be dug into as a volume. The answer must be+ * the same for the same place, and null where it knows no height is air.+ *+ * @experimental+ */+export function heightVoxelSource(heightAt: (x: number, z: number) => number | null, material: (depth: number, sample: VoxelSample) => void = (depth, s) => {+ s.material = depth < 1 ? VoxelMaterial.Topsoil : depth < 4 ? VoxelMaterial.Soil : VoxelMaterial.Rock;+}): VoxelSource {+ return (x, y, z, out) => {+ const h = heightAt(x, z);+ out.distance = h === null ? 1 : y - h;+ material(-out.distance, out);+ };+}diff --git a/sdk/src/voxel/surfaceNets.ts b/sdk/src/voxel/surfaceNets.tsnew file mode 100644index 000000000..2720268cc--- /dev/null+++ b/sdk/src/voxel/surfaceNets.ts@@ -0,0 +1,149 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file surfaceNets.ts+ * @brief The skin of one chunk of a volume: Naive Surface Nets over its samples.+ *+ * @details One vertex for each cell the surface passes through, at the mean of where it crosses that cell's edges, and one quad for each+ * grid edge it crosses. An edge belongs to the chunk its first sample is in, so no quad is made twice; a vertex and its normal are+ * worked out from the eight corners of its cell alone, and those corners are in both chunks' samples at a border, so the two+ * agree exactly and no crack can open between them, however the chunks were edited.+ */+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';++/** A chunk's skin, relative to the chunk's first corner. */+export interface VoxelSurface {+ positions: Float32Array;+ normals: Float32Array;+ /** Four bytes a vertex: how much of each material it is, summing to about 255. */+ weights: Uint8Array;+ indices: Uint32Array;+}++let cellVertex = new Int32Array(0);+let positions = new Float32Array(1 << 14);+let normals = new Float32Array(1 << 14);+let weights = new Uint8Array(1 << 14);+let indices = new Uint32Array(1 << 15);++function growVertices(): void {+ const p = new Float32Array(positions.length * 2); p.set(positions); positions = p;+ const m = new Float32Array(normals.length * 2); m.set(normals); normals = m;+ const w = new Uint8Array(weights.length * 2); w.set(weights); weights = w;+}++/** The skin of a chunk of `cells` a side, with samples from -1 to `cells`; null where the surface does not pass. */+export function surfaceNets(distances: Int8Array, materials: Uint8Array, cells: number, cellSize: number): VoxelSurface | null {+ const s = cells + 2, s2 = s * s, c = cells + 1;+ if (cellVertex.length < c * c * c) cellVertex = new Int32Array(c * c * c);+ cellVertex.fill(-1, 0, c * c * c);+ let vertices = 0, count = 0;+ const tally = [0, 0, 0, 0];++ /** The vertex of the cell whose low corner is at sample (x, y, z), each from 0 to `cells`. */+ const vertexOf = (x: number, y: number, z: number): number => {+ const id = x + y * c + z * c * c;+ const had = cellVertex[id]!;+ if (had >= 0) return had;+ const base = x + y * s + z * s2;+ let sx = 0, sy = 0, sz = 0, crossings = 0;+ for (let a = 0; a < 8; a++) {+ const ia = base + (a & 1) + ((a >> 1) & 1) * s + ((a >> 2) & 1) * s2;+ const da = distances[ia]!;+ for (let axis = 0; axis < 3; axis++) {+ const bit = 1 << axis;+ if (a & bit) continue;+ const ib = ia + (axis === 0 ? 1 : axis === 1 ? s : s2);+ const db = distances[ib]!;+ if ((da < 0) === (db < 0)) continue;+ const t = da / (da - db);+ sx += (a & 1) + (axis === 0 ? t : 0);+ sy += ((a >> 1) & 1) + (axis === 1 ? t : 0);+ sz += ((a >> 2) & 1) + (axis === 2 ? t : 0);+ crossings++;+ }+ }+ const v = vertices++;+ if ((v + 1) * 3 > positions.length) growVertices();+ const d = (dx: number, dy: number, dz: number): number => distances[base + dx + dy * s + dz * s2]!;+ const nx = d(1, 0, 0) - d(0, 0, 0) + d(1, 1, 0) - d(0, 1, 0) + d(1, 0, 1) - d(0, 0, 1) + d(1, 1, 1) - d(0, 1, 1);+ const ny = d(0, 1, 0) - d(0, 0, 0) + d(1, 1, 0) - d(1, 0, 0) + d(0, 1, 1) - d(0, 0, 1) + d(1, 1, 1) - d(1, 0, 1);+ const nz = d(0, 0, 1) - d(0, 0, 0) + d(1, 0, 1) - d(1, 0, 0) + d(0, 1, 1) - d(0, 1, 0) + d(1, 1, 1) - d(1, 1, 0);+ const len = Math.hypot(nx, ny, nz) || 1;+ // Samples start one before the chunk's corner.+ positions[v * 3] = (x - 1 + sx / crossings) * cellSize;+ positions[v * 3 + 1] = (y - 1 + sy / crossings) * cellSize;+ positions[v * 3 + 2] = (z - 1 + sz / crossings) * cellSize;+ normals[v * 3] = nx / len;+ normals[v * 3 + 1] = ny / len;+ normals[v * 3 + 2] = nz / len;+ tally[0] = tally[1] = tally[2] = tally[3] = 0;+ let solid = 0;+ for (let a = 0; a < 8; a++) {+ const ia = base + (a & 1) + ((a >> 1) & 1) * s + ((a >> 2) & 1) * s2;+ if (distances[ia]! < 0) { tally[materials[ia]! & 3]!++; solid++; }+ }+ for (let m = 0; m < 4; m++) weights[v * 4 + m] = Math.round(tally[m]! / solid * 255);+ cellVertex[id] = v;+ return v;+ };++ const quad = (a: number, b: number, c2: number, d: number, flip: boolean): void => {+ if (count + 6 > indices.length) { const g = new Uint32Array(indices.length * 2); g.set(indices); indices = g; }+ if (flip) { indices[count++] = a; indices[count++] = c2; indices[count++] = b; indices[count++] = a; indices[count++] = d; indices[count++] = c2; }+ else { indices[count++] = a; indices[count++] = b; indices[count++] = c2; indices[count++] = a; indices[count++] = c2; indices[count++] = d; }+ };++ // Each edge starts at a sample of this chunk: samples 1..cells in the arrays, the 0th being the margin before it.+ for (let z = 1; z <= cells; z++) {+ for (let y = 1; y <= cells; y++) {+ for (let x = 1; x <= cells; x++) {+ const i = x + y * s + z * s2;+ const inside = distances[i]! < 0;+ if (inside !== (distances[i + 1]! < 0)) {+ quad(vertexOf(x, y - 1, z - 1), vertexOf(x, y, z - 1), vertexOf(x, y, z), vertexOf(x, y - 1, z), !inside);+ }+ if (inside !== (distances[i + s]! < 0)) {+ quad(vertexOf(x - 1, y, z - 1), vertexOf(x - 1, y, z), vertexOf(x, y, z), vertexOf(x, y, z - 1), !inside);+ }+ if (inside !== (distances[i + s2]! < 0)) {+ quad(vertexOf(x - 1, y - 1, z), vertexOf(x, y - 1, z), vertexOf(x, y, z), vertexOf(x - 1, y, z), !inside);+ }+ }+ }+ }+ if (count === 0) return null;+ return {+ positions: positions.slice(0, vertices * 3), normals: normals.slice(0, vertices * 3),+ weights: weights.slice(0, vertices * 4), indices: indices.slice(0, count),+ };+}++/** A skin as geometry for the engine. */+export function voxelMesh(surface: VoxelSurface): MeshData {+ const { channels, vertexStride } = packChannels([+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },+ // Read by nothing here, and left zero; but a WebGPU pipeline fails with a mesh lacking an attribute its vertex stage takes.+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },+ ]);+ const at = (semantic: number): number => channels.find((c) => c.semantic === semantic)!.offset;+ const posAt = at(MeshChannel.Position), normalAt = at(MeshChannel.Normal), colorAt = at(MeshChannel.Color);+ const vertexCount = surface.positions.length / 3;+ const vertices = new Uint8Array(vertexCount * vertexStride);+ const view = new DataView(vertices.buffer);+ const min: [number, number, number] = [Infinity, Infinity, Infinity], max: [number, number, number] = [-Infinity, -Infinity, -Infinity];+ for (let v = 0; v < vertexCount; v++) {+ const base = v * vertexStride;+ for (let k = 0; k < 3; k++) {+ const p = surface.positions[v * 3 + k]!;+ view.setFloat32(base + posAt + k * 4, p, true);+ view.setFloat32(base + normalAt + k * 4, surface.normals[v * 3 + k]!, true);+ if (p < min[k]!) min[k] = p;+ if (p > max[k]!) max[k] = p;+ }+ for (let k = 0; k < 4; k++) vertices[base + colorAt + k] = surface.weights[v * 4 + k]!;+ }+ return { channels, vertexStride, vertexCount, vertices, indices: surface.indices, aabbMin: min, aabbMax: max };+}diff --git a/sdk/src/voxel/voxelPlugin.ts b/sdk/src/voxel/voxelPlugin.tsnew file mode 100644index 000000000..a8811319b--- /dev/null+++ b/sdk/src/voxel/voxelPlugin.ts@@ -0,0 +1,582 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file voxelPlugin.ts+ * @brief `VoxelTerrain`: ground that is a volume, so it can hold caves and overhangs, and that can be carved while the game runs.+ *+ * @details Beside the height-field Terrain, not instead of it. Columns of chunks are made round the eye to be drawn and round what moves to be+ * collided with, by the same owner of chunks the terrain and the plants use. A chunk's skin is an entity of its own holding a+ * mesh, so only the chunks an edit reached are made again, with the old one kept until the new one is ready. What was changed is+ * kept by chunk and saved by chunk.+ */+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 { MaterialShaderSource } from '../asset/loaders/MaterialShaderAssetLoader';+import { Material, MATERIAL_FORMAT_VERSION } from '../render/material';+import { BlendMode } from '../render/blend';+import { collisionGeometryOf } from '../runtime/collisionGeometry';+import { chunksOf, ProceduralChunksRes, streamingSourcesOf, type ChunkSource } from '../residency/chunks';+import { EditorView, editorViewEye } from '../camera/EditorView';+import { movers } from '../terrain/movers';+import { log } from '../util/logger';+import type { Color, Entity } from '../types';+import { chunkKey, VoxelField, type VoxelChunk, type VoxelEditOptions, type VoxelEditResult, type VoxelFieldData, type VoxelHit, type VoxelOp, type VoxelPoint, type VoxelShape, type VoxelSource } from './field';+import { noiseVoxelSource } from './source';+import { surfaceNets, voxelMesh, type VoxelSurface } from './surfaceNets';++/** The fields of the `VoxelTerrain` component. @experimental */+export interface VoxelTerrainData {+ /** The side of a cell, in world units: the finest thing the ground can show. */+ cellSize: number;+ /** How many cells a chunk has a side: what one edit makes again at the least. */+ chunkCells: number;+ /** How far down and up the volume goes from the entity. It is closed at both ends. */+ minY: number;+ maxY: number;+ seed: number;+ surfaceHeight: number;+ hillHeight: number;+ hillScale: number;+ caveWidth: number;+ caveScale: number;+ soilDepth: number;+ oreAmount: number;+ /** How far from the eye it is drawn, in world units. */+ drawDistance: number;+ castShadows: boolean;+ /** Whether 3D bodies and characters collide with it. */+ collision: boolean;+ /** How far round each moving body and character it is built for collision. */+ collisionDistance: number;+ collisionLayer: number;+ friction: number;+ /** A material on the Voxel Ground shader, or 0 for the stock one with the colours and pictures below. */+ material: number;+ color0: Color;+ color1: Color;+ color2: Color;+ color3: Color;+ map0: number;+ map1: number;+ map2: number;+ map3: number;+ /** How long one repeat of the pictures is in the world. */+ tile: number;+}++const rgb = (r: number, g: number, b: number): Color => ({ r, g, b, a: 1 });++/**+ * Ground that is a volume. Presence is the opt-in; the entity's position places it, and its rotation and scale do not apply.+ *+ * @experimental+ */+export const VoxelTerrain: ComponentDef<VoxelTerrainData> = /* @__PURE__ */ defineComponent<VoxelTerrainData>('VoxelTerrain', {+ cellSize: 1, chunkCells: 24, minY: -48, maxY: 48,+ seed: 1, surfaceHeight: 8, hillHeight: 14, hillScale: 60, caveWidth: 2.5, caveScale: 36, soilDepth: 5, oreAmount: 0.06,+ drawDistance: 96, castShadows: true,+ collision: true, collisionDistance: 32, collisionLayer: 0, friction: 0.6,+ material: 0,+ color0: rgb(0.3, 0.42, 0.2), color1: rgb(0.36, 0.27, 0.18), color2: rgb(0.42, 0.41, 0.4), color3: rgb(0.72, 0.55, 0.25),+ map0: 0, map1: 0, map2: 0, map3: 0, tile: 8,+}, {+ assetFields: [{ field: 'material', type: 'material' }, { field: 'map0', type: 'texture' }, { field: 'map1', type: 'texture' }, { field: 'map2', type: 'texture' }, { field: 'map3', type: 'texture' }],+ fields: {+ cellSize: { min: 0.05, unit: 'wu', category: 'Shape', tooltip: 'The side of a cell: the finest thing the ground can show. Half the size is eight times the cells.' },+ chunkCells: { min: 8, max: 64, step: 1, category: 'Shape', advanced: true, tooltip: 'How many cells a chunk has a side. Smaller makes less again for each edit and draws more meshes.' },+ minY: { unit: 'wu', category: 'Shape', tooltip: 'How far down the volume goes from the entity. Nothing digs through its floor.' },+ maxY: { unit: 'wu', category: 'Shape', tooltip: 'How far up the volume goes from the entity. Nothing is built past it.' },+ seed: { step: 1, category: 'Ground', tooltip: 'Another seed is another ground. A save holds what was changed in the ground this seed makes.' },+ surfaceHeight: { unit: 'wu', category: 'Ground', tooltip: 'Where the ground lies on average, from the entity.' },+ hillHeight: { min: 0, unit: 'wu', category: 'Ground', tooltip: 'How far the hills rise and fall from it.' },+ hillScale: { min: 1, unit: 'wu', category: 'Ground', tooltip: 'How wide the hills are.' },+ caveWidth: { min: 0, unit: 'wu', category: 'Ground', tooltip: 'How wide the tunnels through the ground are. 0 has none.' },+ caveScale: { min: 1, unit: 'wu', category: 'Ground', tooltip: 'How far apart the tunnels are.' },+ soilDepth: { min: 0, unit: 'wu', category: 'Ground', tooltip: 'How deep the soil goes before rock.' },+ oreAmount: { min: 0, max: 1, step: 0.01, category: 'Ground', tooltip: 'How much of the rock is ore.' },+ drawDistance: { min: 1, unit: 'wu', category: 'Detail', tooltip: 'How far from the eye the ground is drawn.' },+ castShadows: { category: 'Detail', tooltip: 'Whether the ground casts shadows.' },+ collision: { category: 'Collision', tooltip: 'Whether 3D bodies and characters collide with the ground.' },+ collisionDistance: { min: 1, unit: 'wu', category: 'Collision', tooltip: 'How far round each moving body and character the ground is built for collision.' },+ collisionLayer: { min: 0, max: 15, step: 1, category: 'Collision', advanced: true, tooltip: 'The collision layer the ground is in (0 to 15).' },+ friction: { min: 0, category: 'Collision', advanced: true, tooltip: 'How much the ground holds what slides on it.' },+ material: { category: 'Look', tooltip: 'A material on the Voxel Ground shader. Empty uses the stock one, with the colours and pictures below.' },+ color0: { label: 'Topsoil', category: 'Look' },+ color1: { label: 'Soil', category: 'Look' },+ color2: { label: 'Rock', category: 'Look' },+ color3: { label: 'Ore', category: 'Look' },+ map0: { label: 'Topsoil Picture', category: 'Look', tooltip: 'Laid from the three sides by world position.' },+ map1: { label: 'Soil Picture', category: 'Look', tooltip: 'Laid from the three sides by world position.' },+ map2: { label: 'Rock Picture', category: 'Look', tooltip: 'Laid from the three sides by world position.' },+ map3: { label: 'Ore Picture', category: 'Look', tooltip: 'Laid from the three sides by world position.' },+ tile: { min: 0.01, unit: 'wu', category: 'Look', tooltip: 'How long one repeat of the pictures is in the world.' },+ },+});++/** What a volume is doing. @experimental */+export interface VoxelTerrainStatus {+ /** Chunks drawn, the triangles they hold, and the chunks with collision. */+ drawnChunks: number;+ triangles: number;+ collidingChunks: number;+ /** Chunks held with their samples, those edited (what a save holds), and those waiting to be made again. */+ heldChunks: number;+ editedChunks: number;+ waitingChunks: number;+ /** The milliseconds the last chunk took to make again. */+ lastRebuildMs: number;+}++/** What an edit changed, relative to the world. @experimental */+export interface VoxelEditEvent {+ entity: Entity;+ shape: VoxelShape;+ op: VoxelOp;+ result: VoxelEditResult;+}++interface DrawnChunk { entity: Entity; mesh: number; triangles: number }++interface Built {+ entity: Entity;+ signature: string;+ field: VoxelField;+ origin: VoxelPoint;+ data: VoxelTerrainData;+ drawn: Map<string, DrawnChunk>;+ /** The columns made to be drawn and to be collided with. */+ drawnColumns: Set<string>;+ collidedColumns: Set<string>;+ collided: Set<string>;+ waiting: Map<string, VoxelChunk>;+ instance: number;+ pending: boolean;+ epoch: number;+ lastRebuildMs: number;+}++/** What, changed, makes the ground again: not how it looks, or how far it reaches. */+function signatureOf(d: VoxelTerrainData, at: VoxelPoint, source: VoxelSource | undefined, sources: Map<VoxelSource, number>): string {+ if (source && !sources.has(source)) sources.set(source, sources.size + 1);+ return JSON.stringify([d.cellSize, d.chunkCells, d.minY, d.maxY, d.seed, d.surfaceHeight, d.hillHeight, d.hillScale, d.caveWidth, d.caveScale, d.soilDepth, d.oreAmount, d.material, d.map0, at.x, at.y, at.z, source ? sources.get(source) : 0]);+}++/**+ * Where a volume is wanted drawn. The game's own eye while it runs; while it is laid out, both the view's eye and what it looks at, since an+ * editor's eye often stands far back from the ground it is looking at, past any distance worth drawing round it.+ */+function drawSources(app: App): ChunkSource[] {+ if (app.hasResource(EditorView)) {+ const view = app.getResource(EditorView);+ if (view.active) {+ const eye = editorViewEye(view);+ return [{ x: eye.x, y: eye.y, z: eye.z }, { x: view.x, y: view.y, z: view.z ?? 0 }];+ }+ }+ return streamingSourcesOf(app);+}++const drawLayerOf = (entity: Entity): string => `voxel-draw:${entity}`;+const collideLayerOf = (entity: Entity): string => `voxel-collide:${entity}`;+const pieceKey = (entity: Entity, key: string): string => `voxel:${entity}:${key}`;+const columnKey = (cx: number, cz: number): string => `${cx},${cz}`;++/** The most time edits may take of a frame, in milliseconds. At least one chunk is always made, so a dig is never left waiting. */+const REBUILD_BUDGET_MS = 4;++/** What a game asks of its volumes. Places are in the world. @experimental */+export class VoxelTerrains {+ /** @internal */ app_: App | null = null;+ /** @internal */ readonly built_ = new Map<Entity, Built>();+ /** @internal */ readonly sources_ = new Map<Entity, VoxelSource>();+ /** @internal */ readonly sourceIds_ = new Map<VoxelSource, number>();+ private readonly listeners_ = new Set<(event: VoxelEditEvent) => void>();++ /** Sets what the volume is before anyone digs in it, in place of the stock hills. The same place must always get the same answer. */+ setSource(entity: Entity, source: VoxelSource | null): void {+ if (source) this.sources_.set(entity, source);+ else this.sources_.delete(entity);+ }++ /** The volume's own field: made here if the system has not yet got to it, so a game can edit in the frame it spawned it. */+ private fieldOf_(entity: Entity): Built | null {+ return this.ensure_?.(entity) ?? this.built_.get(entity) ?? null;+ }++ /** @internal */ ensure_: ((entity: Entity) => Built | null) | null = null;++ /** Changes the volume with a shape. Every chunk the shape reaches is made again, and the collision with it. */+ edit(entity: Entity, shape: VoxelShape, op: VoxelOp, options?: VoxelEditOptions): VoxelEditResult | null {+ const built = this.fieldOf_(entity);+ if (!built) return null;+ const local = localShape(shape, built.origin);+ const result = built.field.apply(local, op, options);+ for (const chunk of built.field.takeDirty()) built.waiting.set(chunk.key, chunk);+ if (result.chunks > 0) for (const listener of this.listeners_) listener({ entity, shape, op, result });+ return result;+ }++ /** Carves a shape out of the volume. What it answers is how much of each material came out. */+ carve(entity: Entity, shape: VoxelShape, options?: VoxelEditOptions): VoxelEditResult | null {+ return this.edit(entity, shape, 'subtract', options);+ }++ /** Fills a shape with a material. */+ fill(entity: Entity, shape: VoxelShape, material = 0, options?: VoxelEditOptions): VoxelEditResult | null {+ return this.edit(entity, shape, 'add', { ...options, material });+ }++ /** Hears every edit that changed something: what a game keeps a navmesh or a quest in step by. Returns how to stop. */+ onEdit(listener: (event: VoxelEditEvent) => void): () => void {+ this.listeners_.add(listener);+ return () => { this.listeners_.delete(listener); };+ }++ /** Where a ray first meets any volume, within `maxDistance`. */+ raycast(origin: VoxelPoint, direction: VoxelPoint, maxDistance = 1000): (VoxelHit & { entity: Entity }) | null {+ let best: (VoxelHit & { entity: Entity }) | null = null;+ for (const entity of [...this.built_.keys()]) {+ const built = this.built_.get(entity)!;+ const hit = built.field.raycast(sub(origin, built.origin), direction, best ? best.distance : maxDistance);+ if (hit && (!best || hit.distance < best.distance)) best = { ...hit, point: add(hit.point, built.origin), entity };+ }+ return best;+ }++ /** The signed distance at a place: below zero is inside something solid. Null with no such volume. */+ distanceAt(entity: Entity, at: VoxelPoint): number | null {+ const built = this.fieldOf_(entity);+ if (!built) return null;+ const p = sub(at, built.origin);+ return built.field.distanceAt(p.x, p.y, p.z);+ }++ /** The material at a place, or -1 in the open. Null with no such volume. */+ materialAt(entity: Entity, at: VoxelPoint): number | null {+ const built = this.fieldOf_(entity);+ if (!built) return null;+ const p = sub(at, built.origin);+ return built.field.materialAt(p.x, p.y, p.z);+ }++ /** What a save holds: only chunks that were edited, and with `changedOnly` only those changed since the last such call. Plain JSON. */+ serialize(entity: Entity, changedOnly = false): VoxelFieldData | null {+ return this.fieldOf_(entity)?.field.serialize(changedOnly) ?? null;+ }++ /** Puts a save back; with `merge`, over what is there rather than instead of it. False when it was cut from another grid and nothing changed. */+ restore(entity: Entity, data: VoxelFieldData, merge = false): boolean {+ const built = this.fieldOf_(entity);+ if (!built) return false;+ const skipped: string[] = [];+ const ok = built.field.restore(data, merge, skipped);+ if (skipped.length) log.warn('voxel', `a save's chunks could not be read and were left as they were: ${skipped.slice(0, 8).join(' ')}`);+ for (const chunk of built.field.takeDirty()) built.waiting.set(chunk.key, chunk);+ return ok;+ }++ /** Whether the volume round (x, z) is built for collision: what a game waits on before it drops something there. */+ collisionReadyAt(entity: Entity, x: number, z: number): boolean {+ const built = this.built_.get(entity);+ if (!built) return false;+ const span = built.field.cellSize * built.field.chunkCells;+ return built.collidedColumns.has(columnKey(Math.floor((x - built.origin.x) / span), Math.floor((z - built.origin.z) / span)));+ }++ status(entity: Entity): VoxelTerrainStatus | null {+ const built = this.built_.get(entity);+ if (!built) return null;+ let triangles = 0;+ for (const d of built.drawn.values()) triangles += d.triangles;+ const held = built.field.held;+ return {+ drawnChunks: built.drawn.size, triangles, collidingChunks: built.collided.size, heldChunks: held.chunks, editedChunks: held.edited,+ waitingChunks: built.waiting.size, lastRebuildMs: built.lastRebuildMs,+ };+ }+}++const add = (a: VoxelPoint, b: VoxelPoint): VoxelPoint => ({ x: a.x + b.x, y: a.y + b.y, z: a.z + b.z });+const sub = (a: VoxelPoint, b: VoxelPoint): VoxelPoint => ({ x: a.x - b.x, y: a.y - b.y, z: a.z - b.z });++function localShape(shape: VoxelShape, origin: VoxelPoint): VoxelShape {+ if (shape.kind === 'capsule') return { ...shape, from: sub(shape.from, origin), to: sub(shape.to, origin) };+ return { ...shape, center: sub(shape.center, origin) };+}++/** @experimental */+export const VoxelTerrainsRes = defineResource<VoxelTerrains>(new VoxelTerrains(), 'VoxelTerrains');++/** Makes and keeps every `VoxelTerrain`. @experimental */+export class VoxelPlugin implements Plugin {+ name = 'voxel';+ readonly activeWhen = [VoxelTerrain];+ private stock_ = 0;++ build(app: App): void {+ const terrains = new VoxelTerrains();+ terrains.app_ = app;+ terrains.ensure_ = (entity) => this.ensure(app, terrains, entity);+ app.insertResource(VoxelTerrainsRes, terrains);+ app.world.onDespawn((entity) => {+ const built = terrains.built_.get(entity);+ if (built) this.destroy(app, terrains, built);+ terrains.sources_.delete(entity);+ });+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ const rendering = app.hasResource(Assets);+ for (const built of [...terrains.built_.values()]) {+ if (!app.world.valid(built.entity) || !app.world.has(built.entity, VoxelTerrain)) this.destroy(app, terrains, built);+ }+ for (const entity of app.world.getEntitiesWithComponents([VoxelTerrain, Transform])) {+ const built = this.ensure(app, terrains, entity);+ if (!built) continue;+ built.data = { ...(app.world.get(entity, VoxelTerrain) as VoxelTerrainData) };+ this.collide(app, built);+ if (rendering) {+ if (built.data.material || built.instance) this.draw(app, built);+ else if (!built.pending) void this.prepare(app, built);+ }+ this.remake(app, built);+ built.field.trim((c) => built.collidedColumns.has(columnKey(c.cx, c.cz)));+ }+ }, { name: 'VoxelTerrainSystem' }));+ }++ cleanup(app?: App): void {+ if (!app?.hasResource(VoxelTerrainsRes)) return;+ const terrains = app.getResource(VoxelTerrainsRes);+ for (const built of [...terrains.built_.values()]) this.destroy(app, terrains, built);+ if (this.stock_) Material.release(this.stock_);+ this.stock_ = 0;+ }++ /** The volume's state: made again when what it is made from has changed. */+ private ensure(app: App, terrains: VoxelTerrains, entity: Entity): Built | null {+ const world = app.world;+ if (!world.valid(entity) || !world.has(entity, VoxelTerrain) || !world.has(entity, Transform)) return null;+ world.ensureTransformsComposed();+ const data = world.get(entity, VoxelTerrain) as VoxelTerrainData;+ const at = (world.get(entity, Transform) as TransformData).worldPosition;+ const source = terrains.sources_.get(entity);+ const signature = signatureOf(data, at, source, terrains.sourceIds_);+ const had = terrains.built_.get(entity);+ if (had?.signature === signature) return had;+ // Moved, it is the same volume elsewhere: what was dug goes with it.+ const save = had ? had.field.serialize() : null;+ if (had) this.destroy(app, terrains, had);+ const field = new VoxelField({+ cellSize: data.cellSize, chunkCells: data.chunkCells, minY: data.minY, maxY: data.maxY,+ source: source ?? noiseVoxelSource(data),+ });+ const built: Built = {+ entity, signature, field, origin: { x: at.x, y: at.y, z: at.z }, data: { ...data }, drawn: new Map(), drawnColumns: new Set(), collidedColumns: new Set(), collided: new Set(),+ waiting: new Map(), instance: 0, pending: false, epoch: (had?.epoch ?? 0) + 1, lastRebuildMs: 0,+ };+ if (save) { field.restore(save); field.takeDirty(); }+ terrains.built_.set(entity, built);+ return built;+ }++ private async prepare(app: App, built: Built): Promise<void> {+ built.pending = true;+ const epoch = built.epoch;+ try {+ const material = await this.stock(app);+ if (built.epoch !== epoch || !material) return;+ built.instance = Material.createInstance(material);+ } catch (e) {+ log.error('voxel', 'preparing the volume failed', e);+ } finally {+ built.pending = false;+ }+ }++ private async stock(app: App): Promise<number> {+ if (this.stock_) return this.stock_;+ const source = await app.getResource(Assets).load<MaterialShaderSource>('material-shader', 'builtin:voxel-ground');+ const shader = source.compile([]);+ if (this.stock_) return this.stock_;+ this.stock_ = Material.createFromAsset({+ version: MATERIAL_FORMAT_VERSION, type: 'material', shader: 'builtin:voxel-ground', blendMode: BlendMode.None,+ depthTest: true, depthWrite: true, cull: 0, properties: {},+ }, shader);+ return this.stock_;+ }++ private rows(built: Built): number[] {+ const out: number[] = [];+ for (let y = built.field.rowMin; y <= built.field.rowMax; y++) out.push(y);+ return out;+ }++ /** One chunk's skin, and its surface data, or null where nothing passes through. */+ private skin(built: Built, chunk: VoxelChunk): VoxelSurface | null {+ return chunk.surfaced ? surfaceNets(chunk.distances!, chunk.materials!, built.field.chunkCells, built.field.cellSize) : null;+ }++ private showChunk(app: App, built: Built, chunk: VoxelChunk, surface: VoxelSurface | null): void {+ const d = built.data, world = app.world, assets = app.getResource(Assets);+ const had = built.drawn.get(chunk.key);+ if (!surface) {+ if (had) {+ if (world.valid(had.entity)) world.despawn(had.entity);+ assets.releaseBuiltMesh(had.mesh);+ built.drawn.delete(chunk.key);+ }+ return;+ }+ const mesh = assets.createMesh(voxelMesh(surface));+ if (!mesh) return;+ const span = built.field.cellSize * built.field.chunkCells;+ const entity = had?.entity ?? world.spawn(`VoxelChunk ${chunk.key}`);+ if (!had) {+ world.insert(entity, RuntimeOnly);+ world.insert(entity, Transform, { position: { x: chunk.cx * span, y: chunk.cy * span, z: chunk.cz * span } });+ world.setParent(entity, built.entity);+ }+ const renderer = had ? world.get(entity, MeshRenderer) as MeshRendererData : null;+ world.insert(entity, MeshRenderer, {+ ...renderer, enabled: true, mesh, material: built.instance || d.material, texture: d.map0, lit: true, opaque: true, cullBackfaces: true, castShadows: d.castShadows,+ } as Partial<MeshRendererData>);+ if (had) assets.releaseBuiltMesh(had.mesh);+ built.drawn.set(chunk.key, { entity, mesh, triangles: surface.indices.length / 3 });+ }++ private colliderOf(app: App, built: Built, chunk: VoxelChunk, surface: VoxelSurface | null): void {+ const geometry = collisionGeometryOf(app), key = pieceKey(built.entity, chunk.key), d = built.data;+ if (!surface) {+ geometry.delete(key);+ built.collided.delete(chunk.key);+ return;+ }+ const span = built.field.cellSize * built.field.chunkCells;+ geometry.set(key, {+ owner: built.entity, origin: [built.origin.x + chunk.cx * span, built.origin.y + chunk.cy * span, built.origin.z + chunk.cz * span],+ positions: surface.positions, indices: surface.indices, friction: d.friction, restitution: 0, layer: d.collisionLayer,+ });+ built.collided.add(chunk.key);+ }++ /** The chunks edits reached, for as long as the frame can spare and at least one, so a dig is always seen. */+ private remake(app: App, built: Built): void {+ if (built.waiting.size === 0) return;+ const started = performance.now();+ const rendering = app.hasResource(Assets) && !!(built.instance || built.data.material);+ for (const [key, chunk] of built.waiting) {+ const column = columnKey(chunk.cx, chunk.cz);+ const drawn = rendering && built.drawnColumns.has(column), collided = built.collidedColumns.has(column);+ if (drawn || collided) {+ const began = performance.now();+ const live = built.field.chunk(chunk.cx, chunk.cy, chunk.cz);+ const surface = this.skin(built, live);+ if (drawn) this.showChunk(app, built, live, surface);+ if (collided && built.data.collision) this.colliderOf(app, built, live, surface);+ built.lastRebuildMs = performance.now() - began;+ }+ built.waiting.delete(key);+ if (performance.now() - started > REBUILD_BUDGET_MS) break;+ }+ }++ private draw(app: App, built: Built): void {+ const d = built.data;+ const instance = built.instance;+ if (instance && !d.material) {+ const set = (name: string, value: Parameters<typeof Material.setUniform>[2]): void => { Material.setUniform(instance, name, value); };+ for (const [i, c] of [d.color0, d.color1, d.color2, d.color3].entries()) set(`u_voxelTint${i}`, { x: c.r, y: c.g, z: c.b, w: c.a });+ set('u_voxelTile', d.tile);+ if (d.map1) set('u_voxelMap1', Material.tex(d.map1));+ if (d.map2) set('u_voxelMap2', Material.tex(d.map2));+ if (d.map3) set('u_voxelMap3', Material.tex(d.map3));+ }+ const span = built.field.cellSize * built.field.chunkCells;+ const chunks = chunksOf(app);+ chunks.set<{ cx: number; cz: number; skins: { chunk: VoxelChunk; surface: VoxelSurface | null }[] }>(drawLayerOf(built.entity), {+ label: 'Building the volume',+ originX: built.origin.x, originZ: built.origin.z, sizeX: span, sizeZ: span, extent: null,+ loadRadius: Math.max(d.drawDistance, 0), unloadRadius: Math.max(d.drawDistance, 0) + span,+ generation: built.epoch,+ sources: () => drawSources(app),+ make: (cx, cz) => ({ cx, cz, skins: this.rows(built).map((cy) => {+ const chunk = built.field.chunk(cx, cy, cz);+ return { chunk, surface: this.skin(built, chunk) };+ }) }),+ publish: (cx, cz, { skins }) => {+ built.drawnColumns.add(columnKey(cx, cz));+ for (const { chunk, surface } of skins) {+ this.showChunk(app, built, chunk, surface);+ built.waiting.delete(chunk.key);+ }+ },+ release: (cx, cz) => {+ built.drawnColumns.delete(columnKey(cx, cz));+ for (const cy of this.rows(built)) {+ const key = chunkKey(cx, cy, cz);+ const had = built.drawn.get(key);+ if (!had) continue;+ if (app.world.valid(had.entity)) app.world.despawn(had.entity);+ if (app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(had.mesh);+ built.drawn.delete(key);+ }+ },+ });+ }++ private collide(app: App, built: Built): void {+ const id = collideLayerOf(built.entity), d = built.data;+ if (!d.collision) {+ if (app.hasResource(ProceduralChunksRes)) app.getResource(ProceduralChunksRes).remove(id);+ return;+ }+ const span = built.field.cellSize * built.field.chunkCells;+ chunksOf(app).set<{ skins: { chunk: VoxelChunk; surface: VoxelSurface | null }[] }>(id, {+ label: 'Building the volume\'s collision',+ originX: built.origin.x, originZ: built.origin.z, sizeX: span, sizeZ: span, extent: null,+ loadRadius: Math.max(d.collisionDistance, 0), unloadRadius: Math.max(d.collisionDistance, 0) + span,+ generation: `${built.epoch}:${d.collisionLayer}:${d.friction}`,+ sources: () => movers(app),+ make: (cx, cz) => ({ skins: this.rows(built).map((cy) => {+ const chunk = built.field.chunk(cx, cy, cz);+ return { chunk, surface: this.skin(built, chunk) };+ }) }),+ publish: (cx, cz, { skins }) => {+ built.collidedColumns.add(columnKey(cx, cz));+ for (const { chunk, surface } of skins) this.colliderOf(app, built, chunk, surface);+ },+ release: (cx, cz) => {+ built.collidedColumns.delete(columnKey(cx, cz));+ const geometry = collisionGeometryOf(app);+ for (const cy of this.rows(built)) {+ const key = chunkKey(cx, cy, cz);+ geometry.delete(pieceKey(built.entity, key));+ built.collided.delete(key);+ }+ },+ });+ }++ private destroy(app: App, terrains: VoxelTerrains, built: Built): void {+ terrains.built_.delete(built.entity);+ built.epoch++;+ if (app.hasResource(ProceduralChunksRes)) {+ const chunks = app.getResource(ProceduralChunksRes);+ chunks.remove(drawLayerOf(built.entity));+ chunks.remove(collideLayerOf(built.entity));+ }+ collisionGeometryOf(app).deleteAll(`voxel:${built.entity}:`);+ for (const had of built.drawn.values()) {+ if (app.world.valid(had.entity)) app.world.despawn(had.entity);+ if (app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(had.mesh);+ }+ built.drawn.clear();+ if (built.instance) Material.release(built.instance);+ built.instance = 0;+ }+}++/** @experimental */+export const voxelPlugin: VoxelPlugin = /* @__PURE__ */ new VoxelPlugin();diff --git a/sdk/src/voxel/voxelShader.ts b/sdk/src/voxel/voxelShader.tsnew file mode 100644index 000000000..e5579d104--- /dev/null+++ b/sdk/src/voxel/voxelShader.ts@@ -0,0 +1,96 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file voxelShader.ts+ * @brief The Model shader, for ground with no uv: up to four materials weighted by the vertex colour, each read from the three sides.+ *+ * @details A volume's skin is found afterwards and can face any way, so nothing could be unwrapped: each picture is laid by world position along+ * whichever axis the surface faces. The vertex colour is how much of each material a vertex is. Being derived from Model it is lit,+ * shadowed and fogged as anything else in the scene is, and a material moved onto it keeps every param it had.+ */++/** Material 0 is the shader's main texture, so the others cost three more. The emissive map gives its unit up: this skin has no uv to read one by. */+const PARAMS = `// The colour of each material, multiplied into its picture.+#pragma param u_voxelTint0 color default(0.3,0.42,0.2,1)+#pragma param u_voxelTint1 color default(0.36,0.27,0.18,1)+#pragma param u_voxelTint2 color default(0.42,0.41,0.4,1)+#pragma param u_voxelTint3 color default(0.72,0.55,0.25,1)+// The pictures of materials 1 to 3. Material 0's is the main texture.+#pragma param u_voxelMap1 texture default(white)+#pragma param u_voxelMap2 texture default(white)+#pragma param u_voxelMap3 texture default(white)+// How long one repeat of the pictures is in the world.+#pragma param u_voxelTile float default(8) range(0.01,100000) ui(slider)+// How rough each material is.+#pragma param u_voxelRoughness vec4 default(0.95,0.95,0.85,0.45)+`;++const GLSL_HELPERS = `+vec4 voxelRead(sampler2D map, highp vec3 W, vec3 side) {+ return texture(map, W.zy) * side.x + texture(map, W.xz) * side.y + texture(map, W.xy) * side.z;+}+`;++const WGSL_HELPERS = `+fn voxelRead(map : texture_2d<f32>, smp : sampler, W : vec3f, Wdx : vec3f, Wdy : vec3f, side : vec3f) -> vec4f {+ return textureSampleGrad(map, smp, W.zy, Wdx.zy, Wdy.zy) * side.x+ + textureSampleGrad(map, smp, W.xz, Wdx.xz, Wdy.xz) * side.y+ + textureSampleGrad(map, smp, W.xy, Wdx.xy, Wdy.xy) * side.z;+}+`;++const GLSL_SURFACE = `#ifdef MESH_NORMALS+ highp vec3 voxelW = v_worldXYZ / u_voxelTile;+ vec3 voxelSide = pow(abs(normalize(v_worldNormal)), vec3(4.0));+ voxelSide /= max(voxelSide.x + voxelSide.y + voxelSide.z, 1e-4);+ vec4 voxelMix = v_color / max(v_color.r + v_color.g + v_color.b + v_color.a, 1e-4);+ vec4 base = voxelRead(u_textures[0], voxelW, voxelSide) * u_voxelTint0 * voxelMix.r+ + voxelRead(u_voxelMap1, voxelW, voxelSide) * u_voxelTint1 * voxelMix.g+ + voxelRead(u_voxelMap2, voxelW, voxelSide) * u_voxelTint2 * voxelMix.b+ + voxelRead(u_voxelMap3, voxelW, voxelSide) * u_voxelTint3 * voxelMix.a;+ base.a = 1.0;+ base.rgb *= u_tint.rgb;+#else+ vec4 voxelMix = vec4(0.0, 0.0, 1.0, 0.0);+ vec4 base = u_voxelTint2 * u_tint;+#endif+`;++const WGSL_SURFACE = `#ifdef MESH_NORMALS+ let voxelW = v.v_worldXYZ / mc.u_voxelTile;+ let voxelWdx = dpdx(voxelW);+ let voxelWdy = dpdy(voxelW);+ var voxelSide = pow(abs(normalize(v.v_worldNormal)), vec3f(4.0));+ voxelSide = voxelSide / max(voxelSide.x + voxelSide.y + voxelSide.z, 1e-4);+ let voxelMix = v.v_color / max(v.v_color.r + v.v_color.g + v.v_color.b + v.v_color.a, 1e-4);+ var base = voxelRead(t0, s0, voxelW, voxelWdx, voxelWdy, voxelSide) * mc.u_voxelTint0 * voxelMix.r+ + voxelRead(u_voxelMap1, u_voxelMap1_s, voxelW, voxelWdx, voxelWdy, voxelSide) * mc.u_voxelTint1 * voxelMix.g+ + voxelRead(u_voxelMap2, u_voxelMap2_s, voxelW, voxelWdx, voxelWdy, voxelSide) * mc.u_voxelTint2 * voxelMix.b+ + voxelRead(u_voxelMap3, u_voxelMap3_s, voxelW, voxelWdx, voxelWdy, voxelSide) * mc.u_voxelTint3 * voxelMix.a;+ base = vec4f(base.rgb * mc.u_tint.rgb, 1.0);+#else+ let voxelMix = vec4f(0.0, 0.0, 1.0, 0.0);+ var base = mc.u_voxelTint2 * mc.u_tint;+#endif+`;++function swap(source: string, from: string, to: string): string {+ if (!source.includes(from)) throw new Error(`the Model shader no longer has what Voxel Ground is made from: ${from.slice(0, 60)}`);+ return source.replace(from, () => to);+}++/** Voxel Ground from the Model shader's source. */+export function deriveVoxelGround(model: string): string {+ let s = swap(model, '#pragma shader "Model"', '#pragma shader "Voxel Ground"');+ s = swap(s, '#pragma param u_iridescence float', `${PARAMS}#pragma param u_iridescence float`);+ s = swap(s, '#pragma param u_emissiveMap texture default(white)\n', '');+ s = swap(s, 'texture(u_emissiveMap, v_texCoord).rgb', 'vec3(1.0)');+ s = swap(s, 'textureSampleGrad(u_emissiveMap, u_emissiveMap_s, v.v_texCoord, duvx, duvy).rgb', 'vec3f(1.0)');+ s = swap(s, 'float specularAA(highp vec3', `${GLSL_HELPERS}float specularAA(highp vec3`);+ s = swap(s, 'fn specularAA(dndx : vec3f', `${WGSL_HELPERS}fn specularAA(dndx : vec3f`);+ s = swap(s, ' vec4 base = texture(u_textures[0], v_texCoord) * v_color * u_tint;\n', GLSL_SURFACE);+ s = swap(s, ' var base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color * mc.u_tint;\n', WGSL_SURFACE);+ s = swap(s, 'float roughness = u_roughness * mr.g;', 'float roughness = u_roughness * mr.g * dot(voxelMix, u_voxelRoughness);');+ s = swap(s, 'var roughness = mc.u_roughness * mr.g;', 'var roughness = mc.u_roughness * mr.g * dot(voxelMix, mc.u_voxelRoughness);');+ return s;+}diff --git a/sdk/src/voxel/voxelSupport.ts b/sdk/src/voxel/voxelSupport.tsnew file mode 100644index 000000000..1b19dba5e--- /dev/null+++ b/sdk/src/voxel/voxelSupport.ts@@ -0,0 +1,17 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file voxelSupport.ts — what a build that ships volumes tells the core.+ *+ * A call, not a file's side effect — see tilemap/tilemapSupport.ts.+ */+import { addEntryPlugin } from '../runtime/entryPlugins';+import { makeBuiltinShaderTemplate, MODEL, registerBuiltinShaderTemplate } from '../render/builtinShaders';+import { deriveVoxelGround } from './voxelShader';+import { VoxelPlugin } from './voxelPlugin';++export function registerVoxelSupport(): void {+ registerBuiltinShaderTemplate(makeBuiltinShaderTemplate('voxel-ground', 'Voxel Ground',+ 'Model, for ground with no uv: up to four materials weighted by the vertex colour, each laid from the three sides by world position.', deriveVoxelGround(MODEL)));+ addEntryPlugin('voxel', () => new VoxelPlugin());+}diff --git a/sdk/tests/voxel-field.test.ts b/sdk/tests/voxel-field.test.tsnew file mode 100644index 000000000..a0f9aa42f--- /dev/null+++ b/sdk/tests/voxel-field.test.ts@@ -0,0 +1,324 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** A volume and its skin, with no engine: what can be dug, what it gives back, that chunks meet with no crack, and what a save holds. */+import { describe, expect, it } from 'vitest';+import { VoxelField, type VoxelFieldData, type VoxelSource } from '../src/voxel/field';+import { heightVoxelSource, noiseVoxelSource, VoxelMaterial } from '../src/voxel/source';+import { surfaceNets, type VoxelSurface } from '../src/voxel/surfaceNets';++const flat: VoxelSource = (_x, y, _z, out) => { out.distance = y; out.material = 2; };+const make = (source: VoxelSource = flat, cached = 64) => new VoxelField({ cellSize: 1, chunkCells: 8, minY: -16, maxY: 16, source, cached });+const skinOf = (f: VoxelField, cx: number, cy: number, cz: number): VoxelSurface | null => {+ const c = f.chunk(cx, cy, cz);+ return surfaceNets(c.distances!, c.materials!, f.chunkCells, f.cellSize);+};+const rows = (f: VoxelField) => { const out: number[] = []; for (let y = f.rowMin; y <= f.rowMax; y++) out.push(y); return out; };++/** Every skin of a square of columns, in world positions, each triangle as its three vertices. */+function world(f: VoxelField, from: number, to: number): { x: number; y: number; z: number; nx: number; ny: number; nz: number }[][] {+ const span = f.cellSize * f.chunkCells, out: { x: number; y: number; z: number; nx: number; ny: number; nz: number }[][] = [];+ for (let cz = from; cz <= to; cz++) for (const cy of rows(f)) for (let cx = from; cx <= to; cx++) {+ const s = skinOf(f, cx, cy, cz);+ if (!s) continue;+ for (let i = 0; i < s.indices.length; i += 3) {+ out.push([0, 1, 2].map((k) => {+ const v = s.indices[i + k]!;+ return { x: s.positions[v * 3]! + cx * span, y: s.positions[v * 3 + 1]! + cy * span, z: s.positions[v * 3 + 2]! + cz * span, nx: s.normals[v * 3]!, ny: s.normals[v * 3 + 1]!, nz: s.normals[v * 3 + 2]! };+ }));+ }+ }+ return out;+}++/** Edges not matched by as many running the other way: a hole, or a surface not closed where chunks meet. Inside the square only. */+function openEdges(tris: ReturnType<typeof world>, inside: (x: number, z: number) => boolean): number {+ const key = (p: { x: number; y: number; z: number }) => `${p.x.toFixed(3)},${p.y.toFixed(3)},${p.z.toFixed(3)}`;+ const edges = new Map<string, number>();+ for (const t of tris) for (let k = 0; k < 3; k++) {+ const a = t[k]!, b = t[(k + 1) % 3]!;+ if (!inside(a.x, a.z) || !inside(b.x, b.z)) continue;+ edges.set(`${key(a)}|${key(b)}`, (edges.get(`${key(a)}|${key(b)}`) ?? 0) + 1);+ }+ let open = 0;+ for (const e of edges.keys()) {+ const [a, b] = e.split('|');+ // Equal both ways, not once each: a cell where two sheets touch shares an edge between four faces, and that is no gap.+ if ((edges.get(`${b}|${a}`) ?? 0) !== edges.get(e)) open++;+ }+ return open;+}++describe('a volume', () => {+ it('reads what its source says, and is solid below zero', () => {+ const f = make();+ expect(f.distanceAt(3.5, 2, 3.5)).toBeCloseTo(2, 1);+ expect(f.distanceAt(3.5, -2, 3.5)).toBeCloseTo(-2, 1);+ expect(f.materialAt(3.5, -2, 3.5)).toBe(2);+ expect(f.materialAt(3.5, 3, 3.5)).toBe(-1);+ });++ it('holds what a height field cannot: air under solid, in one column', () => {+ const f = make();+ f.apply({ kind: 'sphere', center: { x: 4, y: -8, z: 4 }, radius: 3 }, 'subtract');+ expect(f.distanceAt(4, 1, 4)).toBeGreaterThan(0);+ expect(f.distanceAt(4, -2, 4)).toBeLessThan(0);+ expect(f.distanceAt(4, -8, 4)).toBeGreaterThan(0);+ expect(f.distanceAt(4, -13, 4)).toBeLessThan(0);+ });++ it('says how much came out of each material, about the volume of the shape', () => {+ const f = make();+ const r = f.apply({ kind: 'sphere', center: { x: 0.3, y: -8.2, z: 0.1 }, radius: 3 }, 'subtract');+ expect(r.removed[2]!).toBeGreaterThan(4 / 3 * Math.PI * 27 * 0.85);+ expect(r.removed[2]!).toBeLessThan(4 / 3 * Math.PI * 27 * 1.15);+ expect(r.removed[0]).toBe(0);+ expect(r.chunks).toBeGreaterThan(1);+ });++ it('counts a place on a border once, however many chunks hold a copy of it', () => {+ const f = make();+ const box = f.apply({ kind: 'box', center: { x: 8, y: -8, z: 8 }, halfExtents: { x: 2.5, y: 2.5, z: 2.5 } }, 'subtract');+ expect(box.removed[2]).toBe(125);+ });++ it('fills with the material it is told, and digging it gives that back', () => {+ const f = make();+ const up = f.apply({ kind: 'box', center: { x: 4, y: 5, z: 4 }, halfExtents: { x: 1.5, y: 1.5, z: 1.5 } }, 'add', { material: 3 });+ expect(up.added).toBe(27);+ expect(f.materialAt(4, 5, 4)).toBe(3);+ const down = f.apply({ kind: 'box', center: { x: 4, y: 5, z: 4 }, halfExtents: { x: 1.5, y: 1.5, z: 1.5 } }, 'subtract');+ expect(down.removed[3]).toBe(27);+ });++ it('paints without changing the shape', () => {+ const f = make();+ const before = f.distanceAt(4, -3, 4);+ f.apply({ kind: 'sphere', center: { x: 4, y: -3, z: 4 }, radius: 2 }, 'paint', { material: 1 });+ expect(f.materialAt(4, -3, 4)).toBe(1);+ expect(f.distanceAt(4, -3, 4)).toBe(before);+ expect(f.materialAt(4, -9, 4)).toBe(2);+ });++ it('leaves alone what the edit is told to keep', () => {+ const f = make();+ const r = f.apply({ kind: 'sphere', center: { x: 4, y: -8, z: 4 }, radius: 3 }, 'subtract', { keep: (m) => m === 2 });+ expect(r.chunks).toBe(0);+ expect(f.distanceAt(4, -8, 4)).toBeLessThan(0);+ });++ it('has a floor nothing digs through and a top nothing is built past', () => {+ const f = make();+ f.apply({ kind: 'sphere', center: { x: 4, y: -16, z: 4 }, radius: 6 }, 'subtract');+ expect(f.distanceAt(4, -15.5, 4)).toBeLessThan(0);+ f.apply({ kind: 'sphere', center: { x: 4, y: 16, z: 4 }, radius: 6 }, 'add');+ expect(f.distanceAt(4, 15.5, 4)).toBeGreaterThan(0);+ });++ it('carves a capsule along its length, and melts a smooth edge', () => {+ const f = make();+ f.apply({ kind: 'capsule', from: { x: 0, y: -6, z: 0 }, to: { x: 20, y: -6, z: 0 }, radius: 2 }, 'subtract');+ for (const x of [0, 7, 16, 20]) expect(f.distanceAt(x, -6, 0)).toBeGreaterThan(0);+ expect(f.distanceAt(26, -6, 0)).toBeLessThan(0);+ const sharp = make(), soft = make();+ sharp.apply({ kind: 'sphere', center: { x: 4, y: 0, z: 4 }, radius: 3 }, 'subtract');+ soft.apply({ kind: 'sphere', center: { x: 4, y: 0, z: 4 }, radius: 3 }, 'subtract', { smooth: 3 });+ expect(soft.distanceAt(7.6, -0.5, 4)).toBeGreaterThan(sharp.distanceAt(7.6, -0.5, 4));+ });+});++describe('the skin', () => {+ it('lies on the surface, faces out of the solid and is lit from there', () => {+ const f = make();+ const tris = world(f, 0, 0);+ expect(tris.length).toBeGreaterThan(0);+ for (const t of tris) {+ for (const v of t) {+ expect(v.y).toBeCloseTo(0, 1);+ expect(v.ny).toBeCloseTo(1, 2);+ }+ const [a, b, c] = t as [typeof t[0], typeof t[0], typeof t[0]];+ const ny = (b.z - a.z) * (c.x - a.x) - (b.x - a.x) * (c.z - a.z);+ expect(ny).toBeGreaterThan(0);+ }+ });++ it('has none where nothing passes', () => {+ const f = make();+ expect(f.chunk(0, 1, 0).surfaced).toBe(false);+ expect(skinOf(f, 0, 1, 0)).toBeNull();+ });++ it('closes across chunks, edited or not: no edge is left open inside', () => {+ const f = make(noiseVoxelSource({ seed: 3, surfaceHeight: 0, hillHeight: 6, hillScale: 14, caveWidth: 2, caveScale: 12, soilDepth: 3, oreAmount: 0.1 }));+ const inside = (x: number, z: number): boolean => x > 2 && x < 22 && z > 2 && z < 22;+ expect(openEdges(world(f, -1, 3), inside)).toBe(0);+ f.apply({ kind: 'sphere', center: { x: 8, y: 0, z: 8 }, radius: 5 }, 'subtract');+ f.apply({ kind: 'capsule', from: { x: 8, y: -2, z: 8 }, to: { x: 16, y: -4, z: 16 }, radius: 2 }, 'subtract');+ f.apply({ kind: 'box', center: { x: 16, y: 3, z: 8 }, halfExtents: { x: 3, y: 3, z: 3 } }, 'add', { material: 1 });+ expect(openEdges(world(f, -1, 3), inside)).toBe(0);+ });++ it('weighs a vertex by the materials of the corners round it', () => {+ const half: VoxelSource = (x, y, _z, out) => { out.distance = y; out.material = x < 4 ? 0 : 3; };+ const f = make(half);+ const s = skinOf(f, 0, -1, 0)!;+ const seen = new Set<string>();+ for (let v = 0; v < s.positions.length / 3; v++) {+ const w = [...s.weights.subarray(v * 4, v * 4 + 4)];+ expect(w[0]! + w[1]! + w[2]! + w[3]!).toBeGreaterThanOrEqual(254);+ seen.add(s.positions[v * 3]! < 3 ? 'left' : s.positions[v * 3]! > 4 ? 'right' : 'middle');+ if (s.positions[v * 3]! < 3) expect(w[0]).toBe(255);+ if (s.positions[v * 3]! > 4) expect(w[3]).toBe(255);+ }+ expect(seen.has('left') && seen.has('right')).toBe(true);+ });+});++describe('a ray', () => {+ it('stops at the surface from above, facing back up', () => {+ const hit = make().raycast({ x: 3, y: 10, z: 3 }, { x: 0, y: -5, z: 0 }, 40)!;+ expect(hit.point.y).toBeCloseTo(0, 1);+ expect(hit.distance).toBeCloseTo(10, 1);+ expect(hit.normal.y).toBeCloseTo(1, 1);+ expect(hit.material).toBe(2);+ });++ it('passes down a shaft that was dug, and finds its bottom', () => {+ const f = make();+ f.apply({ kind: 'capsule', from: { x: 3, y: 0, z: 3 }, to: { x: 3, y: -8, z: 3 }, radius: 2 }, 'subtract');+ expect(f.raycast({ x: 3, y: 5, z: 3 }, { x: 0, y: -1, z: 0 }, 40)!.point.y).toBeCloseTo(-10, 0);+ });++ it('finds nothing past its reach or pointing away, and starts inside at once', () => {+ const f = make();+ expect(f.raycast({ x: 3, y: 10, z: 3 }, { x: 0, y: -1, z: 0 }, 5)).toBeNull();+ expect(f.raycast({ x: 3, y: 10, z: 3 }, { x: 0, y: 1, z: 0 }, 5)).toBeNull();+ expect(f.raycast({ x: 3, y: -3, z: 3 }, { x: 0, y: 1, z: 0 }, 5)!.distance).toBe(0);+ });+});++describe('a save', () => {+ const dig = (f: VoxelField) => f.apply({ kind: 'sphere', center: { x: 4, y: -2, z: 4 }, radius: 3 }, 'subtract');++ it('holds only the chunks that were edited, and is small for what it holds', () => {+ const f = make();+ f.chunk(40, 0, 40);+ dig(f);+ const data = f.serialize();+ expect(Object.keys(data.chunks).length).toBe(f.held.edited);+ expect(data.chunks['40,0,40']).toBeUndefined();+ const raw = f.held.edited * 10 ** 3 * 2;+ expect(JSON.stringify(data).length).toBeLessThan(raw);+ });++ it('comes back through JSON to the same volume', () => {+ const a = make();+ dig(a);+ a.apply({ kind: 'box', center: { x: 4, y: 3, z: 4 }, halfExtents: { x: 1.5, y: 1.5, z: 1.5 } }, 'add', { material: 3 });+ const b = make();+ expect(b.restore(JSON.parse(JSON.stringify(a.serialize())) as VoxelFieldData)).toBe(true);+ for (const p of [[4, -2, 4], [4, 3, 4], [1, -2, 4], [7.5, -1, 4], [20, -1, 20]] as const) {+ expect(b.distanceAt(p[0], p[1], p[2])).toBe(a.distanceAt(p[0], p[1], p[2]));+ expect(b.materialAt(p[0], p[1], p[2])).toBe(a.materialAt(p[0], p[1], p[2]));+ }+ expect(b.held.edited).toBe(a.held.edited);+ const skinA = skinOf(a, 0, 0, 0)!, skinB = skinOf(b, 0, 0, 0)!;+ expect([...skinB.positions]).toEqual([...skinA.positions]);+ });++ it('can be taken chunk by chunk: only what changed since the last time', () => {+ const f = make();+ dig(f);+ expect(Object.keys(f.serialize(true).chunks).length).toBeGreaterThan(0);+ expect(Object.keys(f.serialize(true).chunks).length).toBe(0);+ f.apply({ kind: 'sphere', center: { x: 44, y: -2, z: 4 }, radius: 2 }, 'subtract');+ const next = Object.keys(f.serialize(true).chunks);+ expect(next.length).toBeGreaterThan(0);+ expect(next.every((k) => Number(k.split(',')[0]) >= 4)).toBe(true);+ expect(Object.keys(f.serialize().chunks).length).toBe(f.held.edited);+ });++ it('merges a part over what is there, and otherwise puts all back to the source', () => {+ const a = make();+ dig(a);+ const part = a.serialize();+ const b = make();+ b.apply({ kind: 'sphere', center: { x: 44, y: -2, z: 4 }, radius: 2 }, 'subtract');+ b.restore(part, true);+ expect(b.distanceAt(4, -2, 4)).toBeGreaterThan(0);+ expect(b.distanceAt(44, -2, 4)).toBeGreaterThan(0);+ b.restore(part);+ expect(b.distanceAt(4, -2, 4)).toBeGreaterThan(0);+ expect(b.distanceAt(44, -2, 4)).toBeLessThan(0);+ });++ it('refuses a save cut from another grid, and skips a chunk it cannot read', () => {+ const a = make();+ dig(a);+ const other = new VoxelField({ cellSize: 2, chunkCells: 8, minY: -16, maxY: 16, source: flat });+ expect(other.restore(a.serialize())).toBe(false);+ const data = a.serialize();+ const key = Object.keys(data.chunks)[0]!;+ data.chunks[key] = 'not a chunk!';+ data.chunks['a,b,c'] = 'AAAA';+ const skipped: string[] = [];+ const b = make();+ expect(b.restore(data, false, skipped)).toBe(true);+ expect(skipped.sort()).toEqual([key, 'a,b,c'].sort());+ });++ it('survives what it can make again being let go, and keeps what was dug', () => {+ const asked = { n: 0 };+ const counted: VoxelSource = (x, y, z, out) => { asked.n++; flat(x, y, z, out); };+ const f = make(counted, 2);+ dig(f);+ for (let x = 10; x < 20; x++) f.chunk(x, 0, 0);+ f.trim();+ expect(f.held.chunks).toBe(f.held.edited + 2);+ const before = asked.n;+ expect(f.distanceAt(4, -2, 4)).toBeGreaterThan(0);+ expect(asked.n).toBe(before);+ expect(f.distanceAt(100, -2, 4)).toBeLessThan(0);+ expect(asked.n).toBeGreaterThan(before);+ });+});++describe('the stock ground', () => {+ const source = noiseVoxelSource({ seed: 5, surfaceHeight: 0, hillHeight: 10, hillScale: 40, caveWidth: 3, caveScale: 30, soilDepth: 4, oreAmount: 0.1 });+ const probe = (x: number, y: number, z: number) => { const out = { distance: 0, material: 0 }; source(x, y, z, out); return out; };++ it('is the same each time it is asked, in any order', () => {+ const a = probe(13, -6, 7);+ probe(-40, 3, 90);+ expect(probe(13, -6, 7)).toEqual(a);+ });++ it('is air high up and solid soil just under its surface, and has rock and ore further down', () => {+ expect(probe(0, 40, 0).distance).toBeGreaterThan(0);+ let solid = 0, air = 0;+ const seen = new Set<number>();+ for (let x = 0; x < 80; x += 2) for (let z = 0; z < 80; z += 2) for (let y = -40; y < -6; y += 2) {+ const s = probe(x, y, z);+ if (s.distance < 0) { solid++; seen.add(s.material); } else air++;+ }+ expect(solid).toBeGreaterThan(air);+ expect(air).toBeGreaterThan(0);+ expect(seen.has(VoxelMaterial.Rock)).toBe(true);+ expect(seen.has(VoxelMaterial.Ore)).toBe(true);+ });+});++describe('a body under a height field', () => {+ it('is solid to the height and can be dug as a volume', () => {+ const f = make(heightVoxelSource((x) => x * 0.5));+ expect(f.distanceAt(4, 3, 4)).toBeGreaterThan(0);+ expect(f.distanceAt(4, 1, 4)).toBeLessThan(0);+ f.apply({ kind: 'sphere', center: { x: 4, y: 0, z: 4 }, radius: 1.5 }, 'subtract');+ expect(f.distanceAt(4, 0, 4)).toBeGreaterThan(0);+ });++ it('is air where it knows no height', () => {+ const f = make(heightVoxelSource((x) => (x < 100 ? 0 : null)));+ expect(f.distanceAt(200, -3, 0)).toBeGreaterThan(0);+ });+});diff --git a/sdk/tests/voxel-terrain-wasm.test.ts b/sdk/tests/voxel-terrain-wasm.test.tsnew file mode 100644index 000000000..e0cd4dd30--- /dev/null+++ b/sdk/tests/voxel-terrain-wasm.test.ts@@ -0,0 +1,275 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The real engine and the real 3D solver on ground that is a volume: what rests on it stays, what it is dug out from under falls,+ * a character walks into a tunnel that was just cut, and a save brings the hole back for the solver too.+ */+import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import { App } from '../src/app/app';+import { MeshRenderer, Parent, RuntimeOnly, Transform, type TransformData } from '../src/ecs/component';+import { setEditorMode, setPlayMode } from '../src/ecs/env';+import { Assets } from '../src/asset/AssetPlugin';+import type { Assets as AssetsApi } from '../src/asset/Assets';+import type { MeshData } from '../src/asset/meshFormat';+import { WorldStreamingSource } from '../src/residency/components';+import { Physics3DPlugin } from '../src/physics3d/Physics3DPlugin';+import { Physics3DRuntime } from '../src/physics3d/physics3dRuntime';+import { CapsuleCollider3D, CharacterController3D, RigidBody3D, SphereCollider3D } from '../src/physics3d/Physics3DComponents';+import { collisionGeometryOf } from '../src/runtime/collisionGeometry';+import { VoxelPlugin, VoxelTerrain, VoxelTerrainsRes, type VoxelTerrains } from '../src/voxel/voxelPlugin';+import type { VoxelSource } from '../src/voxel/field';+import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';+import type { Entity } from '../src/types';+import type { ESEngineModule } from '../src/wasm';+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';++const flat: VoxelSource = (_x, y, _z, out) => { out.distance = y; out.material = 2; };++let core: ESEngineModule;+const apps: App[] = [];+afterEach(() => {+ while (apps.length) apps.pop()!.quit?.();+ setEditorMode(false); setPlayMode(false);+});++interface Scene {+ app: App; world: App['world']; terrains: VoxelTerrains; volume: Entity;+ tick(n?: number): Promise<void>;+ meshes: Map<number, MeshData>;+ released: { n: number };+}++async function scene(options: { physics?: boolean; solver?: string; fields?: Record<string, unknown> } = {}): Promise<Scene> {+ core.setActiveContext(null);+ const app = App.new(); apps.push(app); app.connectCpp(new core.Registry(), core, { ownedRegistry: true });+ setPlayMode(true);+ if (options.physics !== false) {+ const module = await loadSideModule<Physics3DWasmModule>(options.solver ?? 'physics3d');+ app.addPlugin(new Physics3DPlugin('', { fixedTimestep: 1 / 60, pixelsPerUnit: 1 }, async () => module));+ await app.getResource(Physics3DRuntime).initPromise;+ }+ let next = 1;+ const meshes = new Map<number, MeshData>(), released = { n: 0 };+ app.insertResource(Assets, {+ createMesh: (data: MeshData) => { const h = next++; meshes.set(h, data); return h; },+ releaseBuiltMesh: (h: number) => { if (meshes.delete(h)) released.n++; },+ onInvalidate: () => () => {}, resolveLoadPath: (p: string) => p,+ } as unknown as AssetsApi);+ const source = app.world.spawn(); app.world.insert(source, Transform, {}); app.world.insert(source, WorldStreamingSource, {});+ app.addPlugin(new VoxelPlugin());+ const terrains = app.getResource(VoxelTerrainsRes);+ const volume = app.world.spawn('Ground');+ app.world.insert(volume, Transform, {});+ app.world.insert(volume, VoxelTerrain, { cellSize: 1, chunkCells: 12, minY: -24, maxY: 24, drawDistance: 30, collisionDistance: 20, material: 1, ...options.fields });+ terrains.setSource(volume, flat);+ const tick = async (n = 1): Promise<void> => { for (let i = 0; i < n; i++) { await app.tick(1 / 60); await Promise.resolve(); } };+ return { app, world: app.world, terrains, volume, tick, meshes, released };+}++function ball(s: Scene, x: number, y: number, z: number): Entity {+ const e = s.world.spawn('Ball');+ s.world.insert(e, Transform, { position: { x, y, z } });+ s.world.insert(e, RigidBody3D, { bodyType: 2 });+ s.world.insert(e, SphereCollider3D, { radius: 0.5 });+ return e;+}++const yOf = (s: Scene, e: Entity): number => (s.world.get(e, Transform) as TransformData).position.y;++describe.skipIf(!HAS_WASM)('ground that is a volume', () => {+ beforeAll(async () => { if (HAS_WASM) core = await loadWasmModule(); });++ describe.skipIf(!hasSideModule('physics3d'))('under the real solver', () => {+ it('holds what falls on it', async () => {+ const s = await scene();+ const b = ball(s, 3, 6, 3);+ await s.tick(180);+ expect(yOf(s, b)).toBeGreaterThan(0.3);+ expect(yOf(s, b)).toBeLessThan(0.8);+ });++ it('lets go of what it was dug out from under, even asleep', async () => {+ const s = await scene();+ const b = ball(s, 3, 3, 3);+ await s.tick(300);+ const rested = yOf(s, b);+ expect(rested).toBeLessThan(0.8);+ s.terrains.carve(s.volume, { kind: 'sphere', center: { x: 3, y: -1, z: 3 }, radius: 4 });+ await s.tick(120);+ expect(yOf(s, b)).toBeLessThan(rested - 2);+ expect(yOf(s, b)).toBeGreaterThan(-6);+ });++ it.skipIf(!hasSideModule('physics3d-physx'))('lets go of it on the other solver too', async () => {+ const s = await scene({ solver: 'physics3d-physx' });+ const b = ball(s, 3, 3, 3);+ await s.tick(300);+ const rested = yOf(s, b);+ expect(rested).toBeLessThan(0.8);+ s.terrains.carve(s.volume, { kind: 'sphere', center: { x: 3, y: -1, z: 3 }, radius: 4 });+ await s.tick(120);+ expect(yOf(s, b)).toBeLessThan(rested - 2);+ });++ it('stops a character at a wall until a tunnel is cut through it', async () => {+ const s = await scene({ fields: { collisionDistance: 30 } });+ s.terrains.fill(s.volume, { kind: 'box', center: { x: 8, y: 6, z: 3 }, halfExtents: { x: 2, y: 6, z: 8 } }, 2);+ const c = s.world.spawn('Walker');+ s.world.insert(c, Transform, { position: { x: 0, y: 1.2, z: 3 } });+ s.world.insert(c, CapsuleCollider3D, { radius: 0.4, halfHeight: 0.5 });+ s.world.insert(c, CharacterController3D, {});+ await s.tick(20);+ const walk = async (frames: number): Promise<void> => {+ for (let i = 0; i < frames; i++) {+ s.world.update(c, CharacterController3D, (d: { velocity: { x: number; y: number; z: number } }) => { d.velocity = { x: 4, y: d.velocity?.y ?? 0, z: 0 }; });+ await s.tick(1);+ }+ };+ const xOf = (): number => (s.world.get(c, Transform) as TransformData).position.x;+ await walk(120);+ expect(xOf()).toBeLessThan(6);+ expect(xOf()).toBeGreaterThan(4);+ s.terrains.carve(s.volume, { kind: 'capsule', from: { x: 3, y: 1.6, z: 3 }, to: { x: 14, y: 1.6, z: 3 }, radius: 1.5 });+ await s.tick(3);+ await walk(120);+ expect(xOf()).toBeGreaterThan(10.5);+ });++ it('falls through a hole, and stands on what is put back', async () => {+ const s = await scene();+ s.terrains.carve(s.volume, { kind: 'capsule', from: { x: 3, y: 2, z: 3 }, to: { x: 3, y: -10, z: 3 }, radius: 2.5 });+ await s.tick(2);+ const b = ball(s, 3, 4, 3);+ await s.tick(180);+ expect(yOf(s, b)).toBeLessThan(-10);+ s.terrains.fill(s.volume, { kind: 'capsule', from: { x: 3, y: 0, z: 3 }, to: { x: 3, y: -8, z: 3 }, radius: 3 });+ await s.tick(2);+ const c = ball(s, 3, 4, 3);+ await s.tick(180);+ expect(yOf(s, c)).toBeGreaterThan(-1);+ });++ it('keeps a hole across the border of chunks: nothing is left to stop a fall', async () => {+ const s = await scene();+ s.terrains.carve(s.volume, { kind: 'capsule', from: { x: 12, y: 2, z: 12 }, to: { x: 12, y: -10, z: 12 }, radius: 3 });+ await s.tick(2);+ const b = ball(s, 12, 4, 12);+ await s.tick(180);+ expect(yOf(s, b)).toBeLessThan(-10);+ });++ it('brings a saved hole back for the solver too', async () => {+ const a = await scene();+ a.terrains.carve(a.volume, { kind: 'capsule', from: { x: 3, y: 2, z: 3 }, to: { x: 3, y: -10, z: 3 }, radius: 2.5 });+ const save = JSON.parse(JSON.stringify(a.terrains.serialize(a.volume)));+ const b = await scene();+ await b.tick(2);+ expect(b.terrains.restore(b.volume, save)).toBe(true);+ await b.tick(10);+ const e = ball(b, 3, 4, 3);+ await b.tick(180);+ expect(yOf(b, e)).toBeLessThan(-10);+ });++ it('changes the ground under what stands on it when a save is put back', async () => {+ const a = await scene();+ a.terrains.carve(a.volume, { kind: 'capsule', from: { x: 3, y: 2, z: 3 }, to: { x: 3, y: -10, z: 3 }, radius: 2.5 });+ const save = JSON.parse(JSON.stringify(a.terrains.serialize(a.volume)));+ const b = await scene();+ const e = ball(b, 3, 3, 3);+ await b.tick(180);+ const rested = yOf(b, e);+ expect(rested).toBeLessThan(0.8);+ expect(b.terrains.restore(b.volume, save)).toBe(true);+ await b.tick(120);+ expect(yOf(b, e)).toBeLessThan(rested - 3);+ });++ it('builds collision only round what moves, and lets it go', async () => {+ const s = await scene();+ await s.tick(5);+ expect(collisionGeometryOf(s.app).size).toBe(0);+ const b = ball(s, 3, 2, 3);+ await s.tick(20);+ const near = collisionGeometryOf(s.app).size;+ expect(near).toBeGreaterThan(0);+ expect(s.terrains.collisionReadyAt(s.volume, 3, 3)).toBe(true);+ expect(s.terrains.collisionReadyAt(s.volume, 400, 3)).toBe(false);+ s.world.despawn(b);+ await s.tick(5);+ expect(collisionGeometryOf(s.app).size).toBe(0);+ });+ });++ describe('drawn', () => {+ const drawnOf = (s: Scene): Entity[] => [...s.world.getEntitiesWithComponents([RuntimeOnly, MeshRenderer])];++ it('is an entity a chunk, under the volume, that a saved scene does not hold', async () => {+ const s = await scene({ physics: false });+ await s.tick(30);+ const chunks = drawnOf(s);+ expect(chunks.length).toBeGreaterThan(4);+ for (const e of chunks) {+ expect((s.world.get(e, Parent) as { entity: Entity }).entity).toBe(s.volume);+ const r = s.world.get(e, MeshRenderer) as { mesh: number; material: number; cullBackfaces: boolean };+ expect(s.meshes.has(r.mesh)).toBe(true);+ expect(r.material).toBe(1);+ expect(r.cullBackfaces).toBe(true);+ }+ });++ it('makes again only the chunks an edit reached', async () => {+ const s = await scene({ physics: false });+ await s.tick(30);+ const before = new Map(drawnOf(s).map((e) => [e, (s.world.get(e, MeshRenderer) as { mesh: number }).mesh]));+ const dug = s.terrains.carve(s.volume, { kind: 'sphere', center: { x: 6, y: -3, z: 6 }, radius: 2 })!;+ expect(dug.removed[2]!).toBeGreaterThan(20);+ await s.tick(1);+ const changed = drawnOf(s).filter((e) => before.get(e) !== (s.world.get(e, MeshRenderer) as { mesh: number }).mesh).length;+ expect(changed).toBeGreaterThan(0);+ expect(changed).toBeLessThanOrEqual(dug.chunks);+ expect(changed).toBeLessThan(before.size / 2);+ expect(s.terrains.status(s.volume)!.waitingChunks).toBe(0);+ });++ it('gives back the meshes it replaces and those it lets go', async () => {+ const s = await scene({ physics: false });+ await s.tick(30);+ const held = s.meshes.size;+ for (let i = 0; i < 20; i++) {+ s.terrains.carve(s.volume, { kind: 'sphere', center: { x: 6, y: -3, z: 6 }, radius: 2 + i * 0.1 });+ await s.tick(1);+ }+ expect(s.meshes.size).toBeLessThan(held + 12);+ s.world.remove(s.volume, VoxelTerrain);+ await s.tick(2);+ expect(s.meshes.size).toBe(0);+ expect(drawnOf(s).length).toBe(0);+ });++ it('keeps what was dug when it is moved, and hears of every edit that changed something', async () => {+ const s = await scene({ physics: false });+ await s.tick(5);+ const heard: number[] = [];+ const stop = s.terrains.onEdit((e) => heard.push(e.result.chunks));+ s.terrains.carve(s.volume, { kind: 'sphere', center: { x: 3, y: -4, z: 3 }, radius: 2 });+ s.terrains.carve(s.volume, { kind: 'sphere', center: { x: 3, y: 40, z: 3 }, radius: 1 });+ expect(heard.length).toBe(1);+ stop();+ s.world.update(s.volume, Transform, (t) => { t.position.x = 100; });+ await s.tick(2);+ expect(s.terrains.distanceAt(s.volume, { x: 103, y: -4, z: 3 })).toBeGreaterThan(0);+ expect(s.terrains.distanceAt(s.volume, { x: 3, y: -4, z: 3 })).toBeLessThan(0);+ });++ it('answers a ray in the world, wherever the volume stands', async () => {+ const s = await scene({ physics: false });+ s.world.update(s.volume, Transform, (t) => { t.position.y = 10; });+ await s.tick(2);+ const hit = s.terrains.raycast({ x: 3, y: 30, z: 3 }, { x: 0, y: -1, z: 0 })!;+ expect(hit.point.y).toBeCloseTo(10, 1);+ expect(hit.entity).toBe(s.volume);+ expect(s.terrains.materialAt(s.volume, { x: 3, y: 8, z: 3 })).toBe(2);+ });+ });+});diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjsindex 7ebe5c7c8..f9cb9132b 100644--- a/tools/apiSubsystems.mjs+++ b/tools/apiSubsystems.mjs@@ -325,6 +325,16 @@ export const SUBSYSTEMS = [whyZh: '地面和上面的植物在编辑器里两个后端都能画出来并有检查,但还没有东西和地面碰撞,创作面板也还没有被拿来定下这套接口的形状',entry: ['Terrain', 'Foliage'],},+ {+ id: 'voxel',+ title: 'Voxel terrain',+ titleZh: '体积地形',+ source: ['voxel'],+ tier: 'experimental',+ why: 'carving, the skin, collision and saves are checked against the real solver and on both backends, but it has no levels of detail or editor brush, and nothing has been measured on a device',+ whyZh: '开挖、网格、碰撞和存档都用真实求解器和两个后端检查过,但还没有 LOD 和编辑器笔刷,也没有在真机上测过',+ entry: ['VoxelTerrain', 'VoxelTerrains'],+ },{id: 'spline',title: 'Splines',diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjsindex 2046cc999..2a623041b 100644--- a/tools/check-corpus-authoring.mjs+++ b/tools/check-corpus-authoring.mjs@@ -125,6 +125,7 @@ const DISPOSITION = {Planet: ['owed', 'authored by a game today (star-neighbors, a round planet from its own generator); an example that registers a planet provider is owed'],MeshInstances: ['derived', 'the foliage and world generation systems write it, one entity a kind and part of a cell; its places are data a system computes, not something a scene authors'],ParticleCollider: ['owed', 'no example has a GPU emitter bouncing off a shape yet; the particle-gpu scenes are where the first one goes'],+ VoxelTerrain: ['owed', 'no example digs in a volume yet; a small mine is where the first one goes'],RoadDecal: ['owed', 'no example lays a road over a terrain yet; wilds is where the first one goes'],PlantProxy: ['derived', 'the plant interaction makes it for a plant near a contact, and takes it away again; a scene never holds one'],FoliageContact: ['owed', 'no example has a character walking through plants yet; wilds gains one when it gets a player'],diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjsindex 970545bc6..cbbb33e30 100644--- a/tools/check-gizmo-coverage.mjs+++ b/tools/check-gizmo-coverage.mjs@@ -202,6 +202,13 @@ const DISPOSITION = {'CharacterController2D.skinWidth': ['no-place', 'a contact skin held off the collider; drawn, it is that outline\'s own line width'],'CharacterController2D.stepHeight': ['no-place', 'the highest ledge it walks up: a limit on motion, not a volume'],'FoliageContact.radius': ['no-place', 'how far plants lean from it, seen on the plants themselves; a ring drawn for it would sit under the grass'],+ 'VoxelTerrain.cellSize': ['no-place', 'the side of a cell of the volume, seen in the skin it makes, not a region of the entity'],+ 'VoxelTerrain.drawDistance': ['no-place', 'how far from the eye the volume is drawn, not a region of the entity'],+ 'VoxelTerrain.collisionDistance': ['no-place', 'how far round each moving body the volume is built for collision, not a region of the entity'],+ 'VoxelTerrain.surfaceHeight': ['renders', 'where the stock ground lies: the ground drawn is its picture'],+ 'VoxelTerrain.hillHeight': ['renders', 'how far its hills rise and fall: the hills drawn are their picture'],+ 'VoxelTerrain.caveWidth': ['renders', 'how wide its tunnels are: the tunnels drawn are their picture'],+ 'VoxelTerrain.soilDepth': ['renders', 'how deep its soil goes: seen in the material of the ground drawn'],'RoadDecal.widthScale': ['no-place', 'a multiplier on the widths its Spline already draws, and the strip it lays shows the result'],'CharacterController3D.stepHeight': ['no-place', 'the tallest step it will climb — a limit on motion, not a volume'],'NavVolume.cellSize': ['no-place', 'the voxel the box is diced into; the box is what has a place'],diff --git a/tools/lib/sdkProgram.mjs b/tools/lib/sdkProgram.mjsindex b515f88da..79700f4ec 100644--- a/tools/lib/sdkProgram.mjs+++ b/tools/lib/sdkProgram.mjs@@ -68,6 +68,7 @@ export const ENTRIES = {'worldgen': 'src/worldgen/index.ts','water': 'src/water/index.ts','spline': 'src/spline/index.ts',+ 'voxel': 'src/voxel/index.ts','rig2d': 'src/rig2d/index.ts','imported-scene': 'src/imported-scene/index.ts','character-shaders': 'src/character/index.ts',diff --git a/tools/nativeScriptModules.js b/tools/nativeScriptModules.jsindex 20509534c..90c9532d6 100644--- a/tools/nativeScriptModules.js+++ b/tools/nativeScriptModules.js@@ -74,6 +74,7 @@ export const MODULES = {'esengine/worldgen': { disposition: 'native-subpath' },'esengine/water': { disposition: 'native-subpath' },'esengine/spline': { disposition: 'native-subpath' },+ 'esengine/voxel': { disposition: 'native-subpath' },'esengine/rig2d': { disposition: 'native-subpath' },'esengine/imported-scene': { disposition: 'native-subpath' },'esengine/character-shaders': { disposition: 'native-subpath' },diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 3b07eab75..7e4765f4a 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4232,6 +4232,8 @@ export const NOTED = {{"note": "Particles and plain sprites in a Canvas paint by their place in its tree."},"fix(text): stopping lets go of the labels the engine holds, so the next Play cannot draw them on other entities":{"note": "Labels no longer come back as black boxes after a change between Plays."},+ "feat(voxel): ground that is a volume, carved while the game runs, with collision that follows and saves by chunk":+ {"note": "Ground that is a volume."},"feat(terrain): a material that fades into the ground it meets, a road laid over a terrain, and snow on whatever faces the sky":{"note": "What stands on the ground can blend into it."},"fix(assets): one hot load at a time per asset, so two rescans cannot lose a texture":