Metadata-Version: 2.1
Name: wow-navmesh
Version: 1.0.0
Summary: Python bindings for Detour (recastnavigation) navmesh pathfinding over TrinityCore/AzerothCore mmaps
Keywords: recastnavigation,detour,navmesh,pathfinding,trinitycore,azerothcore,wow
Author: srounet
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: 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.

## Install

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

Prebuilt wheels are published for 64-bit CPython 3.10–3.13 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

path = nm.find_path((x1, y1, z1), (x2, y2, z2))
for x, y, z in path:
    print(x, y, z)
```

### 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 radius for finding polygons on the navmesh (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)
```

`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. The
`.mmap`/`.mmtile` files store them as `(y, z, x)`; the swap happens internally (in one
centralized helper used by every query function), so callers never need to think about it.

## 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(_area|_flags|_type|_center|_vertices|_neighbors),
              get_tile_info, get_tile_polys, get_offmesh_connections, sample_polys
```

`NavMesh.find_path()` (the original, flat API) still works exactly as before, built on
top of this stack — nothing here is a breaking change. New 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
nearest = nm.query.find_nearest_poly((x, y, z), extents=(50, 50, 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)
```

`polygon_path` is the raw Detour polygon chain — no points yet, just `dtPolyRef`s.
`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 = start
while not path.is_complete():
    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 `position` actually changes, e.g.:
    #   moved = nm.query.move_along_surface(position, steer.position, path.start_poly)
    #   position = moved.position
```

`get_steer_target()` ports the same algorithm AzerothCore's `PathGenerator::GetSteerTarget`
uses (itself derived from Detour's own `NavMeshTesterTool` sample): it walks the straight
path looking for the first corner not already within `min_target_distance` of the current
position, skipping straight to it. `max_target_distance` bounds vertical (y) drift the
same way the original sample's height tolerance did.

### 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.

### 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 = 0x01  # exclude polygons flagged, e.g., "water"
f.set_area_cost(3, 2.5)  # make area 3 twice as expensive to cross
corridor = nm.query.find_polygon_path(start, end, filter=f)
```

### 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)
```

## 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)). Lean single-field wrappers avoid building the whole
`PolyInfo` when only one value is needed:

```python
area = nm.query.get_poly_area(poly_ref)        # int | None
flags = nm.query.get_poly_flags(poly_ref)      # int | None
kind = nm.query.get_poly_type(poly_ref)        # PolyType | None
center = nm.query.get_poly_center(poly_ref)    # (x, y, z) | None
verts = nm.query.get_poly_vertices(poly_ref)   # list[(x, y, z)], [] if invalid
neighbors = nm.query.get_poly_neighbors(poly_ref)  # list[PolyRef], [] if invalid
# (a ref can repeat — a neighbour across several segments of a tile border has one link each)
```

### 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.

## API

- `NavMesh(mmaps_path: str)` — bind to a directory of `.mmap`/`.mmtile` files.
- `.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) -> list[(x, y, z)]`
  — the straight path between two points, or `[]` if none was found.
  - `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.
  - 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`,
  `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, filter=None, 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_poly_type(poly_ref) -> PolyType | None`
- `.get_poly_area(poly_ref) -> int | None`
- `.get_poly_flags(poly_ref) -> int | None`
- `.get_poly_center(poly_ref) -> (x, y, z) | None`
- `.get_poly_vertices(poly_ref) -> list[(x, y, z)]`
- `.get_poly_neighbors(poly_ref) -> list[PolyRef]`
- `.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 ship with the package (`py.typed`).

## 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

Requirements:

- Windows, 64-bit CPython 3.10–3.13.
- 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 && pytest`. A second tier of tests exercises
`find_path()` and the `NavigationQuery`/`Path` API 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 still fixed, for
  backward compatibility with its original signature. `nm.query.find_path()` (or
  `nm.query_config.max_path_polys`) is configurable and should be preferred for new code.
- License: TBD (recastnavigation/Detour itself is zlib-licensed; its notice is included
  under `extern/recastnavigation/`).

## Acknowledgments

- [recastnavigation](https://github.com/recastnavigation/recastnavigation) by Mikko
  Mononen and contributors.
- [nanobind](https://github.com/wjakob/nanobind) by Wenzel Jakob.
