RynthSuite as of 2026-10-04 (internal c94715f): RynthOracle (based on Oracle of Dereth by Advis Eveldan) and RynthInventory, RynthAi patrol doorways and rooms, healing priority, strict monster priority, finish the wounded target, slayer weapons, arcs when clear, blasts like rings, learn unknown spells, looting fixes, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:29 -04:00
commit 12ca25f911
426 changed files with 108239 additions and 7521 deletions

View file

@ -0,0 +1,217 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthNav;
using RynthNav.Routing;
namespace RynthNav.RouteTests;
// The two live bugs of 10-01: a goto that ran into a portal it didn't want (the steering check),
// and a goto from an island that walked instead of taking a portal or a recall (walks that can't be
// done over land are left out of the plan).
internal static partial class Program
{
private static void RunAvoid()
{
Run(nameof(IslandNeedsAPortal), IslandNeedsAPortal);
Run(nameof(IslandNeedsARecall), IslandNeedsARecall);
Run(nameof(IslandNoWayOut), IslandNoWayOut);
Run(nameof(SteerRoundAPortalInTheWay), SteerRoundAPortalInTheWay);
Run(nameof(GoalBesideAnUnwantedPortal), GoalBesideAnUnwantedPortal);
Run(nameof(StartInsideAPortalCircle), StartInsideAPortalCircle);
Run(nameof(RowOfPortalsNoFlailing), RowOfPortalsNoFlailing);
Run(nameof(AvoidSetAndPolygons), AvoidSetAndPolygons);
Run(nameof(BendStaysOnTheMesh), BendStaysOnTheMesh);
}
// An island north of 60N; everything else is one mainland.
private static bool IslandLand(double ans, double aew, double bns, double bew) => (ans > 60) == (bns > 60);
private static void IslandNeedsAPortal()
{
// On the island (61N), going to 59N on the mainland: 2 degrees of walking (480 u) is far
// cheaper on paper than the island's portal (about 770 u), but it's across water.
var portals = new List<PortalLink>
{
new(62, 47, 59.5, 47.5, "Island Exit"), // island -> mainland
new(42.1, 33.6, 84.1, 47.2, "Aerlinthe Island"), // mainland -> island (no use here)
};
PortalRoute.Plan(portals, null, null, 61, 47, 59, 47, out double naiveEst, out int naiveUsed);
Check(naiveUsed == 0, "without the land check the plan walks straight off the island (the 10-01 bug)");
var steps = PortalRoute.Plan(portals, null, null, 61, 47, 59, 47, out double est, out int used, IslandLand);
Check(used == 1 && steps.Count == 2 && steps[0].UsePortal && steps[0].Label == "Island Exit", "with it: walk to the island's portal and take it");
Check(!double.IsInfinity(est) && est > naiveEst, $"a real plan ({est:F0} vs {naiveEst:F0} straight)");
}
private static void IslandNeedsARecall()
{
var recalls = new List<RecallLink> { new(42.1, 33.6, "Lifestone Recall", PortalRoute.RecallCostUnits(5)) };
var steps = PortalRoute.Plan(NoPortals, recalls, null, 61, 47, 59, 47, out _, out int used, IslandLand);
Check(used == 1 && steps.Count == 2 && steps[0].UseRecall && steps[0].Label == "Lifestone Recall", "no portal off the island: the recall, then walk");
// On the mainland, the same goto doesn't need it.
PortalRoute.Plan(NoPortals, recalls, null, 41, 32, 40, 30, out _, out used, IslandLand);
Check(used == 0, "on the mainland it walks");
}
private static void IslandNoWayOut()
{
var steps = PortalRoute.Plan(NoPortals, null, null, 61, 47, 59, 47, out double est, out int used, IslandLand);
Check(steps.Count == 0 && used == 0 && double.IsPositiveInfinity(est), "no portal and no recall: no plan at all (the goto stops and says why)");
// A portal whose entrance can't be walked to doesn't help either.
var portals = new List<PortalLink> { new(42.1, 33.6, 58.9, 47.1, "Mainland Portal") };
PortalRoute.Plan(portals, null, null, 61, 47, 59, 47, out est, out used, IslandLand);
Check(used == 0 && double.IsPositiveInfinity(est), "a portal on the other landmass isn't reachable");
}
// ── Steering round portals: ideal movement, 0.35 u a tick ─────────────────
private static (double MinDist, bool Arrived, int Ticks) WalkWithAvoid(PortalAvoid avoid, double x, double y, double gx, double gy,
double px, double py, double arrive = 7.0, int maxTicks = 2000)
{
double minDist = double.MaxValue;
for (int t = 0; t < maxTicks; t++)
{
minDist = Math.Min(minDist, Math.Sqrt((x - px) * (x - px) + (y - py) * (y - py)));
double dg = Math.Sqrt((gx - x) * (gx - x) + (gy - y) * (gy - y));
if (dg < arrive) return (minDist, true, t);
double want = Math.Atan2(gx - x, gy - y) * 180.0 / Math.PI;
if (want < 0) want += 360;
double h = avoid.Steer(x, y, want, Math.Min(10.0, dg + 2.0), out _) * Math.PI / 180.0;
x += Math.Sin(h) * 0.35; y += Math.Cos(h) * 0.35;
}
return (minDist, false, maxTicks);
}
private static void SteerRoundAPortalInTheWay()
{
var avoid = new PortalAvoid();
avoid.Set(new[] { new PortalAvoid.Spot(100, 120, PortalAvoid.LiveRadius, "Aerlinthe Island") }, Array.Empty<PortalAvoid.Spot>());
// Straight north from (100, 100) to (100, 160): the portal sits right on the line.
var r = WalkWithAvoid(avoid, 100, 100, 100, 160, 100, 120);
Check(r.Arrived, "it still gets there");
Check(r.MinDist >= PortalAvoid.LiveRadius - 0.05, $"never inside the portal's circle (closest {r.MinDist:F2} u)");
// Without the portal in the set it walks straight through that spot.
var none = new PortalAvoid();
var r0 = WalkWithAvoid(none, 100, 100, 100, 160, 100, 120);
Check(r0.MinDist < 0.5, "with no portal known it would have walked through it");
// A portal off to the side isn't steered round.
double h = avoid.Steer(90, 100, 0, 10, out int spot);
Check(spot < 0 && h == 0, "a portal 10 u to the side: the heading is kept");
}
private static void GoalBesideAnUnwantedPortal()
{
var avoid = new PortalAvoid();
avoid.Set(new[] { new PortalAvoid.Spot(100, 150, PortalAvoid.LiveRadius, "Unwanted") }, Array.Empty<PortalAvoid.Spot>());
// The goal is 1 u from the portal, approached head on through it.
var r = WalkWithAvoid(avoid, 100, 100, 100, 151, 100, 150);
Check(r.Arrived, "arrives (within 7 u of the goal)");
Check(r.MinDist >= PortalAvoid.LiveRadius - 0.05, $"without stepping into the portal (closest {r.MinDist:F2} u)");
// From the far side too.
r = WalkWithAvoid(avoid, 100, 200, 100, 151, 100, 150);
Check(r.Arrived && r.MinDist >= PortalAvoid.LiveRadius - 0.05, $"from the other side too (closest {r.MinDist:F2} u)");
// The step's own target portal is never avoided.
var own = new PortalAvoid();
own.Set(new[] { new PortalAvoid.Spot(100, 150, PortalAvoid.LiveRadius, "Target") }, Array.Empty<PortalAvoid.Spot>(), 100, 150, 15);
Check(own.Count == 0, "the step's own portal is left out of the set");
var into = WalkWithAvoid(own, 100, 100, 100, 150, 100, 150, arrive: 0.5);
Check(into.Arrived && into.MinDist < 0.5, "and the walker goes straight into it");
}
private static void StartInsideAPortalCircle()
{
var avoid = new PortalAvoid();
avoid.Set(new[] { new PortalAvoid.Spot(100, 100, PortalAvoid.LiveRadius, "Just landed beside it") }, Array.Empty<PortalAvoid.Spot>());
// Standing 1 u south of a portal, wanting to go north through it.
double h = avoid.Steer(100, 99, 0, 10, out int spot);
Check(spot == 0 && (h > 90 && h < 270), $"inside the circle: heads out of it first, not on through ({h:F0} deg)");
var r = WalkWithAvoid(avoid, 100, 99, 100, 140, 100, 100);
Check(r.Arrived, "then on to the goal");
}
private static void RowOfPortalsNoFlailing()
{
// Holtburg 10-01 19:46: four hub portals in a row ~5 u apart; the lifestone drops you inside
// the row's circles and the goal is beyond it. Get out and round the row without flailing.
var avoid = new PortalAvoid();
var row = new[] { 95.2, 100.0, 104.8, 109.6 };
var spots = new System.Collections.Generic.List<PortalAvoid.Spot>();
foreach (double rx in row) spots.Add(new PortalAvoid.Spot(rx, 100, PortalAvoid.LiveRadius, "hub"));
avoid.Set(spots, Array.Empty<PortalAvoid.Spot>());
double x = 101.5, y = 98.6, gx = 101, gy = 160, last = double.NaN;
int bigFlips = 0; bool arrived = false; double minClear = double.MaxValue; int ticksInside = 0;
for (int t = 0; t < 3000 && !arrived; t++)
{
double dg = Math.Sqrt((gx - x) * (gx - x) + (gy - y) * (gy - y));
if (dg < 7.0) { arrived = true; break; }
double want = Math.Atan2(gx - x, gy - y) * 180.0 / Math.PI; if (want < 0) want += 360;
double h = avoid.Steer(x, y, want, Math.Min(10.0, dg + 2.0), out _);
if (!double.IsNaN(last)) { double dh = Math.Abs(h - last); if (dh > 180) dh = 360 - dh; if (dh > 120) bigFlips++; }
last = h;
bool inside = avoid.Inside(x, y) >= 0;
if (inside) ticksInside++;
else foreach (double rx in row) minClear = Math.Min(minClear, Math.Sqrt((x - rx) * (x - rx) + (y - 100) * (y - 100)) - PortalAvoid.LiveRadius);
double hr = h * Math.PI / 180.0; x += Math.Sin(hr) * 0.35; y += Math.Cos(hr) * 0.35;
}
Check(arrived, "gets round the row to the goal");
Check(bigFlips <= 1, $"no flailing: {bigFlips} heading flips over 120 deg");
Check(ticksInside < 40, $"out of the circles quickly ({ticksInside} ticks inside)");
Check(minClear > -0.05, $"once out, never back into a circle (closest {minClear:F2} u past an edge)");
}
private static void AvoidSetAndPolygons()
{
var avoid = new PortalAvoid();
var live = new[] { new PortalAvoid.Spot(10, 10, PortalAvoid.LiveRadius, "live") };
var map = new[] { new PortalAvoid.Spot(12, 11, PortalAvoid.MapRadius, "the same one from the Atlas"), new PortalAvoid.Spot(50, 50, PortalAvoid.MapRadius, "another") };
avoid.Set(live, map);
Check(avoid.Count == 2 && avoid.Spots[0].R == PortalAvoid.LiveRadius, "a live portal wins over its Atlas entry; others stay");
Check(avoid.Inside(11, 11) == 0 && avoid.Inside(20, 20) == -1, "inside / outside");
// A square 0..20 contains the live portal; a square far away doesn't touch anything.
Check(avoid.Touches(new double[] { 0, 20, 20, 0 }, new double[] { 0, 0, 20, 20 }), "a polygon around a portal touches it");
Check(avoid.Touches(new double[] { 12.0, 30, 30, 12.0 }, new double[] { 0, 0, 30, 30 }), "a polygon 2 u from it touches its circle");
Check(!avoid.Touches(new double[] { 20, 40, 40, 20 }, new double[] { 0, 0, 8, 8 }), "a polygon well clear of both doesn't");
avoid.Clear();
Check(avoid.Count == 0 && avoid.Steer(0, 0, 45, 10, out _) == 45, "no portals: nothing changes");
}
// C9A8, 10-01 21:03: the bend round a housing portal put its corner beside a tree, in the
// navmesh's no-go ring round the trunk; the walker went there and stuck. A corner must now be
// on the mesh and so must both legs to and from it; with no such corner the path is kept.
private static void BendStaysOnTheMesh()
{
var avoid = new PortalAvoid();
avoid.Set(new[] { new PortalAvoid.Spot(50, 0.5, PortalAvoid.LiveRadius, "housing portal") }, Array.Empty<PortalAvoid.Spot>());
var path = new List<(double, double)> { (0, 0), (100, 0) };
// The bend's natural side is south (the path passes south of the portal's centre).
double off = PortalAvoid.LiveRadius + PortalAvoid.SteerMargin + 0.5;
// Open ground: it bends, on the side the path passes.
var open = avoid.Bend(path, (x, y) => true, 12, (ax, ay, bx, by) => true);
Check(open.Count == 3 && open[1].Y < 0, "open ground: one corner, on the near (south) side");
// A tree's no-go ring (2 m; its trunk 1 m south of the corner) covers the south corner: north instead.
bool NoTreeSouth(double x, double y) => Math.Sqrt((x - 50) * (x - 50) + (y + off + 1) * (y + off + 1)) > 2.0;
bool Leg(Func<double, double, bool> mesh, double ax, double ay, double bx, double by)
{
int n = (int)Math.Ceiling(Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay)));
for (int k = 1; k < n; k++) if (!mesh(ax + (bx - ax) * k / n, ay + (by - ay) * k / n)) return false;
return true;
}
var north = avoid.Bend(path, NoTreeSouth, 12, (ax, ay, bx, by) => Leg(NoTreeSouth, ax, ay, bx, by));
Check(north.Count == 3 && north[1].Y > 0, "a tree on the near side: the corner goes on the far side");
// The old test (any navmesh within 1.5 m) took the south corner beside the tree.
bool Near(double x, double y) { for (double dx = -1.5; dx <= 1.5; dx += 0.5) for (double dy = -1.5; dy <= 1.5; dy += 0.5) if (NoTreeSouth(x + dx, y + dy)) return true; return false; }
var old = avoid.Bend(path, Near);
Check(old.Count == 3 && old[1].Y < 0 && !NoTreeSouth(old[1].X, old[1].Y), "(the old 'near the mesh' test put the corner inside the tree's ring)");
// Corners on the mesh on both sides, but each leg to them crosses a no-go area: kept as it was.
bool Walls(double x, double y) => !(Math.Abs(x - 25) < 1 && Math.Abs(y) > 2) && !(Math.Abs(x - 75) < 1 && Math.Abs(y) > 2);
var kept = avoid.Bend(path, Walls, 12, (ax, ay, bx, by) => Leg(Walls, ax, ay, bx, by));
Check(kept.Count == 2 && kept[0] == path[0] && kept[1] == path[1], "no corner with legs on the mesh: the path is kept (steering takes over)");
// Neither side on the mesh at all: kept too.
var none = avoid.Bend(path, (x, y) => Math.Abs(y) < 1, 12, (ax, ay, bx, by) => true);
Check(none.Count == 2, "no corner on the mesh: the path is kept");
}
}

View file

@ -0,0 +1,543 @@
using System;
using System.IO;
using System.Collections.Generic;
using RynthCore.Plugin.RynthNav;
using RynthNav.Routing;
namespace RynthNav.RouteTests;
// Offline tests for RynthNav's travel logic. Self-contained; fails on zero assertions.
// Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
internal static partial class Program
{
private static int _asserts, _fails;
private static void Check(bool cond, string msg)
{
_asserts++;
if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); }
}
private static void Near(double actual, double expected, double tol, string msg)
{
_asserts++;
if (double.IsNaN(actual) || Math.Abs(actual - expected) > tol)
{ _fails++; Console.WriteLine($" [FAIL] {msg}: expected {expected:0.####} ±{tol}, got {actual:0.####}"); }
}
private static int Main()
{
Console.WriteLine("=== RynthNav route tests ===");
Run(nameof(DirectWalkWhenClose), DirectWalkWhenClose);
Run(nameof(OnePortal), OnePortal);
Run(nameof(TwoPortalsChained), TwoPortalsChained);
Run(nameof(RecallBeatsPortal), RecallBeatsPortal);
Run(nameof(SlowRecallLoses), SlowRecallLoses);
Run(nameof(RecallThenPortal), RecallThenPortal);
Run(nameof(RecallCostFromCastTime), RecallCostFromCastTime);
Run(nameof(RecallListFromSpellbookAndMemory), RecallListFromSpellbookAndMemory);
Run(nameof(RecallListColdSpellbook), RecallListColdSpellbook);
Run(nameof(RecallMemoryRoundTrip), RecallMemoryRoundTrip);
Run(nameof(RecallMessages), RecallMessages);
Run(nameof(AtlasSearchAndBestMatch), AtlasSearchAndBestMatch);
Run(nameof(ArrowSingleTarget), ArrowSingleTarget);
Run(nameof(ArrowAlongRoute), ArrowAlongRoute);
Run(nameof(FavoritesAndRecent), FavoritesAndRecent);
Run(nameof(CoordinateParsing), CoordinateParsing);
Run(nameof(BearingAndDistance), BearingAndDistance);
Run(nameof(RealData), RealData);
Run(nameof(NavDataFolder), NavDataFolder);
Run(nameof(DungeonEntrance), DungeonEntrance);
Run(nameof(RouteEndsOnAPortalStep), RouteEndsOnAPortalStep);
Run(nameof(RealDungeonEntrances), RealDungeonEntrances);
RunTownNet();
RunAvoid();
RunTravelPlan();
Console.WriteLine();
Console.WriteLine(_fails == 0 && _asserts > 0
? $"PASS ({_asserts} assertions)"
: $"FAIL ({_fails} of {_asserts} assertions failed)");
return _fails == 0 && _asserts > 0 ? 0 : 1;
}
private static void Run(string name, Action test)
{
int before = _fails;
try { test(); }
catch (Exception ex) { _fails++; _asserts++; Console.WriteLine($" [FAIL] {name} threw {ex.GetType().Name}: {ex.Message}"); }
Console.WriteLine($"{(_fails == before ? "ok " : "FAIL")} {name}");
}
// ── Route planning over small fake portal graphs ─────────────────────────
private static readonly List<PortalLink> NoPortals = new();
private static void DirectWalkWhenClose()
{
var portals = new List<PortalLink> { new(0.5, 0.5, 39.5, 39.5, "Far Portal") };
var steps = PortalRoute.Plan(portals, null, 0, 0, 0.3, 0.2, out double est, out int used);
Check(used == 0, "no teleport for a short walk");
Check(steps.Count == 1 && !steps[0].UsePortal && !steps[0].UseRecall, "one walk leg");
Near(est, NavCoords.Distance(0, 0, 0.3, 0.2), 0.01, "cost is the walk");
}
private static void OnePortal()
{
var portals = new List<PortalLink> { new(0.5, 0.5, 39.5, 39.5, "Far Portal") };
var steps = PortalRoute.Plan(portals, null, 0, 0, 40, 40, out _, out int used);
Check(used == 1, "one portal");
Check(steps.Count == 2, "walk to the portal, walk to the goal");
Check(steps[0].UsePortal && steps[0].Label == "Far Portal", "first leg takes the portal");
Near(steps[0].Ns, 0.5, 1e-9, "first leg ends at the entrance");
Near(steps[0].LandNs, 39.5, 1e-9, "portal step knows where it lands");
Check(!steps[1].UsePortal && !steps[1].UseRecall, "last leg walks");
Near(steps[1].Ns, 40, 1e-9, "last leg ends at the goal");
}
private static void TwoPortalsChained()
{
var portals = new List<PortalLink>
{
new(0.2, 0.2, 20, 20, "First"),
new(20.3, 20.1, 40, 40, "Second"),
new(0.1, -0.1, -40, -40, "Wrong way"),
};
var steps = PortalRoute.Plan(portals, null, 0, 0, 40.2, 40.2, out _, out int used);
Check(used == 2, "two portals");
Check(steps.Count == 3 && steps[0].Label == "First" && steps[1].Label == "Second", "in order");
Check(steps[0].UsePortal && steps[1].UsePortal && !steps[2].UsePortal, "portal, portal, walk");
}
private static void RecallBeatsPortal()
{
var portals = new List<PortalLink> { new(0.7, 0.7, 39.5, 39.5, "Far Portal") };
var recalls = new List<RecallLink> { new(40.1, 40.1, "Quick Recall", PortalRoute.RecallCostUnits(5)) };
var steps = PortalRoute.Plan(portals, recalls, 0, 0, 40, 40, out _, out int used);
Check(used == 1, "one teleport");
Check(steps.Count == 2 && steps[0].UseRecall, "starts with the recall");
Check(steps[0].RecallIndex == 0 && steps[0].Label == "Quick Recall", "recall step names its recall");
Near(steps[0].LandNs, 40.1, 1e-9, "recall step knows where it lands");
Near(steps[0].Ns, 0, 1e-9, "recall is cast where you stand");
}
private static void SlowRecallLoses()
{
var portals = new List<PortalLink> { new(0.7, 0.7, 39.5, 39.5, "Far Portal") };
var recalls = new List<RecallLink> { new(40.1, 40.1, "Slow Recall", PortalRoute.RecallCostUnits(1000)) };
var steps = PortalRoute.Plan(portals, recalls, 0, 0, 40, 40, out _, out _);
Check(steps.Count == 2 && steps[0].UsePortal && !steps[0].UseRecall, "the portal wins over a very slow recall");
}
private static void RecallThenPortal()
{
// A recall to a town, then that town's portal, beats walking or the far portal.
var portals = new List<PortalLink> { new(-30.1, 70.1, 40, 40, "Town Portal") };
var recalls = new List<RecallLink>
{
new(-30, 70, "Town Recall", PortalRoute.RecallCostUnits(5)),
new(-80, -80, "Useless Recall", PortalRoute.RecallCostUnits(5)),
};
var steps = PortalRoute.Plan(portals, recalls, 0, 0, 40.2, 40.2, out _, out int used);
Check(used == 2, "recall then portal");
Check(steps.Count == 3 && steps[0].UseRecall && steps[0].RecallIndex == 0, "the town recall first");
Check(steps[1].UsePortal && steps[1].Label == "Town Portal", "then the town's portal");
}
private static void RecallCostFromCastTime()
{
Near(PortalRoute.RecallCostUnits(0), PortalRoute.TeleportOverheadUnits, 1e-9, "no cast time = the teleport overhead");
Near(PortalRoute.RecallCostUnits(10) - PortalRoute.RecallCostUnits(0), 10 * PortalRoute.RunUnitsPerSecond, 1e-9,
"each second of casting costs a second of running");
Near(new RecallLink(1, 1, "old").CostUnits, PortalRoute.RecallPenaltyUnits, 1e-9, "old constructor keeps the old penalty");
}
// ── The recall list ──────────────────────────────────────────────────────
private const string AtlasJson = @"{
""version"": 1, ""generated"": ""2026-10-01T00:00:00Z"",
""locations"": [
{""id"":1,""name"":""Holtburg"",""type"":""Town"",""cell"":""A9B40019"",""place"":""outdoor"",""ns"":42.08,""ew"":33.6},
{""id"":2,""name"":""Holtburg Portal"",""type"":""Portal"",""wcid"":100,""cell"":""7D640010"",""place"":""outdoor"",""ns"":-21.0,""ew"":-1.6,""dest"":{""cell"":""A9B40019"",""place"":""outdoor"",""ns"":42.08,""ew"":33.6}},
{""id"":3,""name"":""Holtburg"",""type"":""Portal"",""wcid"":101,""cell"":""01D201F7"",""place"":""dungeon"",""dest"":{""cell"":""A7B70037"",""place"":""outdoor"",""ns"":45.06,""ew"":32.3}},
{""id"":4,""name"":""Holtburg Lifestone"",""type"":""Lifestone"",""cell"":""A9B40018"",""place"":""outdoor"",""ns"":42.1,""ew"":33.5},
{""id"":5,""name"":""Yaraq"",""type"":""Town"",""cell"":""7D64000D"",""place"":""outdoor"",""ns"":-21.51,""ew"":-1.82},
{""id"":6,""name"":""Glimmering Cave"",""type"":""Dungeon"",""cell"":""A9B30005"",""place"":""outdoor"",""ns"":41.0,""ew"":33.0,""lb"":""01AB"",""minLevel"":12},
{""id"":7,""name"":""Shopkeeper Renald"",""type"":""Vendor"",""cell"":""A9B40150"",""place"":""building"",""ns"":42.2,""ew"":33.4,""desc"":""Shopkeeper.""},
{""id"":8,""name"":""Cave Hermit"",""type"":""NPC"",""cell"":""01AB0110"",""place"":""dungeon"",""desc"":""In Glimmering Cave.""}
],
""recalls"": [
{""spell"":2041,""name"":""Aerlinthe Recall"",""cell"":""BAE8001D"",""place"":""outdoor"",""ns"":84.09,""ew"":47.2},
{""spell"":2358,""name"":""Lyceum Recall"",""cell"":""BC110014"",""place"":""outdoor"",""ns"":-88.05,""ew"":48.65},
{""spell"":4213,""name"":""Colosseum Recall"",""cell"":""00AF0118"",""place"":""dungeon"",""in"":""The Colosseum""}
]
}";
private static void RecallListFromSpellbookAndMemory()
{
Atlas atlas = Atlas.Parse(AtlasJson);
var known = new HashSet<int> { 2041, 4213, RecallPlanner.LifestoneRecall, RecallPlanner.PrimaryPortalTieRecall };
var mem = new RecallMemory();
mem.Set("Aelrynth|Tom", RecallSlot.Lifestone, new RecallSpot { OnMap = true, Ns = 42.1, Ew = 33.5, Label = "Holtburg" });
mem.Set("Aelrynth|Tom", RecallSlot.House, new RecallSpot { OnMap = true, Ns = 10, Ew = 10, Label = "a cottage" });
mem.Set("Aelrynth|Other", RecallSlot.Sanctuary, new RecallSpot { OnMap = true, Ns = 1, Ew = 1 });
var notes = new List<string>();
var list = RecallPlanner.Build(atlas, known, mem, "Aelrynth|Tom", notes);
var names = list.ConvertAll(o => o.Name);
Check(names.Contains("Aerlinthe Recall"), "a known town recall");
Check(!names.Contains("Lyceum Recall"), "an unknown spell is left out");
Check(!names.Contains("Colosseum Recall"), "a dungeon landing is left out");
Check(notes.Exists(n => n.Contains("Colosseum Recall") && n.Contains("The Colosseum")), "...with a note");
var ls = list.Find(o => o.Name == "Lifestone Recall");
Check(ls != null && ls.SpellId == RecallPlanner.LifestoneRecall && ls.Learned, "Lifestone Recall from memory");
Check(!names.Contains("Primary Portal Tie Recall"), "a tie with no known portal is left out");
Check(notes.Exists(n => n.StartsWith("Primary Portal Tie Recall")), "...with a note");
Check(!names.Contains("Portal Recall"), "Portal Recall needs the spell");
var house = list.Find(o => o.Name == "House recall");
Check(house != null && house.SpellId == 0 && house.Command == "@house recall", "house recall as a command");
Check(!names.Contains("Lifestone (@lifestone)"), "no sanctuary known for this character");
Check(notes.Exists(n => n.StartsWith("Lifestone (@lifestone)")), "...with a note");
Check(list.TrueForAll(o => o.CastSeconds > 0), "every recall has a cast time");
var link = list.Find(o => o.Name == "Aerlinthe Recall")!.ToLink();
Near(link.CostUnits, PortalRoute.RecallCostUnits(RecallPlanner.SpellCastSeconds), 1e-9, "a spell's cost");
Near(house!.ToLink().CostUnits, PortalRoute.RecallCostUnits(RecallPlanner.CommandRecallSeconds), 1e-9, "a command's cost");
}
private static void RecallListColdSpellbook()
{
Atlas atlas = Atlas.Parse(AtlasJson);
var mem = new RecallMemory();
mem.Set("c", RecallSlot.Sanctuary, new RecallSpot { OnMap = true, Ns = 5, Ew = 6 });
var notes = new List<string>();
var list = RecallPlanner.Build(atlas, null, mem, "c", notes);
Check(list.Count == 1 && list[0].Command == "@lifestone", "only @lifestone while the spellbook isn't read");
Check(notes.Exists(n => n.Contains("Spellbook not read")), "says why");
}
private static void RecallMemoryRoundTrip()
{
var mem = new RecallMemory();
mem.Set("Aelrynth|Tom", RecallSlot.Tie1, new RecallSpot { OnMap = true, Ns = -33.54, Ew = 72.8, Label = "Shoushi" });
mem.Set("Aelrynth|Tom", RecallSlot.LastPortal, new RecallSpot { OnMap = false, Label = "Mines of Despair" });
mem.Set("Aelrynth|Ann", RecallSlot.House, new RecallSpot { OnMap = true, Ns = 1.5, Ew = -2.5, Command = "@house recall" });
Check(mem.Version == 3, "version moves");
var back = RecallMemory.Parse(mem.Serialize());
Check(back.Version == 0, "a fresh load isn't dirty");
var t = back.Get("aelrynth|tom", RecallSlot.Tie1);
Check(t != null && t.OnMap && t.Label == "Shoushi", "tie survives (names ignore case)");
Near(t?.Ns ?? double.NaN, -33.54, 1e-9, "tie NS");
var lp = back.Get("Aelrynth|Tom", RecallSlot.LastPortal);
Check(lp != null && !lp.OnMap && lp.Label == "Mines of Despair", "an off-map spot survives");
Check(back.Get("Aelrynth|Ann", RecallSlot.House)?.Command == "@house recall", "command survives");
Check(back.Get("Aelrynth|Ann", RecallSlot.Tie1) == null, "per character");
}
private static void RecallMessages()
{
Check(RecallMemory.Classify("You have attuned your spirit to this Lifestone. You will resurrect here after you die.", "Tom")
== RecallEvent.AttunedLifestone, "lifestone attune");
Check(RecallMemory.Classify("You have successfully linked with the life stone.", "Tom") == RecallEvent.LinkedLifestone, "lifestone tie");
Check(RecallMemory.Classify("You have successfully linked with the portal.", "Tom") == RecallEvent.LinkedPortal, "portal tie");
Check(RecallMemory.Classify("Tom is recalling to the lifestone.", "Tom") == RecallEvent.RecallingLifestone, "@lifestone");
Check(RecallMemory.Classify("Tom is recalling home.", "Tom") == RecallEvent.RecallingHome, "house");
Check(RecallMemory.Classify("Tom is recalling to the Allegiance housing.", "Tom") == RecallEvent.RecallingMansion, "mansion");
Check(RecallMemory.Classify("Tom is going to the Allegiance hometown.", "Tom") == RecallEvent.RecallingHometown, "hometown");
Check(RecallMemory.Classify("Tom is recalling to the marketplace.", "Tom") == RecallEvent.RecallingMarketplace, "marketplace");
Check(RecallMemory.Classify("Tommy is recalling home.", "Tom") == RecallEvent.None, "someone else nearby");
Check(RecallMemory.Classify("Ann says, \"Tom is recalling home.\"", "Tom") == RecallEvent.None, "quoted in chat");
Check(RecallMemory.Classify("", "Tom") == RecallEvent.None, "empty");
Check(RecallMemory.SlotFor(RecallEvent.RecallingHome, out var slot) && slot == RecallSlot.House, "house slot");
Check(!RecallMemory.SlotFor(RecallEvent.RecallingMarketplace, out _), "marketplace has no slot");
}
// ── Atlas ────────────────────────────────────────────────────────────────
private static void AtlasSearchAndBestMatch()
{
Atlas atlas = Atlas.Parse(AtlasJson);
Check(atlas.Locations.Count == 8 && atlas.Recalls.Count == 3, "parsed");
var best = atlas.FindBest("holtburg", hasPos: true, ns: -21.0, ew: -1.6);
Check(best != null && best.Type == "Town" && best.Name == "Holtburg", "the town beats its portals, even standing next to one");
best = atlas.FindBest("holt", hasPos: false, ns: 0, ew: 0);
Check(best != null && best.Type == "Town", "a prefix finds the town");
best = atlas.FindBest("Cave Hermit", hasPos: false, ns: 0, ew: 0);
Check(best == null, "a place with no map position is never an arrow target");
best = atlas.FindBest("renald", hasPos: false, ns: 0, ew: 0);
Check(best != null && best.Type == "Vendor", "a word inside a name");
Check(atlas.FindBest("zzz", false, 0, 0) == null, "no match");
var portals = atlas.Search("", "Portal", 50);
Check(portals.Count == 2 && portals.TrueForAll(p => p.Type == "Portal"), "type filter");
var hits = atlas.Search("Holtburg", null, 50);
Check(hits.Count == 4 && hits[0].Type == "Town", "search: exact names first, town first");
Check(atlas.Search("glimmering cave", null, 50).Count == 1, "case-insensitive");
Check(atlas.Search("cave glimmering", null, 50).Count == 1, "every word, any order");
var p2 = atlas.ById(2)!;
Check(p2.HasDest && p2.DestOnMap, "portal destination");
Near(p2.DestNs, 42.08, 1e-9, "portal destination NS");
var p3 = atlas.ById(3)!;
Check(!p3.OnMap && p3.HasDest && p3.DestOnMap, "a portal inside a dungeon");
Check(atlas.ById(6)!.MinLevel == 12 && atlas.ById(6)!.Lb == "01AB", "dungeon fields");
Check(atlas.Nearest("Lifestone", 42.0, 33.6, 500)?.Id == 4, "nearest lifestone");
Check(atlas.Nearest("Lifestone", 0, 0, 500) == null, "none in range");
Check(atlas.PortalByWcid(100, 0, 0)?.Id == 2, "portal by weenie class");
}
// ── Arrow ────────────────────────────────────────────────────────────────
private static void ArrowSingleTarget()
{
var a = new ArrowGuide();
Check(!a.Active, "starts empty");
a.SetTarget("Holtburg", "Town", 42.08, 33.6);
Check(a.Active && a.Current!.Name == "Holtburg", "set");
Check(a.Update(true, 40, 30, false) == ArrowEvent.None, "far away: nothing");
Check(a.Update(true, 42.08, 33.6 + 5 / 240.0, false) == ArrowEvent.Arrived, "within 10 yd: arrived");
Check(!a.Active, "cleared on arrival");
a.SetTarget("Somewhere", "", 1, 1);
Check(a.Update(false, 1, 1, false) == ArrowEvent.None, "no position: no arrival");
int v = a.Version;
a.Clear();
Check(!a.Active && a.Version > v, "clear");
}
private static void ArrowAlongRoute()
{
var portals = new List<PortalLink> { new(-30.1, 70.1, 40, 40, "Town Portal") };
var recalls = new List<RecallLink> { new(-30, 70, "Town Recall", PortalRoute.RecallCostUnits(5)) };
var route = PortalRoute.Plan(portals, recalls, 0, 0, 40.2, 40.2, out _, out _);
var a = new ArrowGuide();
a.SetRoute(route, "Goal", "Town", 40.2, 40.2);
Check(a.Count == 3, "recall, portal, place");
Check(a.Current!.Kind == ArrowStepKind.Recall && !a.Current.OnMap, "first: cast the recall");
Check(a.Update(true, 0, 0, false) == ArrowEvent.None, "waits for the recall");
Check(a.Update(true, -30, 70, true) == ArrowEvent.Advanced, "teleport: next step");
Check(a.Current!.Kind == ArrowStepKind.Portal && a.Current.Name == "Town Portal", "then the portal");
Check(a.Update(true, -30.1, 70.1, false) == ArrowEvent.None, "standing on the portal isn't through it");
Check(a.Update(true, 40, 40, true) == ArrowEvent.Advanced, "through the portal");
Check(a.Current!.Kind == ArrowStepKind.Place && a.Current.Name == "Goal", "then the place");
Check(a.Update(true, 40.2, 40.2, false) == ArrowEvent.Arrived && !a.Active, "arrived");
a.SetRoute(PortalRoute.Plan(NoPortals, null, 0, 0, 1, 1, out _, out _), "Near", "", 1, 1);
Check(a.Count == 1 && a.Current!.Kind == ArrowStepKind.Place, "no teleports: just the place");
}
// ── Favorites / Recent ───────────────────────────────────────────────────
private static void FavoritesAndRecent()
{
var s = new AtlasStore();
var holt = new SavedPlace { Name = "Holtburg", Type = "Town", Ns = 42.08, Ew = 33.6 };
Check(s.ToggleFavorite(holt) && s.IsFavorite(holt), "add favorite");
Check(!s.ToggleFavorite(new SavedPlace { Name = "holtburg", Ns = 42.09, Ew = 33.61 }), "same place toggles off");
Check(s.Favorites.Count == 0, "removed");
s.ToggleFavorite(holt);
for (int i = 0; i < 25; i++) s.Touch(new SavedPlace { Name = "P" + i, Ns = i, Ew = i });
s.Touch(new SavedPlace { Name = "P5", Ns = 5, Ew = 5 });
Check(s.Recent.Count == AtlasStore.MaxRecent, "recent is capped");
Check(s.Recent[0].Name == "P5" && s.Recent[1].Name == "P24", "touched moves to the front");
var back = AtlasStore.Parse(s.Serialize());
Check(back.Favorites.Count == 1 && back.Favorites[0].Name == "Holtburg" && back.Favorites[0].Type == "Town", "favorites survive");
Check(back.Recent.Count == AtlasStore.MaxRecent && back.Recent[0].Name == "P5", "recent survives in order");
Near(back.Favorites[0].Ns, 42.08, 1e-9, "coordinates survive");
Check(back.RemoveFavorite("HOLTBURG") && back.Favorites.Count == 0, "remove by name");
}
// ── Coordinates ──────────────────────────────────────────────────────────
private static void CoordinateParsing()
{
Check(NavCoords.TryParseLoc("42.1N, 33.6E", out double ns, out double ew) && ns == 42.1 && ew == 33.6, "/loc style");
Check(NavCoords.TryParseLoc("21.5S 1.8W", out ns, out ew) && ns == -21.5 && ew == -1.8, "south and west");
Check(NavCoords.TryParseLoc("33.6E 42.1N", out ns, out ew) && ns == 42.1 && ew == 33.6, "letters set the order");
Check(NavCoords.TryParseLoc("42.1 N, 33.6 E", out ns, out ew) && ns == 42.1 && ew == 33.6, "spaced letters");
Check(!NavCoords.TryParseLoc("42.1N 33.6N", out _, out _), "two N/S refused");
Check(!NavCoords.TryParseLoc("Holtburg", out _, out _), "a name");
Check(!NavCoords.LooksLikeCoords("Area 51"), "a name with a number");
Check(NavCoords.LooksLikeCoords("42.1, 33.6"), "bare numbers are coordinates");
Check(NavCoords.TrySplitCoordsAndName("42.1N, 33.6E Holtburg Lifestone", out ns, out ew, out string name)
&& ns == 42.1 && ew == 33.6 && name == "Holtburg Lifestone", "coords then a name");
Check(NavCoords.TrySplitCoordsAndName("42.1 N, 33.6 E Holtburg", out _, out _, out name) && name == "Holtburg", "spaced letters then a name");
Check(NavCoords.TrySplitCoordsAndName("42.1N 33.6E Eastham", out _, out ew, out name) && ew == 33.6 && name == "Eastham",
"a name starting with a compass letter");
Check(NavCoords.TrySplitCoordsAndName("42.1N 33.6E", out _, out _, out name) && name == "", "no name");
Check(NavCoords.Fmt(-21.51, -1.82) == "21.5S, 1.8W", "format");
}
// ── The generated data (RynthCore's tools/navdata/NavData), when it's beside this repo ──
private static void RealData()
{
string dir = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", "..",
"RynthCore", "tools", "navdata", "NavData"));
string locs = Path.Combine(dir, "locations.json"), tsv = Path.Combine(dir, "portals.tsv");
if (!File.Exists(locs) || !File.Exists(tsv)) { Console.WriteLine(" (no generated NavData beside this repo: skipped)"); return; }
Atlas atlas = Atlas.Load(locs);
Check(atlas.Locations.Count > 1000 && atlas.Recalls.Count > 10, "the real Atlas loads");
var holt = atlas.FindBest("Holtburg", false, 0, 0);
Check(holt != null && holt.Type == "Town", "Holtburg is a town");
Near(holt?.Ns ?? double.NaN, 42.1, 0.1, "Holtburg NS");
Near(holt?.Ew ?? double.NaN, 33.6, 0.1, "Holtburg EW");
var yaraq = atlas.FindBest("Yaraq", false, 0, 0)!;
var portals = new List<PortalLink>();
foreach (string line in File.ReadAllLines(tsv))
{
string[] f = line.Split('\t');
if (f.Length < 5) continue;
portals.Add(new PortalLink(double.Parse(f[0], System.Globalization.CultureInfo.InvariantCulture),
double.Parse(f[1], System.Globalization.CultureInfo.InvariantCulture),
double.Parse(f[2], System.Globalization.CultureInfo.InvariantCulture),
double.Parse(f[3], System.Globalization.CultureInfo.InvariantCulture), f[4]));
}
Check(portals.Count > 300, "the real portals.tsv loads");
// Yaraq to Holtburg: portals only, then with recalls a character might know.
double direct = NavCoords.Distance(yaraq.Ns, yaraq.Ew, holt!.Ns, holt.Ew);
var steps = PortalRoute.Plan(portals, null, yaraq.Ns, yaraq.Ew, holt.Ns, holt.Ew, out double est, out int used);
Check(est <= direct + 1e-6, "a plan is never worse than walking");
Console.WriteLine($" Yaraq -> Holtburg, portals only: {used} teleport(s), ~{est:F0} vs {direct:F0} walking");
foreach (var s in steps) Console.WriteLine($" {(s.UseRecall ? "recall" : s.UsePortal ? "portal" : "walk ")} {s.Label} {NavCoords.Fmt(s.Ns, s.Ew)}");
var mem = new RecallMemory();
mem.Set("w|c", RecallSlot.Sanctuary, new RecallSpot { OnMap = true, Ns = 42.1, Ew = 33.5, Label = "Holtburg" });
var known = new HashSet<int> { 2041, 2358, 3865 }; // Aerlinthe, Lyceum, Glenden Wood
var notes = new List<string>();
var recalls = RecallPlanner.Build(atlas, known, mem, "w|c", notes);
steps = PortalRoute.Plan(portals, RecallPlanner.Links(recalls), yaraq.Ns, yaraq.Ew, holt.Ns, holt.Ew, out est, out used);
Check(steps.Count > 0 && steps[0].UseRecall && recalls[steps[0].RecallIndex].Command == "@lifestone",
"with a lifestone in Holtburg, @lifestone is the way home");
Console.WriteLine($" ... with recalls: {used} teleport(s), ~{est:F0}; first: {steps[0].Label}");
}
// ── Going into a dungeon: the goto ends by walking into its entrance portal ──────
private const string EntranceJson = @"{
""locations"": [
{""id"":1,""name"":""Holtburg"",""type"":""Town"",""ns"":42.08,""ew"":33.6},
{""id"":2,""name"":""Deep Vault"",""type"":""Dungeon"",""cell"":""A9B30005"",""place"":""outdoor"",""ns"":41.0,""ew"":33.0,""lb"":""01AB""},
{""id"":3,""name"":""Deep Vault"",""type"":""Portal"",""cell"":""A9B30005"",""place"":""outdoor"",""ns"":41.0,""ew"":33.0,""dest"":{""cell"":""01AB0100"",""place"":""dungeon"",""name"":""Deep Vault""}},
{""id"":4,""name"":""Deep Vault"",""type"":""Portal"",""cell"":""B0B00005"",""place"":""outdoor"",""ns"":43.0,""ew"":34.0,""dest"":{""cell"":""01AB0100"",""place"":""dungeon"",""name"":""Deep Vault""},""quest"":true},
{""id"":5,""name"":""Deep Vault"",""type"":""Portal"",""cell"":""B1B00005"",""place"":""outdoor"",""ns"":42.2,""ew"":33.7,""dest"":{""cell"":""01AB0100"",""place"":""dungeon"",""name"":""Deep Vault""},""closed"":true},
{""id"":6,""name"":""Sunken Hall"",""type"":""Dungeon"",""cell"":""02CD0100"",""place"":""dungeon"",""lb"":""02CD""},
{""id"":7,""name"":""Inner Gate"",""type"":""Portal"",""cell"":""01AB0110"",""place"":""dungeon"",""dest"":{""cell"":""02CD0100"",""place"":""dungeon"",""name"":""Sunken Hall""}},
{""id"":8,""name"":""Lone Cave"",""type"":""Dungeon"",""cell"":""A7B70005"",""place"":""outdoor"",""ns"":45.0,""ew"":32.0,""lb"":""03EF""}
]
}";
private static void DungeonEntrance()
{
Atlas atlas = Atlas.Parse(EntranceJson);
AtlasLocation town = atlas.ById(1)!, vault = atlas.ById(2)!, sunken = atlas.ById(6)!, inner = atlas.ById(7)!, lone = atlas.ById(8)!;
Check(!Entrance.IsEntrance(town) && Entrance.IsEntrance(vault) && Entrance.IsEntrance(atlas.ById(3)!), "dungeons and portals are entrances, towns aren't");
// Standing at Holtburg (42.08, 33.6): the closed entrance (nearest) is skipped, and the open
// entrance that needs no quest wins over the nearer quest one.
AtlasLocation? p = Entrance.PortalFor(atlas, vault, true, 42.08, 33.6, out string why);
Check(p != null && p.Id == 3 && why.Length == 0, $"nearest open, no-quest entrance (got {p?.Id})");
Check(p!.Ns == 41.0 && p.Ew == 33.0, "the entrance's own map position, not the inside");
p = Entrance.PortalFor(atlas, lone, true, 42, 33, out why);
Check(p == lone, "a dungeon with no portal in the Atlas: its own position (its entrance)");
p = Entrance.PortalFor(atlas, sunken, true, 42, 33, out why);
Check(p == null && why.Contains("Sunken Hall") && why.Contains("no position on the map"), "an entrance inside another dungeon: refused, with the reason");
p = Entrance.PortalFor(atlas, inner, true, 42, 33, out why);
Check(p == null && why.Contains("inside a dungeon"), "a portal inside a dungeon: refused, with the reason");
Check(Entrance.ArrivedText("Deep Vault", "Dungeon") == "arrived inside Deep Vault", "the arrival line for a dungeon");
Check(Entrance.NoTeleportText("Deep Vault").StartsWith("stopped: Deep Vault's portal didn't take you in"), "the stop line when the portal doesn't fire");
}
// The real location database: dungeons sit at their entrance portal (outside), not inside.
private static void RealDungeonEntrances()
{
string locs = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", "..",
"RynthCore", "tools", "navdata", "NavData", "locations.json"));
if (!File.Exists(locs)) { Console.WriteLine(" (no generated NavData beside this repo: skipped)"); return; }
Atlas atlas = Atlas.Load(locs);
foreach (string name in new[] { "Matron Hive West", "Mines of Despair", "Glimmering Cave" })
{
AtlasLocation? d = null;
foreach (var l in atlas.Locations) if (l.Type == "Dungeon" && l.Name == name) { d = l; break; }
if (d == null) { Console.WriteLine($" ({name} isn't in this database)"); continue; }
Check(d.OnMap && d.Place != "dungeon", $"{name}: the Dungeon entry is on the map ({d.Place} cell {d.Cell})");
AtlasLocation? p = Entrance.PortalFor(atlas, d, false, 0, 0, out string why);
Check(p != null && p.Type == "Portal" && p.HasDest && !p.DestOnMap && p.DestName == name && p.Place != "dungeon",
$"{name}: walks into an entrance portal on the map that leads inside ({p?.Ns:F2}, {p?.Ew:F2}, dest {p?.DestPlace})");
Console.WriteLine($" {name}: entrance {NavCoords.Fmt(p?.Ns ?? 0, p?.Ew ?? 0)} ({p?.Place} cell {p?.Cell}) -> inside {p?.DestPlace}");
}
int dungeons = 0, onMap = 0, withPortal = 0;
foreach (var l in atlas.Locations)
{
if (l.Type != "Dungeon") continue;
dungeons++;
if (l.OnMap) onMap++;
if (Entrance.PortalFor(atlas, l, false, 0, 0, out _) is { Type: "Portal" }) withPortal++;
}
Console.WriteLine($" {dungeons} dungeons: {onMap} with a map position, {withPortal} with an entrance portal on the map");
Check(onMap == dungeons, "every dungeon in the database has its entrance's map position");
}
private static void RouteEndsOnAPortalStep()
{
// A plain walk becomes one portal step at the entrance.
List<RouteStep> steps = Entrance.EndingInPortal(null, 41.0, 33.0, "Deep Vault");
Check(steps.Count == 1 && steps[0].UsePortal && !steps[0].UseRecall && steps[0].Ns == 41.0 && steps[0].Ew == 33.0, "walk -> one portal step");
// A route (a portal, then a walk to the entrance): the last walk becomes the portal step.
var route = new List<RouteStep> { new(-21.0, -1.6, true, false, "Holtburg Portal"), new(41.0, 33.0, false, false, "walk") };
steps = Entrance.EndingInPortal(route, 41.0, 33.0, "Deep Vault");
Check(steps.Count == 2 && steps[0].Label == "Holtburg Portal" && steps[1].UsePortal && steps[1].Label == "Deep Vault", "route -> its last walk is the entrance's portal step");
Check(route[1].UsePortal == false, "the planner's own list isn't changed");
// A route that ends somewhere else (a recall landing): the portal step is added after it.
var viaRecall = new List<RouteStep> { new(42.1, 33.5, false, true, "Lifestone") };
steps = Entrance.EndingInPortal(viaRecall, 41.0, 33.0, "Deep Vault");
Check(steps.Count == 2 && steps[0].UseRecall && steps[1].UsePortal, "after a recall, walk on into the portal");
}
// Where the plugin reads its tiles and Atlas from: env var, then rynthnav.json, then the default.
private static void NavDataFolder()
{
string dir = Path.Combine(Path.GetTempPath(), "rnav-cfg-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
string settings = Path.Combine(dir, "rynthnav.json");
try
{
var c = RynthCore.Plugin.RynthNav.NavDataConfig.Resolve(null, settings);
Check(c.Dir == @"C:\Games\RynthCore\NavData" && c.Source == "default", "no settings: the default folder");
File.WriteAllText(settings, "{ \"navDataDir\": \"D:\\\\AC\\\\NavData\\\\\" }");
c = RynthCore.Plugin.RynthNav.NavDataConfig.Resolve(null, settings);
Check(c.Dir == @"D:\AC\NavData" && c.Source == settings, "rynthnav.json's navDataDir, trailing slash trimmed");
c = RynthCore.Plugin.RynthNav.NavDataConfig.Resolve(@"E:\Nav", settings);
Check(c.Dir == @"E:\Nav" && c.Source == "RYNTHNAV_NAVDATA", "the environment variable wins");
c = RynthCore.Plugin.RynthNav.NavDataConfig.Resolve(@"relative\dir", settings);
Check(c.Dir == @"D:\AC\NavData" && c.Source.Contains("ignored"), "a relative env path is ignored, with a note");
File.WriteAllText(settings, "{ \"navDataDir\": \"NavData\" }");
c = RynthCore.Plugin.RynthNav.NavDataConfig.Resolve(null, settings);
Check(c.Dir == @"C:\Games\RynthCore\NavData" && c.Source.Contains("ignored"), "a relative setting falls back to the default");
File.WriteAllText(settings, "not json");
c = RynthCore.Plugin.RynthNav.NavDataConfig.Resolve(null, settings);
Check(c.Dir == @"C:\Games\RynthCore\NavData", "a broken file falls back to the default");
}
finally { try { Directory.Delete(dir, true); } catch { } }
}
private static void BearingAndDistance()
{
Near(NavCoords.Distance(0, 0, 1, 0), 240, 1e-9, "a degree is 240 yd");
Near(NavCoords.Bearing(0, 0, 1, 0), 0, 1e-9, "north");
Near(NavCoords.Bearing(0, 0, 0, 1), 90, 1e-9, "east");
Near(NavCoords.Bearing(0, 0, -1, 0), 180, 1e-9, "south");
Near(NavCoords.Bearing(0, 0, 0, -1), 270, 1e-9, "west");
Check(NavCoords.CompassPoint(44) == "NE" && NavCoords.CompassPoint(359) == "N" && NavCoords.CompassPoint(200) == "SSW", "compass points");
NavCoords.FromCell(0xA9B40019, 84.0, 7.1, out double ns, out double ew);
Near(ns, 42.08, 0.01, "Holtburg NS from its cell");
Near(ew, 33.6, 0.01, "Holtburg EW from its cell");
Near(NavCoords.NsFromWorld(NavCoords.WorldY(-33.54)), -33.54, 1e-9, "world round trip");
}
}

