Skip to content

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

feat(nav): a 3D scene is navigated on a polygon mesh, not a heightfield

esenginee41fc111e42c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 65f309731..a89db6bfe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -106,13 +106,14 @@ published separately; it ships inside the editor.
views one particle from the side: a quad fixed in the x/y plane is edge-on there
and covers nothing.
-- **The navigation grid can be seen in the running game.** `NavDebugDraw` outlines
- the walkable cells at the height of their own ground and marks the pairs the
- step limit refuses — the only thing that explains a route going the long way
- round, since both sides of a ledge are walkable cells. Until now `cellSize`,
- `maxSlopeDegrees` and `agentHeight` were tuned by watching whether an agent
- happened to move. Off by default, and capped at a few thousand cells: an overlay
- that stops the game is not a diagnostic.
+- **What a scene can be navigated over can be seen in the running game.**
+ `NavDebugDraw` outlines every walkable face where it actually is — at the height
+ of the ground for a mesh, in the scene's own plane for a grid — and marks in red
+ every edge the walkable world stops at, which is the only thing that explains a
+ route going the long way round. Until now `cellSize`, `agentRadius` and
+ `agentHeight` were tuned by watching whether an agent happened to move. One
+ drawer for both kinds of surface, off by default, and capped at a few thousand
+ faces: an overlay that stops the game is not a diagnostic.
- **A draw overlay does not throw a frame on a core that cannot draw.** Plugins
register their overlays when they are built, whether or not one is ever turned
@@ -137,38 +138,52 @@ published separately; it ships inside the editor.
shape and does not draw it.
- **A 3D scene authors where its agents may walk.** `NavVolume` is a box on an
- entity; the nav plugin bakes the grid inside it out of the running 3D world and
- installs it, so navigation is authored in the scene rather than written by every
- game. It waits for the solver to create its bodies first — the queries resource
- exists as soon as the module loads, and a bake against a world with no bodies in
- it returns a grid of holes that one-bake-per-volume would never revisit. A volume
- that finds no walkable ground says so in the log instead of leaving agents
- standing still for no stated reason. New editor check `nav3d-play` walks an agent
- round a wall in the running game, which is the only place the side module, the
- plugin and the bodies all exist at once.
-
-- **A navigation grid can be baked out of the 3D solver.** `bakeNavGrid` casts one
- ray straight down per cell and reads three answers off it: whether there is
- ground, how high it is, and how steeply it is tilted. No hit is a hole, ground
- steeper than `maxSlopeDegrees` is a wall, and a ceiling closer than
- `agentHeight` is a crawlspace. The bodies a scene already collides against are
- the source, so the walkable surface cannot disagree with the one an agent
- stands on. It takes a `GroundProbe` — an interface small enough that
- `Physics3DQueries` satisfies it unchanged, and a test satisfies it with a
- function. One surface per column: a bridge and the road under it collapse into
- whichever the ray meets first, which is the whole of what a heightfield can
- honestly answer.
-
-- **Navigation plans and walks in three dimensions.** `NavGrid` now knows which
- world plane its cells lie in — `xy` (a flat scene, the default and unchanged) or
- `xz`, the ground of a spatial one, where each cell also carries the height of
- the ground there. A* honours a `stepHeight`, so a kerb is a route and a ledge of
- the same width is not, and a route that ends up cut in two reports no path
- rather than one that walks through a wall. Paths, `NavAgent` (`targetZ`) and the
- kinematic follower are three-dimensional throughout — a slope is longer than its
- shadow, and spending a frame's budget on the shadow walked agents uphill faster
- than along the flat. One grid class rather than two: a second would be this one
- with two axes renamed.
+ entity; the nav plugin bakes the navmesh inside it out of the scene's own
+ collision geometry and installs it, so navigation is authored in the scene rather
+ than written by every game. Its fields are all facts about the agent or about how
+ finely the world is measured — `cellSize`, `cellHeight`, `agentHeight`,
+ `agentRadius`, `stepHeight`, `maxSlopeDegrees`, `layers` — never about the route,
+ which is what the bake works out from them. Only STATIC bodies count: a crate
+ about to be pushed is not floor. A volume that finds no walkable ground says so
+ in the log instead of leaving agents standing still for no stated reason, and one
+ too big to voxelise at its own `cellSize` says that rather than freezing. New
+ editor check `nav3d-play` walks an agent round a wall in the running game and
+ reads the two floors of a column it never walks on.
+
+- **A 3D scene's navigation is a real navmesh.** `buildNavMesh` voxelises the
+ scene's collision triangles into a solid heightfield, keeps the surfaces an agent
+ of a given size could stand on, and turns what is left into convex polygons that
+ know their neighbours — the Recast pipeline, in TypeScript beside the grid A\*
+ rather than through a second wasm module. Every column of the world keeps **all**
+ of its floors, so a bridge and the road under it are two places and an agent can
+ be on either; a route is planned polygon to polygon and then pulled taut through
+ the doorways it crosses, so crossing an open floor is one straight line rather
+ than a staircase of cells. Four things can take ground away and each is asked for
+ the one answer only it has: too steep, no headroom, on the lip of a drop, or
+ closer to a wall than the agent is wide. `agentRadius` is baked in rather than
+ applied per query — the mesh *is* the set of places a body that wide may stand,
+ which is why a route over one is already clear of the walls.
+
+ `collectNavGeometry` gathers the triangles from the collider components the
+ editor gizmo and the physics overlay already read, so a mesh cannot be baked from
+ a shape nobody can see, and a mesh collider contributes its own triangles rather
+ than the box around them. Nothing waits for the solver any more: the geometry is
+ in the scene from the first frame.
+
+- **Navigation plans and walks in three dimensions.** Paths, `NavAgent`
+ (`targetZ`) and the kinematic follower carry all three axes — a slope is longer
+ than its shadow, and spending a frame's budget on the shadow walked agents uphill
+ faster than along the flat.
+
+ **Breaking.** There is now one interface, `NavSurface`, and two shapes behind it:
+ `NavGrid` for a world that already IS cells (a tilemap, and the only one a game
+ can flip a cell of while it runs) and `NavMesh` for a world made of geometry.
+ `Navigation.grid` / `setGrid` / `hasGrid` are `surface` / `setSurface` /
+ `hasSurface`, and the agent, the overlay and `findWorldPath` never learn which
+ kind they were handed. `NavGrid` is a flat grid again — `plane`, `surface`,
+ `stepHeight` and `canStep` are gone with the ray-cast heightfield they were added
+ for, which the navmesh answers everything of and more. `NavDebugDraw`'s
+ `showCells` / `showLedges` are `showFaces` / `showBorders`.
- **AI sensing is three-dimensional.** A `Perceiver`'s range came from x and y,
its cone from `atan2` in the same plane, and its facing from the Z half of a
diff --git a/desktop b/desktop
index f4e4279f9..c83b72384 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit f4e4279f9e191b4441615f5d0afe713fcb9b37a9
+Subproject commit c83b723844d70defd8e0f52a8f13b87cdceb34f4
diff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
index f66195645..799458abb 100644
--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
@@ -1,23 +1,29 @@
---
title: Navigation
-description: "A navigation grid and A* pathfinding — building the grid, and moving a NavAgent to any world point with replanning."
+description: "Two shapes of navigable world — a grid for cells, a baked polygon mesh for geometry — and moving a NavAgent over either."
---
import { Aside } from '@astrojs/starlight/components';
-Navigation moves an agent to a world point along a route that avoids blocked cells,
-using A\* over a **`NavGrid`**.
+Navigation moves an agent to a world point along a route that goes round whatever
+is in the way. The route is planned over the **`Nav`** resource's active *surface*,
+and there are two of them:
-### Building a grid
+- **`NavGrid`** — a rectangular mask of walkable and blocked cells. What a tilemap
+ already is, and the one you can flip a cell of while the game runs.
+- **`NavMesh`** — convex polygons **baked** out of a scene's own collision geometry.
+ It follows sloped and stacked ground, which no single grid can.
+
+Everything above them — the agent, the overlay, `nav.findWorldPath` — asks the same
+questions of either, so nothing in a game has to know which one it was handed.
-A `NavGrid` is a rectangular grid of walkable/blocked cells. Install it on the `Nav`
-resource so agents can path against it:
+### Building a grid
```typescript
import { defineSystem, Res, Nav, NavGrid } from 'esengine';
export const setupNav = defineSystem([Res(Nav)], (nav) => {
- nav.setGrid(new NavGrid({
+ nav.setSurface(new NavGrid({
width: 60, // columns
height: 44, // rows
cellSize: 20, // world pixels per cell
@@ -31,46 +37,55 @@ export const setupNav = defineSystem([Res(Nav)], (nav) => {
| `width` | number | Cell columns. |
| `height` | number | Cell rows. |
| `cellSize` | number | World pixels per cell (square). |
-| `origin` | `Vec2` | World position of cell `(0,0)`'s center. Defaults to `(0,0)`. |
+| `origin` | `Vec3` | World position of cell `(0,0)`'s center. Its `z` is the depth every waypoint comes back at. Defaults to `(0,0,0)`. |
| `walkable` | `Uint8Array` | Optional row-major `width*height` mask, `1` = walkable, `0` = blocked. Omitted → all walkable. |
-| `plane` | `'xy' \| 'xz'` | Which world plane the cells lie in. `xy` (the default) is a flat scene's own plane; `xz` is the ground of a 3D one. |
-| `surface` | `Float32Array` | Ground height per cell, on the axis the plane leaves out. Omitted → every cell sits at the origin's third axis. |
-| `stepHeight` | number | Height difference between neighbours an agent can climb. `0` (the default) lets any difference through. |
To derive a grid from a painted tilemap instead of hand-authoring the mask, use
`navGridFromTilemapLayer` (which cells a layer's solid tiles block) or
-`navGridFromTiles`.
+`navGridFromTiles`. `grid.setWalkable(x, y, false)` closes a cell at any time — a
+door shuts, a tower goes up — and the next plan routes around it.
-### A grid for a 3D scene
+### A mesh for a 3D scene
-A 3D scene has geometry rather than a tile mask, so its grid is **baked** from the
-bodies it already collides against — put a **`NavVolume`** on an entity and the nav
-plugin fills the box it describes:
+A 3D scene has geometry rather than a tile mask, so its surface is **baked** from
+the bodies it already collides against. Put a **`NavVolume`** on an entity and the
+nav plugin fills the box it describes:
-| `NavVolume` field | Description |
-|---|---|
-| `halfExtents` | Half the box to sample, in world pixels; the entity's Transform is its centre. |
-| `cellSize` | World pixels per cell. Smaller is a finer route and a slower bake. |
-| `maxSlopeDegrees` | Steepest ground an agent can stand on. Anything steeper is a wall. |
-| `agentHeight` | Headroom an agent needs — a cell with less is a crawlspace, not a corridor. `0` skips the check. |
-| `stepHeight` | How high a step the agent can climb between neighbouring cells. |
-| `layers` | Physics layers the ground rays are cast against; `0` = every layer. |
+| `NavVolume` field | Default | Description |
+|---|---|---|
+| `halfExtents` | `1000, 500, 1000` | Half the box to bake, in world pixels; the entity's Transform is its centre. |
+| `cellSize` | `50` | Voxel size in the ground plane. Smaller hugs the geometry more closely and bakes more slowly. |
+| `cellHeight` | `10` | Voxel size vertically — what decides whether a balcony and the floor under it are two levels or one. |
+| `maxSlopeDegrees` | `45` | Steepest ground an agent can stand on. Anything steeper is a wall. |
+| `agentHeight` | `180` | Headroom an agent needs. Ground with less is a crawlspace, not a corridor. |
+| `agentRadius` | `30` | How wide the agent is. The mesh is pulled back from every wall by this. |
+| `stepHeight` | `40` | How high a step the agent can climb rather than walk round. |
+| `layers` | `0` | Physics layers the ground is taken from; `0` = every layer. |
+
+The bake voxelises the collision triangles in the box, keeps the surfaces an agent
+of that size could stand on, and turns what is left into convex polygons. Every
+column of the world keeps **all** of its floors, so a bridge and the road under it
+are two places and a route can use either.
+
+<Aside type="note">
+ **Static bodies only.** A crate that is about to be pushed is not floor, and a
+ mesh baked over one would describe the world for exactly as long as nobody
+ touched it. Give anything that should be walked on (or walked round) a
+ `RigidBody3D` with its body type set to **Static**.
+</Aside>
-One ray straight down per cell answers all of it: no hit is a hole, a tilted hit is
-a slope or a wall, and a hit with a ceiling too close above it is unwalkable. The
-bake waits for the 3D solver to create its bodies, so the grid appears a frame or
-two into play, not at load.
+Each volume is baked once, on the first frame its geometry is available — a mesh
+collider contributes nothing until its asset has loaded, so the bake waits for it.
+`buildNavMesh(verts, indices, options)` is callable directly if a game wants to bake
+on its own terms, and `collectNavGeometry(world, box)` is what gathers the triangles.
<Aside type="caution">
- **One surface per column.** A bridge and the road under it collapse into whichever
- the ray meets first — the top of a wall becomes perfectly good ground two metres
- up, and it is `stepHeight` (not walkability) that keeps agents off it. Multi-level
- routing needs a real navmesh, which this is not.
+ **One agent size per mesh.** `agentRadius` is baked in, not applied per query: the
+ mesh *is* the set of places a body that wide may stand. A `NavAgent` wider than
+ the volume it walks on is routed as if it were the narrower one, and says so once
+ in the log.
</Aside>
-`bakeNavGrid` is also callable directly if a game wants to bake on its own terms;
-it takes any object with a `raycast`, which the `Physics3D` resource already is.
-
### Seeing what was baked
The volume's wireframe says where the bake looked. To see what it **found**, turn
@@ -80,11 +95,12 @@ on the `NavDebugDraw` resource in the running game:
app.getResource(NavDebugDraw).enabled = true;
```
-Walkable cells are outlined at the height of their own ground, and the pairs the
-step limit refuses are marked in red — the only thing that explains a route going
-the long way round, since both sides of a ledge are walkable cells. Off by default
-(a grid is thousands of quads a frame), and it stops after a few thousand cells:
-`cellSize` is the knob for seeing more of a big world.
+Every walkable face is outlined where it actually is — at the height of the ground
+for a mesh, in the scene's own plane for a grid — and every edge the walkable world
+**stops** at is marked in red. Those edges are the only thing that explains a route
+going the long way round. Off by default (a surface is thousands of loops a frame),
+and it stops after a few thousand faces: `cellSize` is the knob for seeing more of a
+big world.
<Aside type="tip">
The `Nav` resource also answers one-off queries directly:
@@ -113,11 +129,11 @@ stopNavAgent(world, entity);
| `NavAgent` field | Default | Description |
|---|---|---|
| `speed` | `120` | Movement speed in world pixels per second. |
-| `radius` | `0` | How wide the body is, in pixels. Planning routes it around anything it would not fit through; `0` routes it as a point. |
+| `radius` | `0` | How wide the body is, in pixels. On a grid, planning routes it around anything it would not fit through; on a mesh this is the volume's `agentRadius` instead. |
| `arriveRadius` | `6` | Stop distance from the final goal. |
| `repathInterval` | `0.5` | Seconds between replans while moving; `0` = replan only when the target changes. |
| `hasTarget` | `false` | Whether a destination is set (managed for you). |
-| `targetX`, `targetY` | `0` | Current destination in world pixels. |
+| `targetX`, `targetY`, `targetZ` | `0` | Current destination in world pixels. |
| `arrived` | `false` | Set true the frame the agent reaches its goal. |
`setNavDestination` is safe to call every frame to chase a moving target — the agent
@@ -126,12 +142,15 @@ only replans when the target actually moves or `repathInterval` elapses. Read
## Agents have width
-Set `radius` to the body's actual half-width and planning keeps it out of gaps
-it cannot fit through. Left at `0` an agent is routed as a point, which is what
-you want for something that has no collider — and what produces the classic
+On a **grid**, set `radius` to the body's actual half-width and planning keeps it
+out of gaps it cannot fit through. Left at `0` an agent is routed as a point, which
+is what you want for something that has no collider — and what produces the classic
sight of an enemy walking confidently into a doorway and stopping there, because
-the cell it was routed to is walkable and the half of it hanging over the next
-one is not.
+the cell it was routed to is walkable and the half of it hanging over the next one
+is not.
+
+On a **mesh** the same thing is settled at bake time by `agentRadius`, which is why
+a route over one is already clear of the walls with nothing asked of the planner.
-A goal the body cannot stand on (a pickup in a corner) is still reached: the
-plan ends as close as the body fits, and `arriveRadius` covers the rest.
+A goal the body cannot stand on (a pickup in a corner) is still reached either way:
+the plan ends as close as the body fits, and `arriveRadius` covers the rest.
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx
index 5be69e39f..6c0162eae 100644
--- a/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx
@@ -1,22 +1,28 @@
---
title: 导航
-description: "导航网格与 A* 寻路——构建网格,以及把 NavAgent 移动到任意世界坐标并随目标重规划。"
+description: "两种可走世界的形态——格子给瓦片,烘焙出来的多边形网格给几何——以及在任意一种上移动 NavAgent。"
---
import { Aside } from '@astrojs/starlight/components';
-导航沿着一条避开被阻挡格子的路线,把 agent 移动到某个世界坐标,底层用 A\* 在一个 **`NavGrid`**
-上寻路。
+导航把 agent 沿着一条绕开所有障碍的路线送到某个世界坐标。路线是在 **`Nav`** 资源当前的
+*surface* 上规划的,而 surface 有两种:
-### 构建网格
+- **`NavGrid`** —— 由可走/阻挡格子构成的矩形掩码。瓦片地图本来就是这个形状,而且它是唯一
+ 能在游戏运行时改一格的。
+- **`NavMesh`** —— 从场景自己的碰撞几何**烘焙**出来的凸多边形。它能跟着倾斜和堆叠的地面走,
+ 这是任何单张网格都做不到的。
+
+它们之上的一切——agent、调试叠加层、`nav.findWorldPath`——对两者问的是同样的问题,所以
+游戏里没有任何地方需要知道自己拿到的是哪一种。
-`NavGrid` 是一个由可走/被阻挡格子构成的矩形网格。把它装到 `Nav` 资源上,agent 才能对它寻路:
+### 构建网格
```typescript
import { defineSystem, Res, Nav, NavGrid } from 'esengine';
export const setupNav = defineSystem([Res(Nav)], (nav) => {
- nav.setGrid(new NavGrid({
+ nav.setSurface(new NavGrid({
width: 60, // 列数
height: 44, // 行数
cellSize: 20, // 每格的世界像素
@@ -30,41 +36,48 @@ export const setupNav = defineSystem([Res(Nav)], (nav) => {
| `width` | number | 格子列数。 |
| `height` | number | 格子行数。 |
| `cellSize` | number | 每格的世界像素(正方形)。 |
-| `origin` | `Vec2` | 格子 `(0,0)` 中心的世界坐标。默认 `(0,0)`。 |
+| `origin` | `Vec3` | 格子 `(0,0)` 中心的世界坐标。它的 `z` 就是每个路点返回时所在的深度。默认 `(0,0,0)`。 |
| `walkable` | `Uint8Array` | 可选的行主序 `width*height` 掩码,`1` = 可走,`0` = 阻挡。省略则全部可走。 |
-| `plane` | `'xy' \| 'xz'` | 格子躺在哪个世界平面上。`xy`(默认)是平面场景自己的平面;`xz` 是 3D 场景的地面。 |
-| `surface` | `Float32Array` | 每格地面的高度,在平面留出的那个轴上。省略则每格都位于原点的第三轴。 |
-| `stepHeight` | number | 相邻格之间 agent 能爬上去的高度差。`0`(默认)表示任何高差都放行。 |
若想从已绘制的瓦片地图推导网格,而不是手写掩码,用 `navGridFromTilemapLayer`(把某图层的
-实心瓦片视作阻挡)或 `navGridFromTiles`。
+实心瓦片视作阻挡)或 `navGridFromTiles`。`grid.setWalkable(x, y, false)` 随时可以关掉一格
+——门关上了、塔造起来了——下一次规划就会绕开它。
### 3D 场景的网格
-3D 场景有的是几何而不是瓦片掩码,所以它的网格是从**它本来就在碰撞的那些刚体**上**烘焙**出来的
-——在一个实体上放 **`NavVolume`**,导航插件就会把它描述的那个盒子填满:
+3D 场景有的是几何而不是瓦片掩码,所以它的 surface 是从**它本来就在碰撞的那些刚体**上
+**烘焙**出来的。在一个实体上放 **`NavVolume`**,导航插件就会把它描述的那个盒子填满:
-| `NavVolume` 字段 | 说明 |
-|---|---|
-| `halfExtents` | 要采样的盒子半尺寸,单位世界像素;实体的 Transform 是盒子中心。 |
-| `cellSize` | 每格的世界像素。越小路线越细、烘焙越慢。 |
-| `maxSlopeDegrees` | agent 能站住的最陡地面。比这更陡的就是墙。 |
-| `agentHeight` | agent 需要的头顶空间——不够的格子是爬行空间不是走廊。`0` 跳过这项检查。 |
-| `stepHeight` | 相邻格之间 agent 能爬上去的台阶高度。 |
-| `layers` | 地面射线投射的物理层;`0` = 所有层。 |
+| `NavVolume` 字段 | 默认 | 说明 |
+|---|---|---|
+| `halfExtents` | `1000, 500, 1000` | 要烘焙的盒子半尺寸,单位世界像素;实体的 Transform 是盒子中心。 |
+| `cellSize` | `50` | 地平面上的体素尺寸。越小越贴合几何,烘焙也越慢。 |
+| `cellHeight` | `10` | 垂直方向的体素尺寸——决定阳台和它下面的地板算两层还是一层的就是它。 |
+| `maxSlopeDegrees` | `45` | agent 能站住的最陡地面。比这更陡的就是墙。 |
+| `agentHeight` | `180` | agent 需要的头顶空间。不够的地面是爬行空间不是走廊。 |
+| `agentRadius` | `30` | agent 有多宽。网格会按这个尺寸从每一面墙上缩回来。 |
+| `stepHeight` | `40` | agent 能直接爬上去、而不必绕开的台阶高度。 |
+| `layers` | `0` | 地面取自哪些物理层;`0` = 所有层。 |
+
+烘焙把盒子里的碰撞三角面体素化,留下这个尺寸的 agent 站得住的那些面,再把剩下的变成凸多边形。
+世界的每一列都保留了它**全部**的楼层,所以桥和桥下的路是两个地方,路线两个都能用。
+
+<Aside type="note">
+ **只烘焙静态刚体。**一个马上要被推走的箱子不是地板,在它上面烘出来的网格只在没人碰它的
+ 这段时间里成立。任何应该被踩上去(或被绕开)的东西,都给它一个 body type 为 **Static**
+ 的 `RigidBody3D`。
+</Aside>
-每格一条向下的射线就回答了全部:没命中是洞,命中面倾斜就是坡或墙,命中点上方净空不够就不可走。
-烘焙会等 3D 求解器把刚体建出来,所以网格是在开始运行后一两帧出现的,不是加载时。
+每个体积只烘焙一次,在它的几何可用的第一帧——网格碰撞体在资产加载完之前贡献不了任何三角面,
+烘焙会等它。想按自己的方式烘焙的游戏可以直接调 `buildNavMesh(verts, indices, options)`,
+而 `collectNavGeometry(world, box)` 就是收集三角面的那一步。
<Aside type="caution">
- **每一列只有一个面。**桥和桥下的路会塌成射线先碰到的那一个——墙顶会变成两米高处一块
- 完全可站的地面,把 agent 挡在墙外的是 `stepHeight` 而不是可走性。多层路网需要真正的
- navmesh,这里不是。
+ **一张网格只对应一种 agent 尺寸。**`agentRadius` 是烘进去的,不是查询时才应用的:这张网格
+ **就是**那么宽的身体可以站的所有位置的集合。比所在体积更宽的 `NavAgent` 会按较窄的那个
+ 规划路线,并在日志里说一次。
</Aside>
-`bakeNavGrid` 也可以直接调用,让游戏按自己的方式烘焙;它只要一个带 `raycast` 的对象,
-而 `Physics3D` 资源本身就是。
-
### 看见烘出来的东西
体积的线框说的是烘焙**往哪看**。想看它**找到了什么**,在运行中的游戏里打开 `NavDebugDraw`:
@@ -73,9 +86,9 @@ export const setupNav = defineSystem([Res(Nav)], (nav) => {
app.getResource(NavDebugDraw).enabled = true;
```
-可走的格子按各自地面的高度描边,被台阶限制拒绝的相邻对标成红色——这是唯一能解释
-「路线为什么绕远」的东西,因为台沿两边都是可走的格子。默认关闭(一张网格是每帧几千个
-四边形),而且画到几千格就停:想看清更大的世界,调 `cellSize`。
+每个可走的面都画在它实际所在的位置——网格画在地面高度上,格子画在场景自己的平面上——而
+可走世界**终止**的每一条边都标成红色。那些边是唯一能解释「路线为什么绕远」的东西。默认关闭
+(一个 surface 是每帧几千个环),而且画到几千个面就停:想看清更大的世界,调 `cellSize`。
<Aside type="tip">
`Nav` 资源也能直接回答一次性查询:`nav.findWorldPath(from, to)` 返回一组世界空间路点
@@ -103,11 +116,11 @@ stopNavAgent(world, entity);
| `NavAgent` 字段 | 默认 | 说明 |
|---|---|---|
| `speed` | `120` | 移动速度(世界像素/秒)。 |
-| `radius` | `0` | 身体有多宽(像素)。寻路会绕开它挤不过去的地方;`0` 按质点寻路。 |
+| `radius` | `0` | 身体有多宽(像素)。在格子上,寻路会绕开它挤不过去的地方;在网格上,这件事由体积的 `agentRadius` 决定。 |
| `arriveRadius` | `6` | 距最终目标的停止距离。 |
| `repathInterval` | `0.5` | 移动中两次重规划的间隔秒数;`0` = 只在目标改变时重规划。 |
| `hasTarget` | `false` | 是否已设目的地(自动管理)。 |
-| `targetX`、`targetY` | `0` | 当前目的地(世界像素)。 |
+| `targetX`、`targetY`、`targetZ` | `0` | 当前目的地(世界像素)。 |
| `arrived` | `false` | agent 到达目标的那一帧被置真。 |
`setNavDestination` 每帧调用都安全,可用于追一个移动的目标——只有当目标真的移动、或
@@ -116,9 +129,12 @@ stopNavAgent(world, entity);
## agent 是有宽度的
-把 `radius` 设成身体的实际半宽,寻路就会绕开它挤不过去的缝隙。留在 `0` 表示按质点寻路——
-没有碰撞体的东西就该这样;而这也正是那个经典画面的成因:敌人信心十足地走进门洞然后
-永远停在那里,因为它被规划到的那一格是可走的,而挂在隔壁那一格上的半个身子不是。
+在**格子**上,把 `radius` 设成身体的实际半宽,寻路就会绕开它挤不过去的缝隙。留在 `0` 表示
+按质点寻路——没有碰撞体的东西就该这样;而这也正是那个经典画面的成因:敌人信心十足地走进
+门洞然后永远停在那里,因为它被规划到的那一格是可走的,而挂在隔壁那一格上的半个身子不是。
+
+在**网格**上,同一件事在烘焙时就由 `agentRadius` 解决了——所以在它上面规划出来的路线本来
+就离墙足够远,规划器什么都不用做。
-身体站不下的目标(墙角里的拾取物)依然到得了:路径规划到身体站得下的最近处为止,
-剩下的交给 `arriveRadius`。
+身体站不下的目标(墙角里的拾取物)两种情况下都依然到得了:路径规划到身体站得下的最近处
+为止,剩下的交给 `arriveRadius`。
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index fab96d467..53c95cac5 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 113,
"beta": 73,
- "experimental": 1605,
+ "experimental": 1612,
"deprecated": 3
},
- "total": 1791,
+ "total": 1798,
"subsystems": [
{
"id": "ecs",
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 568ce83b9..040338789 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -2004,6 +2004,13 @@
"default": "50",
"range": "≥ 1"
},
+ {
+ "key": "cellHeight",
+ "type": "number",
+ "default": "10",
+ "doc": "Vertical voxel size; what separates one level from the one above it.",
+ "range": "≥ 1"
+ },
{
"key": "maxSlopeDegrees",
"type": "number",
@@ -2014,7 +2021,14 @@
"key": "agentHeight",
"type": "number",
"default": "180",
- "doc": "Headroom an agent needs; 0 skips the ceiling check.",
+ "doc": "Headroom an agent needs to walk somewhere.",
+ "range": "≥ 0"
+ },
+ {
+ "key": "agentRadius",
+ "type": "number",
+ "default": "30",
+ "doc": "How wide the agent is; the mesh is pulled back from walls by this.",
"range": "≥ 0"
},
{
@@ -2027,7 +2041,7 @@
"key": "layers",
"type": "number",
"default": "0",
- "doc": "Layer mask the ground rays are cast against; 0 = every layer.",
+ "doc": "Layer mask the ground is taken from; 0 = every layer.",
"range": "≥ 0",
"advanced": true
}
@@ -2037,8 +2051,10 @@
"halfExtents.y",
"halfExtents.z",
"cellSize",
+ "cellHeight",
"maxSlopeDegrees",
"agentHeight",
+ "agentRadius",
"stepHeight",
"layers"
]
diff --git a/examples/celestial-heights/src/systems/world.ts b/examples/celestial-heights/src/systems/world.ts
index 0972ff3ec..eaf8ed002 100644
--- a/examples/celestial-heights/src/systems/world.ts
+++ b/examples/celestial-heights/src/systems/world.ts
@@ -3,7 +3,7 @@ import {
Transform, Camera, FollowTarget, TilemapLayer, RuntimeOnly, Text, Sprite, Prefabs,
Nav, navGridFromTilemapLayer, SceneManager, transitionTo,
} from 'esengine';
-import type { NavGrid } from 'esengine';
+import { NavGrid } from 'esengine';
import { Area, AreaLabel, Player, Gate, NavGridBuilt, Spawner, Spawned } from '../components';
import { session } from '../state';
@@ -40,7 +40,7 @@ export const navFromTerrainSystem = defineSystem(
const width = Math.round((-transform.position.x * 2) / cell);
const height = Math.round((transform.position.y * 2) / cell);
if (width <= 0 || height <= 0) continue;
- nav.setGrid(navGridFromTilemapLayer(entity, {
+ nav.setSurface(navGridFromTilemapLayer(entity, {
width,
height,
cellSize: cell,
@@ -146,8 +146,8 @@ export const spawnerSystem = defineSystem(
// Nothing may be placed before the terrain has said where the ground is:
// the grid is derived from the tilemap by a system that runs just ahead
// of this one, but not on the frame the area arrives.
- if (!nav.hasGrid()) return;
- const grid = nav.grid;
+ if (!(nav.surface instanceof NavGrid)) return;
+ const grid = nav.surface;
for (const [entity, transform, spawner] of spawners) {
commands.entity(entity).insert(Spawned, {}).insert(RuntimeOnly, {});
if (!spawner.prefab) continue;
diff --git a/examples/enemy-ai/src/enemy.ts b/examples/enemy-ai/src/enemy.ts
index 11c581baa..39fa5d5ca 100644
--- a/examples/enemy-ai/src/enemy.ts
+++ b/examples/enemy-ai/src/enemy.ts
@@ -22,7 +22,7 @@ registerAction('patrol', () => { /* hold position until the player is seen */ })
export const setupNavGridSystem = defineSystem(
[Res(Nav)],
(nav) => {
- nav.setGrid(new NavGrid({ width: 60, height: 44, cellSize: 20, origin: { x: -600, y: -440 } }));
+ nav.setSurface(new NavGrid({ width: 60, height: 44, cellSize: 20, origin: { x: -600, y: -440 } }));
},
{ name: 'SetupNavGridSystem' },
);
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 3b970e6de..3456bac26 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: 113 public · 66 beta · 1491 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1498 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1088,17 +1088,6 @@ resolveUrl: (path: string) => string
setBaseUrl: ((url: string) => void) | undefined
```
-## BakeNavGridOptions — interface @experimental
-```
-agentHeight: number | undefined
-cellSize: number
-layers: number | undefined
-max: Vec3
-maxSlopeDegrees: number | undefined
-min: Vec3
-stepHeight: number | undefined
-```
-
## BatchBreak — enum @experimental
```
Blend = 4
@@ -1352,6 +1341,22 @@ origin: Vec2 | undefined
width: number
```
+## BuildNavMeshOptions — interface @experimental
+```
+agentHeight: number | undefined
+agentRadius: number | undefined
+cellHeight: number
+cellSize: number
+max: Vec3
+maxEdgeLength: number | undefined
+maxSimplificationError: number | undefined
+maxSlopeDegrees: number | undefined
+maxVertsPerPoly: number | undefined
+min: Vec3
+minRegionArea: number | undefined
+stepHeight: number | undefined
+```
+
## BuildProfile — interface @experimental
```
remoteRoot: string | undefined
@@ -1958,6 +1963,13 @@ Depth = 2
Nothing = 0
```
+## CollectNavGeometryOptions — interface @experimental
+```
+layers: number | undefined
+max: Vec3
+min: Vec3
+```
+
## Collider3DComponent — type @experimental
```
| 'BoxCollider3D' | 'SphereCollider3D' | 'CapsuleCollider3D'
@@ -3583,17 +3595,6 @@ static new (opts: GridLayoutOptions): GridLayoutProvider
static prototype: GridLayoutProvider
```
-## GroundHit — interface @experimental
-```
-normalY: number
-y: number
-```
-
-## GroundProbe — interface @experimental
-```
-raycast: (origin: Vec3, direction: Vec3, layerMask?: number) => GroundHit | null
-```
-
## HeadlessAppOptions — interface @experimental
```
plugins: Plugin[] | undefined
@@ -4699,32 +4700,37 @@ ResourceDef<NavDebugDrawConfig>
## NavDebugDrawConfig — interface @experimental
```
enabled: boolean
-showCells: boolean
-showLedges: boolean
+showBorders: boolean
+showFaces: boolean
+```
+
+## NavGeometry — interface @experimental
+```
+bodyCount: number
+indices: Uint32Array<ArrayBufferLike>
+verts: Float32Array<ArrayBufferLike>
```
## NavGrid — class @experimental
```
-baseHeight: number
-canStep: (fromX: number, fromY: number, toX: number, toY: number) => boolean
cellSize: number
cellToWorld: (gx: number, gy: number) => Vec3
clearanceAt: (gx: number, gy: number) => number
+describe: (sink: NavSurfaceSink) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
height: number
inBounds: (gx: number, gy: number) => boolean
index: (gx: number, gy: number) => number
isWalkable: (gx: number, gy: number) => boolean
nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | null
-originU: number
-originV: number
-plane: NavPlane
+originX: number
+originY: number
+originZ: number
setWalkable: (gx: number, gy: number, walkable: boolean) => void
-stepHeight: number
-surface: Float32Array<ArrayBufferLike> | null
-surfaceAt: (gx: number, gy: number) => number
+up: Vec3
walkable: Uint8Array<ArrayBufferLike>
width: number
-worldToCell: (p: { x: number; y: number; z?: number; }) => Cell
+worldToCell: (p: NavPoint) => Cell
static new (opts: NavGridOptions): NavGrid
static prototype: NavGrid
```
@@ -4734,16 +4740,42 @@ static prototype: NavGrid
cellSize: number
height: number
origin: { x: number; y: number; z?: number; } | undefined
-plane: NavPlane | undefined
-stepHeight: number | undefined
-surface: ArrayLike<number> | undefined
walkable: ArrayLike<number> | undefined
width: number
```
-## NavPlane — type @experimental
+## NavMesh — class @experimental
+```
+agentRadius: number
+contains: (p: number, x: number, z: number) => boolean
+corner: (p: number, i: number, out: Vec3) => Vec3
+describe: (sink: NavSurfaceSink) => void
+findPoly: (p: NavPoint, out?: Vec3) => number
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+heightAt: (p: number, x: number, z: number) => number
+maxVertsPerPoly: number
+neis: Int32Array<ArrayBufferLike>
+polyCount: number
+polys: Int32Array<ArrayBufferLike>
+snapDistance: number
+up: Vec3
+vertexCount: (p: number) => number
+verticalReach: number
+verts: Float32Array<ArrayBufferLike>
+static new (data: NavMeshData): NavMesh
+static prototype: NavMesh
+```
+
+## NavMeshData — interface @experimental
```
-'xy' | 'xz'
+agentRadius: number
+maxVertsPerPoly: number
+neis: Int32Array<ArrayBufferLike>
+polyCount: number
+polys: Int32Array<ArrayBufferLike>
+snapDistance: number
+verticalReach: number
+verts: Float32Array<ArrayBufferLike>
```
## NavPlugin — class @experimental
@@ -4754,6 +4786,31 @@ static new (): NavPlugin
static prototype: NavPlugin
```
+## NavPoint — interface @experimental
+```
+x: number
+y: number
+z: number | undefined
+```
+
+## NavQueryOptions — interface @experimental
+```
+radius: number | undefined
+```
+
+## NavSurface — interface @experimental
+```
+describe: (sink: NavSurfaceSink) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+up: Vec3
+```
+
+## NavSurfaceSink — interface @experimental
+```
+border: (a: Vec3, b: Vec3) => void
+face: (corners: readonly Vec3[]) => void
+```
+
## NavVolume — const @experimental
```
ComponentDef<NavVolumeData>
@@ -4762,6 +4819,8 @@ ComponentDef<NavVolumeData>
## NavVolumeData — interface @experimental
```
agentHeight: number
+agentRadius: number
+cellHeight: number
cellSize: number
halfExtents: Vec3
layers: number
@@ -4771,10 +4830,10 @@ stepHeight: number
## Navigation — class @experimental
```
-findWorldPath: (from: { x: number; y: number; z?: number; }, to: { x: number; y: number; z?: number; }, opts?: PathfindOptions & { radius?: number; }) => Vec3[] | null
-grid: NavGrid | null
-hasGrid: () => boolean
-setGrid: (grid: NavGrid | null) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+hasSurface: () => boolean
+setSurface: (surface: NavSurface | null) => void
+surface: NavSurface | null
static new (): Navigation
static prototype: Navigation
```
@@ -9434,11 +9493,6 @@ AudioPlugin
() => Dimension
```
-## bakeNavGrid — function @experimental
-```
-(probe: GroundProbe, opts: BakeNavGridOptions): NavGrid
-```
-
## bind — function @experimental
```
<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void
@@ -9484,6 +9538,11 @@ BtPlugin
(input: FrameProfileInput): FrameProfile
```
+## buildNavMesh — function @experimental
+```
+(verts: Float32Array, indices: ArrayLike<number>, opts: BuildNavMeshOptions): NavMesh
+```
+
## buildTerrainIndices — function @experimental
```
(asset: TilesetAsset): TerrainIndices
@@ -9659,6 +9718,11 @@ BtPlugin
(): boolean
```
+## collectNavGeometry — function @experimental
+```
+(world: World, opts: CollectNavGeometryOptions): NavGeometry
+```
+
## collectNestedPrefabPaths — function @experimental
```
(prefab: PrefabData, loadPrefab: (path: string) => PrefabData | null, visited?: Set<string>): string[]
@@ -10909,6 +10973,11 @@ Mesh2DPlugin
(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition
```
+## navGeometryReady — function @experimental
+```
+(world: World, layers?: number): boolean
+```
+
## navGridFromTilemapLayer — function @experimental
```
(entity: Entity, opts: BuildNavGridOptions): NavGrid
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 19a050fc0..102358379 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: 113 public · 71 beta · 1510 experimental · 3 deprecated
+Symbols: 113 public · 71 beta · 1517 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1088,17 +1088,6 @@ resolveUrl: (path: string) => string
setBaseUrl: ((url: string) => void) | undefined
```
-## BakeNavGridOptions — interface @experimental
-```
-agentHeight: number | undefined
-cellSize: number
-layers: number | undefined
-max: Vec3
-maxSlopeDegrees: number | undefined
-min: Vec3
-stepHeight: number | undefined
-```
-
## BatchBreak — enum @experimental
```
Blend = 4
@@ -1352,6 +1341,22 @@ origin: Vec2 | undefined
width: number
```
+## BuildNavMeshOptions — interface @experimental
+```
+agentHeight: number | undefined
+agentRadius: number | undefined
+cellHeight: number
+cellSize: number
+max: Vec3
+maxEdgeLength: number | undefined
+maxSimplificationError: number | undefined
+maxSlopeDegrees: number | undefined
+maxVertsPerPoly: number | undefined
+min: Vec3
+minRegionArea: number | undefined
+stepHeight: number | undefined
+```
+
## BuildProfile — interface @experimental
```
remoteRoot: string | undefined
@@ -1958,6 +1963,13 @@ Depth = 2
Nothing = 0
```
+## CollectNavGeometryOptions — interface @experimental
+```
+layers: number | undefined
+max: Vec3
+min: Vec3
+```
+
## Collider3DComponent — type @experimental
```
| 'BoxCollider3D' | 'SphereCollider3D' | 'CapsuleCollider3D'
@@ -3591,17 +3603,6 @@ static new (opts: GridLayoutOptions): GridLayoutProvider
static prototype: GridLayoutProvider
```
-## GroundHit — interface @experimental
-```
-normalY: number
-y: number
-```
-
-## GroundProbe — interface @experimental
-```
-raycast: (origin: Vec3, direction: Vec3, layerMask?: number) => GroundHit | null
-```
-
## HeadlessAppOptions — interface @experimental
```
plugins: Plugin[] | undefined
@@ -4877,32 +4878,37 @@ ResourceDef<NavDebugDrawConfig>
## NavDebugDrawConfig — interface @experimental
```
enabled: boolean
-showCells: boolean
-showLedges: boolean
+showBorders: boolean
+showFaces: boolean
+```
+
+## NavGeometry — interface @experimental
+```
+bodyCount: number
+indices: Uint32Array<ArrayBufferLike>
+verts: Float32Array<ArrayBufferLike>
```
## NavGrid — class @experimental
```
-baseHeight: number
-canStep: (fromX: number, fromY: number, toX: number, toY: number) => boolean
cellSize: number
cellToWorld: (gx: number, gy: number) => Vec3
clearanceAt: (gx: number, gy: number) => number
+describe: (sink: NavSurfaceSink) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
height: number
inBounds: (gx: number, gy: number) => boolean
index: (gx: number, gy: number) => number
isWalkable: (gx: number, gy: number) => boolean
nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | null
-originU: number
-originV: number
-plane: NavPlane
+originX: number
+originY: number
+originZ: number
setWalkable: (gx: number, gy: number, walkable: boolean) => void
-stepHeight: number
-surface: Float32Array<ArrayBufferLike> | null
-surfaceAt: (gx: number, gy: number) => number
+up: Vec3
walkable: Uint8Array<ArrayBufferLike>
width: number
-worldToCell: (p: { x: number; y: number; z?: number; }) => Cell
+worldToCell: (p: NavPoint) => Cell
static new (opts: NavGridOptions): NavGrid
static prototype: NavGrid
```
@@ -4912,16 +4918,42 @@ static prototype: NavGrid
cellSize: number
height: number
origin: { x: number; y: number; z?: number; } | undefined
-plane: NavPlane | undefined
-stepHeight: number | undefined
-surface: ArrayLike<number> | undefined
walkable: ArrayLike<number> | undefined
width: number
```
-## NavPlane — type @experimental
+## NavMesh — class @experimental
+```
+agentRadius: number
+contains: (p: number, x: number, z: number) => boolean
+corner: (p: number, i: number, out: Vec3) => Vec3
+describe: (sink: NavSurfaceSink) => void
+findPoly: (p: NavPoint, out?: Vec3) => number
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+heightAt: (p: number, x: number, z: number) => number
+maxVertsPerPoly: number
+neis: Int32Array<ArrayBufferLike>
+polyCount: number
+polys: Int32Array<ArrayBufferLike>
+snapDistance: number
+up: Vec3
+vertexCount: (p: number) => number
+verticalReach: number
+verts: Float32Array<ArrayBufferLike>
+static new (data: NavMeshData): NavMesh
+static prototype: NavMesh
+```
+
+## NavMeshData — interface @experimental
```
-'xy' | 'xz'
+agentRadius: number
+maxVertsPerPoly: number
+neis: Int32Array<ArrayBufferLike>
+polyCount: number
+polys: Int32Array<ArrayBufferLike>
+snapDistance: number
+verticalReach: number
+verts: Float32Array<ArrayBufferLike>
```
## NavPlugin — class @experimental
@@ -4932,6 +4964,31 @@ static new (): NavPlugin
static prototype: NavPlugin
```
+## NavPoint — interface @experimental
+```
+x: number
+y: number
+z: number | undefined
+```
+
+## NavQueryOptions — interface @experimental
+```
+radius: number | undefined
+```
+
+## NavSurface — interface @experimental
+```
+describe: (sink: NavSurfaceSink) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+up: Vec3
+```
+
+## NavSurfaceSink — interface @experimental
+```
+border: (a: Vec3, b: Vec3) => void
+face: (corners: readonly Vec3[]) => void
+```
+
## NavVolume — const @experimental
```
ComponentDef<NavVolumeData>
@@ -4940,6 +4997,8 @@ ComponentDef<NavVolumeData>
## NavVolumeData — interface @experimental
```
agentHeight: number
+agentRadius: number
+cellHeight: number
cellSize: number
halfExtents: Vec3
layers: number
@@ -4949,10 +5008,10 @@ stepHeight: number
## Navigation — class @experimental
```
-findWorldPath: (from: { x: number; y: number; z?: number; }, to: { x: number; y: number; z?: number; }, opts?: PathfindOptions & { radius?: number; }) => Vec3[] | null
-grid: NavGrid | null
-hasGrid: () => boolean
-setGrid: (grid: NavGrid | null) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+hasSurface: () => boolean
+setSurface: (surface: NavSurface | null) => void
+surface: NavSurface | null
static new (): Navigation
static prototype: Navigation
```
@@ -9642,11 +9701,6 @@ AudioPlugin
() => Dimension
```
-## bakeNavGrid — function @experimental
-```
-(probe: GroundProbe, opts: BakeNavGridOptions): NavGrid
-```
-
## bind — function @experimental
```
<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void
@@ -9692,6 +9746,11 @@ BtPlugin
(input: FrameProfileInput): FrameProfile
```
+## buildNavMesh — function @experimental
+```
+(verts: Float32Array, indices: ArrayLike<number>, opts: BuildNavMeshOptions): NavMesh
+```
+
## buildTerrainIndices — function @experimental
```
(asset: TilesetAsset): TerrainIndices
@@ -9867,6 +9926,11 @@ BtPlugin
(): boolean
```
+## collectNavGeometry — function @experimental
+```
+(world: World, opts: CollectNavGeometryOptions): NavGeometry
+```
+
## collectNestedPrefabPaths — function @experimental
```
(prefab: PrefabData, loadPrefab: (path: string) => PrefabData | null, visited?: Set<string>): string[]
@@ -11152,6 +11216,11 @@ Mesh2DPlugin
(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition
```
+## navGeometryReady — function @experimental
+```
+(world: World, layers?: number): boolean
+```
+
## navGridFromTilemapLayer — function @experimental
```
(entity: Entity, opts: BuildNavGridOptions): NavGrid
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 7a0a35d19..e355386aa 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: 113 public · 68 beta · 1490 experimental · 3 deprecated
+Symbols: 113 public · 68 beta · 1497 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1083,17 +1083,6 @@ resolveUrl: (path: string) => string
setBaseUrl: ((url: string) => void) | undefined
```
-## BakeNavGridOptions — interface @experimental
-```
-agentHeight: number | undefined
-cellSize: number
-layers: number | undefined
-max: Vec3
-maxSlopeDegrees: number | undefined
-min: Vec3
-stepHeight: number | undefined
-```
-
## BatchBreak — enum @experimental
```
Blend = 4
@@ -1347,6 +1336,22 @@ origin: Vec2 | undefined
width: number
```
+## BuildNavMeshOptions — interface @experimental
+```
+agentHeight: number | undefined
+agentRadius: number | undefined
+cellHeight: number
+cellSize: number
+max: Vec3
+maxEdgeLength: number | undefined
+maxSimplificationError: number | undefined
+maxSlopeDegrees: number | undefined
+maxVertsPerPoly: number | undefined
+min: Vec3
+minRegionArea: number | undefined
+stepHeight: number | undefined
+```
+
## BuildProfile — interface @experimental
```
remoteRoot: string | undefined
@@ -1953,6 +1958,13 @@ Depth = 2
Nothing = 0
```
+## CollectNavGeometryOptions — interface @experimental
+```
+layers: number | undefined
+max: Vec3
+min: Vec3
+```
+
## Collider3DComponent — type @experimental
```
| 'BoxCollider3D' | 'SphereCollider3D' | 'CapsuleCollider3D'
@@ -3578,17 +3590,6 @@ static new (opts: GridLayoutOptions): GridLayoutProvider
static prototype: GridLayoutProvider
```
-## GroundHit — interface @experimental
-```
-normalY: number
-y: number
-```
-
-## GroundProbe — interface @experimental
-```
-raycast: (origin: Vec3, direction: Vec3, layerMask?: number) => GroundHit | null
-```
-
## HeadlessAppOptions — interface @experimental
```
plugins: Plugin[] | undefined
@@ -4694,32 +4695,37 @@ ResourceDef<NavDebugDrawConfig>
## NavDebugDrawConfig — interface @experimental
```
enabled: boolean
-showCells: boolean
-showLedges: boolean
+showBorders: boolean
+showFaces: boolean
+```
+
+## NavGeometry — interface @experimental
+```
+bodyCount: number
+indices: Uint32Array<ArrayBufferLike>
+verts: Float32Array<ArrayBufferLike>
```
## NavGrid — class @experimental
```
-baseHeight: number
-canStep: (fromX: number, fromY: number, toX: number, toY: number) => boolean
cellSize: number
cellToWorld: (gx: number, gy: number) => Vec3
clearanceAt: (gx: number, gy: number) => number
+describe: (sink: NavSurfaceSink) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
height: number
inBounds: (gx: number, gy: number) => boolean
index: (gx: number, gy: number) => number
isWalkable: (gx: number, gy: number) => boolean
nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | null
-originU: number
-originV: number
-plane: NavPlane
+originX: number
+originY: number
+originZ: number
setWalkable: (gx: number, gy: number, walkable: boolean) => void
-stepHeight: number
-surface: Float32Array<ArrayBufferLike> | null
-surfaceAt: (gx: number, gy: number) => number
+up: Vec3
walkable: Uint8Array<ArrayBufferLike>
width: number
-worldToCell: (p: { x: number; y: number; z?: number; }) => Cell
+worldToCell: (p: NavPoint) => Cell
static new (opts: NavGridOptions): NavGrid
static prototype: NavGrid
```
@@ -4729,16 +4735,42 @@ static prototype: NavGrid
cellSize: number
height: number
origin: { x: number; y: number; z?: number; } | undefined
-plane: NavPlane | undefined
-stepHeight: number | undefined
-surface: ArrayLike<number> | undefined
walkable: ArrayLike<number> | undefined
width: number
```
-## NavPlane — type @experimental
+## NavMesh — class @experimental
+```
+agentRadius: number
+contains: (p: number, x: number, z: number) => boolean
+corner: (p: number, i: number, out: Vec3) => Vec3
+describe: (sink: NavSurfaceSink) => void
+findPoly: (p: NavPoint, out?: Vec3) => number
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+heightAt: (p: number, x: number, z: number) => number
+maxVertsPerPoly: number
+neis: Int32Array<ArrayBufferLike>
+polyCount: number
+polys: Int32Array<ArrayBufferLike>
+snapDistance: number
+up: Vec3
+vertexCount: (p: number) => number
+verticalReach: number
+verts: Float32Array<ArrayBufferLike>
+static new (data: NavMeshData): NavMesh
+static prototype: NavMesh
+```
+
+## NavMeshData — interface @experimental
```
-'xy' | 'xz'
+agentRadius: number
+maxVertsPerPoly: number
+neis: Int32Array<ArrayBufferLike>
+polyCount: number
+polys: Int32Array<ArrayBufferLike>
+snapDistance: number
+verticalReach: number
+verts: Float32Array<ArrayBufferLike>
```
## NavPlugin — class @experimental
@@ -4749,6 +4781,31 @@ static new (): NavPlugin
static prototype: NavPlugin
```
+## NavPoint — interface @experimental
+```
+x: number
+y: number
+z: number | undefined
+```
+
+## NavQueryOptions — interface @experimental
+```
+radius: number | undefined
+```
+
+## NavSurface — interface @experimental
+```
+describe: (sink: NavSurfaceSink) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+up: Vec3
+```
+
+## NavSurfaceSink — interface @experimental
+```
+border: (a: Vec3, b: Vec3) => void
+face: (corners: readonly Vec3[]) => void
+```
+
## NavVolume — const @experimental
```
ComponentDef<NavVolumeData>
@@ -4757,6 +4814,8 @@ ComponentDef<NavVolumeData>
## NavVolumeData — interface @experimental
```
agentHeight: number
+agentRadius: number
+cellHeight: number
cellSize: number
halfExtents: Vec3
layers: number
@@ -4766,10 +4825,10 @@ stepHeight: number
## Navigation — class @experimental
```
-findWorldPath: (from: { x: number; y: number; z?: number; }, to: { x: number; y: number; z?: number; }, opts?: PathfindOptions & { radius?: number; }) => Vec3[] | null
-grid: NavGrid | null
-hasGrid: () => boolean
-setGrid: (grid: NavGrid | null) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+hasSurface: () => boolean
+setSurface: (surface: NavSurface | null) => void
+surface: NavSurface | null
static new (): Navigation
static prototype: Navigation
```
@@ -9429,11 +9488,6 @@ AudioPlugin
() => Dimension
```
-## bakeNavGrid — function @experimental
-```
-(probe: GroundProbe, opts: BakeNavGridOptions): NavGrid
-```
-
## bind — function @experimental
```
<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void
@@ -9479,6 +9533,11 @@ BtPlugin
(input: FrameProfileInput): FrameProfile
```
+## buildNavMesh — function @experimental
+```
+(verts: Float32Array, indices: ArrayLike<number>, opts: BuildNavMeshOptions): NavMesh
+```
+
## buildTerrainIndices — function @experimental
```
(asset: TilesetAsset): TerrainIndices
@@ -9654,6 +9713,11 @@ BtPlugin
(): boolean
```
+## collectNavGeometry — function @experimental
+```
+(world: World, opts: CollectNavGeometryOptions): NavGeometry
+```
+
## collectNestedPrefabPaths — function @experimental
```
(prefab: PrefabData, loadPrefab: (path: string) => PrefabData | null, visited?: Set<string>): string[]
@@ -10909,6 +10973,11 @@ Mesh2DPlugin
(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition
```
+## navGeometryReady — function @experimental
+```
+(world: World, layers?: number): boolean
+```
+
## navGridFromTilemapLayer — function @experimental
```
(entity: Entity, opts: BuildNavGridOptions): NavGrid
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 8300431bb..6e7c6b53d 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: 113 public · 66 beta · 1511 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1518 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1083,17 +1083,6 @@ resolveUrl: (path: string) => string
setBaseUrl: ((url: string) => void) | undefined
```
-## BakeNavGridOptions — interface @experimental
-```
-agentHeight: number | undefined
-cellSize: number
-layers: number | undefined
-max: Vec3
-maxSlopeDegrees: number | undefined
-min: Vec3
-stepHeight: number | undefined
-```
-
## BatchBreak — enum @experimental
```
Blend = 4
@@ -1347,6 +1336,22 @@ origin: Vec2 | undefined
width: number
```
+## BuildNavMeshOptions — interface @experimental
+```
+agentHeight: number | undefined
+agentRadius: number | undefined
+cellHeight: number
+cellSize: number
+max: Vec3
+maxEdgeLength: number | undefined
+maxSimplificationError: number | undefined
+maxSlopeDegrees: number | undefined
+maxVertsPerPoly: number | undefined
+min: Vec3
+minRegionArea: number | undefined
+stepHeight: number | undefined
+```
+
## BuildProfile — interface @experimental
```
remoteRoot: string | undefined
@@ -1953,6 +1958,13 @@ Depth = 2
Nothing = 0
```
+## CollectNavGeometryOptions — interface @experimental
+```
+layers: number | undefined
+max: Vec3
+min: Vec3
+```
+
## Collider3DComponent — type @experimental
```
| 'BoxCollider3D' | 'SphereCollider3D' | 'CapsuleCollider3D'
@@ -3578,17 +3590,6 @@ static new (opts: GridLayoutOptions): GridLayoutProvider
static prototype: GridLayoutProvider
```
-## GroundHit — interface @experimental
-```
-normalY: number
-y: number
-```
-
-## GroundProbe — interface @experimental
-```
-raycast: (origin: Vec3, direction: Vec3, layerMask?: number) => GroundHit | null
-```
-
## HeadlessAppOptions — interface @experimental
```
plugins: Plugin[] | undefined
@@ -4939,32 +4940,37 @@ ResourceDef<NavDebugDrawConfig>
## NavDebugDrawConfig — interface @experimental
```
enabled: boolean
-showCells: boolean
-showLedges: boolean
+showBorders: boolean
+showFaces: boolean
+```
+
+## NavGeometry — interface @experimental
+```
+bodyCount: number
+indices: Uint32Array<ArrayBufferLike>
+verts: Float32Array<ArrayBufferLike>
```
## NavGrid — class @experimental
```
-baseHeight: number
-canStep: (fromX: number, fromY: number, toX: number, toY: number) => boolean
cellSize: number
cellToWorld: (gx: number, gy: number) => Vec3
clearanceAt: (gx: number, gy: number) => number
+describe: (sink: NavSurfaceSink) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
height: number
inBounds: (gx: number, gy: number) => boolean
index: (gx: number, gy: number) => number
isWalkable: (gx: number, gy: number) => boolean
nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | null
-originU: number
-originV: number
-plane: NavPlane
+originX: number
+originY: number
+originZ: number
setWalkable: (gx: number, gy: number, walkable: boolean) => void
-stepHeight: number
-surface: Float32Array<ArrayBufferLike> | null
-surfaceAt: (gx: number, gy: number) => number
+up: Vec3
walkable: Uint8Array<ArrayBufferLike>
width: number
-worldToCell: (p: { x: number; y: number; z?: number; }) => Cell
+worldToCell: (p: NavPoint) => Cell
static new (opts: NavGridOptions): NavGrid
static prototype: NavGrid
```
@@ -4974,16 +4980,42 @@ static prototype: NavGrid
cellSize: number
height: number
origin: { x: number; y: number; z?: number; } | undefined
-plane: NavPlane | undefined
-stepHeight: number | undefined
-surface: ArrayLike<number> | undefined
walkable: ArrayLike<number> | undefined
width: number
```
-## NavPlane — type @experimental
+## NavMesh — class @experimental
+```
+agentRadius: number
+contains: (p: number, x: number, z: number) => boolean
+corner: (p: number, i: number, out: Vec3) => Vec3
+describe: (sink: NavSurfaceSink) => void
+findPoly: (p: NavPoint, out?: Vec3) => number
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+heightAt: (p: number, x: number, z: number) => number
+maxVertsPerPoly: number
+neis: Int32Array<ArrayBufferLike>
+polyCount: number
+polys: Int32Array<ArrayBufferLike>
+snapDistance: number
+up: Vec3
+vertexCount: (p: number) => number
+verticalReach: number
+verts: Float32Array<ArrayBufferLike>
+static new (data: NavMeshData): NavMesh
+static prototype: NavMesh
+```
+
+## NavMeshData — interface @experimental
```
-'xy' | 'xz'
+agentRadius: number
+maxVertsPerPoly: number
+neis: Int32Array<ArrayBufferLike>
+polyCount: number
+polys: Int32Array<ArrayBufferLike>
+snapDistance: number
+verticalReach: number
+verts: Float32Array<ArrayBufferLike>
```
## NavPlugin — class @experimental
@@ -4994,6 +5026,31 @@ static new (): NavPlugin
static prototype: NavPlugin
```
+## NavPoint — interface @experimental
+```
+x: number
+y: number
+z: number | undefined
+```
+
+## NavQueryOptions — interface @experimental
+```
+radius: number | undefined
+```
+
+## NavSurface — interface @experimental
+```
+describe: (sink: NavSurfaceSink) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+up: Vec3
+```
+
+## NavSurfaceSink — interface @experimental
+```
+border: (a: Vec3, b: Vec3) => void
+face: (corners: readonly Vec3[]) => void
+```
+
## NavVolume — const @experimental
```
ComponentDef<NavVolumeData>
@@ -5002,6 +5059,8 @@ ComponentDef<NavVolumeData>
## NavVolumeData — interface @experimental
```
agentHeight: number
+agentRadius: number
+cellHeight: number
cellSize: number
halfExtents: Vec3
layers: number
@@ -5011,10 +5070,10 @@ stepHeight: number
## Navigation — class @experimental
```
-findWorldPath: (from: { x: number; y: number; z?: number; }, to: { x: number; y: number; z?: number; }, opts?: PathfindOptions & { radius?: number; }) => Vec3[] | null
-grid: NavGrid | null
-hasGrid: () => boolean
-setGrid: (grid: NavGrid | null) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+hasSurface: () => boolean
+setSurface: (surface: NavSurface | null) => void
+surface: NavSurface | null
static new (): Navigation
static prototype: Navigation
```
@@ -9674,11 +9733,6 @@ AudioPlugin
() => Dimension
```
-## bakeNavGrid — function @experimental
-```
-(probe: GroundProbe, opts: BakeNavGridOptions): NavGrid
-```
-
## bind — function @experimental
```
<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void
@@ -9724,6 +9778,11 @@ BtPlugin
(input: FrameProfileInput): FrameProfile
```
+## buildNavMesh — function @experimental
+```
+(verts: Float32Array, indices: ArrayLike<number>, opts: BuildNavMeshOptions): NavMesh
+```
+
## buildTerrainIndices — function @experimental
```
(asset: TilesetAsset): TerrainIndices
@@ -9899,6 +9958,11 @@ BtPlugin
(): boolean
```
+## collectNavGeometry — function @experimental
+```
+(world: World, opts: CollectNavGeometryOptions): NavGeometry
+```
+
## collectNestedPrefabPaths — function @experimental
```
(prefab: PrefabData, loadPrefab: (path: string) => PrefabData | null, visited?: Set<string>): string[]
@@ -11164,6 +11228,11 @@ Mesh2DPlugin
(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition
```
+## navGeometryReady — function @experimental
+```
+(world: World, layers?: number): boolean
+```
+
## navGridFromTilemapLayer — function @experimental
```
(entity: Entity, opts: BuildNavGridOptions): NavGrid
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 9f820a731..eec055ca8 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: 113 public · 66 beta · 1501 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1508 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1083,17 +1083,6 @@ resolveUrl: (path: string) => string
setBaseUrl: ((url: string) => void) | undefined
```
-## BakeNavGridOptions — interface @experimental
-```
-agentHeight: number | undefined
-cellSize: number
-layers: number | undefined
-max: Vec3
-maxSlopeDegrees: number | undefined
-min: Vec3
-stepHeight: number | undefined
-```
-
## BatchBreak — enum @experimental
```
Blend = 4
@@ -1347,6 +1336,22 @@ origin: Vec2 | undefined
width: number
```
+## BuildNavMeshOptions — interface @experimental
+```
+agentHeight: number | undefined
+agentRadius: number | undefined
+cellHeight: number
+cellSize: number
+max: Vec3
+maxEdgeLength: number | undefined
+maxSimplificationError: number | undefined
+maxSlopeDegrees: number | undefined
+maxVertsPerPoly: number | undefined
+min: Vec3
+minRegionArea: number | undefined
+stepHeight: number | undefined
+```
+
## BuildProfile — interface @experimental
```
remoteRoot: string | undefined
@@ -1953,6 +1958,13 @@ Depth = 2
Nothing = 0
```
+## CollectNavGeometryOptions — interface @experimental
+```
+layers: number | undefined
+max: Vec3
+min: Vec3
+```
+
## Collider3DComponent — type @experimental
```
| 'BoxCollider3D' | 'SphereCollider3D' | 'CapsuleCollider3D'
@@ -3578,17 +3590,6 @@ static new (opts: GridLayoutOptions): GridLayoutProvider
static prototype: GridLayoutProvider
```
-## GroundHit — interface @experimental
-```
-normalY: number
-y: number
-```
-
-## GroundProbe — interface @experimental
-```
-raycast: (origin: Vec3, direction: Vec3, layerMask?: number) => GroundHit | null
-```
-
## HeadlessAppOptions — interface @experimental
```
plugins: Plugin[] | undefined
@@ -4701,32 +4702,37 @@ ResourceDef<NavDebugDrawConfig>
## NavDebugDrawConfig — interface @experimental
```
enabled: boolean
-showCells: boolean
-showLedges: boolean
+showBorders: boolean
+showFaces: boolean
+```
+
+## NavGeometry — interface @experimental
+```
+bodyCount: number
+indices: Uint32Array<ArrayBufferLike>
+verts: Float32Array<ArrayBufferLike>
```
## NavGrid — class @experimental
```
-baseHeight: number
-canStep: (fromX: number, fromY: number, toX: number, toY: number) => boolean
cellSize: number
cellToWorld: (gx: number, gy: number) => Vec3
clearanceAt: (gx: number, gy: number) => number
+describe: (sink: NavSurfaceSink) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
height: number
inBounds: (gx: number, gy: number) => boolean
index: (gx: number, gy: number) => number
isWalkable: (gx: number, gy: number) => boolean
nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | null
-originU: number
-originV: number
-plane: NavPlane
+originX: number
+originY: number
+originZ: number
setWalkable: (gx: number, gy: number, walkable: boolean) => void
-stepHeight: number
-surface: Float32Array<ArrayBufferLike> | null
-surfaceAt: (gx: number, gy: number) => number
+up: Vec3
walkable: Uint8Array<ArrayBufferLike>
width: number
-worldToCell: (p: { x: number; y: number; z?: number; }) => Cell
+worldToCell: (p: NavPoint) => Cell
static new (opts: NavGridOptions): NavGrid
static prototype: NavGrid
```
@@ -4736,16 +4742,42 @@ static prototype: NavGrid
cellSize: number
height: number
origin: { x: number; y: number; z?: number; } | undefined
-plane: NavPlane | undefined
-stepHeight: number | undefined
-surface: ArrayLike<number> | undefined
walkable: ArrayLike<number> | undefined
width: number
```
-## NavPlane — type @experimental
+## NavMesh — class @experimental
+```
+agentRadius: number
+contains: (p: number, x: number, z: number) => boolean
+corner: (p: number, i: number, out: Vec3) => Vec3
+describe: (sink: NavSurfaceSink) => void
+findPoly: (p: NavPoint, out?: Vec3) => number
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+heightAt: (p: number, x: number, z: number) => number
+maxVertsPerPoly: number
+neis: Int32Array<ArrayBufferLike>
+polyCount: number
+polys: Int32Array<ArrayBufferLike>
+snapDistance: number
+up: Vec3
+vertexCount: (p: number) => number
+verticalReach: number
+verts: Float32Array<ArrayBufferLike>
+static new (data: NavMeshData): NavMesh
+static prototype: NavMesh
+```
+
+## NavMeshData — interface @experimental
```
-'xy' | 'xz'
+agentRadius: number
+maxVertsPerPoly: number
+neis: Int32Array<ArrayBufferLike>
+polyCount: number
+polys: Int32Array<ArrayBufferLike>
+snapDistance: number
+verticalReach: number
+verts: Float32Array<ArrayBufferLike>
```
## NavPlugin — class @experimental
@@ -4756,6 +4788,31 @@ static new (): NavPlugin
static prototype: NavPlugin
```
+## NavPoint — interface @experimental
+```
+x: number
+y: number
+z: number | undefined
+```
+
+## NavQueryOptions — interface @experimental
+```
+radius: number | undefined
+```
+
+## NavSurface — interface @experimental
+```
+describe: (sink: NavSurfaceSink) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+up: Vec3
+```
+
+## NavSurfaceSink — interface @experimental
+```
+border: (a: Vec3, b: Vec3) => void
+face: (corners: readonly Vec3[]) => void
+```
+
## NavVolume — const @experimental
```
ComponentDef<NavVolumeData>
@@ -4764,6 +4821,8 @@ ComponentDef<NavVolumeData>
## NavVolumeData — interface @experimental
```
agentHeight: number
+agentRadius: number
+cellHeight: number
cellSize: number
halfExtents: Vec3
layers: number
@@ -4773,10 +4832,10 @@ stepHeight: number
## Navigation — class @experimental
```
-findWorldPath: (from: { x: number; y: number; z?: number; }, to: { x: number; y: number; z?: number; }, opts?: PathfindOptions & { radius?: number; }) => Vec3[] | null
-grid: NavGrid | null
-hasGrid: () => boolean
-setGrid: (grid: NavGrid | null) => void
+findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
+hasSurface: () => boolean
+setSurface: (surface: NavSurface | null) => void
+surface: NavSurface | null
static new (): Navigation
static prototype: Navigation
```
@@ -9456,11 +9515,6 @@ AudioPlugin
() => Dimension
```
-## bakeNavGrid — function @experimental
-```
-(probe: GroundProbe, opts: BakeNavGridOptions): NavGrid
-```
-
## bind — function @experimental
```
<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void
@@ -9506,6 +9560,11 @@ BtPlugin
(input: FrameProfileInput): FrameProfile
```
+## buildNavMesh — function @experimental
+```
+(verts: Float32Array, indices: ArrayLike<number>, opts: BuildNavMeshOptions): NavMesh
+```
+
## buildTerrainIndices — function @experimental
```
(asset: TilesetAsset): TerrainIndices
@@ -9681,6 +9740,11 @@ BtPlugin
(): boolean
```
+## collectNavGeometry — function @experimental
+```
+(world: World, opts: CollectNavGeometryOptions): NavGeometry
+```
+
## collectNestedPrefabPaths — function @experimental
```
(prefab: PrefabData, loadPrefab: (path: string) => PrefabData | null, visited?: Set<string>): string[]
@@ -10936,6 +11000,11 @@ Mesh2DPlugin
(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition
```
+## navGeometryReady — function @experimental
+```
+(world: World, layers?: number): boolean
+```
+
## navGridFromTilemapLayer — function @experimental
```
(entity: Entity, opts: BuildNavGridOptions): NavGrid
diff --git a/sdk/src/ai/nav/NavDebugDraw.ts b/sdk/src/ai/nav/NavDebugDraw.ts
index 83ddf3199..198111cd8 100644
--- a/sdk/src/ai/nav/NavDebugDraw.ts
+++ b/sdk/src/ai/nav/NavDebugDraw.ts
@@ -2,16 +2,17 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file NavDebugDraw.ts
- * @brief The navigation grid, drawn by the running game.
+ * @brief The navigable world, drawn by the running game.
*
* The volume's gizmo answers "is this box where I meant" while a scene is
- * authored. This answers what only the bake can: which cells came back walkable,
- * how high the ground under each one is, and where the step limit cut the grid in
- * two. Without it, `cellSize`, `maxSlopeDegrees` and `agentHeight` are tuned by
- * watching whether an agent happens to move.
+ * authored. This answers what only the bake can: what came back walkable, how
+ * high the ground under it is, and where the walkable world ends. Without it
+ * `cellSize`, `maxSlopeDegrees` and `agentHeight` are tuned by watching whether
+ * an agent happens to move.
*
- * Drawn from the grid the search READS, so the picture cannot disagree with the
- * routes — the same seam the volume gizmo takes from the bake.
+ * Drawn from the surface the search READS, so the picture cannot disagree with
+ * the routes — and through {@link NavSurface.describe}, so a grid and a mesh get
+ * one drawer rather than one each.
*/
import type { App } from '../../app/app';
import type { Color, Vec3 } from '../../types';
@@ -19,94 +20,75 @@ import { Draw } from '../../render/draw';
import { defineResource } from '../../ecs/resource';
import { registerDrawCallback } from '../../render/customDraw';
import { Nav, type Navigation } from './Navigation';
-import type { NavGrid } from './NavGrid';
+import type { NavSurface } from './NavSurface';
export interface NavDebugDrawConfig {
enabled: boolean;
- /** Outline each walkable cell. */
- showCells: boolean;
- /** Mark the pairs the step limit refuses, which is where a route stops. */
- showLedges: boolean;
+ /** Outline every walkable face. */
+ showFaces: boolean;
+ /** Mark the edges the walkable world stops at, which is where a route turns. */
+ showBorders: boolean;
}
-/** Off until a game turns it on: a grid is thousands of cells and each is a quad. */
+/** Off until a game turns it on: a surface is thousands of faces and each is a loop. */
export const NavDebugDraw = defineResource<NavDebugDrawConfig>({
enabled: false,
- showCells: true,
- showLedges: true,
+ showFaces: true,
+ showBorders: true,
}, 'NavDebugDraw');
-const WALKABLE: Color = { r: 0.3, g: 0.9, b: 0.5, a: 0.55 };
-const LEDGE: Color = { r: 1.0, g: 0.35, b: 0.3, a: 0.9 };
-/** World units, at 100 to the metre — thin enough to read a grid through. */
+const FACE: Color = { r: 0.3, g: 0.9, b: 0.5, a: 0.55 };
+const BORDER: Color = { r: 1.0, g: 0.35, b: 0.3, a: 0.9 };
+/** World units, at 100 to the metre — thin enough to read a surface through. */
const LINE_THICKNESS = 1.5;
+/** How far off the ground the overlay floats, so its lines do not fight the floor
+ * they describe for pixels. */
+const LIFT = 1;
/**
- * Cells drawn per frame. A grid is unbounded in principle and every cell costs
- * four lines: past this the overlay is what the frame is spending its time on,
- * and an overlay that stops the game is not a diagnostic. Cells past it are
+ * Faces drawn per frame. A surface is unbounded in principle and every face costs
+ * a line per edge: past this the overlay is what the frame is spending its time
+ * on, and an overlay that stops the game is not a diagnostic. Faces past it are
* simply not drawn — `cellSize` is the knob for seeing more of a big world.
*/
-const MAX_CELLS = 4096;
-
-/** The four corners of a cell, lifted just off its own ground so the lines are
- * not z-fighting the floor they describe. */
-function cellQuad(grid: NavGrid, gx: number, gy: number, lift: number): Vec3[] {
- const c = grid.cellToWorld(gx, gy);
- const h = grid.cellSize / 2;
- const y = c.y + lift;
- return grid.plane === 'xy'
- ? [{ x: c.x - h, y: c.y - h, z: c.z }, { x: c.x + h, y: c.y - h, z: c.z },
- { x: c.x + h, y: c.y + h, z: c.z }, { x: c.x - h, y: c.y + h, z: c.z }]
- : [{ x: c.x - h, y, z: c.z - h }, { x: c.x + h, y, z: c.z - h },
- { x: c.x + h, y, z: c.z + h }, { x: c.x - h, y, z: c.z + h }];
-}
+const MAX_FACES = 4096;
/** Draw one frame of the overlay. Exported for the unit test, which counts what
* it asked to be drawn rather than looking at pixels. */
-export function drawNavDebug(grid: NavGrid | null, cfg: NavDebugDrawConfig): void {
- if (!grid || !cfg.enabled) return;
- const lift = grid.plane === 'xy' ? 0 : 1;
- let drawn = 0;
+export function drawNavDebug(surface: NavSurface | null, cfg: NavDebugDrawConfig): void {
+ if (!surface || !cfg.enabled) return;
+ const up = surface.up;
+ const lx = up.x * LIFT, ly = up.y * LIFT, lz = up.z * LIFT;
+ const a: Vec3 = { x: 0, y: 0, z: 0 };
+ const b: Vec3 = { x: 0, y: 0, z: 0 };
+ let faces = 0;
- if (cfg.showCells) {
- for (let gy = 0; gy < grid.height && drawn < MAX_CELLS; gy++) {
- for (let gx = 0; gx < grid.width && drawn < MAX_CELLS; gx++) {
- if (!grid.isWalkable(gx, gy)) continue;
- const q = cellQuad(grid, gx, gy, lift);
- for (let i = 0; i < 4; i++) {
- Draw.line3D(q[i], q[(i + 1) % 4], WALKABLE, LINE_THICKNESS);
- }
- drawn++;
+ surface.describe({
+ face(corners) {
+ if (!cfg.showFaces || faces >= MAX_FACES) return;
+ faces++;
+ for (let i = 0; i < corners.length; i++) {
+ const p = corners[i]!;
+ const q = corners[(i + 1) % corners.length]!;
+ a.x = p.x + lx; a.y = p.y + ly; a.z = p.z + lz;
+ b.x = q.x + lx; b.y = q.y + ly; b.z = q.z + lz;
+ Draw.line3D(a, b, FACE, LINE_THICKNESS);
}
- }
- }
-
- if (!cfg.showLedges) return;
- // Where two walkable cells are NOT connected: the step limit's own answer, and
- // the only thing that explains a route going the long way round.
- for (let gy = 0; gy < grid.height; gy++) {
- for (let gx = 0; gx < grid.width; gx++) {
- if (!grid.isWalkable(gx, gy)) continue;
- for (const [dx, dy] of [[1, 0], [0, 1]] as const) {
- const nx = gx + dx;
- const ny = gy + dy;
- if (!grid.isWalkable(nx, ny) || grid.canStep(gx, gy, nx, ny)) continue;
- const a = cellQuad(grid, gx, gy, lift);
- const b = cellQuad(grid, nx, ny, lift);
- // The shared edge, drawn at both heights: a ledge IS the drop.
- Draw.line3D(a[dx === 1 ? 1 : 3], a[2], LEDGE, LINE_THICKNESS);
- Draw.line3D(b[dx === 1 ? 0 : 0], b[dx === 1 ? 3 : 1], LEDGE, LINE_THICKNESS);
- }
- }
- }
+ },
+ border(p, q) {
+ if (!cfg.showBorders) return;
+ a.x = p.x + lx; a.y = p.y + ly; a.z = p.z + lz;
+ b.x = q.x + lx; b.y = q.y + ly; b.z = q.z + lz;
+ Draw.line3D(a, b, BORDER, LINE_THICKNESS);
+ },
+ });
}
/** Install the overlay. Off until a game turns the resource on. */
export function setupNavDebugDraw(app: App): void {
- app.insertResource(NavDebugDraw, { enabled: false, showCells: true, showLedges: true });
+ app.insertResource(NavDebugDraw, { enabled: false, showFaces: true, showBorders: true });
registerDrawCallback('nav-debug-draw', () => {
const cfg = app.getResource<NavDebugDrawConfig>(NavDebugDraw);
if (!cfg?.enabled) return;
- drawNavDebug(app.getResource<Navigation>(Nav)?.grid ?? null, cfg);
+ drawNavDebug(app.getResource<Navigation>(Nav)?.surface ?? null, cfg);
});
}
diff --git a/sdk/src/ai/nav/NavGrid.ts b/sdk/src/ai/nav/NavGrid.ts
index c9e5de55d..d953a9604 100644
--- a/sdk/src/ai/nav/NavGrid.ts
+++ b/sdk/src/ai/nav/NavGrid.ts
@@ -5,34 +5,28 @@
* @brief Uniform navigation grid — a walkability bitmap plus the affine map
* between grid cells and world space.
*
- * ONE grid for both kinds of scene. What separates them is which world plane the
- * cells lie in and what the third axis holds: a flat scene's cells lie in x/y at
- * a constant depth, a spatial one's lie in x/z and each carries the height of
- * the ground there. Everything above that — the walkability mask, the clearance
- * transform, the A* over it — is the same question either way, and a second
- * class would be the same code with two axes renamed.
+ * The representation for a world that IS a grid: a tilemap, or any flat scene
+ * whose ground is one plane. Its two advantages over a baked mesh are that it
+ * costs nothing to build from data that is already cells, and that a single cell
+ * can be flipped while the game runs — a door closes, a tower goes up. Ground
+ * that slopes or stacks is not its question; that is {@link NavMesh}.
*
* Pure data + math, zero engine/wasm dependency, so the whole pathfinding core
- * is unit-testable in isolation. The engine bindings (build one from a tilemap
- * layer, or bake one out of the 3D solver) live beside it; A* in pathfind.ts.
+ * is unit-testable in isolation. The engine binding (build one from a tilemap
+ * layer) lives beside it; A* in pathfind.ts.
*/
-import type { Vec2, Vec3 } from '../../types';
+import type { Vec3 } from '../../types';
+import type { NavPoint, NavQueryOptions, NavSurface, NavSurfaceSink } from './NavSurface';
+import { findPath, pathToWorld } from './pathfind';
-/** Integer grid coordinate. Kept distinct from {@link Vec2} to flag cell-space. */
+/** Integer grid coordinate. Its own type rather than a world vector, so a cell
+ * coordinate cannot be passed where world pixels are expected. */
export interface Cell {
x: number;
y: number;
}
-/**
- * Which world plane the cells lie in. `xy` is a flat scene's own plane — the
- * one every 2D game has been navigated on. `xz` is the ground of a spatial
- * scene, whose remaining axis (height) is what {@link NavGrid.surfaceAt}
- * answers per cell.
- */
-export type NavPlane = 'xy' | 'xz';
-
export interface NavGridOptions {
/** Cell columns. */
width: number;
@@ -40,29 +34,14 @@ export interface NavGridOptions {
height: number;
/** World pixels per cell (square). */
cellSize: number;
- /** WORLD position of cell (0,0)'s centre; the plane decides which of its axes
- * the cells run along. Defaults to the world origin. */
+ /** World position of cell (0,0)'s centre. Its `z` is the depth every waypoint
+ * comes back at — the plane the scene is drawn on. Defaults to the origin. */
origin?: { x: number; y: number; z?: number };
/**
* Walkability, row-major `width * height`, 1 = walkable / 0 = blocked.
* Defaults to fully walkable. Copied in, not retained.
*/
walkable?: ArrayLike<number>;
- /** The plane the cells lie in. Defaults to `xy` — a flat scene. */
- plane?: NavPlane;
- /**
- * Height of the walkable ground in each cell, on the axis the plane leaves
- * out, row-major. Absent ⇒ every cell sits at the origin's own third axis,
- * which is what a flat scene means.
- */
- surface?: ArrayLike<number>;
- /**
- * How big a height difference between neighbouring cells an agent can cross
- * — a step it can walk up, as opposed to a ledge it would fall off. Only
- * meaningful with a `surface`; 0 (the default) lets any difference through,
- * which is what a grid with no heights has always done.
- */
- stepHeight?: number;
}
/**
@@ -70,37 +49,27 @@ export interface NavGridOptions {
* +Y; a Y-down source (e.g. a tilemap) flips rows when it builds the grid, so
* NavGrid itself stays direction-agnostic.
*/
-export class NavGrid {
+export class NavGrid implements NavSurface {
+ /** The grid lies in x/y, so off it is toward whoever is looking at the scene. */
+ readonly up: Vec3 = { x: 0, y: 0, z: 1 };
readonly width: number;
readonly height: number;
readonly cellSize: number;
- /** Cell (0,0)'s centre along the plane's first and second axes — x and y for
- * an `xy` grid, x and z for an `xz` one. Named for the plane, not the world,
- * because which world axis `v` is depends on the plane. */
- readonly originU: number;
- readonly originV: number;
- /** Where the ground sits on the axis the plane leaves out, for cells whose
- * own height is not given. */
- readonly baseHeight: number;
- readonly plane: NavPlane;
- readonly stepHeight: number;
+ /** Cell (0,0)'s centre. */
+ readonly originX: number;
+ readonly originY: number;
+ /** The depth the grid lies at — carried onto every waypoint it hands back. */
+ readonly originZ: number;
/** Row-major walkability, 1 = walkable. Mutable via {@link setWalkable}. */
readonly walkable: Uint8Array;
- /** Row-major ground height, or null when every cell sits at `baseHeight`. */
- readonly surface: Float32Array | null;
constructor(opts: NavGridOptions) {
this.width = opts.width;
this.height = opts.height;
this.cellSize = opts.cellSize;
- this.plane = opts.plane ?? 'xy';
- // The origin is a WORLD point; which of its axes the cells run along is
- // the plane's business, so it is taken apart here rather than by callers.
- const o = opts.origin;
- this.originU = o?.x ?? 0;
- this.originV = (this.plane === 'xy' ? o?.y : o?.z) ?? 0;
- this.baseHeight = (this.plane === 'xy' ? o?.z : o?.y) ?? 0;
- this.stepHeight = opts.stepHeight ?? 0;
+ this.originX = opts.origin?.x ?? 0;
+ this.originY = opts.origin?.y ?? 0;
+ this.originZ = opts.origin?.z ?? 0;
const n = this.width * this.height;
this.walkable = new Uint8Array(n);
@@ -109,7 +78,6 @@ export class NavGrid {
} else {
this.walkable.fill(1);
}
- this.surface = opts.surface ? Float32Array.from(opts.surface as ArrayLike<number>) : null;
}
index(gx: number, gy: number): number {
@@ -144,40 +112,20 @@ export class NavGrid {
private clearance_: Uint8Array | null = null;
- /** Height of the ground in cell `(gx, gy)`, on the axis the plane leaves out. */
- surfaceAt(gx: number, gy: number): number {
- if (!this.surface || !this.inBounds(gx, gy)) return this.baseHeight;
- return this.surface[gy * this.width + gx];
- }
-
- /**
- * Whether an agent can walk between two NEIGHBOURING cells. Both must be
- * walkable, and the ground between them must not step further than
- * {@link stepHeight} — a wall a metre high blocks a route that a kerb does
- * not, and a grid with no heights (or no step limit) never says no here.
- */
- canStep(fromX: number, fromY: number, toX: number, toY: number): boolean {
- if (!this.isWalkable(fromX, fromY) || !this.isWalkable(toX, toY)) return false;
- if (!this.surface || this.stepHeight <= 0) return true;
- return Math.abs(this.surfaceAt(toX, toY) - this.surfaceAt(fromX, fromY)) <= this.stepHeight;
- }
-
- /** Centre of cell `(gx, gy)` in world space, on the grid's own plane. */
+ /** Centre of cell `(gx, gy)` in world space. */
cellToWorld(gx: number, gy: number): Vec3 {
- const u = this.originU + gx * this.cellSize;
- const v = this.originV + gy * this.cellSize;
- return this.plane === 'xy'
- ? { x: u, y: v, z: this.baseHeight }
- : { x: u, y: this.surfaceAt(gx, gy), z: v };
+ return {
+ x: this.originX + gx * this.cellSize,
+ y: this.originY + gy * this.cellSize,
+ z: this.originZ,
+ };
}
/** Cell containing a world point. May be out of bounds — caller checks. */
- worldToCell(p: { x: number; y: number; z?: number }): Cell {
- const u = p.x;
- const v = this.plane === 'xy' ? p.y : (p.z ?? 0);
+ worldToCell(p: NavPoint): Cell {
return {
- x: Math.round((u - this.originU) / this.cellSize),
- y: Math.round((v - this.originV) / this.cellSize),
+ x: Math.round((p.x - this.originX) / this.cellSize),
+ y: Math.round((p.y - this.originY) / this.cellSize),
};
}
@@ -201,6 +149,54 @@ export class NavGrid {
}
return null;
}
+
+ findWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): Vec3[] | null {
+ const radius = opts?.radius ?? 0;
+ const cells = findPath(this, this.worldToCell(from), this.worldToCell(to), {
+ clearance: radius > 0 ? Math.ceil(radius / this.cellSize) : 0,
+ });
+ return cells ? pathToWorld(this, cells) : null;
+ }
+
+ /**
+ * Every walkable cell as a quad, and every edge where the walkable world
+ * stops. The corner array is reused between calls — see {@link NavSurfaceSink}.
+ */
+ describe(sink: NavSurfaceSink): void {
+ const h = this.cellSize / 2;
+ const quad: Vec3[] = [
+ { x: 0, y: 0, z: this.originZ }, { x: 0, y: 0, z: this.originZ },
+ { x: 0, y: 0, z: this.originZ }, { x: 0, y: 0, z: this.originZ },
+ ];
+ const a: Vec3 = { x: 0, y: 0, z: this.originZ };
+ const b: Vec3 = { x: 0, y: 0, z: this.originZ };
+
+ for (let gy = 0; gy < this.height; gy++) {
+ for (let gx = 0; gx < this.width; gx++) {
+ if (!this.isWalkable(gx, gy)) continue;
+ const cx = this.originX + gx * this.cellSize;
+ const cy = this.originY + gy * this.cellSize;
+ quad[0]!.x = cx - h; quad[0]!.y = cy - h;
+ quad[1]!.x = cx + h; quad[1]!.y = cy - h;
+ quad[2]!.x = cx + h; quad[2]!.y = cy + h;
+ quad[3]!.x = cx - h; quad[3]!.y = cy + h;
+ sink.face(quad);
+
+ // The four sides that face something unwalkable — the outline of
+ // where a route can go, which the faces alone do not show.
+ for (let e = 0; e < 4; e++) {
+ const dx = e === 0 ? 1 : e === 2 ? -1 : 0;
+ const dy = e === 1 ? 1 : e === 3 ? -1 : 0;
+ if (this.isWalkable(gx + dx, gy + dy)) continue;
+ const p = quad[e]!;
+ const q = quad[(e + 1) % 4]!;
+ a.x = p.x; a.y = p.y;
+ b.x = q.x; b.y = q.y;
+ sink.border(a, b);
+ }
+ }
+ }
+ }
}
/**
diff --git a/sdk/src/ai/nav/NavMesh.ts b/sdk/src/ai/nav/NavMesh.ts
new file mode 100644
index 000000000..543f73ad6
--- /dev/null
+++ b/sdk/src/ai/nav/NavMesh.ts
@@ -0,0 +1,543 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file NavMesh.ts
+ * @brief A polygon navigation mesh and the routes over it.
+ *
+ * The representation for a world made of geometry rather than cells: ground that
+ * slopes, stacks and overhangs. Its polygons are convex, so a straight line
+ * between two points of one is always walkable, and a route is therefore the
+ * DOORWAYS it goes through rather than a chain of little steps — which is why a
+ * path over a mesh comes out as a handful of turns instead of a staircase.
+ *
+ * Built by {@link buildNavMesh}; queried through {@link NavSurface} like any
+ * other navigable world.
+ */
+
+import type { Vec3 } from '../../types';
+import type { NavPoint, NavQueryOptions, NavSurface, NavSurfaceSink } from './NavSurface';
+import { MinHeap } from './minHeap';
+import { log } from '../../util/logger';
+
+export interface NavMeshData {
+ /** `vertCount * 3` world-space floats. */
+ verts: Float32Array;
+ /** `maxVertsPerPoly` vertex indices per polygon, padded with -1. */
+ polys: Int32Array;
+ /** `maxVertsPerPoly` neighbour polygon indices, one per edge, -1 for none. */
+ neis: Int32Array;
+ polyCount: number;
+ maxVertsPerPoly: number;
+ /**
+ * How far the mesh was pulled back from every wall when it was baked. An
+ * agent no wider than this fits along any route over it; the mesh IS the set
+ * of places such an agent's centre may stand.
+ */
+ agentRadius: number;
+ /**
+ * How far off the mesh a world point may be and still be taken as standing
+ * on it, in world pixels — the bake's own resolution, since a point is only
+ * ever off by the grid it was voxelised on plus the erosion.
+ */
+ snapDistance: number;
+ /**
+ * How far above or below a point a floor may be and still be the one it
+ * stands on. Over more than one floor the nearest wins; this is what makes a
+ * point with no floor anywhere near it answer "nowhere" rather than name the
+ * roof three storeys up.
+ */
+ verticalReach: number;
+}
+
+/** How much the heuristic is trusted, as Detour weights it: a straight-line
+ * distance under-estimates a route through doorways, and scaling it up trades a
+ * little optimality for a much smaller search. */
+const HEURISTIC_SCALE = 0.999;
+
+export class NavMesh implements NavSurface {
+ /** The mesh follows the ground, so off it is straight up. */
+ readonly up: Vec3 = { x: 0, y: 1, z: 0 };
+
+ readonly verts: Float32Array;
+ readonly polys: Int32Array;
+ readonly neis: Int32Array;
+ readonly polyCount: number;
+ readonly maxVertsPerPoly: number;
+ readonly agentRadius: number;
+ readonly snapDistance: number;
+ readonly verticalReach: number;
+
+ /** Polygon bounds in the ground plane, four floats each — the whole of what
+ * the lookup below needs, and cheaper to scan than the vertices. */
+ private readonly bounds: Float32Array;
+ private readonly bucketMinX: number;
+ private readonly bucketMinZ: number;
+ private readonly bucketSize: number;
+ private readonly bucketsX: number;
+ private readonly bucketsZ: number;
+ private readonly buckets: Int32Array[];
+
+ constructor(data: NavMeshData) {
+ this.verts = data.verts;
+ this.polys = data.polys;
+ this.neis = data.neis;
+ this.polyCount = data.polyCount;
+ this.maxVertsPerPoly = data.maxVertsPerPoly;
+ this.agentRadius = data.agentRadius;
+ this.snapDistance = data.snapDistance;
+ this.verticalReach = data.verticalReach;
+
+ this.bounds = new Float32Array(this.polyCount * 4);
+ let minX = Infinity, minZ = Infinity, maxX = -Infinity, maxZ = -Infinity;
+ for (let p = 0; p < this.polyCount; p++) {
+ let pminX = Infinity, pminZ = Infinity, pmaxX = -Infinity, pmaxZ = -Infinity;
+ const n = this.vertexCount(p);
+ for (let i = 0; i < n; i++) {
+ const v = this.polys[p * this.maxVertsPerPoly + i]! * 3;
+ const x = this.verts[v]!;
+ const z = this.verts[v + 2]!;
+ if (x < pminX) pminX = x;
+ if (x > pmaxX) pmaxX = x;
+ if (z < pminZ) pminZ = z;
+ if (z > pmaxZ) pmaxZ = z;
+ }
+ this.bounds[p * 4] = pminX;
+ this.bounds[p * 4 + 1] = pminZ;
+ this.bounds[p * 4 + 2] = pmaxX;
+ this.bounds[p * 4 + 3] = pmaxZ;
+ minX = Math.min(minX, pminX); maxX = Math.max(maxX, pmaxX);
+ minZ = Math.min(minZ, pminZ); maxZ = Math.max(maxZ, pmaxZ);
+ }
+
+ // A square bucket grid, roughly one bucket per polygon: point lookup is
+ // the only thing that walks the mesh without a poly to start from, and it
+ // happens once per plan rather than once per step.
+ const side = Math.max(1, Math.min(64, Math.round(Math.sqrt(this.polyCount || 1))));
+ this.bucketMinX = Number.isFinite(minX) ? minX : 0;
+ this.bucketMinZ = Number.isFinite(minZ) ? minZ : 0;
+ const spanX = Number.isFinite(maxX) ? maxX - this.bucketMinX : 0;
+ const spanZ = Number.isFinite(maxZ) ? maxZ - this.bucketMinZ : 0;
+ this.bucketSize = Math.max(1, Math.max(spanX, spanZ) / side);
+ this.bucketsX = side;
+ this.bucketsZ = side;
+
+ const lists: number[][] = Array.from({ length: side * side }, () => []);
+ for (let p = 0; p < this.polyCount; p++) {
+ const x0 = this.bucketX(this.bounds[p * 4]!);
+ const x1 = this.bucketX(this.bounds[p * 4 + 2]!);
+ const z0 = this.bucketZ(this.bounds[p * 4 + 1]!);
+ const z1 = this.bucketZ(this.bounds[p * 4 + 3]!);
+ for (let bz = z0; bz <= z1; bz++) {
+ for (let bx = x0; bx <= x1; bx++) lists[bx + bz * side]!.push(p);
+ }
+ }
+ this.buckets = lists.map(l => Int32Array.from(l));
+ }
+
+ /** How many corners polygon `p` actually has. */
+ vertexCount(p: number): number {
+ const base = p * this.maxVertsPerPoly;
+ for (let i = 0; i < this.maxVertsPerPoly; i++) {
+ if (this.polys[base + i] === -1) return i;
+ }
+ return this.maxVertsPerPoly;
+ }
+
+ /** World position of polygon `p`'s corner `i`, written into `out`. */
+ corner(p: number, i: number, out: Vec3): Vec3 {
+ const v = this.polys[p * this.maxVertsPerPoly + i]! * 3;
+ out.x = this.verts[v]!;
+ out.y = this.verts[v + 1]!;
+ out.z = this.verts[v + 2]!;
+ return out;
+ }
+
+ /** Whether `(x, z)` is inside polygon `p`, seen from above. */
+ contains(p: number, x: number, z: number): boolean {
+ const n = this.vertexCount(p);
+ const base = p * this.maxVertsPerPoly;
+ let inside = false;
+ for (let i = 0, j = n - 1; i < n; j = i++) {
+ const vi = this.polys[base + i]! * 3;
+ const vj = this.polys[base + j]! * 3;
+ const zi = this.verts[vi + 2]!;
+ const zj = this.verts[vj + 2]!;
+ if ((zi > z) === (zj > z)) continue;
+ const xi = this.verts[vi]!;
+ const xj = this.verts[vj]!;
+ if (x < (xj - xi) * (z - zi) / (zj - zi) + xi) inside = !inside;
+ }
+ return inside;
+ }
+
+ /**
+ * Height of polygon `p` at `(x, z)`. A convex polygon is not flat — its
+ * corners came off a voxel grid — so the answer comes from the triangle of
+ * the fan that covers the point, and from the nearest corner when the point
+ * is outside every one of them.
+ */
+ heightAt(p: number, x: number, z: number): number {
+ const n = this.vertexCount(p);
+ const base = p * this.maxVertsPerPoly;
+ const v0 = this.polys[base]! * 3;
+ for (let i = 1; i + 1 < n; i++) {
+ const v1 = this.polys[base + i]! * 3;
+ const v2 = this.polys[base + i + 1]! * 3;
+ const h = heightInTriangle(this.verts, v0, v1, v2, x, z);
+ if (h !== null) return h;
+ }
+ let best = this.verts[v0 + 1]!;
+ let bestD = Infinity;
+ for (let i = 0; i < n; i++) {
+ const v = this.polys[base + i]! * 3;
+ const dx = this.verts[v]! - x;
+ const dz = this.verts[v + 2]! - z;
+ const d = dx * dx + dz * dz;
+ if (d < bestD) { bestD = d; best = this.verts[v + 1]!; }
+ }
+ return best;
+ }
+
+ /**
+ * The polygon a world point stands on, or -1. A point over more than one —
+ * under a bridge, on a balcony — belongs to the floor nearest its own height,
+ * which is the whole reason this mesh exists.
+ */
+ findPoly(p: NavPoint, out?: Vec3): number {
+ const x = p.x;
+ const z = p.z ?? 0;
+ const y = p.y;
+ const reach = this.snapDistance;
+ let best = -1;
+ let bestScore = Infinity;
+ let bestY = 0;
+ let nearest = -1;
+ let nearestScore = reach * reach;
+ let nearestX = 0, nearestY = 0, nearestZ = 0;
+
+ const x0 = this.bucketX(x - reach);
+ const x1 = this.bucketX(x + reach);
+ const z0 = this.bucketZ(z - reach);
+ const z1 = this.bucketZ(z + reach);
+ for (let bz = z0; bz <= z1; bz++) {
+ for (let bx = x0; bx <= x1; bx++) {
+ for (const poly of this.buckets[bx + bz * this.bucketsX]!) {
+ if (x < this.bounds[poly * 4]! - reach || x > this.bounds[poly * 4 + 2]! + reach
+ || z < this.bounds[poly * 4 + 1]! - reach
+ || z > this.bounds[poly * 4 + 3]! + reach) continue;
+ if (this.contains(poly, x, z)) {
+ const h = this.heightAt(poly, x, z);
+ const score = Math.abs(h - y);
+ if (score <= this.verticalReach && score < bestScore) {
+ bestScore = score; best = poly; bestY = h;
+ }
+ continue;
+ }
+ if (best !== -1) continue;
+ const d = this.distanceToEdges(poly, x, y, z, EDGE_HIT);
+ if (d >= nearestScore) continue;
+ nearestScore = d;
+ nearest = poly;
+ nearestX = EDGE_HIT[0]!; nearestY = EDGE_HIT[1]!; nearestZ = EDGE_HIT[2]!;
+ }
+ }
+ }
+
+ if (best !== -1) {
+ if (out) { out.x = x; out.y = bestY; out.z = z; }
+ return best;
+ }
+ if (nearest !== -1 && out) { out.x = nearestX; out.y = nearestY; out.z = nearestZ; }
+ return nearest;
+ }
+
+ /** Squared distance from a point to polygon `p`'s boundary, with the closest
+ * point on it written into `hit`. */
+ private distanceToEdges(p: number, x: number, y: number, z: number, hit: Float64Array): number {
+ const n = this.vertexCount(p);
+ const base = p * this.maxVertsPerPoly;
+ let best = Infinity;
+ for (let i = 0, j = n - 1; i < n; j = i++) {
+ const a = this.polys[base + j]! * 3;
+ const b = this.polys[base + i]! * 3;
+ const ax = this.verts[a]!, ay = this.verts[a + 1]!, az = this.verts[a + 2]!;
+ const bx = this.verts[b]!, by = this.verts[b + 1]!, bz = this.verts[b + 2]!;
+ const ex = bx - ax, ey = by - ay, ez = bz - az;
+ const len = ex * ex + ey * ey + ez * ez;
+ let t = len > 0 ? ((x - ax) * ex + (y - ay) * ey + (z - az) * ez) / len : 0;
+ t = t < 0 ? 0 : t > 1 ? 1 : t;
+ const cx = ax + ex * t, cy = ay + ey * t, cz = az + ez * t;
+ const d = (cx - x) ** 2 + (cy - y) ** 2 + (cz - z) ** 2;
+ if (d < best) { best = d; hit[0] = cx; hit[1] = cy; hit[2] = cz; }
+ }
+ return best;
+ }
+
+ findWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): Vec3[] | null {
+ const radius = opts?.radius ?? 0;
+ if (radius > this.agentRadius + 1e-3) warnRadius(radius, this.agentRadius);
+
+ const start: Vec3 = { x: 0, y: 0, z: 0 };
+ const end: Vec3 = { x: 0, y: 0, z: 0 };
+ const startPoly = this.findPoly(from, start);
+ const endPoly = this.findPoly(to, end);
+ if (startPoly < 0 || endPoly < 0) return null;
+ if (startPoly === endPoly) return [start, end];
+
+ const polyPath = this.findPolyPath(startPoly, endPoly, start, end);
+ if (!polyPath) return null;
+ return this.straightPath(polyPath, start, end);
+ }
+
+ /** A* over the polygon graph, keyed on where each doorway is crossed. */
+ private findPolyPath(startPoly: number, endPoly: number, start: Vec3, end: Vec3): number[] | null {
+ const n = this.polyCount;
+ const cost = new Float64Array(n).fill(Infinity);
+ const parent = new Int32Array(n).fill(-1);
+ const closed = new Uint8Array(n);
+ // Where the search entered each polygon — a doorway midpoint, or the
+ // start itself. Costs measured between these are what a route through
+ // the polygon actually costs, rather than its centre-to-centre distance.
+ const enterX = new Float64Array(n);
+ const enterY = new Float64Array(n);
+ const enterZ = new Float64Array(n);
+
+ cost[startPoly] = 0;
+ enterX[startPoly] = start.x; enterY[startPoly] = start.y; enterZ[startPoly] = start.z;
+ const heap = new MinHeap(n);
+ heap.push(startPoly, distance(start.x, start.y, start.z, end.x, end.y, end.z));
+
+ const a: Vec3 = { x: 0, y: 0, z: 0 };
+ const b: Vec3 = { x: 0, y: 0, z: 0 };
+
+ while (heap.size > 0) {
+ const cur = heap.pop();
+ if (cur === endPoly) break;
+ if (closed[cur]) continue;
+ closed[cur] = 1;
+
+ const vcount = this.vertexCount(cur);
+ for (let e = 0; e < vcount; e++) {
+ const next = this.neis[cur * this.maxVertsPerPoly + e]!;
+ if (next < 0 || closed[next]) continue;
+ this.corner(cur, e, a);
+ this.corner(cur, (e + 1) % vcount, b);
+ const mx = (a.x + b.x) / 2;
+ const my = (a.y + b.y) / 2;
+ const mz = (a.z + b.z) / 2;
+ const g = cost[cur]! + distance(enterX[cur]!, enterY[cur]!, enterZ[cur]!, mx, my, mz);
+ if (g >= cost[next]!) continue;
+ cost[next] = g;
+ parent[next] = cur;
+ enterX[next] = mx; enterY[next] = my; enterZ[next] = mz;
+ const h = next === endPoly
+ ? distance(mx, my, mz, end.x, end.y, end.z)
+ : distance(mx, my, mz, end.x, end.y, end.z) * HEURISTIC_SCALE;
+ heap.push(next, g + h);
+ }
+ }
+
+ if (parent[endPoly] === -1 && endPoly !== startPoly) return null;
+ const path: number[] = [];
+ for (let p = endPoly; p !== -1; p = parent[p]!) {
+ path.push(p);
+ if (p === startPoly) break;
+ }
+ path.reverse();
+ return path[0] === startPoly ? path : null;
+ }
+
+ /**
+ * Pull the route taut through the doorways it crosses — the funnel algorithm.
+ * Without it a path is the chain of polygon midpoints the search happened to
+ * visit; with it, it is the shortest line that stays inside them, and the
+ * only corners left are the ones an agent really has to turn at.
+ */
+ private straightPath(polyPath: number[], start: Vec3, end: Vec3): Vec3[] {
+ const left: Vec3[] = [{ ...start }];
+ const right: Vec3[] = [{ ...start }];
+ for (let i = 0; i + 1 < polyPath.length; i++) {
+ const from = polyPath[i]!;
+ const to = polyPath[i + 1]!;
+ const vcount = this.vertexCount(from);
+ let edge = -1;
+ for (let e = 0; e < vcount; e++) {
+ if (this.neis[from * this.maxVertsPerPoly + e] === to) { edge = e; break; }
+ }
+ if (edge === -1) break;
+ left.push(this.corner(from, edge, { x: 0, y: 0, z: 0 }));
+ right.push(this.corner(from, (edge + 1) % vcount, { x: 0, y: 0, z: 0 }));
+ }
+ left.push({ ...end });
+ right.push({ ...end });
+
+ const out: Vec3[] = [{ ...start }];
+ const atPortal: number[] = [0];
+ let apex = start;
+ let portalLeft = left[0]!;
+ let portalRight = right[0]!;
+ let apexIndex = 0;
+ let leftIndex = 0;
+ let rightIndex = 0;
+
+ for (let i = 1; i < left.length; i++) {
+ const l = left[i]!;
+ const r = right[i]!;
+
+ if (triArea2D(apex, portalRight, r) <= 0) {
+ if (same(apex, portalRight) || triArea2D(apex, portalLeft, r) > 0) {
+ portalRight = r;
+ rightIndex = i;
+ } else {
+ out.push({ ...portalLeft });
+ atPortal.push(leftIndex);
+ apex = portalLeft;
+ apexIndex = leftIndex;
+ portalLeft = apex;
+ portalRight = apex;
+ leftIndex = apexIndex;
+ rightIndex = apexIndex;
+ i = apexIndex;
+ continue;
+ }
+ }
+
+ if (triArea2D(apex, portalLeft, l) >= 0) {
+ if (same(apex, portalLeft) || triArea2D(apex, portalRight, l) < 0) {
+ portalLeft = l;
+ leftIndex = i;
+ } else {
+ out.push({ ...portalRight });
+ atPortal.push(rightIndex);
+ apex = portalRight;
+ apexIndex = rightIndex;
+ portalLeft = apex;
+ portalRight = apex;
+ leftIndex = apexIndex;
+ rightIndex = apexIndex;
+ i = apexIndex;
+ continue;
+ }
+ }
+ }
+
+ if (!same(out[out.length - 1]!, end)) {
+ out.push({ ...end });
+ atPortal.push(left.length - 1);
+ }
+ return followGround(out, atPortal, left, right);
+ }
+
+ describe(sink: NavSurfaceSink): void {
+ const corners: Vec3[] = [];
+ for (let p = 0; p < this.polyCount; p++) {
+ const n = this.vertexCount(p);
+ corners.length = 0;
+ for (let i = 0; i < n; i++) corners.push(this.corner(p, i, { x: 0, y: 0, z: 0 }));
+ sink.face(corners);
+ for (let i = 0; i < n; i++) {
+ if (this.neis[p * this.maxVertsPerPoly + i] !== -1) continue;
+ sink.border(corners[i]!, corners[(i + 1) % n]!);
+ }
+ }
+ }
+
+ private bucketX(x: number): number {
+ const b = Math.floor((x - this.bucketMinX) / this.bucketSize);
+ return b < 0 ? 0 : b >= this.bucketsX ? this.bucketsX - 1 : b;
+ }
+
+ private bucketZ(z: number): number {
+ const b = Math.floor((z - this.bucketMinZ) / this.bucketSize);
+ return b < 0 ? 0 : b >= this.bucketsZ ? this.bucketsZ - 1 : b;
+ }
+}
+
+const EDGE_HIT = new Float64Array(3);
+
+/**
+ * Put the taut route back on the ground. The funnel answers in the ground plane,
+ * so one of its segments can cut straight over a hill the polygons under it
+ * climb; every doorway it crosses has a known height there, and adding those back
+ * follows the floor without bending anywhere the route did not already turn.
+ */
+function followGround(
+ corners: Vec3[], atPortal: number[], left: Vec3[], right: Vec3[],
+): Vec3[] {
+ const out: Vec3[] = [corners[0]!];
+ for (let k = 0; k + 1 < corners.length; k++) {
+ const a = corners[k]!;
+ const b = corners[k + 1]!;
+ for (let q = atPortal[k]! + 1; q < atPortal[k + 1]!; q++) {
+ const p = left[q]!;
+ const r = right[q]!;
+ const cross = crossSegments2D(a, b, p, r);
+ if (!cross) continue;
+ const y = p.y + (r.y - p.y) * cross.s;
+ const lerped = a.y + (b.y - a.y) * cross.t;
+ if (Math.abs(y - lerped) < GROUND_TOLERANCE) continue;
+ out.push({ x: a.x + (b.x - a.x) * cross.t, y, z: a.z + (b.z - a.z) * cross.t });
+ }
+ out.push(b);
+ }
+ return out;
+}
+
+/** How far a route may float over or under the floor before a waypoint is put in
+ * to pull it down, in world pixels — a centimetre at a hundred to the metre. */
+const GROUND_TOLERANCE = 1;
+
+/** Where two segments cross in the ground plane, as the fraction along each. */
+function crossSegments2D(a: Vec3, b: Vec3, p: Vec3, q: Vec3): { t: number; s: number } | null {
+ const abx = b.x - a.x, abz = b.z - a.z;
+ const pqx = q.x - p.x, pqz = q.z - p.z;
+ const denom = abx * pqz - abz * pqx;
+ if (Math.abs(denom) < 1e-9) return null;
+ const t = ((p.x - a.x) * pqz - (p.z - a.z) * pqx) / denom;
+ const s = ((p.x - a.x) * abz - (p.z - a.z) * abx) / denom;
+ if (t <= 0 || t >= 1 || s < 0 || s > 1) return null;
+ return { t, s };
+}
+
+function distance(ax: number, ay: number, az: number, bx: number, by: number, bz: number): number {
+ return Math.sqrt((bx - ax) ** 2 + (by - ay) ** 2 + (bz - az) ** 2);
+}
+
+/** Twice the signed area of a triangle in the ground plane — the funnel's whole
+ * arithmetic, and the reason polygon winding has to be settled at bake time. */
+function triArea2D(a: Vec3, b: Vec3, c: Vec3): number {
+ return (c.x - a.x) * (b.z - a.z) - (b.x - a.x) * (c.z - a.z);
+}
+
+function same(a: Vec3, b: Vec3): boolean {
+ return Math.abs(a.x - b.x) < 1e-4 && Math.abs(a.z - b.z) < 1e-4;
+}
+
+/** Height of `(x, z)` on the plane of a triangle, or null when it is outside. */
+function heightInTriangle(
+ verts: Float32Array, a: number, b: number, c: number, x: number, z: number,
+): number | null {
+ const ax = verts[a]!, az = verts[a + 2]!;
+ const v0x = verts[c]! - ax, v0z = verts[c + 2]! - az;
+ const v1x = verts[b]! - ax, v1z = verts[b + 2]! - az;
+ const v2x = x - ax, v2z = z - az;
+ const denom = v0x * v1z - v1x * v0z;
+ if (Math.abs(denom) < 1e-9) return null;
+ const u = (v1z * v2x - v1x * v2z) / denom;
+ const v = (v0x * v2z - v0z * v2x) / denom;
+ const epsilon = 1e-4;
+ if (u < -epsilon || v < -epsilon || u + v > 1 + epsilon) return null;
+ return verts[a + 1]! + (verts[c + 1]! - verts[a + 1]!) * u + (verts[b + 1]! - verts[a + 1]!) * v;
+}
+
+let radiusWarned = false;
+
+/** Said once: an agent wider than the mesh was baked for is a bake setting to
+ * change, not a per-frame condition, and repeating it every plan would bury it. */
+function warnRadius(radius: number, baked: number): void {
+ if (radiusWarned) return;
+ radiusWarned = true;
+ log.warn('nav', `a NavAgent has radius ${radius} but the mesh was baked for ${baked}`
+ + ' — routes will be planned as if it were the narrower one; raise the'
+ + " NavVolume's agentRadius to plan for this agent");
+}
diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.ts
index cdfc1b273..1ec157eca 100644
--- a/sdk/src/ai/nav/NavPlugin.ts
+++ b/sdk/src/ai/nav/NavPlugin.ts
@@ -2,18 +2,19 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file NavPlugin.ts
- * @brief Drives NavAgents: plan-on-demand + kinematic path following.
+ * @brief Bakes NavVolumes and drives NavAgents: plan-on-demand + kinematic
+ * path following.
*
* One system, gated to play mode. Per-entity runtime path lives in a closure
* Map (the `defineBehavior` pattern) so the NavAgent component stays purely
* authorable/serializable. The per-frame logic is `stepNavigation`, extracted
* so it unit-tests against a fake world. MVP integrates the Transform directly
* (kinematic); physics `moveCharacter` avoidance is a later stage
- * (REARCH_GAMEPLAY_AI.md AI4) — the grid path already clears static blockers.
+ * (REARCH_GAMEPLAY_AI.md AI4) — the planned route already clears static blockers.
*/
import type { App, Plugin } from '../../app/app';
-import type { Entity } from '../../types';
+import type { Entity, Vec3 } from '../../types';
import { defineSystem, Schedule, GetWorld } from '../../ecs/system';
import { Res, Time, type TimeData } from '../../ecs/resource';
import {
@@ -22,20 +23,18 @@ import {
type ComponentData,
} from '../../ecs/component';
import { playModeOnly } from '../../ecs/env';
-import {
- Physics3D, Physics3DRuntime, type Physics3DRuntime as Physics3DRuntimeData,
-} from '../../physics3d/Physics3DPlugin';
import { log } from '../../util/logger';
import { Navigation, Nav } from './Navigation';
import { NavAgent } from './NavAgent';
import { NavVolume } from './NavVolume';
-import { bakeNavGrid, type GroundProbe } from './bakeNavGrid';
+import { buildNavMesh } from './navmesh/build';
+import { collectNavGeometry, navGeometryReady, type NavGeometry } from './navGeometry';
import { setupNavDebugDraw } from './NavDebugDraw';
import { advanceAlongPath } from './follow';
/** Per-entity runtime path state, owned by the driving system (not serialized). */
export interface AgentRuntime {
- waypoints: import('../../types').Vec3[];
+ waypoints: Vec3[];
index: number;
plannedX: number;
plannedY: number;
@@ -44,41 +43,51 @@ export interface AgentRuntime {
reachable: boolean;
}
+/** Where the bake gets its triangles. Null until the world can answer — a mesh
+ * collider has none until its asset has loaded, and a volume is baked once. */
+export type NavGeometryProvider = (min: Vec3, max: Vec3, layers: number) => NavGeometry;
+
/**
- * Bake the first NavVolume that has not been baked yet, and install its grid.
- * `probe` is null until the caller has a world worth sampling (see the plugin):
- * a bake against a solver with no bodies yet returns a grid of holes, and one
- * bake per volume means it would stay that way.
+ * Bake the first NavVolume that has not been baked yet, and install its mesh.
*/
export function bakeVolumes(
world: NavWorldView,
nav: Navigation,
- probe: GroundProbe | null,
+ geometry: NavGeometryProvider | null,
baked: Set<Entity>,
): void {
- if (!probe) return;
+ if (!geometry) return;
for (const entity of world.getEntitiesWithComponents([NavVolume, Transform])) {
if (baked.has(entity)) continue;
const volume = world.get(entity, NavVolume);
+ // The volume is placed in the same space the geometry is collected in.
const at = world.get(entity, Transform).position;
const h = volume.halfExtents;
- nav.setGrid(bakeNavGrid(probe, {
- min: { x: at.x - h.x, y: at.y - h.y, z: at.z - h.z },
- max: { x: at.x + h.x, y: at.y + h.y, z: at.z + h.z },
+ const min = { x: at.x - h.x, y: at.y - h.y, z: at.z - h.z };
+ const max = { x: at.x + h.x, y: at.y + h.y, z: at.z + h.z };
+
+ const geo = geometry(min, max, volume.layers);
+ baked.add(entity);
+
+ const mesh = buildNavMesh(geo.verts, geo.indices, {
+ min, max,
cellSize: volume.cellSize,
+ cellHeight: volume.cellHeight,
maxSlopeDegrees: volume.maxSlopeDegrees,
agentHeight: volume.agentHeight,
+ agentRadius: volume.agentRadius,
stepHeight: volume.stepHeight,
- layers: volume.layers,
- }));
- baked.add(entity);
+ });
+ nav.setSurface(mesh);
+
// Baked once, so a volume that found nothing stays empty: say so rather
// than leave a scene with agents that never move and no reason given.
- if (!nav.grid?.walkable.some(w => w === 1)) {
- log.warn('nav', `NavVolume on entity ${entity} baked no walkable ground —`
- + ' check that it covers the floor and that `layers` includes it');
+ if (mesh.polyCount === 0) {
+ log.warn('nav', `NavVolume on entity ${entity} baked no walkable ground from `
+ + `${geo.bodyCount} static bodies — check that it covers the floor, that the`
+ + ' floor is a STATIC RigidBody3D, and that `layers` includes it');
}
- // One grid is installed at a time, so a scene with two volumes would have
+ // One mesh is installed at a time, so a scene with two volumes would have
// the last one win. Bake one per frame and let the newest be the active
// one rather than silently merging boxes that may not touch.
return;
@@ -126,7 +135,7 @@ export function stepNavigation(
);
rt = {
waypoints: path ?? [],
- // Skip the start cell center to avoid backtracking toward it.
+ // Skip the start point to avoid stepping back toward it.
index: path && path.length > 1 ? 1 : 0,
plannedX: agent.targetX,
plannedY: agent.targetY,
@@ -168,8 +177,8 @@ export class NavPlugin implements Plugin {
build(app: App): void {
app.insertResource(Nav, new Navigation());
- // Installed with the grid, drawn only once a game turns the resource on —
- // the same bargain the 3D physics overlay makes.
+ // Installed with the surface, drawn only once a game turns the resource
+ // on — the same bargain the 3D physics overlay makes.
setupNavDebugDraw(app);
const runtimes = new Map<Entity, AgentRuntime>();
@@ -184,15 +193,14 @@ export class NavPlugin implements Plugin {
defineSystem(
[Res(Nav), Res(Time), GetWorld()],
(nav: Navigation, time: TimeData, world) => {
- // A NavVolume takes its grid from the 3D solver. Waiting for a
- // BODY, not for the queries resource: that appears when the
- // module loads, bodies only when it first steps.
- const runtime = app.hasResource(Physics3DRuntime)
- ? app.getResource<Physics3DRuntimeData>(Physics3DRuntime) : null;
- const populated = (runtime?.bodies.size ?? 0) > 0;
- const probe = populated && app.hasResource(Physics3D)
- ? app.getResource<GroundProbe | null>(Physics3D) : null;
- bakeVolumes(world as NavWorldView, nav, probe, baked);
+ // A NavVolume is baked from the colliders a scene authors, so
+ // there is no solver to wait for — only the mesh assets some
+ // of those colliders read, which arrive when they arrive.
+ const provider = navGeometryReady(app.world)
+ ? (min: Vec3, max: Vec3, layers: number) =>
+ collectNavGeometry(app.world, { min, max, layers })
+ : null;
+ bakeVolumes(world as NavWorldView, nav, provider, baked);
stepNavigation(world as NavWorldView, nav, time.delta, runtimes);
},
{
diff --git a/sdk/src/ai/nav/NavSurface.ts b/sdk/src/ai/nav/NavSurface.ts
new file mode 100644
index 000000000..eba91823f
--- /dev/null
+++ b/sdk/src/ai/nav/NavSurface.ts
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file NavSurface.ts
+ * @brief What "somewhere an agent can walk" means to everything that uses one.
+ *
+ * There are two honest representations of a navigable world and they do not
+ * overlap. A uniform GRID is what a tilemap already is — authored cell by cell,
+ * editable a cell at a time while the game runs, and exactly as accurate as the
+ * tiles it came from. A polygon MESH is what arbitrary geometry reduces to —
+ * it follows sloped and multi-level ground, which no single grid can, and its
+ * cost is that it is baked rather than poked.
+ *
+ * Everything above them asks the same three questions, so they meet here and not
+ * in each consumer: the agent driver, the resource games query, the running
+ * overlay and the editor viewport all speak to a `NavSurface` and never learn
+ * which kind they were handed.
+ */
+
+import type { Vec3 } from '../../types';
+
+/** A world point a caller may name in two axes — a flat scene has no third. */
+export interface NavPoint {
+ x: number;
+ y: number;
+ z?: number;
+}
+
+export interface NavQueryOptions {
+ /**
+ * How wide the body being routed is, in world pixels. A path planned for a
+ * point is a path only the centre of an agent fits through. 0 (the default)
+ * plans for a point.
+ */
+ radius?: number;
+}
+
+/**
+ * Where a surface hands out its shape, for a drawer to turn into lines. A
+ * visitor rather than a returned array because the caller is a per-frame overlay
+ * over thousands of faces: the corner array a `face` call is given belongs to
+ * the surface and is only valid until that call returns.
+ */
+export interface NavSurfaceSink {
+ /** One walkable face — a closed convex polygon, in world space. */
+ face(corners: readonly Vec3[]): void;
+ /** An edge the walkable world STOPS at: a wall, a ledge, a drop. */
+ border(a: Vec3, b: Vec3): void;
+}
+
+/** The active navigable world, however it was built. */
+export interface NavSurface {
+ /**
+ * Which way is OFF the ground here — the direction anything drawn ON this
+ * surface is lifted along so it does not fight the floor for pixels. A flat
+ * grid's is +Z, toward the viewer of a scene laid out in x/y; a spatial
+ * mesh's is +Y, out of the ground it follows.
+ */
+ readonly up: Vec3;
+
+ /**
+ * Plan a world-space route between two world points, or null when there is
+ * no way. The waypoints carry all three axes: on a flat surface the third is
+ * the plane the scene is drawn on, on a spatial one it is the ground the
+ * route walks over.
+ */
+ findWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): Vec3[] | null;
+
+ /** Hand the shape of the walkable world to a drawer. */
+ describe(sink: NavSurfaceSink): void;
+}
diff --git a/sdk/src/ai/nav/NavVolume.ts b/sdk/src/ai/nav/NavVolume.ts
index 9b083dd25..68a661819 100644
--- a/sdk/src/ai/nav/NavVolume.ts
+++ b/sdk/src/ai/nav/NavVolume.ts
@@ -2,13 +2,16 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file NavVolume.ts
- * @brief The box a navigation grid is baked over — where a scene SAYS its
+ * @brief The box a navigation mesh is baked over — where a scene SAYS its
* agents may walk.
*
* Authored, not coded. A flat scene builds its grid from a tilemap, which is
* already data; a spatial one has only geometry, and asking every game to write
* the bake by hand would put the one thing agents depend on outside the scene
* that describes them.
+ *
+ * Every field here is a fact about the AGENT or about how finely the world is
+ * measured — never about the route, which is what the bake works out from them.
*/
import { defineComponent } from '../../ecs/component';
@@ -17,12 +20,19 @@ import type { Vec3 } from '../../types';
export interface NavVolumeData {
/** Half-extents of the box, in world pixels; the entity's Transform is its centre. */
halfExtents: Vec3;
- /** World pixels per cell. Smaller is a finer route and a slower bake. */
+ /** Voxel size in the ground plane, in world pixels. Smaller is a mesh that
+ * hugs the geometry more closely, and a slower bake. */
cellSize: number;
+ /** Voxel size vertically, in world pixels. This is what decides whether a
+ * balcony and the floor under it are two levels or one. */
+ cellHeight: number;
/** Steepest ground an agent can stand on, in degrees from level. */
maxSlopeDegrees: number;
- /** Headroom an agent needs; a cell with less is not walkable. 0 skips the check. */
+ /** Headroom an agent needs; ground with less is not walkable. */
agentHeight: number;
+ /** How wide the agent is. The mesh is pulled back from every wall by this, so
+ * a route over it clears the walls without the planner doing anything. */
+ agentRadius: number;
/** Height difference between neighbouring cells an agent can climb. */
stepHeight: number;
/** Physics layers the ground is on; 0 = every layer. */
@@ -32,17 +42,21 @@ export interface NavVolumeData {
export const NavVolume = defineComponent<NavVolumeData>('NavVolume', {
halfExtents: { x: 1000, y: 500, z: 1000 },
cellSize: 50,
+ cellHeight: 10,
maxSlopeDegrees: 45,
agentHeight: 180,
+ agentRadius: 30,
stepHeight: 40,
layers: 0,
}, {
fields: {
halfExtents: { unit: 'px', category: 'Navigation' },
cellSize: { min: 1, unit: 'px', category: 'Navigation' },
+ cellHeight: { min: 1, unit: 'px', category: 'Navigation', tooltip: 'Vertical voxel size; what separates one level from the one above it.' },
maxSlopeDegrees: { min: 0, max: 89, unit: '°', category: 'Navigation' },
- agentHeight: { min: 0, unit: 'px', category: 'Navigation', tooltip: 'Headroom an agent needs; 0 skips the ceiling check.' },
+ agentHeight: { min: 0, unit: 'px', category: 'Navigation', tooltip: 'Headroom an agent needs to walk somewhere.' },
+ agentRadius: { min: 0, unit: 'px', category: 'Navigation', tooltip: 'How wide the agent is; the mesh is pulled back from walls by this.' },
stepHeight: { min: 0, unit: 'px', category: 'Navigation' },
- layers: { min: 0, category: 'Navigation', advanced: true, tooltip: 'Layer mask the ground rays are cast against; 0 = every layer.' },
+ layers: { min: 0, category: 'Navigation', advanced: true, tooltip: 'Layer mask the ground is taken from; 0 = every layer.' },
},
});
diff --git a/sdk/src/ai/nav/Navigation.ts b/sdk/src/ai/nav/Navigation.ts
index 5b35b9aa8..d6c67a4bb 100644
--- a/sdk/src/ai/nav/Navigation.ts
+++ b/sdk/src/ai/nav/Navigation.ts
@@ -2,52 +2,36 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file Navigation.ts
- * @brief `Nav` resource — holds the active NavGrid and world-space pathfinding.
+ * @brief `Nav` resource — holds the active {@link NavSurface} and routes over it.
*
* Published by NavPlugin; game code reads it as `Res(Nav)` (or
- * `app.getResource(Nav)`) to swap the grid or query a path directly.
+ * `app.getResource(Nav)`) to swap the surface or query a route directly. It does
+ * not say which kind of surface is installed, because nothing above it should
+ * have to branch on that.
*/
import { defineResource } from '../../ecs/resource';
import type { Vec3 } from '../../types';
-import { NavGrid } from './NavGrid';
-import { findPath, pathToWorld, type PathfindOptions } from './pathfind';
+import type { NavPoint, NavQueryOptions, NavSurface } from './NavSurface';
export class Navigation {
- /** The active navigation grid, or null until one is built and installed. */
- grid: NavGrid | null = null;
+ /** Where agents may walk, or null until something builds and installs it. */
+ surface: NavSurface | null = null;
- setGrid(grid: NavGrid | null): void {
- this.grid = grid;
+ setSurface(surface: NavSurface | null): void {
+ this.surface = surface;
}
- hasGrid(): boolean {
- return this.grid !== null;
+ hasSurface(): boolean {
+ return this.surface !== null;
}
/**
- * Plan a world-space path (cell-centre waypoints) between two world points,
- * or null if there is no grid or no route. `radius` is the body being
- * routed, in world units: a path planned for a point is a path only the
- * centre of an agent fits through.
- *
- * The waypoints carry all three axes: on a flat grid the third is the plane
- * the scene is drawn on, and on a spatial one it is the height of the ground
- * the route walks over.
+ * Plan a world-space route, or null if there is no surface or no way. See
+ * {@link NavSurface.findWorldPath} for what the waypoints carry.
*/
- findWorldPath(
- from: { x: number; y: number; z?: number },
- to: { x: number; y: number; z?: number },
- opts?: PathfindOptions & { radius?: number },
- ): Vec3[] | null {
- const grid = this.grid;
- if (!grid) return null;
- const start = grid.worldToCell(from);
- const goal = grid.worldToCell(to);
- const radius = opts?.radius ?? 0;
- const clearance = opts?.clearance ?? (radius > 0 ? Math.ceil(radius / grid.cellSize) : 0);
- const cells = findPath(grid, start, goal, { ...opts, clearance });
- return cells ? pathToWorld(grid, cells) : null;
+ findWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): Vec3[] | null {
+ return this.surface ? this.surface.findWorldPath(from, to, opts) : null;
}
}
diff --git a/sdk/src/ai/nav/bakeNavGrid.ts b/sdk/src/ai/nav/bakeNavGrid.ts
deleted file mode 100644
index fcbb192e5..000000000
--- a/sdk/src/ai/nav/bakeNavGrid.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file bakeNavGrid.ts
- * @brief Build a ground-plane {@link NavGrid} by asking the 3D solver what is
- * under each cell.
- *
- * The bodies a scene already collides against ARE its walkable surface, so this
- * takes them as the source rather than a second authored description that can
- * disagree with them. One ray straight down per cell answers three questions at
- * once: whether there is ground, how high it is, and how steeply it is tilted.
- *
- * What this is NOT: it samples ONE surface per column, so a bridge and the road
- * under it collapse into whichever the ray meets first. Multi-level navigation
- * wants a real navmesh (voxelise → regions → contours), which this deliberately
- * is not — it is the whole of what a heightfield can honestly answer.
- */
-
-import type { Vec3 } from '../../types';
-import { NavGrid } from './NavGrid';
-
-/** One downward hit: the height of the ground and how it is tilted. */
-export interface GroundHit {
- /** World height of the point hit. */
- y: number;
- /** The surface normal's up component, 1 = level, 0 = a vertical wall. */
- normalY: number;
-}
-
-/**
- * What the baker needs from a solver — a ray, and what it hit. `Physics3DQueries`
- * satisfies it as it stands; a test satisfies it with a function.
- */
-export interface GroundProbe {
- raycast(origin: Vec3, direction: Vec3, layerMask?: number): GroundHit | null;
-}
-
-export interface BakeNavGridOptions {
- /** The box of world to sample, in world pixels. */
- min: Vec3;
- max: Vec3;
- /** World pixels per cell (square, in the x/z plane). */
- cellSize: number;
- /**
- * Steepest ground an agent can stand on, in degrees from level. Anything
- * steeper is a wall it walks past, not a slope it walks up.
- */
- maxSlopeDegrees?: number;
- /**
- * How much room an agent needs above the ground. A cell whose ceiling is
- * lower than this is not walkable however flat its floor is — a crawlspace
- * is not a corridor. 0 skips the check (and its second ray per cell).
- */
- agentHeight?: number;
- /** Height difference between neighbours an agent can cross — see NavGrid. */
- stepHeight?: number;
- /** Physics layers the ground is on; 0 (default) = every layer. */
- layers?: number;
-}
-
-/**
- * Sample the solver into a walkable grid over the x/z plane. Every cell centre
- * gets one ray straight down: no hit is a hole, too steep a hit is a wall, too
- * low a ceiling is a crawlspace. What survives is walkable at the height the ray
- * found, which is the surface the agent then walks along.
- */
-export function bakeNavGrid(probe: GroundProbe, opts: BakeNavGridOptions): NavGrid {
- const { min, max, cellSize } = opts;
- const layers = opts.layers ?? 0;
- const agentHeight = opts.agentHeight ?? 0;
- const cosMaxSlope = Math.cos(((opts.maxSlopeDegrees ?? 45) * Math.PI) / 180);
- const depth = max.y - min.y;
-
- const width = Math.max(1, Math.floor((max.x - min.x) / cellSize) + 1);
- const height = Math.max(1, Math.floor((max.z - min.z) / cellSize) + 1);
- const walkable = new Uint8Array(width * height);
- const surface = new Float32Array(width * height);
-
- for (let gy = 0; gy < height; gy++) {
- for (let gx = 0; gx < width; gx++) {
- const i = gy * width + gx;
- const x = min.x + gx * cellSize;
- const z = min.z + gy * cellSize;
- surface[i] = min.y;
-
- const ground = probe.raycast({ x, y: max.y, z }, { x: 0, y: -depth, z: 0 }, layers);
- if (!ground) continue;
- surface[i] = ground.y;
- // Level ground has a normal pointing straight up; the steeper it is,
- // the smaller that component, which is the cosine of the slope.
- if (ground.normalY < cosMaxSlope) continue;
- if (agentHeight > 0) {
- // From just above the floor, so the floor itself is not the ceiling.
- const from = { x, y: ground.y + CEILING_EPSILON, z };
- if (probe.raycast(from, { x: 0, y: agentHeight, z: 0 }, layers)) continue;
- }
- walkable[i] = 1;
- }
- }
-
- return new NavGrid({
- width, height, cellSize,
- origin: { x: min.x, y: min.y, z: min.z },
- plane: 'xz',
- walkable, surface,
- stepHeight: opts.stepHeight ?? 0,
- });
-}
-
-/** How far off the floor the headroom ray starts — enough to leave the surface
- * it was just cast onto, small next to any agent worth the check. */
-const CEILING_EPSILON = 1;
diff --git a/sdk/src/ai/nav/index.ts b/sdk/src/ai/nav/index.ts
index 48bf2804c..df0b42281 100644
--- a/sdk/src/ai/nav/index.ts
+++ b/sdk/src/ai/nav/index.ts
@@ -2,22 +2,25 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file index.ts
- * @brief Navigation barrel — grid, A*, tilemap builder, agent, plugin.
+ * @brief Navigation barrel — the surface, its two shapes, and what drives them.
*/
-export { NavGrid, type NavGridOptions, type NavPlane, type Cell } from './NavGrid';
+export type {
+ NavSurface, NavSurfaceSink, NavQueryOptions, NavPoint,
+} from './NavSurface';
+export { NavGrid, type NavGridOptions, type Cell } from './NavGrid';
export { findPath, pathToWorld, type PathfindOptions } from './pathfind';
export {
navGridFromTiles,
navGridFromTilemapLayer,
type BuildNavGridOptions,
} from './navGridFromTilemap';
+export { NavMesh, type NavMeshData } from './NavMesh';
+export { buildNavMesh, type BuildNavMeshOptions } from './navmesh/build';
export {
- bakeNavGrid,
- type BakeNavGridOptions,
- type GroundProbe,
- type GroundHit,
-} from './bakeNavGrid';
+ collectNavGeometry, navGeometryReady,
+ type NavGeometry, type CollectNavGeometryOptions,
+} from './navGeometry';
export { Navigation, Nav } from './Navigation';
export { NavAgent, type NavAgentData, setNavDestination, stopNavAgent } from './NavAgent';
export { NavVolume, type NavVolumeData } from './NavVolume';
diff --git a/sdk/src/ai/nav/minHeap.ts b/sdk/src/ai/nav/minHeap.ts
new file mode 100644
index 000000000..2d692a745
--- /dev/null
+++ b/sdk/src/ai/nav/minHeap.ts
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file minHeap.ts
+ * @brief The open set both searches run on — grid cells and mesh polygons are
+ * the same problem to a heap.
+ */
+
+/**
+ * Binary min-heap of integer node ids keyed by an f-score, backed by flat typed
+ * arrays. Lazy-deletion friendly: a node may be pushed more than once with a
+ * lower key; the search skips already-closed pops.
+ */
+export class MinHeap {
+ private nodes: Int32Array;
+ private keys: Float64Array;
+ size = 0;
+
+ constructor(capacityHint: number) {
+ const cap = Math.max(16, capacityHint);
+ this.nodes = new Int32Array(cap);
+ this.keys = new Float64Array(cap);
+ }
+
+ push(node: number, key: number): void {
+ if (this.size === this.nodes.length) this.grow();
+ let i = this.size++;
+ this.nodes[i] = node;
+ this.keys[i] = key;
+ while (i > 0) {
+ const parent = (i - 1) >> 1;
+ if (this.keys[parent]! <= this.keys[i]!) break;
+ this.swap(i, parent);
+ i = parent;
+ }
+ }
+
+ pop(): number {
+ const top = this.nodes[0]!;
+ const last = --this.size;
+ this.nodes[0] = this.nodes[last]!;
+ this.keys[0] = this.keys[last]!;
+ let i = 0;
+ for (;;) {
+ const l = i * 2 + 1;
+ const r = l + 1;
+ let smallest = i;
+ if (l < this.size && this.keys[l]! < this.keys[smallest]!) smallest = l;
+ if (r < this.size && this.keys[r]! < this.keys[smallest]!) smallest = r;
+ if (smallest === i) break;
+ this.swap(i, smallest);
+ i = smallest;
+ }
+ return top;
+ }
+
+ private swap(a: number, b: number): void {
+ const tn = this.nodes[a]!; this.nodes[a] = this.nodes[b]!; this.nodes[b] = tn;
+ const tk = this.keys[a]!; this.keys[a] = this.keys[b]!; this.keys[b] = tk;
+ }
+
+ private grow(): void {
+ const nn = new Int32Array(this.nodes.length * 2);
+ const nk = new Float64Array(this.keys.length * 2);
+ nn.set(this.nodes); nk.set(this.keys);
+ this.nodes = nn; this.keys = nk;
+ }
+}
diff --git a/sdk/src/ai/nav/navGeometry.ts b/sdk/src/ai/nav/navGeometry.ts
new file mode 100644
index 000000000..2649ad45a
--- /dev/null
+++ b/sdk/src/ai/nav/navGeometry.ts
@@ -0,0 +1,156 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file navGeometry.ts
+ * @brief The world's static collision surface, as triangles a navmesh can be
+ * baked from.
+ *
+ * The bodies a scene collides against ARE the ground it can walk on, so the bake
+ * takes them as its source rather than a second authored description that can
+ * disagree with them. Which collider on an entity counts is decided by the same
+ * projection the editor gizmo and the physics overlay read, so a navmesh cannot
+ * be baked from a shape nobody can see.
+ *
+ * STATIC bodies only. A crate that is about to be pushed is not floor, and a
+ * mesh baked over one describes the world for exactly as long as nobody touches
+ * it — a moving obstacle is a job for avoidance, not for the bake.
+ */
+
+import type { Entity, Quat, Vec3 } from '../../types';
+import type { World } from '../../ecs/world';
+import { Transform } from '../../ecs/component';
+import {
+ RigidBody3D, MeshCollider3D, ConvexCollider3D,
+ type RigidBody3DData, type MeshCollider3DData, type ConvexCollider3DData,
+} from '../../physics3d/Physics3DComponents';
+import {
+ readCollider3DShapes, collider3DTriangles, rotateVec3ByQuat,
+ type Collider3DInstance,
+} from '../../physics3d/ColliderShape3D';
+import { getMeshCollision } from '../../asset/meshCollision';
+
+/** World-space triangle soup: `verts` is `vertexCount * 3` floats. */
+export interface NavGeometry {
+ verts: Float32Array;
+ indices: Uint32Array;
+ /** How many bodies went into it — zero is the difference between "baked an
+ * empty world" and "baked a world with no static geometry in it". */
+ bodyCount: number;
+}
+
+export interface CollectNavGeometryOptions {
+ /** Only geometry touching this box is collected. */
+ min: Vec3;
+ max: Vec3;
+ /** Physics layers the ground is on, as a mask; 0 (the default) takes them all. */
+ layers?: number;
+}
+
+/**
+ * Whether every static body's shape is available — a mesh collider has none until
+ * its asset loads, and a bake that ran first would leave a hole where the level
+ * is. Read from the components, not the shape projection: an unloaded mesh
+ * produces no shape at all, so the projection would always report nothing amiss.
+ */
+export function navGeometryReady(world: World, layers = 0): boolean {
+ for (const entity of world.getEntitiesWithComponents([RigidBody3D, Transform])) {
+ if (!isBakeable(world, entity, layers)) continue;
+ const handle = namedMesh(world, entity);
+ if (handle !== 0 && getMeshCollision(handle) === null) return false;
+ }
+ return true;
+}
+
+/** The mesh handle an entity's collider names, loaded or not; 0 for none. */
+function namedMesh(world: World, entity: Entity): number {
+ for (const def of [MeshCollider3D, ConvexCollider3D] as const) {
+ if (!world.has(entity, def)) continue;
+ const data = world.get(entity, def) as MeshCollider3DData | ConvexCollider3DData;
+ if (data.enabled !== false && data.mesh !== 0) return data.mesh;
+ }
+ return 0;
+}
+
+export function collectNavGeometry(world: World, opts: CollectNavGeometryOptions): NavGeometry {
+ const layers = opts.layers ?? 0;
+ const verts: number[] = [];
+ const indices: number[] = [];
+ let bodyCount = 0;
+
+ for (const entity of world.getEntitiesWithComponents([RigidBody3D, Transform])) {
+ if (!isBakeable(world, entity, layers)) continue;
+ const local = localTriangles(world, entity);
+ if (!local) continue;
+
+ // The transform the 3D SOLVER builds its bodies from. A mesh baked from
+ // anywhere else would describe a world the agent does not collide with.
+ const tf = world.get(entity, Transform);
+ const at = tf.position as Vec3;
+ const rot = tf.rotation as Quat;
+
+ const base = verts.length / 3;
+ let minX = Infinity, minY = Infinity, minZ = Infinity;
+ let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
+ for (let i = 0; i + 2 < local.positions.length; i += 3) {
+ const p = rotateVec3ByQuat(rot, {
+ x: local.positions[i]!, y: local.positions[i + 1]!, z: local.positions[i + 2]!,
+ });
+ const x = at.x + p.x;
+ const y = at.y + p.y;
+ const z = at.z + p.z;
+ verts.push(x, y, z);
+ if (x < minX) minX = x; if (x > maxX) maxX = x;
+ if (y < minY) minY = y; if (y > maxY) maxY = y;
+ if (z < minZ) minZ = z; if (z > maxZ) maxZ = z;
+ }
+
+ // Whole bodies are culled, not triangles: the rasteriser clips what
+ // crosses the edge of the box, and a body that misses it entirely is the
+ // only thing worth not transforming.
+ if (maxX < opts.min.x || minX > opts.max.x || maxY < opts.min.y || minY > opts.max.y
+ || maxZ < opts.min.z || minZ > opts.max.z) {
+ verts.length = base * 3;
+ continue;
+ }
+
+ for (let i = 0; i < local.indices.length; i++) indices.push(base + local.indices[i]!);
+ bodyCount++;
+ }
+
+ return { verts: Float32Array.from(verts), indices: Uint32Array.from(indices), bodyCount };
+}
+
+function isBakeable(world: World, entity: Entity, layers: number): boolean {
+ const body = world.get(entity, RigidBody3D) as RigidBody3DData;
+ if (body.enabled === false || body.bodyType !== STATIC) return false;
+ return layers === 0 || (layers & (1 << body.layer)) !== 0;
+}
+
+/** The one shape the solver builds for this entity, if it is part of the ground.
+ * A character is an agent walking the mesh rather than part of what it walks
+ * on, and a sensor is a trigger nobody bumps into. */
+function activeCollider(world: World, entity: Entity): Collider3DInstance | null {
+ for (const instance of readCollider3DShapes(world, entity)) {
+ if (!instance.active || instance.isSensor) continue;
+ if (instance.component === 'CharacterController3D') continue;
+ return instance;
+ }
+ return null;
+}
+
+function localTriangles(
+ world: World, entity: Entity,
+): { positions: Float32Array; indices: ArrayLike<number> } | null {
+ const active = activeCollider(world, entity);
+ if (!active) return null;
+ if (active.component === 'MeshCollider3D' || active.component === 'ConvexCollider3D') {
+ const data = getMeshCollision(namedMesh(world, entity));
+ // The hull a convex collider builds is not the mesh, but the mesh's own
+ // triangles are what describe where it is; the difference is a dent the
+ // voxeliser would have rounded away in any case.
+ return data ? { positions: data.positions, indices: data.indices } : null;
+ }
+ return collider3DTriangles(active.shape);
+}
+
+const STATIC = 0;
diff --git a/sdk/src/ai/nav/navmesh/build.ts b/sdk/src/ai/nav/navmesh/build.ts
new file mode 100644
index 000000000..6717f3863
--- /dev/null
+++ b/sdk/src/ai/nav/navmesh/build.ts
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file build.ts
+ * @brief Triangles in, {@link NavMesh} out — the whole bake, in one place.
+ *
+ * Voxelise, filter, partition, trace, polygonise. Each stage lives in its own
+ * file and is testable on its own; this is the order they go in and the one
+ * place the world's units (pixels, degrees) are turned into the voxel counts
+ * every stage below actually works in.
+ *
+ * The stages and their order are Recast's (Mikko Mononen, zlib) — this is an
+ * independent TypeScript implementation of that published pipeline, not a port of
+ * its source. In TypeScript rather than a second wasm module because a bake runs
+ * once per volume and splitting navigation across two languages costs more than
+ * it buys.
+ */
+
+import type { Vec3 } from '../../../types';
+import { NavMesh } from '../NavMesh';
+import {
+ NavHeightfield, heightfieldColumns, rasterizeTriangles,
+ filterLowHangingWalkableObstacles, filterLedgeSpans, filterWalkableLowHeightSpans,
+} from './heightfield';
+import { log } from '../../../util/logger';
+import { NavCompactField, erodeWalkableArea } from './compact';
+import { buildRegionsMonotone } from './regions';
+import { buildContours } from './contours';
+import { buildPolyMesh } from './polymesh';
+
+export interface BuildNavMeshOptions {
+ /** The box of world to bake, in world pixels. */
+ min: Vec3;
+ max: Vec3;
+ /** Voxel size in the ground plane. The finer it is, the closer the mesh hugs
+ * the geometry and the longer the bake takes. */
+ cellSize: number;
+ /** Voxel size vertically. Wants to be several times smaller than `cellSize`,
+ * because it is what decides whether two floors are one. */
+ cellHeight: number;
+ /** Steepest ground an agent can stand on, in degrees from level. */
+ maxSlopeDegrees?: number;
+ /** How much room an agent needs above the floor, in world pixels. */
+ agentHeight?: number;
+ /** How wide the agent is. The mesh is pulled back from every wall by this, so
+ * routes over it clear the walls by construction. */
+ agentRadius?: number;
+ /** The tallest step an agent can walk up rather than round, in world pixels. */
+ stepHeight?: number;
+ /** How far, in world pixels, a simplified outline may stray from the raw one. */
+ maxSimplificationError?: number;
+ /** How long a wall edge may get before it is split, in world pixels. 0 leaves
+ * them alone. */
+ maxEdgeLength?: number;
+ /** Smallest patch of unreachable ground worth a polygon, in world pixels
+ * squared. Below this a stranded ledge is left out of the mesh entirely. */
+ minRegionArea?: number;
+ /** Corners a polygon may have. Six is the default this is tuned around. */
+ maxVertsPerPoly?: number;
+}
+
+export function buildNavMesh(
+ verts: Float32Array, indices: ArrayLike<number>, opts: BuildNavMeshOptions,
+): NavMesh {
+ const cs = opts.cellSize;
+ const ch = opts.cellHeight;
+ const agentRadius = opts.agentRadius ?? 0;
+
+ const slopeCos = Math.cos(((opts.maxSlopeDegrees ?? 45) * Math.PI) / 180);
+ // A span has to be at least one voxel tall to exist at all, so an agent with
+ // no stated height still asks for the one voxel of headroom.
+ const walkableHeight = Math.max(1, Math.ceil((opts.agentHeight ?? 0) / ch));
+ const walkableClimb = Math.floor((opts.stepHeight ?? 0) / ch);
+ const walkableRadius = Math.ceil(agentRadius / cs);
+ const maxError = (opts.maxSimplificationError ?? cs * 1.3) / cs;
+ const maxEdgeLen = Math.floor((opts.maxEdgeLength ?? cs * 12) / cs);
+ const minRegionArea = Math.max(1, Math.round((opts.minRegionArea ?? (cs * 8) ** 2) / (cs * cs)));
+
+ const size = heightfieldColumns(opts.min, opts.max, cs);
+ if (size.width * size.depth > MAX_COLUMNS) {
+ log.warn('nav', `a navigation volume ${size.width}x${size.depth} cells across is too`
+ + ` big to voxelise — raise cellSize (now ${cs}) or shrink the volume`);
+ return emptyMesh(agentRadius, cs);
+ }
+
+ const hf = new NavHeightfield(opts.min, opts.max, cs, ch);
+ rasterizeTriangles(hf, verts, indices, slopeCos, walkableClimb);
+ filterLowHangingWalkableObstacles(hf, walkableClimb);
+ filterLedgeSpans(hf, walkableHeight, walkableClimb);
+ filterWalkableLowHeightSpans(hf, walkableHeight);
+
+ const chf = new NavCompactField(hf, walkableHeight, walkableClimb);
+ erodeWalkableArea(chf, walkableRadius);
+ buildRegionsMonotone(chf, minRegionArea);
+
+ const contours = buildContours(chf, maxError, maxEdgeLen);
+ const mesh = buildPolyMesh(contours, opts.maxVertsPerPoly ?? 6);
+
+ const world = new Float32Array(mesh.vertCount * 3);
+ for (let i = 0; i < mesh.vertCount; i++) {
+ world[i * 3] = opts.min.x + mesh.verts[i * 3]! * cs;
+ world[i * 3 + 1] = opts.min.y + mesh.verts[i * 3 + 1]! * ch;
+ world[i * 3 + 2] = opts.min.z + mesh.verts[i * 3 + 2]! * cs;
+ }
+
+ return new NavMesh({
+ verts: world,
+ polys: mesh.polys,
+ neis: mesh.neis,
+ polyCount: mesh.polyCount,
+ maxVertsPerPoly: mesh.maxVertsPerPoly,
+ agentRadius,
+ // A point is only ever off the mesh by what the bake took away: the
+ // erosion, plus the cell the voxel grid rounded it into.
+ snapDistance: agentRadius + cs,
+ // A floor within an agent's own height and one step of it is one it could
+ // be standing on; anything further is a different storey.
+ verticalReach: Math.max((opts.agentHeight ?? 0) + (opts.stepHeight ?? 0), ch * 4),
+ });
+}
+
+/**
+ * How many voxel columns one bake may cover. Past this it is minutes of work and
+ * a heap the size of the level: a volume this big wants a coarser `cellSize`,
+ * and saying so beats a frozen editor and no explanation.
+ */
+const MAX_COLUMNS = 1_000_000;
+
+function emptyMesh(agentRadius: number, cellSize: number): NavMesh {
+ return new NavMesh({
+ verts: new Float32Array(0),
+ polys: new Int32Array(0),
+ neis: new Int32Array(0),
+ polyCount: 0,
+ maxVertsPerPoly: 6,
+ agentRadius,
+ snapDistance: agentRadius + cellSize,
+ verticalReach: 0,
+ });
+}
diff --git a/sdk/src/ai/nav/navmesh/compact.ts b/sdk/src/ai/nav/navmesh/compact.ts
new file mode 100644
index 000000000..be71d459d
--- /dev/null
+++ b/sdk/src/ai/nav/navmesh/compact.ts
@@ -0,0 +1,238 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file compact.ts
+ * @brief Compact heightfield — the OPEN space above each solid span, with the
+ * neighbours an agent can actually reach from it.
+ *
+ * The solid field says where the world is; this says where an agent may be. Two
+ * open spans are neighbours only if the step between them is small enough to
+ * climb and the gap is tall enough to stand in, so the connection graph here is
+ * already the walkable one: everything after this reads adjacency instead of
+ * re-deciding it.
+ *
+ * Flat typed arrays rather than the solid field's linked spans, because from
+ * here on the field is walked far more often than it is built.
+ */
+
+import {
+ DIR_X, DIR_Z, NAV_AREA_NULL, NAV_SPAN_MAX_HEIGHT, type NavHeightfield,
+} from './heightfield';
+import type { Vec3 } from '../../../types';
+
+/** A direction with no reachable neighbour. Six bits per direction, so 63 is the
+ * one value that cannot also be a span offset. */
+export const NAV_NOT_CONNECTED = 0x3f;
+
+export class NavCompactField {
+ readonly width: number;
+ readonly depth: number;
+ readonly min: Vec3;
+ readonly max: Vec3;
+ readonly cellSize: number;
+ readonly cellHeight: number;
+ /** In voxels — what the connection test was built with. */
+ readonly walkableHeight: number;
+ readonly walkableClimb: number;
+
+ /** First span of column `x + z * width`, and how many it has. */
+ readonly cellIndex: Int32Array;
+ readonly cellCount: Int32Array;
+
+ /** Floor of the open span, in voxels off `min.y`. */
+ readonly y: Int32Array;
+ /** Headroom above it, in voxels. */
+ readonly h: Int32Array;
+ /** Four six-bit neighbour offsets, one per direction. */
+ readonly con: Int32Array;
+ readonly areas: Uint8Array;
+ /** Region id, filled in by the partitioner. 0 = none. */
+ readonly regs: Int32Array;
+ readonly spanCount: number;
+
+ constructor(hf: NavHeightfield, walkableHeight: number, walkableClimb: number) {
+ this.width = hf.width;
+ this.depth = hf.depth;
+ this.min = { ...hf.min };
+ this.max = { ...hf.max };
+ this.cellSize = hf.cellSize;
+ this.cellHeight = hf.cellHeight;
+ this.walkableHeight = walkableHeight;
+ this.walkableClimb = walkableClimb;
+
+ const cells = hf.width * hf.depth;
+ let count = 0;
+ for (let i = 0; i < cells; i++) {
+ for (let s = hf.spans[i] ?? null; s; s = s.next) {
+ if (s.area !== NAV_AREA_NULL) count++;
+ }
+ }
+ this.spanCount = count;
+ this.cellIndex = new Int32Array(cells);
+ this.cellCount = new Int32Array(cells);
+ this.y = new Int32Array(count);
+ this.h = new Int32Array(count);
+ this.con = new Int32Array(count);
+ this.areas = new Uint8Array(count);
+ this.regs = new Int32Array(count);
+
+ let idx = 0;
+ for (let i = 0; i < cells; i++) {
+ this.cellIndex[i] = idx;
+ for (let s = hf.spans[i] ?? null; s; s = s.next) {
+ if (s.area === NAV_AREA_NULL) continue;
+ const bot = s.smax;
+ const top = s.next ? s.next.smin : NAV_SPAN_MAX_HEIGHT;
+ this.y[idx] = Math.min(bot, NAV_SPAN_MAX_HEIGHT);
+ this.h[idx] = Math.min(Math.max(top - bot, 0), NAV_SPAN_MAX_HEIGHT);
+ this.areas[idx] = s.area;
+ idx++;
+ this.cellCount[i]!++;
+ }
+ }
+
+ this.connect();
+ }
+
+ getCon(i: number, dir: number): number {
+ return (this.con[i]! >> (dir * 6)) & 0x3f;
+ }
+
+ private setCon(i: number, dir: number, value: number): void {
+ const shift = dir * 6;
+ this.con[i] = (this.con[i]! & ~(0x3f << shift)) | ((value & 0x3f) << shift);
+ }
+
+ /** Index of the span reached from `i` in `dir`, or -1. */
+ neighbourSpan(x: number, z: number, i: number, dir: number): number {
+ const con = this.getCon(i, dir);
+ if (con === NAV_NOT_CONNECTED) return -1;
+ const nx = x + DIR_X[dir]!;
+ const nz = z + DIR_Z[dir]!;
+ return this.cellIndex[nx + nz * this.width]! + con;
+ }
+
+ private connect(): void {
+ const { width: w, depth: d } = this;
+ for (let z = 0; z < d; z++) {
+ for (let x = 0; x < w; x++) {
+ const c = x + z * w;
+ const start = this.cellIndex[c]!;
+ const end = start + this.cellCount[c]!;
+ for (let i = start; i < end; i++) {
+ for (let dir = 0; dir < 4; dir++) {
+ this.setCon(i, dir, NAV_NOT_CONNECTED);
+ const nx = x + DIR_X[dir]!;
+ const nz = z + DIR_Z[dir]!;
+ if (nx < 0 || nz < 0 || nx >= w || nz >= d) continue;
+ const nc = nx + nz * w;
+ const nStart = this.cellIndex[nc]!;
+ const nEnd = nStart + this.cellCount[nc]!;
+ for (let k = nStart; k < nEnd; k++) {
+ const bot = Math.max(this.y[i]!, this.y[k]!);
+ const top = Math.min(this.y[i]! + this.h[i]!, this.y[k]! + this.h[k]!);
+ if (top - bot < this.walkableHeight) continue;
+ if (Math.abs(this.y[k]! - this.y[i]!) > this.walkableClimb) continue;
+ const offset = k - nStart;
+ // Six bits is what a direction gets; a column with more
+ // than 63 floors is beyond what this can address, and
+ // saying "not connected" is the honest answer for it.
+ if (offset < 0 || offset >= NAV_NOT_CONNECTED) continue;
+ this.setCon(i, dir, offset);
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Take `radius` cells off every edge of the walkable world. An agent is a body:
+ * planning it down the exact edge of a walkway puts half of it over the drop.
+ * Eroding here rather than filtering per query makes the mesh the set of places
+ * the agent's centre may be — and is why a mesh is baked per agent SIZE.
+ */
+export function erodeWalkableArea(chf: NavCompactField, radius: number): void {
+ if (radius <= 0) return;
+ const { width: w, depth: d, spanCount: n } = chf;
+ const dist = new Int32Array(n).fill(0xff);
+
+ // Anything on the boundary of the walkable set starts at zero distance.
+ for (let z = 0; z < d; z++) {
+ for (let x = 0; x < w; x++) {
+ const c = x + z * w;
+ const start = chf.cellIndex[c]!;
+ const end = start + chf.cellCount[c]!;
+ for (let i = start; i < end; i++) {
+ if (chf.areas[i] === NAV_AREA_NULL) { dist[i] = 0; continue; }
+ let open = 0;
+ for (let dir = 0; dir < 4; dir++) {
+ const ni = chf.neighbourSpan(x, z, i, dir);
+ if (ni >= 0 && chf.areas[ni] !== NAV_AREA_NULL) open++;
+ }
+ if (open !== 4) dist[i] = 0;
+ }
+ }
+ }
+
+ chamfer(chf, dist);
+
+ const threshold = radius * 2;
+ for (let i = 0; i < n; i++) {
+ if (dist[i]! < threshold) chf.areas[i] = NAV_AREA_NULL;
+ }
+}
+
+/**
+ * Two sweeps of a 3-4 weighted chamfer transform over the connection graph — the
+ * same approximation of euclidean distance the grid uses, but following reachable
+ * neighbours rather than the raster, so a cell across a wall is not "one away".
+ */
+function chamfer(chf: NavCompactField, dist: Int32Array): void {
+ const { width: w, depth: d } = chf;
+ const relax = (i: number, from: number, cost: number): void => {
+ const nd = Math.min(dist[from]! + cost, 0xff);
+ if (nd < dist[i]!) dist[i] = nd;
+ };
+
+ for (let z = 0; z < d; z++) {
+ for (let x = 0; x < w; x++) {
+ const c = x + z * w;
+ const start = chf.cellIndex[c]!;
+ const end = start + chf.cellCount[c]!;
+ for (let i = start; i < end; i++) {
+ for (const [dir, diag] of BACKWARD) {
+ const ni = chf.neighbourSpan(x, z, i, dir);
+ if (ni < 0) continue;
+ relax(i, ni, 2);
+ const nj = chf.neighbourSpan(x + DIR_X[dir]!, z + DIR_Z[dir]!, ni, diag);
+ if (nj >= 0) relax(i, nj, 3);
+ }
+ }
+ }
+ }
+
+ for (let z = d - 1; z >= 0; z--) {
+ for (let x = w - 1; x >= 0; x--) {
+ const c = x + z * w;
+ const start = chf.cellIndex[c]!;
+ const end = start + chf.cellCount[c]!;
+ for (let i = end - 1; i >= start; i--) {
+ for (const [dir, diag] of FORWARD) {
+ const ni = chf.neighbourSpan(x, z, i, dir);
+ if (ni < 0) continue;
+ relax(i, ni, 2);
+ const nj = chf.neighbourSpan(x + DIR_X[dir]!, z + DIR_Z[dir]!, ni, diag);
+ if (nj >= 0) relax(i, nj, 3);
+ }
+ }
+ }
+ }
+}
+
+/** The two orthogonal directions each sweep comes FROM, each paired with the turn
+ * that reaches the diagonal behind it. */
+const BACKWARD: ReadonlyArray<readonly [number, number]> = [[0, 3], [3, 2]];
+const FORWARD: ReadonlyArray<readonly [number, number]> = [[2, 1], [1, 0]];
diff --git a/sdk/src/ai/nav/navmesh/contours.ts b/sdk/src/ai/nav/navmesh/contours.ts
new file mode 100644
index 000000000..acc51db30
--- /dev/null
+++ b/sdk/src/ai/nav/navmesh/contours.ts
@@ -0,0 +1,333 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file contours.ts
+ * @brief Walk the outline of every region and simplify it into a few corners.
+ *
+ * A region is thousands of cells; its shape is a dozen. The walk follows the
+ * boundary cell by cell, then the simplifier keeps only the corners the outline
+ * cannot be drawn without: the ones where the region on the other side changes
+ * (those are the doorways between regions, and dropping one would tear the mesh
+ * in two), plus enough of the rest to stay within `maxError` of the raw edge.
+ *
+ * Two regions that touch each trace the shared boundary from their own side, in
+ * opposite directions. They must land on the SAME corners, or the polygons will
+ * not share vertices and the finished mesh will have a seam no agent can cross —
+ * which is why the deviation is measured in a fixed order rather than along the
+ * direction of travel.
+ */
+
+import { DIR_X, DIR_Z } from './heightfield';
+import type { NavCompactField } from './compact';
+
+/** One region's outline: `x, y, z` voxel coordinates per vertex. */
+export interface NavContour {
+ verts: Int32Array;
+ reg: number;
+}
+
+/**
+ * @param maxError How far, in cells, the simplified outline may stray from the
+ * raw one.
+ * @param maxEdgeLen How long a wall edge may get before it is split, in cells.
+ * Long edges make big polygons and coarse routes along them;
+ * 0 leaves them alone.
+ */
+export function buildContours(
+ chf: NavCompactField, maxError: number, maxEdgeLen: number,
+): NavContour[] {
+ const { width: w, depth: d } = chf;
+ const flags = new Uint8Array(chf.spanCount);
+
+ for (let z = 0; z < d; z++) {
+ for (let x = 0; x < w; x++) {
+ const c = x + z * w;
+ const start = chf.cellIndex[c]!;
+ const end = start + chf.cellCount[c]!;
+ for (let i = start; i < end; i++) {
+ if (chf.regs[i] === 0) { flags[i] = 0; continue; }
+ let same = 0;
+ for (let dir = 0; dir < 4; dir++) {
+ const ni = chf.neighbourSpan(x, z, i, dir);
+ const r = ni >= 0 ? chf.regs[ni]! : 0;
+ if (r === chf.regs[i]) same |= 1 << dir;
+ }
+ // Invert: the bits left standing are the sides that face OUT.
+ flags[i] = same ^ 0xf;
+ }
+ }
+ }
+
+ const contours: NavContour[] = [];
+ const raw: number[] = [];
+ const simplified: number[] = [];
+
+ for (let z = 0; z < d; z++) {
+ for (let x = 0; x < w; x++) {
+ const c = x + z * w;
+ const start = chf.cellIndex[c]!;
+ const end = start + chf.cellCount[c]!;
+ for (let i = start; i < end; i++) {
+ // 0xf is a span with no neighbour on any side — a single cell of
+ // ground, which has an outline but no interior to walk.
+ if (flags[i] === 0 || flags[i] === 0xf) { flags[i] = 0; continue; }
+ const reg = chf.regs[i]!;
+ if (reg === 0) continue;
+
+ raw.length = 0;
+ simplified.length = 0;
+ walkContour(chf, flags, x, z, i, raw);
+ simplifyContour(raw, simplified, maxError, maxEdgeLen);
+ removeDegenerateSegments(simplified);
+ if (simplified.length / 4 < 3) continue;
+
+ contours.push({ verts: windCorrectly(simplified), reg });
+ }
+ }
+ }
+
+ return contours;
+}
+
+/**
+ * Follow the boundary of one region, emitting a vertex per outward-facing cell
+ * edge and clearing each edge as it is used, so no boundary is walked twice.
+ * Turning right along an outward edge and left through an inward one is what
+ * keeps the walk on the outline instead of wandering into the region.
+ */
+function walkContour(
+ chf: NavCompactField, flags: Uint8Array,
+ startX: number, startZ: number, startI: number, out: number[],
+): void {
+ let dir = 0;
+ while ((flags[startI]! & (1 << dir)) === 0) dir++;
+
+ const startDir = dir;
+ let x = startX;
+ let z = startZ;
+ let i = startI;
+
+ // A contour cannot be longer than the field has edges; the cap is a guard
+ // against a malformed field turning into a hang, not an expected limit.
+ for (let iter = 0; iter < 1 << 20; iter++) {
+ if (flags[i]! & (1 << dir)) {
+ let px = x;
+ let pz = z;
+ const py = cornerHeight(chf, x, z, i, dir);
+ if (dir === 0) pz++;
+ else if (dir === 1) { px++; pz++; }
+ else if (dir === 2) px++;
+
+ const ni = chf.neighbourSpan(x, z, i, dir);
+ out.push(px, py, pz, ni >= 0 ? chf.regs[ni]! : 0);
+
+ flags[i] = flags[i]! & ~(1 << dir);
+ dir = (dir + 1) & 3;
+ } else {
+ const ni = chf.neighbourSpan(x, z, i, dir);
+ if (ni < 0) return;
+ x += DIR_X[dir]!;
+ z += DIR_Z[dir]!;
+ i = ni;
+ dir = (dir + 3) & 3;
+ }
+ if (i === startI && dir === startDir) break;
+ }
+}
+
+/**
+ * The height of the corner between this cell and the three around it — the
+ * highest floor of the four, so a contour vertex sits on top of the step rather
+ * than inside it.
+ */
+function cornerHeight(chf: NavCompactField, x: number, z: number, i: number, dir: number): number {
+ let ch = chf.y[i]!;
+ const dirp = (dir + 1) & 3;
+
+ const a = chf.neighbourSpan(x, z, i, dir);
+ if (a >= 0) {
+ ch = Math.max(ch, chf.y[a]!);
+ const a2 = chf.neighbourSpan(x + DIR_X[dir]!, z + DIR_Z[dir]!, a, dirp);
+ if (a2 >= 0) ch = Math.max(ch, chf.y[a2]!);
+ }
+ const b = chf.neighbourSpan(x, z, i, dirp);
+ if (b >= 0) {
+ ch = Math.max(ch, chf.y[b]!);
+ const b2 = chf.neighbourSpan(x + DIR_X[dirp]!, z + DIR_Z[dirp]!, b, dir);
+ if (b2 >= 0) ch = Math.max(ch, chf.y[b2]!);
+ }
+ return ch;
+}
+
+/** Squared distance from a point to a segment, in the ground plane. */
+function distancePtSeg(x: number, z: number, px: number, pz: number, qx: number, qz: number): number {
+ const pqx = qx - px;
+ const pqz = qz - pz;
+ let dx = x - px;
+ let dz = z - pz;
+ const d = pqx * pqx + pqz * pqz;
+ let t = pqx * dx + pqz * dz;
+ if (d > 0) t /= d;
+ t = t < 0 ? 0 : t > 1 ? 1 : t;
+ dx = px + t * pqx - x;
+ dz = pz + t * pqz - z;
+ return dx * dx + dz * dz;
+}
+
+function simplifyContour(
+ points: number[], simplified: number[], maxError: number, maxEdgeLen: number,
+): void {
+ const pn = points.length / 4;
+
+ let hasPortals = false;
+ for (let i = 0; i < pn; i++) {
+ if (points[i * 4 + 3] !== 0) { hasPortals = true; break; }
+ }
+
+ if (hasPortals) {
+ // Every place the region on the other side changes is a doorway, and both
+ // sides of it must agree where it starts — so it is kept, always.
+ for (let i = 0; i < pn; i++) {
+ const ii = (i + 1) % pn;
+ if (points[i * 4 + 3] === points[ii * 4 + 3]) continue;
+ simplified.push(points[i * 4]!, points[i * 4 + 1]!, points[i * 4 + 2]!, i);
+ }
+ }
+
+ if (simplified.length === 0) {
+ // An outline touching nothing has no fixed points of its own; two
+ // opposite extremes give the refinement below something to work from.
+ let llx = points[0]!, lly = points[1]!, llz = points[2]!, lli = 0;
+ let urx = llx, ury = lly, urz = llz, uri = 0;
+ for (let i = 0; i < pn; i++) {
+ const x = points[i * 4]!, y = points[i * 4 + 1]!, z = points[i * 4 + 2]!;
+ if (x < llx || (x === llx && z < llz)) { llx = x; lly = y; llz = z; lli = i; }
+ if (x > urx || (x === urx && z > urz)) { urx = x; ury = y; urz = z; uri = i; }
+ }
+ simplified.push(llx, lly, llz, lli, urx, ury, urz, uri);
+ }
+
+ for (let i = 0; i < simplified.length / 4;) {
+ const ii = (i + 1) % (simplified.length / 4);
+ let ax = simplified[i * 4]!;
+ let az = simplified[i * 4 + 2]!;
+ const ai = simplified[i * 4 + 3]!;
+ let bx = simplified[ii * 4]!;
+ let bz = simplified[ii * 4 + 2]!;
+ const bi = simplified[ii * 4 + 3]!;
+
+ let maxd = 0;
+ let maxi = -1;
+ let ci: number;
+ let cinc: number;
+ let endi: number;
+
+ // Walk the raw points in a fixed order regardless of which way this
+ // segment runs, so the region on the other side measures the same
+ // deviation and keeps the same corner.
+ if (bx > ax || (bx === ax && bz > az)) {
+ cinc = 1; ci = (ai + 1) % pn; endi = bi;
+ } else {
+ cinc = pn - 1; ci = (bi + cinc) % pn; endi = ai;
+ const tx = ax; ax = bx; bx = tx;
+ const tz = az; az = bz; bz = tz;
+ }
+
+ // Only walls are refined: a segment shared with another region already
+ // runs doorway to doorway, and bending it would bend only this side.
+ if (points[ci * 4 + 3] === 0) {
+ while (ci !== endi) {
+ const d = distancePtSeg(points[ci * 4]!, points[ci * 4 + 2]!, ax, az, bx, bz);
+ if (d > maxd) { maxd = d; maxi = ci; }
+ ci = (ci + cinc) % pn;
+ }
+ }
+
+ if (maxi !== -1 && maxd > maxError * maxError) {
+ simplified.splice((i + 1) * 4, 0,
+ points[maxi * 4]!, points[maxi * 4 + 1]!, points[maxi * 4 + 2]!, maxi);
+ } else {
+ i++;
+ }
+ }
+
+ if (maxEdgeLen > 0) splitLongEdges(points, simplified, pn, maxEdgeLen);
+
+ // Each vertex ends up carrying the region across the edge that LEAVES it.
+ for (let i = 0; i < simplified.length / 4; i++) {
+ const next = (simplified[i * 4 + 3]! + 1) % pn;
+ simplified[i * 4 + 3] = points[next * 4 + 3]!;
+ }
+}
+
+function splitLongEdges(points: number[], simplified: number[], pn: number, maxEdgeLen: number): void {
+ for (let i = 0; i < simplified.length / 4;) {
+ const n = simplified.length / 4;
+ const ii = (i + 1) % n;
+ const ax = simplified[i * 4]!;
+ const az = simplified[i * 4 + 2]!;
+ const ai = simplified[i * 4 + 3]!;
+ const bx = simplified[ii * 4]!;
+ const bz = simplified[ii * 4 + 2]!;
+ const bi = simplified[ii * 4 + 3]!;
+
+ let maxi = -1;
+ const ci = (ai + 1) % pn;
+ if (points[ci * 4 + 3] === 0) {
+ const dx = bx - ax;
+ const dz = bz - az;
+ if (dx * dx + dz * dz > maxEdgeLen * maxEdgeLen) {
+ const span = bi < ai ? bi + pn - ai : bi - ai;
+ if (span > 1) {
+ maxi = bx > ax || (bx === ax && bz > az)
+ ? (ai + (span >> 1)) % pn
+ : (ai + ((span + 1) >> 1)) % pn;
+ }
+ }
+ }
+
+ if (maxi !== -1) {
+ simplified.splice((i + 1) * 4, 0,
+ points[maxi * 4]!, points[maxi * 4 + 1]!, points[maxi * 4 + 2]!, maxi);
+ } else {
+ i++;
+ }
+ }
+}
+
+/** Neighbouring vertices that share a spot in the ground plane confuse the
+ * triangulator, and a zero-length edge is not a shape. */
+function removeDegenerateSegments(simplified: number[]): void {
+ let n = simplified.length / 4;
+ for (let i = 0; i < n; i++) {
+ const ni = (i + 1) % n;
+ if (simplified[i * 4] !== simplified[ni * 4]
+ || simplified[i * 4 + 2] !== simplified[ni * 4 + 2]) continue;
+ simplified.splice(i * 4, 4);
+ n--;
+ i--;
+ }
+}
+
+/**
+ * Every contour comes out wound the same way, so that the triangulator, the
+ * polygon merger and the funnel can each assume a side without asking. The
+ * measure is twice the signed area in the ground plane; a walk that produced the
+ * mirror of it is simply reversed.
+ */
+function windCorrectly(simplified: number[]): Int32Array {
+ const n = simplified.length / 4;
+ let area = 0;
+ for (let i = 0, j = n - 1; i < n; j = i++) {
+ area += simplified[i * 4]! * simplified[j * 4 + 2]! - simplified[j * 4]! * simplified[i * 4 + 2]!;
+ }
+
+ const out = new Int32Array(n * 3);
+ for (let i = 0; i < n; i++) {
+ const src = area > 0 ? i : n - 1 - i;
+ out[i * 3] = simplified[src * 4]!;
+ out[i * 3 + 1] = simplified[src * 4 + 1]!;
+ out[i * 3 + 2] = simplified[src * 4 + 2]!;
+ }
+ return out;
+}
diff --git a/sdk/src/ai/nav/navmesh/heightfield.ts b/sdk/src/ai/nav/navmesh/heightfield.ts
new file mode 100644
index 000000000..b6b996d9b
--- /dev/null
+++ b/sdk/src/ai/nav/navmesh/heightfield.ts
@@ -0,0 +1,393 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file heightfield.ts
+ * @brief Solid voxel heightfield — the first step of turning triangles into a
+ * navigation mesh.
+ *
+ * Every column of the world holds a list of the SOLID intervals in it, so a
+ * bridge and the road under it are two entries rather than whichever a ray met
+ * first. That is the whole reason the navmesh pipeline starts with voxels: a
+ * heightfield with one surface per column cannot describe a world with two.
+ *
+ * Triangles are clipped into the columns they cross rather than sampled, so a
+ * floor tilted between two cells still fills both. The rasteriser is Recast's,
+ * which is the shape this problem has had a standard answer for since 2009.
+ *
+ * All lengths here are WORLD pixels; heights are stored as voxel indices off
+ * `min.y`, which is what keeps a span an integer pair rather than two floats.
+ */
+
+import type { Vec3 } from '../../../types';
+
+/** Not walkable — either never was, or a filter took it away. */
+export const NAV_AREA_NULL = 0;
+/** Ground an agent can stand on. */
+export const NAV_AREA_WALKABLE = 1;
+
+/** The tallest a span may reach, in voxels. */
+export const NAV_SPAN_MAX_HEIGHT = 0xffff;
+
+/** One solid interval in a column: voxels `[smin, smax)` are inside geometry. */
+export interface NavSpan {
+ smin: number;
+ smax: number;
+ area: number;
+ next: NavSpan | null;
+}
+
+/** How many columns a box of world covers at this resolution. Its own function
+ * because a caller has to be able to ask before committing to the memory. */
+export function heightfieldColumns(
+ min: Vec3, max: Vec3, cellSize: number,
+): { width: number; depth: number } {
+ return {
+ width: Math.max(1, Math.ceil((max.x - min.x) / cellSize)),
+ depth: Math.max(1, Math.ceil((max.z - min.z) / cellSize)),
+ };
+}
+
+export class NavHeightfield {
+ /** Columns along world x. */
+ readonly width: number;
+ /** Columns along world z. */
+ readonly depth: number;
+ readonly min: Vec3;
+ readonly max: Vec3;
+ readonly cellSize: number;
+ readonly cellHeight: number;
+ /** Column-major-free: `x + z * width`, lowest span first. */
+ readonly spans: (NavSpan | null)[];
+
+ constructor(min: Vec3, max: Vec3, cellSize: number, cellHeight: number) {
+ this.min = { ...min };
+ this.max = { ...max };
+ this.cellSize = cellSize;
+ this.cellHeight = cellHeight;
+ const size = heightfieldColumns(min, max, cellSize);
+ this.width = size.width;
+ this.depth = size.depth;
+ this.spans = new Array<NavSpan | null>(this.width * this.depth).fill(null);
+ }
+}
+
+/**
+ * Add a solid interval to a column, merging it into whatever it touches: two
+ * spans that overlap ARE one solid thing. `mergeThreshold` is how close two tops
+ * have to be for the more walkable area to win, so a thin slab laid on a wall
+ * keeps its own.
+ */
+export function addSpan(
+ hf: NavHeightfield, x: number, z: number,
+ smin: number, smax: number, area: number, mergeThreshold: number,
+): void {
+ const idx = x + z * hf.width;
+ const s: NavSpan = { smin, smax, area, next: null };
+
+ let prev: NavSpan | null = null;
+ let cur = hf.spans[idx] ?? null;
+ while (cur) {
+ if (cur.smin > s.smax) break;
+ if (cur.smax < s.smin) {
+ prev = cur;
+ cur = cur.next;
+ continue;
+ }
+ if (cur.smin < s.smin) s.smin = cur.smin;
+ if (cur.smax > s.smax) s.smax = cur.smax;
+ if (Math.abs(s.smax - cur.smax) <= mergeThreshold) s.area = Math.max(s.area, cur.area);
+ const next = cur.next;
+ if (prev) prev.next = next; else hf.spans[idx] = next;
+ cur = next;
+ }
+
+ if (prev) {
+ s.next = prev.next;
+ prev.next = s;
+ } else {
+ s.next = hf.spans[idx] ?? null;
+ hf.spans[idx] = s;
+ }
+}
+
+/** Scratch for the clipper: four polygons of at most seven vertices. */
+const CLIP_BUF = new Float32Array(7 * 3 * 4);
+
+/** Where {@link dividePoly} reports the two vertex counts it produced. */
+const DIVIDE_OUT = new Int32Array(2);
+
+/**
+ * Split a polygon by the plane `axis = value` into the part on the near side
+ * (`out1`, where `coord <= value`) and the part beyond it (`out2`), reporting
+ * their vertex counts in {@link DIVIDE_OUT}.
+ */
+function dividePoly(
+ buf: Float32Array, inOff: number, nin: number,
+ out1: number, out2: number, value: number, axis: number,
+): void {
+ const d = DIVIDE_D;
+ for (let i = 0; i < nin; i++) d[i] = value - buf[inOff + i * 3 + axis]!;
+
+ let m = 0;
+ let n = 0;
+ for (let i = 0, j = nin - 1; i < nin; j = i, i++) {
+ const dj = d[j]!;
+ const di = d[i]!;
+ if ((dj >= 0) !== (di >= 0)) {
+ const s = dj / (dj - di);
+ for (let k = 0; k < 3; k++) {
+ const a = buf[inOff + j * 3 + k]!;
+ const v = a + (buf[inOff + i * 3 + k]! - a) * s;
+ buf[out1 + m * 3 + k] = v;
+ buf[out2 + n * 3 + k] = v;
+ }
+ m++; n++;
+ if (di > 0) {
+ for (let k = 0; k < 3; k++) buf[out1 + m * 3 + k] = buf[inOff + i * 3 + k]!;
+ m++;
+ } else if (di < 0) {
+ for (let k = 0; k < 3; k++) buf[out2 + n * 3 + k] = buf[inOff + i * 3 + k]!;
+ n++;
+ }
+ } else {
+ if (di >= 0) {
+ for (let k = 0; k < 3; k++) buf[out1 + m * 3 + k] = buf[inOff + i * 3 + k]!;
+ m++;
+ if (di !== 0) continue;
+ }
+ for (let k = 0; k < 3; k++) buf[out2 + n * 3 + k] = buf[inOff + i * 3 + k]!;
+ n++;
+ }
+ }
+ DIVIDE_OUT[0] = m;
+ DIVIDE_OUT[1] = n;
+}
+
+const DIVIDE_D = new Float32Array(12);
+
+/**
+ * Rasterise world-space triangles into solid spans. A triangle whose normal
+ * leans further from level than `walkableSlopeCos` allows is still solid — it is
+ * simply not ground, which is how a wall comes to block a route rather than
+ * disappear from it.
+ *
+ * @param verts `vertexCount * 3` world-space floats.
+ * @param indices Three per triangle.
+ */
+export function rasterizeTriangles(
+ hf: NavHeightfield, verts: Float32Array, indices: ArrayLike<number>,
+ walkableSlopeCos: number, mergeThreshold: number,
+): void {
+ for (let t = 0; t + 2 < indices.length; t += 3) {
+ const a = indices[t]! * 3;
+ const b = indices[t + 1]! * 3;
+ const c = indices[t + 2]! * 3;
+ const area = triangleArea(verts, a, b, c, walkableSlopeCos);
+ rasterizeTriangle(hf, verts, a, b, c, area, mergeThreshold);
+ }
+}
+
+/** Walkable when the triangle's own normal leans no further than allowed. */
+function triangleArea(
+ verts: Float32Array, a: number, b: number, c: number, walkableSlopeCos: number,
+): number {
+ const e0x = verts[b]! - verts[a]!;
+ const e0y = verts[b + 1]! - verts[a + 1]!;
+ const e0z = verts[b + 2]! - verts[a + 2]!;
+ const e1x = verts[c]! - verts[a]!;
+ const e1y = verts[c + 1]! - verts[a + 1]!;
+ const e1z = verts[c + 2]! - verts[a + 2]!;
+ const nx = e0y * e1z - e0z * e1y;
+ const ny = e0z * e1x - e0x * e1z;
+ const nz = e0x * e1y - e0y * e1x;
+ const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
+ if (len === 0) return NAV_AREA_NULL;
+ return ny / len > walkableSlopeCos ? NAV_AREA_WALKABLE : NAV_AREA_NULL;
+}
+
+function rasterizeTriangle(
+ hf: NavHeightfield, verts: Float32Array, a: number, b: number, c: number,
+ area: number, mergeThreshold: number,
+): void {
+ const { min, max, cellSize: cs, cellHeight: ch, width: w, depth: d } = hf;
+ const ics = 1 / cs;
+ const ich = 1 / ch;
+ const by = max.y - min.y;
+
+ let tminX = verts[a]!, tmaxX = tminX;
+ let tminY = verts[a + 1]!, tmaxY = tminY;
+ let tminZ = verts[a + 2]!, tmaxZ = tminZ;
+ for (let n = 0; n < 2; n++) {
+ const o = n === 0 ? b : c;
+ tminX = Math.min(tminX, verts[o]!); tmaxX = Math.max(tmaxX, verts[o]!);
+ tminY = Math.min(tminY, verts[o + 1]!); tmaxY = Math.max(tmaxY, verts[o + 1]!);
+ tminZ = Math.min(tminZ, verts[o + 2]!); tmaxZ = Math.max(tmaxZ, verts[o + 2]!);
+ }
+ if (tmaxX < min.x || tminX > max.x || tmaxY < min.y || tminY > max.y
+ || tmaxZ < min.z || tminZ > max.z) return;
+
+ const buf = CLIP_BUF;
+ let inOff = 0;
+ let rowOff = 7 * 3;
+ let p1 = 7 * 3 * 2;
+ let p2 = 7 * 3 * 3;
+ for (let k = 0; k < 3; k++) {
+ buf[k] = verts[a + k]!;
+ buf[3 + k] = verts[b + k]!;
+ buf[6 + k] = verts[c + k]!;
+ }
+ let nvIn = 3;
+
+ let z0 = Math.floor((tminZ - min.z) * ics);
+ let z1 = Math.floor((tmaxZ - min.z) * ics);
+ z0 = clampInt(z0, -1, d - 1);
+ z1 = clampInt(z1, 0, d - 1);
+
+ for (let z = z0; z <= z1; z++) {
+ const cz = min.z + z * cs;
+ dividePoly(buf, inOff, nvIn, rowOff, p1, cz + cs, 2);
+ const nvRow = DIVIDE_OUT[0]!;
+ nvIn = DIVIDE_OUT[1]!;
+ // What is left of the triangle rasterises in later rows; swap so the
+ // remainder becomes the input and the buffer we just read is free.
+ const swap = inOff; inOff = p1; p1 = swap;
+ if (nvRow < 3 || z < 0) continue;
+
+ let minX = buf[rowOff]!;
+ let maxX = minX;
+ for (let i = 1; i < nvRow; i++) {
+ minX = Math.min(minX, buf[rowOff + i * 3]!);
+ maxX = Math.max(maxX, buf[rowOff + i * 3]!);
+ }
+ let x0 = Math.floor((minX - min.x) * ics);
+ let x1 = Math.floor((maxX - min.x) * ics);
+ if (x1 < 0 || x0 >= w) continue;
+ x0 = clampInt(x0, -1, w - 1);
+ x1 = clampInt(x1, 0, w - 1);
+
+ let nv2 = nvRow;
+ for (let x = x0; x <= x1; x++) {
+ const cx = min.x + x * cs;
+ dividePoly(buf, rowOff, nv2, p1, p2, cx + cs, 0);
+ const nv = DIVIDE_OUT[0]!;
+ nv2 = DIVIDE_OUT[1]!;
+ const swapRow = rowOff; rowOff = p2; p2 = swapRow;
+ if (nv < 3 || x < 0) continue;
+
+ let smin = buf[p1 + 1]!;
+ let smax = smin;
+ for (let i = 1; i < nv; i++) {
+ smin = Math.min(smin, buf[p1 + i * 3 + 1]!);
+ smax = Math.max(smax, buf[p1 + i * 3 + 1]!);
+ }
+ smin -= min.y;
+ smax -= min.y;
+ if (smax < 0 || smin > by) continue;
+ if (smin < 0) smin = 0;
+ if (smax > by) smax = by;
+
+ const ismin = clampInt(Math.floor(smin * ich), 0, NAV_SPAN_MAX_HEIGHT);
+ const ismax = clampInt(Math.ceil(smax * ich), ismin + 1, NAV_SPAN_MAX_HEIGHT);
+ addSpan(hf, x, z, ismin, ismax, area, mergeThreshold);
+ }
+ }
+}
+
+function clampInt(v: number, lo: number, hi: number): number {
+ return v < lo ? lo : v > hi ? hi : v;
+}
+
+/**
+ * A solid span low enough to step onto becomes ground. Without this a kerb, a
+ * doorstep or the lip of a ramp reads as an obstacle standing on the floor, and
+ * every one of them cuts the walkable world in half.
+ */
+export function filterLowHangingWalkableObstacles(hf: NavHeightfield, walkableClimb: number): void {
+ for (let i = 0; i < hf.spans.length; i++) {
+ let prev: NavSpan | null = null;
+ let prevWalkable = false;
+ let prevArea = NAV_AREA_NULL;
+ for (let s = hf.spans[i] ?? null; s; s = s.next) {
+ const walkable = s.area !== NAV_AREA_NULL;
+ if (!walkable && prevWalkable && prev
+ && Math.abs(s.smax - prev.smax) <= walkableClimb) {
+ s.area = prevArea;
+ }
+ prevWalkable = walkable;
+ prevArea = s.area;
+ prev = s;
+ }
+ }
+}
+
+/**
+ * Ground on the edge of a drop is not ground. An agent standing there is half
+ * over the fall, and a route planned across it walks off — so the last row of
+ * cells before a ledge stops being walkable, which is also what keeps the top of
+ * a wall from connecting to the floor beside it.
+ */
+export function filterLedgeSpans(
+ hf: NavHeightfield, walkableHeight: number, walkableClimb: number,
+): void {
+ const { width: w, depth: d } = hf;
+ for (let z = 0; z < d; z++) {
+ for (let x = 0; x < w; x++) {
+ for (let s = hf.spans[x + z * w] ?? null; s; s = s.next) {
+ if (s.area === NAV_AREA_NULL) continue;
+ const bot = s.smax;
+ const top = s.next ? s.next.smin : NAV_SPAN_MAX_HEIGHT;
+
+ // How far DOWN the biggest reachable neighbour is, and the spread
+ // between the neighbours that are close enough to walk onto.
+ let minDrop = NAV_SPAN_MAX_HEIGHT;
+ let accessMin = s.smax;
+ let accessMax = s.smax;
+
+ for (let dir = 0; dir < 4; dir++) {
+ const nx = x + DIR_X[dir]!;
+ const nz = z + DIR_Z[dir]!;
+ if (nx < 0 || nz < 0 || nx >= w || nz >= d) {
+ minDrop = Math.min(minDrop, -walkableClimb - bot);
+ continue;
+ }
+ let ns = hf.spans[nx + nz * w] ?? null;
+ // The gap under the neighbour's lowest span: the floor there
+ // is the bottom of the world, not the span above it.
+ let nbot = -walkableClimb;
+ let ntop = ns ? ns.smin : NAV_SPAN_MAX_HEIGHT;
+ if (Math.min(top, ntop) - Math.max(bot, nbot) > walkableHeight) {
+ minDrop = Math.min(minDrop, nbot - bot);
+ }
+ for (; ns; ns = ns.next) {
+ nbot = ns.smax;
+ ntop = ns.next ? ns.next.smin : NAV_SPAN_MAX_HEIGHT;
+ if (Math.min(top, ntop) - Math.max(bot, nbot) <= walkableHeight) continue;
+ minDrop = Math.min(minDrop, nbot - bot);
+ if (Math.abs(nbot - bot) <= walkableClimb) {
+ accessMin = Math.min(accessMin, nbot);
+ accessMax = Math.max(accessMax, nbot);
+ }
+ }
+ }
+
+ if (minDrop < -walkableClimb) s.area = NAV_AREA_NULL;
+ else if (accessMax - accessMin > walkableClimb) s.area = NAV_AREA_NULL;
+ }
+ }
+ }
+}
+
+/** Ground with less headroom than the agent is tall is a crawlspace, not floor. */
+export function filterWalkableLowHeightSpans(hf: NavHeightfield, walkableHeight: number): void {
+ for (let i = 0; i < hf.spans.length; i++) {
+ for (let s = hf.spans[i] ?? null; s; s = s.next) {
+ const top = s.next ? s.next.smin : NAV_SPAN_MAX_HEIGHT;
+ if (top - s.smax < walkableHeight) s.area = NAV_AREA_NULL;
+ }
+ }
+}
+
+/** Neighbour offsets, indexed by direction: 0 = -x, 1 = +z, 2 = +x, 3 = -z.
+ * Every walk over the field turns with `(dir + 1) & 3`, so the order matters. */
+export const DIR_X = [-1, 0, 1, 0] as const;
+export const DIR_Z = [0, 1, 0, -1] as const;
diff --git a/sdk/src/ai/nav/navmesh/polymesh.ts b/sdk/src/ai/nav/navmesh/polymesh.ts
new file mode 100644
index 000000000..46120977e
--- /dev/null
+++ b/sdk/src/ai/nav/navmesh/polymesh.ts
@@ -0,0 +1,401 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file polymesh.ts
+ * @brief Turn region outlines into convex polygons that know their neighbours.
+ *
+ * Convex is the point: inside one polygon an agent can walk from any point to
+ * any other in a straight line, so a route only ever has to name the polygons it
+ * crosses and the doorways between them. Getting there is ear clipping, then
+ * merging the resulting triangles back into the biggest convex shapes that still
+ * fit — fewer, larger polygons mean a shorter search and a straighter path.
+ *
+ * Vertices are shared between contours: two regions that touch traced the same
+ * corners, so they land on the same vertex indices and their polygons come out
+ * adjacent. Vertices at the same spot but far apart in height stay separate,
+ * which is what keeps a bridge from being welded to the road under it.
+ */
+
+import type { NavContour } from './contours';
+
+/** No polygon on this edge. */
+export const NAV_NO_NEIGHBOUR = -1;
+
+export interface NavPolyMesh {
+ /** `x, y, z` voxel coordinates per vertex. */
+ verts: Int32Array;
+ vertCount: number;
+ /** `maxVertsPerPoly` vertex indices per polygon, padded with -1. */
+ polys: Int32Array;
+ /** `maxVertsPerPoly` neighbour polygon indices, one per edge, -1 for none. */
+ neis: Int32Array;
+ polyCount: number;
+ maxVertsPerPoly: number;
+}
+
+/**
+ * @param maxVertsPerPoly How many corners a polygon may have. Six is Recast's
+ * default and the number this pipeline is tuned around: more merges the
+ * mesh further but makes every per-edge loop longer.
+ */
+export function buildPolyMesh(contours: NavContour[], maxVertsPerPoly: number): NavPolyMesh {
+ const nvp = Math.max(3, maxVertsPerPoly);
+ const verts: number[] = [];
+ const vertLookup = new Map<number, number[]>();
+ const polys: number[] = [];
+
+ const indices: number[] = [];
+ const tris: number[] = [];
+
+ for (const contour of contours) {
+ const n = contour.verts.length / 3;
+ if (n < 3) continue;
+
+ indices.length = 0;
+ for (let i = 0; i < n; i++) indices.push(i);
+ tris.length = 0;
+ // A negative count is a contour that crossed itself; what it did manage
+ // to cut is still better than dropping the region entirely.
+ const ntris = Math.abs(triangulate(n, contour.verts, indices, tris));
+ if (ntris === 0) continue;
+
+ // Contour-local vertex indices become mesh-wide ones here, which is where
+ // the sharing between neighbouring regions happens.
+ const mapped: number[] = [];
+ for (let i = 0; i < n; i++) {
+ mapped.push(addVertex(verts, vertLookup,
+ contour.verts[i * 3]!, contour.verts[i * 3 + 1]!, contour.verts[i * 3 + 2]!));
+ }
+
+ const local: number[] = [];
+ for (let t = 0; t < ntris; t++) {
+ const a = mapped[tris[t * 3]!]!;
+ const b = mapped[tris[t * 3 + 1]!]!;
+ const c = mapped[tris[t * 3 + 2]!]!;
+ if (a === b || b === c || c === a) continue;
+ const base = local.length;
+ for (let k = 0; k < nvp; k++) local.push(-1);
+ local[base] = a;
+ local[base + 1] = b;
+ local[base + 2] = c;
+ }
+
+ mergePolygons(local, verts, nvp);
+ for (const v of local) polys.push(v);
+ }
+
+ const polyCount = polys.length / nvp;
+ const mesh: NavPolyMesh = {
+ verts: Int32Array.from(verts),
+ vertCount: verts.length / 3,
+ polys: Int32Array.from(polys),
+ neis: new Int32Array(polyCount * nvp).fill(NAV_NO_NEIGHBOUR),
+ polyCount,
+ maxVertsPerPoly: nvp,
+ };
+ buildAdjacency(mesh);
+ return mesh;
+}
+
+/**
+ * Index of a vertex at `(x, y, z)`, adding it if it is new. Two corners at one
+ * spot in the ground plane are the same vertex only if their heights are within a
+ * voxel or two: two regions round a shared height slightly differently, while a
+ * floor and the floor above it are nowhere near.
+ */
+function addVertex(
+ verts: number[], lookup: Map<number, number[]>, x: number, y: number, z: number,
+): number {
+ const key = (x * 73856093) ^ (z * 83492791);
+ let bucket = lookup.get(key);
+ if (!bucket) { bucket = []; lookup.set(key, bucket); }
+ for (const i of bucket) {
+ if (verts[i * 3] === x && verts[i * 3 + 2] === z
+ && Math.abs(verts[i * 3 + 1]! - y) <= VERTEX_WELD_VOXELS) return i;
+ }
+ const index = verts.length / 3;
+ verts.push(x, y, z);
+ bucket.push(index);
+ return index;
+}
+
+/** How far apart in voxels two corners at one spot may be and still be one
+ * vertex. Recast's number, and the reason it is not zero is that the corner
+ * height is a max over four cells, taken from two different sides. */
+const VERTEX_WELD_VOXELS = 2;
+
+// ---------------------------------------------------------------------------
+// Ear clipping
+// ---------------------------------------------------------------------------
+
+/** Twice the signed area of a triangle in the ground plane. */
+function area2(verts: Int32Array, a: number, b: number, c: number): number {
+ return (verts[b * 3]! - verts[a * 3]!) * (verts[c * 3 + 2]! - verts[a * 3 + 2]!)
+ - (verts[c * 3]! - verts[a * 3]!) * (verts[b * 3 + 2]! - verts[a * 3 + 2]!);
+}
+
+function xorb(a: boolean, b: boolean): boolean {
+ return a !== b;
+}
+
+function left(v: Int32Array, a: number, b: number, c: number): boolean {
+ return area2(v, a, b, c) < 0;
+}
+
+function leftOn(v: Int32Array, a: number, b: number, c: number): boolean {
+ return area2(v, a, b, c) <= 0;
+}
+
+function collinear(v: Int32Array, a: number, b: number, c: number): boolean {
+ return area2(v, a, b, c) === 0;
+}
+
+function intersectProp(v: Int32Array, a: number, b: number, c: number, d: number): boolean {
+ if (collinear(v, a, b, c) || collinear(v, a, b, d)
+ || collinear(v, c, d, a) || collinear(v, c, d, b)) return false;
+ return xorb(left(v, a, b, c), left(v, a, b, d)) && xorb(left(v, c, d, a), left(v, c, d, b));
+}
+
+function between(v: Int32Array, a: number, b: number, c: number): boolean {
+ if (!collinear(v, a, b, c)) return false;
+ if (v[a * 3] !== v[b * 3]) {
+ return (v[a * 3]! <= v[c * 3]! && v[c * 3]! <= v[b * 3]!)
+ || (v[a * 3]! >= v[c * 3]! && v[c * 3]! >= v[b * 3]!);
+ }
+ return (v[a * 3 + 2]! <= v[c * 3 + 2]! && v[c * 3 + 2]! <= v[b * 3 + 2]!)
+ || (v[a * 3 + 2]! >= v[c * 3 + 2]! && v[c * 3 + 2]! >= v[b * 3 + 2]!);
+}
+
+function intersect(v: Int32Array, a: number, b: number, c: number, d: number): boolean {
+ return intersectProp(v, a, b, c, d)
+ || between(v, a, b, c) || between(v, a, b, d)
+ || between(v, c, d, a) || between(v, c, d, b);
+}
+
+function vequal(v: Int32Array, a: number, b: number): boolean {
+ return v[a * 3] === v[b * 3] && v[a * 3 + 2] === v[b * 3 + 2];
+}
+
+const INDEX_MASK = 0x0fffffff;
+const EAR_FLAG = 0x10000000;
+
+/** Whether the diagonal (i, j) stays strictly inside the polygon. */
+function diagonalie(v: Int32Array, n: number, indices: number[], i: number, j: number): boolean {
+ const d0 = indices[i]! & INDEX_MASK;
+ const d1 = indices[j]! & INDEX_MASK;
+ for (let k = 0; k < n; k++) {
+ const k1 = (k + 1) % n;
+ if (k === i || k1 === i || k === j || k1 === j) continue;
+ const p0 = indices[k]! & INDEX_MASK;
+ const p1 = indices[k1]! & INDEX_MASK;
+ if (vequal(v, d0, p0) || vequal(v, d1, p0) || vequal(v, d0, p1) || vequal(v, d1, p1)) continue;
+ if (intersect(v, d0, d1, p0, p1)) return false;
+ }
+ return true;
+}
+
+/** Whether the diagonal leaves vertex `i` into the polygon rather than out of it. */
+function inCone(v: Int32Array, n: number, indices: number[], i: number, j: number): boolean {
+ const p = indices[i]! & INDEX_MASK;
+ const pn = indices[(i + 1) % n]! & INDEX_MASK;
+ const pp = indices[(i + n - 1) % n]! & INDEX_MASK;
+ const q = indices[j]! & INDEX_MASK;
+ if (leftOn(v, pp, p, pn)) return left(v, p, q, pp) && left(v, q, p, pn);
+ return !(leftOn(v, p, q, pn) && leftOn(v, q, p, pp));
+}
+
+function diagonal(v: Int32Array, n: number, indices: number[], i: number, j: number): boolean {
+ return inCone(v, n, indices, i, j) && diagonalie(v, n, indices, i, j);
+}
+
+/**
+ * Ear clipping over the contour, always cutting the shortest available ear so
+ * the triangles stay as fat as they can. Returns how many were produced, or a
+ * negative count if the contour was too tangled to finish.
+ */
+function triangulate(n: number, verts: Int32Array, indices: number[], tris: number[]): number {
+ let ntris = 0;
+ let count = n;
+
+ for (let i = 0; i < count; i++) {
+ const i1 = (i + 1) % count;
+ const i2 = (i1 + 1) % count;
+ if (diagonal(verts, count, indices, i, i2)) indices[i1] = indices[i1]! | EAR_FLAG;
+ }
+
+ while (count > 3) {
+ let minLen = -1;
+ let mini = -1;
+ for (let i = 0; i < count; i++) {
+ const i1 = (i + 1) % count;
+ if ((indices[i1]! & EAR_FLAG) === 0) continue;
+ const p0 = (indices[i]! & INDEX_MASK) * 3;
+ const p2 = (indices[(i1 + 1) % count]! & INDEX_MASK) * 3;
+ const dx = verts[p2]! - verts[p0]!;
+ const dz = verts[p2 + 2]! - verts[p0 + 2]!;
+ const len = dx * dx + dz * dz;
+ if (minLen < 0 || len < minLen) { minLen = len; mini = i; }
+ }
+ // No ear anywhere means the outline crosses itself; hand back what there
+ // is rather than loop, and let the caller drop the contour.
+ if (mini === -1) return -ntris;
+
+ const i = mini;
+ const i1 = (i + 1) % count;
+ const i2 = (i1 + 1) % count;
+ tris.push(indices[i]! & INDEX_MASK, indices[i1]! & INDEX_MASK, indices[i2]! & INDEX_MASK);
+ ntris++;
+
+ count--;
+ for (let k = i1; k < count; k++) indices[k] = indices[k + 1]!;
+ const j1 = i1 >= count ? 0 : i1;
+ const j = (j1 + count - 1) % count;
+ setEar(verts, count, indices, (j + count - 1) % count, j1, j);
+ setEar(verts, count, indices, j, (j1 + 1) % count, j1);
+ }
+
+ tris.push(indices[0]! & INDEX_MASK, indices[1]! & INDEX_MASK, indices[2]! & INDEX_MASK);
+ return ntris + 1;
+}
+
+function setEar(
+ verts: Int32Array, count: number, indices: number[], from: number, to: number, at: number,
+): void {
+ if (diagonal(verts, count, indices, from, to)) indices[at] = indices[at]! | EAR_FLAG;
+ else indices[at] = indices[at]! & INDEX_MASK;
+}
+
+// ---------------------------------------------------------------------------
+// Convex merging
+// ---------------------------------------------------------------------------
+
+function polyVertCount(poly: number[], base: number, nvp: number): number {
+ for (let i = 0; i < nvp; i++) if (poly[base + i] === -1) return i;
+ return nvp;
+}
+
+/** True when `c` is left of the line `a → b` — the convexity test at a joint. */
+function uleft(verts: number[], a: number, b: number, c: number): boolean {
+ return (verts[b * 3]! - verts[a * 3]!) * (verts[c * 3 + 2]! - verts[a * 3 + 2]!)
+ - (verts[c * 3]! - verts[a * 3]!) * (verts[b * 3 + 2]! - verts[a * 3 + 2]!) < 0;
+}
+
+/** Where two polygons touch, and how good a merge it would be — the squared
+ * length of the edge that would vanish, or -1 when they cannot merge at all. */
+function polyMergeValue(
+ polys: number[], verts: number[], a: number, b: number, nvp: number, out: Int32Array,
+): number {
+ const na = polyVertCount(polys, a, nvp);
+ const nb = polyVertCount(polys, b, nvp);
+ if (na + nb - 2 > nvp) return -1;
+
+ let ea = -1;
+ let eb = -1;
+ for (let i = 0; i < na && ea === -1; i++) {
+ let va0 = polys[a + i]!;
+ let va1 = polys[a + (i + 1) % na]!;
+ if (va0 > va1) { const t = va0; va0 = va1; va1 = t; }
+ for (let j = 0; j < nb; j++) {
+ let vb0 = polys[b + j]!;
+ let vb1 = polys[b + (j + 1) % nb]!;
+ if (vb0 > vb1) { const t = vb0; vb0 = vb1; vb1 = t; }
+ if (va0 === vb0 && va1 === vb1) { ea = i; eb = j; break; }
+ }
+ }
+ if (ea === -1 || eb === -1) return -1;
+
+ // Both joints where the two outlines meet have to stay convex, or the merged
+ // polygon would have a notch and "straight line inside it" would be a lie.
+ if (!uleft(verts, polys[a + (ea + na - 1) % na]!, polys[a + ea]!, polys[b + (eb + 2) % nb]!)) return -1;
+ if (!uleft(verts, polys[b + (eb + nb - 1) % nb]!, polys[b + eb]!, polys[a + (ea + 2) % na]!)) return -1;
+
+ const va = polys[a + ea]!;
+ const vb = polys[a + (ea + 1) % na]!;
+ const dx = verts[va * 3]! - verts[vb * 3]!;
+ const dz = verts[va * 3 + 2]! - verts[vb * 3 + 2]!;
+ out[0] = ea;
+ out[1] = eb;
+ return dx * dx + dz * dz;
+}
+
+function mergePolygons(polys: number[], verts: number[], nvp: number): void {
+ if (nvp <= 3) return;
+ const edge = new Int32Array(2);
+ const tmp = new Array<number>(nvp);
+
+ for (;;) {
+ let bestValue = 0;
+ let bestA = -1;
+ let bestB = -1;
+ let bestEa = 0;
+ let bestEb = 0;
+ const count = polys.length / nvp;
+ for (let i = 0; i < count - 1; i++) {
+ for (let j = i + 1; j < count; j++) {
+ const v = polyMergeValue(polys, verts, i * nvp, j * nvp, nvp, edge);
+ if (v <= bestValue) continue;
+ bestValue = v;
+ bestA = i; bestB = j;
+ bestEa = edge[0]!; bestEb = edge[1]!;
+ }
+ }
+ if (bestA === -1) break;
+
+ const a = bestA * nvp;
+ const b = bestB * nvp;
+ const na = polyVertCount(polys, a, nvp);
+ const nb = polyVertCount(polys, b, nvp);
+ tmp.fill(-1);
+ let n = 0;
+ for (let i = 0; i < na - 1; i++) tmp[n++] = polys[a + (bestEa + 1 + i) % na]!;
+ for (let i = 0; i < nb - 1; i++) tmp[n++] = polys[b + (bestEb + 1 + i) % nb]!;
+ for (let i = 0; i < nvp; i++) polys[a + i] = tmp[i]!;
+
+ // The merged-away polygon is filled by the last one, so the array stays
+ // packed without shifting everything after it.
+ const last = polys.length - nvp;
+ for (let i = 0; i < nvp; i++) polys[b + i] = polys[last + i]!;
+ polys.length = last;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Adjacency
+// ---------------------------------------------------------------------------
+
+/**
+ * Link polygons that share an edge. Every interior edge is traced twice, once
+ * from each side and in opposite directions — that is what a consistent winding
+ * buys — so matching `(v0, v1)` against `(v1, v0)` finds each pair exactly once.
+ */
+function buildAdjacency(mesh: NavPolyMesh): void {
+ const { polys, neis, polyCount, maxVertsPerPoly: nvp } = mesh;
+ const seen = new Map<number, number>();
+
+ for (let p = 0; p < polyCount; p++) {
+ const base = p * nvp;
+ for (let j = 0; j < nvp; j++) {
+ const v0 = polys[base + j]!;
+ if (v0 === -1) break;
+ const nextIdx = j + 1 >= nvp || polys[base + j + 1] === -1 ? 0 : j + 1;
+ const v1 = polys[base + nextIdx]!;
+ if (v0 >= v1) continue;
+ seen.set(v0 * mesh.vertCount + v1, base + j);
+ }
+ }
+
+ for (let p = 0; p < polyCount; p++) {
+ const base = p * nvp;
+ for (let j = 0; j < nvp; j++) {
+ const v0 = polys[base + j]!;
+ if (v0 === -1) break;
+ const nextIdx = j + 1 >= nvp || polys[base + j + 1] === -1 ? 0 : j + 1;
+ const v1 = polys[base + nextIdx]!;
+ if (v0 <= v1) continue;
+ const other = seen.get(v1 * mesh.vertCount + v0);
+ if (other === undefined) continue;
+ neis[base + j] = ((other / nvp) | 0);
+ neis[other] = p;
+ }
+ }
+}
diff --git a/sdk/src/ai/nav/navmesh/regions.ts b/sdk/src/ai/nav/navmesh/regions.ts
new file mode 100644
index 000000000..e61b1ce29
--- /dev/null
+++ b/sdk/src/ai/nav/navmesh/regions.ts
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file regions.ts
+ * @brief Cut the walkable spans into regions — connected patches that a single
+ * simple outline can describe.
+ *
+ * Monotone partitioning: sweep the field row by row, and let a run of spans keep
+ * the region of the run behind it whenever the two line up one to one. What comes
+ * out is a set of patches with NO HOLES, which is what lets the contour tracer
+ * that follows be one walk around one boundary. Recast's other partitioners give
+ * rounder patches and can produce a region with an island inside it, which then
+ * needs a whole second stage to stitch back up; this pipeline buys robustness
+ * with the shape of its polygons, and `cellSize` is the knob that matters more.
+ */
+
+import { NAV_AREA_NULL } from './heightfield';
+import type { NavCompactField } from './compact';
+
+/** A sweep that touched more than one region behind it, so it can inherit none. */
+const AMBIGUOUS = -1;
+
+interface Sweep {
+ /** Region behind this run, or {@link AMBIGUOUS} when there was more than one. */
+ nei: number;
+ /** How many of this run's spans touch `nei`. */
+ ns: number;
+ /** Final region id, decided at the end of the row. */
+ id: number;
+}
+
+/**
+ * Fill `chf.regs` and return how many region ids were handed out; 0 means "no
+ * region", which is what an unwalkable span keeps. `minRegionArea` is in spans: a
+ * patch smaller than that and reachable from nowhere else is an artefact of the
+ * voxel grid, and a polygon for it is a destination nobody can walk to.
+ */
+export function buildRegionsMonotone(chf: NavCompactField, minRegionArea: number): number {
+ const { width: w, depth: d } = chf;
+ const regs = chf.regs;
+ regs.fill(0);
+
+ let nextId = 1;
+ const sweeps: Sweep[] = [];
+ const prev = new Map<number, number>();
+
+ for (let z = 0; z < d; z++) {
+ prev.clear();
+ let rid = 1;
+ for (let x = 0; x < w; x++) {
+ const c = x + z * w;
+ const start = chf.cellIndex[c]!;
+ const end = start + chf.cellCount[c]!;
+ for (let i = start; i < end; i++) {
+ if (chf.areas[i] === NAV_AREA_NULL) continue;
+
+ // Behind on this row: the run continues if it can.
+ let sweepId = 0;
+ const back = chf.neighbourSpan(x, z, i, 0);
+ if (back >= 0 && chf.areas[back] === chf.areas[i] && regs[back]! > 0) {
+ sweepId = regs[back]!;
+ }
+ if (sweepId === 0) {
+ sweepId = rid++;
+ sweeps[sweepId] = { nei: 0, ns: 0, id: 0 };
+ }
+
+ // Behind on the previous row: which region this run may inherit.
+ const under = chf.neighbourSpan(x, z, i, 3);
+ if (under >= 0 && regs[under]! > 0 && chf.areas[under] === chf.areas[i]) {
+ const nr = regs[under]!;
+ const sweep = sweeps[sweepId]!;
+ if (sweep.nei === 0 || sweep.nei === nr) {
+ sweep.nei = nr;
+ sweep.ns++;
+ prev.set(nr, (prev.get(nr) ?? 0) + 1);
+ } else {
+ sweep.nei = AMBIGUOUS;
+ }
+ }
+
+ regs[i] = sweepId;
+ }
+ }
+
+ // A run inherits only when it covers the whole of the run behind it —
+ // otherwise the two would become one region shaped like a Y, which is
+ // exactly the hole-prone shape this partitioner exists to avoid.
+ for (let i = 1; i < rid; i++) {
+ const sweep = sweeps[i]!;
+ sweep.id = sweep.nei > 0 && prev.get(sweep.nei) === sweep.ns ? sweep.nei : nextId++;
+ }
+
+ for (let x = 0; x < w; x++) {
+ const c = x + z * w;
+ const start = chf.cellIndex[c]!;
+ const end = start + chf.cellCount[c]!;
+ for (let i = start; i < end; i++) {
+ const r = regs[i]!;
+ if (r > 0 && r < rid) regs[i] = sweeps[r]!.id;
+ }
+ }
+ }
+
+ removeSmallRegions(chf, nextId, minRegionArea);
+ return nextId;
+}
+
+/**
+ * Drop patches of walkable ground that are too small to be worth a polygon AND
+ * reachable from nowhere else. Size is judged over the whole connected group of
+ * regions, not one at a time: a big room cut into six regions by the sweep is
+ * not six small islands.
+ */
+function removeSmallRegions(chf: NavCompactField, regionCount: number, minRegionArea: number): void {
+ if (minRegionArea <= 0) return;
+ const { width: w, depth: d } = chf;
+ const spanCount = new Int32Array(regionCount);
+ const linked: Set<number>[] = Array.from({ length: regionCount }, () => new Set<number>());
+
+ for (let z = 0; z < d; z++) {
+ for (let x = 0; x < w; x++) {
+ const c = x + z * w;
+ const start = chf.cellIndex[c]!;
+ const end = start + chf.cellCount[c]!;
+ for (let i = start; i < end; i++) {
+ const r = chf.regs[i]!;
+ if (r === 0) continue;
+ spanCount[r]!++;
+ for (let dir = 0; dir < 4; dir++) {
+ const ni = chf.neighbourSpan(x, z, i, dir);
+ if (ni < 0) continue;
+ const nr = chf.regs[ni]!;
+ if (nr !== 0 && nr !== r) linked[r]!.add(nr);
+ }
+ }
+ }
+ }
+
+ const visited = new Uint8Array(regionCount);
+ const doomed = new Set<number>();
+ for (let r = 1; r < regionCount; r++) {
+ if (visited[r] || spanCount[r] === 0) continue;
+ const group: number[] = [];
+ const stack = [r];
+ visited[r] = 1;
+ let total = 0;
+ while (stack.length) {
+ const cur = stack.pop()!;
+ group.push(cur);
+ total += spanCount[cur]!;
+ for (const nr of linked[cur]!) {
+ if (visited[nr]) continue;
+ visited[nr] = 1;
+ stack.push(nr);
+ }
+ }
+ if (total < minRegionArea) for (const g of group) doomed.add(g);
+ }
+
+ if (doomed.size === 0) return;
+ for (let i = 0; i < chf.spanCount; i++) {
+ if (doomed.has(chf.regs[i]!)) chf.regs[i] = 0;
+ }
+}
diff --git a/sdk/src/ai/nav/pathfind.ts b/sdk/src/ai/nav/pathfind.ts
index 4fb3b684c..d3ac83cc3 100644
--- a/sdk/src/ai/nav/pathfind.ts
+++ b/sdk/src/ai/nav/pathfind.ts
@@ -11,6 +11,7 @@
*/
import type { NavGrid, Cell } from './NavGrid';
+import { MinHeap } from './minHeap';
import type { Vec3 } from '../../types';
export interface PathfindOptions {
@@ -88,9 +89,6 @@ export function findPath(
const nx = cx + dx;
const ny = cy + dy;
if (!fits(grid, nx, ny, clearance)) continue;
- // Ground that steps up further than the agent can climb is a wall,
- // however walkable the cell on top of it is.
- if (!grid.canStep(cx, cy, nx, ny)) continue;
// No corner-cutting: a diagonal needs both shared orthogonals open.
if (i >= 4 && (!fits(grid, cx + dx, cy, clearance) || !fits(grid, cx, cy + dy, clearance))) continue;
@@ -148,64 +146,3 @@ function reconstruct(cameFrom: Int32Array, goalIdx: number, width: number): Cell
path.reverse();
return path;
}
-
-/**
- * Binary min-heap of cell indices keyed by an f-score, backed by flat typed
- * arrays. Lazy-deletion friendly: a cell may be pushed more than once with a
- * lower key; the search skips already-closed pops.
- */
-class MinHeap {
- private nodes: Int32Array;
- private keys: Float64Array;
- size = 0;
-
- constructor(capacityHint: number) {
- const cap = Math.max(16, capacityHint);
- this.nodes = new Int32Array(cap);
- this.keys = new Float64Array(cap);
- }
-
- push(node: number, key: number): void {
- if (this.size === this.nodes.length) this.grow();
- let i = this.size++;
- this.nodes[i] = node;
- this.keys[i] = key;
- while (i > 0) {
- const parent = (i - 1) >> 1;
- if (this.keys[parent] <= this.keys[i]) break;
- this.swap(i, parent);
- i = parent;
- }
- }
-
- pop(): number {
- const top = this.nodes[0];
- const last = --this.size;
- this.nodes[0] = this.nodes[last];
- this.keys[0] = this.keys[last];
- let i = 0;
- for (;;) {
- const l = i * 2 + 1;
- const r = l + 1;
- let smallest = i;
- if (l < this.size && this.keys[l] < this.keys[smallest]) smallest = l;
- if (r < this.size && this.keys[r] < this.keys[smallest]) smallest = r;
- if (smallest === i) break;
- this.swap(i, smallest);
- i = smallest;
- }
- return top;
- }
-
- private swap(a: number, b: number): void {
- const tn = this.nodes[a]; this.nodes[a] = this.nodes[b]; this.nodes[b] = tn;
- const tk = this.keys[a]; this.keys[a] = this.keys[b]; this.keys[b] = tk;
- }
-
- private grow(): void {
- const nn = new Int32Array(this.nodes.length * 2);
- const nk = new Float64Array(this.keys.length * 2);
- nn.set(this.nodes); nk.set(this.keys);
- this.nodes = nn; this.keys = nk;
- }
-}
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 3e7f9434b..3ab50a729 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -656,11 +656,15 @@ export type {
} from './physics';
// =============================================================================
-// AI — Navigation (grid A* today; state machines / behavior trees to come)
+// AI — Navigation (a grid for cells, a polygon mesh for geometry)
// =============================================================================
export {
NavGrid,
+ NavMesh,
+ buildNavMesh,
+ collectNavGeometry,
+ navGeometryReady,
findPath,
pathToWorld,
navGridFromTiles,
@@ -674,18 +678,21 @@ export {
NavPlugin,
navPlugin,
NavDebugDraw,
- bakeNavGrid,
+ type NavSurface,
+ type NavSurfaceSink,
+ type NavQueryOptions,
+ type NavPoint,
type NavGridOptions,
- type NavPlane,
+ type NavMeshData,
+ type BuildNavMeshOptions,
+ type NavGeometry,
+ type CollectNavGeometryOptions,
type Cell,
type PathfindOptions,
type BuildNavGridOptions,
type NavAgentData,
type NavVolumeData,
- type BakeNavGridOptions,
type NavDebugDrawConfig,
- type GroundProbe,
- type GroundHit,
} from './ai';
// =============================================================================
diff --git a/sdk/src/physics3d/ColliderShape3D.ts b/sdk/src/physics3d/ColliderShape3D.ts
index 179d951be..4bd653958 100644
--- a/sdk/src/physics3d/ColliderShape3D.ts
+++ b/sdk/src/physics3d/ColliderShape3D.ts
@@ -280,3 +280,75 @@ export function placeCollider3DWireframe(lines: Vec3[][], position: Vec3, rotati
return { x: position.x + r.x, y: position.y + r.y, z: position.z + r.z };
}));
}
+
+/** Points around a sphere or capsule when it is turned into triangles. Coarser
+ * than the wireframe: this feeds a voxeliser, which rounds everything onto its
+ * own grid anyway, and every extra ring is triangles it has to rasterise. */
+const SOLID_SEGMENTS = 8;
+
+/**
+ * The shape as a closed triangle soup in entity-local space, wound so a face's
+ * normal points OUT — which way a face points is part of the answer to a caller
+ * like a navigation bake, where an upward normal is what makes a triangle ground
+ * rather than wall. The sibling of {@link collider3DWireframe}, in triangles.
+ */
+export function collider3DTriangles(
+ shape: Collider3DShape,
+): { positions: Float32Array; indices: Uint32Array } {
+ if (shape.kind === 'box') {
+ const { center: c, halfExtents: h } = shape;
+ const positions = new Float32Array(8 * 3);
+ let n = 0;
+ for (const sy of [-1, 1] as const) {
+ for (const [sx, sz] of [[-1, -1], [1, -1], [1, 1], [-1, 1]] as const) {
+ positions[n++] = c.x + sx * h.x;
+ positions[n++] = c.y + sy * h.y;
+ positions[n++] = c.z + sz * h.z;
+ }
+ }
+ return { positions, indices: Uint32Array.from(BOX_INDICES) };
+ }
+
+ // A capsule is a sphere cut at its equator and pulled apart, so both are the
+ // same stack of rings with the two halves offset — and the equator ring
+ // appears twice, which is what makes the straight wall between them.
+ const radius = shape.radius;
+ const halfHeight = shape.kind === 'capsule' ? shape.halfHeight : 0;
+ const rings = SOLID_SEGMENTS;
+ const segs = SOLID_SEGMENTS;
+ const rows = rings + 2;
+ const positions = new Float32Array(rows * (segs + 1) * 3);
+ let n = 0;
+ for (let r = 0; r < rows; r++) {
+ const upper = r <= rings / 2;
+ const phi = ((upper ? r : r - 1) / rings) * Math.PI;
+ const y = Math.cos(phi) * radius + (upper ? halfHeight : -halfHeight);
+ const ringRadius = Math.sin(phi) * radius;
+ for (let s = 0; s <= segs; s++) {
+ const theta = (s / segs) * Math.PI * 2;
+ positions[n++] = Math.cos(theta) * ringRadius;
+ positions[n++] = y;
+ positions[n++] = Math.sin(theta) * ringRadius;
+ }
+ }
+ const indices: number[] = [];
+ for (let r = 0; r + 1 < rows; r++) {
+ for (let s = 0; s < segs; s++) {
+ const a = r * (segs + 1) + s;
+ const b = a + segs + 1;
+ indices.push(a, a + 1, b, a + 1, b + 1, b);
+ }
+ }
+ return { positions, indices: Uint32Array.from(indices) };
+}
+
+/** The twelve triangles over the eight corners emitted above, every one of them
+ * wound counter-clockwise seen from outside the box. */
+const BOX_INDICES: readonly number[] = [
+ 0, 1, 2, 0, 2, 3,
+ 4, 6, 5, 4, 7, 6,
+ 0, 4, 5, 0, 5, 1,
+ 1, 5, 6, 1, 6, 2,
+ 2, 6, 7, 2, 7, 3,
+ 3, 7, 4, 3, 4, 0,
+];
diff --git a/sdk/tests/ai-enemy-integration.test.ts b/sdk/tests/ai-enemy-integration.test.ts
index f6114cccd..564c45f3d 100644
--- a/sdk/tests/ai-enemy-integration.test.ts
+++ b/sdk/tests/ai-enemy-integration.test.ts
@@ -58,7 +58,7 @@ describe('enemy AI (FSM + navigation)', () => {
it('patrols while the player is far, then chases via the nav agent when sensed', () => {
const world = new FakeWorld();
const nav = new Navigation();
- nav.setGrid(new NavGrid({ width: 40, height: 40, cellSize: 20 })); // open 800x800 grid
+ nav.setSurface(new NavGrid({ width: 40, height: 40, cellSize: 20 })); // open 800x800 grid
const fsmStates = new Map();
const navRuntimes = new Map<Entity, AgentRuntime>();
@@ -119,7 +119,7 @@ describe('enemy AI (FSM + navigation)', () => {
it('breaks off the chase and returns to patrol when the player escapes', () => {
const world = new FakeWorld();
const nav = new Navigation();
- nav.setGrid(new NavGrid({ width: 40, height: 40, cellSize: 20 }));
+ nav.setSurface(new NavGrid({ width: 40, height: 40, cellSize: 20 }));
const fsmStates = new Map();
const navRuntimes = new Map<Entity, AgentRuntime>();
diff --git a/sdk/tests/nav-bake.test.ts b/sdk/tests/nav-bake.test.ts
deleted file mode 100644
index dd78a5597..000000000
--- a/sdk/tests/nav-bake.test.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file Baking a walkable grid out of what the 3D solver can see.
- *
- * The claims are about what makes a cell UNwalkable — a hole, a wall, a ceiling
- * too low — and about the height it reports for the ones that survive, because
- * that height is what the agent then walks along.
- */
-import { describe, it, expect, vi } from 'vitest';
-import { bakeNavGrid, type GroundHit, type GroundProbe } from '../src/ai/nav/bakeNavGrid';
-import { bakeVolumes } from '../src/ai/nav/NavPlugin';
-import { NavVolume, type NavVolumeData } from '../src/ai/nav/NavVolume';
-import { Navigation } from '../src/ai/nav/Navigation';
-import { Transform } from '../src/ecs/component';
-import type { Physics3DQueries } from '../src/physics3d/Physics3DQueries';
-import type { Vec3 } from '../src/types';
-
-// The engine's own solver satisfies the probe as it stands — the reason the
-// interface is this small. A type-level check, so it costs nothing at runtime
-// and fails at compile time if the two ever drift apart.
-type SolverIsAProbe = Physics3DQueries extends GroundProbe ? true : false;
-const _solverIsAProbe: SolverIsAProbe = true;
-void _solverIsAProbe;
-
-/** A solver that answers by the world position of the ray, not by its own state. */
-function probeOf(
- ground: (x: number, z: number) => GroundHit | null,
- ceiling: (x: number, z: number) => boolean = () => false,
-): GroundProbe {
- return {
- raycast(origin: Vec3, direction: Vec3): GroundHit | null {
- // Down is the ground query; up is the headroom one.
- if (direction.y < 0) return ground(origin.x, origin.z);
- return ceiling(origin.x, origin.z) ? { y: origin.y + 1, normalY: -1 } : null;
- },
- };
-}
-
-const LEVEL = (y: number): GroundHit => ({ y, normalY: 1 });
-const BOX = { min: { x: 0, y: -100, z: 0 }, max: { x: 20, y: 100, z: 20 }, cellSize: 10 };
-
-describe('bakeNavGrid', () => {
- it('covers the box in cells and lies in the ground plane', () => {
- const grid = bakeNavGrid(probeOf(() => LEVEL(0)), BOX);
- expect(grid.width).toBe(3); // 0, 10, 20
- expect(grid.height).toBe(3);
- expect(grid.plane).toBe('xz');
- expect(grid.isWalkable(1, 1)).toBe(true);
- // Cell (2,1) is at x=20, z=10 — the grid's own two axes are x and z.
- expect(grid.cellToWorld(2, 1)).toEqual({ x: 20, y: 0, z: 10 });
- });
-
- it('reports the height of the ground it found, per cell', () => {
- const grid = bakeNavGrid(probeOf((x) => LEVEL(x === 10 ? 35 : 0)), BOX);
- expect(grid.surfaceAt(0, 0)).toBe(0);
- expect(grid.surfaceAt(1, 0)).toBe(35);
- expect(grid.cellToWorld(1, 0).y).toBe(35);
- });
-
- // Three ways a cell fails, and each has to fail on its OWN account: a hole is
- // not a wall and neither is a low ceiling.
- it('a cell with no ground under it is a hole', () => {
- const grid = bakeNavGrid(probeOf((x) => (x === 10 ? null : LEVEL(0))), BOX);
- expect(grid.isWalkable(1, 0)).toBe(false);
- expect(grid.isWalkable(0, 0)).toBe(true);
- });
-
- it('ground steeper than the agent can stand on is a wall', () => {
- // ~60° from level: normalY = cos(60°) = 0.5.
- const steep = { y: 0, normalY: 0.5 };
- const grid = bakeNavGrid(probeOf((x) => (x === 10 ? steep : LEVEL(0))),
- { ...BOX, maxSlopeDegrees: 45 });
- expect(grid.isWalkable(1, 0)).toBe(false);
- // The same ground, an agent that can stand on it.
- const lenient = bakeNavGrid(probeOf((x) => (x === 10 ? steep : LEVEL(0))),
- { ...BOX, maxSlopeDegrees: 70 });
- expect(lenient.isWalkable(1, 0)).toBe(true);
- });
-
- it('a ceiling lower than the agent is a crawlspace, not a corridor', () => {
- const grid = bakeNavGrid(probeOf(() => LEVEL(0), (x) => x === 10),
- { ...BOX, agentHeight: 180 });
- expect(grid.isWalkable(1, 0)).toBe(false);
- expect(grid.isWalkable(0, 0)).toBe(true);
- });
-
- it('skips the headroom ray entirely when no agent height was given', () => {
- const raycast = vi.fn((_o: Vec3, d: Vec3) => (d.y < 0 ? LEVEL(0) : null));
- bakeNavGrid({ raycast }, BOX);
- expect(raycast).toHaveBeenCalledTimes(9); // one per cell, none upward
- });
-
- // A cell that failed still reports the height it found, so a route planned
- // past it (and an agent snapped onto it) is at the height of the floor there.
- it('keeps the height of a cell it refused to make walkable', () => {
- const grid = bakeNavGrid(probeOf((x) => (x === 10 ? { y: 42, normalY: 0.1 } : LEVEL(0))), BOX);
- expect(grid.isWalkable(1, 0)).toBe(false);
- expect(grid.surfaceAt(1, 0)).toBe(42);
- });
-
- it('carries the step limit onto the grid it builds', () => {
- const grid = bakeNavGrid(probeOf((x) => LEVEL(x === 10 ? 90 : 0)),
- { ...BOX, stepHeight: 30 });
- expect(grid.stepHeight).toBe(30);
- expect(grid.canStep(0, 0, 1, 0)).toBe(false);
- });
-
- it('casts the ground ray through the whole box, from its top', () => {
- const raycast = vi.fn(() => null);
- bakeNavGrid({ raycast }, BOX);
- expect(raycast).toHaveBeenCalledWith({ x: 0, y: 100, z: 0 }, { x: 0, y: -200, z: 0 }, 0);
- });
-
- it('casts against the layers it was given', () => {
- const raycast = vi.fn(() => null);
- bakeNavGrid({ raycast }, { ...BOX, layers: 0b101 });
- expect(raycast).toHaveBeenCalledWith(expect.anything(), expect.anything(), 0b101);
- });
-});
-
-/** The narrow world view `bakeVolumes` walks, with just enough store to answer. */
-class VolumeWorld {
- private store = new Map<string, unknown>();
- private ids: number[] = [];
- spawn(comps: Array<[{ _name: string }, unknown]>): number {
- const e = this.ids.length + 1;
- for (const [def, data] of comps) this.store.set(`${e}:${def._name}`, data);
- this.ids.push(e);
- return e;
- }
- getEntitiesWithComponents(defs: readonly { _name: string }[]): number[] {
- return this.ids.filter(e => defs.every(d => this.store.has(`${e}:${d._name}`)));
- }
- get(e: number, def: { _name: string }): never {
- return this.store.get(`${e}:${def._name}`) as never;
- }
- set(): void { /* the bake writes nothing back */ }
-}
-
-describe('bakeVolumes', () => {
- const spawnVolume = (w: VolumeWorld, over: Partial<NavVolumeData> = {}) => w.spawn([
- [NavVolume, NavVolume.create({ halfExtents: { x: 20, y: 100, z: 20 }, cellSize: 10, ...over })],
- [Transform, { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 } }],
- ]);
-
- it('bakes an authored volume into the active grid, centred on its Transform', () => {
- const w = new VolumeWorld();
- spawnVolume(w);
- const nav = new Navigation();
- bakeVolumes(w as never, nav, probeOf(() => LEVEL(7)), new Set());
- expect(nav.grid).not.toBeNull();
- expect(nav.grid!.plane).toBe('xz');
- expect(nav.grid!.width).toBe(5); // 40 across at 10 a cell, inclusive
- expect(nav.grid!.surfaceAt(0, 0)).toBe(7);
- });
-
- // Bodies are created by the physics system on its first step; a bake that ran
- // before it would sample an empty world and produce a grid of holes.
- it('does nothing at all without a solver to ask', () => {
- const w = new VolumeWorld();
- spawnVolume(w);
- const nav = new Navigation();
- bakeVolumes(w as never, nav, null, new Set());
- expect(nav.grid).toBeNull();
- });
-
- it('bakes each volume once, however many frames run', () => {
- const w = new VolumeWorld();
- spawnVolume(w);
- const raycast = vi.fn((_o: Vec3, d: Vec3) => (d.y < 0 ? LEVEL(0) : null));
- const baked = new Set<number>();
- const nav = new Navigation();
- bakeVolumes(w as never, nav, { raycast }, baked as never);
- const afterFirst = raycast.mock.calls.length;
- bakeVolumes(w as never, nav, { raycast }, baked as never);
- expect(raycast.mock.calls.length).toBe(afterFirst);
- });
-
- it('carries the volume own settings into the grid', () => {
- const w = new VolumeWorld();
- spawnVolume(w, { stepHeight: 25 });
- const nav = new Navigation();
- bakeVolumes(w as never, nav, probeOf(() => LEVEL(0)), new Set());
- expect(nav.grid!.stepHeight).toBe(25);
- });
-});
diff --git a/sdk/tests/nav-debug-draw.test.ts b/sdk/tests/nav-debug-draw.test.ts
index 24a48f8c3..fe3fed497 100644
--- a/sdk/tests/nav-debug-draw.test.ts
+++ b/sdk/tests/nav-debug-draw.test.ts
@@ -3,17 +3,21 @@
/**
* @file What the navigation overlay draws.
*
- * Counted, not looked at: the claims are which cells appear (the walkable ones),
- * where the ledges are (the pairs the step limit refuses) and that an overlay
- * nobody asked for costs nothing. A pixel test could say none of those.
+ * Counted, not looked at: the claims are which faces appear, where the walkable
+ * world stops, and that an overlay nobody asked for costs nothing. A pixel test
+ * could say none of those.
+ *
+ * One drawer serves both kinds of surface, so both are asked here — a grid whose
+ * faces lie in the scene's own plane, and a mesh whose faces follow the ground.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { NavGrid } from '../src/ai/nav/NavGrid';
+import { NavMesh } from '../src/ai/nav/NavMesh';
import { drawNavDebug, type NavDebugDrawConfig } from '../src/ai/nav/NavDebugDraw';
import { Draw } from '../src/render/draw';
import type { Vec3 } from '../src/types';
-const ON: NavDebugDrawConfig = { enabled: true, showCells: true, showLedges: true };
+const ON: NavDebugDrawConfig = { enabled: true, showFaces: true, showBorders: true };
let lines: Array<[Vec3, Vec3]>;
beforeEach(() => {
@@ -24,67 +28,67 @@ beforeEach(() => {
});
afterEach(() => vi.restoreAllMocks());
-/** A ground grid whose middle column stands 90 units up. */
-const ridge = (stepHeight: number) => new NavGrid({
- width: 3, height: 1, cellSize: 10, plane: 'xz',
- surface: [0, 90, 0], stepHeight,
+/** One square polygon 40 units up, with nothing beside it. */
+const oneQuadMesh = (): NavMesh => new NavMesh({
+ verts: Float32Array.from([0, 40, 0, 10, 40, 0, 10, 40, 10, 0, 40, 10]),
+ polys: Int32Array.from([0, 1, 2, 3, -1, -1]),
+ neis: Int32Array.from([-1, -1, -1, -1, -1, -1]),
+ polyCount: 1,
+ maxVertsPerPoly: 6,
+ agentRadius: 0,
+ snapDistance: 10,
+ verticalReach: 100,
});
describe('drawNavDebug', () => {
it('draws nothing at all until it is turned on', () => {
- drawNavDebug(ridge(20), { ...ON, enabled: false });
+ drawNavDebug(new NavGrid({ width: 3, height: 3, cellSize: 10 }), { ...ON, enabled: false });
expect(lines).toHaveLength(0);
});
- it('draws nothing when there is no grid', () => {
+ it('draws nothing when there is no surface', () => {
drawNavDebug(null, ON);
expect(lines).toHaveLength(0);
});
- it('outlines the walkable cells and leaves out the blocked ones', () => {
- const grid = new NavGrid({ width: 2, height: 1, cellSize: 10, plane: 'xz' });
+ it('outlines the walkable cells of a grid and leaves out the blocked ones', () => {
+ const grid = new NavGrid({ width: 2, height: 1, cellSize: 10 });
grid.setWalkable(1, 0, false);
- drawNavDebug(grid, { ...ON, showLedges: false });
+ drawNavDebug(grid, { ...ON, showBorders: false });
expect(lines).toHaveLength(4); // one quad, for the one walkable cell
});
- // The height is the point: an overlay drawn on a flat plane would say nothing
- // about the ground the route actually walks over.
- it('draws each cell at the height of its own ground', () => {
- const grid = new NavGrid({
- width: 2, height: 1, cellSize: 10, plane: 'xz', surface: [0, 90],
- });
- drawNavDebug(grid, { ...ON, showLedges: false });
- const heights = new Set(lines.map(([a]) => Math.round(a.y)));
- expect(heights.has(1)).toBe(true); // the low cell, lifted off its floor
- expect(heights.has(91)).toBe(true); // the high one
+ // The borders are the only thing that says where a route can turn: the faces
+ // of an open floor and of a corridor look the same drawn one at a time.
+ it('marks every edge the walkable world stops at', () => {
+ const grid = new NavGrid({ width: 3, height: 1, cellSize: 10 });
+ drawNavDebug(grid, { ...ON, showFaces: false });
+ // Three cells in a row: two ends, and the long side of each, twice over.
+ expect(lines).toHaveLength(8);
});
- // A ledge is the only thing that explains a route going the long way round,
- // and it is invisible in the cells themselves — both sides are walkable.
- it('marks the pairs the step limit refuses, and only those', () => {
- const cells = (g: NavGrid) => {
- lines = [];
- drawNavDebug(g, { ...ON, showLedges: false });
- return lines.length;
- };
- const blocked = ridge(20);
- const base = cells(blocked);
- lines = [];
- drawNavDebug(blocked, ON);
- expect(lines.length).toBeGreaterThan(base); // two ledges, either side of the ridge
+ // Off the ground means different things on a flat scene and a spatial one,
+ // and drawing a grid's overlay along +Y would slide it across the floor it
+ // is describing rather than lifting it off.
+ it('lifts the overlay along the surface own idea of up', () => {
+ drawNavDebug(new NavGrid({ width: 1, height: 1, cellSize: 10, origin: { x: 0, y: 0, z: 5 } }),
+ { ...ON, showBorders: false });
+ expect(lines[0]![0]!.z).toBeCloseTo(6);
+ expect(lines[0]![0]!.y).toBeCloseTo(-5);
- // The same ground with a limit that clears it: cells, and no ledges.
- const climbable = ridge(200);
- const climbBase = cells(climbable);
lines = [];
- drawNavDebug(climbable, ON);
- expect(lines.length).toBe(climbBase);
+ drawNavDebug(oneQuadMesh(), { ...ON, showBorders: false });
+ expect(lines[0]![0]!.y).toBeCloseTo(41);
+ });
+
+ it('draws a mesh polygon as one loop and its open edges as borders', () => {
+ drawNavDebug(oneQuadMesh(), ON);
+ expect(lines).toHaveLength(8); // four edges of the face, four borders
});
- it('stops drawing cells long before an overlay is what the frame is doing', () => {
- const huge = new NavGrid({ width: 200, height: 200, cellSize: 10, plane: 'xz' });
- drawNavDebug(huge, { ...ON, showLedges: false });
+ it('stops drawing faces long before an overlay is what the frame is doing', () => {
+ const huge = new NavGrid({ width: 200, height: 200, cellSize: 10 });
+ drawNavDebug(huge, { ...ON, showBorders: false });
expect(lines.length).toBe(4096 * 4);
});
});
diff --git a/sdk/tests/nav-geometry.test.ts b/sdk/tests/nav-geometry.test.ts
new file mode 100644
index 000000000..5e9ad593b
--- /dev/null
+++ b/sdk/tests/nav-geometry.test.ts
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Which of a scene's colliders a navigation mesh is baked from.
+ *
+ * The bake reads the world the scene already collides against, so what it must
+ * NOT read is as much of the claim as what it must: a crate about to be pushed,
+ * a trigger volume, and the agent's own body are all colliders, and none of them
+ * is floor.
+ */
+import { describe, it, expect } from 'vitest';
+import { World } from '../src/ecs/world';
+import { createMockModule } from './mocks/wasm';
+import { Transform } from '../src/ecs/component';
+import {
+ RigidBody3D, BoxCollider3D, MeshCollider3D, CharacterController3D,
+} from '../src/physics3d/Physics3DComponents';
+import { collectNavGeometry, navGeometryReady } from '../src/ai/nav/navGeometry';
+import { registerMeshCollision, releaseMeshCollision } from '../src/asset/meshCollision';
+
+function testWorld(): World {
+ const mod = createMockModule();
+ const world = new World();
+ world.connectCpp(mod.getRegistry(), mod);
+ return world;
+}
+
+const BOX = { min: { x: -500, y: -500, z: -500 }, max: { x: 500, y: 500, z: 500 } };
+
+/** A static box collider at `at`, plus whatever else the caller wants on it. */
+function addFloor(world: World, at = { x: 0, y: 0, z: 0 }, body = {}, collider = {}): number {
+ const e = world.spawn();
+ world.insert(e, Transform, { position: at });
+ world.insert(e, RigidBody3D, { bodyType: 0, ...body });
+ world.insert(e, BoxCollider3D, { halfExtents: { x: 100, y: 10, z: 100 }, ...collider });
+ return e;
+}
+
+/** The world-space bounds of everything collected. */
+function boundsOf(geo: { verts: Float32Array }): { min: number[]; max: number[] } {
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ for (let i = 0; i < geo.verts.length; i += 3) {
+ for (let k = 0; k < 3; k++) {
+ min[k] = Math.min(min[k]!, geo.verts[i + k]!);
+ max[k] = Math.max(max[k]!, geo.verts[i + k]!);
+ }
+ }
+ return { min, max };
+}
+
+describe('collectNavGeometry', () => {
+ it('takes a static collider, at the size and place the scene put it', () => {
+ const world = testWorld();
+ addFloor(world, { x: 50, y: 20, z: -30 });
+ const geo = collectNavGeometry(world, BOX);
+ expect(geo.bodyCount).toBe(1);
+ expect(geo.indices.length).toBe(36); // twelve triangles
+ const { min, max } = boundsOf(geo);
+ expect(min).toEqual([-50, 10, -130]);
+ expect(max).toEqual([150, 30, 70]);
+ });
+
+ // A mesh baked over a crate describes the world for as long as nobody
+ // touches it, which is not long enough to plan a route on.
+ it('leaves out anything that is going to move', () => {
+ const world = testWorld();
+ addFloor(world, { x: 0, y: 0, z: 0 }, { bodyType: 2 });
+ addFloor(world, { x: 0, y: 0, z: 0 }, { bodyType: 1 });
+ expect(collectNavGeometry(world, BOX).bodyCount).toBe(0);
+ });
+
+ it('leaves out a body that is switched off, and a trigger nobody bumps into', () => {
+ const world = testWorld();
+ addFloor(world, { x: 0, y: 0, z: 0 }, { enabled: false });
+ addFloor(world, { x: 0, y: 0, z: 0 }, {}, { isSensor: true });
+ expect(collectNavGeometry(world, BOX).bodyCount).toBe(0);
+ });
+
+ it('leaves out the agent own body', () => {
+ const world = testWorld();
+ const e = world.spawn();
+ world.insert(e, Transform, { position: { x: 0, y: 0, z: 0 } });
+ world.insert(e, RigidBody3D, { bodyType: 0 });
+ world.insert(e, CharacterController3D, { radius: 30, halfHeight: 40 });
+ expect(collectNavGeometry(world, BOX).bodyCount).toBe(0);
+ });
+
+ it('leaves out geometry the volume does not reach', () => {
+ const world = testWorld();
+ addFloor(world, { x: 5000, y: 0, z: 0 });
+ expect(collectNavGeometry(world, BOX).bodyCount).toBe(0);
+ expect(collectNavGeometry(world, BOX).verts.length).toBe(0);
+ });
+
+ it('takes only the layers it was asked for', () => {
+ const world = testWorld();
+ addFloor(world, { x: 0, y: 0, z: 0 }, { layer: 3 });
+ expect(collectNavGeometry(world, { ...BOX, layers: 1 << 3 }).bodyCount).toBe(1);
+ expect(collectNavGeometry(world, { ...BOX, layers: 1 << 2 }).bodyCount).toBe(0);
+ expect(collectNavGeometry(world, { ...BOX, layers: 0 }).bodyCount).toBe(1);
+ });
+
+ // A mesh collider's shape is its triangles, not the box around them: baking
+ // the box would wall off every doorway in an imported level.
+ it('takes a mesh collider own triangles', () => {
+ const world = testWorld();
+ const handle = 4242;
+ registerMeshCollision(handle, {
+ positions: Float32Array.from([0, 0, 0, 100, 0, 0, 0, 0, 100]),
+ indices: Uint32Array.from([0, 1, 2]),
+ });
+ const e = world.spawn();
+ world.insert(e, Transform, { position: { x: 0, y: 0, z: 0 } });
+ world.insert(e, RigidBody3D, { bodyType: 0 });
+ world.insert(e, MeshCollider3D, { mesh: handle });
+
+ const geo = collectNavGeometry(world, BOX);
+ expect(geo.indices.length).toBe(3);
+ expect(Array.from(geo.verts)).toEqual([0, 0, 0, 100, 0, 0, 0, 0, 100]);
+ releaseMeshCollision(handle);
+ });
+});
+
+describe('navGeometryReady', () => {
+ it('waits for a mesh collider that has not loaded its triangles', () => {
+ const world = testWorld();
+ const e = world.spawn();
+ world.insert(e, Transform, { position: { x: 0, y: 0, z: 0 } });
+ world.insert(e, RigidBody3D, { bodyType: 0 });
+ world.insert(e, MeshCollider3D, { mesh: 777 });
+ expect(navGeometryReady(world)).toBe(false);
+
+ registerMeshCollision(777, {
+ positions: Float32Array.from([0, 0, 0, 1, 0, 0, 0, 0, 1]),
+ indices: Uint32Array.from([0, 1, 2]),
+ });
+ expect(navGeometryReady(world)).toBe(true);
+ releaseMeshCollision(777);
+ });
+
+ it('is ready at once for a world of primitives', () => {
+ const world = testWorld();
+ addFloor(world);
+ expect(navGeometryReady(world)).toBe(true);
+ });
+});
diff --git a/sdk/tests/nav-pathfind.test.ts b/sdk/tests/nav-pathfind.test.ts
index b54725a96..26c7d4e9a 100644
--- a/sdk/tests/nav-pathfind.test.ts
+++ b/sdk/tests/nav-pathfind.test.ts
@@ -43,31 +43,6 @@ describe('NavGrid', () => {
expect(grid.worldToCell({ x: 170, y: 210 })).toEqual({ x: 2, y: 0 });
});
- // The same grid, laid in the ground plane of a spatial scene: the cells map
- // to x/z and the axis they leave out carries the height of the ground.
- it('maps cells to the ground plane, at the height of each cell', () => {
- const grid = new NavGrid({
- width: 2, height: 2, cellSize: 10, plane: 'xz', origin: { x: 0, y: 0, z: 0 },
- surface: [0, 0, 5, 40],
- });
- expect(grid.cellToWorld(0, 0)).toEqual({ x: 0, y: 0, z: 0 });
- expect(grid.cellToWorld(1, 1)).toEqual({ x: 10, y: 40, z: 10 });
- // The cell is named by x/z; the height is an answer, never a question.
- expect(grid.worldToCell({ x: 10, y: 999, z: 10 })).toEqual({ x: 1, y: 1 });
- });
-
- // A step an agent can walk up is a route; a wall of the same width is not.
- // With no surface (or no limit) nothing here can say no — a flat grid's rule.
- it('lets a small step through and a tall one not', () => {
- const opts = { width: 2, height: 1, cellSize: 10, plane: 'xz' as const, stepHeight: 10 };
- const kerb = new NavGrid({ ...opts, surface: [0, 6] });
- const wall = new NavGrid({ ...opts, surface: [0, 60] });
- expect(kerb.canStep(0, 0, 1, 0)).toBe(true);
- expect(wall.canStep(0, 0, 1, 0)).toBe(false);
- expect(new NavGrid({ ...opts, surface: [0, 60], stepHeight: 0 }).canStep(0, 0, 1, 0)).toBe(true);
- expect(new NavGrid(opts).canStep(0, 0, 1, 0)).toBe(true);
- });
-
it('reports bounds and walkability', () => {
const grid = new NavGrid({ width: 3, height: 3, cellSize: 10 });
expect(grid.isWalkable(0, 0)).toBe(true);
@@ -175,35 +150,4 @@ describe('findPath', () => {
{ x: 5, y: 5, z: 0 }, { x: 25, y: 5, z: 0 }, { x: 45, y: 5, z: 0 },
]);
});
-
- // A ledge is not a wall — every cell here is walkable — but it is not a route
- // either, and only the step limit can tell the search that.
- it('routes around a ledge it cannot climb, and over one it can', () => {
- // A tall ridge down the middle column, open along the top row:
- // row 2: . . . row 1: . ^ . row 0: S ^ G
- const ridge = () => [
- 0, 90, 0,
- 0, 90, 0,
- 0, 0, 0,
- ];
- const spatial = { width: 3, height: 3, cellSize: 10, plane: 'xz' as const };
- const blocked = new NavGrid({ ...spatial, surface: ridge(), stepHeight: 20 });
- const path = findPath(blocked, { x: 0, y: 0 }, { x: 2, y: 0 }, { diagonal: false })!;
- expect(path).not.toBeNull();
- // It went the long way: through the open row rather than over the ridge.
- expect(path.some(c => c.y === 2)).toBe(true);
-
- // The same ridge, an agent that can climb it: straight across.
- const climbable = new NavGrid({ ...spatial, surface: ridge(), stepHeight: 100 });
- const over = findPath(climbable, { x: 0, y: 0 }, { x: 2, y: 0 }, { diagonal: false })!;
- expect(over).toEqual([{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }]);
- });
-
- it('reports no route when the ledge cuts the grid in two', () => {
- const grid = new NavGrid({
- width: 3, height: 1, cellSize: 10, plane: 'xz',
- surface: [0, 90, 0], stepHeight: 20,
- });
- expect(findPath(grid, { x: 0, y: 0 }, { x: 2, y: 0 })).toBeNull();
- });
});
diff --git a/sdk/tests/nav-step.test.ts b/sdk/tests/nav-step.test.ts
index dc6b80d10..0dffd996b 100644
--- a/sdk/tests/nav-step.test.ts
+++ b/sdk/tests/nav-step.test.ts
@@ -51,7 +51,7 @@ class FakeWorld implements NavWorldView {
function openNav(width = 10, height = 3, cellSize = 10): Navigation {
const nav = new Navigation();
- nav.setGrid(new NavGrid({ width, height, cellSize }));
+ nav.setSurface(new NavGrid({ width, height, cellSize }));
return nav;
}
@@ -83,7 +83,7 @@ describe('stepNavigation', () => {
const grid = new NavGrid({ width: 10, height: 3, cellSize: 10 });
grid.setWalkable(5, 0, false);
grid.setWalkable(5, 1, false);
- nav.setGrid(grid);
+ nav.setSurface(grid);
const world = new FakeWorld();
const runtimes = new Map<Entity, AgentRuntime>();
const e = world.spawnAgent(0, 0, { speed: 150, repathInterval: 0, hasTarget: true, targetX: 90, targetY: 0 });
@@ -103,7 +103,7 @@ describe('stepNavigation', () => {
// The field is the whole point: an agent chasing something must be able
// to stop short of it rather than walk onto it.
const nav = new Navigation();
- nav.setGrid(new NavGrid({ width: 20, height: 3, cellSize: 10 }));
+ nav.setSurface(new NavGrid({ width: 20, height: 3, cellSize: 10 }));
const world = new FakeWorld();
const runtimes = new Map<Entity, AgentRuntime>();
const e = world.spawnAgent(0, 0, {
@@ -126,7 +126,7 @@ describe('stepNavigation', () => {
const nav = new Navigation();
const grid = new NavGrid({ width: 10, height: 3, cellSize: 10 });
for (let y = 0; y < 3; y++) grid.setWalkable(5, y, false);
- nav.setGrid(grid);
+ nav.setSurface(grid);
const world = new FakeWorld();
const runtimes = new Map<Entity, AgentRuntime>();
const e = world.spawnAgent(0, 0, { speed: 100, repathInterval: 0, hasTarget: true, targetX: 90, targetY: 0 });
diff --git a/sdk/tests/nav-volume-bake.test.ts b/sdk/tests/nav-volume-bake.test.ts
new file mode 100644
index 000000000..39ae912d7
--- /dev/null
+++ b/sdk/tests/nav-volume-bake.test.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a scene AUTHORING a NavVolume gets.
+ *
+ * The bake itself is proved against triangles handed to it; this is about the
+ * seam above: which box is sampled, whose settings it uses, and that a volume is
+ * baked once rather than every frame it exists.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { bakeVolumes } from '../src/ai/nav/NavPlugin';
+import { NavVolume, type NavVolumeData } from '../src/ai/nav/NavVolume';
+import { Navigation } from '../src/ai/nav/Navigation';
+import { NavMesh } from '../src/ai/nav/NavMesh';
+import { Transform } from '../src/ecs/component';
+import type { Vec3 } from '../src/types';
+
+/** The narrow world view `bakeVolumes` walks, with just enough store to answer. */
+class VolumeWorld {
+ private store = new Map<string, unknown>();
+ private ids: number[] = [];
+ spawn(comps: Array<[{ _name: string }, unknown]>): number {
+ const e = this.ids.length + 1;
+ for (const [def, data] of comps) this.store.set(`${e}:${def._name}`, data);
+ this.ids.push(e);
+ return e;
+ }
+ getEntitiesWithComponents(defs: readonly { _name: string }[]): number[] {
+ return this.ids.filter(e => defs.every(d => this.store.has(`${e}:${d._name}`)));
+ }
+ get(e: number, def: { _name: string }): never {
+ return this.store.get(`${e}:${def._name}`) as never;
+ }
+ set(): void { /* the bake writes nothing back */ }
+}
+
+/** A floor slab as world triangles, whatever box is asked for. */
+function floorGeometry(y = 0) {
+ return (min: Vec3, max: Vec3) => {
+ const verts: number[] = [];
+ for (const [x, z] of [[min.x, min.z], [max.x, min.z], [max.x, max.z], [min.x, max.z]]) {
+ verts.push(x!, y, z!);
+ }
+ return {
+ verts: Float32Array.from(verts),
+ indices: Uint32Array.from([0, 2, 1, 0, 3, 2]),
+ bodyCount: 1,
+ };
+ };
+}
+
+const spawnVolume = (w: VolumeWorld, over: Partial<NavVolumeData> = {}) => w.spawn([
+ [NavVolume, NavVolume.create({
+ halfExtents: { x: 400, y: 200, z: 400 }, cellSize: 25, agentRadius: 0, ...over,
+ })],
+ [Transform, { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 } }],
+]);
+
+describe('bakeVolumes', () => {
+ it('bakes an authored volume into the active surface, centred on its Transform', () => {
+ const w = new VolumeWorld();
+ spawnVolume(w);
+ const nav = new Navigation();
+ bakeVolumes(w as never, nav, floorGeometry(), new Set());
+
+ const mesh = nav.surface as NavMesh;
+ expect(mesh).toBeInstanceOf(NavMesh);
+ expect(mesh.polyCount).toBeGreaterThan(0);
+ expect(mesh.findPoly({ x: 0, y: 0, z: 0 })).toBeGreaterThanOrEqual(0);
+ // Outside the box there is no mesh, however much floor was handed over.
+ expect(mesh.findPoly({ x: 900, y: 0, z: 0 })).toBe(-1);
+ });
+
+ it('does nothing at all until the world can answer', () => {
+ const w = new VolumeWorld();
+ spawnVolume(w);
+ const nav = new Navigation();
+ bakeVolumes(w as never, nav, null, new Set());
+ expect(nav.surface).toBeNull();
+ });
+
+ it('bakes each volume once, however many frames run', () => {
+ const w = new VolumeWorld();
+ spawnVolume(w);
+ const geometry = vi.fn(floorGeometry());
+ const baked = new Set<number>();
+ const nav = new Navigation();
+ bakeVolumes(w as never, nav, geometry, baked as never);
+ bakeVolumes(w as never, nav, geometry, baked as never);
+ expect(geometry).toHaveBeenCalledTimes(1);
+ });
+
+ it('carries the volume own settings into the bake', () => {
+ const w = new VolumeWorld();
+ spawnVolume(w, { agentRadius: 90 });
+ const nav = new Navigation();
+ bakeVolumes(w as never, nav, floorGeometry(), new Set());
+ expect((nav.surface as NavMesh).agentRadius).toBe(90);
+ // And it means it: a body that wide cannot stand at the wall.
+ expect((nav.surface as NavMesh).findPoly({ x: 395, y: 0, z: 0 })).toBe(-1);
+ });
+
+ it('asks only for the layers the volume names', () => {
+ const w = new VolumeWorld();
+ spawnVolume(w, { layers: 0b1010 });
+ const geometry = vi.fn(floorGeometry());
+ bakeVolumes(w as never, new Navigation(), geometry, new Set());
+ expect(geometry).toHaveBeenCalledWith(expect.anything(), expect.anything(), 0b1010);
+ });
+});
diff --git a/sdk/tests/navmesh-build.test.ts b/sdk/tests/navmesh-build.test.ts
new file mode 100644
index 000000000..8741a2012
--- /dev/null
+++ b/sdk/tests/navmesh-build.test.ts
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Baking a navigation mesh out of triangles, and routing over it.
+ */
+import { describe, it, expect } from 'vitest';
+import { buildNavMesh } from '../src/ai/nav/navmesh/build';
+import type { Vec3 } from '../src/types';
+
+/** A solid box as world-space triangles, appended to a growing soup. */
+function addBox(
+ soup: { verts: number[]; indices: number[] },
+ center: Vec3, half: Vec3,
+): void {
+ const base = soup.verts.length / 3;
+ for (const sy of [-1, 1]) {
+ for (const [sx, sz] of [[-1, -1], [1, -1], [1, 1], [-1, 1]] as const) {
+ soup.verts.push(center.x + sx * half.x, center.y + sy * half.y, center.z + sz * half.z);
+ }
+ }
+ const faces = [
+ 0, 1, 2, 0, 2, 3,
+ 4, 6, 5, 4, 7, 6,
+ 0, 4, 5, 0, 5, 1,
+ 1, 5, 6, 1, 6, 2,
+ 2, 6, 7, 2, 7, 3,
+ 3, 7, 4, 3, 4, 0,
+ ];
+ for (const i of faces) soup.indices.push(base + i);
+}
+
+function soup(): { verts: number[]; indices: number[] } {
+ return { verts: [], indices: [] };
+}
+
+const BOX = {
+ min: { x: -500, y: -100, z: -500 },
+ max: { x: 500, y: 400, z: 500 },
+ cellSize: 25,
+ cellHeight: 10,
+ agentHeight: 180,
+ agentRadius: 30,
+ stepHeight: 40,
+};
+
+function bake(s: { verts: number[]; indices: number[] }, over: Partial<typeof BOX> = {}) {
+ return buildNavMesh(Float32Array.from(s.verts), Uint32Array.from(s.indices), { ...BOX, ...over });
+}
+
+describe('buildNavMesh', () => {
+ it('covers a flat floor, at the height of its top face', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ const mesh = bake(s);
+
+ expect(mesh.polyCount).toBeGreaterThan(0);
+ // Every vertex sits on top of the slab. A surface is rounded UP to the
+ // voxel it falls in, so the mesh floats by up to one `cellHeight` — the
+ // knob for how closely it hugs the floor, not an error to correct here.
+ for (let i = 0; i < mesh.verts.length; i += 3) {
+ expect(mesh.verts[i + 1]).toBeGreaterThanOrEqual(0);
+ expect(mesh.verts[i + 1]).toBeLessThanOrEqual(BOX.cellHeight);
+ }
+ const at: Vec3 = { x: 0, y: 0, z: 0 };
+ expect(mesh.findPoly({ x: 0, y: 0, z: 0 }, at)).toBeGreaterThanOrEqual(0);
+ expect(at.y).toBeLessThanOrEqual(BOX.cellHeight);
+ });
+
+ it('pulls the mesh back from the walls by the agent radius', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ const wide = bake(s, { agentRadius: 100 });
+ let maxX = -Infinity;
+ for (let i = 0; i < wide.verts.length; i += 3) maxX = Math.max(maxX, wide.verts[i]!);
+ // The floor ends at x = 400; a body 100 wide may not stand closer than that.
+ expect(maxX).toBeLessThanOrEqual(400 - 100 + BOX.cellSize);
+ expect(maxX).toBeGreaterThan(200);
+ });
+
+ it('routes round a wall rather than through it', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ // A wall from z = -400 to z = 200, leaving a gap at the far end.
+ addBox(s, { x: 0, y: 80, z: -100 }, { x: 20, y: 100, z: 300 });
+ const mesh = bake(s);
+
+ const path = mesh.findWorldPath({ x: -300, y: 0, z: -300 }, { x: 300, y: 0, z: -300 });
+ expect(path).not.toBeNull();
+ const maxZ = Math.max(...path!.map(p => p.z));
+ expect(maxZ).toBeGreaterThan(200);
+ });
+
+ it('keeps a bridge and the ground under it apart', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ // A deck three metres up, spanning x, with nothing holding it up in the
+ // middle — so the ground below it keeps its headroom.
+ addBox(s, { x: 0, y: 300, z: 0 }, { x: 400, y: 20, z: 200 });
+ const mesh = bake(s);
+
+ const below: Vec3 = { x: 0, y: 0, z: 0 };
+ const above: Vec3 = { x: 0, y: 0, z: 0 };
+ const groundPoly = mesh.findPoly({ x: 0, y: 0, z: 0 }, below);
+ const deckPoly = mesh.findPoly({ x: 0, y: 320, z: 0 }, above);
+ expect(groundPoly).toBeGreaterThanOrEqual(0);
+ expect(deckPoly).toBeGreaterThanOrEqual(0);
+ expect(deckPoly).not.toBe(groundPoly);
+ expect(below.y).toBeLessThanOrEqual(BOX.cellHeight);
+ expect(above.y).toBeGreaterThan(310);
+ });
+
+ it('will not stand an agent on ground steeper than it can climb', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ const flat = bake(s).polyCount;
+ expect(flat).toBeGreaterThan(0);
+ // The same floor, an agent that can stand on nothing at all.
+ expect(bake(s, { maxSlopeDegrees: 0 } as never).polyCount).toBe(0);
+ });
+
+ it('leaves out ground with no headroom over it', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ // A ceiling 100 up over half the floor — under an agent 180 tall.
+ addBox(s, { x: 200, y: 120, z: 0 }, { x: 200, y: 20, z: 400 });
+ const mesh = bake(s);
+ const open: Vec3 = { x: 0, y: 0, z: 0 };
+ const under: Vec3 = { x: 0, y: 0, z: 0 };
+ expect(mesh.findPoly({ x: -200, y: 0, z: 0 }, open)).toBeGreaterThanOrEqual(0);
+ expect(open.y).toBeLessThanOrEqual(BOX.cellHeight);
+ // Under the ceiling there is no floor at all: the only walkable ground
+ // over that half of the world is the TOP of the slab, which is why the
+ // answer has to be read as a height rather than as a yes or no.
+ mesh.findPoly({ x: 200, y: 0, z: 0 }, under);
+ expect(under.y).toBeGreaterThan(100);
+ });
+
+ // What a mesh buys over a grid: the route is the straight line, not the
+ // staircase a grid of cells would have to walk to draw one.
+ it('crosses an open floor in a single straight line', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ const mesh = bake(s);
+
+ const from = { x: -300, y: 0, z: -300 };
+ const to = { x: 300, y: 0, z: 300 };
+ const path = mesh.findWorldPath(from, to)!;
+ expect(path).not.toBeNull();
+ expect(path).toHaveLength(2);
+ expect(pathLength(path)).toBeCloseTo(Math.hypot(600, 600), 0);
+ });
+
+ // The corner is not a point — erosion by the agent's own width rounds it off —
+ // so the taut path wraps it in a couple of steps, where a route over cells of
+ // this size would turn a couple of dozen times over the same ground.
+ it('turns only at the corner it has to go round', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ // A wall along -x half of the floor, splitting it into an L.
+ addBox(s, { x: -100, y: 80, z: 0 }, { x: 300, y: 100, z: 20 });
+ const mesh = bake(s);
+
+ const path = mesh.findWorldPath({ x: -300, y: 0, z: -200 }, { x: -300, y: 0, z: 200 })!;
+ expect(path).not.toBeNull();
+ expect(path.length).toBeGreaterThan(2);
+ expect(path.length).toBeLessThanOrEqual(6);
+ // Every turn is round the open end of the wall, not back down it.
+ for (const p of path.slice(1, -1)) expect(p.x).toBeGreaterThan(150);
+ });
+
+ it('walks up a step it can climb and round one it cannot', () => {
+ const stepped = (height: number) => {
+ const s = soup();
+ addBox(s, { x: -250, y: -20, z: 0 }, { x: 250, y: 20, z: 400 });
+ addBox(s, { x: 250, y: height / 2 - 20, z: 0 }, { x: 250, y: height / 2 + 20, z: 400 });
+ return s;
+ };
+ const low = bake(stepped(30));
+ expect(low.findWorldPath({ x: -300, y: 0, z: 0 }, { x: 300, y: 30, z: 0 })).not.toBeNull();
+
+ const high = bake(stepped(200));
+ expect(high.findWorldPath({ x: -300, y: 0, z: 0 }, { x: 300, y: 200, z: 0 })).toBeNull();
+ });
+
+ // Two floors with the SAME outline, one over the other: their corners land on
+ // one spot in the ground plane, so anything identifying a vertex by where it
+ // is from above welds the upper storey onto the lower one.
+ it('keeps two floors of the same shape at their own heights', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ addBox(s, { x: 0, y: 280, z: 0 }, { x: 400, y: 20, z: 400 });
+ const mesh = bake(s);
+
+ const lower: Vec3 = { x: 0, y: 0, z: 0 };
+ const upper: Vec3 = { x: 0, y: 0, z: 0 };
+ expect(mesh.findPoly({ x: 0, y: 0, z: 0 }, lower)).toBeGreaterThanOrEqual(0);
+ expect(mesh.findPoly({ x: 0, y: 300, z: 0 }, upper)).toBeGreaterThanOrEqual(0);
+ expect(lower.y).toBeLessThanOrEqual(BOX.cellHeight);
+ expect(upper.y).toBeGreaterThan(290);
+ });
+
+ // Two levels with no way between them: the mesh has both, and no route.
+ it('reports no route from the ground to a deck nothing reaches', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ addBox(s, { x: 0, y: 300, z: 0 }, { x: 400, y: 20, z: 200 });
+ const mesh = bake(s);
+ expect(mesh.findWorldPath({ x: 0, y: 0, z: -350 }, { x: 0, y: 320, z: 0 })).toBeNull();
+ });
+
+ // A volume covering a city at a centimetre a cell is not a slow bake, it is
+ // one that never finishes — and an editor that stops with no reason given is
+ // worse than a scene with no mesh in it.
+ it('refuses a volume too big to voxelise rather than trying', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ const huge = bake(s, {
+ min: { x: -1e5, y: -100, z: -1e5 }, max: { x: 1e5, y: 400, z: 1e5 },
+ });
+ expect(huge.polyCount).toBe(0);
+ });
+
+ it('hands its shape to a drawer as faces and the edges they stop at', () => {
+ const s = soup();
+ addBox(s, { x: 0, y: -20, z: 0 }, { x: 400, y: 20, z: 400 });
+ const mesh = bake(s);
+ let faces = 0;
+ let borders = 0;
+ mesh.describe({
+ face: (corners) => { expect(corners.length).toBeGreaterThanOrEqual(3); faces++; },
+ border: () => { borders++; },
+ });
+ expect(faces).toBe(mesh.polyCount);
+ // A single floor is one island: every edge of its outline is a border.
+ expect(borders).toBeGreaterThanOrEqual(4);
+ });
+});
+
+function pathLength(path: Vec3[]): number {
+ let total = 0;
+ for (let i = 1; i < path.length; i++) {
+ total += Math.hypot(path[i]!.x - path[i - 1]!.x,
+ path[i]!.y - path[i - 1]!.y, path[i]!.z - path[i - 1]!.z);
+ }
+ return total;
+}
diff --git a/sdk/tests/navmesh-poly.test.ts b/sdk/tests/navmesh-poly.test.ts
new file mode 100644
index 000000000..d4adaa745
--- /dev/null
+++ b/sdk/tests/navmesh-poly.test.ts
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Region outlines and the convex polygons made from them.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ NavHeightfield, addSpan, NAV_AREA_WALKABLE,
+} from '../src/ai/nav/navmesh/heightfield';
+import { NavCompactField } from '../src/ai/nav/navmesh/compact';
+import { buildRegionsMonotone } from '../src/ai/nav/navmesh/regions';
+import { buildContours, type NavContour } from '../src/ai/nav/navmesh/contours';
+import { buildPolyMesh } from '../src/ai/nav/navmesh/polymesh';
+
+const SIZE = 12;
+
+/** A field of walkable floor, with `hole` deciding which columns are missing. */
+function fieldOf(hole: (x: number, z: number) => boolean = () => false): NavCompactField {
+ const hf = new NavHeightfield(
+ { x: 0, y: 0, z: 0 }, { x: SIZE * 10, y: 100, z: SIZE * 10 }, 10, 1);
+ for (let z = 0; z < SIZE; z++) {
+ for (let x = 0; x < SIZE; x++) {
+ if (hole(x, z)) continue;
+ addSpan(hf, x, z, 0, 10, NAV_AREA_WALKABLE, 1);
+ }
+ }
+ return new NavCompactField(hf, 5, 4);
+}
+
+/** Twice the signed area of a contour in the ground plane, Recast's measure. */
+function signedArea(contour: NavContour): number {
+ const n = contour.verts.length / 3;
+ let area = 0;
+ for (let i = 0, j = n - 1; i < n; j = i++) {
+ area += contour.verts[i * 3]! * contour.verts[j * 3 + 2]!
+ - contour.verts[j * 3]! * contour.verts[i * 3 + 2]!;
+ }
+ return area;
+}
+
+describe('buildContours', () => {
+ // Which way an outline runs is not a detail: the funnel reads one side of
+ // every doorway as left and the other as right, and a contour traced the
+ // other way round would hand it the two the wrong way about.
+ it('winds every outline the same way', () => {
+ const chf = fieldOf((x, z) => x >= 4 && x <= 7 && z >= 4 && z <= 7);
+ buildRegionsMonotone(chf, 4);
+ const contours = buildContours(chf, 1.3, 12);
+ expect(contours.length).toBeGreaterThan(0);
+ for (const contour of contours) expect(signedArea(contour)).toBeGreaterThan(0);
+ });
+
+ it('puts a corner where the walkable world turns, inside and out', () => {
+ const chf = fieldOf((x, z) => x >= 5 && x <= 6 && z >= 5 && z <= 6);
+ buildRegionsMonotone(chf, 4);
+ const contours = buildContours(chf, 1.3, 12);
+ const corners = contours.flatMap(c => {
+ const out: string[] = [];
+ for (let i = 0; i < c.verts.length; i += 3) out.push(`${c.verts[i]},${c.verts[i + 2]}`);
+ return out;
+ });
+ // The outer corners of the field are on some outline...
+ expect(corners).toContain('0,0');
+ expect(corners).toContain(`${SIZE},${SIZE}`);
+ // ...and so are the corners of the hole, which is what makes it a hole.
+ expect(corners).toContain('5,5');
+ });
+});
+
+describe('buildPolyMesh', () => {
+ const meshOf = (hole?: (x: number, z: number) => boolean) => {
+ const chf = fieldOf(hole);
+ buildRegionsMonotone(chf, 4);
+ return buildPolyMesh(buildContours(chf, 1.3, 12), 6);
+ };
+
+ // Convex is the whole promise: inside one polygon a straight line is always
+ // walkable, and a route that only names polygons rests on it entirely.
+ it('covers the floor in polygons that are actually convex', () => {
+ // A T: one wide row with a narrow stem, so the region the sweep produces
+ // has corners that turn the other way and a careless merge would cut across.
+ const mesh = meshOf((x, z) => z >= 1 && (x < 4 || x > 7));
+ expect(mesh.polyCount).toBeGreaterThan(0);
+ for (let p = 0; p < mesh.polyCount; p++) {
+ const verts: number[] = [];
+ for (let i = 0; i < mesh.maxVertsPerPoly; i++) {
+ const v = mesh.polys[p * mesh.maxVertsPerPoly + i]!;
+ if (v === -1) break;
+ verts.push(v);
+ }
+ expect(verts.length).toBeGreaterThanOrEqual(3);
+ expect(verts.length).toBeLessThanOrEqual(6);
+ expect(isConvex(mesh.verts, verts)).toBe(true);
+ }
+ });
+
+ // Regions are cut by a sweep, not by anything in the world, so the seams
+ // between them are invisible — unless the polygons on either side fail to
+ // find each other, and then the mesh is in pieces no route can cross.
+ it('links the polygons on either side of a region seam', () => {
+ const mesh = meshOf((x, z) => x === 5 && z >= 8);
+ expect(mesh.polyCount).toBeGreaterThan(1);
+ let linked = 0;
+ for (let i = 0; i < mesh.neis.length; i++) if (mesh.neis[i] !== -1) linked++;
+ expect(linked).toBeGreaterThan(0);
+ // Every link is mutual: the neighbour names this polygon back.
+ for (let p = 0; p < mesh.polyCount; p++) {
+ for (let e = 0; e < mesh.maxVertsPerPoly; e++) {
+ const other = mesh.neis[p * mesh.maxVertsPerPoly + e]!;
+ if (other === -1) continue;
+ let back = false;
+ for (let f = 0; f < mesh.maxVertsPerPoly; f++) {
+ if (mesh.neis[other * mesh.maxVertsPerPoly + f] === p) back = true;
+ }
+ expect(back).toBe(true);
+ }
+ }
+ });
+});
+
+/** Whether the polygon turns the same way at every corner, in the ground plane. */
+function isConvex(verts: Int32Array, poly: number[]): boolean {
+ let sign = 0;
+ for (let i = 0; i < poly.length; i++) {
+ const a = poly[i]! * 3;
+ const b = poly[(i + 1) % poly.length]! * 3;
+ const c = poly[(i + 2) % poly.length]! * 3;
+ const cross = (verts[b]! - verts[a]!) * (verts[c + 2]! - verts[b + 2]!)
+ - (verts[b + 2]! - verts[a + 2]!) * (verts[c]! - verts[b]!);
+ if (cross === 0) continue;
+ const s = cross > 0 ? 1 : -1;
+ if (sign === 0) sign = s;
+ else if (s !== sign) return false;
+ }
+ return true;
+}
diff --git a/sdk/tests/navmesh-voxel.test.ts b/sdk/tests/navmesh-voxel.test.ts
new file mode 100644
index 000000000..a455bd75d
--- /dev/null
+++ b/sdk/tests/navmesh-voxel.test.ts
@@ -0,0 +1,180 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The voxel stages of the navmesh bake, each on its own terms.
+ *
+ * The end-to-end bake has four different reasons to leave a cell out, and they
+ * back each other up: take any one away and the mesh usually still comes out
+ * right, which makes a whole-pipeline test blind to three of them. So each stage
+ * is asked here for the one thing only it can answer.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ NavHeightfield, addSpan, rasterizeTriangles, filterLedgeSpans,
+ filterLowHangingWalkableObstacles, filterWalkableLowHeightSpans,
+ NAV_AREA_NULL, NAV_AREA_WALKABLE, type NavSpan,
+} from '../src/ai/nav/navmesh/heightfield';
+import { NavCompactField, erodeWalkableArea, NAV_NOT_CONNECTED } from '../src/ai/nav/navmesh/compact';
+
+const MIN = { x: 0, y: 0, z: 0 };
+const MAX = { x: 100, y: 100, z: 100 };
+/** Ten by ten cells of ten units, in voxels of one. */
+const field = (): NavHeightfield => new NavHeightfield(MIN, MAX, 10, 1);
+
+/** The spans of one column, lowest first. */
+function column(hf: NavHeightfield, x: number, z: number): NavSpan[] {
+ const out: NavSpan[] = [];
+ for (let s = hf.spans[x + z * hf.width] ?? null; s; s = s.next) out.push(s);
+ return out;
+}
+
+/** A level quad at height `y` covering `[x0,x1] x [z0,z1]`, as two triangles. */
+function floor(y: number, x0: number, x1: number, z0: number, z1: number)
+: { verts: Float32Array; indices: Uint32Array } {
+ return {
+ verts: Float32Array.from([x0, y, z0, x1, y, z0, x1, y, z1, x0, y, z1]),
+ indices: Uint32Array.from([0, 2, 1, 0, 3, 2]),
+ };
+}
+
+describe('the solid heightfield', () => {
+ it('fills every column a triangle crosses, not just the ones it has a corner in', () => {
+ const hf = field();
+ const q = floor(50, 5, 95, 5, 95);
+ rasterizeTriangles(hf, q.verts, q.indices, Math.cos(Math.PI / 4), 1);
+ // The quad covers cells 0..9 in both axes; a sampler would have missed
+ // every cell whose centre the two triangles happen to straddle.
+ for (let z = 0; z < 10; z++) {
+ for (let x = 0; x < 10; x++) expect(column(hf, x, z)).toHaveLength(1);
+ }
+ expect(column(hf, 5, 5)[0]!.area).toBe(NAV_AREA_WALKABLE);
+ // A surface is rounded UP to the top of the voxel it falls in, so a floor
+ // at 50 fills the voxel below 51 — the reason a baked mesh floats by up
+ // to one `cellHeight` over the geometry it came from.
+ expect(column(hf, 5, 5)[0]!.smax).toBe(51);
+ });
+
+ it('leaves ground steeper than the agent solid but not walkable', () => {
+ const hf = field();
+ // A wall face: vertical, so its normal has no upward component at all.
+ const wall = {
+ verts: Float32Array.from([50, 0, 5, 50, 0, 95, 50, 80, 95, 50, 80, 5]),
+ indices: Uint32Array.from([0, 1, 2, 0, 2, 3]),
+ };
+ rasterizeTriangles(hf, wall.verts, wall.indices, Math.cos(Math.PI / 4), 1);
+ const spans = column(hf, 5, 5);
+ expect(spans.length).toBeGreaterThan(0);
+ expect(spans[0]!.area).toBe(NAV_AREA_NULL);
+ });
+
+ it('merges overlapping spans into the one solid thing they are', () => {
+ const hf = field();
+ addSpan(hf, 0, 0, 10, 20, NAV_AREA_WALKABLE, 1);
+ addSpan(hf, 0, 0, 15, 30, NAV_AREA_NULL, 1);
+ const spans = column(hf, 0, 0);
+ expect(spans).toHaveLength(1);
+ expect(spans[0]!.smin).toBe(10);
+ expect(spans[0]!.smax).toBe(30);
+ // Two tops far apart: the lower one's area does not carry to the new top.
+ expect(spans[0]!.area).toBe(NAV_AREA_NULL);
+ });
+});
+
+describe('filterLowHangingWalkableObstacles', () => {
+ // A kerb rasterises as an obstacle standing on the floor. Left as one it cuts
+ // the walkable world in two at every doorstep in the level.
+ it('makes a step small enough to walk up into ground', () => {
+ const hf = field();
+ addSpan(hf, 0, 0, 0, 10, NAV_AREA_WALKABLE, 1);
+ addSpan(hf, 0, 0, 12, 13, NAV_AREA_NULL, 1);
+ filterLowHangingWalkableObstacles(hf, 4);
+ expect(column(hf, 0, 0)[1]!.area).toBe(NAV_AREA_WALKABLE);
+ });
+
+ it('leaves one too tall to step onto alone', () => {
+ const hf = field();
+ addSpan(hf, 0, 0, 0, 10, NAV_AREA_WALKABLE, 1);
+ addSpan(hf, 0, 0, 20, 21, NAV_AREA_NULL, 1);
+ filterLowHangingWalkableObstacles(hf, 4);
+ expect(column(hf, 0, 0)[1]!.area).toBe(NAV_AREA_NULL);
+ });
+});
+
+describe('filterLedgeSpans', () => {
+ // The last row of floor before a drop is where an agent walking the very edge
+ // of it would fall. Nothing else in the bake knows that: a cell on the lip
+ // has a floor, has headroom, and is perfectly flat.
+ it('takes the walkable flag off the floor at the edge of a drop', () => {
+ const hf = field();
+ // A plateau over the left half at height 40, nothing at all on the right.
+ for (let z = 0; z < 10; z++) {
+ for (let x = 0; x < 5; x++) addSpan(hf, x, z, 0, 40, NAV_AREA_WALKABLE, 1);
+ }
+ filterLedgeSpans(hf, 4, 2);
+ expect(column(hf, 4, 5)[0]!.area).toBe(NAV_AREA_NULL);
+ expect(column(hf, 2, 5)[0]!.area).toBe(NAV_AREA_WALKABLE);
+ });
+
+ it('leaves a step it can walk down alone', () => {
+ const hf = field();
+ for (let z = 0; z < 10; z++) {
+ for (let x = 0; x < 10; x++) {
+ addSpan(hf, x, z, 0, x < 5 ? 40 : 39, NAV_AREA_WALKABLE, 1);
+ }
+ }
+ filterLedgeSpans(hf, 4, 2);
+ expect(column(hf, 4, 5)[0]!.area).toBe(NAV_AREA_WALKABLE);
+ });
+});
+
+describe('filterWalkableLowHeightSpans', () => {
+ it('takes away floor an agent cannot stand up on', () => {
+ const hf = field();
+ addSpan(hf, 0, 0, 0, 10, NAV_AREA_WALKABLE, 1);
+ addSpan(hf, 0, 0, 13, 20, NAV_AREA_NULL, 1);
+ addSpan(hf, 1, 0, 0, 10, NAV_AREA_WALKABLE, 1);
+ addSpan(hf, 1, 0, 30, 40, NAV_AREA_NULL, 1);
+ filterWalkableLowHeightSpans(hf, 5);
+ expect(column(hf, 0, 0)[0]!.area).toBe(NAV_AREA_NULL);
+ expect(column(hf, 1, 0)[0]!.area).toBe(NAV_AREA_WALKABLE);
+ });
+});
+
+describe('the compact field', () => {
+ /** Two neighbouring columns of floor, the second `step` voxels higher. */
+ const stepped = (step: number, climb: number): NavCompactField => {
+ const hf = field();
+ addSpan(hf, 0, 0, 0, 10, NAV_AREA_WALKABLE, 1);
+ addSpan(hf, 1, 0, 0, 10 + step, NAV_AREA_WALKABLE, 1);
+ return new NavCompactField(hf, 5, climb);
+ };
+
+ it('connects two floors only when the step between them can be climbed', () => {
+ expect(stepped(2, 4).getCon(0, 2)).not.toBe(NAV_NOT_CONNECTED);
+ expect(stepped(20, 4).getCon(0, 2)).toBe(NAV_NOT_CONNECTED);
+ });
+
+ it('will not connect through a gap too short to stand in', () => {
+ const hf = field();
+ addSpan(hf, 0, 0, 0, 10, NAV_AREA_WALKABLE, 1);
+ addSpan(hf, 1, 0, 0, 10, NAV_AREA_WALKABLE, 1);
+ // A ceiling over the second column, three voxels above its floor.
+ addSpan(hf, 1, 0, 13, 20, NAV_AREA_NULL, 1);
+ expect(new NavCompactField(hf, 3, 4).getCon(0, 2)).not.toBe(NAV_NOT_CONNECTED);
+ expect(new NavCompactField(hf, 5, 4).getCon(0, 2)).toBe(NAV_NOT_CONNECTED);
+ });
+
+ it('erodes the walkable area by the width of the agent', () => {
+ const hf = field();
+ for (let z = 0; z < 10; z++) {
+ for (let x = 0; x < 10; x++) addSpan(hf, x, z, 0, 10, NAV_AREA_WALKABLE, 1);
+ }
+ const chf = new NavCompactField(hf, 5, 4);
+ erodeWalkableArea(chf, 2);
+ const areaAt = (x: number, z: number): number => chf.areas[chf.cellIndex[x + z * 10]!]!;
+ // Two cells in from every edge is gone; the middle is untouched.
+ expect(areaAt(0, 5)).toBe(NAV_AREA_NULL);
+ expect(areaAt(1, 5)).toBe(NAV_AREA_NULL);
+ expect(areaAt(5, 5)).toBe(NAV_AREA_WALKABLE);
+ });
+});
diff --git a/tools/check-component-fields.mjs b/tools/check-component-fields.mjs
index 740f346e0..749de492c 100644
--- a/tools/check-component-fields.mjs
+++ b/tools/check-component-fields.mjs
@@ -40,9 +40,9 @@ const DECLARED_GAPS = {
+ ' own built-in shader and never consult the table',
'SpineAnimation.material': 'see ParticleEmitter.material',
'DragonBonesAnimation.material': 'see ParticleEmitter.material',
- 'Perception.targetZ': 'sensing is three-dimensional and nothing ACTS on the third'
- + ' axis yet: the navigation the built-in chase drives is a 2D grid, so a game'
- + ' reads the pair it can walk to. Closed by 3D navigation (a navmesh)',
+ 'Perception.targetZ': 'sensing is three-dimensional and the navigation under it now'
+ + ' is too, but the chase itself is a game\'s to write and the one example that'
+ + ' writes it is a flat scene. Closed by an example that chases through a NavVolume',
'Perception.dirZ': 'see Perception.targetZ',
};