RynthSuite as of 2026-11-08 (internal 6ec9b64): release 2026.11.8.1
This commit is contained in:
parent
7166d256ce
commit
f8fa62b64c
196 changed files with 24980 additions and 633 deletions
44
Plugins/RynthCore.Plugin.RynthNav/AreaFilter.cs
Normal file
44
Plugins/RynthCore.Plugin.RynthNav/AreaFilter.cs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
using System;
|
||||
using DotRecast.Core.Numerics;
|
||||
using DotRecast.Detour;
|
||||
|
||||
namespace RynthNav.Routing;
|
||||
|
||||
/// <summary>
|
||||
/// Another filter (the portal one, AvoidFilter), minus every polygon whose middle lies in ground to
|
||||
/// keep off (<see cref="Inside"/>: a building's outline, BuildingOutlines), so the route maker's legs go
|
||||
/// round buildings rather than through their rooms. The start's and the goal's polygons are always
|
||||
/// allowed. TilePathFinder plans with it first and without it when there is no way round. Only the
|
||||
/// middle: leaving out every polygon with a corner inside an outline (tried 2026-10-30) also left out
|
||||
/// big open-ground polygons that reach under a roof's eaves (an outline is the whole model's hull), and
|
||||
/// the real loops by Holtburg walked further for it and no less inside buildings; by the middle, the
|
||||
/// loop in town kept every leg outside (0 yd inside, 51 yd without it) and a shorter lap. One worker
|
||||
/// only (it keeps the last start and goal).
|
||||
/// </summary>
|
||||
internal sealed class AreaFilter : IDtQueryFilter
|
||||
{
|
||||
private readonly IDtQueryFilter _inner;
|
||||
public Func<double, double, bool>? Inside;
|
||||
public long AllowA, AllowB;
|
||||
|
||||
public AreaFilter(IDtQueryFilter inner) { _inner = inner; }
|
||||
|
||||
public bool PassFilter(long refs, DtMeshTile tile, DtPoly poly)
|
||||
{
|
||||
if (!_inner.PassFilter(refs, tile, poly)) return false;
|
||||
if (Inside == null || refs == AllowA || refs == AllowB || poly.vertCount == 0) return true;
|
||||
float[] v = tile.data.verts;
|
||||
double x = 0, y = 0;
|
||||
for (int i = 0; i < poly.vertCount; i++)
|
||||
{
|
||||
int k = poly.verts[i] * 3;
|
||||
x += v[k];
|
||||
y += v[k + 2];
|
||||
}
|
||||
return !Inside(x / poly.vertCount, y / poly.vertCount);
|
||||
}
|
||||
|
||||
public float GetCost(RcVec3f pa, RcVec3f pb, long prevRef, DtMeshTile prevTile, DtPoly prevPoly,
|
||||
long curRef, DtMeshTile curTile, DtPoly curPoly, long nextRef, DtMeshTile nextTile, DtPoly nextPoly)
|
||||
=> _inner.GetCost(pa, pb, prevRef, prevTile, prevPoly, curRef, curTile, curPoly, nextRef, nextTile, nextPoly);
|
||||
}
|
||||
146
Plugins/RynthCore.Plugin.RynthNav/BuildingOutlines.cs
Normal file
146
Plugins/RynthCore.Plugin.RynthNav/BuildingOutlines.cs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// The ground outlines of Dereth's buildings, from NavData\worldmap.vec (RynthNav.Baker
|
||||
/// --map-vectors; the engine's World Map draws the same file): each building's convex outline, in
|
||||
/// world units. A building's cells are walkable on the landscape navmesh (the baker includes their
|
||||
/// floors), so the route maker keeps a hunting loop's points out of these outlines, and its legs off
|
||||
/// their floors where there is another way. Read once (on a worker), then never changed: any thread
|
||||
/// may ask. Host-free: the route tests read a made-up file.
|
||||
///
|
||||
/// File (little-endian): "RVEC", u32 version (1), u32 building count, u32 road segment count; per
|
||||
/// building a u8 corner count, then that many (f32 x, f32 y) in map cells (24 yards; x east, y north,
|
||||
/// from the map's south-west corner); the road segments follow (not read here).
|
||||
/// </summary>
|
||||
internal sealed class BuildingOutlines
|
||||
{
|
||||
public const string FileName = "worldmap.vec";
|
||||
private const double CellUnits = 24.0;
|
||||
/// <summary>The widest margin <see cref="Inside"/> is asked for: buildings are filed under every landblock this near.</summary>
|
||||
public const double MaxMargin = 12.0;
|
||||
|
||||
private readonly double[][] _xs, _ys;
|
||||
private readonly double[] _minX, _minY, _maxX, _maxY;
|
||||
private readonly Dictionary<uint, List<int>> _byLandblock = new();
|
||||
|
||||
public int Count => _xs.Length;
|
||||
|
||||
private BuildingOutlines(List<(double X, double Y)[]> polys)
|
||||
{
|
||||
int n = polys.Count;
|
||||
_xs = new double[n][]; _ys = new double[n][];
|
||||
_minX = new double[n]; _minY = new double[n]; _maxX = new double[n]; _maxY = new double[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var p = polys[i];
|
||||
_xs[i] = new double[p.Length]; _ys[i] = new double[p.Length];
|
||||
double x0 = double.MaxValue, y0 = double.MaxValue, x1 = double.MinValue, y1 = double.MinValue;
|
||||
for (int k = 0; k < p.Length; k++)
|
||||
{
|
||||
_xs[i][k] = p[k].X; _ys[i][k] = p[k].Y;
|
||||
x0 = Math.Min(x0, p[k].X); y0 = Math.Min(y0, p[k].Y); x1 = Math.Max(x1, p[k].X); y1 = Math.Max(y1, p[k].Y);
|
||||
}
|
||||
_minX[i] = x0; _minY[i] = y0; _maxX[i] = x1; _maxY[i] = y1;
|
||||
int lx0 = Lb(x0 - MaxMargin), lx1 = Lb(x1 + MaxMargin), ly0 = Lb(y0 - MaxMargin), ly1 = Lb(y1 + MaxMargin);
|
||||
for (int x = lx0; x <= lx1; x++)
|
||||
for (int y = ly0; y <= ly1; y++)
|
||||
{
|
||||
uint lb = (uint)((x << 8) | y);
|
||||
if (!_byLandblock.TryGetValue(lb, out List<int>? list)) _byLandblock[lb] = list = new List<int>();
|
||||
list.Add(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int Lb(double world) => (int)Math.Clamp(Math.Floor(world / 192.0), 0, 255);
|
||||
|
||||
/// <summary>Outlines given in world units (the tests).</summary>
|
||||
public static BuildingOutlines FromPolygons(IEnumerable<(double X, double Y)[]> polys)
|
||||
{
|
||||
var list = new List<(double X, double Y)[]>();
|
||||
foreach (var p in polys) if (p.Length >= 3) list.Add(p);
|
||||
return new BuildingOutlines(list);
|
||||
}
|
||||
|
||||
/// <summary>The file at <paramref name="path"/>; null when it isn't there or isn't one (the caller says so).</summary>
|
||||
public static BuildingOutlines? Load(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path)) return null;
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
return Read(fs);
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
/// <summary>Reads the buildings of a worldmap.vec stream. Throws InvalidDataException on a file that isn't one.</summary>
|
||||
public static BuildingOutlines Read(Stream s)
|
||||
{
|
||||
using var r = new BinaryReader(s, System.Text.Encoding.ASCII, leaveOpen: true);
|
||||
if (r.ReadUInt32() != 0x4345_5652u) throw new InvalidDataException("not a vector file"); // "RVEC"
|
||||
if (r.ReadUInt32() != 1u) throw new InvalidDataException("a newer vector file version");
|
||||
uint buildings = r.ReadUInt32();
|
||||
r.ReadUInt32(); // road segments: not needed
|
||||
if (buildings > 200_000) throw new InvalidDataException("too many buildings");
|
||||
var polys = new List<(double X, double Y)[]>((int)buildings);
|
||||
for (uint b = 0; b < buildings; b++)
|
||||
{
|
||||
int n = r.ReadByte();
|
||||
var p = new (double X, double Y)[n];
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
float x = r.ReadSingle(), y = r.ReadSingle();
|
||||
p[k] = (x * CellUnits, y * CellUnits);
|
||||
}
|
||||
bool finite = true;
|
||||
foreach (var (x, y) in p) finite &= double.IsFinite(x) && double.IsFinite(y);
|
||||
if (n >= 3 && finite) polys.Add(p);
|
||||
}
|
||||
return new BuildingOutlines(polys);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The building whose outline holds (x, y), or comes within <paramref name="margin"/> yards of it
|
||||
/// (at most <see cref="MaxMargin"/>); -1 when none does.
|
||||
/// </summary>
|
||||
public int Inside(double x, double y, double margin = 0)
|
||||
{
|
||||
margin = Math.Clamp(margin, 0, MaxMargin);
|
||||
if (x < 0 || y < 0) return -1;
|
||||
uint lb = (uint)((Lb(x) << 8) | Lb(y));
|
||||
if (!_byLandblock.TryGetValue(lb, out List<int>? list)) return -1;
|
||||
foreach (int i in list)
|
||||
{
|
||||
if (x < _minX[i] - margin || x > _maxX[i] + margin || y < _minY[i] - margin || y > _maxY[i] + margin) continue;
|
||||
if (PointInPolygon(x, y, _xs[i], _ys[i])) return i;
|
||||
if (margin > 0)
|
||||
{
|
||||
double[] xs = _xs[i], ys = _ys[i];
|
||||
for (int a = 0, b = xs.Length - 1; a < xs.Length; b = a++)
|
||||
if (SegmentDistance(x, y, xs[b], ys[b], xs[a], ys[a]) < margin) return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static bool PointInPolygon(double x, double y, double[] xs, double[] ys)
|
||||
{
|
||||
bool inside = false;
|
||||
for (int i = 0, j = xs.Length - 1; i < xs.Length; j = i++)
|
||||
if ((ys[i] > y) != (ys[j] > y) && x < (xs[j] - xs[i]) * (y - ys[i]) / (ys[j] - ys[i]) + xs[i]) inside = !inside;
|
||||
return inside;
|
||||
}
|
||||
|
||||
private static double SegmentDistance(double x, double y, double ax, double ay, double bx, double by)
|
||||
{
|
||||
double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy;
|
||||
double t = l2 < 1e-12 ? 0 : Math.Clamp(((x - ax) * dx + (y - ay) * dy) / l2, 0, 1);
|
||||
double px = ax + dx * t - x, py = ay + dy * t - y;
|
||||
return Math.Sqrt(px * px + py * py);
|
||||
}
|
||||
}
|
||||
252
Plugins/RynthCore.Plugin.RynthNav/LoopMaker.cs
Normal file
252
Plugins/RynthCore.Plugin.RynthNav/LoopMaker.cs
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// The route maker's walks on the navmesh (/rnav makeloop and makepath, the "RynthNav.Routes"
|
||||
/// interface), worked out on a worker in a TilePathFinder of its own, never the walker's navmesh.
|
||||
///
|
||||
/// A hunting loop round a centre (<see cref="Loop"/>):
|
||||
/// 1. the ground at the centre;
|
||||
/// 2. per point, a direction round the circle (north first, clockwise); in it, the first spot (out
|
||||
/// at the radius, then nearer, then a little to either side) that is walkable ground, out of every
|
||||
/// building's outline (+ <see cref="LoopOptions.BuildingMargin"/>), at least
|
||||
/// <see cref="LoopOptions.PortalKeep"/> from every portal, <see cref="LoopOptions.MinWall"/> from the
|
||||
/// navmesh's edge, apart from the points already chosen, and reached from the centre by a walk that
|
||||
/// never enters a portal's circle and isn't the long way round. A direction with no such spot is
|
||||
/// dropped, with the reason;
|
||||
/// 3. the points in walking order (RouteShape.OrderLoop: round the centre, no two legs crossing);
|
||||
/// 4. each point joined to the next, the last back to the first, by a walk that keeps out of every
|
||||
/// portal's circle (strict: there is no fallback through one), pushed off walls by the wall
|
||||
/// clearance, and round buildings where there is a way. A leg that can't be walked, or only far
|
||||
/// the long way round, drops its far point and the next point is tried; fewer than three left is
|
||||
/// a failure;
|
||||
/// 5. the legs as a circular nav route (RouteShape.Assemble).
|
||||
/// A path through given points (<see cref="Path"/>): each point onto the ground within
|
||||
/// <see cref="SnapUnits"/>, each leg walked (the route graph for long ones), any leg that can't be is a
|
||||
/// failure naming it; loop, line or once.
|
||||
/// Host-free (Detour only): the graph tests make loops and paths on baked floors and on the real map.
|
||||
/// </summary>
|
||||
internal static class LoopMaker
|
||||
{
|
||||
/// <summary>A makepath point must have walkable ground within this many yards.</summary>
|
||||
public const double SnapUnits = 12.0;
|
||||
|
||||
internal sealed class LoopOptions
|
||||
{
|
||||
public double Radius;
|
||||
public int Points;
|
||||
/// <summary>A point at least this far (yards) from any portal: a fight beside one ends in it.</summary>
|
||||
public double PortalKeep = 20.0;
|
||||
/// <summary>A point at least this far outside every building's outline.</summary>
|
||||
public double BuildingMargin = 3.0;
|
||||
/// <summary>A point at least this far from the navmesh's edge (a wall, a drop, water).</summary>
|
||||
public double MinWall = 2.0;
|
||||
/// <summary>Corners pushed this far off walls (RynthNav's "walls" avoid setting; 0 = off).</summary>
|
||||
public double WallClearance;
|
||||
/// <summary>Legs kept off building floors where there's another way (the points always are).</summary>
|
||||
public bool LegsRoundBuildings = true;
|
||||
public double Spacing = RouteShape.LoopSpacing;
|
||||
}
|
||||
|
||||
internal sealed class Dropped
|
||||
{
|
||||
public double Ns, Ew;
|
||||
public string Why = "";
|
||||
}
|
||||
|
||||
internal sealed class Result
|
||||
{
|
||||
public bool Ok;
|
||||
public string Error = "";
|
||||
public WorldPt Centre;
|
||||
/// <summary>The points kept, in walking order (the snapped ground).</summary>
|
||||
public readonly List<WorldPt> Points = new();
|
||||
public readonly List<Dropped> DroppedPoints = new();
|
||||
public readonly List<List<WorldPt>> Legs = new();
|
||||
public NavRouteParser? Route;
|
||||
public double Yards;
|
||||
/// <summary>Things worth saying that didn't stop it ("no building outlines"...).</summary>
|
||||
public readonly List<string> Notes = new();
|
||||
public int Asked;
|
||||
|
||||
public Result Fail(string why) { Ok = false; Error = why; Route = null; return this; }
|
||||
}
|
||||
|
||||
private static string At(WorldPt p) => NavCoords.Fmt(p.Ns, p.Ew);
|
||||
|
||||
/// <summary>The nearest of <paramref name="portals"/> to (x, y), and how far; -1 = none.</summary>
|
||||
private static int NearestPortal(IReadOnlyList<PortalAvoid.Spot> portals, double x, double y, out double dist)
|
||||
{
|
||||
int best = -1; dist = double.MaxValue;
|
||||
for (int i = 0; i < portals.Count; i++)
|
||||
{
|
||||
double d = Math.Sqrt((portals[i].X - x) * (portals[i].X - x) + (portals[i].Y - y) * (portals[i].Y - y));
|
||||
if (d < dist) { dist = d; best = i; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static double Length(IReadOnlyList<WorldPt> pts)
|
||||
{
|
||||
double d = 0;
|
||||
for (int i = 1; i < pts.Count; i++) d += pts[i - 1].FlatDistance(pts[i]);
|
||||
return d;
|
||||
}
|
||||
|
||||
/// <summary>A leg this much longer than the straight line is the long way round: its far point goes.</summary>
|
||||
private static bool TooLong(double walked, double straight, double radius) =>
|
||||
walked > Math.Max(2.5 * straight + 40.0, straight + radius);
|
||||
|
||||
/// <summary>
|
||||
/// A hunting loop round <paramref name="centre"/> (its height NaN when not known) on
|
||||
/// <paramref name="mesh"/>, keeping out of <paramref name="buildings"/> (null: no outlines) and away
|
||||
/// from <paramref name="portals"/> (the Atlas's and the live ones, as circles of their avoid radius).
|
||||
/// The mesh's options are set here.
|
||||
/// </summary>
|
||||
public static Result Loop(TilePathFinder mesh, WorldPt centre, LoopOptions o, BuildingOutlines? buildings,
|
||||
IReadOnlyList<PortalAvoid.Spot> portals)
|
||||
{
|
||||
var r = new Result { Centre = centre };
|
||||
double R = o.Radius;
|
||||
int n = o.Points > 0 ? o.Points : RouteShape.DefaultPoints(R);
|
||||
r.Asked = n;
|
||||
mesh.StrictPortals = true;
|
||||
mesh.NoGaps = true;
|
||||
mesh.WallClearance = o.WallClearance;
|
||||
mesh.AvoidArea = buildings == null || !o.LegsRoundBuildings ? null : (x, y) => buildings.Inside(x, y) >= 0;
|
||||
if (buildings == null) r.Notes.Add("no building outlines (NavData\\worldmap.vec): points were only kept off walls");
|
||||
|
||||
if (!mesh.LoadArea(centre.X - R - 30, centre.Y - R - 30, centre.X + R + 30, centre.Y + R + 30))
|
||||
return r.Fail($"no navmesh round {At(centre)} (its tiles aren't in NavData)");
|
||||
if (!mesh.Snap(centre, 16, out WorldPt c, out _))
|
||||
return r.Fail($"no walkable ground within 16 yd of {At(centre)}");
|
||||
r.Centre = c;
|
||||
|
||||
// 2. A point per direction.
|
||||
var chosen = new List<WorldPt>();
|
||||
double minApart = Math.Max(10.0, R * 0.25);
|
||||
double sector = 2 * Math.PI / n;
|
||||
double[] reaches = { 1.0, 0.85, 0.7, 0.55, 0.4 };
|
||||
double[] turns = { 0, 0.3, -0.3 };
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
string why = "";
|
||||
int whyRank = -1;
|
||||
void Reason(int rank, string text) { if (rank > whyRank) { whyRank = rank; why = text; } }
|
||||
bool found = false;
|
||||
foreach (double f in reaches)
|
||||
{
|
||||
foreach (double turn in turns)
|
||||
{
|
||||
double a = k * sector + turn * sector;
|
||||
var want = new WorldPt(c.X + Math.Sin(a) * R * f, c.Y + Math.Cos(a) * R * f, c.H);
|
||||
if (!mesh.Snap(want, 6, out WorldPt g, out long poly)) { Reason(0, "no walkable ground there (water, a cliff, a building's wall)"); continue; }
|
||||
if (buildings != null && buildings.Inside(g.X, g.Y, o.BuildingMargin) >= 0) { Reason(1, "in a building"); continue; }
|
||||
int pi = NearestPortal(portals, g.X, g.Y, out double pd);
|
||||
if (pi >= 0 && pd < o.PortalKeep) { Reason(2, $"{pd:F0} yd from the portal {(portals[pi].Name.Length > 0 ? portals[pi].Name : "there")}"); continue; }
|
||||
if (mesh.WallDistance(g, poly, o.MinWall) < o.MinWall) { Reason(1, "against a wall or a drop"); continue; }
|
||||
bool crowded = false;
|
||||
foreach (WorldPt p in chosen) crowded |= p.FlatDistance(g) < minApart;
|
||||
if (crowded) { Reason(1, "too near another point"); continue; }
|
||||
List<WorldPt>? walk = mesh.Leg(c, g, out string note);
|
||||
if (walk == null) { Reason(3, "not reachable from the centre" + (note.Length > 0 ? $" ({note})" : "")); continue; }
|
||||
double len = Length(walk);
|
||||
if (len > 4 * R + 60) { Reason(3, $"only reachable the long way round ({len:F0} yd from the centre)"); continue; }
|
||||
chosen.Add(g);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
if (found) break;
|
||||
}
|
||||
if (!found)
|
||||
{
|
||||
double a0 = k * sector;
|
||||
var spot = new WorldPt(c.X + Math.Sin(a0) * R, c.Y + Math.Cos(a0) * R, double.NaN);
|
||||
r.DroppedPoints.Add(new Dropped { Ns = spot.Ns, Ew = spot.Ew, Why = why.Length > 0 ? why : "no ground there" });
|
||||
}
|
||||
}
|
||||
if (chosen.Count < RouteLimits.MinLoopPoints)
|
||||
return r.Fail($"only {chosen.Count} of {n} points could be placed round {At(c)} within {R:F0} yd"
|
||||
+ (r.DroppedPoints.Count > 0 ? $" ({r.DroppedPoints[0].Why})" : "") + "; try another centre or radius");
|
||||
|
||||
// 3. Walking order.
|
||||
int[] order = RouteShape.OrderLoop(chosen, c);
|
||||
var pts = new List<WorldPt>(order.Length);
|
||||
foreach (int i in order) pts.Add(chosen[i]);
|
||||
|
||||
// 4. Join them.
|
||||
var legs = new List<List<WorldPt>>();
|
||||
int at = 0;
|
||||
while (at < pts.Count)
|
||||
{
|
||||
if (pts.Count < RouteLimits.MinLoopPoints)
|
||||
return r.Fail($"only {pts.Count} points could be joined into a loop round {At(c)}"
|
||||
+ (r.DroppedPoints.Count > 0 ? $" ({r.DroppedPoints[^1].Why})" : ""));
|
||||
int next = (at + 1) % pts.Count;
|
||||
List<WorldPt>? leg = mesh.Leg(pts[at], pts[next], out string note);
|
||||
double straight = pts[at].FlatDistance(pts[next]);
|
||||
string why = leg == null ? (note.Length > 0 ? note : "no walk to it")
|
||||
: TooLong(Length(leg), straight, R) ? $"the walk to it is {Length(leg):F0} yd, the long way round" : "";
|
||||
if (why.Length == 0) { legs.Add(leg!); at++; continue; }
|
||||
// Drop the far point; the closing leg (back to the first) drops the last one instead.
|
||||
int drop = next == 0 ? at : next;
|
||||
r.DroppedPoints.Add(new Dropped { Ns = pts[drop].Ns, Ew = pts[drop].Ew, Why = why });
|
||||
pts.RemoveAt(drop);
|
||||
if (drop == at && legs.Count > 0) { legs.RemoveAt(legs.Count - 1); at--; }
|
||||
}
|
||||
|
||||
// 5. The route.
|
||||
r.Points.AddRange(pts);
|
||||
r.Legs.AddRange(legs);
|
||||
r.Route = RouteShape.Assemble(legs, NavRouteType.Circular, o.Spacing, out r.Yards);
|
||||
r.Ok = r.Route.Points.Count >= 2;
|
||||
if (!r.Ok) r.Error = "the joined legs came to nothing";
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A route through <paramref name="given"/> in order (<paramref name="type"/>: a circular route also
|
||||
/// walks from the last back to the first), on <paramref name="mesh"/> with its options as set by the
|
||||
/// caller; each leg must be walkable, or it fails saying which. A point inside one of
|
||||
/// <paramref name="portals"/>' circles is refused (walking there would take the portal).
|
||||
/// </summary>
|
||||
public static Result Path(TilePathFinder mesh, IReadOnlyList<WorldPt> given, NavRouteType type, double spacing,
|
||||
IReadOnlyList<PortalAvoid.Spot> portals)
|
||||
{
|
||||
var r = new Result { Centre = given.Count > 0 ? given[0] : default, Asked = given.Count };
|
||||
mesh.NoGaps = true;
|
||||
var ground = new List<WorldPt>(given.Count);
|
||||
for (int i = 0; i < given.Count; i++)
|
||||
{
|
||||
WorldPt p = given[i];
|
||||
if (!mesh.LoadArea(p.X - SnapUnits - 2, p.Y - SnapUnits - 2, p.X + SnapUnits + 2, p.Y + SnapUnits + 2)
|
||||
|| !mesh.Snap(p, SnapUnits, out WorldPt g, out _))
|
||||
return r.Fail($"point {i + 1} ({At(p)}) has no walkable ground within {SnapUnits:F0} yd (no navmesh there, water, or inside a wall)");
|
||||
int pi = NearestPortal(portals, g.X, g.Y, out double pd);
|
||||
if (pi >= 0 && pd < portals[pi].R)
|
||||
return r.Fail($"point {i + 1} ({At(p)}) is {pd:F1} yd from the portal {(portals[pi].Name.Length > 0 ? portals[pi].Name : "there")}: walking there would take it");
|
||||
ground.Add(g);
|
||||
}
|
||||
int legs = type == NavRouteType.Circular ? ground.Count : ground.Count - 1;
|
||||
for (int i = 0; i < legs; i++)
|
||||
{
|
||||
int j = (i + 1) % ground.Count;
|
||||
List<WorldPt>? leg = mesh.Walk(ground[i], ground[j], false, out string note);
|
||||
if (leg == null || leg.Count < 2)
|
||||
return r.Fail($"leg {i + 1} (point {i + 1} {At(ground[i])} to point {j + 1} {At(ground[j])}) can't be walked: {(note.Length > 0 ? note : "no path on the navmesh")}");
|
||||
// The walk ends on the navmesh beside the point; the point (on the ground) is where it goes.
|
||||
if (leg[0].FlatDistance(ground[i]) > 2.0) leg.Insert(0, ground[i]);
|
||||
if (leg[^1].FlatDistance(ground[j]) > 2.0) leg.Add(ground[j]);
|
||||
r.Legs.Add(leg);
|
||||
}
|
||||
r.Points.AddRange(ground);
|
||||
r.Route = RouteShape.Assemble(r.Legs, type, spacing, out r.Yards);
|
||||
r.Ok = r.Route.Points.Count >= 2;
|
||||
if (!r.Ok) r.Error = "the joined legs came to nothing";
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
|
@ -23,6 +23,8 @@ public static unsafe class PluginExports
|
|||
try
|
||||
{
|
||||
string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? "";
|
||||
// "RynthNav.Routes" v1 (2026-10-30): the route maker's JSON jobs (RoutesInterface.cs).
|
||||
if (iface == RynthCore.Plugin.Shared.RynthNavRoutesApiV1.InterfaceName) return RoutesInterface.Query(iface, version);
|
||||
return PathInterface.Query(iface, version);
|
||||
}
|
||||
catch
|
||||
|
|
@ -44,6 +46,8 @@ public static unsafe class PluginExports
|
|||
catch (Exception ex) { LogShutdownError(plugin, "Runtime.Shutdown", ex); }
|
||||
try { PathInterface.Release(); }
|
||||
catch (Exception ex) { LogShutdownError(plugin, "PathInterface.Release", ex); }
|
||||
try { RoutesInterface.Release(); }
|
||||
catch (Exception ex) { LogShutdownError(plugin, "RoutesInterface.Release", ex); }
|
||||
}
|
||||
|
||||
private static void LogShutdownError(RynthNavPlugin? plugin, string step, Exception ex)
|
||||
|
|
|
|||
258
Plugins/RynthCore.Plugin.RynthNav/RouteInfo.cs
Normal file
258
Plugins/RynthCore.Plugin.RynthNav/RouteInfo.cs
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// What a saved nav route is (/rnav routeinfo, the "RynthNav.Routes" info op): its type, its points
|
||||
/// by kind, how far it walks, the box it covers on the map and its centre, where it starts and how
|
||||
/// far that is from the player, the landblocks it crosses, whether it is a dungeon route, and the
|
||||
/// portals, recalls and commands a trip uses. Read with RynthAi's own reader (NavRouteParser).
|
||||
///
|
||||
/// yards the walking stretches: from each point to the next (a circular route also from its last
|
||||
/// point back to its first), except after a Portal or Recall step (a teleport) and across a
|
||||
/// jump longer than <see cref="TeleportGapUnits"/> (a teleport the file doesn't say, a
|
||||
/// command recall)
|
||||
/// landblocks every landblock a point is in, and those a walking stretch crosses (sampled every 24 yd)
|
||||
/// dungeon more than half the walked-to points are in dungeon landblocks (the caller says which
|
||||
/// landblocks are dungeons: the Atlas's, and those with a dungeon navmesh and no places on
|
||||
/// the map); coordinates are all a nav file has, so a cellar under the landscape reads as
|
||||
/// the landscape
|
||||
/// Host-free: the route tests describe made-up and real files.
|
||||
/// </summary>
|
||||
internal sealed class RouteInfo
|
||||
{
|
||||
/// <summary>Consecutive points farther apart than this (yards) are a teleport, not a walk.</summary>
|
||||
public const double TeleportGapUnits = 600.0;
|
||||
/// <summary>A walking stretch is sampled this often for the landblocks it crosses.</summary>
|
||||
private const double SampleUnits = 24.0;
|
||||
|
||||
public string Name = "", File = "", Type = "", Warning = "", FollowTarget = "";
|
||||
public int Points, Waypoints, Portals, Recalls, Chats, Pauses, Others;
|
||||
public double Yards;
|
||||
public bool HasBox;
|
||||
public double MinNs, MaxNs, MinEw, MaxEw;
|
||||
public double CentreNs => (MinNs + MaxNs) / 2;
|
||||
public double CentreEw => (MinEw + MaxEw) / 2;
|
||||
public bool HasStart;
|
||||
public double StartNs, StartEw;
|
||||
/// <summary>From the player to the start, yards; NaN when the player isn't on the map.</summary>
|
||||
public double StartYards = double.NaN;
|
||||
/// <summary>The walked-to point nearest the player (RynthAi starts a circular or linear route there), -1 = none.</summary>
|
||||
public int NearestIndex = -1;
|
||||
public double NearestNs, NearestEw, NearestYards = double.NaN;
|
||||
public readonly List<uint> Landblocks = new();
|
||||
public readonly List<uint> DungeonLandblocks = new();
|
||||
public bool Dungeon;
|
||||
public readonly List<string> PortalNames = new(), RecallNames = new(), ChatCommands = new();
|
||||
|
||||
public static string TypeName(NavRouteType t) => t switch
|
||||
{
|
||||
NavRouteType.Circular => "circular",
|
||||
NavRouteType.Linear => "linear",
|
||||
NavRouteType.Follow => "follow",
|
||||
NavRouteType.Once => "once",
|
||||
_ => "unknown",
|
||||
};
|
||||
|
||||
/// <summary>A step after which the character is somewhere else (no walk to the next point).</summary>
|
||||
private static bool Teleports(NavPointType t) => t is NavPointType.PortalNPC or NavPointType.Recall;
|
||||
|
||||
private static uint LandblockOf(double ns, double ew)
|
||||
{
|
||||
double x = NavCoords.WorldX(ew), y = NavCoords.WorldY(ns);
|
||||
int lx = (int)Math.Floor(x / 192.0), ly = (int)Math.Floor(y / 192.0);
|
||||
return lx is >= 0 and <= 255 && ly is >= 0 and <= 255 ? (uint)((lx << 8) | ly) : uint.MaxValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes <paramref name="route"/>. <paramref name="isDungeon"/> says whether a landblock is a
|
||||
/// dungeon (null: none is); the player's map position when <paramref name="hasPlayer"/>;
|
||||
/// <paramref name="spellName"/> names a recall's spell (null: "spell N").
|
||||
/// </summary>
|
||||
public static RouteInfo Describe(NavRouteParser route, string name, string file, Func<uint, bool>? isDungeon,
|
||||
bool hasPlayer, double playerNs, double playerEw, Func<int, string?>? spellName)
|
||||
{
|
||||
var info = new RouteInfo { Name = name, File = file, Type = TypeName(route.RouteType), Warning = route.LoadWarning ?? "" };
|
||||
if (route.RouteType == NavRouteType.Follow && route.Points.Count == 0) info.FollowTarget = route.FollowTargetName;
|
||||
List<NavPoint> pts = route.Points;
|
||||
info.Points = pts.Count;
|
||||
var lbs = new SortedSet<uint>();
|
||||
int walkedTo = 0, inDungeon = 0;
|
||||
var dungeonCache = new Dictionary<uint, bool>();
|
||||
bool IsDun(uint lb)
|
||||
{
|
||||
if (isDungeon == null || lb == uint.MaxValue) return false;
|
||||
if (!dungeonCache.TryGetValue(lb, out bool d)) dungeonCache[lb] = d = isDungeon(lb);
|
||||
return d;
|
||||
}
|
||||
void AddLb(double ns, double ew) { uint lb = LandblockOf(ns, ew); if (lb != uint.MaxValue) lbs.Add(lb); }
|
||||
|
||||
for (int i = 0; i < pts.Count; i++)
|
||||
{
|
||||
NavPoint p = pts[i];
|
||||
switch (p.Type)
|
||||
{
|
||||
case NavPointType.Point: case NavPointType.Checkpoint: case NavPointType.Jump: info.Waypoints++; break;
|
||||
case NavPointType.PortalNPC:
|
||||
info.Portals++;
|
||||
if (p.TargetName.Length > 0 && !info.PortalNames.Contains(p.TargetName)) info.PortalNames.Add(p.TargetName);
|
||||
break;
|
||||
case NavPointType.Recall:
|
||||
info.Recalls++;
|
||||
string rn = spellName?.Invoke(p.SpellId) ?? "";
|
||||
rn = rn.Length > 0 ? rn : "spell " + p.SpellId.ToString(CultureInfo.InvariantCulture);
|
||||
if (!info.RecallNames.Contains(rn)) info.RecallNames.Add(rn);
|
||||
break;
|
||||
case NavPointType.Chat:
|
||||
info.Chats++;
|
||||
if (p.ChatCommand.Length > 0 && !info.ChatCommands.Contains(p.ChatCommand)) info.ChatCommands.Add(p.ChatCommand);
|
||||
break;
|
||||
case NavPointType.Pause: info.Pauses++; break;
|
||||
default: info.Others++; break;
|
||||
}
|
||||
if (!double.IsFinite(p.NS) || !double.IsFinite(p.EW)) continue;
|
||||
if (!info.HasBox) { info.HasBox = true; info.MinNs = info.MaxNs = p.NS; info.MinEw = info.MaxEw = p.EW; }
|
||||
info.MinNs = Math.Min(info.MinNs, p.NS); info.MaxNs = Math.Max(info.MaxNs, p.NS);
|
||||
info.MinEw = Math.Min(info.MinEw, p.EW); info.MaxEw = Math.Max(info.MaxEw, p.EW);
|
||||
if (!info.HasStart) { info.HasStart = true; info.StartNs = p.NS; info.StartEw = p.EW; }
|
||||
AddLb(p.NS, p.EW);
|
||||
if (NavRouteParser.IsPlainWaypoint(p.Type))
|
||||
{
|
||||
walkedTo++;
|
||||
uint lb = LandblockOf(p.NS, p.EW);
|
||||
if (IsDun(lb)) { inDungeon++; if (!info.DungeonLandblocks.Contains(lb)) info.DungeonLandblocks.Add(lb); }
|
||||
if (hasPlayer)
|
||||
{
|
||||
double d = NavCoords.Distance(playerNs, playerEw, p.NS, p.EW);
|
||||
if (info.NearestIndex < 0 || d < info.NearestYards) { info.NearestIndex = i; info.NearestNs = p.NS; info.NearestEw = p.EW; info.NearestYards = d; }
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var (a, b) in WalkingStretches(route))
|
||||
{
|
||||
double d = NavCoords.Distance(a.NS, a.EW, b.NS, b.EW);
|
||||
info.Yards += d;
|
||||
int n = (int)Math.Ceiling(d / SampleUnits);
|
||||
for (int k = 1; k < n; k++) AddLb(a.NS + (b.NS - a.NS) * k / n, a.EW + (b.EW - a.EW) * k / n);
|
||||
}
|
||||
info.Landblocks.AddRange(lbs);
|
||||
info.DungeonLandblocks.Sort();
|
||||
info.Dungeon = walkedTo > 0 && inDungeon * 2 > walkedTo;
|
||||
if (hasPlayer && info.HasStart && !info.Dungeon) info.StartYards = NavCoords.Distance(playerNs, playerEw, info.StartNs, info.StartEw);
|
||||
if (info.Dungeon) { info.NearestIndex = -1; info.NearestYards = double.NaN; } // dungeon coordinates aren't the player's map position
|
||||
return info;
|
||||
}
|
||||
|
||||
/// <summary>The walking length of a route in yards (see the class notes).</summary>
|
||||
public static double Length(NavRouteParser route)
|
||||
{
|
||||
double total = 0;
|
||||
foreach (var (a, b) in WalkingStretches(route)) total += NavCoords.Distance(a.NS, a.EW, b.NS, b.EW);
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <summary>Each pair of points walked between, in order (a circular route's closing pair last).</summary>
|
||||
private static IEnumerable<(NavPoint A, NavPoint B)> WalkingStretches(NavRouteParser route)
|
||||
{
|
||||
List<NavPoint> pts = route.Points;
|
||||
int n = pts.Count;
|
||||
int pairs = route.RouteType == NavRouteType.Circular && n > 1 ? n : n - 1;
|
||||
for (int i = 0; i < pairs; i++)
|
||||
{
|
||||
NavPoint a = pts[i], b = pts[(i + 1) % n];
|
||||
if (Teleports(a.Type)) continue;
|
||||
if (!double.IsFinite(a.NS) || !double.IsFinite(a.EW) || !double.IsFinite(b.NS) || !double.IsFinite(b.EW)) continue;
|
||||
if (NavCoords.Distance(a.NS, a.EW, b.NS, b.EW) > TeleportGapUnits) continue;
|
||||
yield return (a, b);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Out ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The info op's result (Shared/RynthNavRoutesApi.cs has the fields).</summary>
|
||||
public void WriteJson(Utf8JsonWriter w)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("name", Name);
|
||||
w.WriteString("file", File);
|
||||
w.WriteString("type", Type);
|
||||
if (FollowTarget.Length > 0) w.WriteString("follows", FollowTarget);
|
||||
w.WriteNumber("points", Points);
|
||||
w.WriteStartObject("counts");
|
||||
w.WriteNumber("waypoints", Waypoints); w.WriteNumber("portals", Portals); w.WriteNumber("recalls", Recalls);
|
||||
w.WriteNumber("chats", Chats); w.WriteNumber("pauses", Pauses); w.WriteNumber("other", Others);
|
||||
w.WriteEndObject();
|
||||
RouteJson.Num(w, "yards", Yards, 0);
|
||||
if (HasBox)
|
||||
{
|
||||
w.WriteStartObject("box");
|
||||
RouteJson.Num(w, "minNs", MinNs, 4); RouteJson.Num(w, "maxNs", MaxNs, 4);
|
||||
RouteJson.Num(w, "minEw", MinEw, 4); RouteJson.Num(w, "maxEw", MaxEw, 4);
|
||||
w.WriteEndObject();
|
||||
RouteJson.Place(w, "centre", CentreNs, CentreEw);
|
||||
}
|
||||
else { w.WriteNull("box"); w.WriteNull("centre"); }
|
||||
if (HasStart)
|
||||
{
|
||||
w.WriteStartObject("start");
|
||||
RouteJson.Num(w, "ns", StartNs, 4); RouteJson.Num(w, "ew", StartEw, 4); RouteJson.Num(w, "yards", StartYards, 0);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
else w.WriteNull("start");
|
||||
if (NearestIndex >= 0)
|
||||
{
|
||||
w.WriteStartObject("nearest");
|
||||
w.WriteNumber("index", NearestIndex);
|
||||
RouteJson.Num(w, "ns", NearestNs, 4); RouteJson.Num(w, "ew", NearestEw, 4); RouteJson.Num(w, "yards", NearestYards, 0);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
else w.WriteNull("nearest");
|
||||
w.WriteStartArray("landblocks");
|
||||
foreach (uint lb in Landblocks) w.WriteStringValue(lb.ToString("X4", CultureInfo.InvariantCulture));
|
||||
w.WriteEndArray();
|
||||
w.WriteBoolean("dungeon", Dungeon);
|
||||
w.WriteStartArray("dungeonLandblocks");
|
||||
foreach (uint lb in DungeonLandblocks) w.WriteStringValue(lb.ToString("X4", CultureInfo.InvariantCulture));
|
||||
w.WriteEndArray();
|
||||
RouteJson.Strings(w, "portals", PortalNames);
|
||||
RouteJson.Strings(w, "recalls", RecallNames);
|
||||
RouteJson.Strings(w, "chats", ChatCommands);
|
||||
if (Warning.Length > 0) w.WriteString("warning", Warning);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
|
||||
/// <summary>/rnav routeinfo's lines.</summary>
|
||||
public List<string> ChatLines()
|
||||
{
|
||||
var lines = new List<string>();
|
||||
string kinds = $"{Waypoints} waypoint(s)"
|
||||
+ (Portals > 0 ? $", {Portals} portal(s)" : "") + (Recalls > 0 ? $", {Recalls} recall(s)" : "")
|
||||
+ (Chats > 0 ? $", {Chats} command(s)" : "") + (Pauses > 0 ? $", {Pauses} pause(s)" : "") + (Others > 0 ? $", {Others} other" : "");
|
||||
lines.Add(FollowTarget.Length > 0
|
||||
? $"routeinfo {Name}: follow, follows {FollowTarget}"
|
||||
: $"routeinfo {Name}: {Type}, {Points} point(s) ({kinds}), {NavCoords.FmtDistance(Yards)} of walking{(Type == "circular" ? " a lap" : "")}");
|
||||
if (HasBox)
|
||||
lines.Add($" covers {NavCoords.FmtOne(MinNs, 'N', 'S')} to {NavCoords.FmtOne(MaxNs, 'N', 'S')}, {NavCoords.FmtOne(MinEw, 'E', 'W')} to {NavCoords.FmtOne(MaxEw, 'E', 'W')}; centre {NavCoords.Fmt(CentreNs, CentreEw)}");
|
||||
if (HasStart)
|
||||
lines.Add($" starts at {NavCoords.Fmt(StartNs, StartEw)}"
|
||||
+ (double.IsNaN(StartYards) ? "" : $", {NavCoords.FmtDistance(StartYards)} from you")
|
||||
+ (NearestIndex > 0 && !double.IsNaN(NearestYards) && (Type is "circular" or "linear") ? $"; nearest waypoint #{NearestIndex + 1}, {NavCoords.FmtDistance(NearestYards)} away" : ""));
|
||||
if (Landblocks.Count > 0)
|
||||
{
|
||||
var hex = new List<string>();
|
||||
for (int i = 0; i < Landblocks.Count && i < 12; i++) hex.Add(Landblocks[i].ToString("X4", CultureInfo.InvariantCulture));
|
||||
lines.Add($" {Landblocks.Count} landblock(s): {string.Join(" ", hex)}{(Landblocks.Count > 12 ? $" (+{Landblocks.Count - 12} more)" : "")}");
|
||||
}
|
||||
if (Dungeon) lines.Add($" a dungeon route ({string.Join(" ", DungeonLandblocks.ConvertAll(l => l.ToString("X4", CultureInfo.InvariantCulture)))})");
|
||||
else if (DungeonLandblocks.Count > 0) lines.Add($" partly in a dungeon ({string.Join(" ", DungeonLandblocks.ConvertAll(l => l.ToString("X4", CultureInfo.InvariantCulture)))})");
|
||||
if (PortalNames.Count > 0) lines.Add($" portals: {string.Join(", ", PortalNames)}");
|
||||
if (RecallNames.Count > 0) lines.Add($" recalls: {string.Join(", ", RecallNames)}");
|
||||
if (ChatCommands.Count > 0) lines.Add($" commands: {string.Join(", ", ChatCommands)}");
|
||||
if (Warning.Length > 0) lines.Add(" " + Warning);
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
224
Plugins/RynthCore.Plugin.RynthNav/RouteJobs.cs
Normal file
224
Plugins/RynthCore.Plugin.RynthNav/RouteJobs.cs
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>A route maker job's state, as Poll reports it.</summary>
|
||||
internal enum RouteJobState { Queued, Working, Done, Failed }
|
||||
|
||||
/// <summary>
|
||||
/// One request to the route maker (a /rnav command or the "RynthNav.Routes" interface's Request): what
|
||||
/// was asked, where it is (queued, working, done, failed), a line saying so, and the result as JSON.
|
||||
/// The job table changes it; everyone else reads it through the table.
|
||||
/// </summary>
|
||||
internal sealed class RouteJob
|
||||
{
|
||||
public int Id;
|
||||
public RouteRequest Request = new();
|
||||
public RouteJobState State;
|
||||
public string Detail = "";
|
||||
/// <summary>The op's result (JSON), "null" until there is one.</summary>
|
||||
public string ResultJson = "null";
|
||||
public long CreatedMs, StartedMs, EndedMs;
|
||||
/// <summary>The go op: how many gotos had ended when its walk started (the tick's bookkeeping).</summary>
|
||||
public int Seq;
|
||||
public bool Finished => State is RouteJobState.Done or RouteJobState.Failed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The route maker's jobs: the last <see cref="Capacity"/> of them, oldest dropped first once
|
||||
/// finished. A new job is refused while every one kept is still queued or working. Ids go up from
|
||||
/// the first one given (the plugin starts them from the clock, so a reload doesn't reuse a caller's
|
||||
/// old ids); an id not kept any more is unknown. Locked: the interface's Request and Poll and the
|
||||
/// tick may all come at once. Host-free: the route tests drive it.
|
||||
/// </summary>
|
||||
internal sealed class RouteJobTable
|
||||
{
|
||||
public const int Capacity = 32;
|
||||
|
||||
private readonly object _lock = new();
|
||||
private readonly List<RouteJob> _jobs = new();
|
||||
private int _nextId;
|
||||
|
||||
public RouteJobTable(int firstId) { _nextId = Math.Max(1, firstId); }
|
||||
|
||||
public int Count { get { lock (_lock) return _jobs.Count; } }
|
||||
|
||||
/// <summary>A new queued job for <paramref name="request"/>; null (and why) when all the room is taken by unfinished jobs.</summary>
|
||||
public RouteJob? Add(RouteRequest request, long nowMs, out string error)
|
||||
{
|
||||
error = "";
|
||||
lock (_lock)
|
||||
{
|
||||
if (_jobs.Count >= Capacity)
|
||||
{
|
||||
int old = _jobs.FindIndex(j => j.Finished);
|
||||
if (old < 0) { error = $"{Capacity} jobs are already waiting or working: poll them, then ask again"; return null; }
|
||||
_jobs.RemoveAt(old);
|
||||
}
|
||||
var job = new RouteJob { Id = _nextId, Request = request, State = RouteJobState.Queued, Detail = "queued", CreatedMs = nowMs };
|
||||
_nextId = _nextId == int.MaxValue ? 1 : _nextId + 1;
|
||||
_jobs.Add(job);
|
||||
return job;
|
||||
}
|
||||
}
|
||||
|
||||
public RouteJob? Get(int id)
|
||||
{
|
||||
lock (_lock) return _jobs.Find(j => j.Id == id);
|
||||
}
|
||||
|
||||
/// <summary>The queued jobs, oldest first.</summary>
|
||||
public List<RouteJob> Queued()
|
||||
{
|
||||
lock (_lock) return _jobs.FindAll(j => j.State == RouteJobState.Queued);
|
||||
}
|
||||
|
||||
/// <summary>The working jobs, oldest first.</summary>
|
||||
public List<RouteJob> Working()
|
||||
{
|
||||
lock (_lock) return _jobs.FindAll(j => j.State == RouteJobState.Working);
|
||||
}
|
||||
|
||||
public void Start(RouteJob job, string detail, long nowMs)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (job.Finished) return;
|
||||
job.State = RouteJobState.Working;
|
||||
job.Detail = detail;
|
||||
job.StartedMs = nowMs;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A working job's line (a walk's distance left); a result to show while it works.</summary>
|
||||
public void Update(RouteJob job, string detail, string? resultJson = null)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (job.Finished) return;
|
||||
job.Detail = detail;
|
||||
if (resultJson != null) job.ResultJson = resultJson;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The job is over: done (<paramref name="ok"/>) or failed, with its line and result. A finished job stays as it is.</summary>
|
||||
public void Finish(RouteJob job, bool ok, string detail, string? resultJson, long nowMs)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (job.Finished) return;
|
||||
job.State = ok ? RouteJobState.Done : RouteJobState.Failed;
|
||||
job.Detail = detail;
|
||||
if (resultJson != null) job.ResultJson = resultJson;
|
||||
job.EndedMs = nowMs;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How a go job's walk ended, from the goto's last line: "arrived" (FinishGoto's "arrived", a dungeon's
|
||||
/// "arrived inside X" / "went through X") and "stopped" (a stop: the stop op, /rnav stop, the panel)
|
||||
/// are done (true); anything else ("stopped: no progress...", "stopped: logged out") failed.
|
||||
/// </summary>
|
||||
public static bool GoOutcome(string status, out string outcome)
|
||||
{
|
||||
if (status.StartsWith("arrived", StringComparison.Ordinal) || status.StartsWith("went through", StringComparison.Ordinal)) { outcome = "arrived"; return true; }
|
||||
if (status == "stopped") { outcome = "stopped"; return true; }
|
||||
outcome = "failed";
|
||||
return false;
|
||||
}
|
||||
|
||||
public static string StateName(RouteJobState s) => s switch
|
||||
{
|
||||
RouteJobState.Queued => "queued",
|
||||
RouteJobState.Working => "working",
|
||||
RouteJobState.Done => "done",
|
||||
_ => "failed",
|
||||
};
|
||||
|
||||
/// <summary>Poll's answer: {id, op, state, detail, result}; for an id not kept, {id, state: "unknown", error}.</summary>
|
||||
public string PollJson(int id, out bool known)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
RouteJob? j = _jobs.Find(x => x.Id == id);
|
||||
known = j != null;
|
||||
if (j == null)
|
||||
return RouteJson.Write(w =>
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("id", id);
|
||||
w.WriteString("state", "unknown");
|
||||
w.WriteString("error", $"no job {id}: only the last {Capacity} are kept, and a RynthNav reload forgets them");
|
||||
w.WriteEndObject();
|
||||
});
|
||||
return JobJson(j);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Request's answer for a job just queued (the same fields as Poll).</summary>
|
||||
public string Accepted(RouteJob job)
|
||||
{
|
||||
lock (_lock) return JobJson(job);
|
||||
}
|
||||
|
||||
private static string JobJson(RouteJob j) => RouteJson.Write(w =>
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("id", j.Id);
|
||||
w.WriteString("op", RouteRequest.OpName(j.Request.Op));
|
||||
w.WriteString("state", StateName(j.State));
|
||||
w.WriteString("detail", j.Detail);
|
||||
w.WritePropertyName("result");
|
||||
w.WriteRawValue(j.ResultJson, skipInputValidation: false);
|
||||
w.WriteEndObject();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Small helpers for writing the route maker's JSON (System.Text.Json's writer: no reflection, AOT-safe).</summary>
|
||||
internal static class RouteJson
|
||||
{
|
||||
/// <summary>One JSON value written by <paramref name="body"/>, as a string.</summary>
|
||||
public static string Write(Action<Utf8JsonWriter> body)
|
||||
{
|
||||
var buf = new ArrayBufferWriter<byte>(512);
|
||||
using (var w = new Utf8JsonWriter(buf))
|
||||
body(w);
|
||||
return Encoding.UTF8.GetString(buf.WrittenSpan);
|
||||
}
|
||||
|
||||
/// <summary>{"error": why, "usage": usage}: a refused request.</summary>
|
||||
public static string Error(string why, string usage) => Write(w =>
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("error", why);
|
||||
if (usage.Length > 0) w.WriteString("usage", usage);
|
||||
w.WriteEndObject();
|
||||
});
|
||||
|
||||
/// <summary>A number rounded to <paramref name="digits"/>, or null when it isn't one (the writer refuses NaN).</summary>
|
||||
public static void Num(Utf8JsonWriter w, string name, double v, int digits)
|
||||
{
|
||||
if (double.IsFinite(v)) w.WriteNumber(name, Math.Round(v, digits));
|
||||
else w.WriteNull(name);
|
||||
}
|
||||
|
||||
/// <summary>"name": {"ns": n, "ew": e} (4 decimals: 0.02 yd).</summary>
|
||||
public static void Place(Utf8JsonWriter w, string name, double ns, double ew)
|
||||
{
|
||||
w.WriteStartObject(name);
|
||||
Num(w, "ns", ns, 4);
|
||||
Num(w, "ew", ew, 4);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
|
||||
public static void Strings(Utf8JsonWriter w, string name, IEnumerable<string> values)
|
||||
{
|
||||
w.WriteStartArray(name);
|
||||
foreach (string s in values) w.WriteStringValue(s);
|
||||
w.WriteEndArray();
|
||||
}
|
||||
}
|
||||
555
Plugins/RynthCore.Plugin.RynthNav/RouteRequest.cs
Normal file
555
Plugins/RynthCore.Plugin.RynthNav/RouteRequest.cs
Normal file
|
|
@ -0,0 +1,555 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>What the route maker can be asked (chat or the "RynthNav.Routes" interface).</summary>
|
||||
internal enum RouteOp { Plan, MakeRoute, MakeLoop, MakePath, Info, Atlas, Go, Stop, Where }
|
||||
|
||||
/// <summary>The route maker's limits: a request outside them is refused, saying which and why.</summary>
|
||||
internal static class RouteLimits
|
||||
{
|
||||
/// <summary>A loop's radius, yards: under 20 it's a camp spot, over 250 its legs get long and it stops being readable.</summary>
|
||||
public const double MinRadius = 20, MaxRadius = 250;
|
||||
public const int MinLoopPoints = 3, MaxLoopPoints = 16;
|
||||
public const int MinPathPoints = 2, MaxPathPoints = 32;
|
||||
/// <summary>One makepath leg, straight-line yards (about 50 map degrees).</summary>
|
||||
public const double MaxLegYards = 12000;
|
||||
public const int DefaultAtlas = 10, MaxAtlas = 50;
|
||||
/// <summary>A request's JSON, characters.</summary>
|
||||
public const int MaxJson = 16384;
|
||||
/// <summary>Map coordinates beyond this (degrees, either way) are off Dereth.</summary>
|
||||
public const double MapLimit = 102.0;
|
||||
public const int MaxTextLength = 200;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One route maker request, from a /rnav command (<see cref="FromCommand"/>) or the interface's JSON
|
||||
/// (<see cref="FromJson"/>), checked against <see cref="RouteLimits"/> and the nav file name rules
|
||||
/// (NavRouteExport.FileName). Both end up here, so the chat commands and the interface run the same
|
||||
/// thing (RynthNavPlugin.RouteMaker.cs). Host-free: the route tests drive it.
|
||||
/// </summary>
|
||||
internal sealed class RouteRequest
|
||||
{
|
||||
public RouteOp Op;
|
||||
/// <summary>makeroute, makeloop, makepath, info: the nav file's name (without .nav).</summary>
|
||||
public string Name = "";
|
||||
public bool Overwrite;
|
||||
/// <summary>plan, makeroute, go: a place name or coordinates, as /rnav go takes them.</summary>
|
||||
public string To = "";
|
||||
/// <summary>plan, makeroute: use portals and recalls (null: the "portals" switch).</summary>
|
||||
public bool? Portals;
|
||||
/// <summary>plan, makeroute: show the trip in the panel and on the ground, as /rnav route does (chat: always).</summary>
|
||||
public bool Show;
|
||||
/// <summary>makeloop: round the player (else round AtNs, AtEw).</summary>
|
||||
public bool Here = true;
|
||||
public double AtNs, AtEw;
|
||||
public double Radius;
|
||||
/// <summary>makeloop: how many points (0 = RouteShape.DefaultPoints of the radius).</summary>
|
||||
public int Points;
|
||||
public NavRouteType PathType = NavRouteType.Once;
|
||||
/// <summary>makepath: the points, in order.</summary>
|
||||
public readonly List<(double Ns, double Ew)> Path = new();
|
||||
public string Search = "";
|
||||
public int Max = RouteLimits.DefaultAtlas;
|
||||
/// <summary>Typed in chat: the answer goes to chat too.</summary>
|
||||
public bool FromChat;
|
||||
|
||||
/// <summary>The op's name in the JSON ("plan", "makeroute", ...).</summary>
|
||||
public static string OpName(RouteOp op) => op switch
|
||||
{
|
||||
RouteOp.Plan => "plan",
|
||||
RouteOp.MakeRoute => "makeroute",
|
||||
RouteOp.MakeLoop => "makeloop",
|
||||
RouteOp.MakePath => "makepath",
|
||||
RouteOp.Info => "info",
|
||||
RouteOp.Atlas => "atlas",
|
||||
RouteOp.Go => "go",
|
||||
RouteOp.Stop => "stop",
|
||||
_ => "where",
|
||||
};
|
||||
|
||||
/// <summary>The /rnav word for the op (what a chat reply starts with).</summary>
|
||||
public static string CommandName(RouteOp op) => op == RouteOp.Info ? "routeinfo" : OpName(op);
|
||||
|
||||
public string Command => CommandName(Op);
|
||||
|
||||
/// <summary>The usage line said with a refusal: the /rnav form for chat, the JSON form for the interface.</summary>
|
||||
public static string Usage(RouteOp op, bool chat) => chat ? op switch
|
||||
{
|
||||
RouteOp.MakeRoute => "/rnav makeroute <name> to <place|coords> [overwrite]",
|
||||
RouteOp.MakeLoop => $"/rnav makeloop <name> [at <coords>|here] radius <yards {RouteLimits.MinRadius:F0}-{RouteLimits.MaxRadius:F0}> [points <{RouteLimits.MinLoopPoints}-{RouteLimits.MaxLoopPoints}>] [overwrite]",
|
||||
RouteOp.MakePath => "/rnav makepath <name> [loop|line|once] <coords>; <coords>; ... [overwrite]",
|
||||
RouteOp.Info => "/rnav routeinfo <name>",
|
||||
_ => "/rnav help",
|
||||
} : op switch
|
||||
{
|
||||
RouteOp.Plan => "{\"op\":\"plan\",\"to\":\"<place>\"|{\"ns\":n,\"ew\":e},\"portals\":true|false}",
|
||||
RouteOp.MakeRoute => "{\"op\":\"makeroute\",\"name\":\"<name>\",\"to\":\"<place>\"|{\"ns\":n,\"ew\":e},\"overwrite\":false}",
|
||||
RouteOp.MakeLoop => $"{{\"op\":\"makeloop\",\"name\":\"<name>\",\"at\":\"here\"|{{\"ns\":n,\"ew\":e}},\"radius\":{RouteLimits.MinRadius:F0}-{RouteLimits.MaxRadius:F0},\"points\":{RouteLimits.MinLoopPoints}-{RouteLimits.MaxLoopPoints},\"overwrite\":false}}",
|
||||
RouteOp.MakePath => "{\"op\":\"makepath\",\"name\":\"<name>\",\"type\":\"loop|line|once\",\"points\":[{\"ns\":n,\"ew\":e},...],\"overwrite\":false}",
|
||||
RouteOp.Info => "{\"op\":\"info\",\"name\":\"<name>\"}",
|
||||
RouteOp.Atlas => $"{{\"op\":\"atlas\",\"search\":\"<text>\",\"max\":1-{RouteLimits.MaxAtlas}}}",
|
||||
RouteOp.Go => "{\"op\":\"go\",\"to\":\"<place>\"|{\"ns\":n,\"ew\":e}}",
|
||||
RouteOp.Stop => "{\"op\":\"stop\"}",
|
||||
_ => "{\"op\":\"where\"}",
|
||||
};
|
||||
|
||||
/// <summary>Coordinates as text /rnav go reads back exactly ("42.1234N, 33.5E").</summary>
|
||||
public static string CoordText(double ns, double ew)
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
return Math.Abs(ns).ToString("0.#####", ci) + (ns >= 0 ? "N" : "S") + ", " + Math.Abs(ew).ToString("0.#####", ci) + (ew >= 0 ? "E" : "W");
|
||||
}
|
||||
|
||||
private static bool OnMap(double ns, double ew) =>
|
||||
double.IsFinite(ns) && double.IsFinite(ew) && Math.Abs(ns) <= RouteLimits.MapLimit && Math.Abs(ew) <= RouteLimits.MapLimit;
|
||||
|
||||
// ── From a /rnav command ─────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// /rnav makeroute, makeloop, makepath or routeinfo (<paramref name="command"/>, lower case) with
|
||||
/// the rest of the line. Null with <paramref name="error"/> (no usage: the caller adds it).
|
||||
/// </summary>
|
||||
public static RouteRequest? FromCommand(string command, string rest, out string error)
|
||||
{
|
||||
error = "";
|
||||
string text = (rest ?? "").Trim();
|
||||
var r = new RouteRequest { FromChat = true, Show = true };
|
||||
switch (command)
|
||||
{
|
||||
case "makeroute": r.Op = RouteOp.MakeRoute; break;
|
||||
case "makeloop": r.Op = RouteOp.MakeLoop; break;
|
||||
case "makepath": r.Op = RouteOp.MakePath; break;
|
||||
case "routeinfo": r.Op = RouteOp.Info; break;
|
||||
default: error = $"'{command}' isn't a route maker command"; return null;
|
||||
}
|
||||
if (text.Length == 0) { error = "give the route a name"; return null; }
|
||||
if (text.Length > RouteLimits.MaxJson) { error = "that's too long"; return null; }
|
||||
|
||||
// A name in quotes may hold anything a file name can ("Hunt at the lake").
|
||||
string? quoted = null;
|
||||
if (text[0] == '"')
|
||||
{
|
||||
int end = text.IndexOf('"', 1);
|
||||
if (end < 0) { error = "the name's closing quote is missing"; return null; }
|
||||
quoted = text.Substring(1, end - 1);
|
||||
text = text.Substring(end + 1).Trim();
|
||||
}
|
||||
if (r.Op != RouteOp.Info && EndsWithWord(text, "overwrite")) { r.Overwrite = true; text = text[..^9].TrimEnd(); }
|
||||
|
||||
switch (r.Op)
|
||||
{
|
||||
case RouteOp.Info:
|
||||
if (!SetName(r, quoted ?? text, out error)) return null;
|
||||
if (quoted != null && text.Length > 0) { error = $"'{text}' after the name: routeinfo takes only a name"; return null; }
|
||||
return r;
|
||||
|
||||
case RouteOp.MakeRoute:
|
||||
{
|
||||
string where;
|
||||
if (quoted != null)
|
||||
{
|
||||
if (!StartsWithWord(text, "to")) { error = "say where: <name> to <place|coords>"; return null; }
|
||||
where = text.Substring(2).Trim();
|
||||
if (!SetName(r, quoted, out error)) return null;
|
||||
}
|
||||
else
|
||||
{
|
||||
// The first " to " ends the name: place names hold it more often ("Portal to Cragstone").
|
||||
int at = text.IndexOf(" to ", StringComparison.OrdinalIgnoreCase);
|
||||
if (at <= 0) { error = "say where: <name> to <place|coords>"; return null; }
|
||||
if (!SetName(r, text[..at], out error)) return null;
|
||||
where = text[(at + 4)..].Trim();
|
||||
}
|
||||
if (where.Length == 0) { error = "say where: <name> to <place|coords>"; return null; }
|
||||
if (where.Length > RouteLimits.MaxTextLength) { error = "the place is too long"; return null; }
|
||||
if (NavCoords.TryParseLoc(where, out double tns, out double tew) && !OnMap(tns, tew))
|
||||
{ error = $"{where} is off the map"; return null; }
|
||||
r.To = where;
|
||||
return r;
|
||||
}
|
||||
|
||||
case RouteOp.MakeLoop:
|
||||
{
|
||||
string[] t = text.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
int optAt = -1;
|
||||
string firstError = "";
|
||||
for (int k = quoted != null ? 0 : 1; k < t.Length; k++)
|
||||
{
|
||||
if (!IsLoopWord(t[k])) continue;
|
||||
var trial = new RouteRequest();
|
||||
if (TryLoopOptions(t, k, trial, out string why)) { optAt = k; break; }
|
||||
if (firstError.Length == 0) firstError = why;
|
||||
}
|
||||
if (quoted == null && optAt < 0)
|
||||
{
|
||||
error = firstError.Length > 0 ? firstError : "give a name and the radius";
|
||||
return null;
|
||||
}
|
||||
if (quoted != null && optAt != 0)
|
||||
{
|
||||
error = t.Length == 0 ? "give the radius" : firstError.Length > 0 ? firstError : $"'{t[0]}' isn't one of at, here, radius, points, overwrite";
|
||||
return null;
|
||||
}
|
||||
if (!SetName(r, quoted ?? string.Join(' ', t, 0, optAt), out error)) return null;
|
||||
TryLoopOptions(t, optAt, r, out _);
|
||||
return CheckLoop(r, out error) ? r : null;
|
||||
}
|
||||
|
||||
default: // makepath
|
||||
{
|
||||
string[] segs = text.Split(';');
|
||||
string[] t = segs[0].Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
int coordAt = -1;
|
||||
for (int k = quoted != null ? 0 : 1; k < t.Length && coordAt < 0; k++)
|
||||
if (NavCoords.TrySplitCoordsAndName(string.Join(' ', t, k, t.Length - k), out _, out _, out string left) && left.Length == 0)
|
||||
coordAt = k;
|
||||
if (coordAt < 0) { error = "give a name, then the points: <coords>; <coords>; ..."; return null; }
|
||||
int nameEnd = coordAt;
|
||||
if (nameEnd >= 1 && TryPathType(t[nameEnd - 1], out NavRouteType type) && (quoted != null || nameEnd >= 2))
|
||||
{
|
||||
r.PathType = type;
|
||||
nameEnd--;
|
||||
}
|
||||
if (quoted != null && nameEnd != 0) { error = $"'{t[0]}' after the name isn't loop, line, once or coordinates"; return null; }
|
||||
if (!SetName(r, quoted ?? string.Join(' ', t, 0, nameEnd), out error)) return null;
|
||||
for (int s = 0; s < segs.Length; s++)
|
||||
{
|
||||
string seg = s == 0 ? string.Join(' ', t, coordAt, t.Length - coordAt) : segs[s].Trim();
|
||||
if (seg.Length == 0) continue;
|
||||
if (!NavCoords.TrySplitCoordsAndName(seg, out double ns, out double ew, out string extra) || extra.Length > 0)
|
||||
{ error = $"point {r.Path.Count + 1}: can't read '{seg}' as coordinates (e.g. 42.1N, 33.6E)"; return null; }
|
||||
r.Path.Add((ns, ew));
|
||||
}
|
||||
return CheckPath(r, out error) ? r : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool EndsWithWord(string text, string word) =>
|
||||
text.Equals(word, StringComparison.OrdinalIgnoreCase)
|
||||
|| (text.Length > word.Length && text.EndsWith(word, StringComparison.OrdinalIgnoreCase) && text[^(word.Length + 1)] == ' ');
|
||||
|
||||
private static bool StartsWithWord(string text, string word) =>
|
||||
text.Equals(word, StringComparison.OrdinalIgnoreCase)
|
||||
|| (text.Length > word.Length && text.StartsWith(word, StringComparison.OrdinalIgnoreCase) && text[word.Length] == ' ');
|
||||
|
||||
private static bool IsLoopWord(string w) =>
|
||||
w.Equals("at", StringComparison.OrdinalIgnoreCase) || w.Equals("here", StringComparison.OrdinalIgnoreCase)
|
||||
|| w.Equals("radius", StringComparison.OrdinalIgnoreCase) || w.Equals("points", StringComparison.OrdinalIgnoreCase)
|
||||
|| w.Equals("overwrite", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>makeloop's options from token <paramref name="from"/> on: at <coords> | here, radius <yd>, points <n>.</summary>
|
||||
private static bool TryLoopOptions(string[] t, int from, RouteRequest r, out string error)
|
||||
{
|
||||
error = "";
|
||||
bool radius = false, centre = false;
|
||||
for (int i = from; i < t.Length; i++)
|
||||
{
|
||||
string w = t[i].ToLowerInvariant();
|
||||
switch (w)
|
||||
{
|
||||
case "here":
|
||||
if (centre) { error = "say the centre once: at <coords> or here"; return false; }
|
||||
r.Here = true; centre = true;
|
||||
break;
|
||||
case "overwrite":
|
||||
r.Overwrite = true;
|
||||
break;
|
||||
case "radius":
|
||||
if (i + 1 >= t.Length || !double.TryParse(t[i + 1], NumberStyles.Float, CultureInfo.InvariantCulture, out r.Radius))
|
||||
{ error = "radius needs a number of yards"; return false; }
|
||||
radius = true; i++;
|
||||
break;
|
||||
case "points":
|
||||
if (i + 1 >= t.Length || !int.TryParse(t[i + 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out r.Points))
|
||||
{ error = "points needs a whole number"; return false; }
|
||||
i++;
|
||||
break;
|
||||
case "at":
|
||||
{
|
||||
if (centre) { error = "say the centre once: at <coords> or here"; return false; }
|
||||
int j = i + 1;
|
||||
while (j < t.Length && !IsLoopWord(t[j])) j++;
|
||||
string coords = string.Join(' ', t, i + 1, j - i - 1);
|
||||
if (!NavCoords.TrySplitCoordsAndName(coords, out r.AtNs, out r.AtEw, out string extra) || extra.Length > 0)
|
||||
{ error = $"at needs coordinates (e.g. at 42.1N, 33.6E), not '{coords}'"; return false; }
|
||||
r.Here = false; centre = true;
|
||||
i = j - 1;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
error = $"'{t[i]}' isn't one of at, here, radius, points, overwrite";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!radius) { error = "give the radius: radius <yards>"; return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryPathType(string w, out NavRouteType type)
|
||||
{
|
||||
switch (w.ToLowerInvariant())
|
||||
{
|
||||
case "loop": case "circular": type = NavRouteType.Circular; return true;
|
||||
case "line": case "linear": type = NavRouteType.Linear; return true;
|
||||
case "once": type = NavRouteType.Once; return true;
|
||||
default: type = NavRouteType.Once; return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool SetName(RouteRequest r, string typed, out string error)
|
||||
{
|
||||
r.Name = NavRouteExport.FileName(typed, out error);
|
||||
return r.Name.Length > 0;
|
||||
}
|
||||
|
||||
private static bool CheckLoop(RouteRequest r, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (!double.IsFinite(r.Radius) || r.Radius < RouteLimits.MinRadius || r.Radius > RouteLimits.MaxRadius)
|
||||
{ error = $"radius {r.Radius.ToString("0.#", CultureInfo.InvariantCulture)} is out of range ({RouteLimits.MinRadius:F0}-{RouteLimits.MaxRadius:F0} yards)"; return false; }
|
||||
if (r.Points != 0 && (r.Points < RouteLimits.MinLoopPoints || r.Points > RouteLimits.MaxLoopPoints))
|
||||
{ error = $"points {r.Points} is out of range ({RouteLimits.MinLoopPoints}-{RouteLimits.MaxLoopPoints})"; return false; }
|
||||
if (!r.Here && !OnMap(r.AtNs, r.AtEw)) { error = $"{CoordText(r.AtNs, r.AtEw)} is off the map"; return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool CheckPath(RouteRequest r, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (r.Path.Count < RouteLimits.MinPathPoints) { error = $"give at least {RouteLimits.MinPathPoints} points, separated by ;"; return false; }
|
||||
if (r.Path.Count > RouteLimits.MaxPathPoints) { error = $"{r.Path.Count} points is too many (at most {RouteLimits.MaxPathPoints})"; return false; }
|
||||
for (int i = 0; i < r.Path.Count; i++)
|
||||
if (!OnMap(r.Path[i].Ns, r.Path[i].Ew)) { error = $"point {i + 1} ({CoordText(r.Path[i].Ns, r.Path[i].Ew)}) is off the map"; return false; }
|
||||
for (int i = 1; i < r.Path.Count; i++)
|
||||
{
|
||||
double d = NavCoords.Distance(r.Path[i - 1].Ns, r.Path[i - 1].Ew, r.Path[i].Ns, r.Path[i].Ew);
|
||||
if (d > RouteLimits.MaxLegYards) { error = $"leg {i} is {NavCoords.FmtDistance(d)} long (at most {NavCoords.FmtDistance(RouteLimits.MaxLegYards)} a leg)"; return false; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── From the interface's JSON ────────────────────────────────────────
|
||||
|
||||
/// <summary>A request from the "RynthNav.Routes" interface (Shared/RynthNavRoutesApi.cs has the format). Null with <paramref name="error"/>.</summary>
|
||||
public static RouteRequest? FromJson(string? json, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (string.IsNullOrWhiteSpace(json)) { error = "the request is empty"; return null; }
|
||||
if (json.Length > RouteLimits.MaxJson) { error = $"the request is {json.Length} characters (at most {RouteLimits.MaxJson})"; return null; }
|
||||
JsonDocument doc;
|
||||
try { doc = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 8 }); }
|
||||
catch (JsonException ex) { error = "not JSON: " + ex.Message; return null; }
|
||||
using (doc)
|
||||
{
|
||||
JsonElement root = doc.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object) { error = "the request must be a JSON object"; return null; }
|
||||
if (!Str(root, "op", true, out string op, out error)) return null;
|
||||
var r = new RouteRequest();
|
||||
if (!TryOp(op, out r.Op)) { error = $"unknown op '{op}' ({OpList})"; return null; }
|
||||
bool ok = r.Op switch
|
||||
{
|
||||
RouteOp.Plan => ToField(root, r, out error) && OptBool(root, "portals", ref r.Portals, out error) && Bool(root, "show", ref r.Show, out error),
|
||||
RouteOp.Go => ToField(root, r, out error),
|
||||
RouteOp.MakeRoute => NameField(root, r, out error) && ToField(root, r, out error) && OptBool(root, "portals", ref r.Portals, out error)
|
||||
&& Bool(root, "overwrite", ref r.Overwrite, out error) && Bool(root, "show", ref r.Show, out error),
|
||||
RouteOp.MakeLoop => NameField(root, r, out error) && At(root, r, out error) && Num(root, "radius", true, ref r.Radius, out error)
|
||||
&& Int(root, "points", ref r.Points, out error) && Bool(root, "overwrite", ref r.Overwrite, out error) && CheckLoop(r, out error),
|
||||
RouteOp.MakePath => NameField(root, r, out error) && PathTypeOf(root, r, out error) && PathPoints(root, r, out error)
|
||||
&& Bool(root, "overwrite", ref r.Overwrite, out error) && CheckPath(r, out error),
|
||||
RouteOp.Info => NameField(root, r, out error),
|
||||
RouteOp.Atlas => SearchField(root, r, out error),
|
||||
_ => true,
|
||||
};
|
||||
return ok ? r : null;
|
||||
}
|
||||
}
|
||||
|
||||
private const string OpList = "plan, makeroute, makeloop, makepath, info, atlas, go, stop, where";
|
||||
|
||||
private static bool TryOp(string text, out RouteOp op)
|
||||
{
|
||||
switch (text.Trim().ToLowerInvariant())
|
||||
{
|
||||
case "plan": op = RouteOp.Plan; return true;
|
||||
case "makeroute": op = RouteOp.MakeRoute; return true;
|
||||
case "makeloop": op = RouteOp.MakeLoop; return true;
|
||||
case "makepath": op = RouteOp.MakePath; return true;
|
||||
case "info": case "routeinfo": op = RouteOp.Info; return true;
|
||||
case "atlas": op = RouteOp.Atlas; return true;
|
||||
case "go": op = RouteOp.Go; return true;
|
||||
case "stop": op = RouteOp.Stop; return true;
|
||||
case "where": op = RouteOp.Where; return true;
|
||||
default: op = RouteOp.Where; return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The usage to give with a refused request: its op's JSON form when the op was readable, else the list of ops.</summary>
|
||||
public static string UsageFor(string? json)
|
||||
{
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json ?? "", new JsonDocumentOptions { MaxDepth = 8 });
|
||||
if (doc.RootElement.ValueKind == JsonValueKind.Object && doc.RootElement.TryGetProperty("op", out JsonElement v)
|
||||
&& v.ValueKind == JsonValueKind.String && TryOp(v.GetString() ?? "", out RouteOp op))
|
||||
return Usage(op, chat: false);
|
||||
}
|
||||
catch (JsonException) { }
|
||||
return $"{{\"op\": one of {OpList}, ...}} (Plugins/Shared/RynthNavRoutesApi.cs has each op's fields)";
|
||||
}
|
||||
|
||||
private static bool Str(JsonElement o, string name, bool required, out string value, out string error)
|
||||
{
|
||||
value = ""; error = "";
|
||||
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind == JsonValueKind.Null)
|
||||
{
|
||||
if (required) error = $"\"{name}\" is missing";
|
||||
return !required;
|
||||
}
|
||||
if (v.ValueKind != JsonValueKind.String) { error = $"\"{name}\" must be a string"; return false; }
|
||||
value = v.GetString() ?? "";
|
||||
if (value.Length > RouteLimits.MaxTextLength) { error = $"\"{name}\" is too long (at most {RouteLimits.MaxTextLength} characters)"; return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool Bool(JsonElement o, string name, ref bool value, out string error)
|
||||
{
|
||||
bool? b = value;
|
||||
if (!OptBool(o, name, ref b, out error)) return false;
|
||||
value = b ?? value;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool OptBool(JsonElement o, string name, ref bool? value, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind == JsonValueKind.Null) return true;
|
||||
if (v.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) { error = $"\"{name}\" must be true or false"; return false; }
|
||||
value = v.ValueKind == JsonValueKind.True;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool Num(JsonElement o, string name, bool required, ref double value, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind == JsonValueKind.Null)
|
||||
{
|
||||
if (required) error = $"\"{name}\" is missing";
|
||||
return !required;
|
||||
}
|
||||
if (v.ValueKind != JsonValueKind.Number || !v.TryGetDouble(out double d) || !double.IsFinite(d)) { error = $"\"{name}\" must be a number"; return false; }
|
||||
value = d;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool Int(JsonElement o, string name, ref int value, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind == JsonValueKind.Null) return true;
|
||||
if (v.ValueKind != JsonValueKind.Number || !v.TryGetInt32(out int i)) { error = $"\"{name}\" must be a whole number"; return false; }
|
||||
value = i;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>{"ns": n, "ew": e} as map coordinates on Dereth.</summary>
|
||||
private static bool Coords(JsonElement v, string what, out double ns, out double ew, out string error)
|
||||
{
|
||||
ns = ew = 0; error = "";
|
||||
if (v.ValueKind != JsonValueKind.Object
|
||||
|| !v.TryGetProperty("ns", out JsonElement n) || n.ValueKind != JsonValueKind.Number || !n.TryGetDouble(out ns)
|
||||
|| !v.TryGetProperty("ew", out JsonElement e) || e.ValueKind != JsonValueKind.Number || !e.TryGetDouble(out ew))
|
||||
{ error = $"{what} must be {{\"ns\": number, \"ew\": number}} (north and east positive)"; return false; }
|
||||
if (!OnMap(ns, ew)) { error = $"{what} ({CoordText(ns, ew)}) is off the map"; return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool NameField(JsonElement o, RouteRequest r, out string error)
|
||||
{
|
||||
if (!Str(o, "name", true, out string name, out error)) return false;
|
||||
return SetName(r, name, out error);
|
||||
}
|
||||
|
||||
private static bool ToField(JsonElement o, RouteRequest r, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (!o.TryGetProperty("to", out JsonElement v) || v.ValueKind == JsonValueKind.Null) { error = "\"to\" is missing (a place name or {\"ns\", \"ew\"})"; return false; }
|
||||
if (v.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
if (!Coords(v, "\"to\"", out double ns, out double ew, out error)) return false;
|
||||
r.To = CoordText(ns, ew);
|
||||
return true;
|
||||
}
|
||||
if (!Str(o, "to", true, out string to, out error)) { error = "\"to\" must be a place name or {\"ns\", \"ew\"}"; return false; }
|
||||
to = to.Trim();
|
||||
if (to.Length == 0) { error = "\"to\" is empty"; return false; }
|
||||
if (NavCoords.TryParseLoc(to, out double tns, out double tew) && !OnMap(tns, tew)) { error = $"\"to\" ({to}) is off the map"; return false; }
|
||||
r.To = to;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool At(JsonElement o, RouteRequest r, out string error)
|
||||
{
|
||||
error = "";
|
||||
r.Here = true;
|
||||
if (!o.TryGetProperty("at", out JsonElement v) || v.ValueKind == JsonValueKind.Null) return true;
|
||||
if (v.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
string s = (v.GetString() ?? "").Trim();
|
||||
if (s.Equals("here", StringComparison.OrdinalIgnoreCase)) return true;
|
||||
if (!NavCoords.TrySplitCoordsAndName(s, out r.AtNs, out r.AtEw, out string extra) || extra.Length > 0)
|
||||
{ error = "\"at\" must be \"here\", coordinates or {\"ns\", \"ew\"}"; return false; }
|
||||
r.Here = false;
|
||||
return true;
|
||||
}
|
||||
if (!Coords(v, "\"at\"", out r.AtNs, out r.AtEw, out error)) return false;
|
||||
r.Here = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool PathTypeOf(JsonElement o, RouteRequest r, out string error)
|
||||
{
|
||||
if (!Str(o, "type", false, out string type, out error)) return false;
|
||||
if (type.Length == 0) { r.PathType = NavRouteType.Once; return true; }
|
||||
if (TryPathType(type.Trim(), out r.PathType)) return true;
|
||||
error = $"\"type\" '{type}' isn't loop, line or once";
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool PathPoints(JsonElement o, RouteRequest r, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (!o.TryGetProperty("points", out JsonElement arr) || arr.ValueKind != JsonValueKind.Array)
|
||||
{ error = "\"points\" must be an array of {\"ns\", \"ew\"} (or coordinate strings)"; return false; }
|
||||
int i = 0;
|
||||
foreach (JsonElement p in arr.EnumerateArray())
|
||||
{
|
||||
i++;
|
||||
if (i > RouteLimits.MaxPathPoints) { error = $"too many points (at most {RouteLimits.MaxPathPoints})"; return false; }
|
||||
double ns, ew;
|
||||
if (p.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
string s = p.GetString() ?? "";
|
||||
if (!NavCoords.TrySplitCoordsAndName(s, out ns, out ew, out string extra) || extra.Length > 0)
|
||||
{ error = $"point {i}: can't read '{s}' as coordinates"; return false; }
|
||||
}
|
||||
else if (!Coords(p, $"point {i}", out ns, out ew, out error)) return false;
|
||||
r.Path.Add((ns, ew));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool SearchField(JsonElement o, RouteRequest r, out string error)
|
||||
{
|
||||
if (!Str(o, "search", true, out r.Search, out error)) return false;
|
||||
r.Search = r.Search.Trim();
|
||||
if (r.Search.Length == 0) { error = "\"search\" is empty"; return false; }
|
||||
if (!Int(o, "max", ref r.Max, out error)) return false;
|
||||
if (r.Max < 1 || r.Max > RouteLimits.MaxAtlas) { error = $"\"max\" must be 1 to {RouteLimits.MaxAtlas}"; return false; }
|
||||
return true;
|
||||
}
|
||||
}
|
||||
119
Plugins/RynthCore.Plugin.RynthNav/RouteShape.cs
Normal file
119
Plugins/RynthCore.Plugin.RynthNav/RouteShape.cs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// The route maker's geometry that needs no navmesh (RynthNavPlugin.RouteMaker.cs, LoopMaker.cs):
|
||||
/// how many points a loop of a radius gets, the order a loop's points are walked in (round the
|
||||
/// centre, then untangled so no two legs cross), and the joined legs as a RynthAi nav route (thinned,
|
||||
/// heights as nav Z, a circular route not repeating its first point). Host-free and Detour-free:
|
||||
/// the route tests drive it.
|
||||
/// </summary>
|
||||
internal static class RouteShape
|
||||
{
|
||||
/// <summary>A loop's legs get a point at least this often (yards), so RynthAi's nav follows the ground.</summary>
|
||||
public const double LoopSpacing = 30.0;
|
||||
|
||||
/// <summary>A loop's point count when none is asked for: about one every 45 yd of its circle, 4 to 12.</summary>
|
||||
public static int DefaultPoints(double radius) =>
|
||||
Math.Clamp((int)Math.Round(2 * Math.PI * radius / 45.0), 4, 12);
|
||||
|
||||
/// <summary>Compass bearing (0 = north, clockwise) from <paramref name="c"/> to <paramref name="p"/>, 0..360.</summary>
|
||||
public static double Bearing(WorldPt c, WorldPt p)
|
||||
{
|
||||
double b = Math.Atan2(p.X - c.X, p.Y - c.Y) * 180.0 / Math.PI;
|
||||
return b < 0 ? b + 360.0 : b;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The order to walk a loop's points in: clockwise round <paramref name="centre"/> from the first
|
||||
/// point north of it, then untangled (2-opt: two legs that cross are uncrossed by walking the
|
||||
/// stretch between them the other way) until no two straight legs cross. Indexes into
|
||||
/// <paramref name="pts"/>.
|
||||
/// </summary>
|
||||
public static int[] OrderLoop(IReadOnlyList<WorldPt> pts, WorldPt centre)
|
||||
{
|
||||
int n = pts.Count;
|
||||
var order = new List<int>(n);
|
||||
for (int i = 0; i < n; i++) order.Add(i);
|
||||
order.Sort((a, b) =>
|
||||
{
|
||||
int c = Bearing(centre, pts[a]).CompareTo(Bearing(centre, pts[b]));
|
||||
return c != 0 ? c : pts[a].FlatDistance(centre).CompareTo(pts[b].FlatDistance(centre));
|
||||
});
|
||||
if (n < 4) return order.ToArray();
|
||||
int first = order[0];
|
||||
for (int pass = 0; pass < n * n; pass++)
|
||||
{
|
||||
bool changed = false;
|
||||
for (int i = 0; i < n && !changed; i++)
|
||||
for (int j = i + 2; j < n && !changed; j++)
|
||||
{
|
||||
if (i == 0 && j == n - 1) continue; // the two legs meet at order[0]
|
||||
WorldPt a = pts[order[i]], b = pts[order[i + 1]], c = pts[order[j]], d = pts[order[(j + 1) % n]];
|
||||
if (!SegmentsCross(a, b, c, d)) continue;
|
||||
order.Reverse(i + 1, j - i);
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) break;
|
||||
}
|
||||
int at = order.IndexOf(first);
|
||||
var o = new int[n];
|
||||
for (int k = 0; k < n; k++) o[k] = order[(at + k) % n];
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>How many pairs of straight legs of the path cross (<paramref name="closed"/>: the last point joins the first).</summary>
|
||||
public static int Crossings(IReadOnlyList<WorldPt> pts, bool closed)
|
||||
{
|
||||
int n = pts.Count, legs = closed ? n : n - 1, count = 0;
|
||||
for (int i = 0; i < legs; i++)
|
||||
for (int j = i + 1; j < legs; j++)
|
||||
{
|
||||
if (j == i + 1 || (closed && i == 0 && j == n - 1)) continue; // neighbours share a point
|
||||
if (SegmentsCross(pts[i], pts[(i + 1) % n], pts[j], pts[(j + 1) % n])) count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>True when the segments a-b and c-d cross (touching at an end doesn't count).</summary>
|
||||
public static bool SegmentsCross(WorldPt a, WorldPt b, WorldPt c, WorldPt d)
|
||||
{
|
||||
double d1 = Cross(c, d, a), d2 = Cross(c, d, b), d3 = Cross(a, b, c), d4 = Cross(a, b, d);
|
||||
return ((d1 > 1e-9 && d2 < -1e-9) || (d1 < -1e-9 && d2 > 1e-9)) && ((d3 > 1e-9 && d4 < -1e-9) || (d3 < -1e-9 && d4 > 1e-9));
|
||||
}
|
||||
|
||||
private static double Cross(WorldPt o, WorldPt a, WorldPt b) => (a.X - o.X) * (b.Y - o.Y) - (a.Y - o.Y) * (b.X - o.X);
|
||||
|
||||
/// <summary>
|
||||
/// The joined legs as a nav route of <paramref name="type"/>: leg k runs from point k to point k+1
|
||||
/// (first and last points included), each thinned (corners that matter, a point at least every
|
||||
/// <paramref name="spacing"/> yd). A circular route's last leg ends where the first starts, so that
|
||||
/// point isn't written twice (RynthAi walks from the last point back to the first).
|
||||
/// <paramref name="yards"/> is the walk, a circular route's closing leg included.
|
||||
/// </summary>
|
||||
public static NavRouteParser Assemble(IReadOnlyList<IReadOnlyList<WorldPt>> legs, NavRouteType type, double spacing, out double yards)
|
||||
{
|
||||
var route = new NavRouteParser { RouteType = type };
|
||||
yards = 0;
|
||||
var pts = new List<WorldPt>();
|
||||
foreach (IReadOnlyList<WorldPt> leg in legs)
|
||||
{
|
||||
if (leg.Count == 0) continue;
|
||||
List<WorldPt> thin = TripPathBuilder.Thin(leg, TripPathBuilder.ThinTolerance, spacing);
|
||||
for (int i = 1; i < thin.Count; i++) yards += thin[i - 1].FlatDistance(thin[i]);
|
||||
for (int i = pts.Count == 0 ? 0 : 1; i < thin.Count; i++) pts.Add(thin[i]);
|
||||
}
|
||||
if (type == NavRouteType.Circular && pts.Count > 2 && pts[^1].FlatDistance(pts[0]) < TripPathBuilder.DuplicateUnits * 4)
|
||||
pts.RemoveAt(pts.Count - 1);
|
||||
double lastH = 0;
|
||||
foreach (WorldPt p in pts)
|
||||
{
|
||||
if (!double.IsNaN(p.H)) lastH = p.H;
|
||||
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = p.Ns, EW = p.Ew, Z = lastH / 240.0 });
|
||||
}
|
||||
return route;
|
||||
}
|
||||
}
|
||||
93
Plugins/RynthCore.Plugin.RynthNav/RoutesInterface.cs
Normal file
93
Plugins/RynthCore.Plugin.RynthNav/RoutesInterface.cs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// RynthNav's side of the "RynthNav.Routes" interface (Shared/RynthNavRoutesApi.cs): the table
|
||||
/// RynthPluginQueryInterface hands out and the two functions behind it, which queue a route maker job
|
||||
/// and report one (RynthNavPlugin.RouteMaker.cs). They run on the plugin pump thread and act on the
|
||||
/// current plugin instance. <see cref="Release"/> frees the table and the last string at
|
||||
/// RynthPluginShutdown; callers resolve the table again every tick.
|
||||
/// </summary>
|
||||
internal static unsafe class RoutesInterface
|
||||
{
|
||||
private static RynthNavRoutesApiV1* _table;
|
||||
private static IntPtr _out; // the last string handed back (valid until the next call)
|
||||
|
||||
public static IntPtr Query(string iface, uint version)
|
||||
{
|
||||
if (iface != RynthNavRoutesApiV1.InterfaceName || version == 0 || version > RynthNavRoutesApiV1.InterfaceVersion) return IntPtr.Zero;
|
||||
if (PluginExports.Runtime.Plugin == null) return IntPtr.Zero;
|
||||
if (_table == null)
|
||||
{
|
||||
var t = (RynthNavRoutesApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthNavRoutesApiV1));
|
||||
t->Version = RynthNavRoutesApiV1.InterfaceVersion;
|
||||
t->StructSize = (uint)sizeof(RynthNavRoutesApiV1);
|
||||
t->Request = &Request;
|
||||
t->Poll = &Poll;
|
||||
_table = t;
|
||||
}
|
||||
return (IntPtr)_table;
|
||||
}
|
||||
|
||||
/// <summary>Frees the table and the last string (plugin shutdown).</summary>
|
||||
public static void Release()
|
||||
{
|
||||
var t = _table;
|
||||
_table = null;
|
||||
if (t != null) NativeMemory.Free(t);
|
||||
IntPtr o = _out;
|
||||
_out = IntPtr.Zero;
|
||||
if (o != IntPtr.Zero) Marshal.FreeCoTaskMem(o);
|
||||
}
|
||||
|
||||
private static void Out(byte** dst, string value)
|
||||
{
|
||||
if (dst == null) return;
|
||||
IntPtr fresh = Marshal.StringToCoTaskMemUTF8(value);
|
||||
IntPtr old = _out;
|
||||
_out = fresh;
|
||||
if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old);
|
||||
*dst = (byte*)fresh;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int Request(byte* json, byte** reply)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (reply != null) *reply = null;
|
||||
RynthNavPlugin? p = PluginExports.Runtime.Plugin;
|
||||
if (p == null) { Out(reply, "{\"error\":\"RynthNav isn't running\"}"); return 0; }
|
||||
string text = json == null ? "" : Marshal.PtrToStringUTF8((IntPtr)json) ?? "";
|
||||
string answer = p.RoutesRequest(text, out int id);
|
||||
Out(reply, answer);
|
||||
return id;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int Poll(int id, byte** json)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (json != null) *json = null;
|
||||
RynthNavPlugin? p = PluginExports.Runtime.Plugin;
|
||||
if (p == null) { Out(json, "{\"id\":" + id + ",\"state\":\"unknown\",\"error\":\"RynthNav isn't running\"}"); return 0; }
|
||||
string answer = p.RoutesPoll(id, out bool known);
|
||||
Out(json, answer);
|
||||
return known ? 1 : 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -40,6 +40,8 @@
|
|||
<Compile Include="..\..\Tools\RynthNav.PortalGraph\PortalRoute.cs" Link="PortalRoute.cs" />
|
||||
<!-- Interfaces shared with other RynthSuite plugins (RynthAi uses RynthNav.Path). -->
|
||||
<Compile Include="..\Shared\RynthNavPathApi.cs" Link="Shared\RynthNavPathApi.cs" />
|
||||
<!-- The route maker for other plugins (2026-10-30): JSON jobs to make nav routes, plan, walk. -->
|
||||
<Compile Include="..\Shared\RynthNavRoutesApi.cs" Link="Shared\RynthNavRoutesApi.cs" />
|
||||
<!-- One logged, guarded way to use an object (who used what, and why). -->
|
||||
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
|
||||
<!-- Text in the world on the Nav3D buffer (the path markers' labels; RynthAi's waypoint labels use it too). -->
|
||||
|
|
|
|||
|
|
@ -100,23 +100,35 @@ public sealed partial class RynthNavPlugin
|
|||
|
||||
// ── The trip ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A new plan (Route) or goto (Go): its trip, shown, its path worked out. Tick thread.</summary>
|
||||
private void SetTrip(List<RouteStep>? steps, string goal, double goalNs, double goalEw, List<RecallOption>? recalls,
|
||||
string enterName, bool live)
|
||||
/// <summary>
|
||||
/// A new plan (Route) or goto (Go): its trip, shown, its path worked out (<paramref name="buildPath"/>
|
||||
/// false: the caller works it out, the route maker's makeroute). Tick thread.
|
||||
/// </summary>
|
||||
private PlannedTrip SetTrip(List<RouteStep>? steps, string goal, double goalNs, double goalEw, List<RecallOption>? recalls,
|
||||
string enterName, bool live, bool buildPath = true)
|
||||
{
|
||||
var tr = new List<TripRecall>();
|
||||
if (recalls != null) foreach (RecallOption o in recalls) tr.Add(new TripRecall(o.Name, o.SpellId, o.Command, o.CastSeconds));
|
||||
_trip = new PlannedTrip(++_tripSeq, steps ?? new List<RouteStep>(), goal, goalNs, goalEw,
|
||||
IsOnMap(_cellId), new WorldPt(_wx, _wy, _wz), _cellId, tr,
|
||||
enterName.Length > 0 ? _enterPortal : "", enterName, live);
|
||||
PlannedTrip trip = NewTrip(steps, goal, goalNs, goalEw, recalls, enterName, live);
|
||||
_trip = trip;
|
||||
_tripPath = null;
|
||||
_tripShown = true;
|
||||
_markNext = -1; _markStep = -2;
|
||||
_markLb = CurrentLandblock;
|
||||
_saveConflict = "";
|
||||
_saveDefault = NavRouteExport.SafeName("To " + goal);
|
||||
if (_markersOn) StartPathBuild();
|
||||
if (_markersOn && buildPath) StartPathBuild();
|
||||
_markerStatus = "working out the path…";
|
||||
return trip;
|
||||
}
|
||||
|
||||
/// <summary>A trip planned from where you stand, frozen (not shown). Tick thread.</summary>
|
||||
private PlannedTrip NewTrip(List<RouteStep>? steps, string goal, double goalNs, double goalEw, List<RecallOption>? recalls,
|
||||
string enterName, bool live)
|
||||
{
|
||||
var tr = new List<TripRecall>();
|
||||
if (recalls != null) foreach (RecallOption o in recalls) tr.Add(new TripRecall(o.Name, o.SpellId, o.Command, o.CastSeconds));
|
||||
return new PlannedTrip(++_tripSeq, steps ?? new List<RouteStep>(), goal, goalNs, goalEw,
|
||||
IsOnMap(_cellId), new WorldPt(_wx, _wy, _wz), _cellId, tr,
|
||||
enterName.Length > 0 ? _enterPortal : "", enterName, live);
|
||||
}
|
||||
|
||||
/// <summary>Takes the markers off the ground (the trip stays for "save as nav route"). Tick thread.</summary>
|
||||
|
|
|
|||
718
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.RouteMaker.cs
Normal file
718
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.RouteMaker.cs
Normal file
|
|
@ -0,0 +1,718 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// The route maker (2026-10-30): RynthAi nav routes made on demand, on real walkable paths, for the
|
||||
// player and for another plugin (the "RynthNav.Routes" interface, Shared/RynthNavRoutesApi.cs, which
|
||||
// has the JSON). One implementation for both: a /rnav command and an interface Request each become a
|
||||
// RouteRequest and then a job in the same table, run here.
|
||||
// /rnav makeroute <name> to <place|coords> [overwrite] = route, then saveroute, as one job
|
||||
// /rnav makeloop <name> [at <coords>|here] radius <yd> [points <n>] [overwrite] a hunting loop (LoopMaker)
|
||||
// /rnav makepath <name> [loop|line|once] <coords>; <coords>; ... [overwrite] a nav through points
|
||||
// /rnav routeinfo <name> what a saved nav is (RouteInfo)
|
||||
// and for the interface also plan, atlas, go, stop and where.
|
||||
//
|
||||
// Threads, as the trip path for the markers and "save as nav route" (RynthNavPlugin.Markers.cs): the
|
||||
// tick plans (TravelPlan, the recalls, the switches, the pose) and freezes what a worker needs; the
|
||||
// worker works the walks out in a TilePathFinder of its own (never the walker's navmesh), writes the
|
||||
// file (NavRouteExport.Save: a temp file, then moved in) and hands a RouteWork back; the tick takes it
|
||||
// on a later tick and finishes the job (and answers in chat when it was typed). One worker at a time;
|
||||
// atlas, where, stop and go are quick and run on the tick as soon as they come. The interface's
|
||||
// Request and Poll come on the plugin pump thread, the tick's own; the job table is locked anyway.
|
||||
// Names follow saveroute's rules (NavRouteExport.FileName), into the same folder (RynthAi's
|
||||
// NavProfiles), and a file that's there is never replaced unless asked. RynthAi re-lists NavProfiles
|
||||
// when the folder changes (every 3 s, LegacyDashboardRenderer.TickNavFolder), and /ra nav list and
|
||||
// /ra nav load list it again, so a new route shows without a restart.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const long RouteWorkTimeoutMs = 180000; // a worker job still going after this has failed (its late result is dropped)
|
||||
private const double LoopLivePortalUnits = 300.0; // live portals this far past a loop's radius are kept away from too
|
||||
|
||||
private RouteJobTable? _routeJobs;
|
||||
private RouteJobTable RouteJobs => _routeJobs ??= new RouteJobTable(FirstJobId());
|
||||
// The one worker job (tick thread).
|
||||
private RouteJob? _workJob;
|
||||
private Task<RouteWork>? _workTask;
|
||||
private long _workStartMs;
|
||||
private bool _workTimedOut;
|
||||
// Building outlines (NavData\worldmap.vec), read by the first loop's worker.
|
||||
private BuildingOutlines? _buildings;
|
||||
private bool _buildingsTried;
|
||||
// The goto a go job started (tick thread): its job, and how the last goto ended (FinishGoto).
|
||||
private int _goJobId;
|
||||
private string _gotoEndStatus = "";
|
||||
private int _gotoEndSeq;
|
||||
private readonly Dictionary<int, GoInfo> _goInfo = new();
|
||||
|
||||
/// <summary>Job ids start from the clock (seconds since boot), so a RynthNav reload doesn't hand a caller's old ids to new jobs.</summary>
|
||||
private static int FirstJobId() => (int)(Environment.TickCount64 / 1000 % 2_000_000) * 1000 + 1;
|
||||
|
||||
/// <summary>What a worker hands back to the tick.</summary>
|
||||
private sealed class RouteWork
|
||||
{
|
||||
public bool Ok;
|
||||
public string Detail = "";
|
||||
public string Json = "null";
|
||||
/// <summary>The chat answer (a job typed in chat): the first line is the result.</summary>
|
||||
public readonly List<string> Lines = new();
|
||||
public readonly List<string> Log = new();
|
||||
/// <summary>A plan's or makeroute's trip and its path (the markers show it when it's still the trip shown).</summary>
|
||||
public PlannedTrip? Trip;
|
||||
public TripPath? Path;
|
||||
/// <summary>A loop's worker read the building outlines: kept for the next one.</summary>
|
||||
public bool BuildingsRead;
|
||||
public BuildingOutlines? Buildings;
|
||||
}
|
||||
|
||||
private sealed class GoInfo
|
||||
{
|
||||
public string Name = "", Enter = "";
|
||||
public double Ns, Ew;
|
||||
public int Steps, Teleports;
|
||||
}
|
||||
|
||||
private static bool IsWorkerOp(RouteOp op) => op is RouteOp.Plan or RouteOp.MakeRoute or RouteOp.MakeLoop or RouteOp.MakePath or RouteOp.Info;
|
||||
|
||||
// ── In: chat and the interface ───────────────────────────────────────
|
||||
|
||||
/// <summary>/rnav makeroute | makeloop | makepath | routeinfo: queued; the answer comes when the job is done. Tick thread.</summary>
|
||||
private void CmdRouteMaker(string cmd, string rest)
|
||||
{
|
||||
RouteOp op = cmd switch { "makeroute" => RouteOp.MakeRoute, "makeloop" => RouteOp.MakeLoop, "makepath" => RouteOp.MakePath, _ => RouteOp.Info };
|
||||
RouteRequest? req = RouteRequest.FromCommand(cmd, rest, out string error);
|
||||
if (req == null) { SayFail($"{cmd}: {error} — {RouteRequest.Usage(op, chat: true)}"); return; }
|
||||
RouteJob? job = RouteJobs.Add(req, NowMs, out error);
|
||||
if (job == null) { SayFail($"{cmd}: {error}"); return; }
|
||||
Host.Log($"[RynthNav] job {job.Id} {cmd} queued (chat)");
|
||||
// It starts on this tick unless another route is being worked out: then say it waits.
|
||||
if (_workTask != null) Say($"{cmd}: queued; another route is being worked out first ({RouteJobs.Queued().Count} waiting)");
|
||||
}
|
||||
|
||||
/// <summary>"RynthNav.Routes" Request: a job id (and its JSON), or 0 and {error, usage}. Plugin pump thread.</summary>
|
||||
internal string RoutesRequest(string json, out int id)
|
||||
{
|
||||
id = 0;
|
||||
RouteRequest? req = RouteRequest.FromJson(json, out string error);
|
||||
if (req == null)
|
||||
{
|
||||
Host.Log($"[RynthNav] routes request refused: {error}");
|
||||
return RouteJson.Error(error, RouteRequest.UsageFor(json));
|
||||
}
|
||||
RouteJob? job = RouteJobs.Add(req, NowMs, out error);
|
||||
if (job == null) return RouteJson.Error(error, "");
|
||||
id = job.Id;
|
||||
Host.Log($"[RynthNav] job {job.Id} {RouteRequest.OpName(req.Op)} queued (interface)");
|
||||
return RouteJobs.Accepted(job);
|
||||
}
|
||||
|
||||
/// <summary>"RynthNav.Routes" Poll. Any thread.</summary>
|
||||
internal string RoutesPoll(int id, out bool known) => RouteJobs.PollJson(id, out known);
|
||||
|
||||
// ── The tick ─────────────────────────────────────────────────────────
|
||||
|
||||
private void TickRouteJobs()
|
||||
{
|
||||
if (_routeJobs == null) return;
|
||||
long now = NowMs;
|
||||
TakeRouteWork(now);
|
||||
foreach (RouteJob j in _routeJobs.Working())
|
||||
if (j.Request.Op == RouteOp.Go) TickGoJob(j, now);
|
||||
foreach (RouteJob j in _routeJobs.Queued())
|
||||
{
|
||||
if (!IsWorkerOp(j.Request.Op)) { RunNow(j, now); continue; }
|
||||
if (_workTask == null) StartWork(j, now);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A job is over: the table, the log, and the chat when it was typed.</summary>
|
||||
private void EndJob(RouteJob j, bool ok, string detail, string? json, long now, IReadOnlyList<string>? lines = null)
|
||||
{
|
||||
RouteJobs.Finish(j, ok, detail, json, now);
|
||||
Host.Log($"[RynthNav] job {j.Id} {RouteRequest.OpName(j.Request.Op)}: {(ok ? "done" : "failed")}: {detail} ({now - j.CreatedMs} ms)");
|
||||
if (!j.Request.FromChat) return;
|
||||
string cmd = j.Request.Command;
|
||||
if (lines != null && lines.Count > 0)
|
||||
{
|
||||
if (ok) Say(lines[0]); else SayFail($"{lines[0]} — {RouteRequest.Usage(j.Request.Op, chat: true)}");
|
||||
for (int i = 1; i < lines.Count; i++) Say(lines[i]);
|
||||
}
|
||||
else if (ok) Say($"{cmd}: {detail}");
|
||||
else SayFail($"{cmd}: {detail} — {RouteRequest.Usage(j.Request.Op, chat: true)}");
|
||||
}
|
||||
|
||||
private void FailJob(RouteJob j, string why, long now) => EndJob(j, false, why, RouteJson.Error(why, ""), now);
|
||||
|
||||
private void TakeRouteWork(long now)
|
||||
{
|
||||
if (_workTask == null || _workJob == null) return;
|
||||
if (!_workTask.IsCompleted)
|
||||
{
|
||||
if (!_workTimedOut && now - _workStartMs > RouteWorkTimeoutMs)
|
||||
{
|
||||
_workTimedOut = true;
|
||||
FailJob(_workJob, $"still working after {RouteWorkTimeoutMs / 1000} s: given up (a late result is dropped)", now);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Task<RouteWork> task = _workTask;
|
||||
RouteJob job = _workJob;
|
||||
bool late = _workTimedOut;
|
||||
_workTask = null; _workJob = null; _workTimedOut = false;
|
||||
RouteWork w;
|
||||
if (task.IsFaulted)
|
||||
{
|
||||
string why = task.Exception?.GetBaseException().Message ?? "unknown";
|
||||
w = new RouteWork { Ok = false, Detail = "failed: " + why, Json = RouteJson.Error("failed: " + why, "") };
|
||||
w.Lines.Add($"{job.Request.Command}: failed ({why}); see the log");
|
||||
}
|
||||
else w = task.Result;
|
||||
foreach (string line in w.Log) Host.Log(line);
|
||||
if (w.BuildingsRead)
|
||||
{
|
||||
_buildings = w.Buildings; _buildingsTried = true;
|
||||
Host.Log(w.Buildings != null ? $"[RynthNav] building outlines: {w.Buildings.Count} from {BuildingOutlines.FileName}"
|
||||
: $"[RynthNav] building outlines: no {BuildingOutlines.FileName} in {NavDataDir}");
|
||||
}
|
||||
// A plan's path is the shown trip's too (makeroute typed in chat shows it): the markers draw it.
|
||||
if (w.Trip != null && w.Path != null && ReferenceEquals(_trip, w.Trip) && (_tripPath == null || _tripPath.TripId != w.Trip.Id))
|
||||
{
|
||||
_tripPath = w.Path;
|
||||
int points = 0;
|
||||
foreach (WorldPt[]? p in w.Path.Walks) points += p?.Length ?? 0;
|
||||
_markerStatus = $"{points} waypoints";
|
||||
OnPathReady(_trip, w.Path);
|
||||
}
|
||||
if (late) return;
|
||||
EndJob(job, w.Ok, w.Detail, w.Json, now, w.Lines);
|
||||
}
|
||||
|
||||
// ── Quick ops (the tick) ─────────────────────────────────────────────
|
||||
|
||||
private void RunNow(RouteJob j, long now)
|
||||
{
|
||||
RouteRequest q = j.Request;
|
||||
switch (q.Op)
|
||||
{
|
||||
case RouteOp.Atlas:
|
||||
{
|
||||
Atlas atlas = _atlas;
|
||||
if (atlas.Locations.Count == 0) { FailJob(j, "the Atlas isn't loaded (" + _atlasStatus + ")", now); return; }
|
||||
bool hasPos = PlayerMapPos(out double pns, out double pew);
|
||||
List<AtlasLocation> hits = atlas.Search(q.Search, null, q.Max);
|
||||
string json = RouteJson.Write(w =>
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("search", q.Search);
|
||||
w.WriteNumber("count", hits.Count);
|
||||
w.WriteStartArray("places");
|
||||
foreach (AtlasLocation l in hits)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("name", l.Name);
|
||||
w.WriteString("kind", l.Type);
|
||||
w.WriteBoolean("onMap", l.OnMap);
|
||||
RouteJson.Num(w, "ns", l.OnMap ? l.Ns : double.NaN, 4);
|
||||
RouteJson.Num(w, "ew", l.OnMap ? l.Ew : double.NaN, 4);
|
||||
RouteJson.Num(w, "yards", l.OnMap && hasPos ? NavCoords.Distance(pns, pew, l.Ns, l.Ew) : double.NaN, 0);
|
||||
if (!l.OnMap) w.WriteString("where", l.Desc.Length > 0 ? l.Desc : "in a dungeon");
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
w.WriteEndObject();
|
||||
});
|
||||
EndJob(j, true, hits.Count == 0 ? $"no place matches \"{q.Search}\"" : $"{hits.Count} place(s)", json, now);
|
||||
return;
|
||||
}
|
||||
case RouteOp.Where:
|
||||
{
|
||||
if (!_hasPose) { FailJob(j, "no player position yet", now); return; }
|
||||
bool onMap = PlayerMapPos(out double ns, out double ew);
|
||||
double nearYd = double.NaN;
|
||||
AtlasLocation? near = onMap ? NearestPlace(ns, ew, out nearYd) : null;
|
||||
bool dungeon = InDungeon(_cellId), indoors = (_cellId & 0xFFFF) >= 0x100;
|
||||
string json = RouteJson.Write(w =>
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteBoolean("onMap", onMap);
|
||||
RouteJson.Num(w, "ns", onMap ? ns : double.NaN, 4);
|
||||
RouteJson.Num(w, "ew", onMap ? ew : double.NaN, 4);
|
||||
w.WriteString("landblock", CurrentLandblock.ToString("X4", CultureInfo.InvariantCulture));
|
||||
w.WriteString("cell", _cellId.ToString("X8", CultureInfo.InvariantCulture));
|
||||
w.WriteBoolean("indoors", indoors);
|
||||
w.WriteBoolean("dungeon", dungeon);
|
||||
w.WriteBoolean("walking", _gotoActive);
|
||||
if (near != null)
|
||||
{
|
||||
w.WriteStartObject("nearest");
|
||||
w.WriteString("name", near.Name);
|
||||
w.WriteString("kind", near.Type);
|
||||
RouteJson.Num(w, "ns", near.Ns, 4);
|
||||
RouteJson.Num(w, "ew", near.Ew, 4);
|
||||
RouteJson.Num(w, "yards", nearYd, 0);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
else w.WriteNull("nearest");
|
||||
w.WriteEndObject();
|
||||
});
|
||||
string at = onMap ? NavCoords.Fmt(ns, ew) : dungeon ? "in a dungeon" : "off the map";
|
||||
EndJob(j, true, $"{at}, landblock 0x{CurrentLandblock:X4}{(near != null ? $", {NavCoords.FmtDistance(nearYd)} from {near.Name}" : "")}", json, now);
|
||||
return;
|
||||
}
|
||||
case RouteOp.Stop:
|
||||
{
|
||||
bool was = _gotoActive;
|
||||
DoMove(5); // as /rnav stop: the walk ends on the next tick
|
||||
EndJob(j, true, was ? "stopping the walk" : "nothing was walking",
|
||||
RouteJson.Write(w => { w.WriteStartObject(); w.WriteBoolean("wasWalking", was); w.WriteEndObject(); }), now);
|
||||
return;
|
||||
}
|
||||
case RouteOp.Go:
|
||||
StartGoJob(j, now);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Atlas place on the map nearest (ns, ew), and how far.</summary>
|
||||
private AtlasLocation? NearestPlace(double ns, double ew, out double yards)
|
||||
{
|
||||
AtlasLocation? best = null;
|
||||
yards = double.MaxValue;
|
||||
foreach (AtlasLocation l in _atlas.Locations)
|
||||
{
|
||||
if (!l.OnMap) continue;
|
||||
double d = NavCoords.Distance(ns, ew, l.Ns, l.Ew);
|
||||
if (d < yards) { yards = d; best = l; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// ── go: walk there as /rnav go does, and follow the walk to its end ──
|
||||
|
||||
private void StartGoJob(RouteJob j, long now)
|
||||
{
|
||||
if (!_hasPose) { FailJob(j, "no player position yet", now); return; }
|
||||
if (!ResolveGo(j.Request.To, out string name, out string type, out double ns, out double ew, out string enter, out string enterType, out string error))
|
||||
{
|
||||
EndJob(j, false, error, GoJson(null, false, "failed", error), now);
|
||||
return;
|
||||
}
|
||||
_store.Touch(new SavedPlace { Name = name, Type = type, Ns = ns, Ew = ew });
|
||||
_goNote = "";
|
||||
StartWalk(name, type, ns, ew, enter, enterType); // says "walking to ..." in chat, or why it can't
|
||||
if (!_gotoActive)
|
||||
{
|
||||
string why = _goNote.Length > 0 ? _goNote : "the walk didn't start";
|
||||
EndJob(j, false, why, GoJson(null, false, "failed", why), now);
|
||||
return;
|
||||
}
|
||||
_goJobId = j.Id;
|
||||
j.Seq = _gotoEndSeq;
|
||||
int teleports = 0;
|
||||
if (_route != null) foreach (RouteStep s in _route) if (s.UsePortal || s.UseRecall || s.IsHub) teleports++;
|
||||
var info = new GoInfo { Name = enter.Length > 0 ? enter : name, Enter = enter, Ns = ns, Ew = ew, Steps = _route?.Count ?? 1, Teleports = teleports };
|
||||
_goInfo[j.Id] = info;
|
||||
string line; lock (_gate) line = _goLine;
|
||||
RouteJobs.Start(j, line.Length > 0 ? line : $"walking to {info.Name}", now);
|
||||
RouteJobs.Update(j, j.Detail, GoJson(info, true, "walking", ""));
|
||||
}
|
||||
|
||||
private void TickGoJob(RouteJob j, long now)
|
||||
{
|
||||
_goInfo.TryGetValue(j.Id, out GoInfo? info);
|
||||
if (_goJobId != j.Id)
|
||||
{
|
||||
EndGo(j, info, true, "stopped", "stopped: another goto took over", now);
|
||||
return;
|
||||
}
|
||||
if (_gotoActive)
|
||||
{
|
||||
string line; lock (_gate) line = _goLine;
|
||||
if (line.Length > 0 && line != j.Detail) RouteJobs.Update(j, line);
|
||||
return;
|
||||
}
|
||||
string status = _gotoEndSeq != j.Seq ? _gotoEndStatus
|
||||
: !_hasPose ? "stopped: logged out"
|
||||
: _goNote.Length > 0 ? _goNote : "stopped: the walk ended";
|
||||
_goJobId = 0;
|
||||
bool ok = RouteJobTable.GoOutcome(status, out string outcome);
|
||||
EndGo(j, info, ok, outcome, status, now);
|
||||
}
|
||||
|
||||
private void EndGo(RouteJob j, GoInfo? info, bool ok, string outcome, string status, long now)
|
||||
{
|
||||
_goInfo.Remove(j.Id);
|
||||
EndJob(j, ok, status, GoJson(info, true, outcome, status), now);
|
||||
}
|
||||
|
||||
private static string GoJson(GoInfo? info, bool started, string outcome, string reason) => RouteJson.Write(w =>
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteBoolean("started", started);
|
||||
if (info != null)
|
||||
{
|
||||
w.WriteStartObject("to");
|
||||
w.WriteString("name", info.Name);
|
||||
RouteJson.Num(w, "ns", info.Ns, 4);
|
||||
RouteJson.Num(w, "ew", info.Ew, 4);
|
||||
w.WriteEndObject();
|
||||
if (info.Enter.Length > 0) w.WriteString("enter", info.Enter); else w.WriteNull("enter");
|
||||
w.WriteNumber("steps", info.Steps);
|
||||
w.WriteNumber("teleports", info.Teleports);
|
||||
}
|
||||
w.WriteString("outcome", outcome);
|
||||
if (reason.Length > 0) w.WriteString("reason", reason);
|
||||
w.WriteEndObject();
|
||||
});
|
||||
|
||||
// ── Worker ops: what the tick freezes, then the worker ──────────────
|
||||
|
||||
private void StartWork(RouteJob j, long now)
|
||||
{
|
||||
RouteRequest q = j.Request;
|
||||
Func<RouteWork>? work = q.Op switch
|
||||
{
|
||||
RouteOp.Plan or RouteOp.MakeRoute => PrepareTrip(j, now),
|
||||
RouteOp.MakeLoop => PrepareLoop(j, now),
|
||||
RouteOp.MakePath => PreparePath(j, now),
|
||||
_ => PrepareInfo(j),
|
||||
};
|
||||
if (work == null) return; // refused on the tick (already finished)
|
||||
_workJob = j;
|
||||
_workStartMs = now;
|
||||
_workTimedOut = false;
|
||||
_workTask = Task.Run(work);
|
||||
}
|
||||
|
||||
/// <summary>A make op's name that is taken, unless overwrite was asked: refused before any work.</summary>
|
||||
private bool NameTaken(RouteJob j, long now)
|
||||
{
|
||||
RouteRequest q = j.Request;
|
||||
if (q.Overwrite || !File.Exists(Path.Combine(NavProfilesDir, q.Name + ".nav"))) return false;
|
||||
FailJob(j, $"{q.Name}.nav is already in RynthAi's NavProfiles; ask again with overwrite to replace it", now);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The portal objects the client sees within <paramref name="range"/> of (x, y), as avoid circles. Tick thread.</summary>
|
||||
private List<PortalAvoid.Spot> LivePortalsNear(double x, double y, double range)
|
||||
{
|
||||
var list = new List<PortalAvoid.Spot>();
|
||||
if (!Host.HasGetLiveObjectIds) return list;
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue;
|
||||
if (!Host.TryGetObjectPosition(id, out uint cell, out float ox, out float oy, out _) || cell == 0 || (cell & 0xFFFF) >= 0x100) continue;
|
||||
double wx = ((cell >> 24) & 0xFF) * 192.0 + ox, wy = ((cell >> 16) & 0xFF) * 192.0 + oy;
|
||||
if (Math.Abs(wx - x) > range || Math.Abs(wy - y) > range) continue;
|
||||
Host.TryGetObjectName(id, out string name);
|
||||
list.Add(new PortalAvoid.Spot(wx, wy, PortalAvoid.LiveRadius, name ?? ""));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// plan, makeroute: plan on the tick (as /rnav route), the trip's path and the file on the worker.
|
||||
private Func<RouteWork>? PrepareTrip(RouteJob j, long now)
|
||||
{
|
||||
RouteRequest q = j.Request;
|
||||
if (q.Op == RouteOp.MakeRoute && NameTaken(j, now)) return null;
|
||||
if (!_hasPose) { FailJob(j, "no player position yet", now); return null; }
|
||||
if (!ResolveTarget(q.To, out string name, out _, out double ns, out double ew, out string error)) { FailJob(j, error, now); return null; }
|
||||
TravelPlan.Result plan = PlanRoute(name, ns, ew, out List<RecallOption> recalls, q.Portals);
|
||||
if (plan.Refusal.Length > 0) { FailJob(j, $"no way to {name}: {plan.Refusal}", now); return null; }
|
||||
bool portalsOn = q.Portals ?? _portalsEnabled;
|
||||
PlannedTrip trip;
|
||||
if (q.Show || q.FromChat)
|
||||
{
|
||||
// As /rnav route: the panel shows the plan and the markers its path (worked out below, once).
|
||||
_shownRoute = plan.Steps ?? new List<RouteStep> { new(ns, ew, false, false, "walk") };
|
||||
_shownRouteFor = name; _shownRouteEst = plan.Est; _shownRouteLive = false; _routeVersion++;
|
||||
trip = SetTrip(plan.Steps, name, ns, ew, recalls, "", live: false, buildPath: false);
|
||||
}
|
||||
else trip = NewTrip(plan.Steps, name, ns, ew, recalls, "", live: false);
|
||||
if (q.FromChat) Say($"{q.Command}: working out the walk to {name}…");
|
||||
RouteJobs.Start(j, $"working out the walk to {name}", now);
|
||||
|
||||
NavGraph? g = UsableGraph();
|
||||
IReadOnlyList<PortalAvoid.Spot> portals = AtlasPortalSpots();
|
||||
TownNet? net = _townNet;
|
||||
string dir = NavDataDir, folder = NavProfilesDir;
|
||||
int teleports = plan.Teleports;
|
||||
return () => TripWork(q, trip, g, portals, net, dir, folder, teleports, portalsOn);
|
||||
}
|
||||
|
||||
private static RouteWork TripWork(RouteRequest q, PlannedTrip trip, NavGraph? g, IReadOnlyList<PortalAvoid.Spot> portals,
|
||||
TownNet? net, string dir, string folder, int teleports, bool portalsOn)
|
||||
{
|
||||
var o = new RouteWork { Trip = trip };
|
||||
long t0 = Environment.TickCount64;
|
||||
var finder = new TilePathFinder(dir, g, portals);
|
||||
TripPath path = TripPathBuilder.Build(trip, (WorldPt a, WorldPt b, bool intoPortal, out string note) => finder.Walk(a, b, intoPortal, out note), net);
|
||||
o.Path = path;
|
||||
o.Log.Add($"[RynthNav] job: the walk to {trip.Goal}: {trip.Count} step(s), {finder.TilesRead} tile(s) read, {Environment.TickCount64 - t0} ms");
|
||||
foreach (string n in path.Notes) o.Log.Add($"[RynthNav] job: trip path: {n}");
|
||||
TripSummary sum = TripSummary.Of(trip, path);
|
||||
|
||||
if (q.Op == RouteOp.Plan)
|
||||
{
|
||||
o.Ok = true;
|
||||
o.Detail = $"to {trip.Goal}: {sum.Steps.Count} step(s), {NavCoords.FmtDistance(sum.Yards)} walking, {sum.Teleports} teleport(s), about {sum.Minutes:F1} min";
|
||||
o.Json = RouteJson.Write(w =>
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteStartObject("to");
|
||||
w.WriteString("name", trip.Goal);
|
||||
RouteJson.Num(w, "ns", trip.GoalNs, 4);
|
||||
RouteJson.Num(w, "ew", trip.GoalEw, 4);
|
||||
w.WriteEndObject();
|
||||
w.WriteBoolean("portals", portalsOn);
|
||||
sum.WriteFields(w);
|
||||
RouteJson.Strings(w, "notes", path.Notes);
|
||||
w.WriteEndObject();
|
||||
});
|
||||
return o;
|
||||
}
|
||||
|
||||
// makeroute: as saveroute (RynthNavPlugin.SaveRoute.cs).
|
||||
NavRouteExport.Result r = NavRouteExport.Convert(trip, path, net);
|
||||
if (r.Route.Points.Count == 0)
|
||||
return Failed(o, q, $"nothing to save: {(r.StopReason.Length > 0 ? r.StopReason : "the trip has no steps")}");
|
||||
if (!SaveNav(o, q, folder, r.Route, out string file)) return o;
|
||||
double yards = RouteInfo.Length(r.Route);
|
||||
o.Ok = true;
|
||||
o.Detail = $"saved {q.Name}.nav: {r.Route.Points.Count} steps, {NavCoords.FmtDistance(yards)} walking";
|
||||
string line = $"{q.Command}: saved {q.Name}.nav to {folder}: {r.Route.Points.Count} steps ({r.Waypoints} waypoints"
|
||||
+ (r.Portals > 0 ? $", {r.Portals} portal(s)" : "") + (r.Recalls + r.Chats > 0 ? $", {r.Recalls + r.Chats} recall(s)" : "")
|
||||
+ $"). RynthAi: pick it in Nav, or /ra nav load {q.Name}.";
|
||||
if (r.StoppedAt >= 0) line += $" It stops short of {trip.Goal}: {r.StopReason}.";
|
||||
if (path.Notes.Count > 0) line += $" Check it: {path.Notes[0]}{(path.Notes.Count > 1 ? $" (+{path.Notes.Count - 1} more in the log)" : "")}.";
|
||||
o.Lines.Add(line);
|
||||
o.Log.Add($"[RynthNav] {line} ({file})");
|
||||
o.Json = MakeJson(q, file, r.Route, yards, null, w =>
|
||||
{
|
||||
w.WriteStartObject("to");
|
||||
w.WriteString("name", trip.Goal);
|
||||
RouteJson.Num(w, "ns", trip.GoalNs, 4);
|
||||
RouteJson.Num(w, "ew", trip.GoalEw, 4);
|
||||
w.WriteEndObject();
|
||||
w.WriteNumber("waypoints", r.Waypoints);
|
||||
w.WriteNumber("portals", r.Portals);
|
||||
w.WriteNumber("recalls", r.Recalls + r.Chats);
|
||||
w.WriteNumber("teleports", teleports);
|
||||
if (r.StoppedAt >= 0) w.WriteString("stoppedShort", r.StopReason); else w.WriteNull("stoppedShort");
|
||||
}, path.Notes);
|
||||
return o;
|
||||
}
|
||||
|
||||
// makeloop: the centre and the portals on the tick, the loop and the file on the worker.
|
||||
private Func<RouteWork>? PrepareLoop(RouteJob j, long now)
|
||||
{
|
||||
RouteRequest q = j.Request;
|
||||
if (NameTaken(j, now)) return null;
|
||||
WorldPt centre;
|
||||
if (q.Here)
|
||||
{
|
||||
if (!_hasPose) { FailJob(j, "no player position yet", now); return null; }
|
||||
if (InDungeon(_cellId) || !IsOnMap(_cellId)) { FailJob(j, "you're in a dungeon: loops are made on the landscape (give at <coords>)", now); return null; }
|
||||
centre = new WorldPt(_wx, _wy, _wz);
|
||||
}
|
||||
else centre = WorldPt.FromMap(q.AtNs, q.AtEw, double.NaN);
|
||||
if (centre.Landblock == uint.MaxValue) { FailJob(j, $"{NavCoords.Fmt(centre.Ns, centre.Ew)} is off the map", now); return null; }
|
||||
if (!File.Exists(Path.Combine(NavDataDir, $"nav_{centre.Landblock:X4}.tile")))
|
||||
{ FailJob(j, $"no navmesh at {NavCoords.Fmt(centre.Ns, centre.Ew)} (landblock 0x{centre.Landblock:X4} has no tile in {NavDataDir})", now); return null; }
|
||||
|
||||
IReadOnlyList<PortalAvoid.Spot> atlasPortals = AtlasPortalSpots();
|
||||
List<PortalAvoid.Spot> live = _hasPose ? LivePortalsNear(centre.X, centre.Y, q.Radius + LoopLivePortalUnits) : new List<PortalAvoid.Spot>();
|
||||
int points = q.Points > 0 ? q.Points : RouteShape.DefaultPoints(q.Radius);
|
||||
var opt = new LoopMaker.LoopOptions { Radius = q.Radius, Points = points, WallClearance = _avoidWalls ? _wallClearance : 0 };
|
||||
if (q.FromChat) Say($"{q.Command}: choosing {points} points round {NavCoords.Fmt(centre.Ns, centre.Ew)} within {q.Radius:F0} yd…");
|
||||
RouteJobs.Start(j, $"choosing {points} points round {NavCoords.Fmt(centre.Ns, centre.Ew)}", now);
|
||||
string dir = NavDataDir, folder = NavProfilesDir;
|
||||
bool tried = _buildingsTried;
|
||||
BuildingOutlines? buildings = _buildings;
|
||||
return () => LoopWork(q, centre, opt, atlasPortals, live, dir, folder, tried, buildings);
|
||||
}
|
||||
|
||||
private static RouteWork LoopWork(RouteRequest q, WorldPt centre, LoopMaker.LoopOptions opt, IReadOnlyList<PortalAvoid.Spot> atlasPortals,
|
||||
List<PortalAvoid.Spot> live, string dir, string folder, bool buildingsTried, BuildingOutlines? buildings)
|
||||
{
|
||||
var o = new RouteWork();
|
||||
if (!buildingsTried)
|
||||
{
|
||||
buildings = BuildingOutlines.Load(Path.Combine(dir, BuildingOutlines.FileName));
|
||||
o.BuildingsRead = true; o.Buildings = buildings;
|
||||
}
|
||||
long t0 = Environment.TickCount64;
|
||||
var all = new List<PortalAvoid.Spot>(live);
|
||||
all.AddRange(atlasPortals);
|
||||
var finder = new TilePathFinder(dir, null, atlasPortals, live);
|
||||
LoopMaker.Result r = LoopMaker.Loop(finder, centre, opt, buildings, all);
|
||||
o.Log.Add($"[RynthNav] job: loop round {NavCoords.Fmt(centre.Ns, centre.Ew)}, {opt.Radius:F0} yd: {(r.Ok ? $"{r.Points.Count} of {r.Asked} points, {r.Yards:F0} yd" : r.Error)}; "
|
||||
+ $"{finder.TilesRead} tile(s) read, {Environment.TickCount64 - t0} ms");
|
||||
foreach (LoopMaker.Dropped d in r.DroppedPoints) o.Log.Add($"[RynthNav] job: loop point at {NavCoords.Fmt(d.Ns, d.Ew)} dropped: {d.Why}");
|
||||
if (!r.Ok || r.Route == null) { Failed(o, q, r.Error); o.Json = MakeJson(q, "", null, 0, r.DroppedPoints, null, r.Notes, r.Error); return o; }
|
||||
if (!SaveNav(o, q, folder, r.Route, out string file)) return o;
|
||||
o.Ok = true;
|
||||
o.Detail = $"saved {q.Name}.nav: {r.Points.Count} points, {NavCoords.FmtDistance(r.Yards)} a lap"
|
||||
+ (r.DroppedPoints.Count > 0 ? $", {r.DroppedPoints.Count} dropped" : "");
|
||||
string line = $"{q.Command}: saved {q.Name}.nav (circular): {r.Points.Count} points round {NavCoords.Fmt(r.Centre.Ns, r.Centre.Ew)}, "
|
||||
+ $"radius {opt.Radius:F0} yd, {NavCoords.FmtDistance(r.Yards)} a lap, {r.Route.Points.Count} waypoints"
|
||||
+ (r.DroppedPoints.Count > 0 ? $"; {r.DroppedPoints.Count} point(s) dropped ({r.DroppedPoints[0].Why}{(r.DroppedPoints.Count > 1 ? ", ..." : "")})" : "")
|
||||
+ $". RynthAi: /ra nav load {q.Name}.";
|
||||
o.Lines.Add(line);
|
||||
foreach (string n in r.Notes) o.Lines.Add($" {q.Command}: {n}");
|
||||
o.Log.Add($"[RynthNav] {line} ({file})");
|
||||
o.Json = MakeJson(q, file, r.Route, r.Yards, r.DroppedPoints, w =>
|
||||
{
|
||||
RouteJson.Place(w, "centre", r.Centre.Ns, r.Centre.Ew);
|
||||
RouteJson.Num(w, "radius", opt.Radius, 1);
|
||||
w.WriteNumber("loopPoints", r.Points.Count);
|
||||
w.WriteNumber("asked", r.Asked);
|
||||
}, r.Notes);
|
||||
return o;
|
||||
}
|
||||
|
||||
// makepath: the points and the portals on the tick, the legs and the file on the worker.
|
||||
private Func<RouteWork>? PreparePath(RouteJob j, long now)
|
||||
{
|
||||
RouteRequest q = j.Request;
|
||||
if (NameTaken(j, now)) return null;
|
||||
var pts = new List<WorldPt>(q.Path.Count);
|
||||
double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
|
||||
foreach (var (ns, ew) in q.Path)
|
||||
{
|
||||
WorldPt p = WorldPt.FromMap(ns, ew, double.NaN);
|
||||
pts.Add(p);
|
||||
minX = Math.Min(minX, p.X); minY = Math.Min(minY, p.Y); maxX = Math.Max(maxX, p.X); maxY = Math.Max(maxY, p.Y);
|
||||
}
|
||||
IReadOnlyList<PortalAvoid.Spot> atlasPortals = _avoidPortals ? AtlasPortalSpots() : Array.Empty<PortalAvoid.Spot>();
|
||||
var live = new List<PortalAvoid.Spot>();
|
||||
if (_avoidPortals && _hasPose)
|
||||
foreach (PortalAvoid.Spot s in LivePortalsNear((minX + maxX) / 2, (minY + maxY) / 2, Math.Max(maxX - minX, maxY - minY) / 2 + AvoidNearUnits))
|
||||
live.Add(s);
|
||||
bool strict = _avoidPortals;
|
||||
double wall = _avoidWalls ? _wallClearance : 0;
|
||||
NavGraph? g = UsableGraph();
|
||||
if (q.FromChat) Say($"{q.Command}: walking out {q.Path.Count} points…");
|
||||
RouteJobs.Start(j, $"working out {q.Path.Count} points", now);
|
||||
string dir = NavDataDir, folder = NavProfilesDir;
|
||||
return () => PathWork(q, pts, g, atlasPortals, live, strict, wall, dir, folder);
|
||||
}
|
||||
|
||||
private static RouteWork PathWork(RouteRequest q, List<WorldPt> pts, NavGraph? g, IReadOnlyList<PortalAvoid.Spot> atlasPortals,
|
||||
List<PortalAvoid.Spot> live, bool strict, double wall, string dir, string folder)
|
||||
{
|
||||
var o = new RouteWork();
|
||||
long t0 = Environment.TickCount64;
|
||||
var finder = new TilePathFinder(dir, g, atlasPortals, live) { StrictPortals = strict, WallClearance = wall };
|
||||
var all = new List<PortalAvoid.Spot>(live);
|
||||
all.AddRange(atlasPortals);
|
||||
LoopMaker.Result r = LoopMaker.Path(finder, pts, q.PathType, TripPathBuilder.MaxSpacing / 2, all);
|
||||
o.Log.Add($"[RynthNav] job: path through {pts.Count} points ({RouteInfo.TypeName(q.PathType)}): {(r.Ok ? $"{r.Legs.Count} leg(s), {r.Yards:F0} yd" : r.Error)}; "
|
||||
+ $"{finder.TilesRead} tile(s) read, {Environment.TickCount64 - t0} ms");
|
||||
if (!r.Ok || r.Route == null) { Failed(o, q, r.Error); return o; }
|
||||
if (!SaveNav(o, q, folder, r.Route, out string file)) return o;
|
||||
o.Ok = true;
|
||||
string type = RouteInfo.TypeName(q.PathType);
|
||||
o.Detail = $"saved {q.Name}.nav: {pts.Count} points, {r.Legs.Count} leg(s), {NavCoords.FmtDistance(r.Yards)}";
|
||||
string line = $"{q.Command}: saved {q.Name}.nav ({type}): {pts.Count} points, {r.Legs.Count} leg(s), {NavCoords.FmtDistance(r.Yards)}"
|
||||
+ $"{(q.PathType == NavRouteType.Circular ? " a lap" : "")}, {r.Route.Points.Count} waypoints. RynthAi: /ra nav load {q.Name}.";
|
||||
o.Lines.Add(line);
|
||||
o.Log.Add($"[RynthNav] {line} ({file})");
|
||||
o.Json = MakeJson(q, file, r.Route, r.Yards, r.DroppedPoints, w =>
|
||||
{
|
||||
w.WriteNumber("given", pts.Count);
|
||||
w.WriteNumber("legs", r.Legs.Count);
|
||||
}, r.Notes);
|
||||
return o;
|
||||
}
|
||||
|
||||
// info: the file on the worker; what a landblock is (dungeon or not) and the spell names from the tick.
|
||||
private Func<RouteWork>? PrepareInfo(RouteJob j)
|
||||
{
|
||||
RouteRequest q = j.Request;
|
||||
bool hasPlayer = PlayerMapPos(out double pns, out double pew);
|
||||
HashSet<uint> dungeons = _dungeonLandblocks, map = _mapLandblocks;
|
||||
var spells = new Dictionary<int, string>
|
||||
{
|
||||
[RecallPlanner.LifestoneRecall] = "Lifestone Recall", [RecallPlanner.PortalRecall] = "Portal Recall",
|
||||
[RecallPlanner.PrimaryPortalTieRecall] = "Primary Portal Tie Recall", [RecallPlanner.SecondaryPortalTieRecall] = "Secondary Portal Tie Recall",
|
||||
};
|
||||
foreach (AtlasRecall r in _atlas.Recalls) spells.TryAdd(r.SpellId, r.Name);
|
||||
string dir = NavDataDir, folder = NavProfilesDir;
|
||||
RouteJobs.Start(j, $"reading {q.Name}.nav", NowMs);
|
||||
return () => InfoWork(q, folder, dir, hasPlayer, pns, pew, dungeons, map, spells);
|
||||
}
|
||||
|
||||
private static RouteWork InfoWork(RouteRequest q, string folder, string dir, bool hasPlayer, double pns, double pew,
|
||||
HashSet<uint> dungeons, HashSet<uint> map, Dictionary<int, string> spells)
|
||||
{
|
||||
var o = new RouteWork();
|
||||
string file = Path.Combine(folder, q.Name + ".nav");
|
||||
if (!File.Exists(file)) return Failed(o, q, $"no route called {q.Name} in RynthAi's NavProfiles ({folder})");
|
||||
NavRouteParser route = NavRouteParser.Load(file);
|
||||
bool IsDungeon(uint lb) => dungeons.Contains(lb) || (!map.Contains(lb) && File.Exists(Path.Combine(dir, DungeonTileFile.FileName(lb))));
|
||||
RouteInfo info = RouteInfo.Describe(route, q.Name, file, IsDungeon, hasPlayer, pns, pew, id => spells.TryGetValue(id, out string? n) ? n : null);
|
||||
if (info.Points == 0 && info.FollowTarget.Length == 0)
|
||||
return Failed(o, q, $"{q.Name}.nav has no points{(info.Warning.Length > 0 ? $" ({info.Warning})" : "")}");
|
||||
o.Ok = true;
|
||||
o.Detail = $"{info.Type}, {info.Points} point(s), {NavCoords.FmtDistance(info.Yards)}{(info.Dungeon ? ", a dungeon route" : "")}";
|
||||
o.Lines.AddRange(info.ChatLines());
|
||||
o.Json = RouteJson.Write(info.WriteJson);
|
||||
return o;
|
||||
}
|
||||
|
||||
// ── Shared by the workers ────────────────────────────────────────────
|
||||
|
||||
private static RouteWork Failed(RouteWork o, RouteRequest q, string why)
|
||||
{
|
||||
o.Ok = false;
|
||||
o.Detail = why;
|
||||
o.Json = RouteJson.Error(why, "");
|
||||
o.Lines.Clear();
|
||||
o.Lines.Add($"{q.Command}: {why}");
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>Writes the route (never over a file there, unless asked); false with the job failed when it can't.</summary>
|
||||
private static bool SaveNav(RouteWork o, RouteRequest q, string folder, NavRouteParser route, out string file)
|
||||
{
|
||||
if (NavRouteExport.Save(folder, q.Name, route, q.Overwrite, out file, out bool exists, out string error)) return true;
|
||||
Failed(o, q, exists ? $"{q.Name}.nav is already in RynthAi's NavProfiles; ask again with overwrite to replace it"
|
||||
: $"couldn't write {q.Name}.nav: {error}");
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The make ops' result: file, name, type, points, yards, dropped points, notes, and the op's own fields.</summary>
|
||||
private static string MakeJson(RouteRequest q, string file, NavRouteParser? route, double yards, List<LoopMaker.Dropped>? dropped,
|
||||
Action<Utf8JsonWriter>? extra, IReadOnlyList<string> notes, string error = "") => RouteJson.Write(w =>
|
||||
{
|
||||
w.WriteStartObject();
|
||||
if (error.Length > 0) w.WriteString("error", error);
|
||||
w.WriteString("name", q.Name);
|
||||
if (file.Length > 0) w.WriteString("file", file); else w.WriteNull("file");
|
||||
w.WriteString("type", route != null ? RouteInfo.TypeName(route.RouteType) : q.Op == RouteOp.MakeLoop ? "circular" : RouteInfo.TypeName(q.PathType));
|
||||
w.WriteNumber("points", route?.Points.Count ?? 0);
|
||||
RouteJson.Num(w, "yards", yards, 0);
|
||||
w.WriteNumber("dropped", dropped?.Count ?? 0);
|
||||
w.WriteStartArray("droppedPoints");
|
||||
if (dropped != null)
|
||||
foreach (LoopMaker.Dropped d in dropped)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
RouteJson.Num(w, "ns", d.Ns, 4);
|
||||
RouteJson.Num(w, "ew", d.Ew, 4);
|
||||
w.WriteString("why", d.Why);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
extra?.Invoke(w);
|
||||
RouteJson.Strings(w, "notes", notes);
|
||||
w.WriteEndObject();
|
||||
});
|
||||
}
|
||||
|
|
@ -1021,7 +1021,11 @@ public sealed partial class RynthNavPlugin
|
|||
"/rnav avoid — show; avoid portals on|off|<m> | walls on|off|<m> | corners <m>\n" +
|
||||
"/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" +
|
||||
"/rnav mesh on|off | floor on|off | walls on|off | radius <m> | triangles <n> — draw the navmesh: green floor, red walls\n" +
|
||||
"/rnav saveroute [name] [overwrite] — save the last trip as a RynthAi nav route (NavProfiles)";
|
||||
"/rnav saveroute [name] [overwrite] — save the last trip as a RynthAi nav route (NavProfiles)\n" +
|
||||
"/rnav makeroute <name> to <place|coords> [overwrite] — plan a trip and save it as a nav route in one go, no walking\n" +
|
||||
"/rnav makeloop <name> [at <coords>|here] radius <yd> [points <n>] [overwrite] — a hunting loop (circular nav) on walkable ground\n" +
|
||||
"/rnav makepath <name> [loop|line|once] <coords>; <coords>; ... [overwrite] — a nav through those points, each leg walked\n" +
|
||||
"/rnav routeinfo <name> — what a saved nav route is: type, points, yards, where, portals";
|
||||
|
||||
/// <summary>One /rnav command. Tick thread.</summary>
|
||||
private void RunCommand(string raw, bool fromPanel)
|
||||
|
|
@ -1073,6 +1077,12 @@ public sealed partial class RynthNavPlugin
|
|||
case "markers": CmdMarkers(rest); break;
|
||||
case "mesh": CmdMesh(rest); break;
|
||||
case "saveroute": CmdSaveRoute(rest); break;
|
||||
case "makeroute":
|
||||
case "makeloop":
|
||||
case "makepath":
|
||||
case "routeinfo":
|
||||
CmdRouteMaker(cmd, rest); // RynthNavPlugin.RouteMaker.cs
|
||||
break;
|
||||
case "arrive":
|
||||
if (NavReplies.TryArrive(rest, out double yd)) { _arrow.ArriveUnits = yd; Say(NavReplies.Arrived(yd)); }
|
||||
else if (rest.Length == 0) Say(NavReplies.ArriveUsage(rest, _arrow.ArriveUnits));
|
||||
|
|
@ -1115,42 +1125,57 @@ public sealed partial class RynthNavPlugin
|
|||
|
||||
private void CmdGo(string rest)
|
||||
{
|
||||
string name, type; double ns, ew;
|
||||
if (!ResolveGo(rest, out string name, out string type, out double ns, out double ew, out string enter, out string enterType, out string error))
|
||||
{
|
||||
Note(error);
|
||||
return;
|
||||
}
|
||||
StartGoto(name, type, ns, ew, enter, enterType); // StartWalk says "walking to ..." (or why it can't)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where /rnav go (and the route maker's go op) walks to: a place or coordinates, the arrow's target
|
||||
/// when nothing is given, and for a dungeon (or a portal) its entrance portal, walked into. False with
|
||||
/// the line to say. Tick thread.
|
||||
/// </summary>
|
||||
private bool ResolveGo(string rest, out string name, out string type, out double ns, out double ew,
|
||||
out string enter, out string enterType, out string error)
|
||||
{
|
||||
enter = ""; enterType = ""; error = "";
|
||||
AtlasLocation? place;
|
||||
if (rest.Length == 0)
|
||||
{
|
||||
name = ""; type = ""; ns = 0; ew = 0;
|
||||
ArrowStep? fin = _arrow.Final;
|
||||
if (fin == null || !fin.OnMap) { Note("go where? /rnav go <place or coords> (or set the arrow first)"); return; }
|
||||
if (fin == null || !fin.OnMap) { error = "go where? /rnav go <place or coords> (or set the arrow first)"; return false; }
|
||||
name = fin.Name; type = fin.Type; ns = fin.Ns; ew = fin.Ew;
|
||||
place = null;
|
||||
foreach (var l in _atlas.Locations)
|
||||
if (l.OnMap && l.Name == fin.Name && l.Type == fin.Type && NavCoords.Distance(l.Ns, l.Ew, ns, ew) < 3) { place = l; break; }
|
||||
}
|
||||
else if (!ResolveTarget(rest, out name, out type, out ns, out ew, out string error))
|
||||
else if (!ResolveTarget(rest, out name, out type, out ns, out ew, out error))
|
||||
{
|
||||
// A dungeon or portal the Atlas knows, but with no map position: say why, don't guess.
|
||||
foreach (var l in _atlas.Search(rest, null, 5))
|
||||
if (!l.OnMap && Entrance.IsEntrance(l))
|
||||
{
|
||||
Entrance.PortalFor(_atlas, l, false, 0, 0, out string offWhy);
|
||||
if (offWhy.Length > 0) { Note("goto: " + offWhy); return; }
|
||||
if (offWhy.Length > 0) { error = "goto: " + offWhy; return false; }
|
||||
}
|
||||
Note(error);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
else place = _resolvedPlace;
|
||||
|
||||
// A dungeon (or a portal): walk INTO its entrance portal and wait for the teleport.
|
||||
string enter = "", enterType = "";
|
||||
if (place != null && Entrance.IsEntrance(place))
|
||||
{
|
||||
bool hasPos = PlayerMapPos(out double pns, out double pew);
|
||||
AtlasLocation? portal = Entrance.PortalFor(_atlas, place, hasPos, pns, pew, out string why);
|
||||
if (portal == null) { Note("goto: " + why); return; }
|
||||
if (portal == null) { error = "goto: " + why; return false; }
|
||||
ns = portal.Ns; ew = portal.Ew; enter = place.Name; enterType = place.Type;
|
||||
_nextEnterPortal = portal.Name; // the portal object a saved nav route uses (RynthNavPlugin.SaveRoute.cs)
|
||||
}
|
||||
StartGoto(name, type, ns, ew, enter, enterType); // StartWalk says "walking to ..." (or why it can't)
|
||||
return true;
|
||||
}
|
||||
|
||||
private void CmdRoute(string rest)
|
||||
|
|
@ -1293,6 +1318,7 @@ public sealed partial class RynthNavPlugin
|
|||
/// <summary>Starts walking to a place: the arrow points along the same route.</summary>
|
||||
private void StartGoto(string name, string type, double ns, double ew, string enter = "", string enterType = "")
|
||||
{
|
||||
_goJobId = 0; // a goto of its own: no route maker go job's any more (RynthNavPlugin.RouteMaker.cs)
|
||||
_store.Touch(new SavedPlace { Name = name, Type = type, Ns = ns, Ew = ew });
|
||||
lock (_reqGate) { _reqGotoNamed = (name, type, ns, ew, enter, enterType); }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ namespace RynthCore.Plugin.RynthNav;
|
|||
public sealed partial class RynthNavPlugin : RynthPluginBase
|
||||
{
|
||||
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthNav");
|
||||
internal const string PluginVersion = "0.6.7";
|
||||
internal const string PluginVersion = "0.6.8"; // 0.6.8: the route maker (makeroute, makeloop, makepath, routeinfo, "RynthNav.Routes")
|
||||
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginVersion);
|
||||
|
||||
/// <summary>Lets PluginExports log through this plugin's host (the base Log is protected).</summary>
|
||||
|
|
@ -147,7 +147,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
LoadAvoidSettings();
|
||||
LoadMarkerSettings();
|
||||
LoadMeshSettings();
|
||||
Host.Log($"[RynthNav] Initialized v{PluginVersion} (tiled streaming + long-range goto + portal/recall routing + arrow + atlas). Panel: RynthNav. Tiles: {NavDataDir} ({NavConfig.Source})");
|
||||
Host.Log($"[RynthNav] Initialized v{PluginVersion} (tiled streaming + long-range goto + portal/recall routing + arrow + atlas + route maker). Panel: RynthNav. Tiles: {NavDataDir} ({NavConfig.Source})");
|
||||
InitTravel();
|
||||
LoadGraph();
|
||||
LoadTownNet();
|
||||
|
|
@ -213,6 +213,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
TickMarkers();
|
||||
TickMeshView();
|
||||
UpdateGoLine();
|
||||
TickRouteJobs();
|
||||
FlushChat();
|
||||
}
|
||||
|
||||
|
|
@ -426,6 +427,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
|
||||
if (walk)
|
||||
{
|
||||
_goJobId = 0; // a goto of its own: no route maker go job's any more
|
||||
StartWalk(given.Length > 0 ? given : NavCoords.Fmt(tns, tew), "", tns, tew);
|
||||
return;
|
||||
}
|
||||
|
|
@ -850,6 +852,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
ResetBlocked();
|
||||
AutoRun.Stop();
|
||||
lock (_gate) _status = status;
|
||||
_gotoEndStatus = status; _gotoEndSeq++; // a route maker go job reads how it ended (RynthNavPlugin.RouteMaker.cs)
|
||||
Host.Log($"[RynthNav] goto: {status}");
|
||||
Say(status == "arrived" && _gotoName.Length > 0 ? $"goto: arrived at {_gotoName}" : $"goto: {status}");
|
||||
_goNote = status == "arrived" && _gotoName.Length > 0 ? $"arrived at {_gotoName}" : status;
|
||||
|
|
@ -949,19 +952,21 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
/// <summary>
|
||||
/// Plans a trip from where you stand (TravelPlan: the switches, a dungeon start, the land) and
|
||||
/// logs what it considered. Steps null = walk straight there; a refusal = there's no way, and why.
|
||||
/// Tick thread.
|
||||
/// <paramref name="portals"/>: use portals and recalls or not this once (null: the switch; the
|
||||
/// route maker's plan op). Tick thread.
|
||||
/// </summary>
|
||||
private TravelPlan.Result PlanRoute(string name, double goalNs, double goalEw, out List<RecallOption> recalls)
|
||||
private TravelPlan.Result PlanRoute(string name, double goalNs, double goalEw, out List<RecallOption> recalls, bool? portals = null)
|
||||
{
|
||||
bool portalsOn = portals ?? _portalsEnabled;
|
||||
double startNs = NavCoords.NsFromWorld(_wy), startEw = NavCoords.EwFromWorld(_wx);
|
||||
bool startOnMap = IsOnMap(_cellId);
|
||||
var recallNotes = new List<string>();
|
||||
recalls = _charKey.Length == 0 ? new List<RecallOption>() : RecallPlanner.Build(_atlas, _known, _memory, _charKey, recallNotes);
|
||||
if (_charKey.Length == 0) recallNotes.Add("not logged in yet");
|
||||
var hubNotes = new List<string>();
|
||||
HubLinks? hub = _portalsEnabled ? CurrentHubLinks(hubNotes) : null;
|
||||
HubLinks? hub = portalsOn ? CurrentHubLinks(hubNotes) : null;
|
||||
if (hub != null && _preferAphus && _recallsEnabled) hub = ViaAphus(hub, recalls, hubNotes);
|
||||
if (_portalsEnabled) EnsurePortalsLoaded();
|
||||
if (portalsOn) EnsurePortalsLoaded();
|
||||
// Walks that can't be done over land (another landmass) are left out, so an island or the
|
||||
// far side of water is only reached by a portal, a recall or the Town Network.
|
||||
NavGraph? g = UsableGraph();
|
||||
|
|
@ -970,12 +975,12 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
NavGraph.LandblockAt(NavCoords.WorldX(bew), NavCoords.WorldY(bns))) != false;
|
||||
bool? land = startOnMap && g != null ? g.SameLand(CurrentLandblock, NavGraph.LandblockAt(NavCoords.WorldX(goalEw), NavCoords.WorldY(goalNs))) : null;
|
||||
|
||||
TravelPlan.Result r = TravelPlan.Plan(_portalsEnabled ? _portals : null, RecallPlanner.Links(recalls), hub,
|
||||
_portalsEnabled, _recallsEnabled, startOnMap, startNs, startEw, goalNs, goalEw, canWalk, land, name);
|
||||
TravelPlan.Result r = TravelPlan.Plan(portalsOn ? _portals : null, RecallPlanner.Links(recalls), hub,
|
||||
portalsOn, _recallsEnabled, startOnMap, startNs, startEw, goalNs, goalEw, canWalk, land, name);
|
||||
|
||||
Host.Log($"[RynthNav] plan {name}: {r.Basis}; {(_portalsEnabled ? $"{_portals?.Count ?? 0} portals" : "no portals")}, "
|
||||
Host.Log($"[RynthNav] plan {name}: {r.Basis}; {(portalsOn ? $"{_portals?.Count ?? 0} portals" : "no portals")}, "
|
||||
+ $"{recalls.Count} recall(s) ready" + (recalls.Count > 0 ? " (" + string.Join(", ", recalls.ConvertAll(o => o.Name)) + ")" : "")
|
||||
+ $", Town Network {(hub == null ? (_portalsEnabled ? "not loaded" : "unused") : $"{hub.Entries.Count} entries / {hub.Exits.Count} exits")}"
|
||||
+ $", Town Network {(hub == null ? (portalsOn ? "not loaded" : "unused") : $"{hub.Entries.Count} entries / {hub.Exits.Count} exits")}"
|
||||
+ $", land check {(canWalk == null ? "off (no route graph)" : "on")}"
|
||||
+ (startOnMap ? "" : $" (in landblock 0x{CurrentLandblock:X4})"));
|
||||
foreach (string n in recallNotes) Host.Log($"[RynthNav] plan: recall left out: {n}");
|
||||
|
|
|
|||
|
|
@ -16,6 +16,13 @@ namespace RynthNav.Routing;
|
|||
/// except the leg's own. Its own navmesh, filled from the tile files a few tiles at a time, so it
|
||||
/// runs on a worker and never touches the walker's (tick-thread) navmesh. One instance per worker.
|
||||
/// Without a route graph only short legs (a few landblocks) are planned; longer ones get none.
|
||||
///
|
||||
/// The route maker (LoopMaker, RynthNavPlugin.RouteMaker.cs) sets the stricter options: no way
|
||||
/// through a portal's circle at all (<see cref="StrictPortals"/>), no straight line over a navmesh gap
|
||||
/// (<see cref="NoGaps"/>), corners pushed off walls (<see cref="WallClearance"/>, RynthNav's own walks
|
||||
/// do this as they go), building floors left out where there's another way (<see cref="AvoidArea"/>);
|
||||
/// and it asks this navmesh for ground (<see cref="Snap"/>, <see cref="WallDistance"/>, <see cref="Leg"/>).
|
||||
/// With none of them set it plans exactly as it always has.
|
||||
/// </summary>
|
||||
internal sealed class TilePathFinder
|
||||
{
|
||||
|
|
@ -27,27 +34,41 @@ internal sealed class TilePathFinder
|
|||
|
||||
private readonly string _dir;
|
||||
private readonly NavGraph? _graph;
|
||||
private readonly IReadOnlyList<PortalAvoid.Spot> _portals;
|
||||
private readonly IReadOnlyList<PortalAvoid.Spot> _portals, _live;
|
||||
private readonly DtNavMesh _nav;
|
||||
private DtNavMeshQuery _query;
|
||||
private readonly HashSet<uint> _loaded = new(), _bad = new();
|
||||
private readonly PortalAvoid _avoid = new();
|
||||
private readonly AvoidFilter _filter;
|
||||
private readonly AreaFilter _area;
|
||||
private readonly DtQueryDefaultFilter _plain = new();
|
||||
private string _pieceNote = "";
|
||||
|
||||
/// <summary>Tile files read so far (for the log).</summary>
|
||||
public int TilesRead { get; private set; }
|
||||
|
||||
public TilePathFinder(string navDataDir, NavGraph? graph, IReadOnlyList<PortalAvoid.Spot>? portals)
|
||||
/// <summary>Never through a portal's circle: no plan through one when there's no way round, and a bent path that still crosses one is refused.</summary>
|
||||
public bool StrictPortals { get; set; }
|
||||
/// <summary>A stretch the navmesh can't plan fails the walk, instead of becoming a straight line.</summary>
|
||||
public bool NoGaps { get; set; }
|
||||
/// <summary>Each corner pushed this far out from the wall it turns round, where the ground is walkable (0 = not).</summary>
|
||||
public double WallClearance { get; set; }
|
||||
/// <summary>Ground kept off where there is another way (east, north: true = keep off); null = none.</summary>
|
||||
public Func<double, double, bool>? AvoidArea { get; set; }
|
||||
|
||||
public TilePathFinder(string navDataDir, NavGraph? graph, IReadOnlyList<PortalAvoid.Spot>? portals,
|
||||
IReadOnlyList<PortalAvoid.Spot>? livePortals = null)
|
||||
{
|
||||
_dir = navDataDir;
|
||||
_graph = graph;
|
||||
_portals = portals ?? Array.Empty<PortalAvoid.Spot>();
|
||||
_live = livePortals ?? Array.Empty<PortalAvoid.Spot>();
|
||||
_nav = new DtNavMesh();
|
||||
var p = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = MaxTiles, maxPolys = 1 << 16 };
|
||||
_nav.Init(p, 6);
|
||||
_query = new DtNavMeshQuery(_nav);
|
||||
_filter = new AvoidFilter(_avoid);
|
||||
_area = new AreaFilter(_filter);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -88,6 +109,12 @@ internal sealed class TilePathFinder
|
|||
{
|
||||
bool last = k + 2 == anchors.Count;
|
||||
List<WorldPt>? piece = Piece(anchors[k], anchors[k + 1], last && ownPortal ? anchors[k + 1] : null);
|
||||
if (piece == null && NoGaps)
|
||||
{
|
||||
note = $"no navmesh path from {NavCoords.Fmt(anchors[k].Ns, anchors[k].Ew)} to {NavCoords.Fmt(anchors[k + 1].Ns, anchors[k + 1].Ew)}"
|
||||
+ (_pieceNote.Length > 0 ? ": " + _pieceNote : "");
|
||||
return null;
|
||||
}
|
||||
if (piece == null) { gaps++; piece = new List<WorldPt> { anchors[k], anchors[k + 1] }; }
|
||||
for (int i = 1; i < piece.Count; i++) path.Add(piece[i]);
|
||||
}
|
||||
|
|
@ -129,35 +156,51 @@ internal sealed class TilePathFinder
|
|||
return (Math.Abs(ax - bx) + 1) * (Math.Abs(ay - by) + 1);
|
||||
}
|
||||
|
||||
/// <summary>The Detour path a→b (both ends' tiles and those between loaded); null when there's none.</summary>
|
||||
/// <summary>The Detour path a→b (both ends' tiles and those between loaded); null when there's none (_pieceNote: why).</summary>
|
||||
private List<WorldPt>? Piece(WorldPt a, WorldPt b, WorldPt? own)
|
||||
{
|
||||
if (!LoadBox(a, b)) return null;
|
||||
_pieceNote = "";
|
||||
if (!LoadBox(a, b)) { _pieceNote = "no navmesh tiles there"; return null; }
|
||||
var half = new RcVec3f(8, 600, 8);
|
||||
var pa = new RcVec3f((float)a.X, double.IsNaN(a.H) ? 0f : (float)a.H, (float)a.Y);
|
||||
var pb = new RcVec3f((float)b.X, double.IsNaN(b.H) ? 0f : (float)b.H, (float)b.Y);
|
||||
_query.FindNearestPoly(pa, half, _plain, out long sRef, out RcVec3f sPt, out _);
|
||||
_query.FindNearestPoly(pb, half, _plain, out long gRef, out RcVec3f gPt, out _);
|
||||
if (sRef == 0 || gRef == 0) return null;
|
||||
if (sRef == 0 || gRef == 0) { _pieceNote = $"no walkable ground at its {(sRef == 0 ? "start" : "end")}"; return null; }
|
||||
|
||||
// Portals near this piece, except the leg's own.
|
||||
var near = new List<PortalAvoid.Spot>();
|
||||
var nearLive = new List<PortalAvoid.Spot>();
|
||||
double minX = Math.Min(a.X, b.X) - AvoidNearUnits, maxX = Math.Max(a.X, b.X) + AvoidNearUnits;
|
||||
double minY = Math.Min(a.Y, b.Y) - AvoidNearUnits, maxY = Math.Max(a.Y, b.Y) + AvoidNearUnits;
|
||||
foreach (PortalAvoid.Spot sp in _portals)
|
||||
if (sp.X >= minX && sp.X <= maxX && sp.Y >= minY && sp.Y <= maxY) near.Add(sp);
|
||||
if (own is WorldPt ownAt) _avoid.Set(Array.Empty<PortalAvoid.Spot>(), near, ownAt.X, ownAt.Y, OwnPortalUnits);
|
||||
else _avoid.Set(Array.Empty<PortalAvoid.Spot>(), near);
|
||||
foreach (PortalAvoid.Spot sp in _live)
|
||||
if (sp.X >= minX && sp.X <= maxX && sp.Y >= minY && sp.Y <= maxY) nearLive.Add(sp);
|
||||
if (own is WorldPt ownAt) _avoid.Set(nearLive, near, ownAt.X, ownAt.Y, OwnPortalUnits);
|
||||
else _avoid.Set(nearLive, near);
|
||||
_filter.AllowA = sRef; _filter.AllowB = gRef;
|
||||
|
||||
Span<long> polys = new long[1024];
|
||||
_query.FindPath(sRef, gRef, sPt, gPt, _filter, polys, out int pc, 1024);
|
||||
int pc = 0;
|
||||
if (AvoidArea != null)
|
||||
{
|
||||
// Off the floors kept off (buildings) when there's a way; else as without.
|
||||
_area.Inside = AvoidArea; _area.AllowA = sRef; _area.AllowB = gRef;
|
||||
_query.FindPath(sRef, gRef, sPt, gPt, _area, polys, out pc, 1024);
|
||||
if (pc == 0 || polys[pc - 1] != gRef) pc = 0;
|
||||
}
|
||||
if (pc == 0) _query.FindPath(sRef, gRef, sPt, gPt, _filter, polys, out pc, 1024);
|
||||
if ((pc == 0 || polys[pc - 1] != gRef) && _avoid.Count > 0)
|
||||
{
|
||||
_query.FindPath(sRef, gRef, sPt, gPt, _plain, polys, out pc, 1024);
|
||||
if (pc == 0 || polys[pc - 1] != gRef) return null;
|
||||
// Strict: a way that only goes through a portal's circle is no way (and that is why).
|
||||
if (StrictPortals && pc > 0 && polys[pc - 1] == gRef) { _pieceNote = "no way round " + PortalsNamed(_avoid.Spots); return null; }
|
||||
}
|
||||
if (pc == 0 || polys[pc - 1] != gRef) { _pieceNote = "the navmesh doesn't join them (water, a cliff or a wall between)"; return null; }
|
||||
Span<DtStraightPath> sp2 = new DtStraightPath[256];
|
||||
_query.FindStraightPath(sPt, gPt, polys[..pc], pc, sp2, out int spc, 256, 0);
|
||||
if (spc < 2) return null;
|
||||
if (spc < 2) { _pieceNote = "no straight path along the navmesh"; return null; }
|
||||
|
||||
var corners = new List<(double X, double Y)>(spc);
|
||||
List<double>? heights = new List<double>(spc);
|
||||
|
|
@ -182,6 +225,20 @@ internal sealed class TilePathFinder
|
|||
corners = _avoid.Bend(corners, OnMesh, 12, LegOnMesh);
|
||||
if (corners.Count != before) heights = null; // bend corners: heights filled from the neighbours
|
||||
}
|
||||
if (WallClearance > 0 && corners.Count > 2)
|
||||
{
|
||||
// As RynthNav's own walks (Replan): each corner pushed out along the turn's outside, onto ground.
|
||||
var pushed = new List<(double X, double Y)>(corners);
|
||||
PushFromWalls(pushed, heights, pa.Y);
|
||||
if (!StrictPortals || Crosses(pushed) < 0) corners = pushed; // a push into a portal's circle isn't taken
|
||||
}
|
||||
int hit = StrictPortals ? Crosses(corners) : -1;
|
||||
if (hit >= 0)
|
||||
{
|
||||
string name = _avoid.Spots[hit].Name;
|
||||
_pieceNote = $"it would cross {(name.Length > 0 ? "the portal " + name : "a portal")}";
|
||||
return null;
|
||||
}
|
||||
var o = new List<WorldPt>(corners.Count) { a with { H = heights != null ? heights[0] : (double.IsNaN(a.H) ? sPt.Y : a.H) } };
|
||||
for (int i = 1; i < corners.Count; i++)
|
||||
o.Add(new WorldPt(corners[i].X, corners[i].Y, heights != null ? heights[i] : double.NaN));
|
||||
|
|
@ -189,6 +246,95 @@ internal sealed class TilePathFinder
|
|||
return o;
|
||||
}
|
||||
|
||||
/// <summary>"the portal X" / "the portals X and Y" / "3 portals" for a refusal.</summary>
|
||||
private static string PortalsNamed(IReadOnlyList<PortalAvoid.Spot> spots)
|
||||
{
|
||||
var names = new List<string>();
|
||||
foreach (PortalAvoid.Spot s in spots) if (s.Name.Length > 0 && !names.Contains(s.Name)) names.Add(s.Name);
|
||||
if (names.Count == 0) return spots.Count == 1 ? "a portal" : $"{spots.Count} portals";
|
||||
if (names.Count > 2) return $"{spots.Count} portals ({names[0]}, {names[1]}, ...)";
|
||||
return names.Count == 1 ? "the portal " + names[0] : $"the portals {names[0]} and {names[1]}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first kept-out circle a leg of <paramref name="pts"/> enters (or its end lies in), or -1. A circle
|
||||
/// the start is already in doesn't count: that's where the walk begins (the walker steers out of it).
|
||||
/// </summary>
|
||||
private int Crosses(IReadOnlyList<(double X, double Y)> pts)
|
||||
{
|
||||
IReadOnlyList<PortalAvoid.Spot> spots = _avoid.Spots;
|
||||
if (pts.Count == 0) return -1;
|
||||
for (int k = 0; k < spots.Count; k++)
|
||||
{
|
||||
PortalAvoid.Spot s = spots[k];
|
||||
if (Math.Sqrt((pts[0].X - s.X) * (pts[0].X - s.X) + (pts[0].Y - s.Y) * (pts[0].Y - s.Y)) < s.R) continue;
|
||||
for (int i = 1; i < pts.Count; i++)
|
||||
if (PortalAvoid.SegmentDistance(s.X, s.Y, pts[i - 1].X, pts[i - 1].Y, pts[i].X, pts[i].Y) < s.R - 0.05) return k;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Walls: each corner the path turns round sits on the mesh's edge; push it <see cref="WallClearance"/>
|
||||
/// out along the turn's outside bisector where the ground is walkable (inside a polygon, not merely
|
||||
/// near one), as the walker's Replan does. The ends never move.
|
||||
/// </summary>
|
||||
private void PushFromWalls(List<(double X, double Y)> wps, List<double>? heights, float startH)
|
||||
{
|
||||
for (int i = 1; i < wps.Count - 1; i++)
|
||||
{
|
||||
var (px, py) = wps[i]; var (ax, ay) = wps[i - 1]; var (bx, by) = wps[i + 1];
|
||||
double ux = ax - px, uy = ay - py, ul = Math.Sqrt(ux * ux + uy * uy);
|
||||
double vx = bx - px, vy = by - py, vl = Math.Sqrt(vx * vx + vy * vy);
|
||||
if (ul < 0.5 || vl < 0.5) continue;
|
||||
double ox = -(ux / ul + vx / vl), oy = -(uy / ul + vy / vl), ol = Math.Sqrt(ox * ox + oy * oy);
|
||||
if (ol < 0.05) continue; // straight on: no corner to clear
|
||||
double nx = px + ox / ol * WallClearance, ny = py + oy / ol * WallClearance;
|
||||
float h = heights != null && i < heights.Count ? (float)heights[i] : startH;
|
||||
_query.FindNearestPoly(new RcVec3f((float)nx, h, (float)ny), new RcVec3f(0.3f, 24, 0.3f), _plain, out long rr, out RcVec3f rp, out _);
|
||||
if (rr != 0 && Math.Abs(rp.X - nx) < 0.05 && Math.Abs(rp.Z - ny) < 0.05) wps[i] = (nx, ny);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Ground for the route maker (LoopMaker) ───────────────────────────
|
||||
|
||||
/// <summary>Loads the tiles under the box (world units); false when it's more than this navmesh holds at once, or there are none.</summary>
|
||||
public bool LoadArea(double minX, double minY, double maxX, double maxY) =>
|
||||
LoadBox(new WorldPt(minX, minY, double.NaN), new WorldPt(maxX, maxY, double.NaN));
|
||||
|
||||
/// <summary>
|
||||
/// Walkable ground within <paramref name="reach"/> yards (across) of <paramref name="p"/>, the nearest
|
||||
/// to its height (NaN: to height 0, so the lowest floor); its tiles must be loaded. False when none.
|
||||
/// </summary>
|
||||
public bool Snap(WorldPt p, double reach, out WorldPt ground, out long poly)
|
||||
{
|
||||
ground = p;
|
||||
var at = new RcVec3f((float)p.X, double.IsNaN(p.H) ? 0f : (float)p.H, (float)p.Y);
|
||||
_query.FindNearestPoly(at, new RcVec3f((float)reach, 600, (float)reach), _plain, out poly, out RcVec3f pt, out _);
|
||||
if (poly == 0) return false;
|
||||
ground = new WorldPt(pt.X, pt.Z, pt.Y);
|
||||
if (ground.FlatDistance(p) > reach) { poly = 0; return false; } // the search box's corner: farther than asked
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>How far ground found by <see cref="Snap"/> is from the navmesh's edge (a wall, a drop, water), at most <paramref name="max"/>.</summary>
|
||||
public double WallDistance(WorldPt ground, long poly, double max)
|
||||
{
|
||||
DtStatus st = _query.FindDistanceToWall(poly, new RcVec3f((float)ground.X, (float)ground.H, (float)ground.Y), (float)max, _plain, out float d, out _, out _);
|
||||
return st.Failed() ? 0 : Math.Min(d, max);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A leg between two points on ground already loaded (no route graph: a loop's legs are short), with
|
||||
/// the options set; null when there is none, and <paramref name="note"/> says why.
|
||||
/// </summary>
|
||||
public List<WorldPt>? Leg(WorldPt from, WorldPt to, out string note)
|
||||
{
|
||||
List<WorldPt>? piece = Piece(from, to, null);
|
||||
note = piece == null ? _pieceNote : "";
|
||||
return piece;
|
||||
}
|
||||
|
||||
/// <summary>Loads the tiles of the box a..b (evicting others when full); false when it's too big or none loads.</summary>
|
||||
private bool LoadBox(WorldPt a, WorldPt b)
|
||||
{
|
||||
|
|
|
|||
102
Plugins/RynthCore.Plugin.RynthNav/TripSummary.cs
Normal file
102
Plugins/RynthCore.Plugin.RynthNav/TripSummary.cs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// A planned trip in figures (the "RynthNav.Routes" plan op): each step as walk, portal, recall or
|
||||
/// town (the Town Network), with its name, where it is, the yards walked on it (the worked-out path
|
||||
/// where there is one, else the straight line) and where a teleport lands; the yards in all, the
|
||||
/// teleports, and a rough time: walking at PortalRoute.RunUnitsPerSecond, PortalRoute's overhead for
|
||||
/// each teleport, and each recall's cast time. Host-free: the route tests build these.
|
||||
/// </summary>
|
||||
internal sealed class TripSummary
|
||||
{
|
||||
public sealed class Step
|
||||
{
|
||||
public string Kind = "", Name = "";
|
||||
public double Ns = double.NaN, Ew = double.NaN, Yards;
|
||||
public double LandNs = double.NaN, LandEw = double.NaN;
|
||||
}
|
||||
|
||||
public readonly List<Step> Steps = new();
|
||||
public double Yards;
|
||||
public int Teleports;
|
||||
public double CastSeconds;
|
||||
|
||||
/// <summary>Rough minutes for the whole trip (see the class notes).</summary>
|
||||
public double Minutes =>
|
||||
(Yards / PortalRoute.RunUnitsPerSecond + Teleports * PortalRoute.TeleportOverheadUnits / PortalRoute.RunUnitsPerSecond + CastSeconds) / 60.0;
|
||||
|
||||
private static double Length(WorldPt[]? pts)
|
||||
{
|
||||
double d = 0;
|
||||
if (pts != null) for (int i = 1; i < pts.Length; i++) d += pts[i - 1].FlatDistance(pts[i]);
|
||||
return d;
|
||||
}
|
||||
|
||||
/// <summary>The trip's steps with their yards from <paramref name="path"/> (null: straight lines).</summary>
|
||||
public static TripSummary Of(PlannedTrip trip, TripPath? path)
|
||||
{
|
||||
var t = new TripSummary();
|
||||
bool own = path != null && path.TripId == trip.Id;
|
||||
for (int i = 0; i < trip.Count; i++)
|
||||
{
|
||||
RouteStep s = trip.Steps[i];
|
||||
var st = new Step();
|
||||
if (!double.IsNaN(s.LandNs)) { st.LandNs = s.LandNs; st.LandEw = s.LandEw; }
|
||||
if (s.UseRecall)
|
||||
{
|
||||
TripRecall? r = trip.RecallOf(i);
|
||||
st.Kind = "recall";
|
||||
st.Name = r?.Name ?? s.Label ?? "";
|
||||
if (trip.Point[i] is WorldPt at && (i > 0 || trip.StartOnMap)) { st.Ns = at.Ns; st.Ew = at.Ew; } // a first recall in a dungeon: no map position
|
||||
t.CastSeconds += r?.CastSeconds ?? 0;
|
||||
t.Teleports++;
|
||||
}
|
||||
else if (s.IsHub)
|
||||
{
|
||||
st.Kind = "town";
|
||||
st.Name = s.Label ?? "";
|
||||
st.Ns = s.LandNs; st.Ew = s.LandEw;
|
||||
st.Yards = own && i < path!.Hub.Length ? Length(path.Hub[i]) : 0;
|
||||
t.Teleports++;
|
||||
}
|
||||
else
|
||||
{
|
||||
st.Kind = s.UsePortal ? "portal" : "walk";
|
||||
st.Name = s.UsePortal ? trip.PortalName(i) : i == trip.Count - 1 ? trip.Goal : (s.Label ?? "walk");
|
||||
st.Ns = s.Ns; st.Ew = s.Ew;
|
||||
WorldPt[]? w = own && i < path!.Walks.Length ? path.Walks[i] : null;
|
||||
st.Yards = w != null ? Length(w)
|
||||
: trip.WalkFrom[i] is WorldPt f && trip.Point[i] is WorldPt p ? f.FlatDistance(p) : 0;
|
||||
if (s.UsePortal) t.Teleports++;
|
||||
}
|
||||
t.Yards += st.Yards;
|
||||
t.Steps.Add(st);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/// <summary>The steps and totals as the plan op's result fields (inside an object the caller opened).</summary>
|
||||
public void WriteFields(Utf8JsonWriter w)
|
||||
{
|
||||
w.WriteStartArray("steps");
|
||||
foreach (Step s in Steps)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("kind", s.Kind);
|
||||
w.WriteString("name", s.Name);
|
||||
RouteJson.Num(w, "ns", s.Ns, 4);
|
||||
RouteJson.Num(w, "ew", s.Ew, 4);
|
||||
RouteJson.Num(w, "yards", s.Yards, 0);
|
||||
if (double.IsFinite(s.LandNs)) RouteJson.Place(w, "land", s.LandNs, s.LandEw);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
RouteJson.Num(w, "yards", Yards, 0);
|
||||
w.WriteNumber("teleports", Teleports);
|
||||
RouteJson.Num(w, "minutes", Minutes, 1);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue