RynthSuite as of 2026-10-04 (internal c94715f): RynthOracle (based on Oracle of Dereth by Advis Eveldan) and RynthInventory, RynthAi patrol doorways and rooms, healing priority, strict monster priority, finish the wounded target, slayer weapons, arcs when clear, blasts like rings, learn unknown spells, looting fixes, release 2026.10.4.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c33e24a610
commit
12ca25f911
426 changed files with 108239 additions and 7521 deletions
108
Plugins/RynthCore.Plugin.RynthNav/ArrowGuide.cs
Normal file
108
Plugins/RynthCore.Plugin.RynthNav/ArrowGuide.cs
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
internal enum ArrowStepKind { Place, Portal, Recall }
|
||||
|
||||
/// <summary>One thing the arrow points at: a place, a portal to walk into, or a recall to cast.</summary>
|
||||
internal sealed class ArrowStep
|
||||
{
|
||||
public ArrowStepKind Kind;
|
||||
public string Name = "", Type = "";
|
||||
public bool OnMap;
|
||||
public double Ns, Ew;
|
||||
/// <summary>What to do there ("walk into the portal", "cast Lyceum Recall").</summary>
|
||||
public string Hint = "";
|
||||
}
|
||||
|
||||
internal enum ArrowEvent { None, Advanced, Arrived }
|
||||
|
||||
/// <summary>
|
||||
/// The arrow's target, or a chain of them (a route: portals and recalls, then the place).
|
||||
/// A place is reached by walking within ArriveUnits of it; a portal or recall step is done
|
||||
/// when you teleport. Reaching the last step clears the arrow. (GoArrow's arrow, chained
|
||||
/// along a route; Digero 2006, Virindi 2011, MIT.) Tick thread only; no host calls, so the
|
||||
/// offline tests compile this file.
|
||||
/// </summary>
|
||||
internal sealed class ArrowGuide
|
||||
{
|
||||
public const double DefaultArriveUnits = 10.0;
|
||||
|
||||
private readonly List<ArrowStep> _steps = new();
|
||||
private int _index;
|
||||
|
||||
public double ArriveUnits = DefaultArriveUnits;
|
||||
/// <summary>Bumped on every change (the plugin rebuilds its status text when it moves).</summary>
|
||||
public int Version { get; private set; }
|
||||
|
||||
public bool Active => _index < _steps.Count;
|
||||
public ArrowStep? Current => Active ? _steps[_index] : null;
|
||||
public ArrowStep? Final => _steps.Count > 0 ? _steps[^1] : null;
|
||||
public int Index => _index;
|
||||
public int Count => _steps.Count;
|
||||
public IReadOnlyList<ArrowStep> Steps => _steps;
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
if (_steps.Count == 0 && _index == 0) return;
|
||||
_steps.Clear();
|
||||
_index = 0;
|
||||
Version++;
|
||||
}
|
||||
|
||||
public void SetTarget(string name, string type, double ns, double ew, bool onMap = true)
|
||||
{
|
||||
_steps.Clear();
|
||||
_steps.Add(new ArrowStep { Kind = ArrowStepKind.Place, Name = name, Type = type, Ns = ns, Ew = ew, OnMap = onMap });
|
||||
_index = 0;
|
||||
Version++;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Points along a planned route: each portal entrance, each recall, then the place.
|
||||
/// A route with no portal or recall is just the place.
|
||||
/// </summary>
|
||||
public void SetRoute(IReadOnlyList<RouteStep> route, string name, string type, double ns, double ew)
|
||||
{
|
||||
_steps.Clear();
|
||||
foreach (RouteStep s in route)
|
||||
{
|
||||
if (s.UseRecall)
|
||||
_steps.Add(new ArrowStep { Kind = ArrowStepKind.Recall, Name = s.Label, Hint = "recall: " + s.Label });
|
||||
else if (s.IsHub)
|
||||
// Inside the Town Network: no map position; the teleport out moves the arrow on.
|
||||
_steps.Add(new ArrowStep { Kind = ArrowStepKind.Portal, Name = s.Label, Type = "Portal", Hint = "in the Town Network: walk into the " + s.Label });
|
||||
else if (s.UsePortal)
|
||||
_steps.Add(new ArrowStep
|
||||
{
|
||||
Kind = ArrowStepKind.Portal, Name = s.Label, Type = "Portal", Ns = s.Ns, Ew = s.Ew, OnMap = true,
|
||||
Hint = "walk into the portal",
|
||||
});
|
||||
}
|
||||
_steps.Add(new ArrowStep { Kind = ArrowStepKind.Place, Name = name, Type = type, Ns = ns, Ew = ew, OnMap = true });
|
||||
_index = 0;
|
||||
Version++;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Once per tick with where you are. <paramref name="teleported"/>: you went through a
|
||||
/// portal or recalled since the last call.
|
||||
/// </summary>
|
||||
public ArrowEvent Update(bool hasPos, double ns, double ew, bool teleported)
|
||||
{
|
||||
ArrowStep? cur = Current;
|
||||
if (cur == null) return ArrowEvent.None;
|
||||
bool done = cur.Kind == ArrowStepKind.Place
|
||||
? hasPos && cur.OnMap && NavCoords.Distance(ns, ew, cur.Ns, cur.Ew) <= ArriveUnits
|
||||
: teleported;
|
||||
if (!done) return ArrowEvent.None;
|
||||
_index++;
|
||||
Version++;
|
||||
if (Active) return ArrowEvent.Advanced;
|
||||
_steps.Clear();
|
||||
_index = 0;
|
||||
return ArrowEvent.Arrived;
|
||||
}
|
||||
}
|
||||
250
Plugins/RynthCore.Plugin.RynthNav/Atlas.cs
Normal file
250
Plugins/RynthCore.Plugin.RynthNav/Atlas.cs
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// The Atlas: RynthNav's location database (NavData\locations.json, made from the world
|
||||
// database by RynthCore's tools\navdata\gen_locations.py). Read-only; loaded once off the
|
||||
// tick thread and then shared. The idea of a typed, searchable atlas with an arrow is
|
||||
// GoArrow's (Digero 2006, Virindi 2011, MIT); the data is our own server's.
|
||||
// No host calls: the offline tests compile this file.
|
||||
|
||||
internal sealed class AtlasLocation
|
||||
{
|
||||
public int Id;
|
||||
public string Name = "", Type = "", Desc = "", Cell = "", Place = "", Lb = "";
|
||||
public uint Wcid;
|
||||
public bool OnMap;
|
||||
public double Ns, Ew;
|
||||
// A portal's destination.
|
||||
public bool HasDest, DestOnMap;
|
||||
public double DestNs, DestEw;
|
||||
public string DestName = "", DestPlace = "";
|
||||
public int MinLevel, MaxLevel;
|
||||
public bool Quest, Closed;
|
||||
}
|
||||
|
||||
/// <summary>A spell that lands at a fixed spot (from locations.json "recalls").</summary>
|
||||
internal sealed class AtlasRecall
|
||||
{
|
||||
public int SpellId;
|
||||
public string Name = "", In = "";
|
||||
public bool OnMap;
|
||||
public double Ns, Ew;
|
||||
}
|
||||
|
||||
internal sealed class Atlas
|
||||
{
|
||||
public static readonly Atlas Empty = new(new List<AtlasLocation>(), new List<AtlasRecall>(), "", "");
|
||||
|
||||
public IReadOnlyList<AtlasLocation> Locations { get; }
|
||||
public IReadOnlyList<AtlasRecall> Recalls { get; }
|
||||
public string Generated { get; }
|
||||
public string Path { get; }
|
||||
|
||||
private readonly Dictionary<int, AtlasLocation> _byId = new();
|
||||
|
||||
private Atlas(List<AtlasLocation> locations, List<AtlasRecall> recalls, string generated, string path)
|
||||
{
|
||||
Locations = locations;
|
||||
Recalls = recalls;
|
||||
Generated = generated;
|
||||
Path = path;
|
||||
foreach (var l in locations) _byId[l.Id] = l;
|
||||
}
|
||||
|
||||
public static Atlas Load(string path) => Parse(File.ReadAllText(path), path);
|
||||
|
||||
public static Atlas Parse(string json, string path = "")
|
||||
{
|
||||
var locs = new List<AtlasLocation>();
|
||||
var recalls = new List<AtlasRecall>();
|
||||
string generated = "";
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
JsonElement root = doc.RootElement;
|
||||
if (root.TryGetProperty("generated", out var g)) generated = g.GetString() ?? "";
|
||||
if (root.TryGetProperty("locations", out var arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (JsonElement e in arr.EnumerateArray())
|
||||
{
|
||||
var l = new AtlasLocation
|
||||
{
|
||||
Id = Int(e, "id"),
|
||||
Name = Str(e, "name"),
|
||||
Type = Str(e, "type"),
|
||||
Desc = Str(e, "desc"),
|
||||
Cell = Str(e, "cell"),
|
||||
Place = Str(e, "place"),
|
||||
Lb = Str(e, "lb"),
|
||||
Wcid = (uint)Int(e, "wcid"),
|
||||
MinLevel = Int(e, "minLevel"),
|
||||
MaxLevel = Int(e, "maxLevel"),
|
||||
Quest = Bool(e, "quest"),
|
||||
Closed = Bool(e, "closed"),
|
||||
};
|
||||
l.OnMap = TryNum(e, "ns", out l.Ns) & TryNum(e, "ew", out l.Ew);
|
||||
if (e.TryGetProperty("dest", out var d) && d.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
l.HasDest = true;
|
||||
l.DestOnMap = TryNum(d, "ns", out l.DestNs) & TryNum(d, "ew", out l.DestEw);
|
||||
l.DestName = Str(d, "name");
|
||||
l.DestPlace = Str(d, "place");
|
||||
}
|
||||
locs.Add(l);
|
||||
}
|
||||
}
|
||||
if (root.TryGetProperty("recalls", out arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (JsonElement e in arr.EnumerateArray())
|
||||
{
|
||||
var r = new AtlasRecall { SpellId = Int(e, "spell"), Name = Str(e, "name"), In = Str(e, "in") };
|
||||
r.OnMap = TryNum(e, "ns", out r.Ns) & TryNum(e, "ew", out r.Ew);
|
||||
recalls.Add(r);
|
||||
}
|
||||
}
|
||||
return new Atlas(locs, recalls, generated, path);
|
||||
}
|
||||
|
||||
public AtlasLocation? ById(int id) => _byId.TryGetValue(id, out var l) ? l : null;
|
||||
|
||||
// ── Search ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>How well <paramref name="name"/> matches <paramref name="q"/> (lower case): 0 = not at all.</summary>
|
||||
public static int MatchScore(string name, string q)
|
||||
{
|
||||
if (q.Length == 0) return 1;
|
||||
if (name.Equals(q, StringComparison.OrdinalIgnoreCase)) return 100;
|
||||
int at = name.IndexOf(q, StringComparison.OrdinalIgnoreCase);
|
||||
if (at == 0) return 80;
|
||||
if (at > 0)
|
||||
{
|
||||
char before = name[at - 1];
|
||||
return char.IsLetterOrDigit(before) ? 40 : 60; // starts a word / inside a word
|
||||
}
|
||||
// Every word of the query somewhere in the name ("mines despair").
|
||||
string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (words.Length < 2) return 0;
|
||||
foreach (string w in words)
|
||||
if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return 0;
|
||||
return 30;
|
||||
}
|
||||
|
||||
/// <summary>Type order when names match equally well: places before people.</summary>
|
||||
public static int TypeRank(string type) => type switch
|
||||
{
|
||||
"Town" => 0,
|
||||
"Dungeon" => 1,
|
||||
"Landmark" => 2,
|
||||
"Lifestone" => 3,
|
||||
"Bindstone" => 4,
|
||||
"Portal" => 5,
|
||||
"Vendor" => 6,
|
||||
"NPC" => 7,
|
||||
_ => 8,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The best atlas match for a name (/rnav arrow Holtburg): only places with a map
|
||||
/// position; best name match, then type (a town before its portal), then the
|
||||
/// nearest to the player when <paramref name="hasPos"/>.
|
||||
/// </summary>
|
||||
public AtlasLocation? FindBest(string query, bool hasPos, double ns, double ew)
|
||||
{
|
||||
string q = query.Trim();
|
||||
if (q.Length == 0) return null;
|
||||
AtlasLocation? best = null;
|
||||
int bestScore = 0, bestRank = int.MaxValue;
|
||||
double bestDist = double.MaxValue;
|
||||
foreach (var l in Locations)
|
||||
{
|
||||
if (!l.OnMap) continue;
|
||||
int s = MatchScore(l.Name, q);
|
||||
if (s == 0) continue;
|
||||
int rank = TypeRank(l.Type);
|
||||
double dist = hasPos ? NavCoords.Distance(ns, ew, l.Ns, l.Ew) : 0;
|
||||
bool better = s > bestScore
|
||||
|| (s == bestScore && rank < bestRank)
|
||||
|| (s == bestScore && rank == bestRank && dist < bestDist);
|
||||
if (!better) continue;
|
||||
best = l; bestScore = s; bestRank = rank; bestDist = dist;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locations matching <paramref name="query"/> (empty = all) and, when
|
||||
/// <paramref name="type"/> isn't empty, of that type; best matches first.
|
||||
/// </summary>
|
||||
public List<AtlasLocation> Search(string query, string? type, int max)
|
||||
{
|
||||
string q = query.Trim();
|
||||
var hits = new List<(AtlasLocation L, int S)>();
|
||||
foreach (var l in Locations)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(type) && !l.Type.Equals(type, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
int s = MatchScore(l.Name, q);
|
||||
if (s > 0) hits.Add((l, s));
|
||||
}
|
||||
hits.Sort((a, b) =>
|
||||
{
|
||||
int c = b.S.CompareTo(a.S);
|
||||
if (c != 0) return c;
|
||||
c = TypeRank(a.L.Type).CompareTo(TypeRank(b.L.Type));
|
||||
return c != 0 ? c : string.Compare(a.L.Name, b.L.Name, StringComparison.OrdinalIgnoreCase);
|
||||
});
|
||||
var result = new List<AtlasLocation>(Math.Min(max, hits.Count));
|
||||
for (int i = 0; i < hits.Count && result.Count < max; i++) result.Add(hits[i].L);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>The nearest on-map location of a type within <paramref name="maxUnits"/>, or null.</summary>
|
||||
public AtlasLocation? Nearest(string type, double ns, double ew, double maxUnits)
|
||||
{
|
||||
AtlasLocation? best = null;
|
||||
double bestD = maxUnits;
|
||||
foreach (var l in Locations)
|
||||
{
|
||||
if (!l.OnMap || !l.Type.Equals(type, StringComparison.Ordinal)) continue;
|
||||
double d = NavCoords.Distance(ns, ew, l.Ns, l.Ew);
|
||||
if (d <= bestD) { best = l; bestD = d; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>A portal by its weenie class, the one nearest the player when there are several.</summary>
|
||||
public AtlasLocation? PortalByWcid(uint wcid, double ns, double ew)
|
||||
{
|
||||
AtlasLocation? best = null;
|
||||
double bestD = double.MaxValue;
|
||||
foreach (var l in Locations)
|
||||
{
|
||||
if (l.Wcid != wcid || l.Type != "Portal") continue;
|
||||
double d = l.OnMap ? NavCoords.Distance(ns, ew, l.Ns, l.Ew) : double.MaxValue / 2;
|
||||
if (best == null || d < bestD) { best = l; bestD = d; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// ── JSON helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
private static string Str(JsonElement e, string name) =>
|
||||
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
|
||||
|
||||
private static int Int(JsonElement e, string name) =>
|
||||
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : 0;
|
||||
|
||||
private static bool Bool(JsonElement e, string name) =>
|
||||
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.True;
|
||||
|
||||
private static bool TryNum(JsonElement e, string name, out double d)
|
||||
{
|
||||
d = 0;
|
||||
return e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out d);
|
||||
}
|
||||
|
||||
public override string ToString() =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{Locations.Count} locations, {Recalls.Count} recalls ({Generated})");
|
||||
}
|
||||
107
Plugins/RynthCore.Plugin.RynthNav/AtlasStore.cs
Normal file
107
Plugins/RynthCore.Plugin.RynthNav/AtlasStore.cs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>A saved place: favorites and recent arrow targets. Kept by name and coordinates,
|
||||
/// not Atlas id, so they survive the Atlas being regenerated.</summary>
|
||||
internal sealed class SavedPlace
|
||||
{
|
||||
public string Name = "", Type = "";
|
||||
public double Ns, Ew;
|
||||
|
||||
public bool SameAs(SavedPlace o) =>
|
||||
Name.Equals(o.Name, StringComparison.OrdinalIgnoreCase) && Math.Abs(Ns - o.Ns) < 0.05 && Math.Abs(Ew - o.Ew) < 0.05;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Favorites and Recent (NavData\atlas.txt). The tick thread owns it; the plugin saves
|
||||
/// a copy of the text off the tick thread when Version moves. No host calls: the offline
|
||||
/// tests compile this file.
|
||||
/// </summary>
|
||||
internal sealed class AtlasStore
|
||||
{
|
||||
public const int MaxRecent = 20, MaxFavorites = 200;
|
||||
|
||||
public List<SavedPlace> Favorites { get; } = new();
|
||||
public List<SavedPlace> Recent { get; } = new();
|
||||
public int Version { get; private set; }
|
||||
|
||||
public bool IsFavorite(SavedPlace p) => Favorites.Exists(f => f.SameAs(p));
|
||||
|
||||
/// <summary>Adds it if it isn't there, removes it if it is. Returns true when it is now a favorite.</summary>
|
||||
public bool ToggleFavorite(SavedPlace p)
|
||||
{
|
||||
int i = Favorites.FindIndex(f => f.SameAs(p));
|
||||
Version++;
|
||||
if (i >= 0) { Favorites.RemoveAt(i); return false; }
|
||||
if (Favorites.Count >= MaxFavorites) Favorites.RemoveAt(Favorites.Count - 1);
|
||||
Favorites.Add(p);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool RemoveFavorite(string name)
|
||||
{
|
||||
int i = Favorites.FindIndex(f => f.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
if (i < 0) return false;
|
||||
Favorites.RemoveAt(i);
|
||||
Version++;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Puts it first in Recent (an arrow target or a trip).</summary>
|
||||
public void Touch(SavedPlace p)
|
||||
{
|
||||
int i = Recent.FindIndex(r => r.SameAs(p));
|
||||
if (i == 0) return;
|
||||
if (i > 0) Recent.RemoveAt(i);
|
||||
Recent.Insert(0, p);
|
||||
while (Recent.Count > MaxRecent) Recent.RemoveAt(Recent.Count - 1);
|
||||
Version++;
|
||||
}
|
||||
|
||||
public void ClearRecent()
|
||||
{
|
||||
if (Recent.Count == 0) return;
|
||||
Recent.Clear();
|
||||
Version++;
|
||||
}
|
||||
|
||||
// ── atlas.txt ────────────────────────────────────────────────────────────
|
||||
// fav\tname\tns\tew\ttype / recent\tname\tns\tew\ttype (newest first)
|
||||
|
||||
public string Serialize()
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("# RynthNav Atlas: favorites and recent places. kind<TAB>name<TAB>NS<TAB>EW<TAB>type\r\n");
|
||||
foreach (var f in Favorites) Line(sb, "fav", f, ci);
|
||||
foreach (var r in Recent) Line(sb, "recent", r, ci);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static void Line(StringBuilder sb, string kind, SavedPlace p, CultureInfo ci) =>
|
||||
sb.Append(kind).Append('\t').Append(p.Name.Replace('\t', ' ')).Append('\t')
|
||||
.Append(p.Ns.ToString("F2", ci)).Append('\t').Append(p.Ew.ToString("F2", ci)).Append('\t')
|
||||
.Append(p.Type.Replace('\t', ' ')).Append("\r\n");
|
||||
|
||||
public static AtlasStore Parse(string text)
|
||||
{
|
||||
var s = new AtlasStore();
|
||||
foreach (string raw in text.Split('\n'))
|
||||
{
|
||||
string line = raw.TrimEnd('\r');
|
||||
if (line.Length == 0 || line[0] == '#') continue;
|
||||
string[] f = line.Split('\t');
|
||||
if (f.Length < 4) continue;
|
||||
if (!double.TryParse(f[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double ns)) continue;
|
||||
if (!double.TryParse(f[3], NumberStyles.Float, CultureInfo.InvariantCulture, out double ew)) continue;
|
||||
var p = new SavedPlace { Name = f[1], Ns = ns, Ew = ew, Type = f.Length > 4 ? f[4] : "" };
|
||||
if (f[0] == "fav" && s.Favorites.Count < MaxFavorites && !s.IsFavorite(p)) s.Favorites.Add(p);
|
||||
else if (f[0] == "recent" && s.Recent.Count < MaxRecent) s.Recent.Add(p);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
41
Plugins/RynthCore.Plugin.RynthNav/AvoidFilter.cs
Normal file
41
Plugins/RynthCore.Plugin.RynthNav/AvoidFilter.cs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
using System;
|
||||
using DotRecast.Core.Numerics;
|
||||
using DotRecast.Detour;
|
||||
|
||||
namespace RynthNav.Routing;
|
||||
|
||||
/// <summary>
|
||||
/// Detour's default filter, minus every polygon that reaches into a portal's circle
|
||||
/// (<see cref="PortalAvoid"/>), so the detailed path goes round portals that aren't the step's
|
||||
/// target. The polygon under the player and the goal's polygon are always allowed (a path must
|
||||
/// start and end somewhere); a plan that can't reach its goal this way is planned again with the
|
||||
/// default filter and the steering check keeps the walker out of the circles. Tick thread only.
|
||||
/// </summary>
|
||||
internal sealed class AvoidFilter : IDtQueryFilter
|
||||
{
|
||||
private readonly DtQueryDefaultFilter _inner = new();
|
||||
private readonly PortalAvoid _avoid;
|
||||
private readonly double[] _xs = new double[8], _ys = new double[8];
|
||||
public long AllowA, AllowB;
|
||||
|
||||
public AvoidFilter(PortalAvoid avoid) { _avoid = avoid; }
|
||||
|
||||
public bool PassFilter(long refs, DtMeshTile tile, DtPoly poly)
|
||||
{
|
||||
if (!_inner.PassFilter(refs, tile, poly)) return false;
|
||||
if (_avoid.Count == 0 || refs == AllowA || refs == AllowB) return true;
|
||||
int n = Math.Min(poly.vertCount, _xs.Length);
|
||||
float[] v = tile.data.verts;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int k = poly.verts[i] * 3;
|
||||
_xs[i] = v[k]; // east
|
||||
_ys[i] = v[k + 2]; // north
|
||||
}
|
||||
return !_avoid.Touches(_xs.AsSpan(0, n), _ys.AsSpan(0, n));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
92
Plugins/RynthCore.Plugin.RynthNav/Entrance.cs
Normal file
92
Plugins/RynthCore.Plugin.RynthNav/Entrance.cs
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// Going INTO a place whose map position is a portal: a dungeon (the Atlas places a dungeon at
|
||||
/// its entrance portal) or a portal with a destination. The goto's last leg becomes a portal
|
||||
/// step, so it walks into the portal and waits for the teleport (the same step routes use),
|
||||
/// instead of stopping beside it. Host-free (the route tests cover it).
|
||||
/// </summary>
|
||||
internal static class Entrance
|
||||
{
|
||||
/// <summary>
|
||||
/// A wrecked portal ("Destroyed Portal to Redspire", "Destroyed Mayoi Portal"): still in the world
|
||||
/// data, but it takes you nowhere (10-02: routes and dungeon gotos tried to use them).
|
||||
/// </summary>
|
||||
public static bool IsDestroyed(string name) => name.StartsWith("Destroyed", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>True for an Atlas place that you reach by walking into a portal.</summary>
|
||||
public static bool IsEntrance(AtlasLocation l) =>
|
||||
l.Type.Equals("Dungeon", StringComparison.Ordinal) || (l.Type.Equals("Portal", StringComparison.Ordinal) && l.HasDest);
|
||||
|
||||
/// <summary>
|
||||
/// The portal to walk into for <paramref name="place"/>. A dungeon with several entrances: the
|
||||
/// nearest open one on the map (one that needs no quest first, when there is a choice), else the
|
||||
/// dungeon's own position (its entrance). Null, with <paramref name="why"/>, when the entrance
|
||||
/// has no position on the map (it's inside another dungeon): nothing is guessed.
|
||||
/// </summary>
|
||||
public static AtlasLocation? PortalFor(Atlas atlas, AtlasLocation place, bool hasPos, double ns, double ew, out string why)
|
||||
{
|
||||
why = "";
|
||||
if (place.Type.Equals("Portal", StringComparison.Ordinal))
|
||||
{
|
||||
if (IsDestroyed(place.Name)) { why = $"{place.Name} is destroyed: it doesn't take you anywhere"; return null; }
|
||||
if (place.OnMap) return place;
|
||||
why = $"{place.Name} is inside a dungeon (its portal has no position on the map), so I can't walk there";
|
||||
return null;
|
||||
}
|
||||
|
||||
AtlasLocation? best = null;
|
||||
double bestD = double.MaxValue;
|
||||
bool bestQuest = true, sawDestroyed = false;
|
||||
foreach (AtlasLocation l in atlas.Locations)
|
||||
{
|
||||
if (!l.OnMap || l.Closed || !l.HasDest || l.DestOnMap) continue;
|
||||
if (!l.Type.Equals("Portal", StringComparison.Ordinal)) continue;
|
||||
if (!l.DestName.Equals(place.Name, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (IsDestroyed(l.Name)) { sawDestroyed = true; continue; }
|
||||
double d = hasPos ? NavCoords.Distance(ns, ew, l.Ns, l.Ew) : 0;
|
||||
bool better = best == null || (bestQuest && !l.Quest) || (bestQuest == l.Quest && d < bestD);
|
||||
if (!better) continue;
|
||||
best = l; bestD = d; bestQuest = l.Quest;
|
||||
}
|
||||
if (best != null) return best;
|
||||
if (sawDestroyed)
|
||||
{
|
||||
why = $"the only portal into {place.Name} on the map is destroyed, so I can't walk in";
|
||||
return null;
|
||||
}
|
||||
if (place.OnMap) return place;
|
||||
why = $"{place.Name}'s entrance has no position on the map (it's reached from inside another dungeon), so I can't walk there";
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The route, ending with walking into the portal at (<paramref name="ns"/>, <paramref name="ew"/>):
|
||||
/// a plain walk becomes one portal step; a route (portals, recalls) whose last leg walks there
|
||||
/// gets that leg turned into a portal step.
|
||||
/// </summary>
|
||||
public static List<RouteStep> EndingInPortal(List<RouteStep>? route, double ns, double ew, string label)
|
||||
{
|
||||
var steps = route == null ? new List<RouteStep>() : new List<RouteStep>(route);
|
||||
if (steps.Count > 0)
|
||||
{
|
||||
RouteStep last = steps[^1];
|
||||
if (!last.UsePortal && !last.UseRecall && !last.IsHub && NavCoords.Distance(last.Ns, last.Ew, ns, ew) < 1.0)
|
||||
steps.RemoveAt(steps.Count - 1);
|
||||
}
|
||||
steps.Add(new RouteStep(ns, ew, usePortal: true, useRecall: false, label));
|
||||
return steps;
|
||||
}
|
||||
|
||||
/// <summary>The goto's line when the portal takes you in.</summary>
|
||||
public static string ArrivedText(string name, string type) =>
|
||||
type.Equals("Dungeon", StringComparison.Ordinal) ? $"arrived inside {name}" : $"went through {name}";
|
||||
|
||||
/// <summary>The goto's stop line when the portal doesn't fire.</summary>
|
||||
public static string NoTeleportText(string name) =>
|
||||
$"stopped: {name}'s portal didn't take you in (level or quest requirement?)";
|
||||
}
|
||||
231
Plugins/RynthCore.Plugin.RynthNav/NavCoarse.cs
Normal file
231
Plugins/RynthCore.Plugin.RynthNav/NavCoarse.cs
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using DotRecast.Core.Numerics;
|
||||
using DotRecast.Detour;
|
||||
using DotRecast.Detour.Io;
|
||||
|
||||
namespace RynthNav.Routing;
|
||||
|
||||
/// <summary>
|
||||
/// A long-range walking route over <see cref="NavGraph"/>: the portals to cross, in order, from
|
||||
/// the region underfoot to the target's region. The walker keeps its 5x5 tile window and the
|
||||
/// detailed Detour planner; this only tells it which point to plan to next (the furthest portal
|
||||
/// on the route whose tiles are loaded), so a goto can swing around a bay, a lake or a ridge
|
||||
/// instead of probing along the straight line. Tick thread only (Detour objects are not shared).
|
||||
/// </summary>
|
||||
internal sealed class NavCoarse
|
||||
{
|
||||
private readonly NavGraph _g;
|
||||
private readonly List<int> _portals;
|
||||
private readonly int[] _regions; // _regions[i] = region before portal i; _regions[^1] = the goal's region
|
||||
private int _idx; // portals crossed so far
|
||||
public double GoalEw { get; }
|
||||
public double GoalNs { get; }
|
||||
public float Cost { get; }
|
||||
public int Count => _portals.Count;
|
||||
public int Crossed => _idx;
|
||||
|
||||
private NavCoarse(NavGraph g, List<int> portals, int startRegion, double gx, double gz, float cost)
|
||||
{
|
||||
_g = g; _portals = portals; GoalEw = gx; GoalNs = gz; Cost = cost;
|
||||
_regions = new int[portals.Count + 1];
|
||||
_regions[0] = startRegion;
|
||||
for (int i = 0; i < portals.Count; i++) _regions[i + 1] = g.Across(portals[i], _regions[i]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A* over the graph from <paramref name="start"/> to <paramref name="goal"/>; null when it has no
|
||||
/// route between their regions. The first and last legs are measured on the navmesh (the start's
|
||||
/// and the goal's tiles), so a portal behind a wall in the start tile isn't mistaken for a near one.
|
||||
/// </summary>
|
||||
/// <summary>A* with straight first and last legs (no navmesh at hand: tests, tools).</summary>
|
||||
public static NavCoarse? Plan(NavGraph g, int startRegion, double sx, double sz, int goalRegion, double gx, double gz, out int expanded)
|
||||
{
|
||||
List<int>? route = g.FindRoute(startRegion, (float)sx, (float)sz, goalRegion, (float)gx, (float)gz, out float cost, out expanded);
|
||||
return route == null ? null : new NavCoarse(g, route, startRegion, gx, gz, cost);
|
||||
}
|
||||
|
||||
public static NavCoarse? Plan(NavGraph g, Probe start, Probe goal, out int expanded)
|
||||
=> Plan(g, Request.Measure(g, start, goal), out expanded);
|
||||
|
||||
/// <summary>
|
||||
/// Everything A* needs, measured on the navmesh up front (tick thread): the walks from the start
|
||||
/// to its region's portals and from the goal's region's portals to the goal. The search itself
|
||||
/// then touches only the graph, so it can run on a worker.
|
||||
/// </summary>
|
||||
internal sealed class Request
|
||||
{
|
||||
public int StartRegion, GoalRegion;
|
||||
public float Sx, Sz, Gx, Gz;
|
||||
public Dictionary<int, float> StartLegs = new(), GoalLegs = new();
|
||||
|
||||
public static Request Measure(NavGraph g, Probe start, Probe goal)
|
||||
{
|
||||
var r = new Request { StartRegion = start.Region, GoalRegion = goal.Region, Sx = start.Pt.X, Sz = start.Pt.Z, Gx = goal.Pt.X, Gz = goal.Pt.Z };
|
||||
foreach (int p in g.RegionPortals(start.Region)) r.StartLegs[p] = start.WalkTo(g.Portal(p));
|
||||
if (start.Region != goal.Region)
|
||||
foreach (int p in g.RegionPortals(goal.Region)) r.GoalLegs[p] = goal.WalkTo(g.Portal(p));
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A* for a measured request. Touches only the (immutable) graph: safe on a worker thread.</summary>
|
||||
public static NavCoarse? Plan(NavGraph g, Request q, out int expanded)
|
||||
{
|
||||
List<int>? route = g.FindRoute(q.StartRegion, q.Sx, q.Sz, q.GoalRegion, q.Gx, q.Gz, out float cost, out expanded,
|
||||
startLeg: p => q.StartLegs.TryGetValue(p, out float c) ? c : float.NaN,
|
||||
goalLeg: p => q.GoalLegs.TryGetValue(p, out float c) ? c : float.NaN);
|
||||
return route == null ? null : new NavCoarse(g, route, q.StartRegion, q.Gx, q.Gz, cost);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Follows the player: the route position moves to the furthest region on the rest of the route
|
||||
/// that is the region underfoot. False when that region isn't on the rest of the route (wandered
|
||||
/// off it, or knocked onto a roof): plan again.
|
||||
/// </summary>
|
||||
public bool Advance(int currentRegion)
|
||||
{
|
||||
if (currentRegion < 0) return true; // between polygons for a moment: keep going
|
||||
for (int k = _regions.Length - 1; k >= _idx; k--)
|
||||
if (_regions[k] == currentRegion) { _idx = k; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where to plan to next: the furthest portal on the rest of the route whose tiles are all
|
||||
/// loaded (scanning stops at the first one that isn't), or the goal itself once every
|
||||
/// remaining portal is loaded (<paramref name="final"/>).
|
||||
/// </summary>
|
||||
public (float Ew, float Up, float Ns) Steer(Func<uint, bool> loaded, out bool final)
|
||||
{
|
||||
int j = -1;
|
||||
for (int i = _idx; i < _portals.Count; i++)
|
||||
{
|
||||
if (!loaded(_g.RegionLandblock(_regions[i])) || !loaded(_g.RegionLandblock(_regions[i + 1]))) break;
|
||||
j = i;
|
||||
}
|
||||
final = _idx >= _portals.Count || j == _portals.Count - 1;
|
||||
if (final) return ((float)GoalEw, float.NaN, (float)GoalNs);
|
||||
// The next portal isn't loaded yet (j < _idx): aim at it anyway; the caller falls back to
|
||||
// probing toward it until its tile streams in.
|
||||
return _g.Portal(_portals[Math.Max(j, _idx)]);
|
||||
}
|
||||
|
||||
/// <summary>Landblocks of the next few regions on the route (to load ahead).</summary>
|
||||
public IEnumerable<uint> Upcoming(int count)
|
||||
{
|
||||
uint last = uint.MaxValue;
|
||||
for (int i = _idx; i < _regions.Length && count > 0; i++)
|
||||
{
|
||||
uint lb = _g.RegionLandblock(_regions[i]);
|
||||
if (lb == last) continue;
|
||||
last = lb; count--;
|
||||
yield return lb;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What is left to walk: to the next portal, portal to portal, then to the goal (straight
|
||||
/// lines). Falls as the walker follows the route even where the route turns away from the goal,
|
||||
/// so the no-progress watchdog doesn't stop a long detour.
|
||||
/// </summary>
|
||||
public double Remaining(double ew, double ns)
|
||||
{
|
||||
double total = 0, x = ew, z = ns;
|
||||
for (int i = _idx; i < _portals.Count; i++)
|
||||
{
|
||||
var p = _g.Portal(_portals[i]);
|
||||
total += Math.Sqrt((p.Ew - x) * (p.Ew - x) + (p.Ns - z) * (p.Ns - z));
|
||||
x = p.Ew; z = p.Ns;
|
||||
}
|
||||
return total + Math.Sqrt((GoalEw - x) * (GoalEw - x) + (GoalNs - z) * (GoalNs - z));
|
||||
}
|
||||
|
||||
// ── Regions and walking distances at the two ends (shared by the plugin and the harness) ──
|
||||
|
||||
/// <summary>A point on the navmesh, its graph region, and a query to measure walks from it.</summary>
|
||||
internal sealed class Probe
|
||||
{
|
||||
public readonly DtNavMeshQuery Query;
|
||||
public readonly long Ref;
|
||||
public readonly RcVec3f Pt;
|
||||
public readonly int Region;
|
||||
|
||||
public Probe(DtNavMeshQuery q, long polyRef, RcVec3f pt, int region) { Query = q; Ref = polyRef; Pt = pt; Region = region; }
|
||||
|
||||
/// <summary>Walking distance (2D) from here to a portal point; NaN when the navmesh can't tell.</summary>
|
||||
public float WalkTo((float Ew, float Up, float Ns) portal)
|
||||
{
|
||||
var filter = new DtQueryDefaultFilter();
|
||||
var target = new RcVec3f(portal.Ew, portal.Up, portal.Ns);
|
||||
Query.FindNearestPoly(target, new RcVec3f(3, 8, 3), filter, out long pref, out RcVec3f ppt, out _);
|
||||
if (pref == 0) return float.NaN;
|
||||
if (pref == Ref) return Flat(Pt, ppt);
|
||||
Span<long> path = new long[1024];
|
||||
var st = Query.FindPath(Ref, pref, Pt, ppt, filter, path, out int pc, 1024);
|
||||
if (st.Failed() || pc == 0 || path[pc - 1] != pref) return float.NaN;
|
||||
Span<DtStraightPath> sp = new DtStraightPath[256];
|
||||
Query.FindStraightPath(Pt, ppt, path[..pc], pc, sp, out int spc, 256, 0);
|
||||
if (spc < 2) return float.NaN;
|
||||
float len = 0;
|
||||
for (int i = 1; i < spc; i++) len += Flat(sp[i - 1].pos, sp[i].pos);
|
||||
return len + Flat(sp[spc - 1].pos, ppt);
|
||||
}
|
||||
|
||||
private static float Flat(RcVec3f a, RcVec3f b) => MathF.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Z - b.Z) * (a.Z - b.Z));
|
||||
}
|
||||
|
||||
/// <summary>A probe on the loaded navmesh at a polygon already found (the one underfoot).</summary>
|
||||
public static Probe? ProbeAt(NavGraph g, DtNavMesh nav, DtNavMeshQuery q, long polyRef, RcVec3f pt, IReadOnlyDictionary<uint, int[]> tileRegions)
|
||||
{
|
||||
int r = RegionOf(g, nav, polyRef, tileRegions);
|
||||
return r < 0 ? null : new Probe(q, polyRef, pt, r);
|
||||
}
|
||||
|
||||
/// <summary>A probe on the loaded navmesh near a point (12 units, then <paramref name="reach"/>).</summary>
|
||||
public static Probe? ProbeNear(NavGraph g, DtNavMesh nav, DtNavMeshQuery q, double ew, double up, double ns, float reach, IReadOnlyDictionary<uint, int[]> tileRegions)
|
||||
{
|
||||
var filter = new DtQueryDefaultFilter();
|
||||
foreach (float r in new[] { 12f, reach })
|
||||
{
|
||||
q.FindNearestPoly(new RcVec3f((float)ew, (float)up, (float)ns), new RcVec3f(r, 512, r), filter, out long pref, out RcVec3f pt, out _);
|
||||
if (pref != 0) return ProbeAt(g, nav, q, pref, pt, tileRegions);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The graph region of a polygon of a loaded tile, or -1.</summary>
|
||||
public static int RegionOf(NavGraph g, DtNavMesh nav, long polyRef, IReadOnlyDictionary<uint, int[]> tileRegions)
|
||||
{
|
||||
if (polyRef == 0) return -1;
|
||||
if (nav.GetTileAndPolyByRef(polyRef, out DtMeshTile tile, out DtPoly poly).Failed() || tile?.data?.header == null) return -1;
|
||||
uint lb = (uint)((tile.data.header.x << 8) | tile.data.header.y);
|
||||
if (!tileRegions.TryGetValue(lb, out int[]? regions) || poly.index >= regions.Length) return -1;
|
||||
return g.Region(lb, regions[poly.index]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A probe at a point of a tile that may not be loaded: reads the tile file into a throwaway
|
||||
/// one-tile navmesh. Null when there is no tile, it doesn't match the graph, or no walkable
|
||||
/// ground is within <paramref name="reach"/> units.
|
||||
/// </summary>
|
||||
public static Probe? ProbeFile(NavGraph g, string navDataDir, double ew, double up, double ns, float reach)
|
||||
{
|
||||
int x = (int)Math.Floor(ew / 192.0), y = (int)Math.Floor(ns / 192.0);
|
||||
if (x < 0 || x > 255 || y < 0 || y > 255) return null;
|
||||
uint lb = (uint)((x << 8) | y);
|
||||
string path = Path.Combine(navDataDir, $"nav_{lb:X4}.tile");
|
||||
if (!File.Exists(path)) return null;
|
||||
DtMeshData md;
|
||||
using (var fr = File.OpenRead(path)) using (var br = new BinaryReader(fr)) md = new DtMeshDataReader().Read(br, 6);
|
||||
var (polys, verts, tris) = NavRegions.Fingerprint(md);
|
||||
if (!g.Matches(lb, polys, verts, tris)) return null;
|
||||
var regions = new Dictionary<uint, int[]> { [lb] = NavRegions.Build(md, out _) };
|
||||
var nav = new DtNavMesh();
|
||||
var prm = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 2, maxPolys = 1 << 16 };
|
||||
nav.Init(ref prm, 6);
|
||||
nav.AddTile(md, 0, 0, out _);
|
||||
return ProbeNear(g, nav, new DtNavMeshQuery(nav), ew, float.IsFinite((float)up) ? up : 0, ns, reach, regions);
|
||||
}
|
||||
}
|
||||
134
Plugins/RynthCore.Plugin.RynthNav/NavCoords.cs
Normal file
134
Plugins/RynthCore.Plugin.RynthNav/NavCoords.cs
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// Map coordinates (the /loc numbers: NS and EW in decimal degrees, north and east
|
||||
/// positive) and RynthNav's world units (x = east, y = north, 24 units per tenth of
|
||||
/// a degree, landblock 192 units). No host calls: the offline tests compile this file.
|
||||
/// </summary>
|
||||
internal static class NavCoords
|
||||
{
|
||||
public const double UnitsPerDegree = 240.0;
|
||||
|
||||
private static readonly string[] Compass16 =
|
||||
{ "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW" };
|
||||
|
||||
public static double WorldX(double ew) => (ew * 10.0 + 1019.5) * 24.0;
|
||||
public static double WorldY(double ns) => (ns * 10.0 + 1019.5) * 24.0;
|
||||
public static double EwFromWorld(double wx) => (wx / 24.0 - 1019.5) / 10.0;
|
||||
public static double NsFromWorld(double wy) => (wy / 24.0 - 1019.5) / 10.0;
|
||||
|
||||
/// <summary>Map coordinates of a cell-relative position (NavCoordinateHelper's formula).</summary>
|
||||
public static void FromCell(uint cell, double x, double y, out double ns, out double ew)
|
||||
{
|
||||
int lbX = (int)((cell >> 24) & 0xFF), lbY = (int)((cell >> 16) & 0xFF);
|
||||
ew = (lbX * 8.0 + x / 24.0 - 1019.5) / 10.0;
|
||||
ns = (lbY * 8.0 + y / 24.0 - 1019.5) / 10.0;
|
||||
}
|
||||
|
||||
/// <summary>Straight-line distance in world units (yards).</summary>
|
||||
public static double Distance(double ns1, double ew1, double ns2, double ew2)
|
||||
{
|
||||
double dn = (ns2 - ns1) * UnitsPerDegree, de = (ew2 - ew1) * UnitsPerDegree;
|
||||
return Math.Sqrt(dn * dn + de * de);
|
||||
}
|
||||
|
||||
/// <summary>Compass bearing from one point to another: 0 = north, clockwise, 0..360.</summary>
|
||||
public static double Bearing(double fromNs, double fromEw, double toNs, double toEw)
|
||||
{
|
||||
double b = Math.Atan2(toEw - fromEw, toNs - fromNs) * 180.0 / Math.PI;
|
||||
return b < 0 ? b + 360.0 : b;
|
||||
}
|
||||
|
||||
public static string CompassPoint(double bearing) => Compass16[(int)Math.Round(((bearing % 360.0) + 360.0) % 360.0 / 22.5) & 15];
|
||||
|
||||
/// <summary>"42.1N, 33.6E".</summary>
|
||||
public static string Fmt(double ns, double ew) => FmtOne(ns, 'N', 'S') + ", " + FmtOne(ew, 'E', 'W');
|
||||
|
||||
public static string FmtOne(double v, char pos, char neg) =>
|
||||
Math.Abs(v).ToString("F1", CultureInfo.InvariantCulture) + (v >= 0 ? pos : neg);
|
||||
|
||||
/// <summary>"350 yd" up close, "2.4 km" (well, thousands of yards) far away.</summary>
|
||||
public static string FmtDistance(double units) =>
|
||||
units < 1000 ? units.ToString("0", CultureInfo.InvariantCulture) + " yd"
|
||||
: (units / 1000.0).ToString("0.0", CultureInfo.InvariantCulture) + "k yd";
|
||||
|
||||
/// <summary>
|
||||
/// "42.5N, 33.6E" (the /loc order). Also takes "42.5 N, 33.6 E", and the other order
|
||||
/// when the letters say so ("33.6E 42.5N"). Two N/S (or two E/W) values are refused.
|
||||
/// (Moved here from RynthNavPlugin unchanged, so the tests can reach it.)
|
||||
/// </summary>
|
||||
public static bool TryParseLoc(string? s, out double ns, out double ew)
|
||||
{
|
||||
ns = 0; ew = 0;
|
||||
if (string.IsNullOrWhiteSpace(s)) return false;
|
||||
var parts = new List<string>();
|
||||
foreach (var t in s.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
bool loneLetter = t.Length == 1 && "NSEWnsew".IndexOf(t[0]) >= 0;
|
||||
if (loneLetter && parts.Count > 0 && char.IsDigit(parts[^1][^1])) parts[^1] += t;
|
||||
else parts.Add(t);
|
||||
}
|
||||
if (parts.Count < 2) return false;
|
||||
if (!TryCoord(parts[0], out double a, out char axisA) || !TryCoord(parts[1], out double b, out char axisB)) return false;
|
||||
if (axisA != ' ' && axisA == axisB) return false;
|
||||
if (axisA == 'E' || axisB == 'N') { ns = b; ew = a; }
|
||||
else { ns = a; ew = b; }
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A coordinate pair followed by an optional name: "42.1N, 33.6E Holtburg Lifestone"
|
||||
/// gives 42.1, 33.6 and "Holtburg Lifestone" (the panel and chat send targets this way).
|
||||
/// </summary>
|
||||
public static bool TrySplitCoordsAndName(string? s, out double ns, out double ew, out string name)
|
||||
{
|
||||
ns = 0; ew = 0; name = "";
|
||||
if (!TryParseLoc(s, out ns, out ew)) return false;
|
||||
// Skip the tokens TryParseLoc used: two numbers, each maybe with a letter after a space.
|
||||
string t = s!.Trim();
|
||||
int pos = 0;
|
||||
for (int n = 0; n < 2; n++)
|
||||
{
|
||||
while (pos < t.Length && (t[pos] == ' ' || t[pos] == ',')) pos++;
|
||||
while (pos < t.Length && t[pos] != ' ' && t[pos] != ',') pos++;
|
||||
int save = pos;
|
||||
while (pos < t.Length && t[pos] == ' ') pos++;
|
||||
if (pos < t.Length && "NSEWnsew".IndexOf(t[pos]) >= 0 && (pos + 1 == t.Length || t[pos + 1] == ' ' || t[pos + 1] == ','))
|
||||
pos++;
|
||||
else
|
||||
pos = save;
|
||||
}
|
||||
name = pos < t.Length ? t.Substring(pos).Trim(' ', ',') : "";
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="s"/> starts with a coordinate pair ("42.1N 33.6E",
|
||||
/// "42.1, 33.6") rather than a name ("Holtburg", "Area 51").
|
||||
/// </summary>
|
||||
public static bool LooksLikeCoords(string? s) => TryParseLoc(s, out _, out _);
|
||||
|
||||
// axis: 'N' for an N/S letter, 'E' for an E/W letter, ' ' for none.
|
||||
private static bool TryCoord(string tok, out double val, out char axis)
|
||||
{
|
||||
val = 0; axis = ' ';
|
||||
tok = tok.Trim().ToUpperInvariant();
|
||||
if (tok.Length == 0) return false;
|
||||
int sign = 1;
|
||||
char last = tok[^1];
|
||||
if (last is 'N' or 'S' or 'E' or 'W')
|
||||
{
|
||||
if (last is 'S' or 'W') sign = -1;
|
||||
axis = last is 'N' or 'S' ? 'N' : 'E';
|
||||
tok = tok[..^1];
|
||||
}
|
||||
if (!double.TryParse(tok, NumberStyles.Float, CultureInfo.InvariantCulture, out val)) return false;
|
||||
if (double.IsNaN(val) || double.IsInfinity(val)) return false;
|
||||
val *= sign;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
139
Plugins/RynthCore.Plugin.RynthNav/NavDataConfig.cs
Normal file
139
Plugins/RynthCore.Plugin.RynthNav/NavDataConfig.cs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// Where RynthNav's data folder is: navmesh tiles (nav_XXXX.tile), portals.tsv, locations.json,
|
||||
/// and the player's own atlas.txt / recalls.txt. In order:
|
||||
/// 1. the RYNTHNAV_NAVDATA environment variable (a test client, a second install);
|
||||
/// 2. "navDataDir" in %APPDATA%\RynthCore\rynthnav.json, e.g. {"navDataDir": "D:\\AC\\NavData"}
|
||||
/// (the launcher's tile updater reads the same file, so both agree);
|
||||
/// 3. C:\Games\RynthCore\NavData, where the release zip and the launcher put the tiles.
|
||||
/// A value that isn't a full path is ignored (and the source says so). Host-free, so the
|
||||
/// route tests cover it.
|
||||
/// </summary>
|
||||
internal sealed class NavDataConfig
|
||||
{
|
||||
public const string DefaultDir = @"C:\Games\RynthCore\NavData";
|
||||
public const string EnvVar = "RYNTHNAV_NAVDATA";
|
||||
public const string SettingsFileName = "rynthnav.json";
|
||||
|
||||
public string Dir { get; }
|
||||
/// <summary>Where <see cref="Dir"/> came from, for the log and /rnav navdata.</summary>
|
||||
public string Source { get; }
|
||||
|
||||
private NavDataConfig(string dir, string source) { Dir = dir; Source = source; }
|
||||
|
||||
public static string SettingsPath =>
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", SettingsFileName);
|
||||
|
||||
public static NavDataConfig Resolve()
|
||||
{
|
||||
string settings;
|
||||
try { settings = SettingsPath; } catch { settings = ""; }
|
||||
return Resolve(Environment.GetEnvironmentVariable(EnvVar), settings);
|
||||
}
|
||||
|
||||
internal static NavDataConfig Resolve(string? env, string settingsPath)
|
||||
{
|
||||
string note = "";
|
||||
if (!string.IsNullOrWhiteSpace(env))
|
||||
{
|
||||
if (IsFullPath(env)) return new NavDataConfig(Clean(env), EnvVar);
|
||||
note = $"; {EnvVar} ignored (not a full path)";
|
||||
}
|
||||
try
|
||||
{
|
||||
if (settingsPath.Length > 0 && File.Exists(settingsPath))
|
||||
{
|
||||
string? dir = ReadSetting(File.ReadAllText(settingsPath));
|
||||
if (dir != null && IsFullPath(dir)) return new NavDataConfig(Clean(dir), settingsPath + note);
|
||||
if (dir != null) note += $"; navDataDir in {settingsPath} ignored (not a full path)";
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { note += $"; {settingsPath} unreadable ({ex.GetType().Name})"; }
|
||||
return new NavDataConfig(DefaultDir, "default" + note);
|
||||
}
|
||||
|
||||
/// <summary>The "navDataDir" string from rynthnav.json's text, or null.</summary>
|
||||
internal static string? ReadSetting(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Object) return null;
|
||||
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
|
||||
if (p.Name.Equals("navDataDir", StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.String)
|
||||
return p.Value.GetString();
|
||||
}
|
||||
catch (JsonException) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A true/false setting from rynthnav.json ("portals", "recalls"); <paramref name="fallback"/> when absent.</summary>
|
||||
internal static bool ReadSwitch(string name, bool fallback)
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = SettingsPath;
|
||||
if (!File.Exists(path)) return fallback;
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path), new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Object) return fallback;
|
||||
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
|
||||
if (p.Name.Equals(name, StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind is JsonValueKind.True or JsonValueKind.False)
|
||||
return p.Value.GetBoolean();
|
||||
}
|
||||
catch { }
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/// <summary>A number setting from rynthnav.json; <paramref name="fallback"/> when absent or not a number.</summary>
|
||||
internal static double ReadNumber(string name, double fallback)
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = SettingsPath;
|
||||
if (!File.Exists(path)) return fallback;
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path), new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Object) return fallback;
|
||||
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
|
||||
if (p.Name.Equals(name, StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.Number)
|
||||
return p.Value.GetDouble();
|
||||
}
|
||||
catch { }
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/// <summary>Writes a number setting into rynthnav.json, keeping everything else in it.</summary>
|
||||
internal static void WriteNumber(string name, double value) => Write(name, System.Text.Json.Nodes.JsonValue.Create(value));
|
||||
|
||||
/// <summary>Writes a true/false setting into rynthnav.json, keeping everything else in it (navDataDir, which the launcher reads too).</summary>
|
||||
internal static void WriteSwitch(string name, bool value) => Write(name, System.Text.Json.Nodes.JsonValue.Create(value));
|
||||
|
||||
private static void Write(string name, System.Text.Json.Nodes.JsonNode? value)
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = SettingsPath;
|
||||
System.Text.Json.Nodes.JsonObject root = new();
|
||||
if (File.Exists(path)
|
||||
&& System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(path), documentOptions: new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }) is System.Text.Json.Nodes.JsonObject existing)
|
||||
root = existing;
|
||||
root[name] = value;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
string tmp = path + ".tmp";
|
||||
File.WriteAllText(tmp, root.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
|
||||
File.Move(tmp, path, overwrite: true);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static bool IsFullPath(string path)
|
||||
{
|
||||
try { return Path.IsPathFullyQualified(path.Trim()); } catch { return false; }
|
||||
}
|
||||
|
||||
private static string Clean(string path) => path.Trim().TrimEnd('\\', '/');
|
||||
}
|
||||
393
Plugins/RynthCore.Plugin.RynthNav/NavGraph.cs
Normal file
393
Plugins/RynthCore.Plugin.RynthNav/NavGraph.cs
Normal file
|
|
@ -0,0 +1,393 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthNav.Routing;
|
||||
|
||||
/// <summary>
|
||||
/// The coarse long-range graph of the navmesh (NavData\navgraph.bin, made by
|
||||
/// RynthNav.Baker --graph from the finished tiles).
|
||||
///
|
||||
/// - Regions: the connected walkable areas of each tile (<see cref="NavRegions"/>).
|
||||
/// - Portals: places where a region links to a region of the neighbouring tile (Detour's own
|
||||
/// cross-tile links, grouped into stretches along the border; one point per stretch).
|
||||
/// - Costs: the walking distance inside a region between each pair of its portals.
|
||||
///
|
||||
/// A route is an A* over portals: from the region underfoot to the target's region. The walker
|
||||
/// then follows the portal points with the detailed planner, a few landblocks at a time.
|
||||
///
|
||||
/// Tile set check: the file records each tile's polygon/vertex/detail-triangle counts. The
|
||||
/// plugin compares them with every tile it loads and ignores the graph on the first mismatch
|
||||
/// (a graph from another bake), falling back to walking without it.
|
||||
///
|
||||
/// Host-free (no AC, no Detour): the plugin, the baker and the tests share it.
|
||||
/// </summary>
|
||||
internal sealed class NavGraph
|
||||
{
|
||||
public const string FileName = "navgraph.bin";
|
||||
private const uint Magic = 0x31474E52; // "RNG1"
|
||||
private const int Version = 1;
|
||||
private const ushort NoCost = 0xFFFF;
|
||||
public const float CostUnit = 0.5f; // costs are stored in half-units
|
||||
|
||||
public readonly struct TileInfo
|
||||
{
|
||||
public readonly ushort Lb; public readonly int Polys, Verts, DetailTris, RegionBase, RegionCount;
|
||||
public TileInfo(ushort lb, int polys, int verts, int detailTris, int regionBase, int regionCount)
|
||||
{ Lb = lb; Polys = polys; Verts = verts; DetailTris = detailTris; RegionBase = regionBase; RegionCount = regionCount; }
|
||||
}
|
||||
|
||||
public byte[] SetId { get; private set; } = Array.Empty<byte>();
|
||||
public string SetIdHex => Convert.ToHexString(SetId).ToLowerInvariant();
|
||||
public int RegionCount { get; private set; }
|
||||
public int PortalCount => _px.Length;
|
||||
public int TileCount => _tiles.Count;
|
||||
|
||||
private readonly Dictionary<ushort, TileInfo> _tiles = new();
|
||||
private float[] _px = Array.Empty<float>(), _py = Array.Empty<float>(), _pz = Array.Empty<float>();
|
||||
private int[] _pa = Array.Empty<int>(), _pb = Array.Empty<int>();
|
||||
private int[]?[] _regionPortals = Array.Empty<int[]?>();
|
||||
private ushort[]?[] _regionCosts = Array.Empty<ushort[]?>();
|
||||
|
||||
public bool TryGetTile(uint lb, out TileInfo t) => _tiles.TryGetValue((ushort)lb, out t);
|
||||
|
||||
/// <summary>Global region id of local region <paramref name="local"/> in tile <paramref name="lb"/>, or -1.</summary>
|
||||
public int Region(uint lb, int local)
|
||||
=> _tiles.TryGetValue((ushort)lb, out TileInfo t) && local >= 0 && local < t.RegionCount ? t.RegionBase + local : -1;
|
||||
|
||||
private ushort[] _regionLb = Array.Empty<ushort>();
|
||||
|
||||
/// <summary>The landblock a global region belongs to.</summary>
|
||||
public uint RegionLandblock(int region) => (uint)region < (uint)_regionLb.Length ? _regionLb[region] : 0u;
|
||||
|
||||
/// <summary>Portal position in world units: east, height, north.</summary>
|
||||
public (float Ew, float Up, float Ns) Portal(int p) => (_px[p], _py[p], _pz[p]);
|
||||
public (int A, int B) PortalRegions(int p) => (_pa[p], _pb[p]);
|
||||
public int[] RegionPortals(int region) => _regionPortals[region] ?? Array.Empty<int>();
|
||||
|
||||
/// <summary>True when a loaded tile matches what the graph was built from.</summary>
|
||||
public bool Matches(uint lb, int polys, int verts, int detailTris)
|
||||
=> _tiles.TryGetValue((ushort)lb, out TileInfo t) && t.Polys == polys && t.Verts == verts && t.DetailTris == detailTris;
|
||||
|
||||
// ── Building (the baker) ───────────────────────────────────────────────────
|
||||
|
||||
public sealed class Builder
|
||||
{
|
||||
private readonly List<TileInfo> _tiles = new();
|
||||
private readonly List<(float x, float y, float z, int a, int b)> _portals = new();
|
||||
private readonly Dictionary<int, (int[] portals, ushort[] costs)> _costs = new();
|
||||
private int _regions;
|
||||
|
||||
/// <summary>Adds a tile (in any order); returns the global id of its region 0.</summary>
|
||||
public int AddTile(uint lb, int polys, int verts, int detailTris, int regionCount)
|
||||
{
|
||||
int b = _regions;
|
||||
_tiles.Add(new TileInfo((ushort)lb, polys, verts, detailTris, b, regionCount));
|
||||
_regions += regionCount;
|
||||
return b;
|
||||
}
|
||||
|
||||
public int AddPortal(float x, float y, float z, int regionA, int regionB)
|
||||
{
|
||||
_portals.Add((x, y, z, regionA, regionB));
|
||||
return _portals.Count - 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Walking costs inside a region between its portals: costs[i*n+j] (i < j used),
|
||||
/// world units; NaN or infinity = no path found.
|
||||
/// </summary>
|
||||
public void SetRegionCosts(int region, int[] portals, float[] costs)
|
||||
{
|
||||
int n = portals.Length;
|
||||
var tri = new ushort[n * (n - 1) / 2];
|
||||
int k = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
for (int j = i + 1; j < n; j++)
|
||||
{
|
||||
float c = costs[i * n + j];
|
||||
tri[k++] = float.IsFinite(c) ? (ushort)Math.Min(NoCost - 1, Math.Max(1, (int)Math.Round(c / CostUnit))) : NoCost;
|
||||
}
|
||||
_costs[region] = (portals, tri);
|
||||
}
|
||||
|
||||
public int Regions => _regions;
|
||||
|
||||
public void Write(Stream output)
|
||||
{
|
||||
using var gz = new GZipStream(output, CompressionLevel.SmallestSize, leaveOpen: true);
|
||||
using var w = new BinaryWriter(gz, Encoding.UTF8, leaveOpen: true);
|
||||
w.Write(Magic); w.Write(Version);
|
||||
w.Write(SetIdOf(_tiles));
|
||||
w.Write(_tiles.Count);
|
||||
foreach (TileInfo t in _tiles)
|
||||
{
|
||||
w.Write(t.Lb); w.Write(t.Polys); w.Write(t.Verts); w.Write(t.DetailTris); w.Write(t.RegionBase); w.Write(t.RegionCount);
|
||||
}
|
||||
w.Write(_regions);
|
||||
w.Write(_portals.Count);
|
||||
foreach (var p in _portals) { w.Write(p.x); w.Write(p.y); w.Write(p.z); w.Write(p.a); w.Write(p.b); }
|
||||
w.Write(_costs.Count);
|
||||
foreach (var (region, (portals, tri)) in _costs)
|
||||
{
|
||||
w.Write(region); w.Write(portals.Length);
|
||||
foreach (int p in portals) w.Write(p);
|
||||
foreach (ushort c in tri) w.Write(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Id of a tile set: SHA-256 (first 16 bytes) over every tile's landblock and fingerprint, in landblock order.</summary>
|
||||
public static byte[] SetIdOf(IEnumerable<TileInfo> tiles)
|
||||
{
|
||||
var sorted = new List<TileInfo>(tiles);
|
||||
sorted.Sort((a, b) => a.Lb.CompareTo(b.Lb));
|
||||
using var ms = new MemoryStream();
|
||||
using (var w = new BinaryWriter(ms, Encoding.UTF8, leaveOpen: true))
|
||||
foreach (TileInfo t in sorted) { w.Write(t.Lb); w.Write(t.Polys); w.Write(t.Verts); w.Write(t.DetailTris); }
|
||||
return SHA256.HashData(ms.ToArray()).AsSpan(0, 16).ToArray();
|
||||
}
|
||||
|
||||
// ── Loading ──────────────────────────────────────────────────────────────────
|
||||
|
||||
public static NavGraph Load(string path)
|
||||
{
|
||||
using var f = File.OpenRead(path);
|
||||
return Load(f);
|
||||
}
|
||||
|
||||
public static NavGraph Load(Stream input)
|
||||
{
|
||||
using var gz = new GZipStream(input, CompressionMode.Decompress, leaveOpen: true);
|
||||
using var r = new BinaryReader(gz, Encoding.UTF8, leaveOpen: true);
|
||||
if (r.ReadUInt32() != Magic) throw new InvalidDataException("not a RynthNav graph");
|
||||
int version = r.ReadInt32();
|
||||
if (version != Version) throw new InvalidDataException($"graph version {version}, expected {Version}");
|
||||
var g = new NavGraph { SetId = r.ReadBytes(16) };
|
||||
int tiles = r.ReadInt32();
|
||||
if (tiles < 0 || tiles > 65536) throw new InvalidDataException("bad tile count");
|
||||
var list = new List<TileInfo>(tiles);
|
||||
for (int i = 0; i < tiles; i++)
|
||||
{
|
||||
var t = new TileInfo(r.ReadUInt16(), r.ReadInt32(), r.ReadInt32(), r.ReadInt32(), r.ReadInt32(), r.ReadInt32());
|
||||
g._tiles[t.Lb] = t;
|
||||
list.Add(t);
|
||||
}
|
||||
g.RegionCount = r.ReadInt32();
|
||||
if (g.RegionCount < 0 || g.RegionCount > 50_000_000) throw new InvalidDataException("bad region count");
|
||||
g._regionLb = new ushort[g.RegionCount];
|
||||
foreach (TileInfo t in list)
|
||||
{
|
||||
if (t.RegionBase < 0 || t.RegionCount < 0 || (long)t.RegionBase + t.RegionCount > g.RegionCount) throw new InvalidDataException("bad tile region range");
|
||||
for (int k = 0; k < t.RegionCount; k++) g._regionLb[t.RegionBase + k] = t.Lb;
|
||||
}
|
||||
int portals = r.ReadInt32();
|
||||
if (portals < 0 || portals > 50_000_000) throw new InvalidDataException("bad portal count");
|
||||
g._px = new float[portals]; g._py = new float[portals]; g._pz = new float[portals];
|
||||
g._pa = new int[portals]; g._pb = new int[portals];
|
||||
for (int i = 0; i < portals; i++)
|
||||
{
|
||||
g._px[i] = r.ReadSingle(); g._py[i] = r.ReadSingle(); g._pz[i] = r.ReadSingle();
|
||||
g._pa[i] = r.ReadInt32(); g._pb[i] = r.ReadInt32();
|
||||
if ((uint)g._pa[i] >= (uint)g.RegionCount || (uint)g._pb[i] >= (uint)g.RegionCount) throw new InvalidDataException("portal region out of range");
|
||||
}
|
||||
g._regionPortals = new int[]?[g.RegionCount];
|
||||
g._regionCosts = new ushort[]?[g.RegionCount];
|
||||
int withCosts = r.ReadInt32();
|
||||
for (int i = 0; i < withCosts; i++)
|
||||
{
|
||||
int region = r.ReadInt32(), n = r.ReadInt32();
|
||||
if ((uint)region >= (uint)g.RegionCount || n < 0 || n > 100_000) throw new InvalidDataException("bad region record");
|
||||
var ps = new int[n];
|
||||
for (int k = 0; k < n; k++) { ps[k] = r.ReadInt32(); if ((uint)ps[k] >= (uint)portals) throw new InvalidDataException("bad portal id"); }
|
||||
var tri = new ushort[n * (n - 1) / 2];
|
||||
for (int k = 0; k < tri.Length; k++) tri[k] = r.ReadUInt16();
|
||||
g._regionPortals[region] = ps;
|
||||
g._regionCosts[region] = tri;
|
||||
}
|
||||
if (!SetIdOf(list).AsSpan().SequenceEqual(g.SetId)) throw new InvalidDataException("graph set id doesn't match its own tile list");
|
||||
return g;
|
||||
}
|
||||
|
||||
// ── Routing ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Walking cost inside <paramref name="region"/> between its portals (local indices); +inf when unknown.</summary>
|
||||
private float Cost(int region, int i, int j)
|
||||
{
|
||||
if (i == j) return 0;
|
||||
if (i > j) (i, j) = (j, i);
|
||||
int n = _regionPortals[region]!.Length;
|
||||
int k = i * (2 * n - i - 1) / 2 + (j - i - 1);
|
||||
ushort c = _regionCosts[region]![k];
|
||||
return c == NoCost ? float.PositiveInfinity : c * CostUnit;
|
||||
}
|
||||
|
||||
private float Leg(Func<int, float>? leg, int p, float x, float z)
|
||||
{
|
||||
float c = leg?.Invoke(p) ?? float.NaN;
|
||||
return float.IsNaN(c) ? Dist(x, z, _px[p], _pz[p]) : c;
|
||||
}
|
||||
|
||||
private static float Dist(float ax, float az, float bx, float bz) => MathF.Sqrt((ax - bx) * (ax - bx) + (az - bz) * (az - bz));
|
||||
|
||||
/// <summary>
|
||||
/// A* from a point in <paramref name="startRegion"/> to a point in <paramref name="goalRegion"/>.
|
||||
/// Returns the portals to cross, in order (empty when both are the same region), or null when
|
||||
/// the graph has no route. Costs: walking distances inside regions; straight lines for the first
|
||||
/// and last legs (inside the start and goal regions) unless <paramref name="startLeg"/> /
|
||||
/// <paramref name="goalLeg"/> give the real walking distance from the start to a portal and from
|
||||
/// a portal to the goal (NaN = not known: the straight line is used).
|
||||
/// </summary>
|
||||
public List<int>? FindRoute(int startRegion, float sx, float sz, int goalRegion, float gx, float gz,
|
||||
out float cost, out int expanded, int maxExpand = 2_000_000,
|
||||
Func<int, float>? startLeg = null, Func<int, float>? goalLeg = null)
|
||||
{
|
||||
cost = 0; expanded = 0;
|
||||
if ((uint)startRegion >= (uint)RegionCount || (uint)goalRegion >= (uint)RegionCount) return null;
|
||||
if (startRegion == goalRegion) return new List<int>();
|
||||
int[]? startPortals = _regionPortals[startRegion];
|
||||
if (startPortals == null || _regionPortals[goalRegion] == null) return null;
|
||||
|
||||
// State s = portal*2 + side: crossed portal p into region (side 0 = A, 1 = B).
|
||||
var g = new Dictionary<int, float>();
|
||||
var from = new Dictionary<int, int>();
|
||||
var open = new PriorityQueue<int, float>();
|
||||
float best = float.PositiveInfinity; int bestLast = -1;
|
||||
|
||||
foreach (int p in startPortals)
|
||||
{
|
||||
int side = _pa[p] == startRegion ? 1 : 0; // crossing p from the start region lands on the other side
|
||||
int s = p * 2 + side;
|
||||
float c = Leg(startLeg, p, sx, sz);
|
||||
if (!float.IsFinite(c)) continue;
|
||||
if (!g.TryGetValue(s, out float old) || c < old) { g[s] = c; from[s] = -1; open.Enqueue(s, c + Dist(_px[p], _pz[p], gx, gz)); }
|
||||
}
|
||||
|
||||
while (open.TryDequeue(out int s, out float f))
|
||||
{
|
||||
if (f >= best) break;
|
||||
if (++expanded > maxExpand) break;
|
||||
float gs = g[s];
|
||||
int p = s >> 1, side = s & 1;
|
||||
int region = side == 0 ? _pa[p] : _pb[p];
|
||||
if (f > gs + Dist(_px[p], _pz[p], gx, gz) + 0.01f) continue; // stale: a cheaper way here was queued later
|
||||
if (region == goalRegion)
|
||||
{
|
||||
float total = gs + Leg(goalLeg, p, gx, gz);
|
||||
if (total < best) { best = total; bestLast = s; }
|
||||
continue;
|
||||
}
|
||||
int[]? ps = _regionPortals[region];
|
||||
if (ps == null) continue;
|
||||
int li = Array.IndexOf(ps, p);
|
||||
if (li < 0) continue;
|
||||
for (int j = 0; j < ps.Length; j++)
|
||||
{
|
||||
if (j == li) continue;
|
||||
float c = Cost(region, li, j);
|
||||
if (!float.IsFinite(c)) continue;
|
||||
int q = ps[j];
|
||||
int qside = _pa[q] == region ? 1 : 0;
|
||||
int t = q * 2 + qside;
|
||||
float ng = gs + c;
|
||||
if (g.TryGetValue(t, out float og) && og <= ng) continue;
|
||||
g[t] = ng; from[t] = s;
|
||||
open.Enqueue(t, ng + Dist(_px[q], _pz[q], gx, gz));
|
||||
}
|
||||
}
|
||||
if (bestLast < 0) return null;
|
||||
cost = best;
|
||||
var route = new List<int>();
|
||||
for (int s = bestLast; s >= 0; s = from[s]) route.Add(s >> 1);
|
||||
route.Reverse();
|
||||
return route;
|
||||
}
|
||||
|
||||
// ── Landmasses ───────────────────────────────────────────────────────────────
|
||||
|
||||
private int[]? _component; // per region: its landmass (connected through portals)
|
||||
private int[]? _componentSize; // regions per landmass
|
||||
private Dictionary<ushort, int[]>? _landblockComponents;
|
||||
|
||||
/// <summary>
|
||||
/// Groups the regions into landmasses: regions joined by portals, directly or through others.
|
||||
/// Two places on different landmasses can't be walked between (water, cliffs). Built once (the
|
||||
/// plugin calls it on its loading worker); after that the graph is read-only again.
|
||||
/// </summary>
|
||||
public void BuildComponents()
|
||||
{
|
||||
if (_component != null) return;
|
||||
int n = RegionCount;
|
||||
var parent = new int[n];
|
||||
for (int i = 0; i < n; i++) parent[i] = i;
|
||||
int Find(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
|
||||
for (int p = 0; p < _pa.Length; p++)
|
||||
{
|
||||
int a = Find(_pa[p]), b = Find(_pb[p]);
|
||||
if (a != b) parent[a] = b;
|
||||
}
|
||||
var comp = new int[n];
|
||||
var size = new int[n];
|
||||
for (int i = 0; i < n; i++) { comp[i] = Find(i); size[comp[i]]++; }
|
||||
var byLb = new Dictionary<ushort, int[]>(_tiles.Count);
|
||||
var tmp = new List<int>();
|
||||
foreach (var (lb, t) in _tiles)
|
||||
{
|
||||
tmp.Clear();
|
||||
for (int k = 0; k < t.RegionCount; k++) { int c = comp[t.RegionBase + k]; if (!tmp.Contains(c)) tmp.Add(c); }
|
||||
byLb[lb] = tmp.ToArray();
|
||||
}
|
||||
_componentSize = size;
|
||||
_landblockComponents = byLb;
|
||||
_component = comp;
|
||||
}
|
||||
|
||||
/// <summary>A region's landmass (-1 before BuildComponents, or a bad region).</summary>
|
||||
public int Component(int region) => _component != null && (uint)region < (uint)_component.Length ? _component[region] : -1;
|
||||
|
||||
/// <summary>How many regions a landmass has.</summary>
|
||||
public int ComponentSize(int component) => _componentSize != null && (uint)component < (uint)_componentSize.Length ? _componentSize[component] : 0;
|
||||
|
||||
/// <summary>The landmasses with ground in landblock <paramref name="lb"/> (empty: no tile, or not built yet).</summary>
|
||||
public int[] LandblockComponents(uint lb) =>
|
||||
_landblockComponents != null && _landblockComponents.TryGetValue((ushort)lb, out int[]? c) ? c : Array.Empty<int>();
|
||||
|
||||
/// <summary>
|
||||
/// Can you walk from landblock <paramref name="a"/> to landblock <paramref name="b"/>? True when
|
||||
/// they share a landmass, false when they share none, null when either has no tile (unknown).
|
||||
/// Landmasses of fewer than <paramref name="minRegions"/> regions (a roof, a ledge, a rock) only
|
||||
/// count when a landblock has nothing bigger, so standing on a roof doesn't cut you off.
|
||||
/// </summary>
|
||||
public bool? SameLand(uint a, uint b, int minRegions = 8)
|
||||
{
|
||||
int[] ca = Big(LandblockComponents(a), minRegions), cb = Big(LandblockComponents(b), minRegions);
|
||||
if (ca.Length == 0 || cb.Length == 0) return null;
|
||||
foreach (int x in ca) if (Array.IndexOf(cb, x) >= 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private int[] Big(int[] comps, int minRegions)
|
||||
{
|
||||
if (comps.Length <= 1) return comps;
|
||||
int big = 0;
|
||||
foreach (int c in comps) if (ComponentSize(c) >= minRegions) big++;
|
||||
if (big == 0 || big == comps.Length) return comps;
|
||||
var r = new int[big];
|
||||
int i = 0;
|
||||
foreach (int c in comps) if (ComponentSize(c) >= minRegions) r[i++] = c;
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>The landblock under a world point (east, north), or uint.MaxValue off the map.</summary>
|
||||
public static uint LandblockAt(double ew, double ns)
|
||||
{
|
||||
int x = (int)Math.Floor(ew / 192.0), y = (int)Math.Floor(ns / 192.0);
|
||||
return x is >= 0 and <= 255 && y is >= 0 and <= 255 ? (uint)((x << 8) | y) : uint.MaxValue;
|
||||
}
|
||||
|
||||
/// <summary>The region a route's portal leads into (crossing it in route order from <paramref name="previousRegion"/>).</summary>
|
||||
public int Across(int portal, int previousRegion) => _pa[portal] == previousRegion ? _pb[portal] : _pa[portal];
|
||||
}
|
||||
61
Plugins/RynthCore.Plugin.RynthNav/NavRegions.cs
Normal file
61
Plugins/RynthCore.Plugin.RynthNav/NavRegions.cs
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
using DotRecast.Detour;
|
||||
|
||||
namespace RynthNav.Routing;
|
||||
|
||||
/// <summary>
|
||||
/// The connected walkable regions of one navmesh tile: polygons joined by the tile's own
|
||||
/// (internal) polygon links. Two islands in the same landblock (a roof, a ledge, the far
|
||||
/// bank of a river) are different regions.
|
||||
///
|
||||
/// The numbering is deterministic (a region's id is the order of its lowest-numbered
|
||||
/// polygon), so the offline graph tool (RynthNav.Baker --graph) and the plugin, which
|
||||
/// computes it again for the tiles it loads, always agree.
|
||||
/// </summary>
|
||||
internal static class NavRegions
|
||||
{
|
||||
/// <summary>Region id per polygon (0..count-1), from the tile's internal links only.</summary>
|
||||
public static int[] Build(DtMeshData md, out int count)
|
||||
{
|
||||
int n = md.header.polyCount;
|
||||
var parent = new int[n];
|
||||
for (int i = 0; i < n; i++) parent[i] = i;
|
||||
|
||||
int Find(int a)
|
||||
{
|
||||
while (parent[a] != a) { parent[a] = parent[parent[a]]; a = parent[a]; }
|
||||
return a;
|
||||
}
|
||||
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
DtPoly p = md.polys[i];
|
||||
if (p.GetPolyType() != DtPolyTypes.DT_POLYTYPE_GROUND) continue;
|
||||
for (int j = 0; j < p.vertCount; j++)
|
||||
{
|
||||
int nei = p.neis[j];
|
||||
if (nei == 0 || (nei & DtDetour.DT_EXT_LINK) != 0) continue; // a wall, or another tile
|
||||
int k = nei - 1;
|
||||
if (k < 0 || k >= n) continue;
|
||||
int a = Find(i), b = Find(k);
|
||||
if (a != b) { if (a < b) parent[b] = a; else parent[a] = b; }
|
||||
}
|
||||
}
|
||||
|
||||
// Number the roots in polygon order.
|
||||
var region = new int[n];
|
||||
var id = new int[n];
|
||||
for (int i = 0; i < n; i++) id[i] = -1;
|
||||
count = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int r = Find(i);
|
||||
if (id[r] < 0) id[r] = count++;
|
||||
region[i] = id[r];
|
||||
}
|
||||
return region;
|
||||
}
|
||||
|
||||
/// <summary>What the graph file records to recognise a tile: its polygon, vertex and detail-triangle counts.</summary>
|
||||
public static (int Polys, int Verts, int DetailTris) Fingerprint(DtMeshData md)
|
||||
=> (md.header.polyCount, md.header.vertCount, md.header.detailTriCount);
|
||||
}
|
||||
56
Plugins/RynthCore.Plugin.RynthNav/PathInterface.cs
Normal file
56
Plugins/RynthCore.Plugin.RynthNav/PathInterface.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
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.Path" interface (Shared/RynthNavPathApi.cs): the
|
||||
/// table RynthPluginQueryInterface hands out. The functions run on the plugin pump
|
||||
/// thread (the caller's OnTick) and act on the current plugin instance, so the table
|
||||
/// survives a re-Init. <see cref="Release"/> frees it at RynthPluginShutdown.
|
||||
/// </summary>
|
||||
internal static unsafe class PathInterface
|
||||
{
|
||||
private static RynthNavPathApiV1* _table;
|
||||
|
||||
public static IntPtr Query(string iface, uint version)
|
||||
{
|
||||
if (iface != RynthNavPathApiV1.InterfaceName || version != RynthNavPathApiV1.InterfaceVersion) return IntPtr.Zero;
|
||||
if (_table == null)
|
||||
{
|
||||
var t = (RynthNavPathApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthNavPathApiV1));
|
||||
t->Version = RynthNavPathApiV1.InterfaceVersion;
|
||||
t->StructSize = (uint)sizeof(RynthNavPathApiV1);
|
||||
t->FindPath = &FindPath;
|
||||
_table = t;
|
||||
}
|
||||
return (IntPtr)_table;
|
||||
}
|
||||
|
||||
/// <summary>Frees the table (plugin shutdown). Callers re-resolve on every use.</summary>
|
||||
public static void Release()
|
||||
{
|
||||
var t = _table;
|
||||
_table = null;
|
||||
if (t != null) NativeMemory.Free(t);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int FindPath(double sx, double sy, double sz, double gx, double gy, double gz,
|
||||
double* points, int maxPoints, int* count)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (count != null) *count = 0;
|
||||
var p = PluginExports.Runtime.Plugin;
|
||||
if (p == null) return RynthNavPathApiV1.ResultNoMesh;
|
||||
return p.InterfaceFindPath(sx, sy, sz, gx, gy, gz, points, maxPoints, count);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return RynthNavPathApiV1.ResultNoMesh;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -12,13 +12,33 @@ namespace RynthCore.Plugin.RynthNav;
|
|||
// managed RynthNavPlugin instance.
|
||||
public static unsafe class PluginExports
|
||||
{
|
||||
private static readonly RynthPluginRuntime<RynthNavPlugin> Runtime = new();
|
||||
internal static readonly RynthPluginRuntime<RynthNavPlugin> Runtime = new();
|
||||
|
||||
// Typed interfaces for other plugins (host GetPluginInterface, API v68): "RynthNav.Path" v1
|
||||
// (RynthAi plans stuck-recovery detours with it). Fixed signature: void* (const char* iface, uint version).
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version)
|
||||
{
|
||||
try
|
||||
{
|
||||
string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? "";
|
||||
return PathInterface.Query(iface, version);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void Shutdown() => Runtime.Shutdown();
|
||||
public static void Shutdown()
|
||||
{
|
||||
Runtime.Shutdown();
|
||||
PathInterface.Release();
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetName() => RynthNavPlugin.NamePointer;
|
||||
|
|
@ -38,6 +58,41 @@ public static unsafe class PluginExports
|
|||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
|
||||
|
||||
// The server's lines about lifestones, ties and recalls teach RynthNav where recalls land.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
|
||||
|
||||
// Commands from other plugins (host SendPluginCommand): action "rnav", value a /rnav
|
||||
// command without the "/rnav" ("arrow 42.1N, 33.6E", "go Holtburg"). Copied and queued.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi)
|
||||
{
|
||||
try
|
||||
{
|
||||
string action = actionAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(actionAnsi) ?? "" : "";
|
||||
string value = valueAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(valueAnsi) ?? "" : "";
|
||||
if (action.Equals("rnav", StringComparison.OrdinalIgnoreCase)) Runtime.Plugin?.EnqueueCommand(value);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// A /rnav command from the engine's RynthNav panel or the chat window's coordinate menu
|
||||
// (UTF-8, without "/rnav"): "arrow 42.1N, 33.6E Holtburg", "go Holtburg", "fav ...".
|
||||
// Queued; runs on the tick.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthNavCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void Command(IntPtr utf8)
|
||||
{
|
||||
try { if (utf8 != IntPtr.Zero) Runtime.Plugin?.EnqueueCommand(Marshal.PtrToStringUTF8(utf8)); } catch { }
|
||||
}
|
||||
|
||||
// How many times a command has asked to show the arrow: the engine polls this one int
|
||||
// (twice a second, any thread) and opens the arrow overlay when it moves.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthNavArrowSeq", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static int ArrowSeq()
|
||||
{
|
||||
try { return Runtime.Plugin?.ArrowSeq ?? 0; } catch { return 0; }
|
||||
}
|
||||
|
||||
// ── RynthNav panel bridge (engine RynthNavPanel reads/drives via these) ───────
|
||||
// GetStatusJson uses the alloc-new → swap → free-old pointer pattern (matches
|
||||
// RynthVision) so the UI-thread caller never races a free.
|
||||
|
|
@ -58,6 +113,28 @@ public static unsafe class PluginExports
|
|||
catch { return IntPtr.Zero; }
|
||||
}
|
||||
|
||||
private static IntPtr _statusUtf8Ptr = IntPtr.Zero;
|
||||
|
||||
// The same JSON as RynthNavGetStatusJson, UTF-8 (0.6.1+): place and recall names keep
|
||||
// characters the ANSI code page can't hold ("→" in a portal recall's label). The engine
|
||||
// tries this first and falls back to the ANSI one for older RynthNavs. Its own buffer,
|
||||
// same alloc-new → swap → free-old pattern, so either getter can be called alone.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthNavGetStatusJsonUtf8", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetStatusJsonUtf8()
|
||||
{
|
||||
try
|
||||
{
|
||||
RynthNavPlugin? plugin = Runtime.Plugin;
|
||||
byte[] bytes = plugin != null ? plugin.BuildStatusUtf8() : new byte[] { (byte)'{', (byte)'}', 0 };
|
||||
IntPtr nw = Marshal.AllocHGlobal(bytes.Length);
|
||||
Marshal.Copy(bytes, 0, nw, bytes.Length);
|
||||
IntPtr old = Interlocked.Exchange(ref _statusUtf8Ptr, nw);
|
||||
if (old != IntPtr.Zero) Marshal.FreeHGlobal(old);
|
||||
return nw;
|
||||
}
|
||||
catch { return IntPtr.Zero; }
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthNavLoadTile", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void LoadTile() { try { Runtime.Plugin?.DoLoadTile(); } catch { } }
|
||||
|
||||
|
|
|
|||
267
Plugins/RynthCore.Plugin.RynthNav/PortalAvoid.cs
Normal file
267
Plugins/RynthCore.Plugin.RynthNav/PortalAvoid.cs
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthNav.Routing;
|
||||
|
||||
/// <summary>
|
||||
/// Portals a walk must not touch: walking into one teleports you (17:53 on 10-01: a goto from
|
||||
/// Holtburg ran straight into the Aerlinthe island portal). Every portal near the player that isn't
|
||||
/// the current step's own target is a circle to keep out of. The detailed planner leaves out
|
||||
/// navmesh polygons that reach into a circle (AvoidFilter), and the steering check turns the walker
|
||||
/// round a circle in its way, whatever it is heading for (a path corner, the coarse route's aim, a
|
||||
/// blind push). World units (east, north); headings in degrees, 0 = north, 90 = east.
|
||||
/// Host-free and Detour-free: the route tests drive it.
|
||||
/// </summary>
|
||||
internal sealed class PortalAvoid
|
||||
{
|
||||
/// <summary>Around a portal the client knows (exact position): its reach (~1.4 m) + the body (~0.5 m) + room.</summary>
|
||||
public static double LiveRadius { get; set; } = 4.0; // the "portals" avoidance setting (rynthnav.json avoidPortalMetres)
|
||||
/// <summary>Around a portal from the Atlas (positions to 0.01 degree, ±1.2 m each way): more room.</summary>
|
||||
public static double MapRadius => LiveRadius + 1.0;
|
||||
/// <summary>Steering keeps this much past a circle's edge.</summary>
|
||||
public const double SteerMargin = 0.5;
|
||||
|
||||
public readonly struct Spot
|
||||
{
|
||||
public readonly double X, Y, R;
|
||||
public readonly string Name;
|
||||
public Spot(double x, double y, double r, string name) { X = x; Y = y; R = r; Name = name; }
|
||||
}
|
||||
|
||||
private readonly List<Spot> _spots = new();
|
||||
public IReadOnlyList<Spot> Spots => _spots;
|
||||
public int Count => _spots.Count;
|
||||
public int Version { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the set: <paramref name="live"/> first (exact), then <paramref name="map"/> points that
|
||||
/// no live portal stands within 5 m of. Spots within <paramref name="exceptRadius"/> of
|
||||
/// (<paramref name="exceptX"/>, <paramref name="exceptY"/>) are the step's own target: left out.
|
||||
/// </summary>
|
||||
public void Set(IEnumerable<Spot> live, IEnumerable<Spot> map, double exceptX = double.NaN, double exceptY = double.NaN, double exceptRadius = 0)
|
||||
{
|
||||
_spots.Clear();
|
||||
foreach (Spot s in live) if (!Excepted(s, exceptX, exceptY, exceptRadius)) _spots.Add(s);
|
||||
int liveCount = _spots.Count;
|
||||
foreach (Spot s in map)
|
||||
{
|
||||
if (Excepted(s, exceptX, exceptY, exceptRadius)) continue;
|
||||
bool dup = false;
|
||||
for (int i = 0; i < liveCount && !dup; i++) dup = Dist(_spots[i].X, _spots[i].Y, s.X, s.Y) < 5.0;
|
||||
if (!dup) _spots.Add(s);
|
||||
}
|
||||
Version++;
|
||||
}
|
||||
|
||||
public void Clear() { if (_spots.Count > 0) { _spots.Clear(); Version++; } }
|
||||
|
||||
private static bool Excepted(Spot s, double x, double y, double r) =>
|
||||
!double.IsNaN(x) && Dist(s.X, s.Y, x, y) <= r;
|
||||
|
||||
private static double Dist(double ax, double ay, double bx, double by) => Math.Sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
|
||||
|
||||
/// <summary>The spot whose circle (x, y) is inside, or -1.</summary>
|
||||
public int Inside(double x, double y, double extra = 0)
|
||||
{
|
||||
for (int i = 0; i < _spots.Count; i++)
|
||||
if (Dist(_spots[i].X, _spots[i].Y, x, y) < _spots[i].R + extra) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when a convex polygon (2D vertices, east/north) reaches into any circle: a vertex inside,
|
||||
/// the centre inside the polygon, or an edge passing closer than the radius.
|
||||
/// </summary>
|
||||
public bool Touches(ReadOnlySpan<double> xs, ReadOnlySpan<double> ys)
|
||||
{
|
||||
if (_spots.Count == 0 || xs.Length < 3) return false;
|
||||
double minX = double.MaxValue, maxX = double.MinValue, minY = double.MaxValue, maxY = double.MinValue;
|
||||
for (int i = 0; i < xs.Length; i++)
|
||||
{
|
||||
minX = Math.Min(minX, xs[i]); maxX = Math.Max(maxX, xs[i]);
|
||||
minY = Math.Min(minY, ys[i]); maxY = Math.Max(maxY, ys[i]);
|
||||
}
|
||||
foreach (Spot s in _spots)
|
||||
{
|
||||
if (s.X < minX - s.R || s.X > maxX + s.R || s.Y < minY - s.R || s.Y > maxY + s.R) continue;
|
||||
if (PointInPolygon(s.X, s.Y, xs, ys)) return true;
|
||||
for (int i = 0, j = xs.Length - 1; i < xs.Length; j = i++)
|
||||
if (SegmentDistance(s.X, s.Y, xs[j], ys[j], xs[i], ys[i]) < s.R) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool PointInPolygon(double x, double y, ReadOnlySpan<double> xs, ReadOnlySpan<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;
|
||||
}
|
||||
|
||||
public 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);
|
||||
return Dist(x, y, ax + dx * t, ay + dy * t);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The heading to take instead of <paramref name="heading"/> so the next
|
||||
/// <paramref name="lookahead"/> units don't enter a circle: unchanged when the way is clear;
|
||||
/// the tangent past the nearest circle in the way, on the side nearer the wanted heading; or,
|
||||
/// already inside a circle, straight out of it (leaning toward the wanted heading).
|
||||
/// <paramref name="spot"/> is the circle steered round (-1 = none).
|
||||
/// </summary>
|
||||
public double Steer(double x, double y, double heading, double lookahead, out int spot)
|
||||
{
|
||||
spot = -1;
|
||||
if (_spots.Count == 0) return heading;
|
||||
double h = heading * Math.PI / 180.0, ux = Math.Sin(h), uy = Math.Cos(h);
|
||||
|
||||
// Inside one or more circles (a row of portals overlaps into one wall: Holtburg's four hub
|
||||
// portals stand ~5 m apart, and the lifestone drops you beside them): out along the summed
|
||||
// outward directions of every circle you're in, so the way out doesn't flip from one
|
||||
// circle to the next each tick (10-01 19:46, "a full on spazz attack").
|
||||
double sx = 0, sy = 0;
|
||||
for (int i = 0; i < _spots.Count; i++)
|
||||
{
|
||||
Spot s = _spots[i];
|
||||
double ox = x - s.X, oy = y - s.Y, ol = Math.Sqrt(ox * ox + oy * oy);
|
||||
if (ol >= s.R) continue;
|
||||
if (spot < 0) spot = i;
|
||||
if (ol < 1e-6) { ox = -ux; oy = -uy; ol = 1; }
|
||||
double depth = (s.R - ol) / s.R + 0.1;
|
||||
sx += ox / ol * depth; sy += oy / ol * depth;
|
||||
}
|
||||
if (spot >= 0)
|
||||
{
|
||||
double sl = Math.Sqrt(sx * sx + sy * sy);
|
||||
if (sl < 1e-6) { sx = -ux; sy = -uy; sl = 1; }
|
||||
sx /= sl; sy /= sl;
|
||||
// Out, plus whatever of the wanted heading doesn't lead back in.
|
||||
double along = ux * sx + uy * sy;
|
||||
double tx = ux - along * sx, ty = uy - along * sy;
|
||||
return Norm(Math.Atan2(sx + 0.5 * tx, sy + 0.5 * ty) * 180.0 / Math.PI);
|
||||
}
|
||||
|
||||
spot = Blocking(x, y, heading, lookahead);
|
||||
if (spot < 0)
|
||||
{
|
||||
if (++_clearCalls > 15) _side = 0; // clear for half a second: free to pick a side again
|
||||
return heading;
|
||||
}
|
||||
_clearCalls = 0;
|
||||
|
||||
// Pick a side once and keep it while something is in the way, then turn further that way
|
||||
// until the new heading clears every circle (overlapping circles = one obstacle).
|
||||
if (_side == 0)
|
||||
{
|
||||
double l0 = Tangent(x, y, _spots[spot], -1), r0 = Tangent(x, y, _spots[spot], +1);
|
||||
_side = AngleDiff(l0, heading) <= AngleDiff(r0, heading) ? -1 : +1;
|
||||
}
|
||||
double h2 = heading;
|
||||
for (int k = 0; k < 8; k++)
|
||||
{
|
||||
int b = Blocking(x, y, h2, lookahead);
|
||||
if (b < 0) break;
|
||||
spot = b;
|
||||
double t = Tangent(x, y, _spots[b], _side);
|
||||
// Never turn back the other way: only take the tangent if it turns further toward _side.
|
||||
double turn = Norm(t - h2); if (turn > 180) turn -= 360;
|
||||
h2 = (_side < 0 ? turn < 0 : turn > 0) ? t : Norm(h2 + _side * 10.0);
|
||||
}
|
||||
return h2;
|
||||
}
|
||||
|
||||
private int _side; // -1 left, +1 right, 0 not chosen: the side kept while something is in the way
|
||||
private int _clearCalls;
|
||||
|
||||
/// <summary>The nearest circle the stretch from (x, y) along <paramref name="heading"/> passes through, or -1.</summary>
|
||||
private int Blocking(double x, double y, double heading, double lookahead)
|
||||
{
|
||||
double h = heading * Math.PI / 180.0, ux = Math.Sin(h), uy = Math.Cos(h);
|
||||
int spot = -1;
|
||||
double best = double.MaxValue;
|
||||
for (int i = 0; i < _spots.Count; i++)
|
||||
{
|
||||
Spot s = _spots[i];
|
||||
double dx = s.X - x, dy = s.Y - y;
|
||||
double along = dx * ux + dy * uy;
|
||||
if (along <= 0 || along > lookahead + s.R) continue;
|
||||
double perp = Math.Abs(dx * uy - dy * ux);
|
||||
if (perp >= s.R + SteerMargin * 0.5) continue;
|
||||
if (along < best) { best = along; spot = i; }
|
||||
}
|
||||
return spot;
|
||||
}
|
||||
|
||||
/// <summary>The heading that just grazes circle <paramref name="c"/> on <paramref name="side"/> (-1 left, +1 right).</summary>
|
||||
private static double Tangent(double x, double y, Spot c, int side)
|
||||
{
|
||||
double cx = c.X - x, cy = c.Y - y, d = Math.Sqrt(cx * cx + cy * cy);
|
||||
double toCentre = Math.Atan2(cx, cy) * 180.0 / Math.PI;
|
||||
double off = Math.Asin(Math.Min(1.0, (c.R + SteerMargin) / Math.Max(d, 1e-6))) * 180.0 / Math.PI;
|
||||
return Norm(toCentre + side * off);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A path (east, north corners) bent round the circles it passes through: a corner is added
|
||||
/// beside each circle (on the side the path passes, or the other side), until no segment enters
|
||||
/// a circle. A corner is only taken when it is <paramref name="onMesh"/> AND both new legs (to
|
||||
/// it and from it) are <paramref name="legOnMesh"/>; when neither side qualifies the path is
|
||||
/// left as it was there (the steering check keeps the walker out of the circle). Before
|
||||
/// 2026-10-02 a corner only needed navmesh within 1.5 m, so a bend could put the walker in a
|
||||
/// tree's no-go ring beside a portal (C9A8, 10-01 21:03). A circle the path starts or ends
|
||||
/// inside is left alone (the steering gets out of the first; the second is the goal's).
|
||||
/// Big navmesh polygons on open ground let a straight path cut across a portal even when the
|
||||
/// filter leaves out every polygon it can; this bends it.
|
||||
/// </summary>
|
||||
public List<(double X, double Y)> Bend(IReadOnlyList<(double X, double Y)> path, Func<double, double, bool>? onMesh = null,
|
||||
int maxInserts = 12, Func<double, double, double, double, bool>? legOnMesh = null)
|
||||
{
|
||||
var pts = new List<(double X, double Y)>(path);
|
||||
if (_spots.Count == 0 || pts.Count < 2) return pts;
|
||||
// Circles already found impossible to bend round on one leg: don't try them again there.
|
||||
var tried = new HashSet<(int, int)>();
|
||||
for (int pass = 0; pass < maxInserts; pass++)
|
||||
{
|
||||
bool changed = false;
|
||||
for (int i = 1; i < pts.Count && !changed; i++)
|
||||
{
|
||||
var a = pts[i - 1]; var b = pts[i];
|
||||
for (int k = 0; k < _spots.Count; k++)
|
||||
{
|
||||
Spot s = _spots[k];
|
||||
if (Dist(a.X, a.Y, s.X, s.Y) < s.R || Dist(b.X, b.Y, s.X, s.Y) < s.R) continue;
|
||||
double dx = b.X - a.X, dy = b.Y - a.Y, l2 = dx * dx + dy * dy;
|
||||
double t = l2 < 1e-12 ? 0 : Math.Clamp(((s.X - a.X) * dx + (s.Y - a.Y) * dy) / l2, 0, 1);
|
||||
double px = a.X + dx * t, py = a.Y + dy * t;
|
||||
if (Dist(px, py, s.X, s.Y) >= s.R) continue;
|
||||
if (tried.Contains((HashCorner(a, b), k))) continue;
|
||||
double nx = px - s.X, ny = py - s.Y, nl = Math.Sqrt(nx * nx + ny * ny);
|
||||
if (nl < 1e-6) { double l = Math.Sqrt(l2); nx = -dy / l; ny = dx / l; nl = 1; }
|
||||
nx /= nl; ny /= nl;
|
||||
double off = s.R + SteerMargin + 0.5;
|
||||
(double X, double Y) c1 = (s.X + nx * off, s.Y + ny * off), c2 = (s.X - nx * off, s.Y - ny * off);
|
||||
bool Good((double X, double Y) c) =>
|
||||
(onMesh == null || onMesh(c.X, c.Y)) &&
|
||||
(legOnMesh == null || (legOnMesh(a.X, a.Y, c.X, c.Y) && legOnMesh(c.X, c.Y, b.X, b.Y)));
|
||||
(double X, double Y)? pick = Good(c1) ? c1 : Good(c2) ? c2 : null;
|
||||
if (pick == null) { tried.Add((HashCorner(a, b), k)); continue; } // keep this leg as it is
|
||||
pts.Insert(i, pick.Value);
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!changed) break;
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
private static int HashCorner((double X, double Y) a, (double X, double Y) b) =>
|
||||
HashCode.Combine(Math.Round(a.X, 2), Math.Round(a.Y, 2), Math.Round(b.X, 2), Math.Round(b.Y, 2));
|
||||
|
||||
private static double Norm(double deg) { deg %= 360.0; return deg < 0 ? deg + 360.0 : deg; }
|
||||
private static double AngleDiff(double a, double b) { double d = Math.Abs(Norm(a) - Norm(b)); return d > 180 ? 360 - d : d; }
|
||||
}
|
||||
202
Plugins/RynthCore.Plugin.RynthNav/RecallMemory.cs
Normal file
202
Plugins/RynthCore.Plugin.RynthNav/RecallMemory.cs
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Where a character's personal recalls land. The client is never told (the server keeps
|
||||
// a character's lifestone, ties, last portal and house), so RynthNav learns them from what
|
||||
// it sees: the server's messages ("You have attuned your spirit to this Lifestone.", "X is
|
||||
// recalling home.") and the teleport that follows. Saved per character in
|
||||
// NavData\recalls.txt. No host calls: the offline tests compile this file.
|
||||
// (GoArrow kept the same kind of per-character recall list; Digero 2006, Virindi 2011, MIT.)
|
||||
|
||||
internal enum RecallSlot
|
||||
{
|
||||
/// <summary>Where @lifestone (the recall everyone has) lands: the last lifestone you used.</summary>
|
||||
Sanctuary,
|
||||
/// <summary>Where the Lifestone Recall spell lands: the lifestone you cast Lifestone Tie on.</summary>
|
||||
Lifestone,
|
||||
/// <summary>Where Portal Recall lands: the last portal you walked through.</summary>
|
||||
LastPortal,
|
||||
/// <summary>Primary Portal Tie Recall.</summary>
|
||||
Tie1,
|
||||
/// <summary>Secondary Portal Tie Recall.</summary>
|
||||
Tie2,
|
||||
/// <summary>House recall.</summary>
|
||||
House,
|
||||
/// <summary>Allegiance mansion (housing) recall.</summary>
|
||||
Mansion,
|
||||
/// <summary>Allegiance hometown recall.</summary>
|
||||
Hometown,
|
||||
}
|
||||
|
||||
internal sealed class RecallSpot
|
||||
{
|
||||
public bool OnMap;
|
||||
public double Ns, Ew;
|
||||
public string Label = "";
|
||||
/// <summary>The chat command that does this recall, when it's a command (@lifestone, @house recall).</summary>
|
||||
public string Command = "";
|
||||
}
|
||||
|
||||
/// <summary>What a chat line tells RynthNav about recalls.</summary>
|
||||
internal enum RecallEvent
|
||||
{
|
||||
None,
|
||||
/// <summary>"You have attuned your spirit to this Lifestone." (used a lifestone: @lifestone lands here).</summary>
|
||||
AttunedLifestone,
|
||||
/// <summary>"You have successfully linked with the life stone." (Lifestone Tie).</summary>
|
||||
LinkedLifestone,
|
||||
/// <summary>"You have successfully linked with the portal." (a Portal Tie; which one isn't said).</summary>
|
||||
LinkedPortal,
|
||||
/// <summary>"Name is recalling to the lifestone." (@lifestone under way).</summary>
|
||||
RecallingLifestone,
|
||||
/// <summary>"Name is recalling home."</summary>
|
||||
RecallingHome,
|
||||
/// <summary>"Name is recalling to the Allegiance housing."</summary>
|
||||
RecallingMansion,
|
||||
/// <summary>"Name is going to the Allegiance hometown."</summary>
|
||||
RecallingHometown,
|
||||
/// <summary>"Name is recalling to the marketplace." (lands in a dungeon: never used for routes).</summary>
|
||||
RecallingMarketplace,
|
||||
}
|
||||
|
||||
internal sealed class RecallMemory
|
||||
{
|
||||
private readonly Dictionary<string, Dictionary<RecallSlot, RecallSpot>> _byChar = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Bumped on every change (the plugin saves when it moves).</summary>
|
||||
public int Version { get; private set; }
|
||||
|
||||
public RecallSpot? Get(string charKey, RecallSlot slot) =>
|
||||
_byChar.TryGetValue(charKey, out var d) && d.TryGetValue(slot, out var s) ? s : null;
|
||||
|
||||
public void Set(string charKey, RecallSlot slot, RecallSpot spot)
|
||||
{
|
||||
if (!_byChar.TryGetValue(charKey, out var d)) _byChar[charKey] = d = new Dictionary<RecallSlot, RecallSpot>();
|
||||
d[slot] = spot;
|
||||
Version++;
|
||||
}
|
||||
|
||||
public void Clear(string charKey, RecallSlot slot)
|
||||
{
|
||||
if (_byChar.TryGetValue(charKey, out var d) && d.Remove(slot)) Version++;
|
||||
}
|
||||
|
||||
/// <summary>The command for a command recall, as the retail client's own help spells it.</summary>
|
||||
public static string DefaultCommand(RecallSlot slot) => slot switch
|
||||
{
|
||||
RecallSlot.Sanctuary => "@lifestone",
|
||||
RecallSlot.House => "@house recall",
|
||||
RecallSlot.Mansion => "@house mansion_recall",
|
||||
RecallSlot.Hometown => "@allegiance hometown",
|
||||
_ => "",
|
||||
};
|
||||
|
||||
/// <summary>The recall a "... is recalling ..." line announces, if any.</summary>
|
||||
public static bool SlotFor(RecallEvent e, out RecallSlot slot)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case RecallEvent.RecallingLifestone: slot = RecallSlot.Sanctuary; return true;
|
||||
case RecallEvent.RecallingHome: slot = RecallSlot.House; return true;
|
||||
case RecallEvent.RecallingMansion: slot = RecallSlot.Mansion; return true;
|
||||
case RecallEvent.RecallingHometown: slot = RecallSlot.Hometown; return true;
|
||||
default: slot = RecallSlot.Sanctuary; return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a chat line (the server's own wording, ACE's Player_Location / Lifestone /
|
||||
/// WorldObject_Magic). <paramref name="playerName"/> picks out your own "is recalling"
|
||||
/// lines from other players' nearby.
|
||||
/// </summary>
|
||||
public static RecallEvent Classify(string? text, string? playerName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return RecallEvent.None;
|
||||
string t = text.Trim();
|
||||
if (t.StartsWith("You have attuned your spirit to this Lifestone", StringComparison.OrdinalIgnoreCase))
|
||||
return RecallEvent.AttunedLifestone;
|
||||
if (t.StartsWith("You have successfully linked with the life stone", StringComparison.OrdinalIgnoreCase))
|
||||
return RecallEvent.LinkedLifestone;
|
||||
if (t.StartsWith("You have successfully linked with the portal", StringComparison.OrdinalIgnoreCase))
|
||||
return RecallEvent.LinkedPortal;
|
||||
if (string.IsNullOrEmpty(playerName) || !t.StartsWith(playerName + " ", StringComparison.Ordinal))
|
||||
return RecallEvent.None;
|
||||
string rest = t.Substring(playerName.Length + 1);
|
||||
if (rest.StartsWith("is recalling to the lifestone", StringComparison.OrdinalIgnoreCase)) return RecallEvent.RecallingLifestone;
|
||||
if (rest.StartsWith("is recalling home", StringComparison.OrdinalIgnoreCase)) return RecallEvent.RecallingHome;
|
||||
if (rest.StartsWith("is recalling to the Allegiance housing", StringComparison.OrdinalIgnoreCase)) return RecallEvent.RecallingMansion;
|
||||
if (rest.StartsWith("is going to the Allegiance hometown", StringComparison.OrdinalIgnoreCase)) return RecallEvent.RecallingHometown;
|
||||
if (rest.StartsWith("is recalling to the marketplace", StringComparison.OrdinalIgnoreCase)) return RecallEvent.RecallingMarketplace;
|
||||
return RecallEvent.None;
|
||||
}
|
||||
|
||||
// ── recalls.txt ──────────────────────────────────────────────────────────
|
||||
// # comment
|
||||
// <character>\t<slot>\t<ns or ->\t<ew or ->\t<label>\t<command>
|
||||
|
||||
public string Serialize()
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("# RynthNav: where each character's recalls land, learned in game. One line per recall:\r\n");
|
||||
sb.Append("# character<TAB>recall<TAB>NS<TAB>EW<TAB>label<TAB>command (- for a place off the map)\r\n");
|
||||
var chars = new List<string>(_byChar.Keys);
|
||||
chars.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (string c in chars)
|
||||
{
|
||||
var slots = new List<RecallSlot>(_byChar[c].Keys);
|
||||
slots.Sort();
|
||||
foreach (RecallSlot slot in slots)
|
||||
{
|
||||
RecallSpot s = _byChar[c][slot];
|
||||
sb.Append(Clean(c)).Append('\t').Append(SlotName(slot)).Append('\t')
|
||||
.Append(s.OnMap ? s.Ns.ToString("F2", ci) : "-").Append('\t')
|
||||
.Append(s.OnMap ? s.Ew.ToString("F2", ci) : "-").Append('\t')
|
||||
.Append(Clean(s.Label)).Append('\t').Append(Clean(s.Command)).Append("\r\n");
|
||||
}
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static RecallMemory Parse(string text)
|
||||
{
|
||||
var m = new RecallMemory();
|
||||
foreach (string raw in text.Split('\n'))
|
||||
{
|
||||
string line = raw.TrimEnd('\r');
|
||||
if (line.Length == 0 || line[0] == '#') continue;
|
||||
string[] f = line.Split('\t');
|
||||
if (f.Length < 4 || f[0].Length == 0) continue;
|
||||
if (!TrySlot(f[1], out RecallSlot slot)) continue;
|
||||
var s = new RecallSpot
|
||||
{
|
||||
Label = f.Length > 4 ? f[4] : "",
|
||||
Command = f.Length > 5 ? f[5] : "",
|
||||
};
|
||||
s.OnMap = double.TryParse(f[2], NumberStyles.Float, CultureInfo.InvariantCulture, out s.Ns)
|
||||
& double.TryParse(f[3], NumberStyles.Float, CultureInfo.InvariantCulture, out s.Ew);
|
||||
m.Set(f[0], slot, s);
|
||||
}
|
||||
m.Version = 0;
|
||||
return m;
|
||||
}
|
||||
|
||||
// Slot names by hand, not Enum.ToString / Enum.TryParse (NativeAOT plugin; no reflection).
|
||||
private static readonly string[] SlotNames = { "Sanctuary", "Lifestone", "LastPortal", "Tie1", "Tie2", "House", "Mansion", "Hometown" };
|
||||
|
||||
public static string SlotName(RecallSlot slot) => (int)slot >= 0 && (int)slot < SlotNames.Length ? SlotNames[(int)slot] : "?";
|
||||
|
||||
public static bool TrySlot(string name, out RecallSlot slot)
|
||||
{
|
||||
for (int i = 0; i < SlotNames.Length; i++)
|
||||
if (SlotNames[i].Equals(name.Trim(), StringComparison.OrdinalIgnoreCase)) { slot = (RecallSlot)i; return true; }
|
||||
slot = RecallSlot.Sanctuary;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string Clean(string s) => s.Replace('\t', ' ').Replace('\r', ' ').Replace('\n', ' ');
|
||||
}
|
||||
132
Plugins/RynthCore.Plugin.RynthNav/RecallPlanner.cs
Normal file
132
Plugins/RynthCore.Plugin.RynthNav/RecallPlanner.cs
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>One recall the route planner may use: a spell to cast, or a command to type.</summary>
|
||||
internal sealed class RecallOption
|
||||
{
|
||||
public string Name = "";
|
||||
/// <summary>The spell to cast (0 = a command).</summary>
|
||||
public int SpellId;
|
||||
/// <summary>The command to send (@lifestone, @house recall) when SpellId is 0.</summary>
|
||||
public string Command = "";
|
||||
public double Ns, Ew;
|
||||
public double CastSeconds;
|
||||
/// <summary>Learned in game (RecallMemory), not fixed by the world data.</summary>
|
||||
public bool Learned;
|
||||
|
||||
public RecallLink ToLink() => new(Ns, Ew, Name, PortalRoute.RecallCostUnits(CastSeconds));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which recalls this character can use, and where they land: the fixed recall spells
|
||||
/// from the Atlas (only the ones in the character's spellbook), plus the personal ones
|
||||
/// RynthNav has learned (RecallMemory). A recall whose landing isn't known, or is off the
|
||||
/// map (a dungeon), is left out with a note saying why. No host calls: the offline tests
|
||||
/// compile this file.
|
||||
/// </summary>
|
||||
internal static class RecallPlanner
|
||||
{
|
||||
public const int PrimaryPortalTieRecall = 48;
|
||||
public const int PrimaryPortalTie = 47;
|
||||
public const int LifestoneRecall = 1635;
|
||||
public const int LifestoneTie = 2644;
|
||||
public const int PortalRecall = 2645;
|
||||
public const int SecondaryPortalTie = 2646;
|
||||
public const int SecondaryPortalTieRecall = 2647;
|
||||
|
||||
/// <summary>A recall spell: the magic stance (and a wand) plus the cast. Estimated.</summary>
|
||||
public const double SpellCastSeconds = 5.0;
|
||||
/// <summary>@lifestone, @house recall and the like: a long recall animation. Estimated.</summary>
|
||||
public const double CommandRecallSeconds = 14.0;
|
||||
|
||||
/// <param name="known">The character's spellbook; null while it hasn't been read.</param>
|
||||
public static List<RecallOption> Build(Atlas atlas, ISet<int>? known, RecallMemory memory, string charKey, List<string>? notes)
|
||||
{
|
||||
var list = new List<RecallOption>();
|
||||
|
||||
// Fixed-destination recall spells (Aerlinthe Recall, Lyceum Recall, ...).
|
||||
if (known == null)
|
||||
{
|
||||
notes?.Add("Spellbook not read yet: recall spells left out.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var seen = new HashSet<int>();
|
||||
foreach (AtlasRecall r in atlas.Recalls)
|
||||
{
|
||||
if (!known.Contains(r.SpellId) || !seen.Add(r.SpellId)) continue;
|
||||
if (!r.OnMap)
|
||||
{
|
||||
notes?.Add(r.Name + " lands " + (r.In.Length > 0 ? "in " + r.In : "in a dungeon") + ": not used for routes.");
|
||||
continue;
|
||||
}
|
||||
list.Add(new RecallOption { Name = r.Name, SpellId = r.SpellId, Ns = r.Ns, Ew = r.Ew, CastSeconds = SpellCastSeconds });
|
||||
}
|
||||
}
|
||||
|
||||
// Personal recall spells: the landing is the character's own.
|
||||
if (known != null)
|
||||
{
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, LifestoneRecall, "Lifestone Recall", RecallSlot.Lifestone,
|
||||
"cast Lifestone Tie on a lifestone");
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, PortalRecall, "Portal Recall", RecallSlot.LastPortal,
|
||||
"walk through a portal");
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, PrimaryPortalTieRecall, "Primary Portal Tie Recall", RecallSlot.Tie1,
|
||||
"cast Primary Portal Tie on a portal");
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, SecondaryPortalTieRecall, "Secondary Portal Tie Recall", RecallSlot.Tie2,
|
||||
"cast Secondary Portal Tie on a portal");
|
||||
}
|
||||
|
||||
// Command recalls (no spell): @lifestone always; house, mansion and hometown
|
||||
// once the character has used them (only then is it known that they have one).
|
||||
AddLearnedCommand(list, notes, memory, charKey, RecallSlot.Sanctuary, "Lifestone (@lifestone)", alwaysAvailable: true,
|
||||
"use a lifestone");
|
||||
AddLearnedCommand(list, notes, memory, charKey, RecallSlot.House, "House recall", alwaysAvailable: false, "");
|
||||
AddLearnedCommand(list, notes, memory, charKey, RecallSlot.Mansion, "Allegiance mansion recall", alwaysAvailable: false, "");
|
||||
AddLearnedCommand(list, notes, memory, charKey, RecallSlot.Hometown, "Allegiance hometown recall", alwaysAvailable: false, "");
|
||||
return list;
|
||||
}
|
||||
|
||||
private static void AddLearnedSpell(List<RecallOption> list, List<string>? notes, ISet<int> known, RecallMemory memory,
|
||||
string charKey, int spellId, string name, RecallSlot slot, string howToLearn)
|
||||
{
|
||||
if (!known.Contains(spellId)) return;
|
||||
RecallSpot? spot = memory.Get(charKey, slot);
|
||||
if (spot == null) { notes?.Add(name + ": where it lands isn't known yet (" + howToLearn + ")."); return; }
|
||||
if (!spot.OnMap) { notes?.Add(name + " lands " + Where(spot) + ": not used for routes."); return; }
|
||||
list.Add(new RecallOption
|
||||
{
|
||||
Name = name, SpellId = spellId, Ns = spot.Ns, Ew = spot.Ew, CastSeconds = SpellCastSeconds, Learned = true,
|
||||
});
|
||||
}
|
||||
|
||||
private static void AddLearnedCommand(List<RecallOption> list, List<string>? notes, RecallMemory memory, string charKey,
|
||||
RecallSlot slot, string name, bool alwaysAvailable, string howToLearn)
|
||||
{
|
||||
RecallSpot? spot = memory.Get(charKey, slot);
|
||||
if (spot == null)
|
||||
{
|
||||
if (alwaysAvailable) notes?.Add(name + ": where it lands isn't known yet (" + howToLearn + ").");
|
||||
return;
|
||||
}
|
||||
if (!spot.OnMap) { notes?.Add(name + " lands " + Where(spot) + ": not used for routes."); return; }
|
||||
list.Add(new RecallOption
|
||||
{
|
||||
Name = name,
|
||||
Command = spot.Command.Length > 0 ? spot.Command : RecallMemory.DefaultCommand(slot),
|
||||
Ns = spot.Ns, Ew = spot.Ew, CastSeconds = CommandRecallSeconds, Learned = true,
|
||||
});
|
||||
}
|
||||
|
||||
private static string Where(RecallSpot s) => s.Label.Length > 0 ? "in " + s.Label : "in a dungeon";
|
||||
|
||||
public static List<RecallLink> Links(List<RecallOption> options)
|
||||
{
|
||||
var links = new List<RecallLink>(options.Count);
|
||||
foreach (var o in options) links.Add(o.ToLink());
|
||||
return links;
|
||||
}
|
||||
}
|
||||
|
|
@ -34,6 +34,10 @@
|
|||
<ItemGroup>
|
||||
<!-- Shared travel-route planner (same source the offline RynthNav.PortalGraph tool validates). -->
|
||||
<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" />
|
||||
<!-- One logged, guarded way to use an object (who used what, and why). -->
|
||||
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
161
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs
Normal file
161
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Two things a walking leg must never do (Lucy, 10-01 17:53):
|
||||
// 1. Walk into a portal that isn't its target. Every portal near the player is kept out of: the
|
||||
// detailed path goes round it (AvoidFilter) and the steering turns round it (PortalAvoid.Steer),
|
||||
// whatever the walker is heading for: a path corner, the route's aim or a blind push.
|
||||
// 2. Head off toward a target that can't be walked to. With a route graph the walker waits for
|
||||
// the route search's answer before its first step; "no route" to another landmass re-plans
|
||||
// with portals and recalls once (when they're on) or stops and says why.
|
||||
// Tick thread.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const uint ItemTypePortal = 0x00010000;
|
||||
private const long AvoidRefreshMs = 1000;
|
||||
private const double AvoidNearUnits = 300.0; // portals farther than this don't matter yet
|
||||
private const double AvoidTargetUnits = 15.0; // the step's own portal (a portal step's target) isn't avoided
|
||||
private const int CoarseHoldMaxTicks = 90; // ~3 s: never wait longer than this for the search
|
||||
|
||||
private readonly PortalAvoid _avoid = new();
|
||||
private AvoidFilter? _avoidFilter;
|
||||
private long _nextAvoidMs;
|
||||
private bool _avoidFallbackSaid;
|
||||
private Atlas? _avoidAtlas;
|
||||
private List<PortalAvoid.Spot> _atlasPortals = new();
|
||||
private int _avoidLogged = -1;
|
||||
|
||||
private int _coarseHoldTicks; // re-plans to wait for the route search (see StepGoto)
|
||||
private bool _landReplanned; // this goto already re-planned after "no route over land"
|
||||
private string _gotoType = "";
|
||||
private bool _walkHaveLast; // last tick's position on a walking leg (teleport check)
|
||||
private double _walkLastWx, _walkLastWy;
|
||||
|
||||
private AvoidFilter WalkFilter() => _avoidFilter ??= new AvoidFilter(_avoid);
|
||||
|
||||
/// <summary>
|
||||
/// The portals to keep out of, near the player: every portal object the client knows (exact),
|
||||
/// and the Atlas's portals on the map (to 0.01 degree) where no live one stands. The current
|
||||
/// step's own portal (walking into a portal or a dungeon's entrance) is left out.
|
||||
/// </summary>
|
||||
private void RefreshAvoid(bool force)
|
||||
{
|
||||
long now = NowMs;
|
||||
if (!force && now < _nextAvoidMs) return;
|
||||
_nextAvoidMs = now + AvoidRefreshMs;
|
||||
if (!_avoidPortals) { _avoid.Clear(); return; }
|
||||
|
||||
Atlas atlas = _atlas;
|
||||
if (!ReferenceEquals(atlas, _avoidAtlas))
|
||||
{
|
||||
var list = new List<PortalAvoid.Spot>();
|
||||
foreach (AtlasLocation l in atlas.Locations)
|
||||
if (l.OnMap && l.Type.Equals("Portal", StringComparison.Ordinal))
|
||||
list.Add(new PortalAvoid.Spot(NavCoords.WorldX(l.Ew), NavCoords.WorldY(l.Ns), PortalAvoid.MapRadius, l.Name));
|
||||
_atlasPortals = list;
|
||||
_avoidAtlas = atlas;
|
||||
}
|
||||
var map = new List<PortalAvoid.Spot>();
|
||||
foreach (PortalAvoid.Spot sp in _atlasPortals)
|
||||
if (Math.Abs(sp.X - _wx) < AvoidNearUnits && Math.Abs(sp.Y - _wy) < AvoidNearUnits) map.Add(sp);
|
||||
|
||||
var live = new List<PortalAvoid.Spot>();
|
||||
if (Host.HasGetLiveObjectIds)
|
||||
{
|
||||
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 x, out float y, out _) || cell == 0) continue;
|
||||
double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y;
|
||||
if (Math.Abs(wx - _wx) > AvoidNearUnits || Math.Abs(wy - _wy) > AvoidNearUnits) continue;
|
||||
Host.TryGetObjectName(id, out string name);
|
||||
live.Add(new PortalAvoid.Spot(wx, wy, PortalAvoid.LiveRadius, name ?? ""));
|
||||
}
|
||||
}
|
||||
|
||||
// The step's own target: walking into a portal (a route's portal step, a dungeon's entrance).
|
||||
bool portalLeg = _route != null && _routeIdx < _route.Count && _route[_routeIdx].UsePortal;
|
||||
if (portalLeg) _avoid.Set(live, map, _gotoTew, _gotoTns, AvoidTargetUnits);
|
||||
else _avoid.Set(live, map);
|
||||
if (_avoid.Count != _avoidLogged)
|
||||
{
|
||||
_avoidLogged = _avoid.Count;
|
||||
Host.Log($"[RynthNav] avoid: {_avoid.Count} portal(s) near you to keep out of ({live.Count} seen, {map.Count} from the Atlas){(portalLeg ? "; the step's own portal excepted" : "")}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The heading to take instead of <paramref name="desired"/>, round any portal in the next <paramref name="lookahead"/> units.</summary>
|
||||
private double SteerRoundPortals(double desired, double lookahead)
|
||||
{
|
||||
if (_avoid.Count == 0) return desired;
|
||||
double h = _avoid.Steer(_wx, _wy, desired, lookahead, out int spot);
|
||||
if (spot >= 0 && Math.Abs(h - desired) > 0.5 && _blindLogTicks-- <= 0)
|
||||
{
|
||||
_blindLogTicks = 30;
|
||||
Host.Log($"[RynthNav] avoid: steering round {(_avoid.Spots[spot].Name.Length > 0 ? _avoid.Spots[spot].Name : "a portal")} ({desired:F0} -> {h:F0} deg)");
|
||||
}
|
||||
return h;
|
||||
}
|
||||
private int _blindLogTicks;
|
||||
|
||||
/// <summary>
|
||||
/// A route in one readable line for the log: "recall Recall Aphus Lassel → walk 12 yd to the Town
|
||||
/// Network portal → Town Network (exit Arwic) → walk 118 yd; cost ~1265u; walking straight 14210
|
||||
/// yd". So a strange route can be read from the log afterwards.
|
||||
/// </summary>
|
||||
private string RouteLine(List<RouteStep>? steps, double startNs, double startEw, double goalNs, double goalEw, double est, bool? land)
|
||||
{
|
||||
var parts = new List<string>();
|
||||
double pns = startNs, pew = startEw;
|
||||
if (steps != null)
|
||||
for (int i = 0; i < steps.Count; i++)
|
||||
{
|
||||
RouteStep st = steps[i];
|
||||
bool nextHub = i + 1 < steps.Count && steps[i + 1].IsHub;
|
||||
if (st.UseRecall) parts.Add("recall " + st.Label);
|
||||
else if (st.IsHub) parts.Add($"Town Network (exit {HubWhere(HubExitOf(i) ?? (_townNet != null && st.HubExit >= 0 && st.HubExit < _townNet.Exits.Count ? _townNet.Exits[st.HubExit] : null))})");
|
||||
else
|
||||
{
|
||||
double d = NavCoords.Distance(pns, pew, st.Ns, st.Ew);
|
||||
parts.Add(nextHub ? $"walk {d:F0} yd to the Town Network portal"
|
||||
: st.UsePortal ? $"walk {d:F0} yd, portal {st.Label}"
|
||||
: $"walk {d:F0} yd");
|
||||
}
|
||||
if (st.UseRecall || st.IsHub || (st.UsePortal && !double.IsNaN(st.LandNs))) { pns = st.LandNs; pew = st.LandEw; }
|
||||
else { pns = st.Ns; pew = st.Ew; }
|
||||
if (double.IsNaN(pns)) { pns = st.Ns; pew = st.Ew; }
|
||||
}
|
||||
if (parts.Count == 0) parts.Add($"walk {NavCoords.Distance(startNs, startEw, goalNs, goalEw):F0} yd");
|
||||
double straight = NavCoords.Distance(startNs, startEw, goalNs, goalEw);
|
||||
return string.Join(" → ", parts) + $"; cost ~{(double.IsInfinity(est) ? "none" : est.ToString("F0"))}u; walking straight {straight:F0} yd"
|
||||
+ (land == false ? " (not possible: another landmass)" : "");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The route search says the target is on another landmass. With portals and recalls on, plan
|
||||
/// the whole trip again from here, once (walks over water are then left out, so the plan takes
|
||||
/// a portal, a recall or the Town Network); otherwise, or when that finds nothing, stop and say why.
|
||||
/// </summary>
|
||||
private void NoLandRoute()
|
||||
{
|
||||
string name = _gotoName.Length > 0 ? _gotoName : "there";
|
||||
double ns = NavCoords.NsFromWorld(_finalTns), ew = NavCoords.EwFromWorld(_finalTew);
|
||||
string type = _gotoType, enter = _enterName, enterType = _enterType;
|
||||
bool onFinalLeg = _route == null || _routeIdx >= _route.Count - 1;
|
||||
if (_portalsEnabled && !_landReplanned)
|
||||
{
|
||||
_landReplanned = true;
|
||||
Host.Log($"[RynthNav] no route over land to {name}: planning again with portals and recalls");
|
||||
Say($"goto: no walking route to {name} from here (water or cliffs in the way); planning with portals and recalls");
|
||||
StartWalk(name, type, ns, ew, enter, enterType, landReplan: true);
|
||||
return;
|
||||
}
|
||||
string why = $"no walking route to {(onFinalLeg ? name : "the next step")} (water or cliffs in the way)";
|
||||
FinishGoto(_portalsEnabled
|
||||
? $"stopped: {why}, and no portal, recall or the Town Network I know of gets there"
|
||||
: $"stopped: {why}; turn on Use portals and recalls");
|
||||
}
|
||||
}
|
||||
229
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Graph.cs
Normal file
229
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Graph.cs
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DotRecast.Core.Numerics;
|
||||
using DotRecast.Detour;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// RynthNav's long-range walking: the coarse route graph (NavData\navgraph.bin, see NavGraph)
|
||||
// tells the walker which way round a bay, a lake or a ridge to go; the detailed Detour planner
|
||||
// still does every step, inside the usual 5x5 tile window. Without a graph (or with one from
|
||||
// another bake) goto walks as before: straight at the target as far as the navmesh allows.
|
||||
// Tick thread, except the background load.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const int CoarseRetryReplans = 5; // a failed or abandoned route is planned again after this many re-plans (~3 s)
|
||||
private const int CoarseNoRouteReplans = 100; // after "no route": try again in ~60 s (the player may have moved)
|
||||
private const int CoarseOffRouteReplans = 3; // re-plans off the route before planning it again
|
||||
private const int CoarseLoadAhead = 3; // load route tiles up to this many landblocks from the player
|
||||
|
||||
private volatile NavGraph? _graph;
|
||||
private volatile string _graphStatus = "loading…";
|
||||
private NavGraph? _graphChecked; // the graph every loaded tile has been checked against
|
||||
// Region per polygon, and the fingerprint, of every loaded tile.
|
||||
private readonly Dictionary<uint, int[]> _tileRegions = new();
|
||||
private readonly Dictionary<uint, (int Polys, int Verts, int Tris)> _tilePrints = new();
|
||||
private NavCoarse? _coarse; // the current leg's route (null = none, or none yet)
|
||||
private int _coarseRetry; // re-plans left before planning a route again
|
||||
private int _coarseOff; // re-plans in a row off the route
|
||||
private bool _coarseAnnounced, _coarseNoRouteSaid;
|
||||
private double _aimEw, _aimNs; // where the last re-plan aimed (the blind push follows it)
|
||||
|
||||
private void LoadGraph()
|
||||
{
|
||||
string path = Path.Combine(NavDataDir, NavGraph.FileName);
|
||||
Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path)) { _graphStatus = "no navgraph.bin: long gotos head straight for the target"; return; }
|
||||
NavGraph g = NavGraph.Load(path);
|
||||
g.BuildComponents(); // landmasses: which walks can be done at all
|
||||
_graph = g;
|
||||
_graphStatus = $"{g.TileCount} tiles, {g.PortalCount} portals (set {g.SetIdHex[..8]})";
|
||||
Host.Log($"[RynthNav] route graph: {_graphStatus}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_graphStatus = $"navgraph.bin failed to load ({ex.GetType().Name}: {ex.Message}): long gotos head straight for the target";
|
||||
Host.Log($"[RynthNav] {_graphStatus}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void OnTileLoaded(uint lb, DtMeshData md)
|
||||
{
|
||||
_tileRegions[lb] = NavRegions.Build(md, out _);
|
||||
_tilePrints[lb] = NavRegions.Fingerprint(md);
|
||||
NavGraph? g = _graph;
|
||||
if (g != null && ReferenceEquals(g, _graphChecked)) CheckTile(g, lb);
|
||||
}
|
||||
|
||||
private void OnTileUnloaded(uint lb) { _tileRegions.Remove(lb); _tilePrints.Remove(lb); }
|
||||
|
||||
private void CheckTile(NavGraph g, uint lb)
|
||||
{
|
||||
if (!_tilePrints.TryGetValue(lb, out var fp) || g.Matches(lb, fp.Polys, fp.Verts, fp.Tris)) return;
|
||||
DropGraph($"tile 0x{lb:X4} isn't the one it was built from (a graph from another bake, or tiles changed since)");
|
||||
}
|
||||
|
||||
private void DropGraph(string why)
|
||||
{
|
||||
_graph = null; _graphChecked = null; _coarse = null; _coarseTask = null; _coarseVersion++;
|
||||
_graphStatus = "ignored: " + why;
|
||||
Host.Log($"[RynthNav] route graph {_graphStatus}");
|
||||
}
|
||||
|
||||
/// <summary>The graph, once every loaded tile matches it; null to walk without it.</summary>
|
||||
private NavGraph? UsableGraph()
|
||||
{
|
||||
NavGraph? g = _graph;
|
||||
if (g == null) return null;
|
||||
if (!ReferenceEquals(g, _graphChecked))
|
||||
{
|
||||
_graphChecked = g;
|
||||
foreach (uint lb in new List<uint>(_tilePrints.Keys)) { CheckTile(g, lb); if (_graph == null) return null; }
|
||||
}
|
||||
return _graph;
|
||||
}
|
||||
|
||||
/// <summary>A new leg (or goto): its route is planned on the first re-plan.</summary>
|
||||
/// <summary>
|
||||
/// Can the target's landblock be walked to from region <paramref name="here"/>? The region's own
|
||||
/// landmass when it's a real one; on a roof or a ledge (a tiny landmass), its landblock's.
|
||||
/// </summary>
|
||||
private static bool? LandFromRegion(NavGraph g, int here, uint goalLb)
|
||||
{
|
||||
int c = g.Component(here);
|
||||
int[] goalComps = g.LandblockComponents(goalLb);
|
||||
if (c < 0 || goalComps.Length == 0) return null;
|
||||
if (g.ComponentSize(c) < 8) return g.SameLand(g.RegionLandblock(here), goalLb);
|
||||
return Array.IndexOf(goalComps, c) >= 0;
|
||||
}
|
||||
|
||||
private void ResetCoarse()
|
||||
{
|
||||
_coarse = null; _coarseRetry = 0; _coarseOff = 0; _coarseAnnounced = false; _coarseNoRouteSaid = false;
|
||||
_coarseTask = null; _coarseVersion++;
|
||||
}
|
||||
|
||||
// The search runs on a worker (it touches only the immutable graph; the navmesh walks it
|
||||
// needs at both ends are measured on the tick first). Its result is picked up on a later
|
||||
// re-plan, if the leg it was planned for is still the current one.
|
||||
private Task<(NavCoarse? Route, int Expanded, long Ms, int Version, int Here, int Goal, double Straight)>? _coarseTask;
|
||||
private int _coarseVersion;
|
||||
|
||||
/// <summary>
|
||||
/// Called from Replan with the polygon underfoot: keeps the route in step with the player,
|
||||
/// plans it when needed, loads its tiles ahead, and returns the point to plan to next
|
||||
/// (null = the target itself, as without a graph). Sets <paramref name="tilesChanged"/>
|
||||
/// when it loaded tiles (the query must be rebuilt).
|
||||
/// </summary>
|
||||
private (float Ew, float Up, float Ns)? CoarseSteer(long sRef, RcVec3f sPt, ref bool tilesChanged)
|
||||
{
|
||||
NavGraph? g = UsableGraph();
|
||||
if (g == null) { _coarse = null; _coarseTask = null; _coarseHoldTicks = 0; return null; }
|
||||
TakeCoarseResult();
|
||||
int here = NavCoarse.RegionOf(g, _navMesh!, sRef, _tileRegions);
|
||||
// Off the route: the detailed path can cut through a small region the route doesn't
|
||||
// list (a ledge, a porch), so only plan again after a few re-plans (~2 s) off it.
|
||||
if (_coarse != null)
|
||||
{
|
||||
if (_coarse.Advance(here)) _coarseOff = 0;
|
||||
else if (++_coarseOff >= CoarseOffRouteReplans) { _coarse = null; _coarseRetry = 0; _coarseOff = 0; }
|
||||
}
|
||||
if (_coarse == null)
|
||||
{
|
||||
if (_coarseTask != null) return null; // being planned
|
||||
if (_coarseRetry > 0) { _coarseRetry--; return null; }
|
||||
_coarseRetry = CoarseRetryReplans;
|
||||
if (here < 0) { _coarseHoldTicks = 0; return null; }
|
||||
PlanCoarse(g, sRef, sPt);
|
||||
if (_coarseTask == null) _coarseHoldTicks = 0; // nothing to wait for (no ground at one end)
|
||||
return null;
|
||||
}
|
||||
|
||||
int pX = (int)((_cellId >> 24) & 0xFF), pY = (int)((_cellId >> 16) & 0xFF);
|
||||
foreach (uint lb in _coarse.Upcoming(8))
|
||||
{
|
||||
int x = (int)(lb >> 8), y = (int)(lb & 0xFF);
|
||||
if (Math.Max(Math.Abs(x - pX), Math.Abs(y - pY)) > CoarseLoadAhead) break;
|
||||
if (!_loadedTiles.Contains(lb) && EnsureTile(lb)) tilesChanged = true;
|
||||
}
|
||||
_tileCount = _loadedTiles.Count;
|
||||
var s = _coarse.Steer(lb => _loadedTiles.Contains(lb), out bool final);
|
||||
return final ? null : s;
|
||||
}
|
||||
|
||||
private void PlanCoarse(NavGraph g, long sRef, RcVec3f sPt)
|
||||
{
|
||||
NavCoarse.Probe? start = _query == null ? null : NavCoarse.ProbeAt(g, _navMesh!, _query, sRef, sPt, _tileRegions);
|
||||
if (start == null) return;
|
||||
// The target's region: from the loaded navmesh when its tile is in, else from its tile file.
|
||||
NavCoarse.Probe? target = null;
|
||||
int gx = (int)Math.Floor(_gotoTew / 192.0), gy = (int)Math.Floor(_gotoTns / 192.0);
|
||||
uint goalLb = gx is >= 0 and <= 255 && gy is >= 0 and <= 255 ? (uint)((gx << 8) | gy) : 0;
|
||||
try
|
||||
{
|
||||
target = _loadedTiles.Contains(goalLb)
|
||||
? NavCoarse.ProbeNear(g, _navMesh!, _query!, _gotoTew, _wz, _gotoTns, 40f, _tileRegions)
|
||||
: NavCoarse.ProbeFile(g, NavDataDir, _gotoTew, _wz, _gotoTns, 40f);
|
||||
}
|
||||
catch (Exception ex) { Host.Log($"[RynthNav] route: target tile unreadable: {ex.Message}"); }
|
||||
if (target == null) return; // no navmesh at the target: head straight, as without a graph
|
||||
|
||||
NavCoarse.Request req = NavCoarse.Request.Measure(g, start, target);
|
||||
int version = _coarseVersion, here = start.Region, goal = target.Region;
|
||||
double straight = Math.Sqrt((_gotoTew - _wx) * (_gotoTew - _wx) + (_gotoTns - _wy) * (_gotoTns - _wy));
|
||||
_coarseTask = Task.Run(() =>
|
||||
{
|
||||
long t0 = Environment.TickCount64;
|
||||
NavCoarse? c = NavCoarse.Plan(g, req, out int expanded);
|
||||
return (c, expanded, Environment.TickCount64 - t0, version, here, goal, straight);
|
||||
});
|
||||
}
|
||||
|
||||
private void TakeCoarseResult()
|
||||
{
|
||||
if (_coarseTask is not { IsCompleted: true } task) return;
|
||||
_coarseTask = null;
|
||||
if (task.IsFaulted) { Host.Log($"[RynthNav] route search failed: {task.Exception?.GetBaseException().Message}"); return; }
|
||||
var (c, expanded, ms, version, here, goal, straight) = task.Result;
|
||||
if (version != _coarseVersion || !_gotoActive) return; // planned for a leg that's over
|
||||
_coarseHoldTicks = 0; // the answer is in: walk (or stop)
|
||||
if (c == null)
|
||||
{
|
||||
NavGraph? g = _graph;
|
||||
uint goalLb = NavGraph.LandblockAt(_gotoTew, _gotoTns);
|
||||
bool? land = g == null ? null : LandFromRegion(g, here, goalLb);
|
||||
Host.Log($"[RynthNav] route: none from region {here} to {goal} ({expanded} expanded, {ms} ms); over land: {(land == null ? "unknown" : land.Value ? "the target's landblock has ground on this landmass" : "no, another landmass")}");
|
||||
_coarseRetry = CoarseNoRouteReplans; // searching a whole landmass again every few seconds would cost
|
||||
if (land == false)
|
||||
{
|
||||
// Water or cliffs between here and there: walking (or a blind push) only leads
|
||||
// somewhere wrong, like into a portal. Plan with portals and recalls, or stop.
|
||||
NoLandRoute();
|
||||
return;
|
||||
}
|
||||
if (!_coarseNoRouteSaid)
|
||||
{
|
||||
_coarseNoRouteSaid = true;
|
||||
Say("goto: no walkable route to that exact spot on the navmesh (a roof or a ledge?); heading for it as far as it goes");
|
||||
}
|
||||
return;
|
||||
}
|
||||
_coarse = c;
|
||||
_coarseOff = 0;
|
||||
// A new route measures progress differently: restart the watchdog's best.
|
||||
_bestDist = double.MaxValue; _bestTick = _legTicks;
|
||||
Host.Log($"[RynthNav] route: {c.Count} border crossing(s), ~{c.Cost:F0}u walking vs {straight:F0}u straight ({expanded} expanded, {ms} ms)");
|
||||
if (!_coarseAnnounced && c.Count > 0)
|
||||
{
|
||||
_coarseAnnounced = true;
|
||||
if (c.Cost > straight * 1.15) Say($"goto: the way over land is about {c.Cost:F0} yd (straight line {straight:F0} yd)");
|
||||
}
|
||||
}
|
||||
}
|
||||
207
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs
Normal file
207
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// What the engine's RynthNav panel shows beyond the basic status (RynthNav 0.6.1+): the
|
||||
// status line in plain words ("walking to Holtburg, 1.2k yd left", "taking portal ...",
|
||||
// "arrived inside Matron Hive") with the current step's distance left; the "here" and
|
||||
// NavData facts (the Info section); and, in the travel JSON, the character's own recall
|
||||
// spots and a portal tie waiting for "which tie was it?".
|
||||
//
|
||||
// Threads: the tick builds these (UpdateGoLine, RefreshInfo) and the engine's pump thread
|
||||
// reads them in BuildStatusJson: the strings under _gate, the numbers volatile.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const long InfoRefreshMs = 30000; // tile files on disk: counted this often while the panel polls
|
||||
private const long PanelPollWindowMs = 3000; // the panel counts as open this long after its last status poll
|
||||
|
||||
// Tick thread: how the last goto (or the last panel-visible command) ended, as said in chat.
|
||||
private string _goNote = "";
|
||||
// Read under _gate.
|
||||
private string _goLine = "", _goPhase = "";
|
||||
private double _goLeft = -1;
|
||||
// Rebuild only when these change (tick thread).
|
||||
private string _glPhase = "", _glNote = "";
|
||||
private int _glIdx = -2;
|
||||
private long _glLeftKey = -1;
|
||||
private int _glSub;
|
||||
private bool _glActive;
|
||||
|
||||
// Info (tick writes, any thread reads).
|
||||
private volatile int _tileHere = -1; // a tile file for the current landblock: 1 yes, 0 no, -1 not checked
|
||||
private volatile int _tilesOnDisk = -1;
|
||||
private int _infoBusy;
|
||||
private long _nextInfoMs, _lastStatusPollMs;
|
||||
|
||||
/// <summary>Says <paramref name="text"/> in chat and shows it on the panel's status line. Tick thread.</summary>
|
||||
private void Note(string text)
|
||||
{
|
||||
Say(text);
|
||||
_goNote = text;
|
||||
}
|
||||
|
||||
/// <summary>The panel's status line and the current step's distance left. Tick thread, every tick.</summary>
|
||||
private void UpdateGoLine()
|
||||
{
|
||||
bool active = _gotoActive;
|
||||
string phase = "";
|
||||
double left = -1;
|
||||
int idx = active && _route != null ? _routeIdx : -1;
|
||||
if (active)
|
||||
{
|
||||
if (_recallWait) phase = "recall";
|
||||
else if (_portalWait) phase = "portal";
|
||||
else if (CurrentStepIsHub) { phase = "town"; left = HubLeft(); }
|
||||
else
|
||||
{
|
||||
phase = "walk";
|
||||
if (_hasPose)
|
||||
{
|
||||
double dx = _gotoTew - _wx, dy = _gotoTns - _wy;
|
||||
left = _coarse != null ? _coarse.Remaining(_wx, _wy) : Math.Sqrt(dx * dx + dy * dy);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Whole yards under 1000, tens of yards above (FmtDistance shows 0.1k there).
|
||||
long leftKey = left < 0 ? -1 : left < 1000 ? (long)left : 100000 + (long)(left / 100);
|
||||
int sub = phase == "town" ? (_hubLanded ? 1 : 0) + (HubIsWaiting ? 2 : 0) : 0; // the hub step's line changes with these
|
||||
if (active == _glActive && phase == _glPhase && idx == _glIdx && leftKey == _glLeftKey && sub == _glSub && ReferenceEquals(_goNote, _glNote))
|
||||
return;
|
||||
_glActive = active; _glPhase = phase; _glIdx = idx; _glLeftKey = leftKey; _glSub = sub; _glNote = _goNote;
|
||||
|
||||
string line = active ? GoLine(phase, left) : _goNote;
|
||||
lock (_gate) { _goLine = line; _goPhase = phase; _goLeft = left; }
|
||||
}
|
||||
|
||||
private string GoLine(string phase, double left)
|
||||
{
|
||||
bool hasStep = _route != null && _routeIdx < _route.Count;
|
||||
RouteStep step = hasStep ? _route![_routeIdx] : default;
|
||||
string label = hasStep ? step.Label ?? "" : "";
|
||||
bool last = _route == null || _routeIdx >= _route.Count - 1;
|
||||
string name = _gotoName.Length > 0 ? _gotoName : "the target";
|
||||
switch (phase)
|
||||
{
|
||||
case "recall":
|
||||
{
|
||||
RecallOption? o = CurrentRecallOption();
|
||||
return "casting " + (o != null ? o.Name : label.Length > 0 ? label : "a recall");
|
||||
}
|
||||
case "portal":
|
||||
if (NextStepIsHub) return $"taking the Town Network to {HubWhere(HubExitOf(_routeIdx + 1))}";
|
||||
return last && _enterName.Length > 0 ? "going into " + _enterName : "taking portal " + label;
|
||||
case "town":
|
||||
return HubLine(left);
|
||||
}
|
||||
string far = left >= 0 ? ", " + NavCoords.FmtDistance(left) + " left" : "";
|
||||
if (hasStep && step.UseRecall) return "getting ready to cast " + label;
|
||||
if (hasStep && step.UsePortal && NextStepIsHub)
|
||||
return $"walking to the Town Network portal{far} (to {HubWhere(HubExitOf(_routeIdx + 1))})";
|
||||
if (hasStep && step.UsePortal)
|
||||
return last && _enterName.Length > 0 ? $"walking to {_enterName}'s portal{far}" : $"walking to the portal {label}{far}";
|
||||
return $"walking to {name}{far}";
|
||||
}
|
||||
|
||||
/// <summary>Tile file here, and how many are on disk; the count only while the panel polls. Tick thread.</summary>
|
||||
private void RefreshInfo(bool landblockChanged)
|
||||
{
|
||||
long now = NowMs;
|
||||
if (landblockChanged && _hasPose)
|
||||
{
|
||||
try { _tileHere = File.Exists(Path.Combine(NavDataDir, $"nav_{CurrentLandblock:X4}.tile")) ? 1 : 0; } catch { _tileHere = -1; }
|
||||
}
|
||||
if (now < _nextInfoMs || now - Interlocked.Read(ref _lastStatusPollMs) > PanelPollWindowMs) return;
|
||||
_nextInfoMs = now + InfoRefreshMs;
|
||||
if (Interlocked.Exchange(ref _infoBusy, 1) != 0) return;
|
||||
uint lb = CurrentLandblock;
|
||||
bool hasPose = _hasPose;
|
||||
Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
int n = 0;
|
||||
if (Directory.Exists(NavDataDir))
|
||||
foreach (string _ in Directory.EnumerateFiles(NavDataDir, "nav_*.tile")) n++;
|
||||
_tilesOnDisk = n;
|
||||
if (hasPose) _tileHere = File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile")) ? 1 : 0;
|
||||
}
|
||||
catch { }
|
||||
finally { Interlocked.Exchange(ref _infoBusy, 0); }
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The live panel fields of the status JSON ("go", "info"). Any thread.</summary>
|
||||
private void AppendPanelJson(StringBuilder sb)
|
||||
{
|
||||
Interlocked.Exchange(ref _lastStatusPollMs, NowMs);
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
string line, phase; double left;
|
||||
lock (_gate) { line = _goLine; phase = _goPhase; left = _goLeft; }
|
||||
sb.Append(",\"v\":\"").Append(PluginVersion).Append('"');
|
||||
sb.Append(",\"go\":{\"line\":\"").Append(Esc(line)).Append("\",\"phase\":\"").Append(phase)
|
||||
.Append("\",\"left\":").Append(left < 0 ? "-1" : left.ToString("F0", ci)).Append('}');
|
||||
uint cell = _cellId;
|
||||
sb.Append(",\"info\":{\"dir\":\"").Append(Esc(NavDataDir)).Append("\",\"source\":\"").Append(Esc(NavConfig.Source))
|
||||
.Append("\",\"graph\":").Append(_graph != null ? 1 : 0).Append(",\"graphStatus\":\"").Append(Esc(_graphStatus))
|
||||
.Append("\",\"tileHere\":").Append(_tileHere).Append(",\"indoors\":").Append(_hasPose && (cell & 0xFFFF) >= 0x100 ? 1 : 0)
|
||||
.Append(",\"onDisk\":").Append(_tilesOnDisk)
|
||||
.Append(",\"townNet\":").Append(_townNet != null ? 1 : 0).Append(",\"townNetStatus\":\"").Append(Esc(_townNetStatus)).Append("\"}");
|
||||
}
|
||||
|
||||
// ── The character's own recall spots, for the Recalls section (travel JSON) ──
|
||||
|
||||
private static readonly (RecallSlot Slot, string Name)[] MySlots =
|
||||
{
|
||||
(RecallSlot.Tie1, "Primary portal tie"),
|
||||
(RecallSlot.Tie2, "Secondary portal tie"),
|
||||
(RecallSlot.Lifestone, "Lifestone Recall (tied lifestone)"),
|
||||
(RecallSlot.Sanctuary, "@lifestone (last lifestone used)"),
|
||||
(RecallSlot.LastPortal, "Portal Recall (last portal)"),
|
||||
(RecallSlot.House, "House recall"),
|
||||
(RecallSlot.Mansion, "Allegiance mansion recall"),
|
||||
(RecallSlot.Hometown, "Allegiance hometown recall"),
|
||||
};
|
||||
|
||||
/// <summary>"mine" (every recall spot learned for this character), "ties", "tiePending". Tick thread.</summary>
|
||||
private void AppendMyRecalls(StringBuilder sb, CultureInfo ci)
|
||||
{
|
||||
sb.Append(",\"mine\":[");
|
||||
bool first = true;
|
||||
if (_charKey.Length > 0)
|
||||
foreach (var (slot, name) in MySlots)
|
||||
{
|
||||
RecallSpot? s = _memory.Get(_charKey, slot);
|
||||
if (s == null) continue;
|
||||
if (!first) sb.Append(',');
|
||||
first = false;
|
||||
sb.Append("{\"s\":\"").Append(RecallMemory.SlotName(slot)).Append("\",\"n\":\"").Append(Esc(name))
|
||||
.Append("\",\"on\":").Append(s.OnMap ? 1 : 0)
|
||||
.Append(",\"ns\":").Append(s.Ns.ToString("F2", ci)).Append(",\"ew\":").Append(s.Ew.ToString("F2", ci))
|
||||
.Append(",\"at\":\"").Append(Esc(s.Label)).Append("\"}");
|
||||
}
|
||||
sb.Append(']');
|
||||
// Which tie spells the character knows: 1 yes, 0 no, -1 the spellbook isn't read yet.
|
||||
int k1 = _known == null ? -1 : _known.Contains(RecallPlanner.PrimaryPortalTie) ? 1 : 0;
|
||||
int k2 = _known == null ? -1 : _known.Contains(RecallPlanner.SecondaryPortalTie) ? 1 : 0;
|
||||
sb.Append(",\"ties\":{\"t1\":").Append(k1).Append(",\"t2\":").Append(k2).Append('}');
|
||||
RecallSpot? p = _pendingTie;
|
||||
sb.Append(",\"tiePending\":\"").Append(p == null ? "" : Esc(p.OnMap ? $"{p.Label} ({NavCoords.Fmt(p.Ns, p.Ew)})" : p.Label)).Append('"');
|
||||
}
|
||||
|
||||
// ── UTF-8 status (RynthNavGetStatusJsonUtf8) ─────────────────────────────
|
||||
|
||||
/// <summary>The status JSON as UTF-8 bytes, NUL-terminated. Any thread.</summary>
|
||||
internal byte[] BuildStatusUtf8()
|
||||
{
|
||||
string json = BuildStatusJson();
|
||||
byte[] bytes = new byte[Encoding.UTF8.GetByteCount(json) + 1];
|
||||
Encoding.UTF8.GetBytes(json, 0, json.Length, bytes, 0);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
132
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PortalAim.cs
Normal file
132
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PortalAim.cs
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Taking a portal: aim at the portal object the client actually shows (its exact position), not the
|
||||
// Atlas spot (positions to 0.01 degree, a couple of metres out: "completely missing the portal by a
|
||||
// few yards", 10-01 20:40), run straight into it, and if it doesn't fire, back off and try again
|
||||
// rather than giving up. Timed by the clock, not by ticks, so a low frame rate doesn't cut it short.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const long PortalTryMs = 12000; // one run at the portal before backing off
|
||||
private const long PortalBackoffMs = 2500; // back away this long, then run in again
|
||||
private const int PortalMaxTries = 5; // about a minute in all
|
||||
private const double PortalSnapUnits = 25.0; // a live portal this close to the planned spot is it
|
||||
private const double PortalUseUnits = 8.0; // within this of the live portal, use it (the game walks you in)
|
||||
|
||||
private long _portalTryStartMs, _portalBackoffUntilMs, _nextPortalSnapMs;
|
||||
private int _portalTries;
|
||||
private uint _portalLiveId; // the live portal object aimed at (0 = none seen)
|
||||
private long _portalLastUseMs;
|
||||
private bool _portalSnapped;
|
||||
|
||||
private void BeginPortalAim()
|
||||
{
|
||||
_portalTryStartMs = NowMs; _portalBackoffUntilMs = 0; _nextPortalSnapMs = 0;
|
||||
_portalTries = 1; _portalSnapped = false; _portalLiveId = 0; _portalLastUseMs = 0;
|
||||
}
|
||||
|
||||
/// <summary>The name the step's portal goes by (route step label, or the dungeon's entrance).</summary>
|
||||
private string PortalStepName()
|
||||
{
|
||||
if (_route != null && _routeIdx < _route.Count && _route[_routeIdx].Label.Length > 0) return _route[_routeIdx].Label;
|
||||
return _enterName;
|
||||
}
|
||||
|
||||
/// <summary>Move the goal onto the live portal nearest the planned spot (a name match first).</summary>
|
||||
private void SnapToLivePortal()
|
||||
{
|
||||
long now = NowMs;
|
||||
if (now < _nextPortalSnapMs || !Host.HasGetLiveObjectIds) return;
|
||||
_nextPortalSnapMs = now + 500;
|
||||
string want = PortalStepName();
|
||||
double bestNamed = double.MaxValue, bestAny = double.MaxValue;
|
||||
double nx = 0, ny = 0, ax = 0, ay = 0; string nName = "", aName = ""; uint nId = 0, aId = 0;
|
||||
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 x, out float y, out _) || cell == 0) continue;
|
||||
double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y;
|
||||
double d = Math.Sqrt((wx - _gotoTew) * (wx - _gotoTew) + (wy - _gotoTns) * (wy - _gotoTns));
|
||||
if (d > PortalSnapUnits) continue;
|
||||
Host.TryGetObjectName(id, out string name);
|
||||
name ??= "";
|
||||
bool named = want.Length > 0 && name.Length > 0
|
||||
&& (name.IndexOf(want, StringComparison.OrdinalIgnoreCase) >= 0 || want.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0);
|
||||
if (named && d < bestNamed) { bestNamed = d; nx = wx; ny = wy; nName = name; nId = id; }
|
||||
if (d < bestAny) { bestAny = d; ax = wx; ay = wy; aName = name; aId = id; }
|
||||
}
|
||||
bool haveNamed = bestNamed < double.MaxValue;
|
||||
if (!haveNamed && !(bestAny < 12.0)) return; // an unnamed match only when it's clearly the one
|
||||
double tx = haveNamed ? nx : ax, ty = haveNamed ? ny : ay;
|
||||
double shift = Math.Sqrt((tx - _gotoTew) * (tx - _gotoTew) + (ty - _gotoTns) * (ty - _gotoTns));
|
||||
_gotoTew = tx; _gotoTns = ty;
|
||||
_portalLiveId = haveNamed ? nId : aId;
|
||||
if (!_portalSnapped)
|
||||
{
|
||||
_portalSnapped = true;
|
||||
Host.Log($"[RynthNav] portal: aiming at the live '{(haveNamed ? nName : aName)}' ({shift:F1}u from the planned spot)");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drive into the portal; after PortalTryMs without a teleport back off and run in again, up to
|
||||
/// PortalMaxTries. True when it gave up (the goto has been finished).
|
||||
/// </summary>
|
||||
private bool DriveIntoPortal(double dew, double dns, double d)
|
||||
{
|
||||
long now = NowMs;
|
||||
if (_portalBackoffUntilMs > now)
|
||||
{
|
||||
double away = Math.Atan2(-dew, -dns) * 180.0 / Math.PI;
|
||||
DriveTo(away);
|
||||
lock (_gate) _status = $"backing off to try the portal again ({_portalTries}/{PortalMaxTries})";
|
||||
return false;
|
||||
}
|
||||
if (_portalBackoffUntilMs != 0) { _portalBackoffUntilMs = 0; _portalTryStartMs = now; }
|
||||
|
||||
if (now - _portalTryStartMs > PortalTryMs)
|
||||
{
|
||||
if (_portalTries >= PortalMaxTries)
|
||||
{
|
||||
Host.Log($"[RynthNav] portal did not fire after {_portalTries} tries — stopping");
|
||||
bool entrance = _enterName.Length > 0 && _route != null && _routeIdx >= _route.Count - 1;
|
||||
FinishGoto(entrance ? Entrance.NoTeleportText(_enterName) : $"stopped: the portal '{PortalStepName()}' didn't take you after {_portalTries} tries");
|
||||
return true;
|
||||
}
|
||||
_portalTries++;
|
||||
_portalBackoffUntilMs = now + PortalBackoffMs;
|
||||
Host.Log($"[RynthNav] portal didn't fire yet ({d:F1}u from it): backing off, try {_portalTries}/{PortalMaxTries}");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Close enough: use it, like a click - the game walks you the last few yards and in. Simpler
|
||||
// and surer than running into it (housing neighbourhood portals only fire when used, 10-01
|
||||
// 20:42). Within PortalUseUnits with the live portal seen: stand still and use it every 3 s.
|
||||
if (_portalLiveId != 0 && Host.HasUseObject && d <= PortalUseUnits)
|
||||
{
|
||||
Host.SetAutoRun(false);
|
||||
if (now - _portalLastUseMs > 3000)
|
||||
{
|
||||
_portalLastUseMs = now;
|
||||
Host.UseFor(_portalLiveId, "Goto", $"take the portal '{PortalStepName()}' on the route", UseKind.Asked);
|
||||
Host.Log($"[RynthNav] portal: using '{PortalStepName()}' from {d:F1}u (0x{_portalLiveId:X8})");
|
||||
}
|
||||
lock (_gate) _status = $"taking portal '{Trunc(PortalStepName())}'";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Straight at its centre: a portal fires on contact, so run right into it.
|
||||
double desired = Math.Atan2(dew, dns) * 180.0 / Math.PI;
|
||||
if (desired < 0) desired += 360.0;
|
||||
if (d > PortalContactUnits)
|
||||
{
|
||||
RefreshAvoid(force: false);
|
||||
desired = SteerRoundPortals(desired, Math.Min(10.0, d));
|
||||
}
|
||||
DriveTo(desired);
|
||||
lock (_gate) _status = $"taking portal '{Trunc(PortalStepName())}'";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
91
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settings.cs
Normal file
91
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settings.cs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Avoidance settings, one per kind of thing the walk keeps away from, each on/off with a distance.
|
||||
// Saved in rynthnav.json (beside navDataDir and the portals/recalls switches); /rnav avoid changes them.
|
||||
// portals: keep this many metres from every portal that isn't the step's own (default 4).
|
||||
// walls: push each path corner this many metres away from the building or wall it turns round (default 1).
|
||||
// corners: a path corner counts as reached this close (default 1.5; the old 7 cut every corner).
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private bool _avoidPortals = true;
|
||||
private bool _avoidWalls = true;
|
||||
private double _wallClearance = 1.0;
|
||||
private double _cornerReach = 1.5;
|
||||
private string _builtAvoidKey = "";
|
||||
private bool _preferAphus = true; // the Town Network only by Recall Aphus Lassel when it's known (rynthnav.json preferAphus) // the status JSON's last avoid settings (rebuild when they change)
|
||||
|
||||
private void LoadAvoidSettings()
|
||||
{
|
||||
_avoidPortals = NavDataConfig.ReadSwitch("avoidPortals", true);
|
||||
PortalAvoid.LiveRadius = Math.Clamp(NavDataConfig.ReadNumber("avoidPortalMetres", 4.0), 1.0, 15.0);
|
||||
_avoidWalls = NavDataConfig.ReadSwitch("avoidWalls", true);
|
||||
_wallClearance = Math.Clamp(NavDataConfig.ReadNumber("avoidWallMetres", 1.0), 0.0, 5.0);
|
||||
_cornerReach = Math.Clamp(NavDataConfig.ReadNumber("cornerReachMetres", 1.5), 0.5, 7.0);
|
||||
_preferAphus = NavDataConfig.ReadSwitch("preferAphus", true);
|
||||
}
|
||||
|
||||
private string AvoidSummary() =>
|
||||
$"avoid: portals {(_avoidPortals ? $"on, {PortalAvoid.LiveRadius:0.#} m" : "off")}; " +
|
||||
$"walls {(_avoidWalls ? $"on, corners {_wallClearance:0.#} m out" : "off")}; corners reached at {_cornerReach:0.#} m";
|
||||
|
||||
/// <summary>
|
||||
/// The Town Network entered only by Recall Aphus Lassel, whose landing is a few yards from a
|
||||
/// network portal, when that recall is known: town network portals stand among other portals
|
||||
/// and are harder to take (Tom's call, 10-01). Without the recall, every entry stays.
|
||||
/// </summary>
|
||||
private static HubLinks ViaAphus(HubLinks hub, List<RecallOption> recalls, List<string> notes)
|
||||
{
|
||||
RecallOption? aphus = recalls.Find(r => r.Name.IndexOf("Aphus", StringComparison.OrdinalIgnoreCase) >= 0);
|
||||
if (aphus == null) return hub;
|
||||
var only = new HubLinks { Name = hub.Name, Arrivals = hub.Arrivals };
|
||||
foreach (HubEntry e in hub.Entries)
|
||||
if (Math.Abs(e.SrcNs - aphus.Ns) < 0.3 && Math.Abs(e.SrcEw - aphus.Ew) < 0.3) only.Entries.Add(e);
|
||||
if (only.Entries.Count == 0) return hub; // no entry beside the landing: keep them all
|
||||
only.Exits.AddRange(hub.Exits);
|
||||
notes.Add($"Town Network: entered by {aphus.Name} only (prefer Aphus)");
|
||||
return only;
|
||||
}
|
||||
|
||||
/// <summary>/rnav aphus on|off: the Town Network only by Recall Aphus Lassel when it's known.</summary>
|
||||
private void CmdAphus(string rest)
|
||||
{
|
||||
if (rest is "on" or "off") { _preferAphus = rest == "on"; NavDataConfig.WriteSwitch("preferAphus", _preferAphus); }
|
||||
Say($"Town Network by Recall Aphus Lassel: {(_preferAphus ? "on (when you know it)" : "off (the nearest network portal)")}");
|
||||
}
|
||||
|
||||
/// <summary>/rnav avoid [portals on|off|<m> | walls on|off|<m> | corners <m>]</summary>
|
||||
private void CmdAvoid(string rest)
|
||||
{
|
||||
string[] a = rest.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (a.Length < 2) { Say(AvoidSummary() + " — /rnav avoid portals on|off|<m>, walls on|off|<m>, corners <m>"); return; }
|
||||
string what = a[0].ToLowerInvariant(), val = a[1].ToLowerInvariant();
|
||||
bool isNum = double.TryParse(val, NumberStyles.Float, CultureInfo.InvariantCulture, out double m);
|
||||
switch (what)
|
||||
{
|
||||
case "portals":
|
||||
if (val is "on" or "off") { _avoidPortals = val == "on"; NavDataConfig.WriteSwitch("avoidPortals", _avoidPortals); }
|
||||
else if (isNum) { PortalAvoid.LiveRadius = Math.Clamp(m, 1.0, 15.0); NavDataConfig.WriteNumber("avoidPortalMetres", PortalAvoid.LiveRadius); _avoidPortals = true; NavDataConfig.WriteSwitch("avoidPortals", true); }
|
||||
else { Say("/rnav avoid portals on|off|<metres>"); return; }
|
||||
_avoidAtlas = null; _nextAvoidMs = 0; // rebuild the circles at the new size
|
||||
break;
|
||||
case "walls":
|
||||
if (val is "on" or "off") { _avoidWalls = val == "on"; NavDataConfig.WriteSwitch("avoidWalls", _avoidWalls); }
|
||||
else if (isNum) { _wallClearance = Math.Clamp(m, 0.0, 5.0); NavDataConfig.WriteNumber("avoidWallMetres", _wallClearance); _avoidWalls = true; NavDataConfig.WriteSwitch("avoidWalls", true); }
|
||||
else { Say("/rnav avoid walls on|off|<metres>"); return; }
|
||||
break;
|
||||
case "corners":
|
||||
if (!isNum) { Say("/rnav avoid corners <metres>"); return; }
|
||||
_cornerReach = Math.Clamp(m, 0.5, 7.0); NavDataConfig.WriteNumber("cornerReachMetres", _cornerReach);
|
||||
break;
|
||||
default:
|
||||
Say("/rnav avoid portals on|off|<m>, walls on|off|<m>, corners <m>"); return;
|
||||
}
|
||||
lock (_gotoGate) _gotoPath = null; // re-plan with the new settings
|
||||
Say(AvoidSummary());
|
||||
}
|
||||
}
|
||||
51
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settle.cs
Normal file
51
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settle.cs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// After a recall or a portal: wait for the arrival to finish before the next step, the way
|
||||
// RynthAi's nav does. The position jump comes first and the client's portal space after it
|
||||
// (10-01 20:55: Recall Aphus Lassel jumped at 12.5 s, portal space 12.9-19.4 s). Moving on at the
|
||||
// jump started the Town Network portal step while the recall's portal space was still to come, and
|
||||
// that portal space's end was then taken for the Town Network portal firing.
|
||||
// Settled = out of portal space for SettleQuietMs, after portal space was seen (or SettleNoPortalMs
|
||||
// passed without any).
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const long SettleQuietMs = 1000;
|
||||
private const long SettleNoPortalMs = 3000;
|
||||
private const long SettleGiveUpMs = 60000;
|
||||
|
||||
private bool _settling, _settleSawPortal;
|
||||
private long _settleJumpMs, _settleQuietSince;
|
||||
|
||||
private void BeginSettle()
|
||||
{
|
||||
_settling = true;
|
||||
_settleJumpMs = NowMs;
|
||||
_settleQuietSince = 0;
|
||||
_settleSawPortal = Host.HasIsPortaling && Host.IsPortaling();
|
||||
Host.SetAutoRun(false);
|
||||
lock (_gate) _status = "arriving…";
|
||||
}
|
||||
|
||||
private void StepSettle()
|
||||
{
|
||||
long now = NowMs;
|
||||
bool portaling = Host.HasIsPortaling && Host.IsPortaling();
|
||||
Host.SetAutoRun(false);
|
||||
if (portaling)
|
||||
{
|
||||
_settleSawPortal = true;
|
||||
_settleQuietSince = 0;
|
||||
if (now - _settleJumpMs > SettleGiveUpMs) { _settling = false; FinishGoto("stopped: still in portal space a minute after the teleport"); }
|
||||
return;
|
||||
}
|
||||
if (_settleQuietSince == 0) _settleQuietSince = now;
|
||||
if (now - _settleQuietSince < SettleQuietMs) return;
|
||||
if (!_settleSawPortal && now - _settleJumpMs < SettleNoPortalMs) return;
|
||||
|
||||
_settling = false;
|
||||
_lastLandMs = now; // the portal cooldown counts from the real landing
|
||||
RefreshTiles(CurrentLandblock);
|
||||
Host.Log($"[RynthNav] arrived after the teleport ({(now - _settleJumpMs) / 1000.0:F1} s{(_settleSawPortal ? ", portal space over" : "")}) — next step");
|
||||
AdvanceRoute();
|
||||
}
|
||||
}
|
||||
295
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TownNet.cs
Normal file
295
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TownNet.cs
Normal file
|
|
@ -0,0 +1,295 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// The Town Network on a goto: the route planner takes it like a portal hub (entry portal → an
|
||||
// arrival point inside → the walk to an exit portal → out), and here the walker follows the stored
|
||||
// walk inside (NavData\townnet.json), where there is no navmesh. The entry portal is an ordinary
|
||||
// portal step (StepPortalWait); the hub step is everything from landing inside to landing at the
|
||||
// exit's destination. Without townnet.json (or with one that fails its checks) routes don't use the
|
||||
// network and everything walks as before. Tick thread, except the background load.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const uint StypeLevel = 25, StypeHeritageGroup = 188;
|
||||
private const int HeritageOlthoi = 12, HeritageOlthoiAcid = 13;
|
||||
|
||||
private const double HubOffRouteUnits = HubWalker.OffRouteUnits;
|
||||
private const long HubLandTimeoutMs = 20000; // the entry portal's teleport never lands inside
|
||||
private const long HubPortalSpaceTimeoutMs = 60000; // ...or never ends
|
||||
private const long HubSettleMs = 1500; // out of portal space and inside this long = landed
|
||||
|
||||
private volatile TownNet? _townNet;
|
||||
private volatile string _townNetStatus = "loading…";
|
||||
private HubLinks? _hubLinks;
|
||||
private (TownNet? Net, int Level, bool Olthoi) _hubLinksKey;
|
||||
|
||||
// The hub step being walked (tick thread).
|
||||
private bool _hubActive, _hubLanded, _hubWaitSaid;
|
||||
private long _hubSettleSince; // when the landing settled (inside, out of portal space); 0 = not yet
|
||||
private long _hubStepMs;
|
||||
private HubWalker? _hubWalker;
|
||||
private bool HubIsWaiting => _hubWalker?.Waiting == true;
|
||||
|
||||
private void LoadTownNet()
|
||||
{
|
||||
string path = Path.Combine(NavDataDir, TownNet.FileName);
|
||||
Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path)) { _townNetStatus = "no townnet.json: routes don't use the Town Network"; return; }
|
||||
TownNet? t = TownNet.Parse(File.ReadAllText(path), out string why);
|
||||
if (t == null)
|
||||
{
|
||||
_townNetStatus = $"townnet.json ignored ({why}): routes don't use the Town Network";
|
||||
Host.Log($"[RynthNav] {_townNetStatus}");
|
||||
return;
|
||||
}
|
||||
_townNet = t;
|
||||
_townNetStatus = $"{t.Entries.Count} entry portals, {t.Exits.Count} exits (set {t.SetId[..Math.Min(8, t.SetId.Length)]})";
|
||||
Host.Log($"[RynthNav] Town Network: {t}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_townNetStatus = $"townnet.json failed to load ({ex.GetType().Name}: {ex.Message}): routes don't use the Town Network";
|
||||
Host.Log($"[RynthNav] {_townNetStatus}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The character's level (0 = not known) and whether they're an Olthoi. Tick thread.</summary>
|
||||
private void ReadCharacterRules(out int level, out bool olthoi)
|
||||
{
|
||||
level = 0; olthoi = false;
|
||||
uint me = Host.HasGetPlayerId ? Host.GetPlayerId() : 0;
|
||||
if (me == 0 || !Host.HasGetObjectIntProperty) return;
|
||||
if (Host.TryGetObjectIntProperty(me, StypeLevel, out int lv) && lv > 0) level = lv;
|
||||
if (Host.TryGetObjectIntProperty(me, StypeHeritageGroup, out int h)) olthoi = h is HeritageOlthoi or HeritageOlthoiAcid;
|
||||
}
|
||||
|
||||
/// <summary>The Town Network as this character's route planner sees it; null without townnet.json.</summary>
|
||||
private HubLinks? CurrentHubLinks(List<string>? notes)
|
||||
{
|
||||
TownNet? t = _townNet;
|
||||
if (t == null) return null;
|
||||
ReadCharacterRules(out int level, out bool olthoi);
|
||||
if (notes == null && _hubLinks != null && ReferenceEquals(_hubLinksKey.Net, t) && _hubLinksKey.Level == level && _hubLinksKey.Olthoi == olthoi)
|
||||
return _hubLinks;
|
||||
HubLinks links = t.Links(level, olthoi, notes);
|
||||
_hubLinks = links;
|
||||
_hubLinksKey = (t, level, olthoi);
|
||||
return links;
|
||||
}
|
||||
|
||||
private bool CurrentStepIsHub => _route != null && _routeIdx < _route.Count && _route[_routeIdx].IsHub;
|
||||
|
||||
/// <summary>The exit the route's step <paramref name="i"/> takes (a hub step), or null.</summary>
|
||||
private TownNetExit? HubExitOf(int i)
|
||||
{
|
||||
TownNet? t = _townNet;
|
||||
if (t == null || _route == null || i < 0 || i >= _route.Count || !_route[i].IsHub) return null;
|
||||
int x = _route[i].HubExit;
|
||||
return x >= 0 && x < t.Exits.Count ? t.Exits[x] : null;
|
||||
}
|
||||
|
||||
/// <summary>The next step takes the Town Network (this one walks to its entry portal).</summary>
|
||||
private bool NextStepIsHub => _route != null && _routeIdx + 1 < _route.Count && _route[_routeIdx + 1].IsHub;
|
||||
|
||||
private static string HubWhere(TownNetExit? x) => x?.Where ?? "the next town";
|
||||
|
||||
private void ResetHub()
|
||||
{
|
||||
_hubActive = false; _hubLanded = false; _hubWaitSaid = false; _hubSettleSince = 0;
|
||||
_hubWalker = null;
|
||||
}
|
||||
|
||||
private double LocalX => _wx - ((_cellId >> 24) & 0xFF) * 192.0;
|
||||
private double LocalY => _wy - ((_cellId >> 16) & 0xFF) * 192.0;
|
||||
|
||||
private void HubHalt()
|
||||
{
|
||||
Host.SetAutoRun(false);
|
||||
Host.StopCompletely();
|
||||
}
|
||||
|
||||
/// <summary>One tick of a hub step: wait for the landing inside, walk to the exit, take it.</summary>
|
||||
private void StepHub()
|
||||
{
|
||||
long now = NowMs;
|
||||
TownNet? t = _townNet;
|
||||
TownNetExit? exit = HubExitOf(_routeIdx);
|
||||
if (t == null || exit == null) { FinishGoto("stopped: the Town Network data isn't loaded"); return; }
|
||||
if (!_hubActive)
|
||||
{
|
||||
ResetHub();
|
||||
_hubActive = true;
|
||||
_hubStepMs = now;
|
||||
lock (_gate) _status = $"Town Network → {exit.Where}";
|
||||
}
|
||||
bool portaling = Host.HasIsPortaling && Host.IsPortaling();
|
||||
uint lb = CurrentLandblock;
|
||||
bool inside = t.Contains(lb);
|
||||
|
||||
if (!_hubLanded)
|
||||
{
|
||||
// Landed = inside the network, out of portal space, and settled for HubSettleMs. The
|
||||
// landblock jump comes BEFORE the client's portal space (10-01 20:19: jump at 38.7 s,
|
||||
// portal space 38.9-45.9 s): starting the walk at the jump ran its stuck clock through
|
||||
// seven seconds of portal space. RynthAi's nav waits for portal space to end the same way.
|
||||
if (portaling || !inside) _hubSettleSince = 0;
|
||||
else if (_hubSettleSince == 0) _hubSettleSince = now;
|
||||
if (portaling || !inside || now - _hubSettleSince < HubSettleMs)
|
||||
{
|
||||
HubHalt();
|
||||
if (!portaling && now - _hubStepMs > HubLandTimeoutMs)
|
||||
FinishGoto($"stopped: the portal didn't take you into the Town Network (you're in landblock 0x{lb:X4})");
|
||||
else if (now - _hubStepMs > HubPortalSpaceTimeoutMs)
|
||||
FinishGoto("stopped: still in portal space a minute after taking the Town Network portal");
|
||||
return;
|
||||
}
|
||||
_hubLanded = true;
|
||||
// Normally the landing is now. A goto started inside the network: the last teleport we
|
||||
// saw (none seen: assume the cooldown is long over).
|
||||
long landMs = _routeIdx > 0 ? _hubSettleSince : _trkLastTeleportMs > 0 ? Math.Min(now, _trkLastTeleportMs) : now - HubWalker.CooldownMs;
|
||||
double x = LocalX, y = LocalY;
|
||||
List<TownNetPoint>? way = t.WayTo(_route![_routeIdx].HubExit, x, y, HubOffRouteUnits, out string from);
|
||||
if (way == null)
|
||||
{
|
||||
FinishGoto($"stopped in the Town Network: you landed at {x:F1}, {y:F1}, away from every walk to the {exit.Name}");
|
||||
return;
|
||||
}
|
||||
_hubWalker = new HubWalker(way, landMs, now);
|
||||
Say($"Town Network: walking to the {exit.Name} ({_hubWalker.Length:F0} m).");
|
||||
Host.Log($"[RynthNav] Town Network: landed at {x:F1},{y:F1} (lb 0x{lb:X4}), walk from {from}: {way.Count} points, {_hubWalker.Length:F1} m to {exit.Name}");
|
||||
}
|
||||
|
||||
// The exit portal's teleport (portal space can't last for ever: the walker's limit still runs).
|
||||
if (portaling)
|
||||
{
|
||||
HubHalt();
|
||||
_hubWalker!.Pause(now); // portal space isn't being stuck
|
||||
if (now > _hubWalker!.LimitMs + HubPortalSpaceTimeoutMs) FinishGoto("stopped: still in portal space a minute after the Town Network's exit");
|
||||
return;
|
||||
}
|
||||
if (!inside)
|
||||
{
|
||||
HubHalt();
|
||||
RefreshTiles(lb);
|
||||
if (exit.DestCell != 0 && lb != exit.DestLandblock)
|
||||
{
|
||||
FinishGoto($"stopped: the Town Network sent you to landblock 0x{lb:X4}, not to {exit.Where} (0x{exit.DestLandblock:X4}): wrong portal");
|
||||
return;
|
||||
}
|
||||
Say($"Town Network: took the {exit.Name}.");
|
||||
Host.Log($"[RynthNav] Town Network: took {exit.Name} (lb 0x{lb:X4})");
|
||||
ResetHub();
|
||||
_lastLandMs = NowMs; // the exit's own portal space may still follow (see StepGoto)
|
||||
if (_routeIdx >= _route!.Count - 1) { FinishGoto("arrived"); return; }
|
||||
AdvanceRoute();
|
||||
return;
|
||||
}
|
||||
|
||||
switch (_hubWalker!.Step(LocalX, LocalY, now, out double heading, out string why))
|
||||
{
|
||||
case HubWalker.Act.Run:
|
||||
DriveTo(heading);
|
||||
return;
|
||||
case HubWalker.Act.Hold:
|
||||
HubHalt();
|
||||
if (_hubWalker.JustStartedWaiting && !_hubWaitSaid)
|
||||
{
|
||||
_hubWaitSaid = true;
|
||||
Say($"Town Network: waiting {_hubWalker.WaitSeconds} s for the portal to let you through.");
|
||||
}
|
||||
return;
|
||||
case HubWalker.Act.NoTeleport:
|
||||
{
|
||||
string need = exit.Rules.MinLevel > 0 ? $" (it needs level {exit.Rules.MinLevel})" : " (level or quest requirement?)";
|
||||
FinishGoto($"stopped in the Town Network: the {exit.Name} didn't take you{need}");
|
||||
return;
|
||||
}
|
||||
default:
|
||||
HubStop(exit, why);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void HubStop(TownNetExit exit, string why) =>
|
||||
FinishGoto($"stopped in the Town Network: {why} on the way to the {exit.Name}");
|
||||
|
||||
/// <summary>Metres left on the walk inside (to the exit's centre); -1 before landing.</summary>
|
||||
private double HubLeft() => _hubLanded && _hubWalker != null ? _hubWalker.Left(LocalX, LocalY) : -1;
|
||||
|
||||
/// <summary>The panel's status line during a hub step.</summary>
|
||||
private string HubLine(double left)
|
||||
{
|
||||
TownNetExit? exit = HubExitOf(_routeIdx);
|
||||
string name = exit?.Name ?? "exit portal";
|
||||
if (!_hubLanded) return $"taking the Town Network to {HubWhere(exit)}";
|
||||
if (HubIsWaiting) return $"Town Network: waiting for the {name} to let you through";
|
||||
return $"Town Network: walking to the {name}{(left >= 0 ? $", {left:F0} yd left" : "")}";
|
||||
}
|
||||
|
||||
/// <summary>The route's first Town Network leg, for the goto's start line ("" = none).</summary>
|
||||
private string HubStartText()
|
||||
{
|
||||
if (_route == null) return "";
|
||||
for (int i = 0; i < _route.Count; i++)
|
||||
{
|
||||
if (!_route[i].IsHub) continue;
|
||||
TownNetExit? exit = HubExitOf(i);
|
||||
if (exit == null) return "";
|
||||
if (i == 0) return $"taking the Town Network to {exit.Where} (the {exit.Name})";
|
||||
RouteStep entry = _route[i - 1];
|
||||
return $"taking the Town Network to {exit.Where}: its portal at {NavCoords.Fmt(entry.Ns, entry.Ew)}, then the {exit.Name} inside";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A goto started inside the Town Network: there is no navmesh, so the only way on is an exit.
|
||||
/// Picks the exit that leaves the least to do (the walk inside, the teleport, then what it costs
|
||||
/// from its landing: a route with portals when portal routing is on, else the straight walk).
|
||||
/// Null when no exit is usable.
|
||||
/// </summary>
|
||||
private List<RouteStep>? PlanFromInsideHub(double goalNs, double goalEw, out double est, out int teleports)
|
||||
{
|
||||
est = 0; teleports = 0;
|
||||
TownNet? t = _townNet;
|
||||
HubLinks? links = CurrentHubLinks(null);
|
||||
if (t == null || links == null) return null;
|
||||
double px = LocalX, py = LocalY;
|
||||
List<RouteStep>? best = null;
|
||||
double bestCost = double.MaxValue;
|
||||
int bestUsed = 0;
|
||||
if (_portalsEnabled) EnsurePortalsLoaded();
|
||||
foreach (HubExit hx in links.Exits)
|
||||
{
|
||||
List<TownNetPoint>? way = t.WayTo(hx.Id, px, py, HubOffRouteUnits, out _);
|
||||
if (way == null) continue;
|
||||
double inside = TownNet.PathLength(way, 0) + PortalRoute.PortalPenaltyUnits;
|
||||
List<RouteStep> rest;
|
||||
double restCost;
|
||||
int used = 0;
|
||||
if (_portalsEnabled && _portals is { Count: > 0 })
|
||||
rest = PortalRoute.Plan(_portals, null, hx.DstNs, hx.DstEw, goalNs, goalEw, out restCost, out used);
|
||||
else
|
||||
{
|
||||
restCost = NavCoords.Distance(hx.DstNs, hx.DstEw, goalNs, goalEw);
|
||||
rest = new List<RouteStep> { new(goalNs, goalEw, false, false, "walk") };
|
||||
}
|
||||
if (inside + restCost >= bestCost) continue;
|
||||
bestCost = inside + restCost;
|
||||
best = new List<RouteStep> { RouteStep.Hub(hx.DstNs, hx.DstEw, hx.Name, hx.Id) };
|
||||
best.AddRange(rest);
|
||||
bestUsed = used + 1;
|
||||
}
|
||||
est = bestCost;
|
||||
teleports = bestUsed;
|
||||
return best;
|
||||
}
|
||||
}
|
||||
1054
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs
Normal file
1054
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs
Normal file
File diff suppressed because it is too large
Load diff
50
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Turn.cs
Normal file
50
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Turn.cs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Turning the way RynthAi's nav does it (NavigationEngine.DriveHeading, mode 0 heading servo):
|
||||
// the heading is slewed toward the target at a capped rate rather than snapped onto it, and a big
|
||||
// turn is made standing (autorun off) and the run resumes once lined up. The numbers are RynthAi's
|
||||
// defaults (Nav Turn Rate 270 deg/s, Stop Turn Angle 20, Resume Turn Angle 10, Dead Zone 4).
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const double TurnRateDegPerSec = 270.0;
|
||||
private const double TurnDeadZoneDeg = 4.0;
|
||||
private const double StopTurnAngleDeg = 20.0;
|
||||
private const double ResumeTurnAngleDeg = 10.0;
|
||||
|
||||
private bool _turnInPlace;
|
||||
private long _lastTurnMs;
|
||||
|
||||
/// <summary>Turn toward <paramref name="desiredDeg"/> (0 = north, clockwise) and run when lined up.</summary>
|
||||
private void DriveTo(double desiredDeg)
|
||||
{
|
||||
desiredDeg = ((desiredDeg % 360.0) + 360.0) % 360.0;
|
||||
double current = desiredDeg;
|
||||
if (Host.TryGetPlayerPose(out _, out _, out _, out _, out float qw, out _, out _, out float qz))
|
||||
current = (-(2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) + 720.0) % 360.0;
|
||||
|
||||
double error = desiredDeg - current;
|
||||
if (error > 180.0) error -= 360.0; else if (error < -180.0) error += 360.0;
|
||||
double abs = Math.Abs(error);
|
||||
|
||||
long now = NowMs;
|
||||
double dt = _lastTurnMs == 0 ? 33.0 : Math.Clamp(now - _lastTurnMs, 10, 200);
|
||||
_lastTurnMs = now;
|
||||
double maxStep = TurnRateDegPerSec * dt / 1000.0;
|
||||
|
||||
// Run gate with hysteresis: stop to turn when far off, run again once close.
|
||||
if (_turnInPlace) { if (abs <= ResumeTurnAngleDeg) _turnInPlace = false; }
|
||||
else if (abs > StopTurnAngleDeg) _turnInPlace = true;
|
||||
|
||||
if (abs > TurnDeadZoneDeg)
|
||||
{
|
||||
double next = current + Math.Clamp(error, -maxStep, maxStep);
|
||||
Host.TurnToHeading((float)(((next % 360.0) + 360.0) % 360.0));
|
||||
}
|
||||
Host.SetAutoRun(!_turnInPlace);
|
||||
}
|
||||
|
||||
/// <summary>A fresh start for the turn servo (a new goto, a teleport).</summary>
|
||||
private void ResetTurn() { _turnInPlace = false; _lastTurnMs = 0; }
|
||||
}
|
||||
69
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Wand.cs
Normal file
69
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Wand.cs
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// A recall spell wants a wand in hand. Done the way RynthAi equips its wand: a caster already in
|
||||
// hand is used as it is; otherwise whatever is in the hands (a weapon, a shield) goes into the pack
|
||||
// first, then a caster from the pack is wielded into the held slot, and only then the magic stance.
|
||||
// Before, the stance was tried bare-handed for 6 s and then the caster "used" from the pack, which
|
||||
// the server refused while a weapon was still wielded (10-02 18:45, WeenieError 0x0468).
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const int HeldSlot = 0x01000000; // where a caster is wielded
|
||||
// Wield slots that hold something in your hands: melee, shield, missile, held, two-handed.
|
||||
private const uint HandSlots = 0x00100000 | 0x00200000 | 0x00400000 | 0x01000000 | 0x02000000;
|
||||
private const long WandStepMs = 1500; // between one move or wield and the next
|
||||
private const long WandGiveUpMs = 15000; // then cast with what's in hand
|
||||
|
||||
private long _wandStartMs, _wandLastActMs;
|
||||
private bool _wandReady;
|
||||
|
||||
private void BeginWand() { _wandReady = false; _wandStartMs = NowMs; _wandLastActMs = 0; }
|
||||
|
||||
/// <summary>True once a caster is in hand (or there is none to wield, or it's taking too long).</summary>
|
||||
private bool PrepareWand(long now)
|
||||
{
|
||||
if (_wandReady) return true;
|
||||
uint me = Host.HasGetPlayerId ? Host.GetPlayerId() : 0;
|
||||
if (me == 0 || !Host.HasGetLiveObjectIds) return _wandReady = true;
|
||||
if (now - _wandStartMs > WandGiveUpMs)
|
||||
{
|
||||
Host.Log("[RynthNav] recall: couldn't get a wand in hand in 15 s — casting with what's in hand");
|
||||
return _wandReady = true;
|
||||
}
|
||||
|
||||
uint inHand = 0, caster = 0, packCaster = 0;
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!Host.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out uint loc)) continue;
|
||||
bool isCaster = Host.TryGetItemType(id, out uint type) && (type & ItemTypeCaster) != 0;
|
||||
if (wielder == me && (loc & HandSlots) != 0)
|
||||
{
|
||||
if (isCaster) caster = id; else if (inHand == 0) inHand = id;
|
||||
}
|
||||
else if (isCaster && packCaster == 0)
|
||||
{
|
||||
bool mine = container == me
|
||||
|| (container != 0 && Host.TryGetObjectOwnershipInfo(container, out uint outer, out _, out _) && outer == me);
|
||||
if (mine) packCaster = id;
|
||||
}
|
||||
}
|
||||
if (caster != 0) return _wandReady = true; // a wand is in hand
|
||||
if (packCaster == 0) return _wandReady = true; // none carried: bare hands it is
|
||||
if (now - _wandLastActMs < WandStepMs) return false;
|
||||
_wandLastActMs = now;
|
||||
|
||||
if (inHand != 0)
|
||||
{
|
||||
if (Host.HasMoveItemInternal && Host.MoveItemInternal(inHand, me, 0, 1))
|
||||
Host.Log($"[RynthNav] recall: putting 0x{inHand:X8} away to wield a wand");
|
||||
else return _wandReady = true;
|
||||
return false;
|
||||
}
|
||||
bool sent = Host.HasWieldItem ? Host.WieldItem(packCaster, HeldSlot) : Host.HasUseObject && Host.UseFor(packCaster, "Recall", "wield a wand for the recall spell", UseKind.Asked);
|
||||
Host.Log($"[RynthNav] recall: wielding wand 0x{packCaster:X8}{(sent ? "" : " (not sent)")}");
|
||||
if (!sent) return _wandReady = true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
541
Plugins/RynthCore.Plugin.RynthNav/TownNet.cs
Normal file
541
Plugins/RynthCore.Plugin.RynthNav/TownNet.cs
Normal file
|
|
@ -0,0 +1,541 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// The Town Network (NavData\townnet.json, made by RynthCore's tools\navdata\gen_townnet.py from the
|
||||
// world database plus RynthNav.TownNet's walks from the dats): the "Portal to Town Network" in many
|
||||
// towns, the arrival points inside, the exit portal to each town, and the walk from every arrival
|
||||
// to every exit. RynthNav's route planner uses it as a hub (PortalRoute's HubLinks) and the walker
|
||||
// follows the stored walks inside, where there is no navmesh. Read-only once loaded.
|
||||
// No host calls: the offline tests compile this file.
|
||||
|
||||
internal sealed class TownNetPoint
|
||||
{
|
||||
public uint Cell;
|
||||
public double X, Y, Z;
|
||||
}
|
||||
|
||||
internal sealed class TownNetArrival
|
||||
{
|
||||
public string Id = "";
|
||||
public uint Cell;
|
||||
public double X, Y, Z;
|
||||
}
|
||||
|
||||
/// <summary>Restrictions the server checks before it lets a character through a portal.</summary>
|
||||
internal sealed class TownNetRules
|
||||
{
|
||||
public int MinLevel, MaxLevel, AccountRequirements;
|
||||
public string Quest = "";
|
||||
public bool Closed, NoOlthoi, OnlyOlthoi, AdvocateOnly, NoPk, NoPkLite, NoNpk, NoVitae, NoNewAccounts;
|
||||
|
||||
/// <summary>
|
||||
/// Why this character can't use the portal ("" = it can). Level 0 = not known yet: a portal with a
|
||||
/// level rule is then left out, since it can't be shown to be open. Rules the plugin can't check
|
||||
/// (quests, player killer status, vitae) leave the portal out too.
|
||||
/// </summary>
|
||||
public string Blocks(int level, bool olthoi)
|
||||
{
|
||||
if (Closed) return "closed";
|
||||
if (AdvocateOnly) return "advocates only";
|
||||
if (Quest.Length > 0) return "needs a quest flag";
|
||||
if (olthoi && NoOlthoi) return "no Olthoi";
|
||||
if (!olthoi && OnlyOlthoi) return "Olthoi only";
|
||||
if (MinLevel > 0 || MaxLevel > 0)
|
||||
{
|
||||
if (level <= 0) return MinLevel > 0 ? $"needs level {MinLevel} (your level isn't known yet)" : $"level {MaxLevel} or lower (your level isn't known yet)";
|
||||
if (MinLevel > 0 && level < MinLevel) return $"needs level {MinLevel}";
|
||||
if (MaxLevel > 0 && level > MaxLevel) return $"level {MaxLevel} or lower";
|
||||
}
|
||||
if (NoPk || NoPkLite || NoNpk) return "player killer rules";
|
||||
if (NoVitae) return "no vitae";
|
||||
if (NoNewAccounts || AccountRequirements > 1) return "account rules";
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class TownNetEntry
|
||||
{
|
||||
public string Guid = "", Name = "", Place = "", Town = "";
|
||||
public bool OnMap;
|
||||
public double Ns, Ew;
|
||||
public int Arrival = -1;
|
||||
public readonly TownNetRules Rules = new();
|
||||
}
|
||||
|
||||
internal sealed class TownNetExit
|
||||
{
|
||||
public string Guid = "", Name = "", Label = "", DestTown = "", DestPlace = "";
|
||||
public uint Cell;
|
||||
public double X, Y, Z;
|
||||
public bool DestOnMap;
|
||||
public double DestNs, DestEw;
|
||||
public uint DestCell;
|
||||
public readonly TownNetRules Rules = new();
|
||||
|
||||
/// <summary>"Yaraq" for the Portal to Yaraq: the town or place it leads to.</summary>
|
||||
public string Where => Label.Length > 0 ? Label : DestTown.Length > 0 ? DestTown : Name;
|
||||
public uint DestLandblock => DestCell >> 16;
|
||||
}
|
||||
|
||||
internal sealed class TownNetWalk
|
||||
{
|
||||
public int Arrival, Exit;
|
||||
public double Length;
|
||||
/// <summary>The least room on the walk from the walker's centre to a wall or object (m); 0 = not given.</summary>
|
||||
public double MinClear;
|
||||
public TownNetPoint[] Points = Array.Empty<TownNetPoint>();
|
||||
}
|
||||
|
||||
internal sealed class TownNet
|
||||
{
|
||||
public const string FileName = "townnet.json";
|
||||
public const int SupportedVersion = 1;
|
||||
/// <summary>Landing within this of an arrival point counts as landing there (metres = yards here).</summary>
|
||||
public const double ArrivalNearUnits = 3.0;
|
||||
|
||||
public int Version;
|
||||
public string SetId = "", Generated = "";
|
||||
/// <summary>The network's landblocks (0x0007 on our data).</summary>
|
||||
public readonly HashSet<uint> Landblocks = new();
|
||||
public readonly List<TownNetArrival> Arrivals = new();
|
||||
public readonly List<TownNetEntry> Entries = new();
|
||||
public readonly List<TownNetExit> Exits = new();
|
||||
public readonly List<TownNetWalk> Walks = new();
|
||||
private readonly Dictionary<(int, int), TownNetWalk> _walk = new();
|
||||
|
||||
public bool Contains(uint landblock) => Landblocks.Contains(landblock);
|
||||
public TownNetWalk? Walk(int arrival, int exit) => _walk.TryGetValue((arrival, exit), out var w) ? w : null;
|
||||
|
||||
public override string ToString() =>
|
||||
$"{Entries.Count} entry portals, {Exits.Count} exits, {Walks.Count} walks (set {SetId})";
|
||||
|
||||
/// <summary>
|
||||
/// The first 16 hex digits of the SHA-256 of the text without its "setId" and "generated" lines,
|
||||
/// carriage returns dropped: the same id gen_townnet.py and RynthNav.TownNet write.
|
||||
/// </summary>
|
||||
public static string ComputeSetId(string text)
|
||||
{
|
||||
var kept = new List<string>();
|
||||
foreach (string l in text.Replace("\r", "").Split('\n'))
|
||||
if (!l.StartsWith(" \"setId\":", StringComparison.Ordinal) && !l.StartsWith(" \"generated\":", StringComparison.Ordinal))
|
||||
kept.Add(l);
|
||||
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(string.Join("\n", kept)));
|
||||
return Convert.ToHexString(hash, 0, 8).ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads townnet.json. Null, with <paramref name="why"/>, when it can't be used: another version,
|
||||
/// a set id that doesn't match the contents (edited or damaged), or no walks. Routing then works
|
||||
/// as if there were no file.
|
||||
/// </summary>
|
||||
public static TownNet? Parse(string text, out string why)
|
||||
{
|
||||
why = "";
|
||||
var t = new TownNet();
|
||||
using JsonDocument doc = JsonDocument.Parse(text, new JsonDocumentOptions { AllowTrailingCommas = true });
|
||||
JsonElement r = doc.RootElement;
|
||||
if (r.ValueKind != JsonValueKind.Object) { why = "not a townnet.json"; return null; }
|
||||
t.Version = Int(r, "version");
|
||||
if (t.Version != SupportedVersion) { why = $"version {t.Version}, this RynthNav reads version {SupportedVersion}"; return null; }
|
||||
t.SetId = Str(r, "setId");
|
||||
t.Generated = Str(r, "generated");
|
||||
string actual = ComputeSetId(text);
|
||||
if (t.SetId.Length == 0 || !t.SetId.Equals(actual, StringComparison.OrdinalIgnoreCase))
|
||||
{ why = $"its set id ({(t.SetId.Length > 0 ? t.SetId : "none")}) doesn't match its contents ({actual}): edited or damaged"; return null; }
|
||||
|
||||
if (r.TryGetProperty("landblocks", out var lbs) && lbs.ValueKind == JsonValueKind.Array)
|
||||
foreach (var e in lbs.EnumerateArray())
|
||||
if (e.ValueKind == JsonValueKind.String && uint.TryParse(e.GetString(), NumberStyles.HexNumber, null, out uint lb)) t.Landblocks.Add(lb);
|
||||
|
||||
var arrivalIndex = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (var e in Arr(r, "arrivals"))
|
||||
{
|
||||
var a = new TownNetArrival { Id = Str(e, "id"), Cell = Hex(e, "cell"), X = Num(e, "x"), Y = Num(e, "y"), Z = Num(e, "z") };
|
||||
arrivalIndex[a.Id] = t.Arrivals.Count;
|
||||
t.Arrivals.Add(a);
|
||||
t.Landblocks.Add(a.Cell >> 16);
|
||||
}
|
||||
foreach (var e in Arr(r, "entries"))
|
||||
{
|
||||
var en = new TownNetEntry { Guid = Str(e, "guid"), Name = Str(e, "name"), Place = Str(e, "place") };
|
||||
en.OnMap = TryNum(e, "ns", out en.Ns) & TryNum(e, "ew", out en.Ew);
|
||||
if (e.TryGetProperty("town", out var town) && town.ValueKind == JsonValueKind.Object) en.Town = Str(town, "name");
|
||||
en.Arrival = arrivalIndex.TryGetValue(Str(e, "arrival"), out int ai) ? ai : -1;
|
||||
ReadRules(e, en.Rules);
|
||||
t.Entries.Add(en);
|
||||
}
|
||||
var exitIndex = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (var e in Arr(r, "exits"))
|
||||
{
|
||||
var x = new TownNetExit
|
||||
{
|
||||
Guid = Str(e, "guid"), Name = Str(e, "name"), Label = Str(e, "label"),
|
||||
Cell = Hex(e, "cell"), X = Num(e, "x"), Y = Num(e, "y"), Z = Num(e, "z"),
|
||||
};
|
||||
if (e.TryGetProperty("dest", out var d) && d.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
x.DestCell = Hex(d, "cell");
|
||||
x.DestPlace = Str(d, "place");
|
||||
x.DestOnMap = TryNum(d, "ns", out x.DestNs) & TryNum(d, "ew", out x.DestEw);
|
||||
if (d.TryGetProperty("town", out var town) && town.ValueKind == JsonValueKind.Object) x.DestTown = Str(town, "name");
|
||||
}
|
||||
ReadRules(e, x.Rules);
|
||||
exitIndex[x.Guid] = t.Exits.Count;
|
||||
t.Exits.Add(x);
|
||||
}
|
||||
foreach (var e in Arr(r, "walks"))
|
||||
{
|
||||
if (!arrivalIndex.TryGetValue(Str(e, "from"), out int a) || !exitIndex.TryGetValue(Str(e, "to"), out int x)) continue;
|
||||
var pts = new List<TownNetPoint>();
|
||||
if (e.TryGetProperty("points", out var ps) && ps.ValueKind == JsonValueKind.Array)
|
||||
foreach (var p in ps.EnumerateArray())
|
||||
{
|
||||
if (p.ValueKind != JsonValueKind.Array || p.GetArrayLength() < 3) continue;
|
||||
var pt = new TownNetPoint
|
||||
{
|
||||
Cell = p[0].ValueKind == JsonValueKind.String && uint.TryParse(p[0].GetString(), NumberStyles.HexNumber, null, out uint c) ? c : 0,
|
||||
X = p[1].GetDouble(), Y = p[2].GetDouble(), Z = p.GetArrayLength() > 3 ? p[3].GetDouble() : 0,
|
||||
};
|
||||
pts.Add(pt);
|
||||
}
|
||||
if (pts.Count < 2) continue;
|
||||
var w = new TownNetWalk { Arrival = a, Exit = x, Length = Num(e, "length"), MinClear = Num(e, "minClear"), Points = pts.ToArray() };
|
||||
if (w.Length <= 0) w.Length = PathLength(w.Points, 0);
|
||||
t.Walks.Add(w);
|
||||
t._walk[(a, x)] = w;
|
||||
}
|
||||
if (t.Arrivals.Count == 0 || t.Exits.Count == 0 || t.Walks.Count == 0) { why = "it has no arrivals, exits or walks"; return null; }
|
||||
return t;
|
||||
}
|
||||
|
||||
private static void ReadRules(JsonElement e, TownNetRules r)
|
||||
{
|
||||
r.MinLevel = Int(e, "minLevel");
|
||||
r.MaxLevel = Int(e, "maxLevel");
|
||||
r.AccountRequirements = Int(e, "accountRequirements");
|
||||
r.Quest = Str(e, "quest");
|
||||
r.Closed = Bool(e, "closed");
|
||||
r.NoOlthoi = Bool(e, "noOlthoi");
|
||||
r.OnlyOlthoi = Bool(e, "onlyOlthoi");
|
||||
r.AdvocateOnly = Bool(e, "advocateOnly");
|
||||
r.NoPk = Bool(e, "noPk");
|
||||
r.NoPkLite = Bool(e, "noPkLite");
|
||||
r.NoNpk = Bool(e, "noNpk");
|
||||
r.NoVitae = Bool(e, "noVitae");
|
||||
r.NoNewAccounts = Bool(e, "noNewAccounts");
|
||||
}
|
||||
|
||||
// ── The planner's view ───────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The network as the route planner sees it, for a character of <paramref name="level"/> (0 = not
|
||||
/// known) who is (or isn't) an Olthoi: the entry portals on the map, the exits that lead onto the
|
||||
/// map, and the walks inside. A portal the character can't use is left out, with a note. Entries
|
||||
/// and exits in dungeons have no map position and are left out too (silently: they never could
|
||||
/// be on a map route). <see cref="HubExit.Id"/> is the index into <see cref="Exits"/>.
|
||||
/// </summary>
|
||||
public HubLinks Links(int level, bool olthoi, List<string>? notes)
|
||||
{
|
||||
var hub = new HubLinks { Name = "Town Network", Arrivals = Arrivals.Count };
|
||||
int entriesBlocked = 0;
|
||||
string entryWhy = "";
|
||||
foreach (TownNetEntry e in Entries)
|
||||
{
|
||||
if (!e.OnMap || e.Arrival < 0) continue;
|
||||
string why = e.Rules.Blocks(level, olthoi);
|
||||
if (why.Length > 0) { entriesBlocked++; entryWhy = why; continue; }
|
||||
hub.Entries.Add(new HubEntry(e.Ns, e.Ew, e.Arrival, e.Name));
|
||||
}
|
||||
if (entriesBlocked > 0)
|
||||
notes?.Add($"Town Network: {entriesBlocked} entry portal(s) left out ({entryWhy}).");
|
||||
for (int x = 0; x < Exits.Count; x++)
|
||||
{
|
||||
TownNetExit ex = Exits[x];
|
||||
if (!ex.DestOnMap) continue;
|
||||
string why = ex.Rules.Blocks(level, olthoi);
|
||||
if (why.Length > 0) { notes?.Add($"Town Network: {ex.Name} left out ({why})."); continue; }
|
||||
var walk = new double[Arrivals.Count];
|
||||
bool any = false;
|
||||
for (int a = 0; a < Arrivals.Count; a++)
|
||||
{
|
||||
TownNetWalk? w = Walk(a, x);
|
||||
walk[a] = w != null ? w.Length : double.NaN;
|
||||
any |= w != null;
|
||||
}
|
||||
if (!any) continue;
|
||||
hub.Exits.Add(new HubExit(ex.DestNs, ex.DestEw, ex.Name, x, walk));
|
||||
}
|
||||
return hub;
|
||||
}
|
||||
|
||||
// ── The walker's view (landblock coordinates inside the network) ─────────
|
||||
|
||||
/// <summary>The arrival within <see cref="ArrivalNearUnits"/> of (x, y), or -1.</summary>
|
||||
public int ArrivalNear(double x, double y)
|
||||
{
|
||||
int best = -1;
|
||||
double bestD = ArrivalNearUnits;
|
||||
for (int i = 0; i < Arrivals.Count; i++)
|
||||
{
|
||||
double d = Math.Sqrt((Arrivals[i].X - x) * (Arrivals[i].X - x) + (Arrivals[i].Y - y) * (Arrivals[i].Y - y));
|
||||
if (d <= bestD) { best = i; bestD = d; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The way from (x, y) to exit <paramref name="exit"/>: the walk from the arrival you stand on,
|
||||
/// else the walk (from any arrival) that passes nearest, joined at that point. The first point
|
||||
/// returned is where you stand. Null when no walk to that exit comes within
|
||||
/// <paramref name="maxOff"/> of you.
|
||||
/// </summary>
|
||||
public List<TownNetPoint>? WayTo(int exit, double x, double y, double maxOff, out string from)
|
||||
{
|
||||
from = "";
|
||||
int a = ArrivalNear(x, y);
|
||||
TownNetWalk? w = a >= 0 ? Walk(a, exit) : null;
|
||||
if (w != null)
|
||||
{
|
||||
from = Arrivals[a].Id;
|
||||
var list = new List<TownNetPoint> { new() { Cell = w.Points[0].Cell, X = x, Y = y, Z = w.Points[0].Z } };
|
||||
for (int i = 1; i < w.Points.Length; i++) list.Add(w.Points[i]);
|
||||
return list;
|
||||
}
|
||||
TownNetWalk? best = null;
|
||||
int bestSeg = -1;
|
||||
double bestD = maxOff;
|
||||
foreach (TownNetWalk cand in Walks)
|
||||
{
|
||||
if (cand.Exit != exit) continue;
|
||||
for (int i = 1; i < cand.Points.Length; i++)
|
||||
{
|
||||
double d = SegmentDistance(x, y, cand.Points[i - 1], cand.Points[i], out _);
|
||||
if (d <= bestD) { bestD = d; best = cand; bestSeg = i; }
|
||||
}
|
||||
}
|
||||
if (best == null) return null;
|
||||
from = "the nearest walk (from " + Arrivals[best.Arrival].Id + ")";
|
||||
var way = new List<TownNetPoint> { new() { Cell = best.Points[bestSeg - 1].Cell, X = x, Y = y, Z = best.Points[bestSeg - 1].Z } };
|
||||
for (int i = bestSeg; i < best.Points.Length; i++) way.Add(best.Points[i]);
|
||||
return way;
|
||||
}
|
||||
|
||||
/// <summary>Distance from (x, y) to the segment a→b, and how far along it the nearest point is (0..1).</summary>
|
||||
public static double SegmentDistance(double x, double y, TownNetPoint a, TownNetPoint b, out double t)
|
||||
{
|
||||
double dx = b.X - a.X, dy = b.Y - a.Y, len2 = dx * dx + dy * dy;
|
||||
t = len2 < 1e-9 ? 1 : Math.Clamp(((x - a.X) * dx + (y - a.Y) * dy) / len2, 0, 1);
|
||||
double px = a.X + dx * t - x, py = a.Y + dy * t - y;
|
||||
return Math.Sqrt(px * px + py * py);
|
||||
}
|
||||
|
||||
/// <summary>Straight-segment length of <paramref name="pts"/> from index <paramref name="from"/> on.</summary>
|
||||
public static double PathLength(IReadOnlyList<TownNetPoint> pts, int from)
|
||||
{
|
||||
double len = 0;
|
||||
for (int i = Math.Max(1, from + 1); i < pts.Count; i++)
|
||||
len += Math.Sqrt((pts[i].X - pts[i - 1].X) * (pts[i].X - pts[i - 1].X) + (pts[i].Y - pts[i - 1].Y) * (pts[i].Y - pts[i - 1].Y));
|
||||
return len;
|
||||
}
|
||||
|
||||
// ── JSON helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
private static IEnumerable<JsonElement> Arr(JsonElement e, string name)
|
||||
{
|
||||
if (!e.TryGetProperty(name, out var v) || v.ValueKind != JsonValueKind.Array) yield break;
|
||||
foreach (var x in v.EnumerateArray()) if (x.ValueKind == JsonValueKind.Object) yield return x;
|
||||
}
|
||||
|
||||
private static string Str(JsonElement e, string name) =>
|
||||
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
|
||||
|
||||
private static int Int(JsonElement e, string name) =>
|
||||
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : 0;
|
||||
|
||||
private static bool Bool(JsonElement e, string name) =>
|
||||
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.True;
|
||||
|
||||
private static double Num(JsonElement e, string name) => TryNum(e, name, out double d) ? d : 0;
|
||||
|
||||
private static bool TryNum(JsonElement e, string name, out double d)
|
||||
{
|
||||
d = 0;
|
||||
return e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out d);
|
||||
}
|
||||
|
||||
private static uint Hex(JsonElement e, string name) =>
|
||||
uint.TryParse(Str(e, name), NumberStyles.HexNumber, null, out uint v) ? v : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Follows one stored walk inside the Town Network: straight segments, steering at the next waypoint
|
||||
/// every tick; a waypoint counts once within 0.5 m or passed along its segment (never circled); more
|
||||
/// than 2 m off the line steers back to it, more than 6 m stops. It holds short of the exit portal
|
||||
/// until 4 s after landing (ACE refuses a portal within 3.5 s of a teleport), then walks into its
|
||||
/// centre; standing there with no teleport it backs off and walks in once more. No 0.5 m of progress
|
||||
/// in 3 s, or more than length ÷ 3 + 10 s (plus the hold) in all, stops with a reason. The teleport
|
||||
/// itself is the caller's to notice. Host-free: the route tests drive it.
|
||||
/// </summary>
|
||||
internal sealed class HubWalker
|
||||
{
|
||||
public const double WaypointUnits = 0.5;
|
||||
/// <summary>
|
||||
/// A corner is cut by about (radius × sin of the turn); the walks keep 0.15 m of spare room, so a
|
||||
/// sharp corner counts as reached closer in: radius = min(0.5, MaxCutUnits / sin(turn)).
|
||||
/// </summary>
|
||||
public const double MaxCutUnits = 0.1;
|
||||
public const double SteerBackUnits = 2.0;
|
||||
public const double OffRouteUnits = 6.0;
|
||||
/// <summary>Hold this far from the exit's centre (portal reach 1.36 m + body 0.48 m + room) during the cooldown.</summary>
|
||||
public const double HoldUnits = 2.6;
|
||||
public const double BackOffUnits = 3.0;
|
||||
public const double StuckProgress = 0.5;
|
||||
public const long CooldownMs = 4000;
|
||||
public const long StuckMs = 8000; // 3 s stopped a walk that had only just landed (10-01 20:13: the client holds you a moment after portal space; a turn in place takes time too)
|
||||
public const long TouchWaitMs = 3000;
|
||||
|
||||
public enum Act { Run, Hold, Stop, NoTeleport }
|
||||
|
||||
private readonly List<TownNetPoint> _way;
|
||||
private readonly long _landMs;
|
||||
private int _idx = 1;
|
||||
private double _best = double.MaxValue;
|
||||
private long _bestMs, _atPortalMs;
|
||||
private bool _retried, _backing;
|
||||
private readonly double[] _radius; // per waypoint: how close counts as reached (sharper turn, closer)
|
||||
|
||||
public double Length { get; }
|
||||
public long LimitMs { get; }
|
||||
public bool Waiting { get; private set; }
|
||||
/// <summary>True on the tick the cooldown hold began (say so once).</summary>
|
||||
public bool JustStartedWaiting { get; private set; }
|
||||
/// <summary>Whole seconds of cooldown left when the hold began.</summary>
|
||||
public long WaitSeconds { get; private set; }
|
||||
public int Index => _idx;
|
||||
public int Count => _way.Count;
|
||||
|
||||
/// <param name="way">From where you stand to the exit portal's centre (TownNet.WayTo).</param>
|
||||
/// <param name="landMs">When you landed in the network (the cooldown counts from it).</param>
|
||||
public HubWalker(List<TownNetPoint> way, long landMs, long nowMs)
|
||||
{
|
||||
if (way.Count < 2) throw new ArgumentException("a walk needs two points", nameof(way));
|
||||
_way = way;
|
||||
_landMs = landMs;
|
||||
_bestMs = nowMs;
|
||||
Length = TownNet.PathLength(way, 0);
|
||||
_radius = new double[way.Count];
|
||||
for (int i = 0; i < way.Count; i++)
|
||||
{
|
||||
_radius[i] = WaypointUnits;
|
||||
if (i == 0 || i == way.Count - 1) continue;
|
||||
double ax = way[i].X - way[i - 1].X, ay = way[i].Y - way[i - 1].Y, bx = way[i + 1].X - way[i].X, by = way[i + 1].Y - way[i].Y;
|
||||
double la = Math.Sqrt(ax * ax + ay * ay), lb = Math.Sqrt(bx * bx + by * by);
|
||||
if (la < 1e-6 || lb < 1e-6) continue;
|
||||
double cos = (ax * bx + ay * by) / (la * lb);
|
||||
double sin = cos < 0 ? 1.0 : Math.Sqrt(Math.Max(0, 1 - cos * cos)); // past 90 degrees: as sharp as it gets
|
||||
if (sin > 1e-6) _radius[i] = Math.Min(WaypointUnits, Math.Max(0.05, MaxCutUnits / sin));
|
||||
}
|
||||
LimitMs = nowMs + (long)((Length / 3.0 + 10.0) * 1000) + CooldownMs;
|
||||
}
|
||||
|
||||
/// <summary>Metres left to the exit's centre from (x, y).</summary>
|
||||
public double Left(double x, double y)
|
||||
{
|
||||
TownNetPoint t = _way[_idx];
|
||||
return Math.Sqrt((t.X - x) * (t.X - x) + (t.Y - y) * (t.Y - y)) + TownNet.PathLength(_way, _idx);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One tick at (x, y): Run with <paramref name="heading"/> (degrees, 0 = north, 90 = east), Hold
|
||||
/// (stand still), Stop (<paramref name="why"/>), or NoTeleport (stood on the exit twice and
|
||||
/// nothing happened).
|
||||
/// </summary>
|
||||
/// <summary>Not moving through no fault of the walk (portal space): the stuck clock starts again.</summary>
|
||||
public void Pause(long now) { _bestMs = now; _best = double.MaxValue; }
|
||||
|
||||
public Act Step(double x, double y, long now, out double heading, out string why)
|
||||
{
|
||||
heading = 0; why = "";
|
||||
JustStartedWaiting = false;
|
||||
if (now > LimitMs) { why = "it took too long"; return Act.Stop; }
|
||||
int last = _way.Count - 1;
|
||||
|
||||
while (_idx < last)
|
||||
{
|
||||
TownNetPoint b = _way[_idx];
|
||||
double db = Math.Sqrt((b.X - x) * (b.X - x) + (b.Y - y) * (b.Y - y));
|
||||
TownNet.SegmentDistance(x, y, _way[_idx - 1], b, out double along);
|
||||
if (db >= _radius[_idx] && along < 1.0) break;
|
||||
_idx++;
|
||||
_best = double.MaxValue; _bestMs = now;
|
||||
}
|
||||
TownNetPoint tgt = _way[_idx], prev = _way[_idx - 1];
|
||||
double off = TownNet.SegmentDistance(x, y, prev, tgt, out double tSeg);
|
||||
if (off > OffRouteUnits) { why = $"{off:F1} m off the way"; return Act.Stop; }
|
||||
double toExit = Math.Sqrt((_way[last].X - x) * (_way[last].X - x) + (_way[last].Y - y) * (_way[last].Y - y));
|
||||
|
||||
// The portal cooldown: hold short of the exit until CooldownMs after landing.
|
||||
if (_idx == last && !_backing && now - _landMs < CooldownMs && toExit < HoldUnits)
|
||||
{
|
||||
if (!Waiting)
|
||||
{
|
||||
Waiting = true;
|
||||
JustStartedWaiting = true;
|
||||
WaitSeconds = (CooldownMs - (now - _landMs) + 999) / 1000;
|
||||
}
|
||||
_bestMs = now; // waiting isn't being stuck
|
||||
return Act.Hold;
|
||||
}
|
||||
if (Waiting) { Waiting = false; _best = double.MaxValue; _bestMs = now; }
|
||||
|
||||
// On the exit's centre with no teleport: back off and walk in again, once.
|
||||
if (_idx == last && !_backing && toExit < WaypointUnits)
|
||||
{
|
||||
if (_atPortalMs == 0) _atPortalMs = now;
|
||||
_bestMs = now;
|
||||
if (now - _atPortalMs < TouchWaitMs) return Act.Hold;
|
||||
if (_retried) return Act.NoTeleport;
|
||||
_retried = true; _backing = true; _atPortalMs = 0;
|
||||
_best = double.MaxValue;
|
||||
}
|
||||
|
||||
double aimX = tgt.X, aimY = tgt.Y;
|
||||
if (_backing)
|
||||
{
|
||||
// A point BackOffUnits back along the last segment (or its start, if it's shorter).
|
||||
TownNetPoint a = _way[last - 1], e = _way[last];
|
||||
double sx = a.X - e.X, sy = a.Y - e.Y, sl = Math.Sqrt(sx * sx + sy * sy);
|
||||
double k = sl > BackOffUnits ? BackOffUnits / sl : 1.0;
|
||||
aimX = e.X + sx * k; aimY = e.Y + sy * k;
|
||||
if (Math.Sqrt((aimX - x) * (aimX - x) + (aimY - y) * (aimY - y)) < WaypointUnits)
|
||||
{
|
||||
_backing = false;
|
||||
_best = double.MaxValue; _bestMs = now;
|
||||
aimX = tgt.X; aimY = tgt.Y;
|
||||
}
|
||||
}
|
||||
else if (off > SteerBackUnits)
|
||||
{
|
||||
// Drifted off the line: steer back to it, a metre ahead of the nearest point.
|
||||
double sx = tgt.X - prev.X, sy = tgt.Y - prev.Y, sl = Math.Sqrt(sx * sx + sy * sy);
|
||||
double tt = sl > 1e-6 ? Math.Min(1.0, tSeg + 1.0 / sl) : 1.0;
|
||||
aimX = prev.X + sx * tt; aimY = prev.Y + sy * tt;
|
||||
}
|
||||
|
||||
// Stuck: no StuckProgress closer to where we're heading in StuckMs.
|
||||
double dAim = Math.Sqrt((aimX - x) * (aimX - x) + (aimY - y) * (aimY - y));
|
||||
if (dAim < _best - StuckProgress) { _best = dAim; _bestMs = now; }
|
||||
else if (now - _bestMs > StuckMs) { why = $"stuck near {x:F1}, {y:F1}"; return Act.Stop; }
|
||||
|
||||
heading = Math.Atan2(aimX - x, aimY - y) * 180.0 / Math.PI;
|
||||
if (heading < 0) heading += 360.0;
|
||||
return Act.Run;
|
||||
}
|
||||
}
|
||||
84
Plugins/RynthCore.Plugin.RynthNav/TravelPlan.cs
Normal file
84
Plugins/RynthCore.Plugin.RynthNav/TravelPlan.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// What a goto (or the panel's Route, or the arrow's route) may use, and the plan: the switches,
|
||||
/// where you stand, and what the land allows, in one place. Host-free: the route tests drive it.
|
||||
/// - "Use portals and recalls" off: walking only. Route and Go both respect it (Route used to plan
|
||||
/// with portals either way).
|
||||
/// - "Recalls" is part of that: it only counts when "Use portals and recalls" is on.
|
||||
/// - In a dungeon (no map position) there is no walking start: the route must begin with a recall
|
||||
/// (your dungeon's coordinates aren't map coordinates; 10-01 a route "walked" from 0,0 to a
|
||||
/// portal at 86S). With no recall to cast, it refuses and says why.
|
||||
/// - Walks between landmasses are left out (canWalk); a target only reachable over water needs a
|
||||
/// portal, a recall or the Town Network.
|
||||
/// </summary>
|
||||
internal static class TravelPlan
|
||||
{
|
||||
public sealed class Result
|
||||
{
|
||||
/// <summary>The legs; null = walk straight there (no teleport helps, or none may be used).</summary>
|
||||
public List<RouteStep>? Steps;
|
||||
public double Est;
|
||||
public int Teleports;
|
||||
/// <summary>Why there is no way at all ("" = there is one: Steps, or a plain walk).</summary>
|
||||
public string Refusal = "";
|
||||
/// <summary>One line on what was allowed, for the log.</summary>
|
||||
public string Basis = "";
|
||||
}
|
||||
|
||||
public static Result Plan(IReadOnlyList<PortalLink>? portals, IReadOnlyList<RecallLink>? recalls, HubLinks? hub,
|
||||
bool portalsOn, bool recallsOn, bool startOnMap,
|
||||
double startNs, double startEw, double goalNs, double goalEw,
|
||||
Func<double, double, double, double, bool>? canWalk, bool? landReachable, string goalName)
|
||||
{
|
||||
var r = new Result { Est = NavCoords.Distance(startNs, startEw, goalNs, goalEw) };
|
||||
recalls ??= Array.Empty<RecallLink>();
|
||||
var usableRecalls = portalsOn && recallsOn ? recalls : Array.Empty<RecallLink>();
|
||||
r.Basis = $"portals {(portalsOn ? "on" : "off")}, recalls {(portalsOn && recallsOn ? $"on ({recalls.Count} known)" : recallsOn ? "on but unused (portals off)" : "off")}, "
|
||||
+ $"start {(startOnMap ? "on the map" : "in a dungeon")}, over land {(landReachable == null ? "unknown" : landReachable.Value ? "yes" : "no")}";
|
||||
|
||||
if (!startOnMap)
|
||||
{
|
||||
// No walking start: only a recall gets you out.
|
||||
if (!portalsOn) { r.Refusal = "you're in a dungeon, so the way out is a recall: turn on Use portals and recalls"; return r; }
|
||||
if (!recallsOn) { r.Refusal = "you're in a dungeon, so the way out is a recall: turn on Recalls"; return r; }
|
||||
if (usableRecalls.Count == 0) { r.Refusal = "you're in a dungeon and no recall is ready to use (/rnav recalls says why)"; return r; }
|
||||
r.Steps = PortalRoute.Plan(portals ?? Array.Empty<PortalLink>(), usableRecalls, hub, startNs, startEw, goalNs, goalEw,
|
||||
out r.Est, out r.Teleports, canWalk, startOnMap: false);
|
||||
if (double.IsPositiveInfinity(r.Est) || r.Steps.Count == 0)
|
||||
{
|
||||
r.Steps = null;
|
||||
r.Refusal = $"you're in a dungeon and none of your recalls leads on to {goalName}";
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
if (!portalsOn)
|
||||
{
|
||||
if (landReachable == false) r.Refusal = $"no walking route to {goalName}: it's on another landmass (water or cliffs in the way); turn on Use portals and recalls";
|
||||
return r; // walk
|
||||
}
|
||||
|
||||
var steps = PortalRoute.Plan(portals ?? Array.Empty<PortalLink>(), usableRecalls, hub, startNs, startEw, goalNs, goalEw,
|
||||
out double est, out int used, canWalk);
|
||||
if (double.IsPositiveInfinity(est))
|
||||
{
|
||||
r.Refusal = $"no walking route to {goalName}: it's on another landmass (water or cliffs in the way), and none of your portals, "
|
||||
+ (recallsOn ? "recalls " : "") + "or the Town Network gets there" + (recallsOn ? "" : " (Recalls are off)");
|
||||
return r;
|
||||
}
|
||||
r.Est = est;
|
||||
if (used == 0)
|
||||
{
|
||||
if (landReachable == false) r.Refusal = $"no walking route to {goalName}: it's on another landmass (water or cliffs in the way)";
|
||||
return r; // walk
|
||||
}
|
||||
r.Steps = steps;
|
||||
r.Teleports = used;
|
||||
return r;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue