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 scene can say there is a way where the ground has none

esengine1342ccb38432
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a65b062e..0e07f3ce6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -170,6 +170,25 @@ published separately; it ships inside the editor.
than the box around them. Nothing waits for the solver any more: the geometry is
in the scene from the first frame.
+- **A scene can say there is a way where the ground has none.** A mesh baked from
+ what an agent can walk says two floors with a gap between them are two places,
+ and it is right. `NavLink` is where a scene says what the floor does not: this
+ ledge is a drop, this ladder climbs, this plank reaches the roof. Both ends are
+ offsets in the entity's own frame, so a link travels and turns with whatever
+ carries it, and one whose end reaches no ground joins nothing — a route ending in
+ the air is worse than no route. Moving or switching one costs a lookup rather
+ than a bake, because it joins polygons that already exist.
+
+ The route BREAKS at both ends of a link: pulling a funnel taut over a ladder
+ would plan a walk through the air beside it, so the search is run over each run
+ of polygons and the runs are joined end to end. Which uncovered the other half —
+ an agent crossing a link is not standing on the navigable world, so the replan it
+ asks for there has no answer and it used to strand itself mid-air. A plan that
+ cannot be replaced now beats no plan: a failed replan keeps the route the agent
+ was already walking, which is also the right answer for one standing where a door
+ has just shut. New editor check `nav3d-link` switches a link on in a running game
+ and watches an agent climb it.
+
- **A door can shut.** `NavObstacle` is a box that takes ground away from the
navigable world without being geometry — a door, a gate, a tower just built —
and `enabled` is what opens it again. Blocking is a BAKE input rather than a
diff --git a/desktop b/desktop
index 39008bd43..2a0db5583 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 39008bd43e9fb63b6834fe5cd7dce36bee15817c
+Subproject commit 2a0db558337c0247c26db35a4ee1390ccf0d3c65
diff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
index 10937c21f..21ed8bd16 100644
--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
@@ -100,6 +100,39 @@ on its own terms, and `collectNavGeometry(world, box)` is what gathers the trian
in the log.
</Aside>
+### Ways the ground does not provide
+
+A mesh is baked from what an agent can WALK, so two floors with a gap between them
+are two places — which is the honest answer and not the whole one. A scene knows
+things the floor does not: that this ledge can be dropped off, that this ladder is
+climbable, that this plank reaches the roof. **`NavLink`** is where it says them.
+
+| `NavLink` field | Default | Description |
+|---|---|---|
+| `start` | `0, 0, 0` | Where the way starts, as an offset in the entity's own frame. |
+| `end` | `0, 0, 150` | Where it comes out. |
+| `bidirectional` | `true` | Whether it can be taken both ways. A drop off a ledge cannot. |
+| `radius` | `50` | How far from each end ground may be and still be joined. |
+| `enabled` | `true` | Whether the way exists right now. |
+
+Both ends are offsets in the entity's frame, so a link travels and turns with
+whatever carries it — a ladder inside a prefab is a ladder wherever the prefab is
+put down. A link whose end reaches no ground joins nothing at all: a route that
+ended in the air would be worse than no route.
+
+Moving or switching a link costs a **lookup**, not a bake — it joins polygons that
+already exist. That is the difference between it and an obstacle, and the reason
+one is cheap to animate and the other is not.
+
+<Aside type="note">
+ **The route breaks at both ends of a link.** A funnel pulled taut over a ladder
+ would plan a walk through the air beside it, so the waypoints always include the
+ two points the link joins, and a following agent goes through them. While it is
+ crossing, it is not standing on the navigable world at all — a replan asked there
+ has no answer, so the agent keeps the route it already had rather than stranding
+ itself halfway.
+</Aside>
+
### Doors, gates and things placed in the way
Anything with a collider already blocks, because the mesh is baked from the
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 47bc9ef9a..ec31cd52a 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
@@ -89,6 +89,34 @@ export const setupNav = defineSystem([Res(Nav)], (nav) => {
规划路线,并在日志里说一次。
</Aside>
+### 地面没有提供的路
+
+网格是从 agent **能走**的地方烘出来的,所以中间隔着空的两层楼就是两个地方——这是诚实的答案,
+但不是全部答案。场景知道地面不知道的事:这道沿可以跳下去、这架梯子能爬、这块板搭到了屋顶。
+**`NavLink`** 就是场景说这些事的地方。
+
+| `NavLink` 字段 | 默认 | 说明 |
+|---|---|---|
+| `start` | `0, 0, 0` | 这条路从哪开始,是实体自身坐标系里的偏移。 |
+| `end` | `0, 0, 150` | 从哪出来。 |
+| `bidirectional` | `true` | 是否双向可走。从沿上跳下去不是。 |
+| `radius` | `50` | 两端多远范围内的地面还算得上被它连起来。 |
+| `enabled` | `true` | 这条路现在存不存在。 |
+
+两端都是实体坐标系里的偏移,所以链接会跟着承载它的东西移动和旋转——预制体里的一架梯子,
+放到哪都还是梯子。**一端够不到任何地面的链接什么也不连**:一条走到半空中结束的路线,
+比没有路线更糟。
+
+移动或开关一个链接的代价是一次**查找**,不是一次烘焙——它连的是已经存在的多边形。
+这就是它和障碍的区别,也是为什么一个能便宜地动、另一个不能。
+
+<Aside type="note">
+ **路线在链接的两端断开。**把绳子拉直会从梯子旁边的空气里穿过去,所以路点里一定包含链接
+ 连起来的那两个点,跟随的 agent 会经过它们。**正在跨越链接的时候,agent 根本不站在可走世界上**
+ ——在那里问重规划是没有答案的,所以 agent 会继续走它已经有的那条路线,而不是把自己
+ 搁在半路上。
+</Aside>
+
### 门、闸,以及被放在路上的东西
任何带碰撞体的东西本来就会挡路——网格就是从场景的碰撞几何烘出来的。**`NavObstacle`**
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 906820fbd..8f60b5f09 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": 1618,
+ "experimental": 1623,
"deprecated": 3
},
- "total": 1804,
+ "total": 1809,
"subsystems": [
{
"id": "ecs",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 833950378..9a98440e3 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -146,6 +146,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
NavAgent: { category: 'gameplay', summary: 'Steers an entity along a path found on the navigation grid.', doc: 'gameplay/ai/navigation' },
NavVolume: { category: 'gameplay', summary: 'The box a navigation mesh is baked over, out of the scene\u2019s own collision geometry.', doc: 'gameplay/ai/navigation' },
NavObstacle: { category: 'gameplay', summary: 'A box that blocks without being geometry \u2014 a door, a gate, a placed building.', doc: 'gameplay/ai/navigation' },
+ NavLink: { category: 'gameplay', summary: 'A way between two places the ground does not join \u2014 a drop, a ladder, a plank.', doc: 'gameplay/ai/navigation' },
Perceiver: { category: 'gameplay', summary: 'Senses nearby perception targets within a sight cone and range.', doc: 'gameplay/ai/perception' },
Perception: { category: 'gameplay', summary: "What a perceiver currently sees — written each frame for the entity's own logic to read.", doc: 'gameplay/ai/perception' },
PerceptionTarget: { category: 'gameplay', summary: 'Tag: perceivers can see this entity.', doc: 'gameplay/ai/perception' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 63c53b3d6..5e235dbfc 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1989,6 +1989,49 @@
"targetZ"
]
},
+ {
+ "name": "NavLink",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "start",
+ "type": "Vec3",
+ "default": "(0, 0, 0)"
+ },
+ {
+ "key": "end",
+ "type": "Vec3",
+ "default": "(0, 0, 150)"
+ },
+ {
+ "key": "bidirectional",
+ "type": "boolean",
+ "default": "true",
+ "doc": "Whether it can be taken both ways — a drop off a ledge cannot."
+ },
+ {
+ "key": "radius",
+ "type": "number",
+ "default": "50",
+ "doc": "How far from each end ground may be and still be joined.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "start.x",
+ "start.y",
+ "start.z",
+ "end.x",
+ "end.y",
+ "end.z",
+ "radius"
+ ]
+ },
{
"name": "NavObstacle",
"source": "ts",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 74c65e83c..8ead49420 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 · 1504 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1509 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1347,6 +1347,7 @@ agentHeight: number | undefined
agentRadius: number | undefined
cellHeight: number
cellSize: number
+links: readonly NavLinkSegment[] | undefined
max: Vec3
maxEdgeLength: number | undefined
maxSimplificationError: number | undefined
@@ -4703,6 +4704,7 @@ ResourceDef<NavDebugDrawConfig>
enabled: boolean
showBorders: boolean
showFaces: boolean
+showLinks: boolean
```
## NavGeometry — interface @experimental
@@ -4747,15 +4749,39 @@ walkable: ArrayLike<number> | undefined
width: number
```
+## NavLink — const @experimental
+```
+ComponentDef<NavLinkData>
+```
+
+## NavLinkData — interface @experimental
+```
+bidirectional: boolean
+enabled: boolean
+end: Vec3
+radius: number
+start: Vec3
+```
+
+## NavLinkSegment — interface @experimental
+```
+bidirectional: boolean
+end: Vec3
+radius: number
+start: Vec3
+```
+
## NavMesh — class @experimental
```
agentRadius: number
+connect: (segments: readonly NavLinkSegment[]) => void
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
+findPoly: (p: NavPoint, out?: Vec3, snap?: number) => number
findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
heightAt: (p: number, x: number, z: number) => number
+linkCount: number
maxVertsPerPoly: number
neis: Int32Array<ArrayBufferLike>
polyCount: number
@@ -4830,6 +4856,7 @@ up: Vec3
```
border: (a: Vec3, b: Vec3) => void
face: (corners: readonly Vec3[]) => void
+link: (a: Vec3, b: Vec3) => void
```
## NavVolume — const @experimental
@@ -9749,6 +9776,11 @@ BtPlugin
(world: World, opts: CollectNavGeometryOptions): NavGeometry
```
+## collectNavLinks — function @experimental
+```
+(world: World): NavLinkSegment[]
+```
+
## collectNavObstacles — function @experimental
```
(world: World): NavObstacleBox[]
@@ -11019,6 +11051,11 @@ Mesh2DPlugin
(getTile: (x: number, y: number) => number, opts: BuildNavGridOptions): NavGrid
```
+## navLinkDigest — function @experimental
+```
+(links: readonly NavLinkSegment[]): number
+```
+
## navObstacleDigest — function @experimental
```
(obstacles: readonly NavObstacleBox[]): number
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 5d79a3123..68b35cddc 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 · 1523 experimental · 3 deprecated
+Symbols: 113 public · 71 beta · 1528 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1347,6 +1347,7 @@ agentHeight: number | undefined
agentRadius: number | undefined
cellHeight: number
cellSize: number
+links: readonly NavLinkSegment[] | undefined
max: Vec3
maxEdgeLength: number | undefined
maxSimplificationError: number | undefined
@@ -4881,6 +4882,7 @@ ResourceDef<NavDebugDrawConfig>
enabled: boolean
showBorders: boolean
showFaces: boolean
+showLinks: boolean
```
## NavGeometry — interface @experimental
@@ -4925,15 +4927,39 @@ walkable: ArrayLike<number> | undefined
width: number
```
+## NavLink — const @experimental
+```
+ComponentDef<NavLinkData>
+```
+
+## NavLinkData — interface @experimental
+```
+bidirectional: boolean
+enabled: boolean
+end: Vec3
+radius: number
+start: Vec3
+```
+
+## NavLinkSegment — interface @experimental
+```
+bidirectional: boolean
+end: Vec3
+radius: number
+start: Vec3
+```
+
## NavMesh — class @experimental
```
agentRadius: number
+connect: (segments: readonly NavLinkSegment[]) => void
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
+findPoly: (p: NavPoint, out?: Vec3, snap?: number) => number
findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
heightAt: (p: number, x: number, z: number) => number
+linkCount: number
maxVertsPerPoly: number
neis: Int32Array<ArrayBufferLike>
polyCount: number
@@ -5008,6 +5034,7 @@ up: Vec3
```
border: (a: Vec3, b: Vec3) => void
face: (corners: readonly Vec3[]) => void
+link: (a: Vec3, b: Vec3) => void
```
## NavVolume — const @experimental
@@ -9957,6 +9984,11 @@ BtPlugin
(world: World, opts: CollectNavGeometryOptions): NavGeometry
```
+## collectNavLinks — function @experimental
+```
+(world: World): NavLinkSegment[]
+```
+
## collectNavObstacles — function @experimental
```
(world: World): NavObstacleBox[]
@@ -11262,6 +11294,11 @@ Mesh2DPlugin
(getTile: (x: number, y: number) => number, opts: BuildNavGridOptions): NavGrid
```
+## navLinkDigest — function @experimental
+```
+(links: readonly NavLinkSegment[]): number
+```
+
## navObstacleDigest — function @experimental
```
(obstacles: readonly NavObstacleBox[]): number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index d84fabfa8..40a27d2af 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 · 1503 experimental · 3 deprecated
+Symbols: 113 public · 68 beta · 1508 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1342,6 +1342,7 @@ agentHeight: number | undefined
agentRadius: number | undefined
cellHeight: number
cellSize: number
+links: readonly NavLinkSegment[] | undefined
max: Vec3
maxEdgeLength: number | undefined
maxSimplificationError: number | undefined
@@ -4698,6 +4699,7 @@ ResourceDef<NavDebugDrawConfig>
enabled: boolean
showBorders: boolean
showFaces: boolean
+showLinks: boolean
```
## NavGeometry — interface @experimental
@@ -4742,15 +4744,39 @@ walkable: ArrayLike<number> | undefined
width: number
```
+## NavLink — const @experimental
+```
+ComponentDef<NavLinkData>
+```
+
+## NavLinkData — interface @experimental
+```
+bidirectional: boolean
+enabled: boolean
+end: Vec3
+radius: number
+start: Vec3
+```
+
+## NavLinkSegment — interface @experimental
+```
+bidirectional: boolean
+end: Vec3
+radius: number
+start: Vec3
+```
+
## NavMesh — class @experimental
```
agentRadius: number
+connect: (segments: readonly NavLinkSegment[]) => void
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
+findPoly: (p: NavPoint, out?: Vec3, snap?: number) => number
findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
heightAt: (p: number, x: number, z: number) => number
+linkCount: number
maxVertsPerPoly: number
neis: Int32Array<ArrayBufferLike>
polyCount: number
@@ -4825,6 +4851,7 @@ up: Vec3
```
border: (a: Vec3, b: Vec3) => void
face: (corners: readonly Vec3[]) => void
+link: (a: Vec3, b: Vec3) => void
```
## NavVolume — const @experimental
@@ -9744,6 +9771,11 @@ BtPlugin
(world: World, opts: CollectNavGeometryOptions): NavGeometry
```
+## collectNavLinks — function @experimental
+```
+(world: World): NavLinkSegment[]
+```
+
## collectNavObstacles — function @experimental
```
(world: World): NavObstacleBox[]
@@ -11019,6 +11051,11 @@ Mesh2DPlugin
(getTile: (x: number, y: number) => number, opts: BuildNavGridOptions): NavGrid
```
+## navLinkDigest — function @experimental
+```
+(links: readonly NavLinkSegment[]): number
+```
+
## navObstacleDigest — function @experimental
```
(obstacles: readonly NavObstacleBox[]): number
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index df9099149..75f748681 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 · 1524 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1529 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1342,6 +1342,7 @@ agentHeight: number | undefined
agentRadius: number | undefined
cellHeight: number
cellSize: number
+links: readonly NavLinkSegment[] | undefined
max: Vec3
maxEdgeLength: number | undefined
maxSimplificationError: number | undefined
@@ -4943,6 +4944,7 @@ ResourceDef<NavDebugDrawConfig>
enabled: boolean
showBorders: boolean
showFaces: boolean
+showLinks: boolean
```
## NavGeometry — interface @experimental
@@ -4987,15 +4989,39 @@ walkable: ArrayLike<number> | undefined
width: number
```
+## NavLink — const @experimental
+```
+ComponentDef<NavLinkData>
+```
+
+## NavLinkData — interface @experimental
+```
+bidirectional: boolean
+enabled: boolean
+end: Vec3
+radius: number
+start: Vec3
+```
+
+## NavLinkSegment — interface @experimental
+```
+bidirectional: boolean
+end: Vec3
+radius: number
+start: Vec3
+```
+
## NavMesh — class @experimental
```
agentRadius: number
+connect: (segments: readonly NavLinkSegment[]) => void
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
+findPoly: (p: NavPoint, out?: Vec3, snap?: number) => number
findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
heightAt: (p: number, x: number, z: number) => number
+linkCount: number
maxVertsPerPoly: number
neis: Int32Array<ArrayBufferLike>
polyCount: number
@@ -5070,6 +5096,7 @@ up: Vec3
```
border: (a: Vec3, b: Vec3) => void
face: (corners: readonly Vec3[]) => void
+link: (a: Vec3, b: Vec3) => void
```
## NavVolume — const @experimental
@@ -9989,6 +10016,11 @@ BtPlugin
(world: World, opts: CollectNavGeometryOptions): NavGeometry
```
+## collectNavLinks — function @experimental
+```
+(world: World): NavLinkSegment[]
+```
+
## collectNavObstacles — function @experimental
```
(world: World): NavObstacleBox[]
@@ -11274,6 +11306,11 @@ Mesh2DPlugin
(getTile: (x: number, y: number) => number, opts: BuildNavGridOptions): NavGrid
```
+## navLinkDigest — function @experimental
+```
+(links: readonly NavLinkSegment[]): number
+```
+
## navObstacleDigest — function @experimental
```
(obstacles: readonly NavObstacleBox[]): number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 568e2f248..c34bd011c 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 · 1514 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1519 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1342,6 +1342,7 @@ agentHeight: number | undefined
agentRadius: number | undefined
cellHeight: number
cellSize: number
+links: readonly NavLinkSegment[] | undefined
max: Vec3
maxEdgeLength: number | undefined
maxSimplificationError: number | undefined
@@ -4705,6 +4706,7 @@ ResourceDef<NavDebugDrawConfig>
enabled: boolean
showBorders: boolean
showFaces: boolean
+showLinks: boolean
```
## NavGeometry — interface @experimental
@@ -4749,15 +4751,39 @@ walkable: ArrayLike<number> | undefined
width: number
```
+## NavLink — const @experimental
+```
+ComponentDef<NavLinkData>
+```
+
+## NavLinkData — interface @experimental
+```
+bidirectional: boolean
+enabled: boolean
+end: Vec3
+radius: number
+start: Vec3
+```
+
+## NavLinkSegment — interface @experimental
+```
+bidirectional: boolean
+end: Vec3
+radius: number
+start: Vec3
+```
+
## NavMesh — class @experimental
```
agentRadius: number
+connect: (segments: readonly NavLinkSegment[]) => void
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
+findPoly: (p: NavPoint, out?: Vec3, snap?: number) => number
findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
heightAt: (p: number, x: number, z: number) => number
+linkCount: number
maxVertsPerPoly: number
neis: Int32Array<ArrayBufferLike>
polyCount: number
@@ -4832,6 +4858,7 @@ up: Vec3
```
border: (a: Vec3, b: Vec3) => void
face: (corners: readonly Vec3[]) => void
+link: (a: Vec3, b: Vec3) => void
```
## NavVolume — const @experimental
@@ -9771,6 +9798,11 @@ BtPlugin
(world: World, opts: CollectNavGeometryOptions): NavGeometry
```
+## collectNavLinks — function @experimental
+```
+(world: World): NavLinkSegment[]
+```
+
## collectNavObstacles — function @experimental
```
(world: World): NavObstacleBox[]
@@ -11046,6 +11078,11 @@ Mesh2DPlugin
(getTile: (x: number, y: number) => number, opts: BuildNavGridOptions): NavGrid
```
+## navLinkDigest — function @experimental
+```
+(links: readonly NavLinkSegment[]): number
+```
+
## navObstacleDigest — function @experimental
```
(obstacles: readonly NavObstacleBox[]): number
diff --git a/sdk/src/ai/nav/NavDebugDraw.ts b/sdk/src/ai/nav/NavDebugDraw.ts
index 198111cd8..98205bdec 100644
--- a/sdk/src/ai/nav/NavDebugDraw.ts
+++ b/sdk/src/ai/nav/NavDebugDraw.ts
@@ -28,6 +28,8 @@ export interface NavDebugDrawConfig {
showFaces: boolean;
/** Mark the edges the walkable world stops at, which is where a route turns. */
showBorders: boolean;
+ /** Draw the ways between places the ground does not join. */
+ showLinks: boolean;
}
/** Off until a game turns it on: a surface is thousands of faces and each is a loop. */
@@ -35,10 +37,13 @@ export const NavDebugDraw = defineResource<NavDebugDrawConfig>({
enabled: false,
showFaces: true,
showBorders: true,
+ showLinks: true,
}, 'NavDebugDraw');
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 };
+/** Its own colour: a link is the one thing here that is not ground. */
+const LINK: Color = { r: 0.45, g: 0.7, b: 1.0, a: 0.95 };
/** 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
@@ -80,12 +85,19 @@ export function drawNavDebug(surface: NavSurface | null, cfg: NavDebugDrawConfig
b.x = q.x + lx; b.y = q.y + ly; b.z = q.z + lz;
Draw.line3D(a, b, BORDER, LINE_THICKNESS);
},
+ link(p, q) {
+ if (!cfg.showLinks) 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, LINK, LINE_THICKNESS * 2);
+ },
});
}
/** Install the overlay. Off until a game turns the resource on. */
export function setupNavDebugDraw(app: App): void {
- app.insertResource(NavDebugDraw, { enabled: false, showFaces: true, showBorders: true });
+ app.insertResource(NavDebugDraw,
+ { enabled: false, showFaces: true, showBorders: true, showLinks: true });
registerDrawCallback('nav-debug-draw', () => {
const cfg = app.getResource<NavDebugDrawConfig>(NavDebugDraw);
if (!cfg?.enabled) return;
diff --git a/sdk/src/ai/nav/NavLink.ts b/sdk/src/ai/nav/NavLink.ts
new file mode 100644
index 000000000..630670661
--- /dev/null
+++ b/sdk/src/ai/nav/NavLink.ts
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file NavLink.ts
+ * @brief A way between two places the ground does not join — a drop off a
+ * ledge, a ladder, a plank across a gap.
+ *
+ * The mesh is baked from what an agent can WALK, so two floors are two places
+ * unless geometry joins them. That is the honest answer and it is not the whole
+ * one: a scene knows things the floor does not, and this is where it says them.
+ *
+ * Both ends are offsets in the entity's own frame, so a link turns and travels
+ * with whatever carries it — a ladder in a prefab is a ladder wherever the prefab
+ * is put down.
+ */
+
+import { defineComponent } from '../../ecs/component';
+import type { Vec3 } from '../../types';
+
+export interface NavLinkData {
+ /** Where the way starts, relative to the entity. */
+ start: Vec3;
+ /** Where it comes out, relative to the entity. */
+ end: Vec3;
+ /** Whether it can be taken in both directions. A drop off a ledge is not. */
+ bidirectional: boolean;
+ /**
+ * How far from each end the ground may be and still be joined, in world
+ * pixels. An end that reaches no ground joins nothing.
+ */
+ radius: number;
+ enabled: boolean;
+}
+
+export const NavLink = defineComponent<NavLinkData>('NavLink', {
+ start: { x: 0, y: 0, z: 0 },
+ end: { x: 0, y: 0, z: 150 },
+ bidirectional: true,
+ radius: 50,
+ enabled: true,
+}, {
+ fields: {
+ start: { unit: 'px', category: 'Navigation' },
+ end: { unit: 'px', category: 'Navigation' },
+ bidirectional: { category: 'Navigation', tooltip: 'Whether it can be taken both ways — a drop off a ledge cannot.' },
+ radius: { min: 1, unit: 'px', category: 'Navigation', tooltip: 'How far from each end ground may be and still be joined.' },
+ enabled: { category: 'Navigation' },
+ },
+});
diff --git a/sdk/src/ai/nav/NavMesh.ts b/sdk/src/ai/nav/NavMesh.ts
index 543f73ad6..3cb5693ce 100644
--- a/sdk/src/ai/nav/NavMesh.ts
+++ b/sdk/src/ai/nav/NavMesh.ts
@@ -19,6 +19,24 @@ import type { NavPoint, NavQueryOptions, NavSurface, NavSurfaceSink } from './Na
import { MinHeap } from './minHeap';
import { log } from '../../util/logger';
+/** A way between two places the ground does not join, in world space. */
+export interface NavLinkSegment {
+ start: Vec3;
+ end: Vec3;
+ /** Whether it can be taken from `end` back to `start`. */
+ bidirectional: boolean;
+ /** How far from each end ground may be and still be joined. */
+ radius: number;
+}
+
+/** One resolved link: the polygons it joins, and the two points it joins them at. */
+interface NavLinkEdge {
+ from: number;
+ to: number;
+ start: Vec3;
+ end: Vec3;
+}
+
export interface NavMeshData {
/** `vertCount * 3` world-space floats. */
verts: Float32Array;
@@ -66,6 +84,9 @@ export class NavMesh implements NavSurface {
readonly agentRadius: number;
readonly snapDistance: number;
readonly verticalReach: number;
+ /** Ways between polygons that share no edge, both directions listed separately. */
+ private links_: NavLinkEdge[] = [];
+ private linksFrom_: Map<number, number[]> = new Map();
/** Polygon bounds in the ground plane, four floats each — the whole of what
* the lookup below needs, and cheaper to scan than the vertices. */
@@ -134,6 +155,39 @@ export class NavMesh implements NavSurface {
this.buckets = lists.map(l => Int32Array.from(l));
}
+ /**
+ * Join places the ground does not. Each segment is resolved to the polygons
+ * under its two ends; one that reaches no ground at either end joins nothing
+ * and is dropped, because a link to nowhere is a route that ends in the air.
+ */
+ connect(segments: readonly NavLinkSegment[]): void {
+ this.links_ = [];
+ this.linksFrom_ = new Map();
+ const at = { x: 0, y: 0, z: 0 };
+ for (const segment of segments) {
+ const from = this.findPoly(segment.start, at, segment.radius);
+ const start = { ...at };
+ const to = this.findPoly(segment.end, at, segment.radius);
+ if (from < 0 || to < 0 || from === to) continue;
+ this.addLink({ from, to, start, end: { ...at } });
+ if (segment.bidirectional) {
+ this.addLink({ from: to, to: from, start: { ...at }, end: start });
+ }
+ }
+ }
+
+ /** How many links this mesh carries, counting each direction of a two-way one. */
+ get linkCount(): number {
+ return this.links_.length;
+ }
+
+ private addLink(edge: NavLinkEdge): void {
+ const index = this.links_.push(edge) - 1;
+ const list = this.linksFrom_.get(edge.from);
+ if (list) list.push(index);
+ else this.linksFrom_.set(edge.from, [index]);
+ }
+
/** How many corners polygon `p` actually has. */
vertexCount(p: number): number {
const base = p * this.maxVertsPerPoly;
@@ -201,13 +255,14 @@ export class NavMesh implements NavSurface {
/**
* 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.
+ * which is the whole reason this mesh exists. `snap` overrides how far off the
+ * mesh the point may be, for a caller that has its own idea of near.
*/
- findPoly(p: NavPoint, out?: Vec3): number {
+ findPoly(p: NavPoint, out?: Vec3, snap?: number): number {
const x = p.x;
const z = p.z ?? 0;
const y = p.y;
- const reach = this.snapDistance;
+ const reach = snap ?? this.snapDistance;
let best = -1;
let bestScore = Infinity;
let bestY = 0;
@@ -286,14 +341,39 @@ export class NavMesh implements NavSurface {
const polyPath = this.findPolyPath(startPoly, endPoly, start, end);
if (!polyPath) return null;
- return this.straightPath(polyPath, start, end);
+ return this.routeThroughLinks(polyPath, start, end);
+ }
+
+ /**
+ * The taut route, broken at every link. A link joins two points and nothing
+ * between them, so the funnel is run over each RUN of polygons the route walks
+ * and the runs are joined end to end — pulling one taut across a link would cut
+ * the corner off a ladder.
+ */
+ private routeThroughLinks(path: PolyPath, start: Vec3, end: Vec3): Vec3[] {
+ const out: Vec3[] = [];
+ let runFrom = 0;
+ let runStart = start;
+ for (let i = 0; i <= path.polys.length; i++) {
+ const link = i < path.polys.length ? path.links[i]! : null;
+ if (link === null || link < 0) continue;
+ const edge = this.links_[link]!;
+ append(out, this.straightPath(path.polys.slice(runFrom, i + 1), runStart, edge.start));
+ append(out, [edge.end]);
+ runFrom = i + 1;
+ runStart = edge.end;
+ }
+ append(out, this.straightPath(path.polys.slice(runFrom), runStart, end));
+ return out;
}
/** A* over the polygon graph, keyed on where each doorway is crossed. */
- private findPolyPath(startPoly: number, endPoly: number, start: Vec3, end: Vec3): number[] | null {
+ private findPolyPath(startPoly: number, endPoly: number, start: Vec3, end: Vec3): PolyPath | null {
const n = this.polyCount;
const cost = new Float64Array(n).fill(Infinity);
const parent = new Int32Array(n).fill(-1);
+ /** Which link was taken to reach each polygon, or -1 for a shared edge. */
+ const via = 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
@@ -329,22 +409,47 @@ export class NavMesh implements NavSurface {
if (g >= cost[next]!) continue;
cost[next] = g;
parent[next] = cur;
+ via[next] = -1;
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);
+ heap.push(next, g + heuristic(mx, my, mz, end));
+ }
+
+ // The ways the ground does not join: crossing one costs getting to the
+ // near end and then the span itself.
+ for (const li of this.linksFrom_.get(cur) ?? EMPTY_LINKS) {
+ const link = this.links_[li]!;
+ const next = link.to;
+ if (closed[next]) continue;
+ const g = cost[cur]!
+ + distance(enterX[cur]!, enterY[cur]!, enterZ[cur]!,
+ link.start.x, link.start.y, link.start.z)
+ + distance(link.start.x, link.start.y, link.start.z,
+ link.end.x, link.end.y, link.end.z);
+ if (g >= cost[next]!) continue;
+ cost[next] = g;
+ parent[next] = cur;
+ via[next] = li;
+ enterX[next] = link.end.x; enterY[next] = link.end.y; enterZ[next] = link.end.z;
+ heap.push(next, g + heuristic(link.end.x, link.end.y, link.end.z, end));
}
}
if (parent[endPoly] === -1 && endPoly !== startPoly) return null;
- const path: number[] = [];
+ const polys: number[] = [];
+ const links: number[] = [];
for (let p = endPoly; p !== -1; p = parent[p]!) {
- path.push(p);
+ polys.push(p);
+ // The link recorded on a polygon is the one taken to REACH it, so it
+ // belongs to the step out of the polygon before it.
+ links.push(via[p]!);
if (p === startPoly) break;
}
- path.reverse();
- return path[0] === startPoly ? path : null;
+ polys.reverse();
+ links.reverse();
+ // Shift by one: `links[i]` is now the step from `polys[i]` to `polys[i+1]`.
+ links.shift();
+ links.push(-1);
+ return polys[0] === startPoly ? { polys, links } : null;
}
/**
@@ -353,7 +458,7 @@ export class NavMesh implements NavSurface {
* 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[] {
+ private straightPath(polyPath: readonly number[], start: Vec3, end: Vec3): Vec3[] {
const left: Vec3[] = [{ ...start }];
const right: Vec3[] = [{ ...start }];
for (let i = 0; i + 1 < polyPath.length; i++) {
@@ -429,6 +534,7 @@ export class NavMesh implements NavSurface {
}
describe(sink: NavSurfaceSink): void {
+ for (const link of this.links_) sink.link(link.start, link.end);
const corners: Vec3[] = [];
for (let p = 0; p < this.polyCount; p++) {
const n = this.vertexCount(p);
@@ -453,8 +559,30 @@ export class NavMesh implements NavSurface {
}
}
+/** A route as the search found it: the polygons walked, and for each step the
+ * link that made it, or -1 where the two polygons share an edge. */
+interface PolyPath {
+ polys: number[];
+ links: number[];
+}
+
+const EMPTY_LINKS: readonly number[] = [];
const EDGE_HIT = new Float64Array(3);
+/** Add waypoints, dropping one that repeats the point already there. */
+function append(out: Vec3[], points: readonly Vec3[]): void {
+ for (const p of points) {
+ const last = out[out.length - 1];
+ if (last && same(last, p) && Math.abs(last.y - p.y) < 1e-4) continue;
+ out.push(p);
+ }
+}
+
+/** Straight-line distance to the goal, trusted as Detour trusts it. */
+function heuristic(x: number, y: number, z: number, end: Vec3): number {
+ return distance(x, y, z, end.x, end.y, end.z) * HEURISTIC_SCALE;
+}
+
/**
* 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
diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.ts
index 7124d8971..f532d42e4 100644
--- a/sdk/src/ai/nav/NavPlugin.ts
+++ b/sdk/src/ai/nav/NavPlugin.ts
@@ -32,9 +32,12 @@ import { NavObstacle } from './NavObstacle';
import { buildNavMesh } from './navmesh/build';
import { collectNavGeometry, navGeometryReady, type NavGeometry } from './navGeometry';
import {
- applyObstaclesToGrid, collectNavObstacles, navObstacleDigest, type NavObstacleBox,
+ applyObstaclesToGrid, collectNavObstacles, navObstacleDigest,
+ collectNavLinks, navLinkDigest, type NavObstacleBox,
} from './navObstacles';
import { NavGrid } from './NavGrid';
+import { NavMesh, type NavLinkSegment } from './NavMesh';
+import { NavLink } from './NavLink';
import { setupNavDebugDraw } from './NavDebugDraw';
import { advanceAlongPath } from './follow';
@@ -65,6 +68,7 @@ export function bakeVolumes(
geometry: NavGeometryProvider | null,
baked: Set<Entity>,
obstacles: readonly NavObstacleBox[] = [],
+ links: readonly NavLinkSegment[] = [],
): void {
if (!geometry) return;
const volumes = world.getEntitiesWithComponents([NavVolume, Transform]);
@@ -89,6 +93,7 @@ export function bakeVolumes(
agentRadius: volume.agentRadius,
stepHeight: volume.stepHeight,
obstacles,
+ links,
});
nav.setSurface(mesh);
@@ -148,6 +153,23 @@ export function updateObstacles(
return changed;
}
+/**
+ * Re-join a mesh's links when the scene's have changed. Separate from the
+ * obstacles because it is a different KIND of change: a link joins polygons that
+ * already exist, so moving one costs a lookup rather than a bake, and paying a
+ * bake for it would be the reason nobody moves one.
+ */
+export function updateLinks(
+ nav: Navigation, links: readonly NavLinkSegment[], state: LinkState,
+): void {
+ const digest = navLinkDigest(links);
+ const mesh = nav.surface instanceof NavMesh ? nav.surface : null;
+ if (digest === state.digest && mesh === state.mesh) return;
+ state.digest = digest;
+ state.mesh = mesh;
+ if (mesh) mesh.connect(links);
+}
+
/** What the obstacles were when the world was last built for them. */
export interface ObstacleState {
digest: number;
@@ -156,6 +178,12 @@ export interface ObstacleState {
grid: NavGrid | null;
}
+/** What the links were when the mesh was last joined for them. */
+export interface LinkState {
+ digest: number;
+ mesh: NavMesh | null;
+}
+
/** The shortest gap between two rebuilds. A door should shut at once; something
* that keeps moving must not take the frame rate with it. */
const NAV_REBAKE_MS = 200;
@@ -202,16 +230,28 @@ export function stepNavigation(
{ x: agent.targetX, y: agent.targetY, z: agent.targetZ },
{ radius: agent.radius },
);
- rt = {
- waypoints: path ?? [],
- // Skip the start point to avoid stepping back toward it.
- index: path && path.length > 1 ? 1 : 0,
- plannedX: agent.targetX,
- plannedY: agent.targetY,
- plannedZ: agent.targetZ,
- repathTimer: agent.repathInterval,
- reachable: path !== null,
- };
+ // A plan that cannot be replaced beats no plan: an agent crossing a
+ // link is not standing on the navigable world, so the replan it asks
+ // for there has no answer and dropping the route strands it mid-air.
+ const keep = path === null && rt !== undefined && rt.reachable
+ && rt.index < rt.waypoints.length;
+ if (keep && rt) {
+ rt.plannedX = agent.targetX;
+ rt.plannedY = agent.targetY;
+ rt.plannedZ = agent.targetZ;
+ rt.repathTimer = agent.repathInterval;
+ } else {
+ rt = {
+ waypoints: path ?? [],
+ // Skip the start point to avoid stepping back toward it.
+ index: path && path.length > 1 ? 1 : 0,
+ plannedX: agent.targetX,
+ plannedY: agent.targetY,
+ plannedZ: agent.targetZ,
+ repathTimer: agent.repathInterval,
+ reachable: path !== null,
+ };
+ }
runtimes.set(entity, rt);
}
@@ -316,6 +356,7 @@ export class NavPlugin implements Plugin {
const runtimes = new Map<Entity, AgentRuntime>();
const baked = new Set<Entity>();
const obstacleState: ObstacleState = { digest: 0, at: 0, deferred: 0, grid: null };
+ const linkState: LinkState = { digest: 0, mesh: null };
app.world.onDespawn((entity: Entity) => {
runtimes.delete(entity);
baked.delete(entity);
@@ -334,14 +375,16 @@ export class NavPlugin implements Plugin {
collectNavGeometry(app.world, { min, max, layers })
: null;
const obstacles = collectNavObstacles(app.world);
+ const links = collectNavLinks(app.world);
if (updateObstacles(nav, obstacles, obstacleState, Date.now())) baked.clear();
- bakeVolumes(world as NavWorldView, nav, provider, baked, obstacles);
+ bakeVolumes(world as NavWorldView, nav, provider, baked, obstacles, links);
+ updateLinks(nav, links, linkState);
stepNavigation(world as NavWorldView, nav, time.delta, runtimes);
},
{
name: 'NavAgentSystem',
touches: {
- reads: [NavVolume._name, NavObstacle._name],
+ reads: [NavVolume._name, NavObstacle._name, NavLink._name],
writes: [NavAgent._name, Transform._name, CharacterController3D._name],
},
// Both move an entity; for one carrying both, the path is the
diff --git a/sdk/src/ai/nav/NavSurface.ts b/sdk/src/ai/nav/NavSurface.ts
index eba91823f..8bdfd267a 100644
--- a/sdk/src/ai/nav/NavSurface.ts
+++ b/sdk/src/ai/nav/NavSurface.ts
@@ -46,6 +46,9 @@ export interface NavSurfaceSink {
face(corners: readonly Vec3[]): void;
/** An edge the walkable world STOPS at: a wall, a ledge, a drop. */
border(a: Vec3, b: Vec3): void;
+ /** A way between two places the ground does not join — see `NavLink`. A
+ * surface with no such thing simply never calls it. */
+ link(a: Vec3, b: Vec3): void;
}
/** The active navigable world, however it was built. */
diff --git a/sdk/src/ai/nav/index.ts b/sdk/src/ai/nav/index.ts
index 24f24721c..f4e147c69 100644
--- a/sdk/src/ai/nav/index.ts
+++ b/sdk/src/ai/nav/index.ts
@@ -15,7 +15,7 @@ export {
navGridFromTilemapLayer,
type BuildNavGridOptions,
} from './navGridFromTilemap';
-export { NavMesh, type NavMeshData } from './NavMesh';
+export { NavMesh, type NavMeshData, type NavLinkSegment } from './NavMesh';
export { buildNavMesh, type BuildNavMeshOptions } from './navmesh/build';
export {
collectNavGeometry, navGeometryReady,
@@ -25,8 +25,10 @@ export { Navigation, Nav } from './Navigation';
export { NavAgent, type NavAgentData, setNavDestination, stopNavAgent } from './NavAgent';
export { NavVolume, type NavVolumeData } from './NavVolume';
export { NavObstacle, type NavObstacleData } from './NavObstacle';
+export { NavLink, type NavLinkData } from './NavLink';
export {
collectNavObstacles, navObstacleDigest, applyObstaclesToGrid, type NavObstacleBox,
+ collectNavLinks, navLinkDigest,
} from './navObstacles';
export { NavPlugin, navPlugin } from './NavPlugin';
export { NavDebugDraw, drawNavDebug, type NavDebugDrawConfig } from './NavDebugDraw';
diff --git a/sdk/src/ai/nav/navObstacles.ts b/sdk/src/ai/nav/navObstacles.ts
index b057a98a6..6c4cb4d94 100644
--- a/sdk/src/ai/nav/navObstacles.ts
+++ b/sdk/src/ai/nav/navObstacles.ts
@@ -16,6 +16,8 @@ import type { World } from '../../ecs/world';
import { Transform } from '../../ecs/component';
import { q } from '../../math/quat';
import { NavObstacle, type NavObstacleData } from './NavObstacle';
+import { NavLink, type NavLinkData } from './NavLink';
+import type { NavLinkSegment } from './NavMesh';
import type { NavGrid } from './NavGrid';
import type { NavObstacleBox } from './navmesh/compact';
@@ -40,6 +42,44 @@ export function collectNavObstacles(world: World): NavObstacleBox[] {
return out;
}
+/** Every link a scene declares, with both ends placed in the world. */
+export function collectNavLinks(world: World): NavLinkSegment[] {
+ const out: NavLinkSegment[] = [];
+ for (const entity of world.getEntitiesWithComponents([NavLink, Transform])) {
+ const link = world.get(entity, NavLink) as NavLinkData;
+ if (link.enabled === false) continue;
+ const tf = world.get(entity, Transform);
+ const at = tf.position as Vec3;
+ const rot = tf.rotation as Quat;
+ const place = (offset: Vec3): Vec3 => {
+ const r = q.rotate(rot, offset);
+ return { x: at.x + r.x, y: at.y + r.y, z: at.z + r.z };
+ };
+ out.push({
+ start: place(link.start),
+ end: place(link.end),
+ bidirectional: link.bidirectional !== false,
+ radius: Math.max(1, link.radius),
+ });
+ }
+ return out;
+}
+
+/** A number that differs whenever the links do. Same shape as the obstacles'
+ * digest, and separate because re-joining a mesh is cheap and re-baking is not. */
+export function navLinkDigest(links: readonly NavLinkSegment[]): number {
+ let hash = 2166136261;
+ const mix = (v: number): void => {
+ hash = Math.imul(hash ^ (Math.round(v * 10) | 0), 16777619);
+ };
+ for (const link of links) {
+ mix(link.start.x); mix(link.start.y); mix(link.start.z);
+ mix(link.end.x); mix(link.end.y); mix(link.end.z);
+ mix(link.radius); mix(link.bidirectional ? 1 : 0);
+ }
+ return hash;
+}
+
/**
* A number that differs whenever the obstacles do — one moved, resized, added,
* removed or switched off. Positions are rounded to a tenth of a pixel first, so
diff --git a/sdk/src/ai/nav/navmesh/build.ts b/sdk/src/ai/nav/navmesh/build.ts
index e576ee3b2..3a89c9f1f 100644
--- a/sdk/src/ai/nav/navmesh/build.ts
+++ b/sdk/src/ai/nav/navmesh/build.ts
@@ -17,7 +17,7 @@
*/
import type { Vec3 } from '../../../types';
-import { NavMesh } from '../NavMesh';
+import { NavMesh, type NavLinkSegment } from '../NavMesh';
import {
NavHeightfield, heightfieldColumns, rasterizeTriangles,
filterLowHangingWalkableObstacles, filterLedgeSpans, filterWalkableLowHeightSpans,
@@ -61,6 +61,8 @@ export interface BuildNavMeshOptions {
maxVertsPerPoly?: number;
/** Boxes that block without being geometry — see `NavObstacle`. */
obstacles?: readonly NavObstacleBox[];
+ /** Ways between places the ground does not join — see `NavLink`. */
+ links?: readonly NavLinkSegment[];
}
export function buildNavMesh(
@@ -108,7 +110,7 @@ export function buildNavMesh(
world[i * 3 + 2] = opts.min.z + mesh.verts[i * 3 + 2]! * cs;
}
- return new NavMesh({
+ const built = new NavMesh({
verts: world,
polys: mesh.polys,
neis: mesh.neis,
@@ -122,6 +124,8 @@ export function buildNavMesh(
// be standing on; anything further is a different storey.
verticalReach: Math.max((opts.agentHeight ?? 0) + (opts.stepHeight ?? 0), ch * 4),
});
+ if (opts.links?.length) built.connect(opts.links);
+ return built;
}
/**
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index ac0a31fbb..be61330e3 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -674,7 +674,10 @@ export {
NavAgent,
NavVolume,
NavObstacle,
+ NavLink,
collectNavObstacles,
+ collectNavLinks,
+ navLinkDigest,
navObstacleDigest,
applyObstaclesToGrid,
setNavDestination,
@@ -697,6 +700,8 @@ export {
type NavAgentData,
type NavVolumeData,
type NavObstacleData,
+ type NavLinkData,
+ type NavLinkSegment,
type NavObstacleBox,
type NavDebugDrawConfig,
} from './ai';
diff --git a/sdk/tests/nav-links.test.ts b/sdk/tests/nav-links.test.ts
new file mode 100644
index 000000000..fc132c562
--- /dev/null
+++ b/sdk/tests/nav-links.test.ts
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Ways between places the ground does not join.
+ *
+ * A mesh baked from what an agent can WALK says two floors are two places, and
+ * that is the honest answer. A scene knows things the floor does not — that this
+ * ledge can be dropped off, that this ladder is climbable — and a link is where
+ * it says them. So the claims are about the ROUTE: that one appears, that it goes
+ * through both ends rather than across them, and that a one-way drop is one way.
+ */
+import { describe, it, expect } from 'vitest';
+import { buildNavMesh } from '../src/ai/nav/navmesh/build';
+import { NavMesh, type NavLinkSegment } from '../src/ai/nav/NavMesh';
+import { Navigation } from '../src/ai/nav/Navigation';
+import { updateLinks, type LinkState } from '../src/ai/nav/NavPlugin';
+import type { Vec3 } from '../src/types';
+
+/** Two floors with a gap between them: the lower one, and one three metres up. */
+function twoFloors(): { verts: Float32Array; indices: Uint32Array } {
+ const verts: number[] = [];
+ const indices: number[] = [];
+ const quad = (y: number, x0: number, x1: number) => {
+ const base = verts.length / 3;
+ verts.push(x0, y, -400, x1, y, -400, x1, y, 400, x0, y, 400);
+ indices.push(base, base + 2, base + 1, base, base + 3, base + 2);
+ };
+ quad(0, -600, -100);
+ quad(300, 100, 600);
+ return { verts: Float32Array.from(verts), indices: Uint32Array.from(indices) };
+}
+
+const BOX = {
+ min: { x: -700, y: -100, z: -500 },
+ max: { x: 700, y: 600, z: 500 },
+ cellSize: 25,
+ cellHeight: 10,
+ agentHeight: 180,
+ agentRadius: 30,
+ stepHeight: 40,
+};
+
+const bake = (links: NavLinkSegment[] = []): NavMesh => {
+ const g = twoFloors();
+ return buildNavMesh(g.verts, g.indices, { ...BOX, links });
+};
+
+const LADDER: NavLinkSegment = {
+ start: { x: -200, y: 0, z: 0 },
+ end: { x: 200, y: 300, z: 0 },
+ bidirectional: true,
+ radius: 60,
+};
+
+const LOW: Vec3 = { x: -500, y: 0, z: 0 };
+const HIGH: Vec3 = { x: 500, y: 300, z: 0 };
+
+describe('a link between two floors', () => {
+ it('is what makes the two of them one navigable world', () => {
+ expect(bake().findWorldPath(LOW, HIGH)).toBeNull();
+ expect(bake([LADDER]).findWorldPath(LOW, HIGH)).not.toBeNull();
+ });
+
+ // The route has to go THROUGH the link, not across the gap it spans: a funnel
+ // pulled taut over a ladder would plan a walk through the air beside it.
+ it('breaks the route at both of its ends', () => {
+ const path = bake([LADDER]).findWorldPath(LOW, HIGH)!;
+ const near = (p: Vec3, to: Vec3): boolean =>
+ Math.hypot(p.x - to.x, p.y - to.y, p.z - to.z) < 80;
+ expect(path.some(p => near(p, LADDER.start))).toBe(true);
+ expect(path.some(p => near(p, LADDER.end))).toBe(true);
+ // And it climbs: the route leaves the floor it started on.
+ expect(Math.max(...path.map(p => p.y))).toBeGreaterThan(250);
+ });
+
+ it('is one way when the scene says so', () => {
+ const drop = bake([{ ...LADDER, bidirectional: false }]);
+ expect(drop.findWorldPath(LOW, HIGH)).not.toBeNull();
+ expect(drop.findWorldPath(HIGH, LOW)).toBeNull();
+ });
+
+ // A link is a claim about ground at both ends. One end over nothing joins
+ // nothing, and a route that ended in the air would be worse than no route.
+ it('joins nothing when an end reaches no ground', () => {
+ const intoTheAir: NavLinkSegment = { ...LADDER, end: { x: 200, y: 1000, z: 0 } };
+ expect(bake([intoTheAir]).linkCount).toBe(0);
+ expect(bake([intoTheAir]).findWorldPath(LOW, HIGH)).toBeNull();
+ });
+
+ it('counts both directions of a two-way one, and one of a one-way', () => {
+ expect(bake([LADDER]).linkCount).toBe(2);
+ expect(bake([{ ...LADDER, bidirectional: false }]).linkCount).toBe(1);
+ });
+
+ it('hands itself to a drawer, since nothing else on screen says it is there', () => {
+ const drawn: Array<[Vec3, Vec3]> = [];
+ bake([LADDER]).describe({
+ face: () => {}, border: () => {},
+ link: (a, b) => drawn.push([{ ...a }, { ...b }]),
+ });
+ expect(drawn).toHaveLength(2);
+ });
+});
+
+describe('updateLinks', () => {
+ const state = (): LinkState => ({ digest: 0, mesh: null });
+
+ it('joins a mesh the moment there is one to join', () => {
+ const nav = new Navigation();
+ const s = state();
+ updateLinks(nav, [LADDER], s); // nothing installed yet
+ nav.setSurface(bake());
+ updateLinks(nav, [LADDER], s);
+ expect((nav.surface as NavMesh).linkCount).toBe(2);
+ });
+
+ // Moving a link re-joins polygons that already exist. Charging a bake for that
+ // is the reason nobody would ever move one.
+ it('re-joins without rebuilding anything', () => {
+ const nav = new Navigation();
+ const mesh = bake();
+ nav.setSurface(mesh);
+ const s = state();
+ updateLinks(nav, [LADDER], s);
+ updateLinks(nav, [], s);
+ expect(mesh.linkCount).toBe(0);
+ expect(nav.surface).toBe(mesh); // the same mesh throughout
+ });
+
+ it('does nothing at all while the links have not changed', () => {
+ const nav = new Navigation();
+ nav.setSurface(bake([LADDER]));
+ const s = state();
+ updateLinks(nav, [LADDER], s);
+ const before = (nav.surface as NavMesh).linkCount;
+ updateLinks(nav, [LADDER], s);
+ expect((nav.surface as NavMesh).linkCount).toBe(before);
+ });
+});
diff --git a/sdk/tests/nav-step.test.ts b/sdk/tests/nav-step.test.ts
index ed08b196e..a96d65f06 100644
--- a/sdk/tests/nav-step.test.ts
+++ b/sdk/tests/nav-step.test.ts
@@ -302,3 +302,36 @@ describe('an agent with a body', () => {
expect(world.pos(entity).x).toBeGreaterThan(0);
});
});
+
+/**
+ * A replan is asked from wherever the agent has got to, and that is not always
+ * somewhere the navigable world has an answer for — halfway across a link, or
+ * standing where a door has just shut.
+ */
+describe('a replan that finds nothing', () => {
+ it('leaves the agent walking the route it already had', () => {
+ const world = new FakeWorld();
+ const entity = world.spawnAgent(0, 0, {
+ speed: 100, arriveRadius: 0, repathInterval: 0.1, hasTarget: true, targetX: 80, targetY: 0,
+ });
+ const nav = openNav();
+ const runtimes = new Map<Entity, AgentRuntime>();
+ stepNavigation(world, nav, 0.05, runtimes);
+ const after = world.pos(entity).x;
+ expect(after).toBeGreaterThan(0);
+
+ // Nowhere to plan from any more, and the timer is up.
+ nav.setSurface(new NavGrid({ width: 10, height: 3, cellSize: 10, walkable: new Uint8Array(30) }));
+ stepNavigation(world, nav, 0.2, runtimes);
+ expect(world.pos(entity).x).toBeGreaterThan(after);
+ });
+
+ it('does not move an agent that never had one', () => {
+ const world = new FakeWorld();
+ const entity = world.spawnAgent(0, 0, { speed: 100, hasTarget: true, targetX: 80, targetY: 0 });
+ const nav = new Navigation();
+ nav.setSurface(new NavGrid({ width: 10, height: 3, cellSize: 10, walkable: new Uint8Array(30) }));
+ stepNavigation(world, nav, 0.05, new Map());
+ expect(world.pos(entity).x).toBe(0);
+ });
+});
diff --git a/sdk/tests/navmesh-build.test.ts b/sdk/tests/navmesh-build.test.ts
index 8741a2012..482a59b68 100644
--- a/sdk/tests/navmesh-build.test.ts
+++ b/sdk/tests/navmesh-build.test.ts
@@ -229,6 +229,7 @@ describe('buildNavMesh', () => {
mesh.describe({
face: (corners) => { expect(corners.length).toBeGreaterThanOrEqual(3); faces++; },
border: () => { borders++; },
+ link: () => {},
});
expect(faces).toBe(mesh.polyCount);
// A single floor is one island: every edge of its outline is a border.