Metadata-Version: 2.4
Name: wow-navmesh
Version: 1.0.1
Summary: Python bindings for Detour (recastnavigation) navmesh pathfinding over TrinityCore/AzerothCore mmaps
Keywords: recastnavigation,detour,navmesh,pathfinding,trinitycore,azerothcore,wow
Author: srounet
License-Expression: MIT
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES.md
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: C++
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Operating System :: Microsoft :: Windows
Classifier: Topic :: Games/Entertainment
Classifier: Topic :: Software Development :: Libraries
Project-URL: Homepage, https://github.com/srounet/wow-navmesh
Project-URL: Repository, https://github.com/srounet/wow-navmesh
Project-URL: Issues, https://github.com/srounet/wow-navmesh/issues
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# wow-navmesh

Python bindings (via [nanobind](https://github.com/wjakob/nanobind)) for
[Detour](https://github.com/recastnavigation/recastnavigation), the navmesh query engine
from recastnavigation — scoped to pathfinding over the `.mmap`/`.mmtile` navmesh files
generated by TrinityCore/AzerothCore for World of Warcraft 3.3.5a.

This wraps Detour's *query* engine (`dtNavMesh` / `dtNavMeshQuery`) only. It does not
build navmeshes — that's Recast, and TrinityCore/AzerothCore's own mmap generator tools
already produce the `.mmap`/`.mmtile` files this library reads.

Use it to compute walkable paths, snap points to the ground, cast rays across the
walkable surface, or inspect the navmesh polygons themselves, from Python, using
the same navmesh data a 3.3.5a server uses or the latest Forever client.

> wow-navmesh does not ship any navmesh or game data. Generate the mmaps with your
> TrinityCore/AzerothCore server's `mmaps_generator` tool, or use the ones your server
> already has.

## Install

```bash
pip install wow-navmesh
```

Prebuilt wheels are published for 64-bit CPython 3.10–3.15 on Windows (x64) only. No
compiler needed for a normal install. Linux and macOS are not supported.

## Quickstart

```python
import wow_navmesh as wn

nm = wn.NavMesh(r"C:\path\to\mmaps")
nm.load_map(0)  # 0 = Eastern Kingdoms

result = nm.find_path((x1, y1, z1), (x2, y2, z2))
print(result.path_type)  # PathType.NORMAL, PARTIAL or NOT_FOUND
for x, y, z in result.points:
    print(x, y, z)
```

`find_path()` returns a `PathResult`: `points` is empty and `path_type` is
`NOT_FOUND` when no path exists, and `PARTIAL` when the points stop short of the
destination (`actual_end` then says where). That happens when the destination is
unreachable, but also when the route is longer than `max_points`, the 512-polygon
corridor, or the search's node pool (see [Long routes](#long-routes)).

`NavMesh` also works as a context manager, freeing the loaded map on exit:

```python
with wn.NavMesh(r"C:\path\to\mmaps") as nm:
    nm.load_map(0)
    path = nm.find_path((x1, y1, z1), (x2, y2, z2))
```

Coordinates are `(x, y, z)` in WoW world-coordinate order everywhere in this API, so `z`
is height. The `.mmap`/`.mmtile` files store them as `(y, z, x)`; the conversion happens
internally, so callers never need to think about it.

### Precision for bot navigation

For precise bot navigation with closely-spaced waypoints, use `waypoint_distance` to
subdivide the path:

```python
# Return waypoints no more than 2.5 units apart
path = nm.find_path(
    (x1, y1, z1), (x2, y2, z2),
    waypoint_distance=2.5  # Add intermediate waypoints every 2.5 units
)
```

You can also adjust the search box used to find the nearest polygon to `start` and
`end` (half-extent per axis, default 50):

```python
# Tighter matching (more restrictive)
path = nm.find_path((x1, y1, z1), (x2, y2, z2), search_extent=20.0)

# Looser matching (more forgiving)
path = nm.find_path((x1, y1, z1), (x2, y2, z2), search_extent=100.0)
```

Pass `centered=True` to route through the middle of each polygon edge instead of the
shortest path. The path is longer, but it stays away from walls instead of hugging
corners:

```python
path = nm.find_path((x1, y1, z1), (x2, y2, z2), centered=True)
```

### Long routes

Each search may expand at most `max_nodes` polygons (2048 by default). A route that needs
more comes back `PARTIAL` even though the destination is reachable. Either re-path from
where it stopped, or give the `NavMesh` a bigger node pool (Detour's maximum is 65535):

```python
nm = wn.NavMesh(r"C:\path\to\mmaps", max_nodes=65535)
```

On Eastern Kingdoms, Goldshire to Booty Bay (about 3,600 units) stops after 117
polygons with the default and gets within 15 units with 65535, at roughly 12 ms instead
of 0.4 ms per search. A larger pool also makes a search for an unreachable point take
longer, because it explores more before giving up.

## Architecture

```text
NavMesh              map load/free, tile lifetime
   │
   ├── get_loaded_tiles()  -> list[TileInfo]
   │
   └── NavigationQuery   (.query)  thin wrapper over dtNavMeshQuery
          │
          ├── find_nearest_poly, closest_point_on_poly(_boundary), get_poly_height
          ├── find_polygon_path      -> PolygonPathResult (raw dtPolyRef corridor)
          ├── find_straight_path     -> StraightPathResult (funnel points + flags)
          ├── move_along_surface, raycast, find_distance_to_wall
          ├── find_path              -> Path
          │                             ├── polygon_corridor / straight_path
          │                             ├── status (PathStatus)
          │                             └── get_steer_target()  (steering)
          └── introspection: get_poly, get_tile_info, get_tile_polys,
              get_offmesh_connections, sample_polys
```

`NavMesh.find_path()` is the simple entry point. Code that needs the polygon corridor,
`dtPolyRef`s, a distinguishable failure reason, or a steering target should use
`nm.query` instead.

### Nearest poly, raw corridor, straight path

```python
# Half-extents in (x, y, z) order: 5 units around the point, 50 up and down.
nearest = nm.query.find_nearest_poly((x, y, z), extents=(5, 5, 50))
if nearest.found:
    print(nearest.poly_ref, nearest.position, nearest.distance)

corridor = nm.query.find_polygon_path(start, end)
print(corridor.status, corridor.reached_end, corridor.polygons)

straight = nm.query.find_straight_path(start, end, corridor.polygons)
for point in straight.points:
    print(point.position, point.flags, point.poly_ref)
```

`find_polygon_path()` returns the raw Detour polygon chain — no points yet, just `dtPolyRef`s.
`find_straight_path()` runs Detour's funnel algorithm over that corridor to produce actual
waypoints, each carrying its polygon and `DT_STRAIGHTPATH_*` flags (start/end/off-mesh).

### `Path` and steering

`nm.query.find_path(start, end)` returns a `Path` — the corridor and straight path from
one query, plus enough state to ask for a steering target as an agent advances:

```python
path = nm.query.find_path(start, end)
print(path.status)              # PathStatus.SUCCESS / PARTIAL / NO_PATH / ...
print(path.start_poly, path.end_poly)
print(path.actual_end_position)  # may differ from `end` on a PARTIAL path

position, poly = path.start_position, path.start_poly
while path.is_valid():
    steer = path.get_steer_target(position)
    if steer is None or steer.reached:
        break
    # This library only tells you *where* to go next -- it never moves anything. A
    # caller-owned movement layer decides how far the agent gets each tick, e.g. a
    # few units toward steer.position; move_along_surface() keeps it on the mesh:
    desired = step_toward(position, steer.position)  # your own movement code
    moved = nm.query.move_along_surface(position, desired, poly)
    position, poly = moved.position, moved.visited[-1]
```

Pass the polygon the agent is currently in (`moved.visited[-1]`) to each move, not
`path.start_poly`: the start polygon only contains the agent until its first step.

`get_steer_target()` uses the same algorithm as Detour's `NavMeshTesterTool` sample
(which TrinityCore/AzerothCore's path generators also use): it walks the straight path
looking for the first corner not already horizontally within `min_target_distance` of
the current position, skipping straight to it. `max_target_distance` is that check's
height (z) tolerance, as in the original sample.

### Partial paths

If a path can't reach the requested destination but gets as close as the navmesh allows,
that's `PathStatus.PARTIAL`, not an error — `path.actual_end_position` is where it
actually arrives, `path.requested_end_position` is what you asked for. Callers decide
what "close enough" means for their use case. `PARTIAL` also covers a search that ran out
of nodes before reaching a reachable destination (see [Long routes](#long-routes)).

`PathStatus.BUFFER_FULL` means a result outgrew its buffer (`max_polys`,
`max_straight_path_points`, `max_visited`, ...): the result holds as much as fit, from
the start. A `Path` with that status is still usable (`is_valid()` is true): steering
follows its corridor, but not past its end.

### Query filters

`QueryFilter` wraps `dtQueryFilter` — include/exclude flags and per-area costs, passed to
any `NavigationQuery` method that takes `filter=`:

```python
f = wn.QueryFilter()
f.exclude_flags = 0x08  # never cross water (TrinityCore's flag value)
f.set_area_cost(1, 2.5)  # make ground (area 1) 2.5 times as expensive to cross
corridor = nm.query.find_polygon_path(start, end, filter=f)
```

Flag and area values are whatever your core's mmap generator wrote, not something Detour
defines. TrinityCore's 3.3.5 mmaps use flags/area `0x01`/`1` for ground (nearly every
polygon) and `0x08`/`8` for water; check `get_poly()` on your own data before relying on
them. Area ids must be 0 to 63; anything else raises `ValueError`.

### Move along surface, raycast, closest point, wall distance

```python
moved = nm.query.move_along_surface(current, desired, start_poly=nearest.poly_ref)
hit = nm.query.raycast(start, end)              # Detour's navmesh-surface raycast
pt = nm.query.closest_point_on_poly(poly_ref, position)
wall = nm.query.find_distance_to_wall(position, max_radius=10.0)
```

`move_along_surface()` snaps the height of the position it returns onto the navmesh
surface. Detour's own call doesn't: it keeps the height you asked to move to.
`raycast()` results carry a `status`: check it before trusting `hit`, since a ray that
never started (`START_NOT_FOUND`, or `QUERY_FAILED` for a bad `start_poly`) also has
`hit == False`.

## World Navigation / NavMesh Introspection

Beyond pathfinding, `NavigationQuery` exposes the raw structural data behind the
navmesh — polygons, tiles, and off-mesh connections — so Python can inspect the world
without touching Detour directly. This is deliberately **raw NavMesh data**: `area`,
`flags`, and geometry don't by themselves mean "road", "water", "building", or "city".
Building that kind of semantic classification on top (e.g. a `WorldAnalyzer`) is a job
for a separate layer — this library only guarantees the data is there to build one from.

### Inspecting a polygon

```python
nearest = nm.query.find_nearest_poly(position)
poly = nm.query.get_poly(nearest.poly_ref)

if poly:
    print(poly.type)       # PolyType.GROUND or PolyType.OFFMESH_CONNECTION
    print(poly.area)
    print(poly.flags)
    print(poly.center)     # vertex centroid, WoW (x, y, z)
    print(poly.vertices)   # list[(x, y, z)]
    print(poly.neighbors)  # list[PolyRef] reachable across this poly's edges
```

`get_poly()` returns `None` — never raises — for `0` or a garbage `dtPolyRef`. A ref from
a map generation that's since been reloaded or freed is different: the query object itself
is stale, so any call on it raises `RuntimeError` (see
[Map lifecycle](#map-lifecycle)). In `poly.neighbors` a ref can repeat: a neighbour
across several segments of a tile border has one link per segment.

### Inspecting tiles

```python
for tile in nm.get_loaded_tiles():
    print(tile.x, tile.y, tile.poly_count, tile.uses_liquids)
```

`tile.uses_liquids` is TrinityCore/AzerothCore's own per-tile mmap flag (from
`MmapTileHeader`, not part of Detour itself) — it describes the tile's liquid handling,
**not** a per-polygon `poly.is_water`.

Fetching every polygon in a tile in one call avoids per-polygon round trips when
scanning the whole mesh:

```python
for tile in nm.get_loaded_tiles():
    for poly in nm.query.get_tile_polys(tile.x, tile.y, tile.layer):
        print(poly.ref, poly.area, poly.flags)
```

### Off-mesh connections

`dtOffMeshConnection`s (jumps, ferries, teleporters, doors, or any other special
traversal the mmap generator emitted) are exposed as raw data — no semantics attached:

```python
for conn in nm.query.get_offmesh_connections():
    print(conn.start, conn.end, conn.radius, conn.bidirectional)

# Or scoped to one tile:
connections = nm.query.get_offmesh_connections(tile.x, tile.y, tile.layer)
```

Pass both `tile_x` and `tile_y` or neither — passing only one raises `ValueError` rather
than quietly falling back to every tile.

See [Limitations](#limitations) — TrinityCore/AzerothCore's mmap generator doesn't
currently emit any, so this is untested against real data.

### Sampling an area

`sample_polys()` finds every polygon within a box around a point, using Detour's own
BV-tree-accelerated `queryPolygons` rather than a linear scan over the mesh:

```python
nearby = nm.query.sample_polys(position, radius=30.0)
for poly in nearby:
    print(poly.area, poly.flags, poly.center)
```

The `radius` bounds an axis-aligned box, not an exact circle — polygons slightly beyond
`radius` at the corners of that box can be included.

If more than `max_polys` polygons fall in range (default: `config.max_path_polys`),
`sample_polys()` raises `RuntimeError` instead of returning an arbitrary subset — raise
`max_polys` or shrink `radius`.

### `PolyRef`

A `dtPolyRef` is a plain Python `int` everywhere in this API — 64-bit under the
`DT_POLYREF64` build this project uses by default for TrinityCore/AzerothCore mmaps (see
below), 32-bit if built with `WOW_NAVMESH_POLYREF64=OFF`. Never assume a fixed width;
treat it as an opaque handle.

### Thread safety

One `NavigationQuery` (and the `dtNavMeshQuery` behind it) belongs to one `NavMesh`
instance and is **not** safe to use concurrently from multiple threads — Detour's query
object carries mutable search state internally. If you need to path-find from multiple
threads, use a separate `NavMesh` instance per thread (they can point at the same
`mmaps_path` and `load_map()` the same map id independently; tile data is read-only once
loaded).

### Map lifecycle

`load_map()` can be called again at any time to switch maps (it frees whatever was
loaded first), and `free_map()`/the context manager both release cleanly. Any
`NavigationQuery` or `Path` obtained *before* a `load_map()`/`free_map()` call becomes
stale the moment that call happens — using it afterwards raises `RuntimeError` rather
than touching the (by then freed and possibly reallocated) navmesh data:

```python
q = nm.query
nm.load_map(1)   # switches map
q.find_nearest_poly(pos)  # RuntimeError: stale NavigationQuery
```

Get a fresh `nm.query` (and re-run `find_path()`) after any reload.

### Limitations

- Off-mesh connections are recognized in straight paths and steering targets
  (`DT_STRAIGHTPATH_OFFMESH_CONNECTION` / `SteerTarget.off_mesh`), but this library
  doesn't move an agent across one — that decision belongs to a caller-owned movement
  layer, same as every other steering step. In practice this path is effectively
  untested: TrinityCore/AzerothCore's mmap generator doesn't emit off-mesh connections at
  all (verified: 0 across every tile on both Eastern Kingdoms and Kalimdor), so there's
  nothing in real WoW mmap data to exercise it against.
- No agent-radius/height reshaping: Detour queries the navmesh as it was generated. A
  different agent size requires a differently generated navmesh, not a runtime parameter.
- This is navigation-only: no bot AI, click-to-move, keyboard input, character movement,
  or combat logic. It answers "where is the next useful point on the navmesh," never
  "move the character there."
- No WoW-specific semantics: `area`/`flags` are raw NavMesh data. Classifying them as
  "road", "water", "building", etc. is intentionally left to a layer built on top.
- Only load mmaps you trust. `load_map()` checks each tile's header and size, but Detour
  doesn't validate what's inside a tile, so a crafted file can crash the process.

## API

- `NavMesh(mmaps_path: str | os.PathLike, max_nodes: int = 2048)` — bind to a directory
  of `.mmap`/`.mmtile` files. `max_nodes` sizes the search node pool (see
  [Long routes](#long-routes)).
- `.load_map(map_id: int)` — load the navmesh for a map id, replacing any map currently
  loaded. Raises `RuntimeError` if the files are missing, truncated, or were built for a
  different `dtPolyRef` layout than this build targets (see below).
- `.free_map()` — release the currently loaded map.
- `.find_path(start, end, max_points=256, waypoint_distance=None, search_extent=50.0, centered=False) -> PathResult`
  — the straight path between two points (`points`, `path_type`, `actual_end`).
  - `waypoint_distance` (optional): if set, subdivides the path to maintain max distance
    between waypoints (useful for smooth bot navigation).
  - `search_extent` (default 50.0): search radius for finding the nearest polygon on the
    navmesh. Increase for looser matching, decrease for tighter precision.
  - `centered` (default False): route through polygon edge midpoints, away from walls.
  - Raises `RuntimeError` if no map is loaded, `ValueError` if arguments are invalid.
- `.is_loaded`, `.map_id`, `.mmaps_path` — read-only properties.
- `.query -> NavigationQuery` — bound to the currently loaded map. Raises `RuntimeError`
  if no map is loaded.
- `.query_config: NavMeshQueryConfig` — defaults (`nearest_poly_extents` in `(x, y, z)`
  order, `max_path_polys`, `max_straight_path_points`) used by `NavigationQuery` methods
  that aren't given an explicit override.
- `.get_loaded_tiles() -> list[TileInfo]` — every currently loaded tile. Raises
  `RuntimeError` if no map is loaded.

`NavigationQuery` methods (see [Architecture](#architecture) above for the full picture):

- `.find_nearest_poly(position, extents=None, filter=None) -> NearestPolyResult`
- `.find_polygon_path(start, end, filter=None, max_polys=None) -> PolygonPathResult`
- `.find_straight_path(start, end, polygons, max_points=None) -> StraightPathResult`
- `.move_along_surface(current, desired, start_poly, filter=None, max_visited=None) -> MoveAlongSurfaceResult`
- `.raycast(start, end, start_poly=None, filter=None, max_path=None) -> RaycastResult`
- `.closest_point_on_poly(poly_ref, position) -> (x, y, z)`
- `.closest_point_on_poly_boundary(poly_ref, position) -> (x, y, z)`
- `.get_poly_height(poly_ref, position) -> float`
- `.find_distance_to_wall(position, start_poly=None, max_radius=10.0, filter=None) -> WallDistanceResult`
- `.find_path(start, end, filter=None, max_polys=None) -> Path`
- `.get_poly(poly_ref) -> PolyInfo | None`
- `.get_tile_info(poly_ref) -> TileInfo | None`
- `.get_tile_polys(tile_x, tile_y, tile_layer=0) -> list[PolyInfo]`
- `.get_offmesh_connections(tile_x=None, tile_y=None, tile_layer=0) -> list[OffMeshConnection]`
- `.sample_polys(center, radius, filter=None, max_polys=None) -> list[PolyInfo]`
- `.config: NavMeshQueryConfig`

`Path` methods/properties: `.is_valid()`, `.is_complete()`, `.status`,
`.start_position`, `.requested_end_position`, `.actual_end_position`, `.start_poly`,
`.end_poly`, `.polygon_corridor`, `.straight_path`,
`.get_steer_target(current, min_target_distance=0.5, max_target_distance=6.0) -> SteerTarget | None`.

Full type stubs with docstrings ship with the package (`py.typed`), and every function
has a docstring available through `help()`.

## A note on `DT_POLYREF64`

TrinityCore/AzerothCore build their mmap generator with Detour's `DT_POLYREF64` option
enabled, which widens `dtPolyRef` from 32 to 64 bits. That changes the on-disk byte
layout of every tile (`dtLink`, which embeds a `dtPolyRef`, changes size — and every
section of a tile after it shifts as a result). Published wheels are built with
`DT_POLYREF64` on, matching TrinityCore/AzerothCore's own tools; `load_map()` checks
each tile's layout against what it expects and raises a clear `RuntimeError` (naming the
mismatch) rather than silently misreading a tile built the other way.

Building from source against a plain Detour navmesh (not TrinityCore/AzerothCore's)?
Set `WOW_NAVMESH_POLYREF64=OFF` before installing:

```powershell
$env:WOW_NAVMESH_POLYREF64 = "OFF"
pip install --no-binary wow-navmesh wow-navmesh
```

wow-navmesh only supports 64-bit Windows Python interpreters; 32-bit builds and
non-Windows platforms are rejected at configure time.

## Building from source

You only need this to hack on wow-navmesh itself, or to build with
`WOW_NAVMESH_POLYREF64=OFF`. Requirements:

- Windows, 64-bit CPython 3.10–3.15.
- A C++ compiler with MSVC support — the
  [Visual Studio Build Tools](https://visualstudio.microsoft.com/downloads/) (or full
  Visual Studio) "Desktop development with C++" workload. CMake and Ninja are pulled in
  automatically by `pip` and don't need to be installed separately.

```powershell
git clone --recursive https://github.com/srounet/wow-navmesh
cd wow-navmesh
pip install .
```

The `--recursive` clone (or a `git submodule update --init --recursive` afterwards) is
required — Detour's sources are vendored as a git submodule under
`extern/recastnavigation/`, pinned to upstream tag `v1.6.0`.

Run the tests with `pip install pytest nanobind && pytest`. Most of them run against a
small synthetic navmesh tile the tests write themselves, so they need no game data;
`tests/test_stubs.py` checks the type stubs against the compiled module (it needs
`nanobind`, and is skipped without it). A further tier runs against a real mmaps
directory; point `WOW_NAVMESH_TEST_MMAPS` at one to enable it:

```powershell
$env:WOW_NAVMESH_TEST_MMAPS = "C:\path\to\mmaps"
pytest
```

## Known limitations

- Only verified against TrinityCore/AzerothCore mmaps for WoW 3.3.5a. The mmap format
  may differ across core versions or forks; nothing here has been tested against those.
- `NavMesh.find_path()`'s internal path-buffer size (512 polygons) is fixed; a longer
  route comes back `PARTIAL`. `nm.query.find_path()` (with `max_polys` or
  `nm.query_config.max_path_polys`) is configurable.

## Contributing

Bug reports and pull requests are welcome on
[GitHub](https://github.com/srounet/wow-navmesh/issues). For a pull request:

1. Build an editable install (see [Building from source](#building-from-source)):
   `pip install -e . --no-build-isolation` (needs `scikit-build-core` and `nanobind`
   installed first).
2. Run `pytest`, ideally with `WOW_NAVMESH_TEST_MMAPS` pointing at real mmaps.
   CI runs every test that needs no game data, including the synthetic-tile ones.
3. Keep the documentation in sync: C++ comments follow the
   [Google C++ style](https://google.github.io/styleguide/cppguide.html#Comments),
   Python docstrings the
   [Google Python style](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings).
   The type stubs in `src/wow_navmesh/__init__.pyi` and the docstrings in
   `src/bindings.cpp` are maintained by hand and must match; `tests/test_stubs.py`
   fails when they don't.
4. Add an entry to `CHANGELOG.md`.

All of the C++ code lives in `src/bindings.cpp`. Detour itself is an unmodified git
submodule under `extern/recastnavigation/`; fixes to Detour belong upstream.

## License

wow-navmesh is released under the [MIT License](LICENSE).

It builds on third-party software, and prebuilt wheels include it compiled in:

- [recastnavigation](https://github.com/recastnavigation/recastnavigation) (Detour),
  by Mikko Mononen and contributors. zlib license.
- [nanobind](https://github.com/wjakob/nanobind), by Wenzel Jakob. BSD-3-Clause
  license. It bundles [tsl::robin_map](https://github.com/Tessil/robin-map) (MIT).

Their full license texts are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md), which
is also shipped inside every wheel and sdist.

World of Warcraft is a trademark of Blizzard Entertainment, Inc. This project is not
affiliated with or endorsed by Blizzard Entertainment, TrinityCore, or AzerothCore.