View file

@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline tests for RynthNav's travel logic: route planning with recalls (over small fake
portal graphs), the recall list a character gets, the recall memory and its chat
messages, the Atlas search, the arrow's chain, favorites/recent and the coordinate
parser. The plugin is a NativeAOT x86 library, so its host-free source files are
compiled in here directly.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<RootNamespace>RynthNav.RouteTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\RynthNav.PortalGraph\PortalRoute.cs" Link="Linked\PortalRoute.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavCoords.cs" Link="Linked\NavCoords.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\Atlas.cs" Link="Linked\Atlas.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\AtlasStore.cs" Link="Linked\AtlasStore.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\ArrowGuide.cs" Link="Linked\ArrowGuide.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RecallMemory.cs" Link="Linked\RecallMemory.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RecallPlanner.cs" Link="Linked\RecallPlanner.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavDataConfig.cs" Link="Linked\NavDataConfig.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\Entrance.cs" Link="Linked\Entrance.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TownNet.cs" Link="Linked\TownNet.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\PortalAvoid.cs" Link="Linked\PortalAvoid.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TravelPlan.cs" Link="Linked\TravelPlan.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,443 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using RynthCore.Plugin.RynthNav;
using RynthNav.Routing;
namespace RynthNav.RouteTests;
// The Town Network: the planner's hub edges (made-up hubs and the real townnet.json), the
// restrictions (level, Olthoi), townnet.json's checks, the way inside, and the walker inside.
internal static partial class Program
{
private static void RunTownNet()
{
Run(nameof(HubChosenWhenCheaper), HubChosenWhenCheaper);
Run(nameof(HubSkippedWhenWalkingIsCheaper), HubSkippedWhenWalkingIsCheaper);
Run(nameof(HubAfterAPortal), HubAfterAPortal);
Run(nameof(TownNetFileChecks), TownNetFileChecks);
Run(nameof(TownNetLevelAndOlthoi), TownNetLevelAndOlthoi);
Run(nameof(HubStepInTheArrowAndEntrance), HubStepInTheArrowAndEntrance);
Run(nameof(RealTownNetwork), RealTownNetwork);
Run(nameof(RealTownNetworkLevelBlocks), RealTownNetworkLevelBlocks);
Run(nameof(RealTownNetworkWays), RealTownNetworkWays);
Run(nameof(AphusRecallThenTownNetworkToArwic), AphusRecallThenTownNetworkToArwic);
Run(nameof(HubWalkerFollowsTheWalk), HubWalkerFollowsTheWalk);
Run(nameof(HubWalkerStops), HubWalkerStops);
}
// A hub with one arrival: an entry beside (0, 0), an exit to (40, 40.1) after a 60 m walk.
private static HubLinks FakeHub(double walk = 60)
{
var hub = new HubLinks { Name = "Town Network", Arrivals = 1 };
hub.Entries.Add(new HubEntry(0.1, 0, 0, "Portal to Town Network"));
hub.Exits.Add(new HubExit(40, 40.1, "Portal to Far Town", 7, new[] { walk }));
return hub;
}
private static void HubChosenWhenCheaper()
{
var steps = PortalRoute.Plan(NoPortals, null, FakeHub(), 0, 0, 40, 40, out double est, out int used);
Check(used == 2, "into the network and out: two teleports");
Check(steps.Count == 3, "walk to the entry, the network, walk on");
Check(steps[0].UsePortal && !steps[0].IsHub && steps[0].Label == "Portal to Town Network", "first: take the entry portal");
Near(steps[0].Ns, 0.1, 1e-9, "the entry's position");
Check(steps[1].IsHub && steps[1].HubExit == 7 && steps[1].Label == "Portal to Far Town", "then the exit, with its id");
Near(steps[1].LandNs, 40, 1e-9, "the hub step knows where it lands");
Check(!steps[2].UsePortal && !steps[2].IsHub, "last leg walks");
double expected = 0.1 * 240 + PortalRoute.PortalPenaltyUnits + 60 + PortalRoute.PortalPenaltyUnits + 0.1 * 240;
Near(est, expected, 0.01, "cost: walk, teleport, walk inside, teleport, walk");
Check(!default(RouteStep).IsHub && default(RouteStep).HubExit == -1, "a default step isn't a hub step");
Check(!new RouteStep(1, 1, true, false, "p").IsHub, "an ordinary portal step isn't one either");
}
private static void HubSkippedWhenWalkingIsCheaper()
{
// 2 degrees (480 units) is less than two teleports.
var steps = PortalRoute.Plan(NoPortals, null, FakeHub(), 0, 0, 0, 2, out double est, out int used);
Check(used == 0 && steps.Count == 1 && !steps[0].IsHub, "a short trip walks");
Near(est, 480, 0.01, "cost is the walk");
// A walk inside so long the network loses to walking.
PortalRoute.Plan(NoPortals, null, FakeHub(walk: 20000), 0, 0, 40, 40, out _, out used);
Check(used == 0, "an expensive walk inside is skipped");
// An exit with no walk from the entry's arrival can't be reached.
var noWalk = FakeHub(walk: double.NaN);
PortalRoute.Plan(NoPortals, null, noWalk, 0, 0, 40, 40, out _, out used);
Check(used == 0, "no walk inside: not used");
}
private static void HubAfterAPortal()
{
// A portal from the start takes you near the entry; the network then takes you on.
var portals = new List<PortalLink> { new(-60, -60, 0.2, 0.2, "First Portal") };
var hub = FakeHub();
var steps = PortalRoute.Plan(portals, null, hub, -60, -60.05, 40, 40, out _, out int used);
Check(used == 3, "portal, into the network, out");
Check(steps.Count == 4 && steps[0].UsePortal && steps[0].Label == "First Portal", "the portal first");
Check(steps[1].UsePortal && steps[1].Label == "Portal to Town Network", "then walk to the entry and take it");
Check(steps[2].IsHub && !steps[3].UsePortal, "then the network, then the walk");
}
// ── townnet.json ─────────────────────────────────────────────────────────
/// <summary>A small townnet.json: one arrival, an entry (noOlthoi), an exit with minLevel, its walk.</summary>
private static string SmallTownNet(int version = 1, int minLevel = 80, bool fixId = true)
{
string text =
"{\n" +
$" \"version\": {version},\n" +
" \"setId\": \"\",\n" +
" \"generated\": \"2026-10-01T00:00:00Z\",\n" +
" \"landblocks\": [\"0007\"],\n" +
" \"arrivals\": [\n" +
" {\"id\":\"A1\",\"cell\":\"00070133\",\"x\":60.0,\"y\":-70.0,\"z\":0.005}\n" +
" ],\n" +
" \"entries\": [\n" +
" {\"guid\":\"7A0B0001\",\"name\":\"Portal to Town Network\",\"cell\":\"A9B40001\",\"place\":\"outdoor\",\"ns\":0.1,\"ew\":0.0,\"noOlthoi\":true,\"arrival\":\"A1\"},\n" +
" {\"guid\":\"701AC00F\",\"name\":\"Portal to Town Network\",\"cell\":\"01AC0104\",\"place\":\"dungeon\",\"arrival\":\"A1\"}\n" +
" ],\n" +
" \"exits\": [\n" +
" {\"guid\":\"70007084\",\"name\":\"Portal to Eastwatch\",\"label\":\"Eastwatch\",\"cell\":\"0007016B\",\"x\":86.5,\"y\":-70.0,\"z\":0,\"dest\":{\"cell\":\"49F00013\",\"place\":\"outdoor\",\"ns\":40.0,\"ew\":40.1}" + (minLevel > 0 ? $",\"minLevel\":{minLevel}" : "") + "},\n" +
" {\"guid\":\"7000707E\",\"name\":\"The Marketplace of Dereth\",\"label\":\"The Marketplace of Dereth\",\"cell\":\"00070165\",\"x\":60,\"y\":-90,\"z\":0,\"dest\":{\"cell\":\"016C01BC\",\"place\":\"dungeon\"},\"noOlthoi\":true}\n" +
" ],\n" +
" \"walks\": [\n" +
" {\"from\":\"A1\",\"to\":\"70007084\",\"length\":26.5,\"points\":[[\"00070133\",60,-70,0],[\"00070140\",70,-70,0],[\"0007016B\",86.5,-70,0]]},\n" +
" {\"from\":\"A1\",\"to\":\"7000707E\",\"length\":20,\"points\":[[\"00070133\",60,-70,0],[\"00070165\",60,-90,0]]}\n" +
" ]\n" +
"}\n";
if (!fixId) return text;
return text.Replace("\"setId\": \"\"", "\"setId\": \"" + TownNet.ComputeSetId(text) + "\"");
}
private static void TownNetFileChecks()
{
TownNet? t = TownNet.Parse(SmallTownNet(), out string why);
Check(t != null && why == "", "a good file loads: " + why);
Check(t != null && t.Contains(0x0007) && !t.Contains(0xA9B4), "the network's landblock");
Check(t != null && t.Arrivals.Count == 1 && t.Entries.Count == 2 && t.Exits.Count == 2 && t.Walks.Count == 2, "its lists");
Check(t?.Walk(0, 0)?.Points.Length == 3, "a walk by arrival and exit");
Check(t != null && t.Exits[0].Where == "Eastwatch" && t.Exits[0].DestLandblock == 0x49F0, "an exit's place and landblock");
Check(t != null && t.Exits[0].Rules.MinLevel == 80 && t.Entries[0].Rules.NoOlthoi, "restrictions read");
string crlf = SmallTownNet().Replace("\n", "\r\n");
Check(TownNet.Parse(crlf, out _) != null, "a CRLF copy has the same set id");
Check(TownNet.Parse(SmallTownNet(fixId: false), out why) == null && why.Contains("set id"), "no set id: ignored (" + why + ")");
string edited = SmallTownNet().Replace("\"length\":26.5", "\"length\":2.5");
Check(TownNet.Parse(edited, out why) == null && why.Contains("doesn't match"), "an edited file is ignored (" + why + ")");
Check(TownNet.Parse(SmallTownNet(version: 2), out why) == null && why.Contains("version 2"), "another version is ignored (" + why + ")");
}
private static void TownNetLevelAndOlthoi()
{
TownNet t = TownNet.Parse(SmallTownNet(), out _)!;
var notes = new List<string>();
HubLinks low = t.Links(45, false, notes);
Check(low.Entries.Count == 1, "the outdoor entry is on the map (the dungeon one isn't)");
Check(low.Exits.Count == 0, "level 45: the level 80 exit is left out (and the Marketplace is in a dungeon)");
Check(notes.Exists(n => n.Contains("Portal to Eastwatch") && n.Contains("needs level 80")), "...with a note");
HubLinks high = t.Links(90, false, null);
Check(high.Exits.Count == 1 && high.Exits[0].Id == 0 && high.Exits[0].WalkUnits[0] == 26.5, "level 90: the exit, with its walk");
notes.Clear();
HubLinks unknown = t.Links(0, false, notes);
Check(unknown.Exits.Count == 0 && notes.Exists(n => n.Contains("isn't known")), "level not known yet: a level rule leaves it out");
HubLinks olthoi = t.Links(90, true, notes);
Check(olthoi.Entries.Count == 0, "an Olthoi can't use the entry portals");
// Planned: level 45 walks, level 90 takes the network.
PortalRoute.Plan(NoPortals, null, low, 0, 0, 40, 40, out _, out int used);
Check(used == 0, "level 45: the route doesn't use the blocked exit");
var steps = PortalRoute.Plan(NoPortals, null, high, 0, 0, 40, 40, out _, out used);
Check(used == 2 && steps.Exists(s => s.IsHub && s.HubExit == 0), "level 90: the network to Eastwatch");
PortalRoute.Plan(NoPortals, null, olthoi, 0, 0, 40, 40, out _, out used);
Check(used == 0, "an Olthoi walks");
var rules = new TownNetRules { MaxLevel = 50 };
Check(rules.Blocks(60, false).Contains("50 or lower") && rules.Blocks(40, false) == "", "max level");
Check(new TownNetRules { Closed = true }.Blocks(90, false) == "closed", "closed");
Check(new TownNetRules { Quest = "SomeFlag" }.Blocks(90, false).Contains("quest"), "a quest flag can't be checked: left out");
Check(new TownNetRules { OnlyOlthoi = true }.Blocks(90, false) != "" && new TownNetRules { OnlyOlthoi = true }.Blocks(90, true) == "", "Olthoi only");
Check(new TownNetRules { AccountRequirements = 1 }.Blocks(90, false) == "", "account requirement 1 restricts nobody");
}
private static void HubStepInTheArrowAndEntrance()
{
var route = PortalRoute.Plan(NoPortals, null, FakeHub(), 0, 0, 40, 40, out _, out _);
var a = new ArrowGuide();
a.SetRoute(route, "Far Town", "Town", 40, 40);
Check(a.Count == 3, "entry portal, the network's exit, the place");
Check(a.Current!.Kind == ArrowStepKind.Portal && a.Current.OnMap, "first: the entry portal on the map");
Check(a.Update(true, 0.1, 0, true) == ArrowEvent.Advanced, "into the network");
Check(a.Current!.Kind == ArrowStepKind.Portal && !a.Current.OnMap && a.Current.Hint.Contains("Town Network"), "then the exit inside (no map position)");
Check(a.Update(false, 0, 0, true) == ArrowEvent.Advanced && a.Current!.Kind == ArrowStepKind.Place, "out: the place");
// A dungeon behind the network's exit: the last walk becomes its portal; the hub step stays.
var withEntrance = Entrance.EndingInPortal(route, 40, 40, "Some Dungeon");
Check(withEntrance.Count == 3 && withEntrance[1].IsHub && withEntrance[2].UsePortal && !withEntrance[2].IsHub,
"the last walk becomes the dungeon's portal; the hub step stays");
var endsInHub = new List<RouteStep> { route[0], route[1] };
Check(Entrance.EndingInPortal(endsInHub, 40, 40.1, "X").Count == 3, "a hub step is never taken for the last walk");
}
// ── The real townnet.json (RynthCore's tools/navdata/NavData), when it's beside this repo ──
private static string RealNavDataDir() => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", "..",
"RynthCore", "tools", "navdata", "NavData"));
private static (TownNet? Net, Atlas? Atlas, List<PortalLink>? Portals) RealTownNetData()
{
string dir = RealNavDataDir();
string tn = Path.Combine(dir, TownNet.FileName), locs = Path.Combine(dir, "locations.json"), tsv = Path.Combine(dir, "portals.tsv");
if (!File.Exists(tn) || !File.Exists(locs) || !File.Exists(tsv)) return (null, null, null);
TownNet? t = TownNet.Parse(File.ReadAllText(tn), out string why);
Check(t != null, "the real townnet.json loads: " + why);
var portals = new List<PortalLink>();
foreach (string line in File.ReadAllLines(tsv))
{
string[] f = line.Split('\t');
if (f.Length < 5) continue;
portals.Add(new PortalLink(double.Parse(f[0], CultureInfo.InvariantCulture), double.Parse(f[1], CultureInfo.InvariantCulture),
double.Parse(f[2], CultureInfo.InvariantCulture), double.Parse(f[3], CultureInfo.InvariantCulture), f[4]));
}
return (t, Atlas.Load(locs), portals);
}
private static int ExitIndex(TownNet t, string where)
{
for (int i = 0; i < t.Exits.Count; i++) if (t.Exits[i].Where == where) return i;
return -1;
}
private static void RealTownNetwork()
{
var (t, atlas, portals) = RealTownNetData();
if (t == null || atlas == null || portals == null) { Console.WriteLine(" (no generated NavData beside this repo: skipped)"); return; }
Check(t.Arrivals.Count == 4 && t.Walks.Count == 196 && t.Contains(0x0007), "4 arrivals, 196 walks, landblock 0007");
var holt = atlas.FindBest("Holtburg", false, 0, 0)!;
var yaraq = atlas.FindBest("Yaraq", false, 0, 0)!;
HubLinks hub = t.Links(100, false, null);
Check(hub.Entries.Count == 52 && hub.Exits.Count == 47, $"on the map: 52 entries, 47 exits (got {hub.Entries.Count}, {hub.Exits.Count})");
double direct = NavCoords.Distance(holt.Ns, holt.Ew, yaraq.Ns, yaraq.Ew);
var without = PortalRoute.Plan(NoPortals, null, null, holt.Ns, holt.Ew, yaraq.Ns, yaraq.Ew, out double estWalk, out _);
var steps = PortalRoute.Plan(NoPortals, null, hub, holt.Ns, holt.Ew, yaraq.Ns, yaraq.Ew, out double est, out int used);
Console.WriteLine($" Holtburg -> Yaraq, Town Network only: {used} teleport(s), ~{est:F0} vs {direct:F0} walking");
foreach (var s in steps) Console.WriteLine($" {(s.IsHub ? "town " : s.UsePortal ? "portal" : "walk ")} {s.Label} {NavCoords.Fmt(s.Ns, s.Ew)}");
int yx = ExitIndex(t, "Yaraq");
Check(used == 2 && steps.Count == 3, "Holtburg to Yaraq: the network (two teleports)");
Check(steps[0].UsePortal && NavCoords.Distance(steps[0].Ns, steps[0].Ew, 42.28, 33.31) < 1, "from Holtburg's Town Network portal");
Check(steps[1].IsHub && steps[1].HubExit == yx && yx >= 0, "out through the Portal to Yaraq");
Check(est < estWalk && est < 1500, $"far cheaper than walking ({est:F0} vs {estWalk:F0})");
// With the real portals too: the network is still taken (no portal chain beats it).
var all = PortalRoute.Plan(portals, null, hub, holt.Ns, holt.Ew, yaraq.Ns, yaraq.Ew, out double estAll, out _);
PortalRoute.Plan(portals, null, null, holt.Ns, holt.Ew, yaraq.Ns, yaraq.Ew, out double estPortals, out _);
Check(all.Exists(s => s.IsHub) && estAll <= estPortals + 1e-6, $"with the portals too ({estAll:F0} vs {estPortals:F0} portals only)");
// Short trips stay walks: Holtburg to a spot 1 degree away.
PortalRoute.Plan(portals, null, hub, holt.Ns, holt.Ew, holt.Ns + 1, holt.Ew, out _, out used);
Check(used == 0, "a short trip near Holtburg walks");
}
private static void RealTownNetworkLevelBlocks()
{
var (t, atlas, _) = RealTownNetData();
if (t == null || atlas == null) { Console.WriteLine(" (no generated NavData beside this repo: skipped)"); return; }
var holt = atlas.FindBest("Holtburg", false, 0, 0)!;
int ex = ExitIndex(t, "Eastwatch");
Check(ex >= 0 && t.Exits[ex].Rules.MinLevel == 80, "the Portal to Eastwatch needs level 80");
TownNetExit e = t.Exits[ex];
var hi = PortalRoute.Plan(NoPortals, null, t.Links(90, false, null), holt.Ns, holt.Ew, e.DestNs, e.DestEw, out double estHi, out _);
var notes = new List<string>();
var lo = PortalRoute.Plan(NoPortals, null, t.Links(45, false, notes), holt.Ns, holt.Ew, e.DestNs, e.DestEw, out double estLo, out _);
Console.WriteLine($" Holtburg -> Eastwatch: level 90 ~{estHi:F0} via {Describe(hi)}; level 45 ~{estLo:F0} via {Describe(lo)}");
Check(hi.Exists(s => s.IsHub && s.HubExit == ex), "level 90: through the Portal to Eastwatch");
Check(!lo.Exists(s => s.IsHub && s.HubExit == ex), "level 45: never through the Portal to Eastwatch");
Check(estLo > estHi, "...so the trip costs more");
Check(notes.Exists(n => n.Contains("Eastwatch") && n.Contains("80")), "...and the note says why");
Check(notes.Exists(n => n.Contains("Facility Hub")) == false, "the Facility Hub (in a dungeon) isn't a map exit at all");
}
// Tom, 10-01: "for Arwic, which should be simple Aphus -> Town Network -> Arwic". Recall Aphus
// Lassel lands 12 yd from a Town Network portal, so from anywhere far from a town with its own
// network portal, the plan is: cast the recall, walk into that portal, the network to Arwic.
private static void AphusRecallThenTownNetworkToArwic()
{
var (t, atlas, portals) = RealTownNetData();
if (t == null || atlas == null || portals == null) { Console.WriteLine(" (no generated NavData beside this repo: skipped)"); return; }
AtlasRecall? aphus = null;
foreach (AtlasRecall r in atlas.Recalls) if (r.SpellId == 2931) { aphus = r; break; }
Check(aphus != null && aphus.OnMap && aphus.Name == "Recall Aphus Lassel", "the Atlas has Recall Aphus Lassel (2931) on the map");
if (aphus == null) return;
// It's in RecallPlanner's list when the spellbook has it (and not when it doesn't).
var mem = new RecallMemory();
var withIt = RecallPlanner.Build(atlas, new HashSet<int> { 2931 }, mem, "Aelrynth|Lucy", null);
Check(withIt.Exists(o => o.SpellId == 2931 && o.Name == "Recall Aphus Lassel"), "a character who knows 2931 can plan with it");
Check(!RecallPlanner.Build(atlas, new HashSet<int>(), mem, "Aelrynth|Lucy", null).Exists(o => o.SpellId == 2931), "one who doesn't, can't");
var arwic = atlas.FindBest("Arwic", false, 0, 0)!;
HubLinks hub = t.Links(100, false, null);
var recalls = RecallPlanner.Links(withIt);
int arwicExit = ExitIndex(t, "Arwic");
Check(arwicExit >= 0, "the network has a Portal to Arwic");
// Starts far from any town with a Town Network portal of its own.
foreach (var (where, ns, ew) in new[] { ("the southern wilds", -65.0, 45.0), ("north of Ayan Baqur", -45.0, -80.0), ("the Direlands", 20.0, -60.0) })
{
var steps = PortalRoute.Plan(portals, recalls, hub, ns, ew, arwic.Ns, arwic.Ew, out double est, out int used);
Console.WriteLine($" {where} -> Arwic: ~{est:F0} via {Describe(steps)}");
Check(steps.Count >= 4 && steps[0].UseRecall && steps[0].Label == "Recall Aphus Lassel", $"{where}: first, cast Recall Aphus Lassel");
Check(steps.Count >= 4 && steps[1].UsePortal && NavCoords.Distance(steps[1].Ns, steps[1].Ew, aphus.Ns, aphus.Ew) < 30,
$"{where}: then walk the few yards into the Town Network portal beside its landing");
Check(steps.Count >= 4 && steps[2].IsHub && steps[2].HubExit == arwicExit, $"{where}: then the network's Portal to Arwic");
Check(est < 2000, $"{where}: all for about {est:F0} (a recall, two portals and short walks)");
}
// In a town with its own network portal, walking to that one is cheaper than the recall.
var yaraq = atlas.FindBest("Yaraq", false, 0, 0)!;
var fromYaraq = PortalRoute.Plan(portals, recalls, hub, yaraq.Ns, yaraq.Ew, arwic.Ns, arwic.Ew, out _, out _);
Check(fromYaraq.Count >= 2 && !fromYaraq[0].UseRecall && fromYaraq[0].UsePortal && fromYaraq[1].IsHub && fromYaraq[1].HubExit == arwicExit,
$"from Yaraq: its own network portal, no recall needed ({Describe(fromYaraq)})");
}
private static string Describe(List<RouteStep> steps)
{
var parts = new List<string>();
foreach (var s in steps) parts.Add(s.UseRecall ? "recall:" + s.Label : s.IsHub ? "town:" + s.Label : s.UsePortal ? "portal:" + s.Label : "walk");
return string.Join(" > ", parts);
}
private static void RealTownNetworkWays()
{
var (t, _, _) = RealTownNetData();
if (t == null) { Console.WriteLine(" (no generated NavData beside this repo: skipped)"); return; }
int yx = ExitIndex(t, "Yaraq");
TownNetArrival a1 = t.Arrivals[0];
var way = t.WayTo(yx, a1.X, a1.Y, HubWalker.OffRouteUnits, out string from);
Check(way != null && from == "A1", "standing on A1: A1's walk");
TownNetWalk w = t.Walk(0, yx)!;
Check(way != null && way.Count == w.Points.Length && Math.Abs(way[^1].X - t.Exits[yx].X) < 0.05 && Math.Abs(way[^1].Y - t.Exits[yx].Y) < 0.05, "it ends on the exit's centre");
Near(TownNet.PathLength(way!, 0), w.Length, 0.05, "and is as long as the stored walk");
Check(t.ArrivalNear(a1.X + 2, a1.Y) == 0 && t.ArrivalNear(a1.X + 4, a1.Y) == -1, "an arrival counts within 3 m");
// Off every arrival, 1 m beside the middle of a walk: joined there.
TownNetPoint p0 = w.Points[1], p1 = w.Points[2];
double mx = (p0.X + p1.X) / 2, my = (p0.Y + p1.Y) / 2, dx = p1.X - p0.X, dy = p1.Y - p0.Y, len = Math.Sqrt(dx * dx + dy * dy);
var joined = t.WayTo(yx, mx - dy / len, my + dx / len, HubWalker.OffRouteUnits, out from);
Check(joined != null && from.StartsWith("the nearest walk") && Math.Abs(joined[^1].X - t.Exits[yx].X) < 0.05
&& Math.Abs(joined[0].X - (mx - dy / len)) < 1e-9, "beside a walk: starts where you stand and joins it (" + from + ")");
Check(t.WayTo(yx, 500, 500, HubWalker.OffRouteUnits, out _) == null, "far from every walk: none");
// Every walk is sound for the walker: at least 2 points, ends on its exit, no zero-length jump.
int bad = 0;
foreach (TownNetWalk x in t.Walks)
if (x.Points.Length < 2 || Math.Abs(x.Points[^1].X - t.Exits[x.Exit].X) > 0.05 || Math.Abs(x.Points[^1].Y - t.Exits[x.Exit].Y) > 0.05) bad++;
Check(bad == 0, $"all {t.Walks.Count} walks end on their exit");
}
// ── The walker inside: ideal movement over the real walks ────────────────
private const double RunMetresPerTick = 10.0 / 30.0; // ~10 m/s at 30 ticks a second
private const long TickMs = 33;
/// <summary>
/// Runs a HubWalker over a way with ideal movement. Returns when it would touch the exit portal
/// (its reach plus the body, as the server checks) once the cooldown allows, or when it stops.
/// </summary>
private static (HubWalker.Act Last, long TouchMs, double MaxOff, int Holds, string Why) Simulate(List<TownNetPoint> way, long landMs,
Func<long, (double dx, double dy)>? shove = null, bool portalFires = true, int maxTicks = 3000)
{
var walker = new HubWalker(way, landMs, 0);
double x = way[0].X, y = way[0].Y, maxOff = 0;
int holds = 0;
for (int i = 0; i < maxTicks; i++)
{
long now = i * TickMs;
if (shove != null) { var (sx, sy) = shove(now); x += sx; y += sy; }
double dExit = Math.Sqrt((way[^1].X - x) * (way[^1].X - x) + (way[^1].Y - y) * (way[^1].Y - y));
if (portalFires && dExit < 1.36 + 0.48 && now - landMs >= 3500) return (HubWalker.Act.Run, now, maxOff, holds, "");
if (dExit < 1.36 + 0.48 && now - landMs < 3500 && portalFires)
return (HubWalker.Act.Stop, now, maxOff, holds, "touched the portal inside the cooldown");
var act = walker.Step(x, y, now, out double heading, out string why);
if (act == HubWalker.Act.Stop || act == HubWalker.Act.NoTeleport) return (act, now, maxOff, holds, why);
if (act == HubWalker.Act.Hold) { holds++; continue; }
double h = heading * Math.PI / 180.0;
x += Math.Sin(h) * RunMetresPerTick; y += Math.Cos(h) * RunMetresPerTick;
double off = double.MaxValue;
for (int k = 1; k < way.Count; k++) off = Math.Min(off, TownNet.SegmentDistance(x, y, way[k - 1], way[k], out _));
maxOff = Math.Max(maxOff, off);
}
return (HubWalker.Act.Stop, -1, maxOff, holds, "ran out of ticks");
}
private static void HubWalkerFollowsTheWalk()
{
var (t, _, _) = RealTownNetData();
if (t == null) { Console.WriteLine(" (no generated NavData beside this repo: skipped)"); return; }
int touched = 0, early = 0, waited = 0, worst = 0, tight = 0;
double worstOff = 0, slowest = 0, worstOverSpare = double.MinValue;
foreach (TownNetWalk w in t.Walks)
{
TownNetArrival a = t.Arrivals[w.Arrival];
var way = t.WayTo(w.Exit, a.X, a.Y, HubWalker.OffRouteUnits, out _)!;
var r = Simulate(way, 0);
if (r.Last == HubWalker.Act.Run && r.TouchMs >= 0) touched++;
else { early++; if (early <= 3) Console.WriteLine($" {a.Id} -> {t.Exits[w.Exit].Name}: {r.Why}"); }
if (r.Holds > 0) waited++;
if (r.MaxOff > worstOff) { worstOff = r.MaxOff; worst = t.Walks.IndexOf(w); }
// The walks were checked for a 0.48 m body: their spare room is MinClear - 0.48.
double spare = w.MinClear - 0.48;
if (w.MinClear > 0 && r.MaxOff > spare) tight++;
if (w.MinClear > 0) worstOverSpare = Math.Max(worstOverSpare, r.MaxOff - spare);
slowest = Math.Max(slowest, r.TouchMs / 1000.0);
}
Console.WriteLine($" {touched}/{t.Walks.Count} walks reach their exit after the cooldown; {waited} held for it; slowest {slowest:F1} s; widest {worstOff:F2} m off the line; {tight} walk(s) stray past their tightest spare room (by up to {worstOverSpare:F2} m)");
Check(touched == t.Walks.Count && early == 0, "every walk reaches its exit portal, never inside the 3.5 s cooldown");
Check(waited > 0, "short walks hold for the cooldown");
// Ideal movement steps ~0.33 m a tick, so a sharp corner can be overshot by part of a step.
Check(worstOff < 0.25, $"never more than a quarter metre off the line ({worstOff:F3} m)");
}
private static void HubWalkerStops()
{
var (t, _, _) = RealTownNetData();
if (t == null) { Console.WriteLine(" (no generated NavData beside this repo: skipped)"); return; }
TownNetWalk w = t.Walks[0];
TownNetArrival a = t.Arrivals[w.Arrival];
var way = t.WayTo(w.Exit, a.X, a.Y, HubWalker.OffRouteUnits, out _)!;
// Held in place (a wall, a monster): stuck after 3 s, with where.
var walker = new HubWalker(way, -10000, 0);
HubWalker.Act act = HubWalker.Act.Run;
string why = "";
long stoppedAt = -1;
for (int i = 0; i < 300 && act != HubWalker.Act.Stop; i++) { act = walker.Step(way[0].X, way[0].Y, i * TickMs, out _, out why); stoppedAt = i * TickMs; }
Check(act == HubWalker.Act.Stop && why.StartsWith("stuck near"), "standing still: stuck (" + why + ")");
Check(stoppedAt >= HubWalker.StuckMs && stoppedAt <= HubWalker.StuckMs + 200, $"after {HubWalker.StuckMs / 1000} s ({stoppedAt} ms)");
// Knocked 8 m off the way: stops.
walker = new HubWalker(way, -10000, 0);
TownNetPoint p = way[1];
act = walker.Step(p.X + 8, p.Y + 8, 0, out _, out why);
Check(act == HubWalker.Act.Stop && why.Contains("off the way"), "8 m off the way: stops (" + why + ")");
// 3 m off: steers back toward the line.
walker = new HubWalker(way, -10000, 0);
TownNetPoint s0 = way[0], s1 = way[1];
double dx = s1.X - s0.X, dy = s1.Y - s0.Y, len = Math.Sqrt(dx * dx + dy * dy);
double ox = s0.X + dx / len * 2 - dy / len * 3, oy = s0.Y + dy / len * 2 + dx / len * 3;
walker.Step(ox, oy, 0, out double heading, out _);
double h = heading * Math.PI / 180.0;
double nx = ox + Math.Sin(h), ny = oy + Math.Cos(h);
Check(TownNet.SegmentDistance(nx, ny, s0, s1, out _) < TownNet.SegmentDistance(ox, oy, s0, s1, out _) - 0.5, "3 m off: heads back to the line");
// The portal never fires: holds on its centre, backs off, walks in once more, then gives up.
var r = Simulate(way, -10000, portalFires: false);
Check(r.Last == HubWalker.Act.NoTeleport, "a portal that doesn't take you: stops after one more try (" + r.Last + " " + r.Why + ")");
Check(r.TouchMs > 2 * HubWalker.TouchWaitMs, "after waiting on it twice");
// Too long in all: the limit.
walker = new HubWalker(way, -10000, 0);
act = walker.Step(way[0].X, way[0].Y, walker.LimitMs + 1, out _, out why);
Check(act == HubWalker.Act.Stop && why.Contains("too long"), "the overall limit (" + why + ")");
Check(walker.LimitMs >= (long)((walker.Length / 3 + 10) * 1000), "limit: length / 3 + 10 s at least");
}
}

