Recursive AI

Save and restore a pathfinding grid in C#

OnePath is a free, open-source pathfinding library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

This saves the map, not a search in progress. To keep an unfinished search, see Resume a search across ticks. Here . is open, 2 is area 2, and # is a wall.

Terminal
dotnet add package RecursiveAI.OnePath

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OnePath;
 
var map = Grid.FromText(".2.\n.#.");
map.Areas[2] = 5; // 5 per step within area 2
byte[] state = map.SaveState();
var copy = Grid.FromState(state);
Console.WriteLine(
    $"{copy.Width} x {copy.Height}");
Console.WriteLine(copy.Areas[2]);
Text
3 x 2
5

Unzip the example, then dotnet run.

The full program

The program saves the 3×2 grid to a byte array, reads it into a new grid, and prints the restored cells and terrain cost. Then it removes the last byte and tries to restore that incomplete snapshot.

C#
using RecursiveAI.OnePath;
 
var map = Grid.FromText(".2.\n.#.");
map.Areas[2] = 5;
byte[] state = map.SaveState();
var restored = Grid.FromState(state);
Console.WriteLine($"Dimensions: {restored.Width} x {restored.Height}");
Console.WriteLine($"Cell (1,0): area {restored.GetArea(1, 0)}");
Console.WriteLine($"Cell (1,1): area {restored.GetArea(1, 1)}");
Console.WriteLine($"Area 2 multiplier: {restored.Areas[2]}");
Console.WriteLine($"Same bytes: {state.SequenceEqual(restored.SaveState())}");
 
// Simulate an incomplete save by dropping the last byte.
try
{
    restored.RestoreState(state.AsSpan(0, state.Length - 1));
    throw new InvalidOperationException("Accepted a truncated snapshot.");
}
catch (GridStateException error)
{
    Console.WriteLine($"Rejected: {error.GetType().Name}");
}
Console.WriteLine($"Grid unchanged: {state.SequenceEqual(restored.SaveState())}");

dotnet run prints:

Text
Dimensions: 3 x 2
Cell (1,0): area 2
Cell (1,1): area 255
Area 2 multiplier: 5
Same bytes: True
Rejected: GridStateException
Grid unchanged: True

Area 255 means a wall (AreaCosts.Wall). If the data is truncated, RestoreState throws GridStateException and leaves the existing Grid unchanged.

Variations

Restore into the original grid. Append this to the snippet at the top to undo a wall edit. The original cell is area 2 again.

C#
map.SetArea(1, 0, AreaCosts.Wall);
map.RestoreState(state);
Console.WriteLine(map.GetArea(1, 0));
Text
2

The short answer

Call Grid.SaveState() to get a binary snapshot, then pass it to Grid.FromState(bytes) to create a new grid. If you need to keep the same object, use grid.RestoreState(bytes) instead; that grid must already have the saved width and height. This is a snapshot of the map, not an unfinished path query.

What does a serialized pathfinding grid contain?

The grid payload includes its width, height, version, coordinate space, area table, and cells in row order. Keeping the area table matters: the byte 2 in the cell at (1,0) says which area the tile uses, but it doesn’t say that area 2 costs 5. The saved multiplier completes the definition. In the example, restoring and saving again produces the same bytes.

The byte array is the library’s binary format, not JSON and not the text map used to build the example. You can store those bytes as a binary file or in another store that preserves binary values. Clearance and cached indexes aren’t part of the payload; the grid derives them from the restored map.

How do you restore a grid without losing the current map on a bad save?

Catch GridStateException when passing the stored bytes to FromState or RestoreState. The restore contract says that a Grid is unchanged when its restore throws that exception. The truncated snapshot in the example shows this for an in-place restore. That is format validation, not a promise that every possible change to the bytes will be detected. Don’t overlap a restore with queries or edits on the same grid.

A one-shot FindPath keeps no in-progress search to save. If your app uses a sliced search or replanner and must resume it rather than start it again, save that object’s state separately, restore the grid first, and restore the dependent object with the matching options. The snapshot can’t serialize delegate callbacks; your app supplies those again.

All onepath recipes