---
name: pathforge-setup
description: Integrates PathForge (native, deterministic pathfinding for Unity 6) into the open Unity project. Finds the installed package, verifies the native plugin, picks the graph adapter for the project's map (Grid, Tilemap, Hex, Waypoint, Mesh, NavMesh or a custom graph), writes the solver code, runs one route and verifies it, wires dynamic-map toggles, and (with PathForge Pro) shared fields for crowds. Use when the user asks to add PathForge, set up pathfinding, route units or agents, or mentions DnskSolver, QueryPath, GridGraphBuilder or a graph adapter.
license: Proprietary. See LICENSE.md in the PathForge package (Unity Asset Store EULA).
compatibility: Unity 6000.0 or later. Works with any coding agent that can read project files and edit C#. Unity Editor APIs run on the main thread only.
metadata:
  author: Birdblu GmbH
  product: PathForge 1.1.0 (com.birdblu.pathforge)
  docs: https://birdblu.com/pathforge/docs/
---

# PathForge setup skill

You are integrating PathForge into the Unity project that is open in this workspace. Work in this
order and verify each step before the next. Report what you did at the end (step 9).

PathForge is a **route engine, not a movement controller**: it answers "which way?" (a path or a
next step). Animation, steering and collision stay in the user's code. All Base types live in the
**global namespace** (no `using` for PathForge); the Pro field API lives in `PathForge.Pro`.

## 1. Preflight

1. Unity version: read `ProjectSettings/ProjectVersion.txt`; `m_EditorVersion` must be `6000.0` or later.
2. Locate the package (either layout is valid):
   - UPM: `Packages/com.birdblu.pathforge/package.json` exists, or `Packages/manifest.json` lists `com.birdblu.pathforge`.
   - Assets import (older Asset Store workflow): a `package.json` with `"name": "com.birdblu.pathforge"` somewhere under `Assets/`.
   If neither exists, stop and tell the user: install PathForge from the Package Manager (My Assets),
   then run this skill again.
3. Pro: the same check for `com.birdblu.pathforge.pro`. If present, the shared-field API (step 7) is available.
4. Read the version from `package.json`. This skill describes 1.1.0; for older versions read the
   package's `CHANGELOG.md` first (1.0.0 has no dynamic maps and accepts edge weight 0).

## 2. Verify the native plugin

PathForge loads a native library (`dnsk_ffi`; Pro adds `dnsk_ffi_pro`). Add this temporary
component to any GameObject, enter Play mode once, read the Console, then delete the component:

```csharp
using UnityEngine;

public class PathForgeProbe : MonoBehaviour
{
    void Start()
    {
        Debug.Log(DnskNative.Available
            ? "PathForge native plugin OK"
            : "PathForge native plugin NOT loaded: " + DnskNative.LoadError + "\n" + DnskNative.Diagnose());
    }
}
```

If it is not loaded, read [Troubleshooting](https://birdblu.com/pathforge/docs/Troubleshooting.html) (plugin importer settings,
CPU architecture, editor restart after a plugin update) before writing any other code.

## 3. Pick the graph adapter

Every adapter implements `IGraphSource`; vertex ids are `0 .. NumVertices-1`.

| The project navigates on | Adapter | Vertex id | World position |
|---|---|---|---|
| Unity `Grid` + `Tilemap`, **tile = obstacle** | `GridGraphBuilder(grid, tilemap, cols, rows[, diagonal[, dynamicCell]])` | `x + y * cols` | `builder.VertexToWorld(v)` (cell centre) |
| Unity `Tilemap`, **tile = walkable**, per-tile cost | `TilemapGraphBuilder(tilemap[, bounds, diagonal[, dynamicCell]])` + `SetTileWeight(tile, w)` | cell order of the bounds | `builder.VertexToWorld(v)` |
| Hex board (pointy-top, odd-row offset) | `HexGraphBuilder(cols, rows, blocked[, dynamicCell], cellWidth, rowHeight)` | `x + y * cols` | `builder.HexToWorld(v)` |
| Waypoints (`Transform[]`) | `WaypointGraphBuilder(waypoints[, connectionDistance])` | array index | `builder.VertexToWorld(v)` |
| Triangle `Mesh` (walk on the surface) | `MeshGraphBuilder(mesh[, triangleBlocked])` | triangle index | `builder.TriangleCentroid(v)` (mesh-local) |
| Baked Unity NavMesh | `NavMeshGraphBuilder([areaBlocked])` | triangle index | `builder.TriangleCentroid(v)` (world) |
| Anything else | implement `IGraphSource` ([Bring Your Graph](https://birdblu.com/pathforge/docs/BringYourGraph.html)) | yours | yours |

Rules every adapter obeys: each undirected connection is two directed edges; edge weights are
integers `1 .. 536 870 912` (`DnskSolver.MaxEdgeWeight`); weight 0 is rejected. `diagonal: true`
means 8-connectivity with costs 10 (straight) and 14 (diagonal), corner cutting guarded.

## 4. Write the integration

Template for a Grid/Tilemap map (adapt the builder line for other adapters). Keep the solver for
the life of the map, reuse the path buffer, dispose in `OnDestroy`.

```csharp
using UnityEngine;
using UnityEngine.Tilemaps;

public class PathForgeRouter : MonoBehaviour
{
    [SerializeField] Grid grid;
    [SerializeField] Tilemap obstacles;     // GridGraphBuilder: tile present = blocked
    [SerializeField] uint cols = 20, rows = 15;

    DnskSolver solver;
    GridGraphBuilder builder;
    readonly uint[] pathBuffer = new uint[1024];   // allocate once; QueryPath allocates nothing

    void Awake()
    {
        builder = new GridGraphBuilder(grid, obstacles, cols, rows);
        solver = new DnskSolver(builder.NumVertices);
        solver.BuildFrom(builder, HeuristicMode.Landmarks);   // once per map
    }

    public uint VertexAt(Vector3 world)
    {
        var c = grid.WorldToCell(world);
        return (uint)c.x + (uint)c.y * cols;
    }

    public bool Route(uint from, uint to, out int length, out uint cost)
    {
        PathResult r = solver.QueryPath(from, to, pathBuffer);  // pathBuffer[0..r.PathLength-1] = vertex ids
        length = r.PathLength; cost = r.Distance;
        return r.Reachable;
    }

    public Vector3 WorldOf(uint v) => builder.VertexToWorld(v);

    void OnDestroy() => solver?.Dispose();
}
```

Notes: `Build`/`BuildFrom` once per solver; a new vertex set needs a new solver. Unity engine APIs
(Grid, Tilemap, NavMesh) are main-thread only; call PathForge from the main thread as well unless
the user has an explicit threading design. For a static map that is built at startup, offer
`SaveGraph()` at build time and `LoadGraph(bytes)` at runtime (see [API Reference](https://birdblu.com/pathforge/docs/API-Reference.html)).

## 5. Verify one route

Pick two walkable vertices, call `Route`, and log `Reachable`, `PathLength`, `Distance`; draw the
buffer with `Debug.DrawLine` between `WorldOf(pathBuffer[i])` and `WorldOf(pathBuffer[i+1])`.
`Reachable == false` with `Distance == uint.MaxValue` means no connection, not an error. If the path
looks offset by half a cell, the project uses `CellToWorld` (corner) where `GetCellCenterWorld`
(centre) is meant.

## 6. Dynamic maps (doors, destroyed walls, flooded roads) — no rebuild

- Cells that can change at runtime: pass a `dynamicCell(x, y) => true` predicate to
  `GridGraphBuilder`/`TilemapGraphBuilder`/`HexGraphBuilder`, build, then once
  `builder.ApplyDynamicCells(solver)`. After each change of such a cell call
  `builder.RefreshCell(solver, x, y)`. Non-dynamic cells must not change after the build.
- Direct edits: `solver.BlockVertex(v)` / `UnblockVertex(v)` (all edges of a vertex),
  `solver.CloseEdge(a, b)` (one direction), `solver.SetEdgeWeight(a, b, w)` (raise a cost; reopen a
  closed edge). The rule: a weight may be raised and lowered back to its build-time value, never
  below it; a lower cost means rebuilding with that cost as the base.
- `solver.GraphVersion` increases with every effective change; use it as the cache key for anything
  derived from the graph. Pro fields computed before a change report "field is stale": recompute.

## 7. Shared fields for crowds (PathForge Pro only)

Only when `com.birdblu.pathforge.pro` is installed (step 1.3). On a Base-only project these calls
throw `DnskProRequiredException`; do not write them then.

```csharp
using PathForge.Pro;

var field = solver.CreateField();                 // shares the solver's native memory, no Dispose
var distances = new uint[builder.NumVertices];
field.ComputeField(targetVertex, distances);       // once per target (or per map change)

// per frame, all agents in one native call:
int valid = field.BatchNextStep(agentVertices, nextOut, terminalOut);
// or per agent: FieldStep s = field.NextStep(v); s.NextVertex, s.IsTerminal
```

Many targets: `ComputeWeightedField(targets, costs, distances, roots)`; partial floods:
`ComputeFieldWatched`. The Pro package ships six field scenes (Package Manager → PathForge Pro →
Samples → "PathForge Pro Samples"); they use the sample kit that Base installs.

## 8. Pitfalls to check before handing back

- `GridGraphBuilder`: tile present = **blocked**. `TilemapGraphBuilder`: tile present = **walkable**.
- Edge weights `1 .. 536 870 912`; `AddEdges`/`BuildFrom` reject the whole batch otherwise, with a message naming the rule.
- One `DnskSolver` per map, disposed in `OnDestroy`; never allocate the path buffer inside `Update`.
- `pathBuffer` too small truncates the path silently; size it for the longest route you expect.
- Mono and IL2CPP both work; platforms: Windows x64, macOS 11+ (Intel, Apple Silicon), Linux x64/ARM64, Android ARM64. No WebGL, no iOS.
- Samples: Package Manager → PathForge → Samples → "PathForge Samples" (QuickStart, Benchmark, Determinism, Graph Gallery, Base Demo).

## 9. Hand back

Tell the user: which adapter you chose and why, the files you added or changed, the result of the
route check (reachable, length, cost), whether dynamic cells and (Pro) fields are wired, and any
pitfall from step 8 that applies to their project. Point to [Getting Started](https://birdblu.com/pathforge/docs/GettingStarted.html),
[API Reference](https://birdblu.com/pathforge/docs/API-Reference.html), [FAQ](https://birdblu.com/pathforge/docs/FAQ.html) and [Troubleshooting](https://birdblu.com/pathforge/docs/Troubleshooting.html)
(online: https://birdblu.com/pathforge/docs/).