View file

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthNav;
using RynthNav.Routing;
namespace RynthNav.RouteTests;
// Bug 5 (10-01): in a dungeon the panel planned from "0,0" and walked to a portal at 86S; and the
// Route button planned with portals while "Use portals and recalls" was off.
internal static partial class Program
{
private static void RunTravelPlan()
{
Run(nameof(DungeonStartBeginsWithARecall), DungeonStartBeginsWithARecall);
Run(nameof(DungeonStartRefusals), DungeonStartRefusals);
Run(nameof(PortalsOffMeansWalkingOnly), PortalsOffMeansWalkingOnly);
Run(nameof(RecallsSwitch), RecallsSwitch);
}
private static readonly List<PortalLink> NearPortal = new() { new(0.1, 0, 39.9, 40, "Handy Portal") };
private static readonly List<RecallLink> OneRecall = new() { new(39.5, 39.5, "Some Recall", PortalRoute.RecallCostUnits(5)) };
private static void DungeonStartBeginsWithARecall()
{
// A dungeon's coordinates look like 0,0 on the map: right beside "Handy Portal". It must
// not walk there; it recalls out.
var r = TravelPlan.Plan(NearPortal, OneRecall, null, true, true, startOnMap: false, 0, 0, 40, 40, null, null, "Goal");
Check(r.Refusal == "" && r.Steps != null && r.Steps.Count >= 1 && r.Steps[0].UseRecall, "in a dungeon the route starts with a recall");
Check(r.Steps != null && !r.Steps.Exists(s => s.UsePortal && s.Label == "Handy Portal"), "never a walk from the dungeon to a portal");
// The real data: in a dungeon, knowing Recall Aphus Lassel, to Arwic.
var (t, atlas, portals) = RealTownNetData();
if (t == null || atlas == null || portals == null) { Console.WriteLine(" (no generated NavData beside this repo: real part skipped)"); return; }
var arwic = atlas.FindBest("Arwic", false, 0, 0)!;
var recalls = RecallPlanner.Links(RecallPlanner.Build(atlas, new HashSet<int> { 2931, RecallPlanner.LifestoneRecall }, new RecallMemory(), "Aelrynth|Lucy", null));
var real = TravelPlan.Plan(portals, recalls, t.Links(100, false, null), true, true, startOnMap: false, -86.2, -0.7, arwic.Ns, arwic.Ew, null, null, "Arwic");
Console.WriteLine($" in a dungeon -> Arwic: ~{real.Est:F0} via {(real.Steps == null ? "walk" : Describe(real.Steps))}");
Check(real.Steps != null && real.Steps.Count >= 3 && real.Steps[0].UseRecall && real.Steps[0].Label == "Recall Aphus Lassel"
&& real.Steps[1].UsePortal && real.Steps[2].IsHub && real.Steps[2].HubExit == ExitIndex(t, "Arwic"),
"from a dungeon: Recall Aphus Lassel, the Town Network portal beside it, the Portal to Arwic");
}
private static void DungeonStartRefusals()
{
var off = TravelPlan.Plan(NearPortal, OneRecall, null, false, true, startOnMap: false, 0, 0, 40, 40, null, null, "Goal");
Check(off.Steps == null && off.Refusal.Contains("dungeon") && off.Refusal.Contains("Use portals and recalls"), "portals off: refuses, says to turn them on (" + off.Refusal + ")");
var noRecalls = TravelPlan.Plan(NearPortal, OneRecall, null, true, false, startOnMap: false, 0, 0, 40, 40, null, null, "Goal");
Check(noRecalls.Steps == null && noRecalls.Refusal.Contains("turn on Recalls"), "recalls off: refuses, says to turn Recalls on (" + noRecalls.Refusal + ")");
var none = TravelPlan.Plan(NearPortal, new List<RecallLink>(), null, true, true, startOnMap: false, 0, 0, 40, 40, null, null, "Goal");
Check(none.Steps == null && none.Refusal.Contains("no recall"), "no recall ready: refuses (" + none.Refusal + ")");
}
private static void PortalsOffMeansWalkingOnly()
{
// The portal would save a lot; with the switch off the plan still walks.
var on = TravelPlan.Plan(NearPortal, OneRecall, null, true, true, true, 0, 0, 40, 40, null, true, "Goal");
Check(on.Steps != null && on.Teleports > 0, "switch on: the portal (or recall) is used");
var off = TravelPlan.Plan(NearPortal, OneRecall, null, false, true, true, 0, 0, 40, 40, null, true, "Goal");
Check(off.Steps == null && off.Teleports == 0 && off.Refusal == "", "switch off: walking only, no portal or recall steps");
Check(Math.Abs(off.Est - NavCoords.Distance(0, 0, 40, 40)) < 1e-6, "its cost is the walk");
// Off, and the target is across water: say so instead of walking into the sea.
var island = TravelPlan.Plan(NearPortal, OneRecall, null, false, true, true, 0, 0, 40, 40, null, false, "Goal");
Check(island.Steps == null && island.Refusal.Contains("another landmass") && island.Refusal.Contains("Use portals and recalls"), "off, across water: refuses with the switch to turn on");
}
private static void RecallsSwitch()
{
var recallOnly = new List<PortalLink>();
var withRecalls = TravelPlan.Plan(recallOnly, OneRecall, null, true, true, true, 0, 0, 40, 40, null, true, "Goal");
Check(withRecalls.Steps != null && withRecalls.Steps[0].UseRecall, "Recalls on: the recall is used");
var noRecalls = TravelPlan.Plan(recallOnly, OneRecall, null, true, false, true, 0, 0, 40, 40, null, true, "Goal");
Check(noRecalls.Steps == null && noRecalls.Refusal == "", "Recalls off: walks (no recall step)");
var portalsStill = TravelPlan.Plan(NearPortal, OneRecall, null, true, false, true, 0, 0, 40, 40, null, true, "Goal");
Check(portalsStill.Steps != null && !portalsStill.Steps.Exists(s => s.UseRecall) && portalsStill.Steps.Exists(s => s.UsePortal), "Recalls off: portals still used");
}
}