feat: SK backlog from test through 2026.11.22.48 (Trade Shop, Oracle, quests, loot, nav)
Squash of test/main-merge-2026-10-25 onto aelrynth main 2026.11.19.1 for the standing sk PR. Includes Trade Shop, Oracle wiki/ILT tracker, quest runs, loot checklist, RynthNav, VTank import. HandWrittenVersion remains 0.5.0-legacy-ui. See Changelog/2026-11-22-sk-backlog-test-merge.md.
This commit is contained in:
parent
660e6b5b1c
commit
dc08e1abba
521 changed files with 47247 additions and 795 deletions
|
|
@ -64,7 +64,8 @@ internal sealed class ArrowGuide
|
|||
/// 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)
|
||||
/// <param name="hubName">A hub step's place ("the Abandoned Mine"); null: "the Town Network".</param>
|
||||
public void SetRoute(IReadOnlyList<RouteStep> route, string name, string type, double ns, double ew, Func<RouteStep, string>? hubName = null)
|
||||
{
|
||||
_steps.Clear();
|
||||
foreach (RouteStep s in route)
|
||||
|
|
@ -73,7 +74,7 @@ internal sealed class ArrowGuide
|
|||
_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 });
|
||||
_steps.Add(new ArrowStep { Kind = ArrowStepKind.Portal, Name = s.Label, Type = "Portal", Hint = $"in {hubName?.Invoke(s) ?? "the Town Network"}: walk into the " + s.Label });
|
||||
else if (s.UsePortal)
|
||||
_steps.Add(new ArrowStep
|
||||
{
|
||||
|
|
|
|||
|
|
@ -34,6 +34,8 @@ internal sealed class AtlasRecall
|
|||
public string Name = "", In = "";
|
||||
public bool OnMap;
|
||||
public double Ns, Ew;
|
||||
/// <summary>Where it lands (0 = not given): a dungeon landing's cell matches a learned dungeon's arrival.</summary>
|
||||
public uint Cell;
|
||||
}
|
||||
|
||||
internal sealed class Atlas
|
||||
|
|
@ -141,6 +143,7 @@ internal sealed class Atlas
|
|||
foreach (JsonElement e in arr.EnumerateArray())
|
||||
{
|
||||
var r = new AtlasRecall { SpellId = Int(e, "spell"), Name = Str(e, "name"), In = Str(e, "in") };
|
||||
uint.TryParse(Str(e, "cell"), System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out r.Cell);
|
||||
r.OnMap = TryNum(e, "ns", out r.Ns) & TryNum(e, "ew", out r.Ew);
|
||||
recalls.Add(r);
|
||||
}
|
||||
|
|
@ -198,6 +201,39 @@ internal sealed class Atlas
|
|||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The best place INSIDE a dungeon (no map position, a dungeon cell) for a name: a person, a vendor or a
|
||||
/// landmark whose name is the query or starts with it as whole words ("Drogur", "Torgluuk" for "Torgluuk,
|
||||
/// High Shaman of Kor-Gursha"); never a portal. Ties: one in <paramref name="hereLb"/> (the landblock you
|
||||
/// are in), then the exact name. Null when none answers (2026-11-11: quest people inside dungeons and the Bur).
|
||||
/// </summary>
|
||||
public AtlasLocation? FindInside(string query, uint hereLb = 0)
|
||||
{
|
||||
string q = query.Trim();
|
||||
if (q.Length < 3) return null;
|
||||
AtlasLocation? best = null;
|
||||
int bestScore = 0;
|
||||
foreach (AtlasLocation l in Locations)
|
||||
{
|
||||
if (l.OnMap || l.Type.Equals("Portal", StringComparison.Ordinal) || l.Type.Equals("Dungeon", StringComparison.Ordinal)) continue;
|
||||
if (!l.Place.Equals("dungeon", StringComparison.Ordinal) || !TryCell(l.Cell, out uint cell)) continue;
|
||||
int s = l.Name.Equals(q, StringComparison.OrdinalIgnoreCase) ? 2
|
||||
: l.Name.Length > q.Length && l.Name.StartsWith(q, StringComparison.OrdinalIgnoreCase) && !char.IsLetterOrDigit(l.Name[q.Length]) ? 1 : 0;
|
||||
if (s == 0) continue;
|
||||
if (hereLb != 0 && cell >> 16 == hereLb) s += 10;
|
||||
if (s <= bestScore) continue;
|
||||
best = l; bestScore = s;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>An 8-digit hex cell ("009C0270").</summary>
|
||||
public static bool TryCell(string text, out uint cell)
|
||||
{
|
||||
cell = 0;
|
||||
return text.Length == 8 && uint.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out cell);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
|
|
|
|||
610
Plugins/RynthCore.Plugin.RynthNav/CustomPortals.cs
Normal file
610
Plugins/RynthCore.Plugin.RynthNav/CustomPortals.cs
Normal file
|
|
@ -0,0 +1,610 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Portals a server added that the world data (portals.tsv, retail/ACE) doesn't have: Infinite
|
||||
// Leaftide's and other custom servers' own portals (2026-10-29). Found two ways:
|
||||
// * "/rnav portals scan": every portal object the client knows around you is written down,
|
||||
// where it stands (the source end);
|
||||
// * taking a portal: the teleport that follows tells where it goes (the landing), so a scanned
|
||||
// portal becomes a route link the first time it is used, and an unscanned one is added then.
|
||||
// Kept per server (the world name the client logged into), so one server's portals never route a
|
||||
// character on another. Portals with both ends on the map are given to the route planner as links.
|
||||
//
|
||||
// Dungeons (2026-10-29, later): a portal standing inside a dungeon is kept too (its cell and
|
||||
// landblock-local x, y, z), a landing inside a dungeon keeps where you landed, and the way you
|
||||
// walked inside the dungeon from where you landed to the portal you left by is kept as a walk
|
||||
// (DungeonWalk). Those make the dungeon a hub like the Town Network (TownNet.Merge): a map portal
|
||||
// into it, the walk inside, and the exit portal out (onto the map, or into another learned
|
||||
// dungeon). Saved in NavData\custom-portals.txt and custom-dungeon-walks.txt. No host calls: the
|
||||
// offline tests compile this file.
|
||||
|
||||
internal sealed class CustomPortal
|
||||
{
|
||||
public string Name = "";
|
||||
public uint Wcid;
|
||||
/// <summary>Where the portal stands: its cell, and map coordinates when on the map, else landblock-local X, Y, Z.</summary>
|
||||
public uint Cell;
|
||||
public bool OnMap;
|
||||
public double Ns, Ew;
|
||||
public double X, Y, Z;
|
||||
/// <summary>Where it lands: learned by taking it. DestKnown false = only scanned.</summary>
|
||||
public bool DestKnown, DestOnMap;
|
||||
public double DestNs, DestEw;
|
||||
public uint DestCell;
|
||||
/// <summary>A landing in a dungeon: where in it (landblock-local). DestHasPos false = not known (older saves).</summary>
|
||||
public bool DestHasPos;
|
||||
public double DestX, DestY, DestZ;
|
||||
public DateTime SeenUtc, LearnedUtc;
|
||||
|
||||
/// <summary>Both ends on the map: the route planner can use it as a plain portal link.</summary>
|
||||
public bool Routable => OnMap && DestKnown && DestOnMap;
|
||||
|
||||
/// <summary>Stands in a dungeon (OnMap false).</summary>
|
||||
public bool InDungeon => !OnMap;
|
||||
public uint Landblock => Cell >> 16;
|
||||
public uint DestLandblock => DestCell >> 16;
|
||||
|
||||
public PortalLink ToLink() => new(Ns, Ew, DestNs, DestEw, Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One walk inside a dungeon: from where a teleport set you down (or where the recording began) to
|
||||
/// the portal you left by, as you walked it (loops cut out). Landblock-local coordinates.
|
||||
/// </summary>
|
||||
internal sealed class DungeonWalk
|
||||
{
|
||||
public uint Landblock;
|
||||
public uint ArrivalCell;
|
||||
public double ArrivalX, ArrivalY, ArrivalZ;
|
||||
/// <summary>The walk began at a landing (a teleport), not somewhere in the middle (a login).</summary>
|
||||
public bool FromLanding;
|
||||
public string ExitName = "";
|
||||
public uint ExitCell;
|
||||
public double ExitX, ExitY, ExitZ;
|
||||
/// <summary>From the arrival to the exit portal's centre (x, y, z), at least two points.</summary>
|
||||
public double[] Points = Array.Empty<double>(); // x0,y0,z0, x1,y1,z1, ...
|
||||
public double Length;
|
||||
public DateTime LearnedUtc;
|
||||
|
||||
public int Count => Points.Length / 3;
|
||||
public (double X, double Y, double Z) this[int i] => (Points[i * 3], Points[i * 3 + 1], Points[i * 3 + 2]);
|
||||
|
||||
public static double PathLength(double[] pts)
|
||||
{
|
||||
double len = 0;
|
||||
for (int i = 3; i + 2 < pts.Length; i += 3)
|
||||
{
|
||||
double dx = pts[i] - pts[i - 3], dy = pts[i + 1] - pts[i - 2];
|
||||
len += Math.Sqrt(dx * dx + dy * dy);
|
||||
}
|
||||
return len;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a scan did with one portal object.</summary>
|
||||
internal enum CustomScanResult { Added, Updated, BuiltIn, OffMap }
|
||||
|
||||
/// <summary>What a portal taken told the store (2026-11-01): new, a landing that changed, or nothing new.</summary>
|
||||
internal enum CustomLearnResult { New, LandingChanged, AlreadyKnown }
|
||||
|
||||
internal sealed class CustomPortalStore
|
||||
{
|
||||
/// <summary>A portal object this close (world units) to a saved one of the same name is that one.</summary>
|
||||
public const double SameUnits = 8.0;
|
||||
/// <summary>In a dungeon (landblock-local metres, with a height check): the same portal.</summary>
|
||||
public const double SameDungeonUnits = 3.0;
|
||||
public const double SameDungeonHeight = 3.0;
|
||||
/// <summary>A portals.tsv portal this close to a scanned one already routes it.</summary>
|
||||
public const double BuiltInUnits = 12.0;
|
||||
public const int MaxPerServer = 2000;
|
||||
public const int MaxWalksPerServer = 1000;
|
||||
/// <summary>Two walks between the same arrival and exit: within this, the same pair (the shorter is kept).</summary>
|
||||
public const double SameWalkEndUnits = 3.0;
|
||||
|
||||
private readonly Dictionary<string, List<CustomPortal>> _byServer = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, List<DungeonWalk>> _walks = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Bumped on every change (the plugin saves, and rebuilds its route list, when it moves).</summary>
|
||||
public int Version { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// What the last Learned / LearnedInDungeon call did. AlreadyKnown: the portal and its landing were
|
||||
/// known (within LandingSameUnits / LandingSameMeters), and nothing was rewritten: taking a known
|
||||
/// portal used to say "learned" and rewrite the file and the route hub every time (2026-11-01).
|
||||
/// </summary>
|
||||
public CustomLearnResult LastLearn { get; private set; }
|
||||
|
||||
/// <summary>A map landing this close (yards, NavCoords.Distance; landings scatter a little) is the same landing.</summary>
|
||||
public const double LandingSameUnits = 30.0;
|
||||
/// <summary>A dungeon landing this close (metres, same landblock) is the same landing.</summary>
|
||||
public const double LandingSameMeters = 6.0;
|
||||
|
||||
public IReadOnlyList<CustomPortal> For(string server) =>
|
||||
_byServer.TryGetValue(Key(server), out var l) ? l : Array.Empty<CustomPortal>();
|
||||
|
||||
public IReadOnlyList<DungeonWalk> WalksFor(string server) =>
|
||||
_walks.TryGetValue(Key(server), out var l) ? l : Array.Empty<DungeonWalk>();
|
||||
|
||||
public IEnumerable<string> Servers
|
||||
{
|
||||
get
|
||||
{
|
||||
var all = new HashSet<string>(_byServer.Keys, StringComparer.OrdinalIgnoreCase);
|
||||
all.UnionWith(_walks.Keys);
|
||||
return all;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Key(string server) => string.IsNullOrWhiteSpace(server) ? "?" : server.Trim();
|
||||
|
||||
private List<CustomPortal> ListFor(string server)
|
||||
{
|
||||
string k = Key(server);
|
||||
if (!_byServer.TryGetValue(k, out var l)) _byServer[k] = l = new List<CustomPortal>();
|
||||
return l;
|
||||
}
|
||||
|
||||
private List<DungeonWalk> WalkListFor(string server)
|
||||
{
|
||||
string k = Key(server);
|
||||
if (!_walks.TryGetValue(k, out var l)) _walks[k] = l = new List<DungeonWalk>();
|
||||
return l;
|
||||
}
|
||||
|
||||
/// <summary>The saved portal of that name standing at (cell, map spot), or null. Map portals only.</summary>
|
||||
public CustomPortal? Find(string server, string name, uint cell, bool onMap, double ns, double ew)
|
||||
{
|
||||
foreach (CustomPortal p in For(server))
|
||||
{
|
||||
if (!p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (onMap && p.OnMap) { if (NavCoords.Distance(p.Ns, p.Ew, ns, ew) <= SameUnits) return p; }
|
||||
else if (!onMap && !p.OnMap && (p.Cell >> 16) == (cell >> 16)) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The saved portal of that name standing in the dungeon of <paramref name="cell"/> at (x, y, z), or null.</summary>
|
||||
public CustomPortal? FindInDungeon(string server, string name, uint cell, double x, double y, double z)
|
||||
{
|
||||
foreach (CustomPortal p in For(server))
|
||||
{
|
||||
if (p.OnMap || p.Landblock != (cell >> 16) || !p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (Flat(p.X, p.Y, x, y) <= SameDungeonUnits && Math.Abs(p.Z - z) <= SameDungeonHeight) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static double Flat(double ax, double ay, double bx, double by) => Math.Sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
|
||||
|
||||
/// <summary>A portals.tsv portal at that spot (same name, or any within half the distance).</summary>
|
||||
public static bool IsBuiltIn(IReadOnlyList<PortalLink>? builtIn, string name, double ns, double ew)
|
||||
{
|
||||
if (builtIn == null) return false;
|
||||
foreach (PortalLink b in builtIn)
|
||||
{
|
||||
double d = NavCoords.Distance(b.SrcNs, b.SrcEw, ns, ew);
|
||||
if (d > BuiltInUnits) continue;
|
||||
if (d <= BuiltInUnits / 2) return true;
|
||||
if (b.Name.Length > 0 && name.Length > 0
|
||||
&& (b.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf(b.Name, StringComparison.OrdinalIgnoreCase) >= 0))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>A portal object on the map seen by a scan: written down (or its sighting refreshed). A dungeon one: OffMap (see SawInDungeon).</summary>
|
||||
public CustomScanResult Saw(string server, string name, uint wcid, uint cell, bool onMap, double ns, double ew,
|
||||
IReadOnlyList<PortalLink>? builtIn, DateTime nowUtc)
|
||||
{
|
||||
name = Clean(name);
|
||||
if (!onMap) return CustomScanResult.OffMap;
|
||||
CustomPortal? p = Find(server, name, cell, onMap, ns, ew);
|
||||
if (p == null && IsBuiltIn(builtIn, name, ns, ew)) return CustomScanResult.BuiltIn;
|
||||
if (p != null)
|
||||
{
|
||||
p.SeenUtc = nowUtc; // kept in memory; written with the next change
|
||||
bool changed = (wcid != 0 && p.Wcid != wcid) || p.Cell != cell
|
||||
|| Math.Abs(p.Ns - ns) > 0.0005 || Math.Abs(p.Ew - ew) > 0.0005;
|
||||
if (wcid != 0) p.Wcid = wcid;
|
||||
p.Cell = cell; p.Ns = ns; p.Ew = ew; // the live object is exact; the first sighting may not be
|
||||
if (changed) Version++;
|
||||
return CustomScanResult.Updated;
|
||||
}
|
||||
var list = ListFor(server);
|
||||
if (list.Count >= MaxPerServer) list.RemoveAt(0);
|
||||
list.Add(new CustomPortal { Name = name, Wcid = wcid, Cell = cell, OnMap = true, Ns = ns, Ew = ew, SeenUtc = nowUtc });
|
||||
Version++;
|
||||
return CustomScanResult.Added;
|
||||
}
|
||||
|
||||
/// <summary>A portal object standing in a dungeon (landblock-local x, y, z): written down, or its sighting refreshed.</summary>
|
||||
public CustomScanResult SawInDungeon(string server, string name, uint wcid, uint cell, double x, double y, double z, DateTime nowUtc)
|
||||
{
|
||||
name = Clean(name);
|
||||
CustomPortal? p = FindInDungeon(server, name, cell, x, y, z);
|
||||
if (p != null)
|
||||
{
|
||||
p.SeenUtc = nowUtc; // kept in memory; written with the next change
|
||||
bool changed = (wcid != 0 && p.Wcid != wcid) || p.Cell != cell
|
||||
|| Math.Abs(p.X - x) > 0.05 || Math.Abs(p.Y - y) > 0.05 || Math.Abs(p.Z - z) > 0.05;
|
||||
if (wcid != 0) p.Wcid = wcid;
|
||||
p.Cell = cell; p.X = x; p.Y = y; p.Z = z;
|
||||
if (changed) Version++;
|
||||
return CustomScanResult.Updated;
|
||||
}
|
||||
var list = ListFor(server);
|
||||
if (list.Count >= MaxPerServer) list.RemoveAt(0);
|
||||
list.Add(new CustomPortal { Name = name, Wcid = wcid, Cell = cell, OnMap = false, X = x, Y = y, Z = z, SeenUtc = nowUtc });
|
||||
Version++;
|
||||
return CustomScanResult.Added;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The map portal you were standing at took you to (destOnMap, destNs, destEw / destCell). A portal
|
||||
/// the world data already routes is left alone (returns null); otherwise it is added if it
|
||||
/// wasn't scanned, and its landing set. Returns the portal, or null when nothing was learned.
|
||||
/// </summary>
|
||||
public CustomPortal? Learned(string server, string name, uint wcid, uint cell, double ns, double ew,
|
||||
bool destOnMap, double destNs, double destEw, uint destCell, IReadOnlyList<PortalLink>? builtIn, DateTime nowUtc)
|
||||
=> Learned(server, name, wcid, cell, ns, ew, destOnMap, destNs, destEw, destCell, false, 0, 0, 0, builtIn, nowUtc);
|
||||
|
||||
/// <summary>As above, with where in the dungeon a dungeon landing set you down (<paramref name="destHasPos"/>).</summary>
|
||||
public CustomPortal? Learned(string server, string name, uint wcid, uint cell, double ns, double ew,
|
||||
bool destOnMap, double destNs, double destEw, uint destCell, bool destHasPos, double destX, double destY, double destZ,
|
||||
IReadOnlyList<PortalLink>? builtIn, DateTime nowUtc)
|
||||
{
|
||||
name = Clean(name);
|
||||
CustomPortal? p = Find(server, name, cell, true, ns, ew);
|
||||
bool added = false;
|
||||
if (p == null)
|
||||
{
|
||||
// portals.tsv holds map-to-map portals only: a landing in a dungeon is never one of them.
|
||||
if (destOnMap && IsBuiltIn(builtIn, name, ns, ew)) { LastLearn = CustomLearnResult.AlreadyKnown; return null; }
|
||||
var list = ListFor(server);
|
||||
if (list.Count >= MaxPerServer) list.RemoveAt(0);
|
||||
p = new CustomPortal { Name = name, Wcid = wcid, Cell = cell, OnMap = true, Ns = ns, Ew = ew, SeenUtc = nowUtc };
|
||||
list.Add(p);
|
||||
added = true;
|
||||
}
|
||||
SetLanding(p, added, destOnMap, destNs, destEw, destCell, destHasPos, destX, destY, destZ, nowUtc);
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>The dungeon portal you were standing at (landblock-local x, y, z) took you there: added if new, landing set.</summary>
|
||||
public CustomPortal LearnedInDungeon(string server, string name, uint wcid, uint cell, double x, double y, double z,
|
||||
bool destOnMap, double destNs, double destEw, uint destCell, bool destHasPos, double destX, double destY, double destZ, DateTime nowUtc)
|
||||
{
|
||||
name = Clean(name);
|
||||
CustomPortal? p = FindInDungeon(server, name, cell, x, y, z);
|
||||
bool added = false;
|
||||
if (p == null)
|
||||
{
|
||||
var list = ListFor(server);
|
||||
if (list.Count >= MaxPerServer) list.RemoveAt(0);
|
||||
p = new CustomPortal { Name = name, Wcid = wcid, Cell = cell, OnMap = false, X = x, Y = y, Z = z, SeenUtc = nowUtc };
|
||||
list.Add(p);
|
||||
added = true;
|
||||
}
|
||||
else if (wcid != 0) p.Wcid = wcid;
|
||||
SetLanding(p, added, destOnMap, destNs, destEw, destCell, destHasPos, destX, destY, destZ, nowUtc);
|
||||
return p;
|
||||
}
|
||||
|
||||
private void SetLanding(CustomPortal p, bool added, bool destOnMap, double destNs, double destEw, uint destCell,
|
||||
bool destHasPos, double destX, double destY, double destZ, DateTime nowUtc)
|
||||
{
|
||||
p.SeenUtc = nowUtc;
|
||||
// Known already, landing and all: nothing to write (and nothing to tell the player).
|
||||
if (!added && SameLanding(p, destOnMap, destNs, destEw, destCell, destHasPos, destX, destY, destZ))
|
||||
{
|
||||
LastLearn = CustomLearnResult.AlreadyKnown;
|
||||
return;
|
||||
}
|
||||
LastLearn = added || !p.DestKnown ? CustomLearnResult.New : CustomLearnResult.LandingChanged;
|
||||
p.DestKnown = true;
|
||||
p.DestOnMap = destOnMap;
|
||||
p.DestNs = destOnMap ? Math.Round(destNs, 2) : 0;
|
||||
p.DestEw = destOnMap ? Math.Round(destEw, 2) : 0;
|
||||
p.DestCell = destCell;
|
||||
p.DestHasPos = !destOnMap && destHasPos;
|
||||
p.DestX = p.DestHasPos ? Math.Round(destX, 2) : 0;
|
||||
p.DestY = p.DestHasPos ? Math.Round(destY, 2) : 0;
|
||||
p.DestZ = p.DestHasPos ? Math.Round(destZ, 2) : 0;
|
||||
p.LearnedUtc = nowUtc;
|
||||
Version++;
|
||||
}
|
||||
|
||||
/// <summary>The landing <paramref name="p"/> already has is this one (map: within LandingSameUnits; dungeon: same landblock, within LandingSameMeters).</summary>
|
||||
internal static bool SameLanding(CustomPortal p, bool destOnMap, double destNs, double destEw, uint destCell,
|
||||
bool destHasPos, double destX, double destY, double destZ)
|
||||
{
|
||||
if (!p.DestKnown || p.DestOnMap != destOnMap) return false;
|
||||
if (destOnMap) return NavCoords.Distance(p.DestNs, p.DestEw, destNs, destEw) <= LandingSameUnits;
|
||||
if ((p.DestCell >> 16) != (destCell >> 16)) return false;
|
||||
if (!destHasPos) return true; // nothing more precise to compare
|
||||
if (!p.DestHasPos) return false; // the known one had no spot: this one adds it
|
||||
double dx = p.DestX - destX, dy = p.DestY - destY, dz = p.DestZ - destZ;
|
||||
return Math.Sqrt(dx * dx + dy * dy + dz * dz) <= LandingSameMeters;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A walk inside a dungeon to one of its portals: kept, unless a walk between the same arrival
|
||||
/// and exit is already kept that is no longer (the shorter way wins). False when it was refused
|
||||
/// (fewer than two points) or a shorter one was already kept.
|
||||
/// </summary>
|
||||
public bool AddWalk(string server, DungeonWalk w)
|
||||
{
|
||||
if (w.Count < 2) return false;
|
||||
w.Length = DungeonWalk.PathLength(w.Points);
|
||||
var list = WalkListFor(server);
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
DungeonWalk o = list[i];
|
||||
if (o.Landblock != w.Landblock) continue;
|
||||
if (Flat(o.ArrivalX, o.ArrivalY, w.ArrivalX, w.ArrivalY) > SameWalkEndUnits || Math.Abs(o.ArrivalZ - w.ArrivalZ) > SameDungeonHeight) continue;
|
||||
if (Flat(o.ExitX, o.ExitY, w.ExitX, w.ExitY) > SameWalkEndUnits || Math.Abs(o.ExitZ - w.ExitZ) > SameDungeonHeight) continue;
|
||||
if (o.Length <= w.Length && (o.FromLanding || !w.FromLanding)) return false;
|
||||
list[i] = w;
|
||||
Version++;
|
||||
return true;
|
||||
}
|
||||
if (list.Count >= MaxWalksPerServer) list.RemoveAt(0);
|
||||
list.Add(w);
|
||||
Version++;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The route links for <paramref name="server"/>: its portals with both ends on the map.</summary>
|
||||
public List<PortalLink> Links(string server)
|
||||
{
|
||||
var links = new List<PortalLink>();
|
||||
foreach (CustomPortal p in For(server))
|
||||
if (p.Routable) links.Add(p.ToLink());
|
||||
return links;
|
||||
}
|
||||
|
||||
/// <summary>Forgets this server's portals (and the walks to them) whose name contains <paramref name="name"/>. How many portals went.</summary>
|
||||
public int Forget(string server, string name)
|
||||
{
|
||||
string n = name.Trim();
|
||||
int gone = 0;
|
||||
if (_byServer.TryGetValue(Key(server), out var l)) gone = l.RemoveAll(p => p.Name.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0);
|
||||
int walks = _walks.TryGetValue(Key(server), out var w) ? w.RemoveAll(x => x.ExitName.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) : 0;
|
||||
if (gone + walks > 0) Version++;
|
||||
return gone;
|
||||
}
|
||||
|
||||
/// <summary>Forgets every portal and dungeon walk saved for <paramref name="server"/>. How many portals went.</summary>
|
||||
public int Clear(string server)
|
||||
{
|
||||
int n = 0, w = 0;
|
||||
if (_byServer.TryGetValue(Key(server), out var l)) { n = l.Count; l.Clear(); }
|
||||
if (_walks.TryGetValue(Key(server), out var wl)) { w = wl.Count; wl.Clear(); }
|
||||
if (n + w > 0) Version++;
|
||||
return n;
|
||||
}
|
||||
|
||||
private static string Clean(string name)
|
||||
{
|
||||
string s = (name ?? "").Replace('\t', ' ').Replace('\r', ' ').Replace('\n', ' ').Trim();
|
||||
return s.Length == 0 ? "Portal" : s;
|
||||
}
|
||||
|
||||
// ── custom-portals.txt ─────────────────────────────────────────────────
|
||||
// One portal per line, tab-separated:
|
||||
// server, name, wcid, cell (hex), ns, ew, dest (map|dungeon|-), destNs, destEw, destCell (hex),
|
||||
// seen (UTC, ISO), learned (UTC, ISO or -),
|
||||
// where (map|dungeon), x, y, z (in a dungeon), destX, destY, destZ (a dungeon landing; "-" = not known)
|
||||
// Lines starting with '#' are comments. The last seven are newer: a line without them is a map
|
||||
// portal whose dungeon landing spot isn't known.
|
||||
|
||||
public string Serialize()
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder("# RynthNav custom portals, per server (written by RynthNav; hand-edits OK)\n");
|
||||
foreach (var (server, list) in _byServer)
|
||||
foreach (CustomPortal p in list)
|
||||
{
|
||||
sb.Append(server).Append('\t').Append(p.Name).Append('\t')
|
||||
.Append(p.Wcid.ToString(ci)).Append('\t').Append(p.Cell.ToString("X8", ci)).Append('\t')
|
||||
.Append(p.Ns.ToString("0.###", ci)).Append('\t').Append(p.Ew.ToString("0.###", ci)).Append('\t')
|
||||
.Append(!p.DestKnown ? "-" : p.DestOnMap ? "map" : "dungeon").Append('\t')
|
||||
.Append(p.DestNs.ToString("0.##", ci)).Append('\t').Append(p.DestEw.ToString("0.##", ci)).Append('\t')
|
||||
.Append(p.DestCell.ToString("X8", ci)).Append('\t')
|
||||
.Append(Iso(p.SeenUtc)).Append('\t').Append(p.LearnedUtc == default ? "-" : Iso(p.LearnedUtc)).Append('\t')
|
||||
.Append(p.OnMap ? "map" : "dungeon").Append('\t')
|
||||
.Append(p.X.ToString("0.##", ci)).Append('\t').Append(p.Y.ToString("0.##", ci)).Append('\t').Append(p.Z.ToString("0.##", ci)).Append('\t');
|
||||
if (p.DestHasPos)
|
||||
sb.Append(p.DestX.ToString("0.##", ci)).Append('\t').Append(p.DestY.ToString("0.##", ci)).Append('\t').Append(p.DestZ.ToString("0.##", ci));
|
||||
else sb.Append("-\t-\t-");
|
||||
sb.Append('\n');
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static CustomPortalStore Parse(string text) => Parse(text, null);
|
||||
|
||||
/// <summary>Reads custom-portals.txt and (when given) custom-dungeon-walks.txt.</summary>
|
||||
public static CustomPortalStore Parse(string? text, string? walksText)
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
var store = new CustomPortalStore();
|
||||
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 < 7) continue;
|
||||
var p = new CustomPortal { Name = f[1].Trim() };
|
||||
if (p.Name.Length == 0) continue;
|
||||
uint.TryParse(f[2], NumberStyles.Integer, ci, out p.Wcid);
|
||||
uint.TryParse(f[3], NumberStyles.HexNumber, ci, out p.Cell);
|
||||
if (!double.TryParse(f[4], NumberStyles.Float, ci, out p.Ns) || !double.TryParse(f[5], NumberStyles.Float, ci, out p.Ew)) continue;
|
||||
p.OnMap = true;
|
||||
string dest = f[6].Trim().ToLowerInvariant();
|
||||
p.DestKnown = dest is "map" or "dungeon";
|
||||
p.DestOnMap = dest == "map";
|
||||
if (f.Length > 8 && p.DestOnMap
|
||||
&& (!double.TryParse(f[7], NumberStyles.Float, ci, out p.DestNs) || !double.TryParse(f[8], NumberStyles.Float, ci, out p.DestEw)))
|
||||
p.DestKnown = p.DestOnMap = false;
|
||||
if (f.Length > 9) uint.TryParse(f[9], NumberStyles.HexNumber, ci, out p.DestCell);
|
||||
if (f.Length > 10) p.SeenUtc = ReadIso(f[10]);
|
||||
if (f.Length > 11) p.LearnedUtc = ReadIso(f[11]);
|
||||
if (f.Length > 15 && f[12].Trim().Equals("dungeon", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!double.TryParse(f[13], NumberStyles.Float, ci, out p.X) || !double.TryParse(f[14], NumberStyles.Float, ci, out p.Y)) continue;
|
||||
double.TryParse(f[15], NumberStyles.Float, ci, out p.Z);
|
||||
p.OnMap = false;
|
||||
}
|
||||
if (f.Length > 18 && p.DestKnown && !p.DestOnMap
|
||||
&& double.TryParse(f[16], NumberStyles.Float, ci, out p.DestX) && double.TryParse(f[17], NumberStyles.Float, ci, out p.DestY))
|
||||
{
|
||||
double.TryParse(f[18], NumberStyles.Float, ci, out p.DestZ);
|
||||
p.DestHasPos = true;
|
||||
}
|
||||
store.ListFor(f[0]).Add(p);
|
||||
}
|
||||
if (walksText != null) store.ParseWalks(walksText);
|
||||
return store;
|
||||
}
|
||||
|
||||
// ── custom-dungeon-walks.txt ───────────────────────────────────────────
|
||||
// One walk per line, tab-separated:
|
||||
// server, landblock (hex), arrival cell (hex), arrival x, y, z, from a landing (1|0),
|
||||
// exit name, exit cell (hex), exit x, y, z, length, learned (UTC, ISO), points "x,y,z;x,y,z;..."
|
||||
|
||||
public string SerializeWalks()
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder("# RynthNav walks inside dungeons, per server: from a landing to the portal taken (written by RynthNav)\n");
|
||||
foreach (var (server, list) in _walks)
|
||||
foreach (DungeonWalk w in list)
|
||||
{
|
||||
sb.Append(server).Append('\t').Append(w.Landblock.ToString("X4", ci)).Append('\t')
|
||||
.Append(w.ArrivalCell.ToString("X8", ci)).Append('\t')
|
||||
.Append(w.ArrivalX.ToString("0.##", ci)).Append('\t').Append(w.ArrivalY.ToString("0.##", ci)).Append('\t').Append(w.ArrivalZ.ToString("0.##", ci)).Append('\t')
|
||||
.Append(w.FromLanding ? '1' : '0').Append('\t')
|
||||
.Append(w.ExitName).Append('\t').Append(w.ExitCell.ToString("X8", ci)).Append('\t')
|
||||
.Append(w.ExitX.ToString("0.##", ci)).Append('\t').Append(w.ExitY.ToString("0.##", ci)).Append('\t').Append(w.ExitZ.ToString("0.##", ci)).Append('\t')
|
||||
.Append(w.Length.ToString("0.#", ci)).Append('\t').Append(Iso(w.LearnedUtc)).Append('\t');
|
||||
for (int i = 0; i < w.Count; i++)
|
||||
{
|
||||
if (i > 0) sb.Append(';');
|
||||
var (x, y, z) = w[i];
|
||||
sb.Append(x.ToString("0.##", ci)).Append(',').Append(y.ToString("0.##", ci)).Append(',').Append(z.ToString("0.##", ci));
|
||||
}
|
||||
sb.Append('\n');
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private void ParseWalks(string text)
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
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 < 15) continue;
|
||||
var w = new DungeonWalk { ExitName = f[7].Trim() };
|
||||
if (!uint.TryParse(f[1], NumberStyles.HexNumber, ci, out w.Landblock)) continue;
|
||||
uint.TryParse(f[2], NumberStyles.HexNumber, ci, out w.ArrivalCell);
|
||||
double.TryParse(f[3], NumberStyles.Float, ci, out w.ArrivalX);
|
||||
double.TryParse(f[4], NumberStyles.Float, ci, out w.ArrivalY);
|
||||
double.TryParse(f[5], NumberStyles.Float, ci, out w.ArrivalZ);
|
||||
w.FromLanding = f[6].Trim() == "1";
|
||||
uint.TryParse(f[8], NumberStyles.HexNumber, ci, out w.ExitCell);
|
||||
double.TryParse(f[9], NumberStyles.Float, ci, out w.ExitX);
|
||||
double.TryParse(f[10], NumberStyles.Float, ci, out w.ExitY);
|
||||
double.TryParse(f[11], NumberStyles.Float, ci, out w.ExitZ);
|
||||
w.LearnedUtc = ReadIso(f[13]);
|
||||
var pts = new List<double>();
|
||||
bool ok = true;
|
||||
foreach (string pt in f[14].Split(';', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
string[] c = pt.Split(',');
|
||||
if (c.Length < 3 || !double.TryParse(c[0], NumberStyles.Float, ci, out double x)
|
||||
|| !double.TryParse(c[1], NumberStyles.Float, ci, out double y) || !double.TryParse(c[2], NumberStyles.Float, ci, out double z))
|
||||
{ ok = false; break; }
|
||||
pts.Add(x); pts.Add(y); pts.Add(z);
|
||||
}
|
||||
if (!ok || pts.Count < 6) continue;
|
||||
w.Points = pts.ToArray();
|
||||
w.Length = DungeonWalk.PathLength(w.Points);
|
||||
WalkListFor(f[0]).Add(w);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Iso(DateTime t) => t == default ? "-" : t.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
|
||||
|
||||
private static DateTime ReadIso(string s) =>
|
||||
DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime t) ? t.ToUniversalTime() : default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The way walked inside a dungeon since the last landing, landblock-local, with loops cut out (coming
|
||||
/// back within <see cref="LoopUnits"/> of an earlier point drops everything walked since). Host-free.
|
||||
/// </summary>
|
||||
internal sealed class DungeonTrail
|
||||
{
|
||||
public const double StepUnits = 1.0;
|
||||
public const double LoopUnits = 1.5;
|
||||
public const double LoopHeight = 2.0;
|
||||
public const int MaxPoints = 4000;
|
||||
|
||||
private readonly List<double> _pts = new();
|
||||
public uint Landblock { get; private set; }
|
||||
public uint StartCell { get; private set; }
|
||||
public bool FromLanding { get; private set; }
|
||||
/// <summary>Grew past MaxPoints: no longer kept (a walk this long isn't a route).</summary>
|
||||
public bool Overflow { get; private set; }
|
||||
public int Count => _pts.Count / 3;
|
||||
|
||||
public void Clear() { _pts.Clear(); Landblock = 0; StartCell = 0; Overflow = false; FromLanding = false; }
|
||||
|
||||
public void Start(uint cell, double x, double y, double z, bool fromLanding)
|
||||
{
|
||||
Clear();
|
||||
Landblock = cell >> 16; StartCell = cell; FromLanding = fromLanding;
|
||||
_pts.Add(x); _pts.Add(y); _pts.Add(z);
|
||||
}
|
||||
|
||||
/// <summary>One position; true when the trail changed.</summary>
|
||||
public bool Add(double x, double y, double z)
|
||||
{
|
||||
if (Overflow || _pts.Count == 0) return false;
|
||||
int n = Count;
|
||||
double lx = _pts[^3], ly = _pts[^2];
|
||||
if (Math.Sqrt((lx - x) * (lx - x) + (ly - y) * (ly - y)) < StepUnits) return false;
|
||||
for (int j = 0; j < n - 3; j++)
|
||||
{
|
||||
double jx = _pts[j * 3], jy = _pts[j * 3 + 1], jz = _pts[j * 3 + 2];
|
||||
if (Math.Sqrt((jx - x) * (jx - x) + (jy - y) * (jy - y)) < LoopUnits && Math.Abs(jz - z) < LoopHeight)
|
||||
{
|
||||
_pts.RemoveRange((j + 1) * 3, _pts.Count - (j + 1) * 3);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (n >= MaxPoints) { Overflow = true; return false; }
|
||||
_pts.Add(x); _pts.Add(y); _pts.Add(z);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The trail plus the portal's centre as its last point (x, y, z triples).</summary>
|
||||
public double[] To(double x, double y, double z)
|
||||
{
|
||||
var a = new List<double>(_pts);
|
||||
// The last recorded point and the portal itself: the walker walks into its centre.
|
||||
if (a.Count >= 6 && Math.Sqrt((a[^3] - x) * (a[^3] - x) + (a[^2] - y) * (a[^2] - y)) < 0.3) a.RemoveRange(a.Count - 3, 3);
|
||||
a.Add(x); a.Add(y); a.Add(z);
|
||||
return a.ToArray();
|
||||
}
|
||||
|
||||
public (double X, double Y, double Z) First => (_pts[0], _pts[1], _pts[2]);
|
||||
}
|
||||
|
|
@ -64,6 +64,28 @@ internal static class Entrance
|
|||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A portal on the map that leads into landblock <paramref name="lb"/> (a dungeon): the nearest open one,
|
||||
/// one that needs no quest first when there is a choice; never a destroyed one. Null when none does.
|
||||
/// </summary>
|
||||
public static AtlasLocation? PortalInto(Atlas atlas, uint lb, bool hasPos, double ns, double ew)
|
||||
{
|
||||
AtlasLocation? best = null;
|
||||
double bestD = double.MaxValue;
|
||||
bool bestQuest = true;
|
||||
foreach (AtlasLocation l in atlas.Locations)
|
||||
{
|
||||
if (!l.OnMap || l.Closed || !l.HasDest || l.DestOnMap) continue;
|
||||
if (!l.Type.Equals("Portal", StringComparison.Ordinal) || IsDestroyed(l.Name)) continue;
|
||||
if (!Atlas.TryCell(l.DestCell, out uint dc) || dc >> 16 != lb) 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;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <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
|
||||
|
|
|
|||
|
|
@ -109,7 +109,7 @@ internal static class NavRouteExport
|
|||
if (inside == null || exit == null || net == null)
|
||||
{
|
||||
trip.HubWalk(i, net, out string why);
|
||||
Stop(i, $"the walk inside the Town Network isn't known ({(why.Length > 0 ? why : "no townnet.json")})");
|
||||
Stop(i, $"the walk inside to the {s.Label} isn't known ({(why.Length > 0 ? why : "no townnet.json or learned dungeon")})");
|
||||
return r;
|
||||
}
|
||||
List<WorldPt> walk = TripPathBuilder.StopShort(inside, HubStopShort);
|
||||
|
|
|
|||
277
Plugins/RynthCore.Plugin.RynthNav/PackGems.cs
Normal file
277
Plugins/RynthCore.Plugin.RynthNav/PackGems.cs
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Portal gems in your pack (2026-10-29): an item whose use casts a teleport (a recall gem, a portal
|
||||
// gem, a custom server's town gem) is a recall the route planner can take, used with UseObject, no
|
||||
// magic stance. Where one lands:
|
||||
// 1. learned in game: you (or a route) used one and a teleport followed (GemMemory, per server and
|
||||
// weenie class, so the same gem on another character is known too);
|
||||
// 2. its spell is a personal recall (Lifestone Recall, Portal Recall, a portal tie recall): the
|
||||
// character's own landing (RecallMemory);
|
||||
// 3. its spell is a fixed recall the Atlas knows (Aerlinthe Recall...): the Atlas's landing;
|
||||
// 4. guessed from its name: "Abandoned Mines Portal Sending Gem" is the Atlas's dungeon "Abandoned
|
||||
// Mine", landing where the world data's portal into it does; "Timaru Portal Sending Gem" the town.
|
||||
// Using one teaches its real landing, which wins from then on.
|
||||
// A gem landing in a dungeon is routed when RynthNav has learned walks there (TownNet.Merge): the
|
||||
// planner lands at that dungeon's arrival and goes on by its portals.
|
||||
// A gem costs the planner its use plus GemCostUnits on top (rynthnav.json "gemCostYards"), so the
|
||||
// same recall cast as a spell, which spends nothing, comes first, and a gem is only spent when it
|
||||
// saves real walking. Saved in NavData\gems.txt. No host calls: the offline tests compile this file.
|
||||
|
||||
/// <summary>One kind of usable teleport item in the pack (stacks of the same weenie class added up).</summary>
|
||||
internal sealed class PackGem
|
||||
{
|
||||
public uint Id; // one object of it (the one used)
|
||||
public uint Wcid;
|
||||
public string Name = "";
|
||||
public int SpellId; // its use spell (DID Spell), 0 = not known
|
||||
public int Count; // how many, stacks added up
|
||||
}
|
||||
|
||||
/// <summary>Where gems land, learned in game: per server and weenie class.</summary>
|
||||
internal sealed class GemMemory
|
||||
{
|
||||
private readonly Dictionary<string, (string Name, RecallSpot Spot)> _map = new(StringComparer.OrdinalIgnoreCase);
|
||||
public int Version { get; private set; }
|
||||
public int Count => _map.Count;
|
||||
|
||||
private static string Key(string server, uint wcid) =>
|
||||
(string.IsNullOrWhiteSpace(server) ? "?" : server.Trim()) + "|" + wcid.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
public RecallSpot? Get(string server, uint wcid) => _map.TryGetValue(Key(server, wcid), out var v) ? v.Spot : null;
|
||||
|
||||
public void Set(string server, uint wcid, string name, RecallSpot spot)
|
||||
{
|
||||
_map[Key(server, wcid)] = (Clean(name), spot);
|
||||
Version++;
|
||||
}
|
||||
|
||||
public bool Forget(string server, uint wcid)
|
||||
{
|
||||
bool gone = _map.Remove(Key(server, wcid));
|
||||
if (gone) Version++;
|
||||
return gone;
|
||||
}
|
||||
|
||||
public IEnumerable<(uint Wcid, string Name, RecallSpot Spot)> For(string server)
|
||||
{
|
||||
string prefix = (string.IsNullOrWhiteSpace(server) ? "?" : server.Trim()) + "|";
|
||||
foreach (var (k, v) in _map)
|
||||
if (k.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
|
||||
&& uint.TryParse(k.AsSpan(prefix.Length), NumberStyles.Integer, CultureInfo.InvariantCulture, out uint w))
|
||||
yield return (w, v.Name, v.Spot);
|
||||
}
|
||||
|
||||
private static string Clean(string s) => (s ?? "").Replace('\t', ' ').Replace('\n', ' ').Replace('\r', ' ').Trim();
|
||||
|
||||
// gems.txt: server, wcid, name, where (map|dungeon), ns, ew, label, cell (hex), x, y, z (in a dungeon; - = not known)
|
||||
// — tab-separated, '#' comments.
|
||||
public string Serialize()
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder("# RynthNav: where portal gems land, per server and weenie class (learned by using them)\n");
|
||||
foreach (var (k, v) in _map)
|
||||
{
|
||||
int bar = k.LastIndexOf('|');
|
||||
sb.Append(k, 0, bar).Append('\t').Append(k, bar + 1, k.Length - bar - 1).Append('\t').Append(v.Name).Append('\t')
|
||||
.Append(v.Spot.OnMap ? "map" : "dungeon").Append('\t')
|
||||
.Append(v.Spot.Ns.ToString("0.##", ci)).Append('\t').Append(v.Spot.Ew.ToString("0.##", ci)).Append('\t')
|
||||
.Append(Clean(v.Spot.Label)).Append('\t').Append(v.Spot.Cell.ToString("X8", ci)).Append('\t')
|
||||
.Append(v.Spot.HasPos ? v.Spot.X.ToString("0.##", ci) + "\t" + v.Spot.Y.ToString("0.##", ci) + "\t" + v.Spot.Z.ToString("0.##", ci) : "-\t-\t-")
|
||||
.Append('\n');
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static GemMemory Parse(string? text)
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
var m = new GemMemory();
|
||||
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 < 6 || !uint.TryParse(f[1], NumberStyles.Integer, ci, out uint wcid)) continue;
|
||||
var spot = new RecallSpot { OnMap = f[3].Trim().Equals("map", StringComparison.OrdinalIgnoreCase), Label = f.Length > 6 ? f[6] : "" };
|
||||
if (spot.OnMap && (!double.TryParse(f[4], NumberStyles.Float, ci, out spot.Ns) || !double.TryParse(f[5], NumberStyles.Float, ci, out spot.Ew))) continue;
|
||||
if (f.Length > 7) uint.TryParse(f[7], NumberStyles.HexNumber, ci, out spot.Cell);
|
||||
if (f.Length > 10 && double.TryParse(f[8], NumberStyles.Float, ci, out spot.X) && double.TryParse(f[9], NumberStyles.Float, ci, out spot.Y))
|
||||
{
|
||||
double.TryParse(f[10], NumberStyles.Float, ci, out spot.Z);
|
||||
spot.HasPos = true;
|
||||
}
|
||||
m._map[Key(f[0], wcid)] = (f[2].Trim(), spot);
|
||||
}
|
||||
m.Version = 0;
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class GemPlanner
|
||||
{
|
||||
/// <summary>Using a gem: no stance, no wand, a short animation. Estimated.</summary>
|
||||
public const double GemUseSeconds = 3.0;
|
||||
/// <summary>On top of the use: a gem is spent (rynthnav.json "gemCostYards"; 1 /loc degree = 240).</summary>
|
||||
public const double GemCostUnitsDefault = 240.0;
|
||||
|
||||
/// <summary>The chat command "save as nav route" writes for a gem (RynthAi's /mt usei: use from inventory by name).</summary>
|
||||
public static string UseCommand(string name) => "/mt usei " + name;
|
||||
|
||||
/// <summary>Which recall spell a gem's spell is for the character's own landings, or null.</summary>
|
||||
public static RecallSlot? PersonalSlot(int spellId) => spellId switch
|
||||
{
|
||||
RecallPlanner.LifestoneRecall => RecallSlot.Lifestone,
|
||||
RecallPlanner.PortalRecall => RecallSlot.LastPortal,
|
||||
RecallPlanner.PrimaryPortalTieRecall => RecallSlot.Tie1,
|
||||
RecallPlanner.SecondaryPortalTieRecall => RecallSlot.Tie2,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The pack's gems as recalls the planner may take (one per weenie class), each with where it
|
||||
/// lands; a gem whose landing isn't known, or is in a dungeon, is left out with a note.
|
||||
/// </summary>
|
||||
public static List<RecallOption> Build(IReadOnlyList<PackGem> gems, Atlas atlas, RecallMemory memory, string charKey,
|
||||
GemMemory learned, string server, double gemCostUnits, List<string>? notes, ArrivalResolver? arrivalOf = null)
|
||||
{
|
||||
var list = new List<RecallOption>();
|
||||
var seen = new HashSet<uint>();
|
||||
foreach (PackGem g in gems)
|
||||
{
|
||||
if (g.Count <= 0 || !seen.Add(g.Wcid)) continue;
|
||||
RecallSpot? spot = learned.Get(server, g.Wcid);
|
||||
string from = "learned";
|
||||
if (spot == null && g.SpellId != 0 && PersonalSlot(g.SpellId) is RecallSlot slot)
|
||||
{
|
||||
spot = memory.Get(charKey, slot);
|
||||
from = "your " + RecallMemory.SlotName(slot);
|
||||
if (spot == null) { notes?.Add($"{g.Name} (gem): casts {RecallMemory.SlotName(slot)}, whose landing isn't known yet."); continue; }
|
||||
}
|
||||
if (spot == null && g.SpellId != 0)
|
||||
foreach (AtlasRecall r in atlas.Recalls)
|
||||
if (r.SpellId == g.SpellId)
|
||||
{
|
||||
spot = new RecallSpot { OnMap = r.OnMap, Ns = r.Ns, Ew = r.Ew, Label = r.OnMap ? r.Name : (r.In.Length > 0 ? r.In : r.Name), Cell = r.Cell };
|
||||
from = r.Name;
|
||||
break;
|
||||
}
|
||||
if (spot == null && GuessFromName(g.Name, atlas, out RecallSpot? guess, out string what))
|
||||
{
|
||||
spot = guess;
|
||||
from = "guessed from its name: " + what;
|
||||
}
|
||||
if (spot == null) { notes?.Add($"{g.Name} (gem): where it lands isn't known yet (use one once)."); continue; }
|
||||
var o = new RecallOption
|
||||
{
|
||||
Name = g.Name + " (gem)", Command = UseCommand(g.Name), Ns = spot.Ns, Ew = spot.Ew,
|
||||
CastSeconds = GemUseSeconds, ExtraCostUnits = Math.Max(0, gemCostUnits),
|
||||
ItemWcid = g.Wcid, ItemName = g.Name, ItemCount = g.Count, Learned = from == "learned", Via = from,
|
||||
};
|
||||
if (!spot.OnMap)
|
||||
{
|
||||
int a = spot.Cell != 0 && arrivalOf != null ? arrivalOf(spot.Cell, spot.HasPos, spot.X, spot.Y, spot.Z) : -1;
|
||||
if (a < 0)
|
||||
{
|
||||
notes?.Add($"{g.Name} (gem) lands in {(spot.Label.Length > 0 ? spot.Label : "a dungeon")}: not used for routes until RynthNav has learned a way out of it (walk to one of its portals and take it).");
|
||||
continue;
|
||||
}
|
||||
o.Ns = o.Ew = 0;
|
||||
o.ToArrival = a;
|
||||
o.Into = spot.Label.Length > 0 ? spot.Label : $"dungeon {spot.Cell >> 16:X4}";
|
||||
}
|
||||
list.Add(o);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// Words a gem's name adds to the place it sends you to.
|
||||
private static readonly string[] GemWords = { "gem", "gems", "portal", "sending", "recall", "orb", "everlasting", "summoning", "attuned" };
|
||||
private static readonly string[] GemLeadWords = { "unlimited", "infinite", "everlasting", "attuned" };
|
||||
|
||||
/// <summary>The place a gem's name points at: "Abandoned Mines Portal Sending Gem" → "Abandoned Mines".</summary>
|
||||
public static string PlaceInName(string gemName)
|
||||
{
|
||||
var words = new List<string>((gemName ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries));
|
||||
while (words.Count > 0 && Array.IndexOf(GemWords, words[^1].ToLowerInvariant()) >= 0) words.RemoveAt(words.Count - 1);
|
||||
while (words.Count > 0 && Array.IndexOf(GemLeadWords, words[0].ToLowerInvariant()) >= 0) words.RemoveAt(0);
|
||||
if (words.Count > 0 && words[0].Equals("to", StringComparison.OrdinalIgnoreCase)) words.RemoveAt(0);
|
||||
return string.Join(" ", words);
|
||||
}
|
||||
|
||||
/// <summary>A name for matching: lower case, letters and digits only, each word's trailing s dropped ("Mines" = "Mine").</summary>
|
||||
public static string Norm(string s)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
foreach (string w0 in (s ?? "").ToLowerInvariant().Split(new[] { ' ', '-', '_' }, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var w = new StringBuilder();
|
||||
foreach (char c in w0) if (char.IsLetterOrDigit(c)) w.Append(c);
|
||||
string x = w.ToString();
|
||||
if (x.Length > 3 && x.EndsWith('s')) x = x[..^1];
|
||||
if (x.Length == 0) continue;
|
||||
if (sb.Length > 0) sb.Append(' ');
|
||||
sb.Append(x);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A gem's landing guessed from its name and the Atlas: a dungeon of that name (where the world
|
||||
/// data's portal into it lands: its cell), else a town of that name (the town's spot). False when
|
||||
/// the name matches nothing, or several dungeon landings.
|
||||
/// </summary>
|
||||
public static bool GuessFromName(string gemName, Atlas atlas, out RecallSpot? spot, out string what)
|
||||
{
|
||||
spot = null; what = "";
|
||||
string place = PlaceInName(gemName);
|
||||
string key = Norm(place);
|
||||
if (key.Length < 3) return false;
|
||||
foreach (AtlasLocation d in atlas.Locations)
|
||||
{
|
||||
if (!d.Type.Equals("Dungeon", StringComparison.Ordinal) || Norm(d.Name) != key) continue;
|
||||
// Where the world data's portal into it lands: a portal whose landing is named this dungeon, in its landblock.
|
||||
uint cell = 0;
|
||||
foreach (AtlasLocation p in atlas.Locations)
|
||||
{
|
||||
if (!p.Type.Equals("Portal", StringComparison.Ordinal) || !p.HasDest || p.DestOnMap) continue;
|
||||
if (!uint.TryParse(p.DestCell, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint dc)) continue;
|
||||
if (!d.Lb.Equals(((dc >> 16) & 0xFFFF).ToString("X4", CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (p.OnMap || Norm(p.DestName) == key) { cell = dc; if (p.OnMap) break; }
|
||||
}
|
||||
if (cell == 0) continue;
|
||||
spot = new RecallSpot { OnMap = false, Cell = cell, Label = d.Name };
|
||||
what = d.Name;
|
||||
return true;
|
||||
}
|
||||
foreach (AtlasLocation tl in atlas.Locations)
|
||||
{
|
||||
if (!tl.Type.Equals("Town", StringComparison.Ordinal) || !tl.OnMap || Norm(tl.Name) != key) continue;
|
||||
spot = new RecallSpot { OnMap = true, Ns = tl.Ns, Ew = tl.Ew, Label = tl.Name };
|
||||
what = tl.Name;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Worth watching as a possible teleport gem: a gem (item type), or anything whose use spell is a
|
||||
/// recall, or whose name says so. Used to keep the pack's list (and spot one being used up).
|
||||
/// </summary>
|
||||
public static bool LooksLikeTeleportItem(uint itemType, int spellId, string name, Atlas atlas, GemMemory learned, string server, uint wcid)
|
||||
{
|
||||
if (learned.Get(server, wcid) != null) return true;
|
||||
if (spellId == 0) return false;
|
||||
if ((itemType & ItemTypeGem) != 0) return true;
|
||||
if (PersonalSlot(spellId) != null) return true;
|
||||
foreach (AtlasRecall r in atlas.Recalls) if (r.SpellId == spellId) return true;
|
||||
return name.IndexOf("portal", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("recall", StringComparison.OrdinalIgnoreCase) >= 0
|
||||
|| name.IndexOf("teleport", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("sending", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
}
|
||||
|
||||
public const uint ItemTypeGem = 0x00000800;
|
||||
}
|
||||
|
|
@ -125,7 +125,8 @@ internal static class PathMarkers
|
|||
if (s.UsePortal)
|
||||
{
|
||||
bool intoHub = i + 1 < n && trip.Steps[i + 1].IsHub;
|
||||
string label = intoHub ? "TOWN NETWORK"
|
||||
int nx = intoHub ? trip.Steps[i + 1].HubExit : -1;
|
||||
string label = intoHub ? (net != null && nx >= 0 && nx < net.Exits.Count ? net.Exits[nx].Hub : "Town Network")
|
||||
: last && trip.EndsInEntrance ? "ENTER " + trip.EnterName
|
||||
: "PORTAL " + s.Label;
|
||||
end = new Mark(to, intoHub ? MarkKind.Town : MarkKind.Portal, Fit(label), i, false);
|
||||
|
|
|
|||
|
|
@ -43,6 +43,10 @@ internal sealed class RecallSpot
|
|||
public string Label = "";
|
||||
/// <summary>The chat command that does this recall, when it's a command (@lifestone, @house recall).</summary>
|
||||
public string Command = "";
|
||||
/// <summary>The landing's cell (0 = not known); off the map, where in the dungeon (landblock-local) when HasPos.</summary>
|
||||
public uint Cell;
|
||||
public bool HasPos;
|
||||
public double X, Y, Z;
|
||||
}
|
||||
|
||||
/// <summary>What a chat line tells RynthNav about recalls.</summary>
|
||||
|
|
@ -169,7 +173,10 @@ internal sealed class RecallMemory
|
|||
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");
|
||||
.Append(Clean(s.Label)).Append('\t').Append(Clean(s.Command)).Append('\t')
|
||||
.Append(s.Cell.ToString("X8", ci)).Append('\t')
|
||||
.Append(s.HasPos ? s.X.ToString("0.##", ci) + "\t" + s.Y.ToString("0.##", ci) + "\t" + s.Z.ToString("0.##", ci) : "-\t-\t-")
|
||||
.Append("\r\n");
|
||||
}
|
||||
}
|
||||
return sb.ToString();
|
||||
|
|
@ -192,6 +199,13 @@ internal sealed class RecallMemory
|
|||
};
|
||||
s.OnMap = double.TryParse(f[2], NumberStyles.Float, CultureInfo.InvariantCulture, out s.Ns)
|
||||
& double.TryParse(f[3], NumberStyles.Float, CultureInfo.InvariantCulture, out s.Ew);
|
||||
if (f.Length > 6) uint.TryParse(f[6], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out s.Cell);
|
||||
if (f.Length > 9 && double.TryParse(f[7], NumberStyles.Float, CultureInfo.InvariantCulture, out s.X)
|
||||
&& double.TryParse(f[8], NumberStyles.Float, CultureInfo.InvariantCulture, out s.Y))
|
||||
{
|
||||
double.TryParse(f[9], NumberStyles.Float, CultureInfo.InvariantCulture, out s.Z);
|
||||
s.HasPos = true;
|
||||
}
|
||||
m.Set(f[0], slot, s);
|
||||
}
|
||||
m.Version = 0;
|
||||
|
|
|
|||
|
|
@ -16,10 +16,33 @@ internal sealed class RecallOption
|
|||
public double CastSeconds;
|
||||
/// <summary>Learned in game (RecallMemory), not fixed by the world data.</summary>
|
||||
public bool Learned;
|
||||
/// <summary>Planner cost on top of the cast time (a portal gem is spent: GemPlanner).</summary>
|
||||
public double ExtraCostUnits;
|
||||
/// <summary>A portal gem from the pack (PackGems.cs): used with UseObject instead of cast. 0 = not a gem.</summary>
|
||||
public uint ItemWcid;
|
||||
public string ItemName = "";
|
||||
public int ItemCount;
|
||||
/// <summary>For a gem: where its landing comes from ("learned", the recall it casts...).</summary>
|
||||
public string Via = "";
|
||||
public bool IsGem => ItemWcid != 0;
|
||||
/// <summary>
|
||||
/// >= 0: it lands in a dungeon RynthNav learned, at that arrival of the route hub (TownNet.Merge);
|
||||
/// the route goes on by the dungeon's walks. Ns/Ew are then 0 and <see cref="Where"/> says where.
|
||||
/// </summary>
|
||||
public int ToArrival = -1;
|
||||
public string Into = "";
|
||||
|
||||
public RecallLink ToLink() => new(Ns, Ew, Name, PortalRoute.RecallCostUnits(CastSeconds));
|
||||
public string Where => ToArrival >= 0 ? (Into.Length > 0 ? Into : "a dungeon RynthNav learned") : NavCoords.Fmt(Ns, Ew);
|
||||
|
||||
public RecallLink ToLink() => ToArrival >= 0
|
||||
? new(double.NaN, double.NaN, Name, PortalRoute.RecallCostUnits(CastSeconds) + ExtraCostUnits, ToArrival)
|
||||
: new(Ns, Ew, Name, PortalRoute.RecallCostUnits(CastSeconds) + ExtraCostUnits);
|
||||
}
|
||||
|
||||
/// <summary>The route hub's arrival a landing in a dungeon is (cell; and landblock-local x, y, z when hasPos), or -1.</summary>
|
||||
internal delegate int ArrivalResolver(uint cell, bool hasPos, double x, double y, double z);
|
||||
|
||||
|
||||
/// <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
|
||||
|
|
@ -43,7 +66,9 @@ internal static class RecallPlanner
|
|||
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)
|
||||
/// <param name="arrivalOf">A landing in a dungeon RynthNav learned: its hub arrival (the recall is then routed through the dungeon). Null: dungeon landings are left out.</param>
|
||||
public static List<RecallOption> Build(Atlas atlas, ISet<int>? known, RecallMemory memory, string charKey, List<string>? notes,
|
||||
ArrivalResolver? arrivalOf = null)
|
||||
{
|
||||
var list = new List<RecallOption>();
|
||||
|
||||
|
|
@ -60,7 +85,13 @@ internal static class RecallPlanner
|
|||
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.");
|
||||
int a = r.Cell != 0 && arrivalOf != null ? arrivalOf(r.Cell, false, 0, 0, 0) : -1;
|
||||
if (a >= 0)
|
||||
{
|
||||
list.Add(new RecallOption { Name = r.Name, SpellId = r.SpellId, CastSeconds = SpellCastSeconds, ToArrival = a, Into = r.In.Length > 0 ? r.In : $"dungeon {r.Cell >> 16:X4}" });
|
||||
continue;
|
||||
}
|
||||
notes?.Add(r.Name + " lands " + (r.In.Length > 0 ? "in " + r.In : "in a dungeon") + ": not used for routes (no walk out of it learned yet).");
|
||||
continue;
|
||||
}
|
||||
list.Add(new RecallOption { Name = r.Name, SpellId = r.SpellId, Ns = r.Ns, Ew = r.Ew, CastSeconds = SpellCastSeconds });
|
||||
|
|
@ -70,13 +101,13 @@ internal static class RecallPlanner
|
|||
// Personal recall spells: the landing is the character's own.
|
||||
if (known != null)
|
||||
{
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, LifestoneRecall, "Lifestone Recall", RecallSlot.Lifestone,
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, arrivalOf, LifestoneRecall, "Lifestone Recall", RecallSlot.Lifestone,
|
||||
"cast Lifestone Tie on a lifestone, cast Lifestone Recall once, or /rnav tie lifestone at the tied lifestone");
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, PortalRecall, "Portal Recall", RecallSlot.LastPortal,
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, arrivalOf, PortalRecall, "Portal Recall", RecallSlot.LastPortal,
|
||||
"walk through a portal");
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, PrimaryPortalTieRecall, "Primary Portal Tie Recall", RecallSlot.Tie1,
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, arrivalOf, PrimaryPortalTieRecall, "Primary Portal Tie Recall", RecallSlot.Tie1,
|
||||
"cast Primary Portal Tie on a portal, cast Primary Portal Tie Recall once, or /rnav tie 1 at the tied portal");
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, SecondaryPortalTieRecall, "Secondary Portal Tie Recall", RecallSlot.Tie2,
|
||||
AddLearnedSpell(list, notes, known, memory, charKey, arrivalOf, SecondaryPortalTieRecall, "Secondary Portal Tie Recall", RecallSlot.Tie2,
|
||||
"cast Secondary Portal Tie on a portal, cast Secondary Portal Tie Recall once, or /rnav tie 2 at the tied portal");
|
||||
}
|
||||
|
||||
|
|
@ -91,12 +122,22 @@ internal static class RecallPlanner
|
|||
}
|
||||
|
||||
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)
|
||||
string charKey, ArrivalResolver? arrivalOf, 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; }
|
||||
if (!spot.OnMap)
|
||||
{
|
||||
int a = spot.Cell != 0 && arrivalOf != null ? arrivalOf(spot.Cell, spot.HasPos, spot.X, spot.Y, spot.Z) : -1;
|
||||
if (a >= 0)
|
||||
{
|
||||
list.Add(new RecallOption { Name = name, SpellId = spellId, CastSeconds = SpellCastSeconds, Learned = true, ToArrival = a, Into = spot.Label });
|
||||
return;
|
||||
}
|
||||
notes?.Add(name + " lands " + Where(spot) + ": not used for routes (no walk out of it learned yet).");
|
||||
return;
|
||||
}
|
||||
list.Add(new RecallOption
|
||||
{
|
||||
Name = name, SpellId = spellId, Ns = spot.Ns, Ew = spot.Ew, CastSeconds = SpellCastSeconds, Learned = true,
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@
|
|||
<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" />
|
||||
<Compile Include="..\Shared\RynthAiDungeonPathApi.cs" Link="Shared\RynthAiDungeonPathApi.cs" />
|
||||
<!-- The route maker for other plugins (2026-10-30): JSON jobs to make nav routes, plan, walk. -->
|
||||
<Compile Include="..\Shared\RynthNavRoutesApi.cs" Link="Shared\RynthNavRoutesApi.cs" />
|
||||
<!-- One logged, guarded way to use an object (who used what, and why). -->
|
||||
|
|
|
|||
|
|
@ -120,11 +120,15 @@ public sealed partial class RynthNavPlugin
|
|||
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 if (st.IsHub)
|
||||
{
|
||||
TownNetExit? hx = HubExitOf(i) ?? (_townNet != null && st.HubExit >= 0 && st.HubExit < _townNet.Exits.Count ? _townNet.Exits[st.HubExit] : null);
|
||||
parts.Add($"{TheHub(hx)} (exit {HubWhere(hx)})");
|
||||
}
|
||||
else
|
||||
{
|
||||
double d = NavCoords.Distance(pns, pew, st.Ns, st.Ew);
|
||||
parts.Add(nextHub ? $"walk {d:F0} yd to the Town Network portal"
|
||||
parts.Add(nextHub ? $"walk {d:F0} yd to the portal into {TheHub(HubExitOf(steps[i + 1]))}"
|
||||
: st.UsePortal ? $"walk {d:F0} yd, portal {st.Label}"
|
||||
: $"walk {d:F0} yd");
|
||||
}
|
||||
|
|
@ -149,7 +153,7 @@ public sealed partial class RynthNavPlugin
|
|||
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)
|
||||
if (PortalsRouting && !_landReplanned)
|
||||
{
|
||||
_landReplanned = true;
|
||||
Host.Log($"[RynthNav] no route over land to {name}: planning again with portals and recalls");
|
||||
|
|
@ -158,7 +162,7 @@ public sealed partial class RynthNavPlugin
|
|||
return;
|
||||
}
|
||||
string why = $"no walking route to {(onFinalLeg ? name : "the next step")} (water or cliffs in the way)";
|
||||
FinishGoto(_portalsEnabled
|
||||
FinishGoto(PortalsRouting
|
||||
? $"stopped: {why}, and no portal, recall or the Town Network I know of gets there"
|
||||
: $"stopped: {why}; turn on Use portals and recalls");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,8 @@ namespace RynthCore.Plugin.RynthNav;
|
|||
// little islands (Shoushi's plaza, where the Town Network drops you, 10-08); where the plan runs
|
||||
// out the walk heads straight for its goal for a moment (BlindPushTicks), and that, or a wall the
|
||||
// mesh doesn't show, used to mean running into it until the 30 s progress watchdog. Now: blocked
|
||||
// for StuckWindowMs = turn away toward open ground (WalkSteer.UnstickHeading), remember the spot as
|
||||
// for StuckWindowMs = (since 2026-10-30, the first block at a spot: a running jump on the same
|
||||
// heading, over a fence or a step) turn away toward open ground (WalkSteer.UnstickHeading), remember the spot as
|
||||
// something to keep out of (the next plan bends round it, like round a portal), plan again, and
|
||||
// after StuckMaxTries on one leg without progress stop and say where.
|
||||
//
|
||||
|
|
@ -19,10 +20,14 @@ namespace RynthCore.Plugin.RynthNav;
|
|||
// it turned 120 degrees off, alternating sides, ran 1.6 s, planned the same path again and ran back
|
||||
// into the same spot, four times in 20 s, then stopped. The remembered spots now make each new
|
||||
// plan go round what it ran into.
|
||||
//
|
||||
// 11-07 (Silentkelpie: "routes are still getting stuck at walls that could be jumped"): the jump was a
|
||||
// tap of the key, the smallest hop AC has, and the character had moved 0.0 u after it every time; and a
|
||||
// walk swinging between headings against a wall never counted as blocked. Now (WallStuck.cs) the stuck
|
||||
// watch counts turning too, and the jump is charged (0.6 s, then a full 1 s) and let go with run and
|
||||
// forward held. Both jumps at a spot come before stepping round it.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const long StuckWindowMs = 1200; // running this long...
|
||||
private const double StuckMoveUnits = 0.6; // ...and moved less than this = blocked (a run covers 4+ u/s)
|
||||
private const long UnstickMs = 1600; // then turn away from it and run this long (~0.5 s of it turning)
|
||||
private const int StuckMaxTries = 4; // blocked this often on a leg without progress = stop
|
||||
private const double BlockedAheadUnits = 3.5; // the remembered spot: this far ahead of where it stuck...
|
||||
|
|
@ -30,19 +35,34 @@ public sealed partial class RynthNavPlugin
|
|||
private const int BlockedMaxSpots = 12;
|
||||
private const double UnstickOpenUnits = 6.0; // a way out is open ground this far along it
|
||||
|
||||
private bool _ranLastTick; // the walk asked to run last tick (not standing, not turning in place)
|
||||
private double _lastDriveDeg;
|
||||
private long _stuckWinMs, _unstickUntilMs;
|
||||
private double _stuckWx, _stuckWy, _unstickDeg;
|
||||
private long _unstickUntilMs;
|
||||
private double _unstickDeg, _jumpDeg;
|
||||
private int _stuckTries, _stuckSide = 1;
|
||||
private readonly StuckWatch _stuck = new();
|
||||
private readonly WallJump _jump = new();
|
||||
private readonly List<PortalAvoid.Spot> _blockedSpots = new();
|
||||
|
||||
/// <summary>DriveTo for the walk's own steering: remembers that it ran and which way.</summary>
|
||||
/// <summary>DriveTo for the walk's own steering: remembers which way, and that it wanted to move.</summary>
|
||||
private void WalkDrive(double deg)
|
||||
{
|
||||
DriveTo(deg, _steerOpen);
|
||||
_lastDriveDeg = deg;
|
||||
_ranLastTick = !_steerOpen.TurnInPlace;
|
||||
_stuck.Wanted(NowMs, running: !_steerOpen.TurnInPlace);
|
||||
}
|
||||
|
||||
/// <summary>Lets go of a charged jump: with run and forward held (the run's momentum), else a plain release.</summary>
|
||||
private void ReleaseJump()
|
||||
{
|
||||
if (Host.HasLaunchJumpWithMotion) Host.LaunchJumpWithMotion(shift: true, holdW: true, holdX: false, holdZ: false, holdC: false);
|
||||
else if (Host.HasDoJump) Host.DoJump(true);
|
||||
}
|
||||
|
||||
/// <summary>A jump that is charging or in the air ends (a new leg, the goto over): let go of the key.</summary>
|
||||
private void CancelJump()
|
||||
{
|
||||
if (_jump.Now == WallJump.Phase.Charging) ReleaseJump();
|
||||
_jump.Reset();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -92,8 +112,11 @@ public sealed partial class RynthNavPlugin
|
|||
/// <summary>A new leg (or goto): nothing blocked yet.</summary>
|
||||
private void ResetBlocked()
|
||||
{
|
||||
_ranLastTick = false;
|
||||
_stuckWinMs = 0; _unstickUntilMs = 0; _stuckTries = 0;
|
||||
if (_doorStep != DoorStep.None) ResetDoor();
|
||||
_stuck.Reset();
|
||||
CancelJump();
|
||||
_lockedDoorHere = false;
|
||||
_unstickUntilMs = 0; _stuckTries = 0;
|
||||
_blockedSpots.Clear();
|
||||
}
|
||||
|
||||
|
|
@ -104,8 +127,22 @@ public sealed partial class RynthNavPlugin
|
|||
private bool StepBlocked()
|
||||
{
|
||||
long now = NowMs;
|
||||
bool ran = _ranLastTick;
|
||||
_ranLastTick = false;
|
||||
// A jump under way: hold the heading, let go of the key when charged, look again once landed.
|
||||
if (_jump.Busy)
|
||||
{
|
||||
DriveTo(_jumpDeg);
|
||||
switch (_jump.Tick(now))
|
||||
{
|
||||
case WallJump.Step.Release:
|
||||
ReleaseJump();
|
||||
break;
|
||||
case WallJump.Step.Landed:
|
||||
_stuck.Reset();
|
||||
return false;
|
||||
}
|
||||
lock (_gate) _status = $"blocked: jumping ({_jump.Tries}/{_jump.Plan.Length})";
|
||||
return true;
|
||||
}
|
||||
if (_unstickUntilMs > now)
|
||||
{
|
||||
DriveTo(_unstickDeg, _steerOpen);
|
||||
|
|
@ -118,20 +155,52 @@ public sealed partial class RynthNavPlugin
|
|||
_unstickUntilMs = 0;
|
||||
lock (_gotoGate) _gotoPath = null;
|
||||
_blindTicks = 0; _replanTick = 0;
|
||||
_stuckWinMs = 0;
|
||||
_stuck.Reset();
|
||||
return false;
|
||||
}
|
||||
if (!_stuck.Check(now, _wx, _wy, out double moved, out long windowMs))
|
||||
{
|
||||
if (windowMs > 0) _jump.Moved(); // a window ended with progress: the next spot gets its jumps
|
||||
return false;
|
||||
}
|
||||
if (!ran || _stuckWinMs == 0) { _stuckWinMs = now; _stuckWx = _wx; _stuckWy = _wy; return false; }
|
||||
if (now - _stuckWinMs < StuckWindowMs) return false;
|
||||
double moved = Math.Sqrt((_wx - _stuckWx) * (_wx - _stuckWx) + (_wy - _stuckWy) * (_wy - _stuckWy));
|
||||
_stuckWinMs = now; _stuckWx = _wx; _stuckWy = _wy;
|
||||
if (moved >= StuckMoveUnits) return false;
|
||||
|
||||
string at = NavCoords.Fmt(NavCoords.NsFromWorld(_wy), NavCoords.EwFromWorld(_wx));
|
||||
// A closed door in front of us: open it first (GotoDoor works it from the next tick).
|
||||
if (OpenDoorInFront())
|
||||
{
|
||||
AutoRun.Halt();
|
||||
lock (_gate) _status = "blocked: opening a door";
|
||||
return true;
|
||||
}
|
||||
// First jump on the same heading, charged (a fence, a step, a low wall the mesh smooths over); only
|
||||
// then step round it. Since 2026-11-07 the jumps of a spot come from the character's jump (buffed
|
||||
// Jump skill, burden) and how high the thing is (RynthNavPlugin.Jump.cs): just enough, then a full
|
||||
// one, or none when nothing clears it.
|
||||
if (_jump.Tries == 0 && (Host.HasCommenceJump || Host.HasTapJump)) PlanJumpHere(at);
|
||||
if (_jump.CanTry && (Host.HasCommenceJump || Host.HasTapJump))
|
||||
{
|
||||
_jumpDeg = _lastDriveDeg;
|
||||
DriveTo(_jumpDeg);
|
||||
string how;
|
||||
if (Host.HasCommenceJump && Host.CommenceJump())
|
||||
how = $"a charged jump ({_jump.StartCharged(now)} ms{(_jump.Hard ? ", jumping hard" : "")})";
|
||||
else
|
||||
{
|
||||
Host.TapJump();
|
||||
_jump.StartTap(now);
|
||||
how = "a tap jump (no charged jump in this engine)";
|
||||
}
|
||||
Host.Log($"[RynthNav] walk: blocked at {at} heading {_jumpDeg:F0} (moved {moved:F1}u in {windowMs / 1000.0:F1} s): {how}, try {_jump.Tries}/{_jump.Plan.Length}");
|
||||
lock (_gate) _status = $"blocked: jumping ({_jump.Tries}/{_jump.Plan.Length})";
|
||||
return true;
|
||||
}
|
||||
bool hard = _jump.Hard;
|
||||
_jump.Reset();
|
||||
_jump.Hard = hard;
|
||||
if (++_stuckTries > StuckMaxTries)
|
||||
{
|
||||
string why; lock (_gate) why = _status;
|
||||
FinishGoto($"stopped: blocked at {at} ({StuckMaxTries} tries to get round it; something in the way the map doesn't show) ({why})");
|
||||
FinishGoto($"stopped: blocked at {at} ({StuckMaxTries} tries to get round it, jumping first each time; something in the way the map doesn't show) ({why})");
|
||||
return true;
|
||||
}
|
||||
// Remember what it ran into, so the next plans go round it (RefreshAvoid adds these).
|
||||
|
|
@ -148,7 +217,7 @@ public sealed partial class RynthNavPlugin
|
|||
return WalkableStraight(_wx, _wy, _wx + Math.Sin(r) * UnstickOpenUnits, _wy + Math.Cos(r) * UnstickOpenUnits);
|
||||
});
|
||||
_unstickUntilMs = now + UnstickMs;
|
||||
Host.Log($"[RynthNav] walk: blocked at {at} heading {_lastDriveDeg:F0} (moved {moved:F1}u in {StuckWindowMs / 1000.0:F1} s); "
|
||||
Host.Log($"[RynthNav] walk: blocked at {at} heading {_lastDriveDeg:F0} (moved {moved:F1}u in {windowMs / 1000.0:F1} s, jumped {_jump.Plan.Length}x); "
|
||||
+ $"turning to {_unstickDeg:F0}, keeping out of that spot ({_blockedSpots.Count} so far) and planning again ({_stuckTries}/{StuckMaxTries})");
|
||||
DriveTo(_unstickDeg, _steerOpen);
|
||||
lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})";
|
||||
|
|
|
|||
|
|
@ -0,0 +1,364 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Custom-server portals (CustomPortals.cs): "/rnav portals scan" writes down the portal objects
|
||||
// around you, taking a portal learns where it lands, and the route planner gets this server's
|
||||
// portals with both ends on the map on top of portals.tsv (2026-10-29). Tick thread.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const string CustomPortalsFile = "custom-portals.txt";
|
||||
private const string DungeonWalksFile = "custom-dungeon-walks.txt";
|
||||
/// <summary>The portal you took: the live portal object this close to where portal space began.</summary>
|
||||
private const double UsedPortalUnits = 10.0;
|
||||
|
||||
private CustomPortalStore _custom = new();
|
||||
private volatile CustomPortalStore? _loadedCustom;
|
||||
private bool _customLoaded;
|
||||
private int _savedCustomVersion;
|
||||
|
||||
/// <summary>The server the client logged into (its world name); "" before login.</summary>
|
||||
private string _server = "";
|
||||
|
||||
// The route list: portals.tsv plus this server's custom portals, rebuilt when either changes.
|
||||
private List<PortalLink>? _routePortals;
|
||||
private (string Server, int Version, int BaseCount) _routePortalsKey;
|
||||
|
||||
// The portal object nearest you as portal space began (learned from the teleport that follows).
|
||||
private bool _usedPortalSeen;
|
||||
private string _usedPortalName = "";
|
||||
private uint _usedPortalWcid, _usedPortalCell;
|
||||
private double _usedPortalNs, _usedPortalEw;
|
||||
// ...standing in a dungeon: where in it (landblock-local), and the way walked to it since the landing.
|
||||
private bool _usedPortalInDungeon;
|
||||
private double _usedPortalX, _usedPortalY, _usedPortalZ;
|
||||
private double[]? _usedTrail;
|
||||
private uint _usedTrailCell;
|
||||
private bool _usedTrailFromLanding;
|
||||
|
||||
private void LoadCustomPortals()
|
||||
{
|
||||
string path = NavFile(CustomPortalsFile), walks = NavFile(DungeonWalksFile);
|
||||
Task.Run(() =>
|
||||
{
|
||||
CustomPortalStore s = new();
|
||||
try
|
||||
{
|
||||
string? text = File.Exists(path) ? File.ReadAllText(path) : null;
|
||||
string? walkText = File.Exists(walks) ? File.ReadAllText(walks) : null;
|
||||
s = CustomPortalStore.Parse(text, walkText);
|
||||
}
|
||||
catch (Exception ex) { Host.Log($"[RynthNav] {CustomPortalsFile}: {ex.Message}"); }
|
||||
_loadedCustom = s;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Takes the loaded store once, and saves it when it changes. Tick thread.</summary>
|
||||
private void TickCustomPortals(bool force = false)
|
||||
{
|
||||
if (!_customLoaded)
|
||||
{
|
||||
if (_loadedCustom is not { } loaded) return;
|
||||
_custom = loaded; _customLoaded = true; _savedCustomVersion = _custom.Version;
|
||||
int n = 0, w = 0; foreach (string s in _custom.Servers) { n += _custom.For(s).Count; w += _custom.WalksFor(s).Count; }
|
||||
if (n + w > 0) Host.Log($"[RynthNav] custom portals: {n} saved, {w} dungeon walk(s) ({string.Join(", ", _custom.Servers)})");
|
||||
}
|
||||
if (_custom.Version != _savedCustomVersion || force)
|
||||
{
|
||||
_savedCustomVersion = _custom.Version;
|
||||
WriteLater(CustomPortalsFile, _custom.Serialize());
|
||||
WriteLater(DungeonWalksFile, _custom.SerializeWalks());
|
||||
}
|
||||
RefreshCustomCounts();
|
||||
}
|
||||
|
||||
/// <summary>The server key for the custom portals: the world name, or "" before it's known.</summary>
|
||||
private string CurrentServer()
|
||||
{
|
||||
if (_server.Length == 0 && Host.TryGetWorldName(out string world) && world.Trim().Length > 0) _server = world.Trim();
|
||||
return _server;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The portals the route planner uses: portals.tsv, plus the logged-in server's custom portals
|
||||
/// with both ends on the map. Null when portals.tsv hasn't been loaded.
|
||||
/// </summary>
|
||||
private List<PortalLink>? RoutePortals()
|
||||
{
|
||||
if (_portals == null) return null;
|
||||
string server = CurrentServer();
|
||||
var key = (server, _custom.Version, _portals.Count);
|
||||
if (_routePortals != null && key == _routePortalsKey) return _routePortals;
|
||||
List<PortalLink> custom = server.Length > 0 ? _custom.Links(server) : new List<PortalLink>();
|
||||
if (custom.Count == 0) _routePortals = _portals;
|
||||
else
|
||||
{
|
||||
_routePortals = new List<PortalLink>(_portals.Count + custom.Count);
|
||||
_routePortals.AddRange(_portals);
|
||||
_routePortals.AddRange(custom);
|
||||
Host.Log($"[RynthNav] route portals: {_portals.Count} from portals.tsv + {custom.Count} custom for {server}");
|
||||
}
|
||||
_routePortalsKey = key;
|
||||
return _routePortals;
|
||||
}
|
||||
|
||||
/// <summary>A live object's map spot: true with its world position when it's a portal standing on the map.</summary>
|
||||
private bool LivePortalAt(uint id, out uint cell, out double wx, out double wy, out string name) =>
|
||||
LivePortalAt(id, out cell, out wx, out wy, out _, out name);
|
||||
|
||||
/// <summary>As above, with its height (z).</summary>
|
||||
private bool LivePortalAt(uint id, out uint cell, out double wx, out double wy, out double wz, out string name)
|
||||
{
|
||||
cell = 0; wx = wy = wz = 0; name = "";
|
||||
if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) return false;
|
||||
if (!Host.TryGetObjectPosition(id, out cell, out float x, out float y, out float z) || cell == 0) return false;
|
||||
wz = z;
|
||||
wx = ((cell >> 24) & 0xFF) * 192.0 + x; wy = ((cell >> 16) & 0xFF) * 192.0 + y;
|
||||
Host.TryGetObjectName(id, out name);
|
||||
name ??= "";
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── /rnav portals scan ─────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Writes down every portal object the client knows around you, for this server.</summary>
|
||||
private void ScanCustomPortals(double radiusYards)
|
||||
{
|
||||
string server = CurrentServer();
|
||||
if (server.Length == 0) { Say("portal scan: not logged in yet (no server name)"); return; }
|
||||
if (!Host.HasGetLiveObjectIds) { Say("portal scan: this RynthCore engine can't list the objects around you"); return; }
|
||||
if (!_customLoaded) { Say("portal scan: the saved portals are still loading; try again in a moment"); return; }
|
||||
EnsurePortalsLoaded();
|
||||
var seen = new Dictionary<CustomScanResult, int>();
|
||||
var added = new List<string>();
|
||||
int portals = 0;
|
||||
DateTime now = DateTime.UtcNow;
|
||||
int inDungeon = 0;
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!LivePortalAt(id, out uint cell, out double wx, out double wy, out double wz, out string name)) continue;
|
||||
if (_hasPose && radiusYards > 0 && Math.Sqrt((wx - _wx) * (wx - _wx) + (wy - _wy) * (wy - _wy)) > radiusYards) continue;
|
||||
portals++;
|
||||
bool onMap = IsOnMap(cell);
|
||||
double ns = NavCoords.NsFromWorld(wy), ew = NavCoords.EwFromWorld(wx);
|
||||
Host.TryGetObjectWcid(id, out uint wcid);
|
||||
if (!onMap)
|
||||
{
|
||||
// Inside a dungeon: kept where it stands in it; its landing (and the walk to it) is learned by taking it.
|
||||
double lx = wx - ((cell >> 24) & 0xFF) * 192.0, ly = wy - ((cell >> 16) & 0xFF) * 192.0;
|
||||
CustomScanResult d = _custom.SawInDungeon(server, name, wcid, cell, lx, ly, wz, now);
|
||||
inDungeon++;
|
||||
if (d == CustomScanResult.Added) added.Add($"{name} (in dungeon {cell >> 16:X4})");
|
||||
seen[d] = seen.TryGetValue(d, out int dc) ? dc + 1 : 1;
|
||||
continue;
|
||||
}
|
||||
CustomScanResult r = _custom.Saw(server, name, wcid, cell, onMap, ns, ew, _portals, now);
|
||||
seen[r] = seen.TryGetValue(r, out int c) ? c + 1 : 1;
|
||||
if (r == CustomScanResult.Added) added.Add($"{name} {NavCoords.Fmt(ns, ew)}");
|
||||
}
|
||||
int Count(CustomScanResult r) => seen.TryGetValue(r, out int c) ? c : 0;
|
||||
int total = _custom.For(server).Count, routable = _custom.Links(server).Count;
|
||||
Say($"portal scan ({server}{(radiusYards > 0 ? $", {radiusYards:0} yd" : "")}): {portals} portal(s) seen — "
|
||||
+ $"{Count(CustomScanResult.Added)} new, {Count(CustomScanResult.Updated)} already saved, "
|
||||
+ $"{Count(CustomScanResult.BuiltIn)} already in the world data, {inDungeon} inside a dungeon.");
|
||||
foreach (string a in added) Say(" new: " + a);
|
||||
if (Count(CustomScanResult.Added) > 0)
|
||||
Say("A new portal's landing is learned the first time you take it; then routes use it. "
|
||||
+ $"This server: {total} saved, {routable} with a known landing.");
|
||||
Host.Log($"[RynthNav] portal scan {server}: seen {portals}, added {Count(CustomScanResult.Added)}, updated {Count(CustomScanResult.Updated)}, "
|
||||
+ $"built-in {Count(CustomScanResult.BuiltIn)}, in a dungeon {inDungeon}; {total} saved, {routable} routable");
|
||||
}
|
||||
|
||||
// ── Learning a landing from the teleport ───────────────────────────────
|
||||
|
||||
/// <summary>Portal space began: remember the live portal nearest where you stood (the one you took, if any).</summary>
|
||||
private void NoteUsedPortal(bool havePos, uint cell, double wx, double wy, double wz)
|
||||
{
|
||||
_usedPortalSeen = false;
|
||||
_usedPortalInDungeon = false;
|
||||
_usedTrail = null;
|
||||
if (!havePos || !Host.HasGetLiveObjectIds) return;
|
||||
bool onMap = IsOnMap(cell);
|
||||
if (!onMap && (cell & 0xFFFF) < 0x100) return;
|
||||
double best = UsedPortalUnits * UsedPortalUnits;
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!LivePortalAt(id, out uint pc, out double px, out double py, out double pz, out string name)) continue;
|
||||
if (!onMap && ((pc >> 16) != (cell >> 16) || Math.Abs(pz - wz) > 4.0)) continue; // a dungeon: this one, this floor
|
||||
double d2 = (px - wx) * (px - wx) + (py - wy) * (py - wy);
|
||||
if (d2 >= best) continue;
|
||||
best = d2;
|
||||
Host.TryGetObjectWcid(id, out uint wcid);
|
||||
_usedPortalSeen = true;
|
||||
_usedPortalName = name; _usedPortalWcid = wcid; _usedPortalCell = pc;
|
||||
_usedPortalNs = NavCoords.NsFromWorld(py); _usedPortalEw = NavCoords.EwFromWorld(px);
|
||||
_usedPortalInDungeon = !onMap;
|
||||
_usedPortalX = px - ((pc >> 24) & 0xFF) * 192.0; _usedPortalY = py - ((pc >> 16) & 0xFF) * 192.0; _usedPortalZ = pz;
|
||||
}
|
||||
if (!_usedPortalSeen && RecentNearPortal(wx, wy, out uint rc, out double rx, out double ry, out double rz, out string rn, out uint rw)
|
||||
&& (onMap || (rc >> 16) == (cell >> 16)))
|
||||
{
|
||||
_usedPortalSeen = true;
|
||||
_usedPortalName = rn; _usedPortalWcid = rw; _usedPortalCell = rc;
|
||||
_usedPortalNs = NavCoords.NsFromWorld(ry); _usedPortalEw = NavCoords.EwFromWorld(rx);
|
||||
_usedPortalInDungeon = !onMap;
|
||||
_usedPortalX = rx - ((rc >> 24) & 0xFF) * 192.0; _usedPortalY = ry - ((rc >> 16) & 0xFF) * 192.0; _usedPortalZ = rz;
|
||||
}
|
||||
_nearPortalSeen = false;
|
||||
// The way walked in this dungeon to it (DungeonWalks): kept until the landing says where it went.
|
||||
if (_usedPortalSeen && _usedPortalInDungeon && _trail.Count > 0 && !_trail.Overflow && _trail.Landblock == (cell >> 16))
|
||||
{
|
||||
_usedTrail = _trail.To(_usedPortalX, _usedPortalY, _usedPortalZ);
|
||||
_usedTrailCell = _trail.StartCell;
|
||||
_usedTrailFromLanding = _trail.FromLanding;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A teleport that wasn't a recall: if it began at a portal, learn where that portal lands.</summary>
|
||||
private void LearnCustomPortal(RecallSpot landing)
|
||||
{
|
||||
if (!_usedPortalSeen) return;
|
||||
_usedPortalSeen = false;
|
||||
string server = CurrentServer();
|
||||
if (server.Length == 0 || !_customLoaded) return;
|
||||
EnsurePortalsLoaded();
|
||||
// A landing in a dungeon: where in it (the arrival a learned walk starts from).
|
||||
bool destPos = !landing.OnMap && _hasPose;
|
||||
double dx = destPos ? LocalX : 0, dy = destPos ? LocalY : 0, dz = destPos ? _wz : 0;
|
||||
DateTime now = DateTime.UtcNow;
|
||||
// A portal doesn't set you down beside itself: that's the tail of a teleport already counted
|
||||
// (portal space seen late), with the "used" portal one standing at the landing.
|
||||
if (_usedPortalInDungeon ? !landing.OnMap && (_usedPortalCell >> 16) == CurrentLandblock
|
||||
&& Math.Sqrt((_usedPortalX - dx) * (_usedPortalX - dx) + (_usedPortalY - dy) * (_usedPortalY - dy)) < 10.0
|
||||
: landing.OnMap && NavCoords.Distance(_usedPortalNs, _usedPortalEw, landing.Ns, landing.Ew) < 20.0)
|
||||
{
|
||||
Host.Log($"[RynthNav] custom portal: '{_usedPortalName}' would land beside itself; not learned");
|
||||
_usedTrail = null;
|
||||
return;
|
||||
}
|
||||
string where = landing.OnMap ? $"{NavCoords.Fmt(landing.Ns, landing.Ew)} ({landing.Label})" : landing.Label;
|
||||
if (_usedPortalInDungeon)
|
||||
{
|
||||
CustomPortal d = _custom.LearnedInDungeon(server, _usedPortalName, _usedPortalWcid, _usedPortalCell, _usedPortalX, _usedPortalY, _usedPortalZ,
|
||||
landing.OnMap, landing.Ns, landing.Ew, _cellId, destPos, dx, dy, dz, now);
|
||||
bool walked = false;
|
||||
if (_usedTrail != null)
|
||||
{
|
||||
var w = new DungeonWalk
|
||||
{
|
||||
Landblock = _usedPortalCell >> 16, ArrivalCell = _usedTrailCell,
|
||||
ArrivalX = _usedTrail[0], ArrivalY = _usedTrail[1], ArrivalZ = _usedTrail[2], FromLanding = _usedTrailFromLanding,
|
||||
ExitName = d.Name, ExitCell = d.Cell, ExitX = d.X, ExitY = d.Y, ExitZ = d.Z,
|
||||
Points = _usedTrail, LearnedUtc = now,
|
||||
};
|
||||
walked = _custom.AddWalk(server, w);
|
||||
Host.Log($"[RynthNav] dungeon walk ({server}, lb 0x{w.Landblock:X4}): {w.Count} points, {w.Length:F0} m to {d.Name}{(walked ? "" : " (a shorter one is kept)")}");
|
||||
}
|
||||
_usedTrail = null;
|
||||
CustomLearnResult dr = _custom.LastLearn;
|
||||
if (dr == CustomLearnResult.AlreadyKnown)
|
||||
{
|
||||
// Taken before, same landing: nothing new (a shorter walk to it is still worth a word).
|
||||
Host.Log($"[RynthNav] custom portal: {d.Name} in dungeon 0x{d.Landblock:X4} → {where}: already known{(walked ? "; a shorter walk to it is kept" : "")}");
|
||||
if (walked) Say($"portal '{d.Name}': a shorter walk to it is kept");
|
||||
return;
|
||||
}
|
||||
Host.Log($"[RynthNav] custom portal {(dr == CustomLearnResult.New ? "learned" : "landing updated")} ({server}): {d.Name} in dungeon 0x{d.Landblock:X4} at {d.X:F1},{d.Y:F1} → {where}");
|
||||
Say($"{(dr == CustomLearnResult.New ? "learned" : "updated")} portal '{d.Name}' inside the dungeon → {where}"
|
||||
+ (walked ? " — the walk to it is kept, so routes can go through this dungeon" : ""));
|
||||
return;
|
||||
}
|
||||
CustomPortal? p = _custom.Learned(server, _usedPortalName, _usedPortalWcid, _usedPortalCell, _usedPortalNs, _usedPortalEw,
|
||||
landing.OnMap, landing.Ns, landing.Ew, _cellId, destPos, dx, dy, dz, _portals, now);
|
||||
if (p == null) return; // the world data routes it already
|
||||
CustomLearnResult r = _custom.LastLearn;
|
||||
if (r == CustomLearnResult.AlreadyKnown)
|
||||
{
|
||||
Host.Log($"[RynthNav] custom portal: {p.Name} at {NavCoords.Fmt(p.Ns, p.Ew)} → {where}: already known");
|
||||
return;
|
||||
}
|
||||
Host.Log($"[RynthNav] custom portal {(r == CustomLearnResult.New ? "learned" : "landing updated")} ({server}): {p.Name} at {NavCoords.Fmt(p.Ns, p.Ew)} → {where}");
|
||||
Say($"{(r == CustomLearnResult.New ? "learned" : "updated")} portal '{p.Name}' → {where}" + (p.Routable ? " — routes can use it now"
|
||||
: " (lands in a dungeon: routes go through it once a walk inside to one of its portals is learned)"));
|
||||
}
|
||||
|
||||
// ── Commands ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>/rnav portals on|off|scan [yd]|list|forget <name>|clear. Tick thread.</summary>
|
||||
private void CmdPortals(string rest)
|
||||
{
|
||||
string arg = rest.Trim();
|
||||
int sp = arg.IndexOf(' ');
|
||||
string sub = (sp < 0 ? arg : arg.Substring(0, sp)).ToLowerInvariant();
|
||||
string tail = sp < 0 ? "" : arg.Substring(sp + 1).Trim();
|
||||
string server = CurrentServer();
|
||||
switch (sub)
|
||||
{
|
||||
case "":
|
||||
case "on":
|
||||
case "off":
|
||||
_portalsEnabled = sub != "off";
|
||||
NavDataConfig.WriteSwitch("portals", _portalsEnabled);
|
||||
Say($"portal and recall routing {(_portalsEnabled ? "ON" : "OFF")} for walking (go/goto)"
|
||||
+ (server.Length > 0 ? $"; {server}: {_custom.Links(server).Count} custom portal(s) in routes" : ""));
|
||||
break;
|
||||
case "learn":
|
||||
{
|
||||
string l = tail.ToLowerInvariant();
|
||||
if (l is "" or "start" or "on") StartLearn();
|
||||
else if (l is "stop" or "off") { if (LearningPortals) StopLearn("stopped", stopWalk: true); else Say("not learning portals"); }
|
||||
else if (l.StartsWith("range", StringComparison.Ordinal))
|
||||
{
|
||||
string n = l.Substring(5).Trim();
|
||||
if (n.Length == 0) { Say($"learn range {_learnRange:0} yd ({LearnRangeMin:0}-{LearnRangeMax:0})"); break; }
|
||||
if (!double.TryParse(n, NumberStyles.Float, CultureInfo.InvariantCulture, out double r))
|
||||
{ Say($"portals learn range <yards {LearnRangeMin:0}-{LearnRangeMax:0}>"); break; }
|
||||
SetLearnRange(r);
|
||||
}
|
||||
else Say("portals learn | learn stop | learn range <yd> — try every portal in range (and the portals inside the dungeons they lead to), learn where each lands, come back, repeat");
|
||||
break;
|
||||
}
|
||||
case "scan":
|
||||
double yd = 0;
|
||||
if (tail.Length > 0 && (!double.TryParse(tail, NumberStyles.Float, CultureInfo.InvariantCulture, out yd) || yd < 5 || yd > 1000))
|
||||
{ Say("portals scan [yards 5-1000] — without a distance, every portal the client knows around you"); return; }
|
||||
ScanCustomPortals(yd);
|
||||
break;
|
||||
case "list":
|
||||
{
|
||||
if (server.Length == 0) { Say("not logged in yet (no server name)"); return; }
|
||||
IReadOnlyList<CustomPortal> list = _custom.For(server);
|
||||
if (list.Count == 0) { Say($"no custom portals saved for {server} — /rnav portals scan"); return; }
|
||||
Say($"custom portals for {server}: {list.Count} ({_custom.Links(server).Count} map-to-map links); {_custom.WalksFor(server).Count} walk(s) learned inside dungeons");
|
||||
int shown = 0;
|
||||
foreach (CustomPortal p in list)
|
||||
{
|
||||
if (++shown > 40) { Say($" ... and {list.Count - 40} more ({CustomPortalsFile} in {NavDataDir})"); break; }
|
||||
string dest = !p.DestKnown ? "landing not learned yet (take it once)"
|
||||
: p.DestOnMap ? "→ " + NavCoords.Fmt(p.DestNs, p.DestEw) : $"→ a dungeon (landblock {p.DestCell >> 16:X4})";
|
||||
string at = p.OnMap ? NavCoords.Fmt(p.Ns, p.Ew) : $"in dungeon {p.Landblock:X4} ({p.X:F0}, {p.Y:F0})";
|
||||
Say($" {p.Name} {at} {dest}");
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "forget":
|
||||
if (server.Length == 0 || tail.Length == 0) { Say("portals forget <name> — forgets this server's custom portals with that in their name"); return; }
|
||||
Say($"forgot {_custom.Forget(server, tail)} custom portal(s) named like '{tail}' on {server}");
|
||||
break;
|
||||
case "clear":
|
||||
if (server.Length == 0) { Say("not logged in yet (no server name)"); return; }
|
||||
if (!tail.Equals("confirm", StringComparison.OrdinalIgnoreCase))
|
||||
{ Say($"portals clear confirm — forgets all {_custom.For(server).Count} custom portal(s) saved for {server}"); return; }
|
||||
Say($"forgot all {_custom.Clear(server)} custom portal(s) for {server}");
|
||||
break;
|
||||
default:
|
||||
Say("portals on|off | scan [yd] | learn [stop | range <yd>] | list | forget <name> | clear confirm — custom portals are kept per server");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
432
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Doors.cs
Normal file
432
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Doors.cs
Normal file
|
|
@ -0,0 +1,432 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Doors, locks, jumps and drops on RynthNav's walks inside dungeons (2026-10-30). The walks (a
|
||||
// route's way through a learned dungeon, the learn-portals walk) went straight at a closed door
|
||||
// until the 8 s stuck clock stopped them, never jumped, and the dungeon pathfinder never planned a
|
||||
// way down a ledge. Now, each tick of a dungeon walk (WalkDoor, before the walker steps):
|
||||
// - a closed door across the walk in the next 10 m (WalkDoors.AlongWalk) is used (the server
|
||||
// walks you to it and swings it open); the walk holds while it opens, its clocks waiting too;
|
||||
// - a door still closed after the server answered ("The door is locked!", or two uses that
|
||||
// didn't open it) is unlocked with what the pack has: each key or keyring once, then each
|
||||
// lockpick up to three times (a pick can fail on skill), opening it again after each;
|
||||
// - a door nothing opens is remembered (this session) and the walk is planned again round it
|
||||
// (RynthAi's dungeon pathfinder leaves its doorway out); no other way: the walk stops and says so.
|
||||
// The walker jumps (running on) when it makes no progress for 2 s, twice per spot, before giving up
|
||||
// at 8 s (HubWalker.Act.Jump). Planned walks may drop down a ledge or shaft up to "/rnav doors
|
||||
// drops" metres (8 by default; never up), and on a walk over several levels a point is reached only
|
||||
// on its own level (HubWalker.LevelOk). "/rnav doors" for the switches.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const uint BitfieldDoor = 0x1000;
|
||||
private const uint PhysicsEthereal = 0x4; // CPhysicsObj state: an open door is ethereal
|
||||
private const long DoorScanMs = 250;
|
||||
private const double DoorUseUnits = 6.0; // use a door across the walk this close (along the walk)
|
||||
private const long DoorAnswerMs = 6000; // a use with no answer this long is lost
|
||||
private const long DoorSettleMs = 1200; // answered, and still closed this long after: it didn't open
|
||||
private const int DoorMaxUses = 3;
|
||||
private const int DoorPickTries = 3;
|
||||
private const long DoorOpenSkipMs = 30_000; // an opened door isn't looked at again for this long
|
||||
private const long DoorBlockedSkipMs = 300_000; // nor a door nothing opened
|
||||
private const double DropMetersDefault = 8.0;
|
||||
|
||||
private enum DoorStep { None, Opening, Unlocking }
|
||||
internal enum DoorAct { None, Busy, Blocked }
|
||||
|
||||
private bool _doorsEnabled = true, _unlockEnabled = true;
|
||||
private double _dropMeters = DropMetersDefault;
|
||||
private DoorStep _doorStep;
|
||||
private uint _doorId;
|
||||
private string _doorName = "";
|
||||
private long _doorSentMs, _doorAnsweredMs, _doorLastTickMs, _nextDoorScanMs;
|
||||
private int _doorSeq, _doorUses;
|
||||
private bool _doorUnlockTried;
|
||||
private List<(uint Id, string Name, WalkDoors.Unlocker Kind)>? _doorUnlockers;
|
||||
private int _doorUnlockIdx, _doorPickUses;
|
||||
private long _doorLockedSaidMs = long.MinValue; // NowMs of the last "is locked" line (any thread: Interlocked)
|
||||
private readonly Dictionary<uint, long> _doorSkipUntil = new();
|
||||
private readonly List<(uint Lb, double X, double Y, double Z)> _lockedDoors = new();
|
||||
private int _lockedDoorVersion;
|
||||
private bool _doorNoStateSaid;
|
||||
|
||||
private void InitDoors()
|
||||
{
|
||||
_doorsEnabled = NavDataConfig.ReadSwitch("doors", true);
|
||||
_unlockEnabled = NavDataConfig.ReadSwitch("unlockDoors", true);
|
||||
_dropMeters = Math.Clamp(NavDataConfig.ReadNumber("dropMeters", DropMetersDefault), 0, 40);
|
||||
}
|
||||
|
||||
/// <summary>The locked doors found in dungeon <paramref name="lb"/> (landblock-local), for the pathfinder to go round.</summary>
|
||||
private List<(double X, double Y, double Z)> LockedDoorSpots(uint lb)
|
||||
{
|
||||
var list = new List<(double, double, double)>();
|
||||
foreach (var d in _lockedDoors) if (d.Lb == (lb & 0xFFFF)) list.Add((d.X, d.Y, d.Z));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>A chat line: the server's "The door is locked!" (any thread).</summary>
|
||||
private void NoteDoorText(string? text)
|
||||
{
|
||||
if (WalkDoors.IsLockedText(text)) System.Threading.Interlocked.Exchange(ref _doorLockedSaidMs, NowMs);
|
||||
}
|
||||
|
||||
private bool LockedSaidSince(long ms) => System.Threading.Interlocked.Read(ref _doorLockedSaidMs) >= ms;
|
||||
|
||||
/// <summary>Forgets the door being worked (a new walk, the goto ending).</summary>
|
||||
private void ResetDoor()
|
||||
{
|
||||
_doorStep = DoorStep.None;
|
||||
_doorId = 0; _doorName = "";
|
||||
_doorUses = 0; _doorUnlockTried = false;
|
||||
_doorUnlockers = null; _doorUnlockIdx = 0; _doorPickUses = 0;
|
||||
_doorLastTickMs = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Doors on a dungeon walk, before the walker steps: None (walk on), Busy (a door is being
|
||||
/// opened or unlocked: the walk holds), Blocked (a door across the walk nothing opens:
|
||||
/// <paramref name="why"/>; it is remembered, so a walk planned again goes round it).
|
||||
/// </summary>
|
||||
private DoorAct WalkDoor(HubWalker w, long now, out string why)
|
||||
{
|
||||
var ahead = new List<TownNetPoint>();
|
||||
foreach (var (_, p) in w.Ahead()) ahead.Add(p);
|
||||
return WalkDoor(ahead, w.Levels, (n, held) => w.Hold(n, held), now, out why);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The same for any walk (2026-11-01: the goto's own walk over land and through towns, not only the
|
||||
/// dungeon walks): <paramref name="ahead"/> are the walk's points still ahead in this landblock's
|
||||
/// local coordinates, <paramref name="hold"/> pauses the walk's clocks while a door is worked.
|
||||
/// </summary>
|
||||
private DoorAct WalkDoor(List<TownNetPoint> ahead, bool levels, Action<long, long> hold, long now, out string why)
|
||||
{
|
||||
why = "";
|
||||
if (!_doorsEnabled || !Host.HasUseObject || !Host.HasGetLiveObjectIds) return DoorAct.None;
|
||||
if (!Host.HasGetObjectState && !Host.HasGetObjectMotionOn)
|
||||
{
|
||||
if (!_doorNoStateSaid) { _doorNoStateSaid = true; Host.Log("[RynthNav] doors: this RynthCore engine can't tell an open door from a closed one: walks don't open doors"); }
|
||||
return DoorAct.None;
|
||||
}
|
||||
long held = _doorLastTickMs == 0 ? 0 : Math.Max(0, now - _doorLastTickMs);
|
||||
_doorLastTickMs = now;
|
||||
|
||||
if (_doorStep == DoorStep.None)
|
||||
{
|
||||
if (now < _nextDoorScanMs) { _doorLastTickMs = 0; return DoorAct.None; }
|
||||
_nextDoorScanMs = now + DoorScanMs;
|
||||
uint id = ClosedDoorAhead(ahead, levels, now, out double along, out string name);
|
||||
if (id == 0 || along > DoorUseUnits) { _doorLastTickMs = 0; return DoorAct.None; }
|
||||
_doorId = id; _doorName = name;
|
||||
_doorUses = 0; _doorUnlockTried = false; _doorUnlockers = null; _doorUnlockIdx = 0; _doorPickUses = 0;
|
||||
Host.Log($"[RynthNav] door: '{name}' (0x{id:X8}) is closed across the walk {along:F1} m ahead: opening it");
|
||||
lock (_gate) _status = $"opening the {name}";
|
||||
if (!SendDoorUse(now)) { ResetDoor(); return DoorAct.None; }
|
||||
hold(now, 0);
|
||||
return DoorAct.Busy;
|
||||
}
|
||||
|
||||
hold(now, held);
|
||||
AutoRun.Halt();
|
||||
if (DoorOpen(_doorId))
|
||||
{
|
||||
Host.Log($"[RynthNav] door: '{_doorName}' is open{(_doorUnlockTried ? " (unlocked)" : "")}");
|
||||
if (_doorUnlockTried) Say($"unlocked and opened the {_doorName}.");
|
||||
_doorSkipUntil[_doorId] = now + DoorOpenSkipMs;
|
||||
ResetDoor();
|
||||
return DoorAct.None;
|
||||
}
|
||||
|
||||
bool answered = DoorAnswered(out uint err);
|
||||
if (answered && _doorAnsweredMs == 0)
|
||||
{
|
||||
_doorAnsweredMs = now;
|
||||
if (err != 0) Host.Log($"[RynthNav] door: the server answered the {(_doorStep == DoorStep.Unlocking ? "unlock" : "use")} with error 0x{err:X}");
|
||||
}
|
||||
|
||||
if (_doorStep == DoorStep.Unlocking)
|
||||
{
|
||||
// The key or pick was answered (or lost): use the door again.
|
||||
if ((answered && now - _doorAnsweredMs >= 300) || now - _doorSentMs > DoorAnswerMs)
|
||||
{
|
||||
_doorStep = DoorStep.Opening;
|
||||
_doorUses = 0;
|
||||
if (!SendDoorUse(now)) return Blocked(now, "the door use wouldn't go out", false, out why);
|
||||
}
|
||||
return DoorAct.Busy;
|
||||
}
|
||||
|
||||
// Opening: answered and still closed a moment later, or no answer at all.
|
||||
bool settled = answered && now - _doorAnsweredMs >= DoorSettleMs;
|
||||
bool lost = !answered && now - _doorSentMs > DoorAnswerMs;
|
||||
if (!settled && !lost) return DoorAct.Busy;
|
||||
bool locked = LockedSaidSince(_doorSentMs) || (settled && _doorUses >= 2);
|
||||
if (locked || (_doorUnlockTried && settled))
|
||||
{
|
||||
if (!_unlockEnabled)
|
||||
return Blocked(now, $"the {_doorName} is locked (unlocking is off: /rnav doors unlock on)", true, out why);
|
||||
if (!SendUnlock(now, out string none))
|
||||
return Blocked(now, $"the {_doorName} is locked and {none}", true, out why);
|
||||
return DoorAct.Busy;
|
||||
}
|
||||
if (_doorUses >= DoorMaxUses)
|
||||
return Blocked(now, $"the {_doorName} didn't open after {_doorUses} uses", false, out why);
|
||||
Host.Log($"[RynthNav] door: '{_doorName}' still closed after use {_doorUses}{(lost ? " (no answer)" : "")}: using it again");
|
||||
if (!SendDoorUse(now)) return Blocked(now, "the door use wouldn't go out", false, out why);
|
||||
return DoorAct.Busy;
|
||||
}
|
||||
|
||||
private DoorAct Blocked(long now, string text, bool locked, out string why)
|
||||
{
|
||||
why = text;
|
||||
Host.Log($"[RynthNav] door: {text}");
|
||||
_doorSkipUntil[_doorId] = now + DoorBlockedSkipMs;
|
||||
if (_doorId != 0 && Host.TryGetObjectPosition(_doorId, out uint cell, out float x, out float y, out float z) && cell != 0)
|
||||
{
|
||||
_lockedDoors.Add(((cell >> 16) & 0xFFFF, x, y, z));
|
||||
_lockedDoorVersion++;
|
||||
// For a jump over the wall it sits in (RynthNavPlugin.Jump.cs TryJumpLockedDoor): world units.
|
||||
_lockedDoorHere = true;
|
||||
_lockedDoorX = ((cell >> 24) & 0xFF) * 192.0 + x;
|
||||
_lockedDoorY = ((cell >> 16) & 0xFF) * 192.0 + y;
|
||||
}
|
||||
ResetDoor();
|
||||
return DoorAct.Blocked;
|
||||
}
|
||||
|
||||
private bool SendDoorUse(long now)
|
||||
{
|
||||
_doorSeq = Host.HasUseDoneSeq ? Host.GetUseDoneSeq() : 0;
|
||||
bool sent = Host.UseFor(_doorId, "Goto", $"open the {_doorName} across the dungeon walk");
|
||||
_doorStep = DoorStep.Opening;
|
||||
_doorSentMs = now; _doorAnsweredMs = 0;
|
||||
if (sent) _doorUses++;
|
||||
return sent;
|
||||
}
|
||||
|
||||
/// <summary>The next key or lockpick from the pack on the door; false (<paramref name="why"/>) when none is left.</summary>
|
||||
private bool SendUnlock(long now, out string why)
|
||||
{
|
||||
why = "";
|
||||
_doorUnlockers ??= WalkDoors.TryOrder(PackItems());
|
||||
if (_doorUnlockers.Count == 0) { why = "there's no key or lockpick in your pack"; return false; }
|
||||
while (_doorUnlockIdx < _doorUnlockers.Count)
|
||||
{
|
||||
var u = _doorUnlockers[_doorUnlockIdx];
|
||||
bool pick = u.Kind == WalkDoors.Unlocker.Lockpick;
|
||||
if (_doorUnlockTried && (!pick || _doorPickUses >= DoorPickTries)) { _doorUnlockIdx++; _doorPickUses = 0; _doorUnlockTried = false; continue; }
|
||||
if (!Host.TryGetObjectName(u.Id, out _)) { _doorUnlockIdx++; _doorPickUses = 0; continue; } // used up
|
||||
_doorSeq = Host.HasUseDoneSeq ? Host.GetUseDoneSeq() : 0;
|
||||
if (!Host.UseOnFor(u.Id, _doorId, "Goto", $"unlock the {_doorName} on the dungeon walk")) { why = "the unlock wouldn't go out"; return false; }
|
||||
if (pick) _doorPickUses++;
|
||||
_doorUnlockTried = true;
|
||||
_doorStep = DoorStep.Unlocking;
|
||||
_doorSentMs = now; _doorAnsweredMs = 0;
|
||||
Host.Log($"[RynthNav] door: '{_doorName}' is locked: trying {u.Name}{(pick ? $" (pick {_doorPickUses} of {DoorPickTries})" : "")}");
|
||||
lock (_gate) _status = $"unlocking the {_doorName} with {u.Name}";
|
||||
return true;
|
||||
}
|
||||
why = $"none of your {_doorUnlockers.Count} key(s)/lockpick(s) opened it";
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool DoorAnswered(out uint err)
|
||||
{
|
||||
err = 0;
|
||||
if (!Host.HasUseDoneSeq) return NowMs - _doorSentMs > 2000;
|
||||
int seq = Host.GetUseDoneSeq();
|
||||
if (seq == _doorSeq) return false;
|
||||
if (Host.HasGetLastUseDone && Host.TryGetLastUseDone(out int ls, out uint le) && ls == _doorSeq + 1) err = le;
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool DoorOpen(uint id)
|
||||
{
|
||||
if (Host.HasGetObjectState && Host.TryGetObjectState(id, out uint st)) return (st & PhysicsEthereal) != 0;
|
||||
if (Host.HasGetObjectMotionOn && Host.TryGetObjectMotionOn(id, out bool on)) return on;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool LooksLikeDoorName(string n) =>
|
||||
n.Contains("door", StringComparison.OrdinalIgnoreCase) || n.Contains("gate", StringComparison.OrdinalIgnoreCase)
|
||||
|| n.Contains("hatch", StringComparison.OrdinalIgnoreCase) || n.Contains("portcullis", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The nearest closed door standing across the walk ahead (0: none), and how far along the walk it is.</summary>
|
||||
private uint ClosedDoorAhead(List<TownNetPoint> ahead, bool levels, long now, out double bestAlong, out string bestName)
|
||||
{
|
||||
bestAlong = double.MaxValue; bestName = "";
|
||||
uint best = 0;
|
||||
if (ahead.Count == 0) return 0;
|
||||
uint lb = CurrentLandblock;
|
||||
double x = LocalX, y = LocalY;
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (id >= 0x80000000u) continue; // doors are static objects
|
||||
if (_doorSkipUntil.TryGetValue(id, out long until) && now < until) continue;
|
||||
if (!Host.TryGetObjectPosition(id, out uint cell, out float dxf, out float dyf, out float dz)) continue;
|
||||
double dx = dxf, dy = dyf;
|
||||
if (!SameFrame(cell, lb, ref dx, ref dy)) continue;
|
||||
if (Math.Abs(dx - x) > WalkDoors.LookAheadUnits + 2 || Math.Abs(dy - y) > WalkDoors.LookAheadUnits + 2) continue;
|
||||
Host.TryGetObjectName(id, out string name);
|
||||
name ??= "";
|
||||
bool door = Host.HasGetObjectBitfield
|
||||
? Host.TryGetObjectBitfield(id, out uint bf) && (bf & BitfieldDoor) != 0
|
||||
: LooksLikeDoorName(name);
|
||||
if (!door || DoorOpen(id)) continue;
|
||||
double along = WalkDoors.AlongWalk(x, y, _wz, ahead, levels, dx, dy, dz);
|
||||
if (along < 0 || along >= bestAlong) continue;
|
||||
bestAlong = along; best = id; bestName = name.Length > 0 ? name : "door";
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A position in <paramref name="cell"/>'s landblock as coordinates local to landblock <paramref name="lb"/>:
|
||||
/// the same landblock as it is; on the map, a neighbouring landblock shifted by 192 a block (a door
|
||||
/// just over the line). False: a dungeon elsewhere, or too far.
|
||||
/// </summary>
|
||||
private bool SameFrame(uint cell, uint lb, ref double x, ref double y)
|
||||
{
|
||||
uint olb = (cell >> 16) & 0xFFFF;
|
||||
if (olb == lb) return true;
|
||||
if (!IsOnMap(_cellId)) return false; // a dungeon has no neighbours
|
||||
int ox = (int)(olb >> 8), oy = (int)(olb & 0xFF), cx = (int)(lb >> 8), cy = (int)(lb & 0xFF);
|
||||
if (Math.Abs(ox - cx) > 1 || Math.Abs(oy - cy) > 1) return false;
|
||||
x += (ox - cx) * 192.0;
|
||||
y += (oy - cy) * 192.0;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Doors on the goto's own walk (the navmesh path over land, through towns and buildings), each tick
|
||||
/// before it steers: the path's points still ahead, in this landblock's local coordinates.
|
||||
/// </summary>
|
||||
private DoorAct GotoDoor(long now, out string why)
|
||||
{
|
||||
why = "";
|
||||
if (!_doorsEnabled) return DoorAct.None;
|
||||
List<(double ew, double ns)>? path; int idx;
|
||||
lock (_gotoGate) { path = _gotoPath; idx = _gotoIdx; }
|
||||
if (path == null || idx >= path.Count) { if (_doorStep == DoorStep.None) return DoorAct.None; path ??= new(); }
|
||||
double ox = ((_cellId >> 24) & 0xFF) * 192.0, oy = ((_cellId >> 16) & 0xFF) * 192.0;
|
||||
var ahead = new List<TownNetPoint>(Math.Max(0, path.Count - idx));
|
||||
for (int i = idx; i < path.Count; i++)
|
||||
ahead.Add(new TownNetPoint { X = path[i].ew - ox, Y = path[i].ns - oy, Z = double.NaN });
|
||||
return WalkDoor(ahead, false, (n, held) => { _bestTick = _legTicks; _stuck.Reset(); }, now, out why);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Blocked with no door on the path ahead (the mesh may go round a door it was baked without): a closed
|
||||
/// door within reach in front of us, used before jumping or stepping round (2026-11-01).
|
||||
/// </summary>
|
||||
private bool OpenDoorInFront()
|
||||
{
|
||||
if (!_doorsEnabled || !Host.HasUseObject || !Host.HasGetLiveObjectIds) return false;
|
||||
if (!Host.HasGetObjectState && !Host.HasGetObjectMotionOn) return false;
|
||||
long now = NowMs;
|
||||
uint lb = CurrentLandblock;
|
||||
double x = LocalX, y = LocalY;
|
||||
double hx = Math.Sin(_lastDriveDeg * Math.PI / 180.0), hy = Math.Cos(_lastDriveDeg * Math.PI / 180.0);
|
||||
uint best = 0; double bestD = double.MaxValue; string bestName = "";
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (id >= 0x80000000u) continue;
|
||||
if (_doorSkipUntil.TryGetValue(id, out long until) && now < until) continue;
|
||||
if (!Host.TryGetObjectPosition(id, out uint cell, out float dxf, out float dyf, out float dz)) continue;
|
||||
double dx = dxf, dy = dyf;
|
||||
if (!SameFrame(cell, lb, ref dx, ref dy)) continue;
|
||||
if (!WalkDoors.InFront(x, y, _wz, hx, hy, dx, dy, dz, out double d) || d >= bestD) continue;
|
||||
Host.TryGetObjectName(id, out string name);
|
||||
name ??= "";
|
||||
bool door = Host.HasGetObjectBitfield
|
||||
? Host.TryGetObjectBitfield(id, out uint bf) && (bf & BitfieldDoor) != 0
|
||||
: LooksLikeDoorName(name);
|
||||
if (!door || DoorOpen(id)) continue;
|
||||
best = id; bestD = d; bestName = name.Length > 0 ? name : "door";
|
||||
}
|
||||
if (best == 0) return false;
|
||||
_doorId = best; _doorName = bestName;
|
||||
_doorUses = 0; _doorUnlockTried = false; _doorUnlockers = null; _doorUnlockIdx = 0; _doorPickUses = 0;
|
||||
Host.Log($"[RynthNav] door: blocked by '{bestName}' (0x{best:X8}) {bestD:F1} m in front: opening it");
|
||||
lock (_gate) _status = $"opening the {bestName}";
|
||||
if (!SendDoorUse(now)) { ResetDoor(); return false; }
|
||||
_doorLastTickMs = now;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The items in your pack (main pack and side packs), by id and name.</summary>
|
||||
private List<(uint Id, string Name)> PackItems()
|
||||
{
|
||||
var list = new List<(uint, string)>();
|
||||
uint me = Host.HasGetPlayerId ? Host.GetPlayerId() : 0;
|
||||
if (me == 0 || !Host.HasGetObjectOwnershipInfo) return list;
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!Host.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _) || wielder == me) continue;
|
||||
bool mine = container == me
|
||||
|| (container != 0 && Host.TryGetObjectOwnershipInfo(container, out uint outer, out _, out _) && outer == me);
|
||||
if (!mine) continue;
|
||||
Host.TryGetObjectName(id, out string name);
|
||||
if (!string.IsNullOrEmpty(name)) list.Add((id, name));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>A dungeon walk's jump (HubWalker.Act.Jump): on at the heading, and a jump.</summary>
|
||||
private void WalkJump(double heading, HubWalker w)
|
||||
{
|
||||
DriveTo(heading);
|
||||
bool ok = Host.HasTapJump && Host.TapJump();
|
||||
Host.Log($"[RynthNav] walk: no progress, jumping{(ok ? "" : " (this engine can't jump)")} (jump {w.JumpsTotal} on this walk)");
|
||||
}
|
||||
|
||||
/// <summary>/rnav doors [on|off | unlock on|off | drops <m>|off | forget].</summary>
|
||||
private void CmdDoors(string rest)
|
||||
{
|
||||
string[] a = rest.Trim().ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
string sub = a.Length > 0 ? a[0] : "";
|
||||
string arg = a.Length > 1 ? a[1] : "";
|
||||
switch (sub)
|
||||
{
|
||||
case "on":
|
||||
case "off":
|
||||
_doorsEnabled = sub == "on";
|
||||
NavDataConfig.WriteSwitch("doors", _doorsEnabled);
|
||||
Say($"doors on walks {(_doorsEnabled ? "ON: closed doors across the walk, or in the way, are opened" : "OFF")}");
|
||||
return;
|
||||
case "unlock":
|
||||
if (arg is not ("on" or "off")) { SayFail("doors unlock on|off — use keys and lockpicks from your pack on a locked door"); return; }
|
||||
_unlockEnabled = arg == "on";
|
||||
NavDataConfig.WriteSwitch("unlockDoors", _unlockEnabled);
|
||||
Say($"unlocking doors {(_unlockEnabled ? "ON: keys first, then lockpicks" : "OFF: a locked door is gone round, or the walk stops")}");
|
||||
return;
|
||||
case "drops":
|
||||
case "drop":
|
||||
if (arg == "off") _dropMeters = 0;
|
||||
else if (double.TryParse(arg, NumberStyles.Float, CultureInfo.InvariantCulture, out double m) && m >= 0 && m <= 40) _dropMeters = Math.Round(m, 1);
|
||||
else { SayFail($"doors drops <metres 0-40>|off — how far a dungeon walk may drop down a ledge (now {DropText()})"); return; }
|
||||
NavDataConfig.WriteNumber("dropMeters", _dropMeters);
|
||||
_dunPathCache.Clear();
|
||||
Say($"dungeon walks may drop {DropText()} (planned walks are worked out again)");
|
||||
return;
|
||||
case "forget":
|
||||
int n = _lockedDoors.Count;
|
||||
_lockedDoors.Clear(); _doorSkipUntil.Clear(); _lockedDoorVersion++;
|
||||
Say($"forgot {n} locked door(s): walks may try them again");
|
||||
return;
|
||||
case "":
|
||||
Say($"doors: {(_doorsEnabled ? "opened on walks (dungeons, towns, buildings)" : "OFF")}; unlock: {(_unlockEnabled ? "keys, then lockpicks" : "OFF")}; drops: {DropText()}; " +
|
||||
$"{_lockedDoors.Count} locked door(s) gone round this session; jumps: when a walk stops making progress");
|
||||
return;
|
||||
default:
|
||||
SayFail("doors [on|off] | unlock on|off | drops <m>|off | forget");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private string DropText() => _dropMeters > 0 ? $"down ledges up to {_dropMeters:0.#} m (never up)" : "OFF (no drops)";
|
||||
}
|
||||
116
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.DungeonPath.cs
Normal file
116
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.DungeonPath.cs
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Walking inside a dungeon RynthNav has never walked (2026-10-29): RynthAi's dungeon pathfinder (the
|
||||
// Dungeon Patrol's, from the client's cell dat; the "RynthAi.DungeonPath" interface) works out the
|
||||
// way from where you land to the portal a route needs. TownNet.Merge plans those walks for the
|
||||
// route hub, the hub walker falls back to it when you land away from every walk, and learning
|
||||
// portals uses it to reach a dungeon's portals. Walking one and taking the portal records it as a
|
||||
// learned walk (DungeonWalks), which is used from then on. Without RynthAi everything works as
|
||||
// before. Tick thread.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const int DunPathMaxPoints = 512;
|
||||
private const long DunPathRetryMs = 5000;
|
||||
|
||||
private readonly Dictionary<string, DungeonWay?> _dunPathCache = new(StringComparer.Ordinal);
|
||||
private bool _dunPathAvailable;
|
||||
private long _dunPathCheckMs;
|
||||
private string _dunPathWhy = "";
|
||||
private bool _dunPathNoData; // a lookup found the dats not ready (TownNet.Merge plans again later)
|
||||
|
||||
/// <summary>RynthAi's dungeon pathfinder is there (looked up again every few seconds while it isn't).</summary>
|
||||
private unsafe bool DungeonPathAvailable()
|
||||
{
|
||||
long now = NowMs;
|
||||
if (_dunPathAvailable || now < _dunPathCheckMs) return _dunPathAvailable;
|
||||
_dunPathCheckMs = now + DunPathRetryMs;
|
||||
_dunPathAvailable = DungeonPathTable() != null;
|
||||
if (_dunPathAvailable) Host.Log("[RynthNav] RynthAi's dungeon pathfinder is available: routes can walk dungeon portals nobody walked to yet");
|
||||
return _dunPathAvailable;
|
||||
}
|
||||
|
||||
private unsafe RynthAiDungeonPathApiV1* DungeonPathTable()
|
||||
{
|
||||
if (!Host.HasGetPluginInterface) { _dunPathWhy = "this RynthCore can't link plugins"; return null; }
|
||||
try
|
||||
{
|
||||
// Version 1 is enough to link: a RynthAi from before v3 still walks dungeons (the newer functions
|
||||
// are checked by Version and StructSize where they are used).
|
||||
var t = (RynthAiDungeonPathApiV1*)Host.GetPluginInterface(RynthAiDungeonPathApiV1.PluginName, RynthAiDungeonPathApiV1.InterfaceName, 1);
|
||||
if (t == null || t->Version < 1 || t->StructSize < 16 || t->FindPath == null)
|
||||
{ _dunPathWhy = "RynthAi isn't loaded (or is older than its dungeon path interface)"; return null; }
|
||||
return t;
|
||||
}
|
||||
catch { _dunPathWhy = "RynthAi's interface failed"; return null; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A walk inside dungeon <paramref name="lb"/> between two landblock-local points (x,y,z triples,
|
||||
/// local), or null. Remembered per pair (the dats don't change). With RynthAi's v2 interface
|
||||
/// (2026-10-30) the walk may drop down a ledge or shaft up to the drop setting, and keeps out of
|
||||
/// the doorways of the locked doors this session found (RynthNavPlugin.Doors.cs). Tick thread.
|
||||
/// </summary>
|
||||
private unsafe DungeonWay? DungeonPath(uint lb, double ax, double ay, double az, double bx, double by, double bz)
|
||||
{
|
||||
lb &= 0xFFFF;
|
||||
List<(double X, double Y, double Z)> avoid = LockedDoorSpots(lb);
|
||||
string key = string.Create(CultureInfo.InvariantCulture,
|
||||
$"{lb:X4}|{ax:0.#},{ay:0.#},{az:0}|{bx:0.#},{by:0.#},{bz:0}|d{_dropMeters:0.#}|a{avoid.Count}:{_lockedDoorVersion}");
|
||||
if (_dunPathCache.TryGetValue(key, out DungeonWay? cached)) return cached;
|
||||
RynthAiDungeonPathApiV1* t = DungeonPathTable();
|
||||
if (t == null) { _dunPathAvailable = false; return null; } // not cached: RynthAi may come back
|
||||
double ox = ((lb >> 8) & 0xFF) * 192.0, oy = (lb & 0xFF) * 192.0;
|
||||
var buf = new double[DunPathMaxPoints * 3];
|
||||
var kinds = new int[DunPathMaxPoints];
|
||||
int count = 0, r;
|
||||
bool v2 = t->Version >= 2 && t->StructSize >= 24 && t->FindPath2 != null;
|
||||
if (v2)
|
||||
{
|
||||
var av = new double[Math.Max(1, avoid.Count * 3)];
|
||||
for (int i = 0; i < avoid.Count; i++) { av[i * 3] = ox + avoid[i].X; av[i * 3 + 1] = oy + avoid[i].Y; av[i * 3 + 2] = avoid[i].Z; }
|
||||
fixed (double* p = buf) fixed (int* k = kinds) fixed (double* a = av)
|
||||
r = t->FindPath2(lb, ox + ax, oy + ay, az, ox + bx, oy + by, bz, _dropMeters, a, avoid.Count, p, k, DunPathMaxPoints, &count);
|
||||
}
|
||||
else
|
||||
{
|
||||
fixed (double* p = buf)
|
||||
r = t->FindPath(lb, ox + ax, oy + ay, az, ox + bx, oy + by, bz, p, DunPathMaxPoints, &count);
|
||||
}
|
||||
DungeonWay? result = null;
|
||||
if (r == RynthAiDungeonPathApiV1.ResultOk && count >= 2)
|
||||
{
|
||||
var pts = new double[count * 3];
|
||||
bool[]? drops = null;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
pts[i * 3] = buf[i * 3] - ox;
|
||||
pts[i * 3 + 1] = buf[i * 3 + 1] - oy;
|
||||
pts[i * 3 + 2] = buf[i * 3 + 2];
|
||||
if (v2 && kinds[i] == RynthAiDungeonPathApiV1.KindDrop) (drops ??= new bool[count])[i] = true;
|
||||
}
|
||||
result = new DungeonWay(pts, drops);
|
||||
}
|
||||
else if (r == RynthAiDungeonPathApiV1.ResultNoData) { _dunPathNoData = true; return null; } // the dats may not be loaded yet: ask again later
|
||||
if (_dunPathCache.Count > 4000) _dunPathCache.Clear();
|
||||
_dunPathCache[key] = result;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>The way from where you stand to (x, y, z) in this dungeon, as walker points, or null.</summary>
|
||||
private List<TownNetPoint>? DungeonWayHere(double x, double y, double z)
|
||||
{
|
||||
if (!DungeonPathAvailable()) return null;
|
||||
DungeonWay? dw = DungeonPath(CurrentLandblock, LocalX, LocalY, _wz, x, y, z);
|
||||
if (dw == null) return null;
|
||||
var way = new List<TownNetPoint>(dw.ToPoints(_cellId));
|
||||
if (way.Count > 0) way[0] = new TownNetPoint { Cell = _cellId, X = LocalX, Y = LocalY, Z = _wz, Drop = way[0].Drop };
|
||||
if (dw.HasDrop) Host.Log($"[RynthNav] dungeon walk drops down {dw.Drops!.Count(d => d)} ledge(s) on the way (drops up to {_dropMeters:0.#} m allowed: /rnav drops)");
|
||||
return way.Count >= 2 ? way : null;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Walks inside dungeons (2026-10-29): dungeons have no navmesh, so RynthNav keeps the way you walked
|
||||
// in one (DungeonTrail: from the landing, loops cut out). Taking a portal there keeps that walk with
|
||||
// the portal it reached (RynthNavPlugin.CustomPortals.cs), and TownNet.Merge turns this server's
|
||||
// walks into a hub the route planner and the walker use like the Town Network. Recorded whoever does
|
||||
// the walking: you, a goto, or learning portals. Not inside the Town Network (townnet.json has it).
|
||||
// Tick thread.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private readonly DungeonTrail _trail = new();
|
||||
|
||||
// The nearest live portal a moment ago (within UsedPortalUnits): when the client moves you before
|
||||
// portal space, the portal's object may be gone by the time the jump is seen.
|
||||
private int _nearPortalTick;
|
||||
private bool _nearPortalSeen;
|
||||
private long _nearPortalMs;
|
||||
private string _nearPortalName = "";
|
||||
private uint _nearPortalWcid, _nearPortalCell;
|
||||
private double _nearPortalWx, _nearPortalWy, _nearPortalWz;
|
||||
|
||||
private void TickNearPortal()
|
||||
{
|
||||
if (!_hasPose || !Host.HasGetLiveObjectIds || (++_nearPortalTick % 8) != 0) return;
|
||||
if (_trkPortaling || (Host.HasIsPortaling && Host.IsPortaling())) return;
|
||||
double best = UsedPortalUnits * UsedPortalUnits;
|
||||
bool found = false;
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!LivePortalAt(id, out uint pc, out double px, out double py, out double pz, out string name)) continue;
|
||||
double d2 = (px - _wx) * (px - _wx) + (py - _wy) * (py - _wy);
|
||||
if (d2 >= best || Math.Abs(pz - _wz) > 4.0) continue;
|
||||
best = d2; found = true;
|
||||
Host.TryGetObjectWcid(id, out uint wcid);
|
||||
_nearPortalName = name; _nearPortalWcid = wcid; _nearPortalCell = pc;
|
||||
_nearPortalWx = px; _nearPortalWy = py; _nearPortalWz = pz;
|
||||
}
|
||||
if (found) { _nearPortalSeen = true; _nearPortalMs = NowMs; }
|
||||
}
|
||||
|
||||
/// <summary>The portal seen beside (wx, wy) within the last moment, for NoteUsedPortal when the live one is gone.</summary>
|
||||
private bool RecentNearPortal(double wx, double wy, out uint cell, out double px, out double py, out double pz, out string name, out uint wcid)
|
||||
{
|
||||
cell = _nearPortalCell; px = _nearPortalWx; py = _nearPortalWy; pz = _nearPortalWz; name = _nearPortalName; wcid = _nearPortalWcid;
|
||||
return _nearPortalSeen && NowMs - _nearPortalMs < 2500
|
||||
&& (px - wx) * (px - wx) + (py - wy) * (py - wy) < UsedPortalUnits * UsedPortalUnits;
|
||||
}
|
||||
|
||||
/// <summary>One tick of the trail: started at each landing in a dungeon, extended as you move, dropped on the map.</summary>
|
||||
private void TickDungeonTrail(bool teleported)
|
||||
{
|
||||
if (!_hasPose || (_cellId >> 16) == 0) return;
|
||||
if (_trkPortaling || (Host.HasIsPortaling && Host.IsPortaling())) return; // NoteUsedPortal took what it needed
|
||||
uint lb = CurrentLandblock;
|
||||
bool dungeon = !IsOnMap(_cellId) && (_cellId & 0xFFFF) >= 0x100 && _baseTownNet?.Contains(lb) != true;
|
||||
if (!dungeon) { if (_trail.Count > 0) _trail.Clear(); return; }
|
||||
if (teleported || _trail.Count == 0 || _trail.Landblock != lb)
|
||||
{
|
||||
bool fromLanding = teleported || (LastTeleportMs > 0 && NowMs - LastTeleportMs < 15000);
|
||||
_trail.Start(_cellId, LocalX, LocalY, _wz, fromLanding);
|
||||
return;
|
||||
}
|
||||
_trail.Add(LocalX, LocalY, _wz);
|
||||
}
|
||||
}
|
||||
225
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Gems.cs
Normal file
225
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Gems.cs
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Portal gems in the pack as route steps (PackGems.cs, 2026-10-29). Every couple of seconds the pack
|
||||
// is looked through for teleport items (gems, recall stones, a custom server's town gems); the route
|
||||
// planner gets them as recalls ("/rnav gems on|off"), and a route's gem step uses one (UseObject)
|
||||
// and waits for the teleport like a recall. A gem used up just before a teleport (by you or by a
|
||||
// route) teaches where it lands, kept per server in NavData\gems.txt. Tick thread.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const string GemsFile = "gems.txt";
|
||||
private const uint StypeStackSize = 12, DidSpell = 28;
|
||||
private const long GemScanMs = 2000;
|
||||
private const long GemSpentWindowMs = 20000; // used up this long before a teleport: that gem took you
|
||||
private const long GemUseRetryMs = 15000;
|
||||
|
||||
private GemMemory _gemMemory = new();
|
||||
private volatile GemMemory? _loadedGems;
|
||||
private bool _gemsLoaded;
|
||||
private int _savedGemVersion;
|
||||
private volatile bool _gemsEnabled = true;
|
||||
private double _gemCostUnits = GemPlanner.GemCostUnitsDefault;
|
||||
|
||||
private volatile List<PackGem> _packGems = new();
|
||||
private Dictionary<uint, (string Name, int Count)> _packSnap = new(); // by weenie class: stacks merged or split aren't used up
|
||||
private long _nextGemScanMs;
|
||||
|
||||
// A gem just used up (seen gone from the pack), or used by a route's gem step.
|
||||
private uint _gemSpentWcid;
|
||||
private string _gemSpentName = "";
|
||||
private long _gemSpentMs;
|
||||
|
||||
// The route's gem step.
|
||||
private long _gemLastUseMs;
|
||||
|
||||
private void InitGems()
|
||||
{
|
||||
_gemsEnabled = NavDataConfig.ReadSwitch("gems", true);
|
||||
_gemCostUnits = Math.Clamp(NavDataConfig.ReadNumber("gemCostYards", GemPlanner.GemCostUnitsDefault), 0, 5000);
|
||||
string path = NavFile(GemsFile);
|
||||
Task.Run(() =>
|
||||
{
|
||||
GemMemory m = new();
|
||||
try { if (File.Exists(path)) m = GemMemory.Parse(File.ReadAllText(path)); }
|
||||
catch (Exception ex) { Host.Log($"[RynthNav] {GemsFile}: {ex.Message}"); }
|
||||
_loadedGems = m;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Takes the loaded gem landings, saves them when they change, and looks through the pack every couple of seconds.</summary>
|
||||
private void TickGems(long now, bool force = false)
|
||||
{
|
||||
if (!_gemsLoaded && _loadedGems is { } loaded) { _gemMemory = loaded; _gemsLoaded = true; _savedGemVersion = loaded.Version; }
|
||||
if (_gemsLoaded && (_gemMemory.Version != _savedGemVersion || force))
|
||||
{
|
||||
_savedGemVersion = _gemMemory.Version;
|
||||
WriteLater(GemsFile, _gemMemory.Serialize());
|
||||
}
|
||||
if (force || now < _nextGemScanMs || !_hasPose) return;
|
||||
_nextGemScanMs = now + GemScanMs;
|
||||
if (_trkPortaling || (Host.HasIsPortaling && Host.IsPortaling())) return; // the pack isn't changing hands mid-teleport
|
||||
ScanPackGems(now);
|
||||
}
|
||||
|
||||
/// <summary>The teleport items in your pack (main pack and side packs), and which went missing since the last look.</summary>
|
||||
private void ScanPackGems(long now)
|
||||
{
|
||||
if (!Host.HasGetLiveObjectIds || !Host.HasGetObjectOwnershipInfo) return;
|
||||
uint me = Host.HasGetPlayerId ? Host.GetPlayerId() : 0;
|
||||
if (me == 0) return;
|
||||
string server = CurrentServer();
|
||||
Atlas atlas = _atlas;
|
||||
var byWcid = new Dictionary<uint, PackGem>();
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!Host.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _) || wielder == me) continue;
|
||||
bool mine = container == me
|
||||
|| (container != 0 && Host.TryGetObjectOwnershipInfo(container, out uint outer, out _, out _) && outer == me);
|
||||
if (!mine) continue;
|
||||
int spell = Host.HasGetObjectDataIdProperty && Host.TryGetObjectDataIdProperty(id, DidSpell, out uint sp) && sp < 0x10000 ? (int)sp : 0;
|
||||
Host.TryGetObjectWcid(id, out uint wcid);
|
||||
if (spell == 0 && _gemMemory.Get(server, wcid) == null) continue;
|
||||
Host.TryGetItemType(id, out uint type);
|
||||
Host.TryGetObjectName(id, out string name);
|
||||
name ??= "";
|
||||
if (!GemPlanner.LooksLikeTeleportItem(type, spell, name, atlas, _gemMemory, server, wcid)) continue;
|
||||
int count = Host.HasGetObjectIntProperty && Host.TryGetObjectIntProperty(id, StypeStackSize, out int st) && st > 0 ? st : 1;
|
||||
if (byWcid.TryGetValue(wcid, out PackGem? g)) g.Count += count;
|
||||
else byWcid[wcid] = new PackGem { Id = id, Wcid = wcid, Name = name, SpellId = spell, Count = count };
|
||||
}
|
||||
// One gone, or a stack down: used up (or sold, dropped, given: only a teleport soon after counts).
|
||||
var snap = new Dictionary<uint, (string Name, int Count)>();
|
||||
foreach (var (w, g) in byWcid) snap[w] = (g.Name, g.Count);
|
||||
foreach (var (w, was) in _packSnap)
|
||||
{
|
||||
int left = snap.TryGetValue(w, out var cur) ? cur.Count : 0;
|
||||
if (left >= was.Count) continue;
|
||||
_gemSpentWcid = w; _gemSpentName = was.Name; _gemSpentMs = now;
|
||||
Host.Log($"[RynthNav] gem: a {was.Name} left the pack ({left} left)");
|
||||
}
|
||||
_packSnap = snap;
|
||||
_packGems = new List<PackGem>(byWcid.Values);
|
||||
}
|
||||
|
||||
/// <summary>The recalls the planner may use: spells and commands (RecallPlanner), plus the pack's gems.</summary>
|
||||
private List<RecallOption> AllRecalls(Atlas atlas, List<string>? notes)
|
||||
{
|
||||
List<RecallOption> list = RecallPlanner.Build(atlas, _known, _memory, _charKey, notes, ArrivalFor);
|
||||
if (!_gemsEnabled) { if (_packGems.Count > 0) notes?.Add("Portal gems are off (/rnav gems on)."); return list; }
|
||||
list.AddRange(GemPlanner.Build(_packGems, atlas, _memory, _charKey, _gemMemory, CurrentServer(), _gemCostUnits, notes, ArrivalFor));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A landing in a dungeon RynthNav learned walks in: that arrival of the route hub (_townNet), so a
|
||||
/// recall or gem into it goes on by the dungeon's portals. By position when known (within 3 m),
|
||||
/// else by the exact cell. -1: not a learned arrival.
|
||||
/// </summary>
|
||||
private int ArrivalFor(uint cell, bool hasPos, double x, double y, double z)
|
||||
{
|
||||
TownNet? t = _townNet;
|
||||
if (t == null || cell == 0) return -1;
|
||||
int first = _baseTownNet?.Arrivals.Count ?? 0;
|
||||
if (hasPos)
|
||||
{
|
||||
int a = t.LearnedArrival(first, cell >> 16, x, y, z);
|
||||
if (a >= 0) return a;
|
||||
}
|
||||
return t.LearnedArrivalByCell(first, cell);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A teleport right after a gem was used up (or a route's gem step used one): that gem lands
|
||||
/// here. True when it was a gem's teleport (it is then nothing else: not a portal, not a recall).
|
||||
/// </summary>
|
||||
private bool TryLearnGem(RecallSpot landing, long now)
|
||||
{
|
||||
if (_gemSpentWcid == 0 || now - _gemSpentMs > GemSpentWindowMs) return false;
|
||||
// A recall RynthNav cast, or one announced: that's what this teleport was.
|
||||
if ((_castRecallSpell != 0 && now - _castRecallMs < RecallCastWindowMs) || _pendingRecallSlot != null) return false;
|
||||
uint wcid = _gemSpentWcid;
|
||||
string name = _gemSpentName;
|
||||
_gemSpentWcid = 0;
|
||||
string server = CurrentServer();
|
||||
if (server.Length == 0 || !_gemsLoaded) return true;
|
||||
RecallSpot? was = _gemMemory.Get(server, wcid);
|
||||
_gemMemory.Set(server, wcid, name, landing);
|
||||
string where = landing.OnMap ? $"{NavCoords.Fmt(landing.Ns, landing.Ew)} ({landing.Label})" : landing.Label;
|
||||
Host.Log($"[RynthNav] gem {name} (wcid {wcid}) lands at {where}{(was == null ? " (new)" : "")}");
|
||||
if (was == null || was.OnMap != landing.OnMap || NavCoords.Distance(was.Ns, was.Ew, landing.Ns, landing.Ew) > RecallNearUnits)
|
||||
Say($"learned: {name} takes you to {where}" + (landing.OnMap ? (_gemsEnabled ? " — routes can use it now" : " (gems are off in routes: /rnav gems on)") : " (a dungeon: not used for routes)"));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One tick of a route's gem step (from StepRecall): uses one of that gem from the pack, again
|
||||
/// after a while if nothing happened. False when there's none left (the goto stops).
|
||||
/// </summary>
|
||||
private bool UseRouteGem(RecallOption o, long now)
|
||||
{
|
||||
if (_gemLastUseMs != 0 && now - _gemLastUseMs < GemUseRetryMs) return true;
|
||||
PackGem? g = null;
|
||||
foreach (PackGem p in _packGems) if (p.Wcid == o.ItemWcid && p.Count > 0) { g = p; break; }
|
||||
if (g == null || !Host.HasUseObject) return false;
|
||||
Host.UseObject(g.Id);
|
||||
_gemLastUseMs = now;
|
||||
_gemSpentWcid = g.Wcid; _gemSpentName = g.Name; _gemSpentMs = now; // the teleport that follows is this gem's
|
||||
Host.Log($"[RynthNav] used {g.Name} (0x{g.Id:X8}, {g.Count} in the pack)");
|
||||
lock (_gate) _status = $"using {g.Name}";
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>/rnav gems [on|off|list|cost <yd>|forget <name>].</summary>
|
||||
private void CmdGems(string rest)
|
||||
{
|
||||
string arg = rest.Trim();
|
||||
int sp = arg.IndexOf(' ');
|
||||
string sub = (sp < 0 ? arg : arg.Substring(0, sp)).ToLowerInvariant();
|
||||
string tail = sp < 0 ? "" : arg.Substring(sp + 1).Trim();
|
||||
string server = CurrentServer();
|
||||
switch (sub)
|
||||
{
|
||||
case "on":
|
||||
case "off":
|
||||
_gemsEnabled = sub == "on";
|
||||
NavDataConfig.WriteSwitch("gems", _gemsEnabled);
|
||||
Say($"portal gems in routes {(_gemsEnabled ? "ON" : "OFF")}");
|
||||
return;
|
||||
case "cost":
|
||||
if (!double.TryParse(tail, NumberStyles.Float, CultureInfo.InvariantCulture, out double yd) || yd < 0 || yd > 5000)
|
||||
{ Say($"gems cost <yards 0-5000> — what spending a gem counts as on top of using it (now {_gemCostUnits:0} yd)"); return; }
|
||||
_gemCostUnits = Math.Round(yd);
|
||||
NavDataConfig.WriteNumber("gemCostYards", _gemCostUnits);
|
||||
Say($"a gem now counts as {_gemCostUnits:0} yd of walking on top of using it (lower: routes spend gems more readily)");
|
||||
return;
|
||||
case "forget":
|
||||
{
|
||||
int n = 0;
|
||||
foreach (var (w, name, _) in new List<(uint, string, RecallSpot)>(_gemMemory.For(server)))
|
||||
if (tail.Length > 0 && name.IndexOf(tail, StringComparison.OrdinalIgnoreCase) >= 0 && _gemMemory.Forget(server, w)) n++;
|
||||
Say($"forgot where {n} gem kind(s) named like '{tail}' land on {server}");
|
||||
return;
|
||||
}
|
||||
case "":
|
||||
case "list":
|
||||
{
|
||||
ScanPackGems(NowMs);
|
||||
var notes = new List<string>();
|
||||
List<RecallOption> usable = GemPlanner.Build(_packGems, _atlas, _memory, _charKey, _gemMemory, server, _gemCostUnits, notes, ArrivalFor);
|
||||
Say($"portal gems in routes: {(_gemsEnabled ? "ON" : "OFF")} (cost {_gemCostUnits:0} yd each); {_packGems.Count} kind(s) in your pack, {usable.Count} with a known landing:");
|
||||
foreach (RecallOption o in usable) Say($" {o.ItemName} x{o.ItemCount} → {o.Where}{(o.ToArrival >= 0 ? ", then out through its learned portals" : "")} ({o.Via})");
|
||||
foreach (string n in notes) Say(" " + n);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
Say("gems [list] | on | off | cost <yd> | forget <name> — teleport gems in your pack as route steps");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -108,6 +108,7 @@ public sealed partial class RynthNavPlugin
|
|||
private void ResetCoarse()
|
||||
{
|
||||
_coarse = null; _coarseRetry = 0; _coarseOff = 0; _coarseAnnounced = false; _coarseNoRouteSaid = false; _coarseGoalMovedSaid = false;
|
||||
_jump.Hard = false;
|
||||
_coarseTask = null; _coarseVersion++;
|
||||
}
|
||||
|
||||
|
|
@ -221,12 +222,25 @@ public sealed partial class RynthNavPlugin
|
|||
}
|
||||
// On open ground (the start links to its neighbours, on a real landmass) and still no
|
||||
// route though the goal end was already moved to ground a walk can end on: the graph
|
||||
// knows of no way there. Heading straight for it then only runs into what's between
|
||||
// (11-01: a bridge, then round in circles for minutes). Stop and say so. Standing in a
|
||||
// pocket yourself (indoors, a roof), the way out may be narrower than the mesh shows:
|
||||
// head for it as before.
|
||||
// knows of no way there. Until 2026-11-07 that stopped the goto ("pick a spot nearby";
|
||||
// 11-01: heading straight had run into a bridge, then round in circles). But on the same
|
||||
// land what is between is often a wall, a fence or a ledge the navmesh's 2 m agent doesn't
|
||||
// cross and a jump does (Silentkelpie: "it should use more power to jump if needed").
|
||||
// Now it heads for the spot along the trip's straight line jumping hard: three full jumps
|
||||
// at each place it is stuck before stepping round, and the stuck tries and the 30 s
|
||||
// progress watchdog still stop it where nothing gets it over.
|
||||
if (g != null && g.RegionPortals(here).Length > 0 && g.ComponentSize(g.Component(here)) >= 8)
|
||||
{
|
||||
if (land == true)
|
||||
{
|
||||
if (!_jump.Hard)
|
||||
{
|
||||
_jump.Hard = true;
|
||||
Host.Log("[RynthNav] route: no walking way in the route graph, but the same land: heading straight for it, jumping hard where it is blocked");
|
||||
Say("goto: no walking way there on the map (a wall or a ledge between?); heading straight for it and jumping hard where it's blocked");
|
||||
}
|
||||
return;
|
||||
}
|
||||
FinishGoto("stopped: the route graph has no walking way to that spot (nothing walkable within 96 yd of it links to where you are); pick a spot nearby");
|
||||
return;
|
||||
}
|
||||
|
|
@ -239,6 +253,7 @@ public sealed partial class RynthNavPlugin
|
|||
}
|
||||
_coarse = c;
|
||||
_coarseOff = 0;
|
||||
_jump.Hard = false; // a walking way after all
|
||||
// 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)");
|
||||
|
|
|
|||
211
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Inside.cs
Normal file
211
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Inside.cs
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Going to someone (or something) INSIDE a dungeon (2026-11-11, Silentkelpie: "some npc can be inside dungeons
|
||||
// or bur and should route to them correctly"). The Atlas has 2,963 NPCs and 172 vendors in dungeon cells, with no
|
||||
// map position: a goto by their name used to say "no place called ... on the map". Now the way in is found:
|
||||
// 1. already in that dungeon: arrived (the quest run walks the rest with RynthAi's dungeon map);
|
||||
// 2. a portal on the map that leads into that dungeon's landblock: walked to and into (the nearest, one that
|
||||
// needs no quest first when there is a choice);
|
||||
// 3. a recall this character knows that lands in it (Bur Recall into the Bur, a learned Lifestone or Portal
|
||||
// Recall): cast.
|
||||
// The arrival line ends with "(<name> is in cell XXXXXXXX)", which RynthOracle's quest run reads to walk the
|
||||
// dungeon to that cell. Tick thread.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
/// <summary>What the goto into a dungeon is after: the person's name and cell (0 = none). Added to the arrival line.</summary>
|
||||
private string _insideName = "";
|
||||
private uint _insideCell;
|
||||
|
||||
/// <summary>"... (Drogur is in cell 009C0270)": the end of an arrival line for a target inside a dungeon.</summary>
|
||||
internal static string InsideTail(string name, uint cell) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $" ({name} is in cell {cell:X8})");
|
||||
|
||||
/// <summary>
|
||||
/// "a || b || c" for go: the candidates in the order given; the first that is coordinates or a place on the
|
||||
/// map is left to the usual go, unless the same name is someone inside a dungeon by its exact name and the
|
||||
/// map's place only half matches. False when the usual go should take it.
|
||||
/// </summary>
|
||||
private bool TryGoInsideAlternative(string text)
|
||||
{
|
||||
foreach (string raw in text.Split("||", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
if (NavCoords.TrySplitCoordsAndName(raw, out _, out _, out _)) return false;
|
||||
AtlasLocation? inside = PreferInside(raw, out bool onMap);
|
||||
if (inside != null) return GoInside(inside);
|
||||
if (onMap) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>A go to one name: someone inside a dungeon when the map has nothing better for it.</summary>
|
||||
private bool TryGoInside(string text)
|
||||
{
|
||||
AtlasLocation? inside = PreferInside(text, out _);
|
||||
return inside != null && GoInside(inside);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The place inside a dungeon a name means, or null when the map answers it as well or better (a place on the
|
||||
/// map with the exact name, or any whole-word match when nothing inside has the exact name).
|
||||
/// </summary>
|
||||
private AtlasLocation? PreferInside(string name, out bool onMap)
|
||||
{
|
||||
bool hasPos = PlayerMapPos(out double pns, out double pew);
|
||||
AtlasLocation? map = _atlas.FindBest(name, hasPos, pns, pew);
|
||||
int mapScore = map == null ? 0 : Atlas.MatchScore(map.Name, name);
|
||||
onMap = mapScore >= 60;
|
||||
AtlasLocation? inside = _atlas.FindInside(name, CurrentLandblock);
|
||||
if (inside == null) return null;
|
||||
if (mapScore >= 100) return null;
|
||||
bool exact = inside.Name.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase);
|
||||
if (onMap && !exact) return null;
|
||||
return inside;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "/rnav inside a || b": which of these people is in THIS dungeon, and in which cell (RynthOracle's quest run,
|
||||
/// already inside, before it walks the dungeon). The answer is the arrival line, or "inside: ..." saying why not.
|
||||
/// It never travels.
|
||||
/// </summary>
|
||||
private void CmdInside(string text)
|
||||
{
|
||||
uint here = CurrentLandblock;
|
||||
bool inDungeon = (_cellId & 0xFFFF) >= 0x100;
|
||||
string elsewhere = "";
|
||||
foreach (string raw in text.Split("||", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
AtlasLocation? l = _atlas.FindInside(raw, here);
|
||||
if (l == null || !Atlas.TryCell(l.Cell, out uint cell)) continue;
|
||||
if (inDungeon && cell >> 16 == here)
|
||||
{
|
||||
_gotoName = l.Name;
|
||||
Say($"goto: arrived in {InsideDungeonName(here)}: {l.Name} is inside{InsideTail(l.Name, cell)}");
|
||||
return;
|
||||
}
|
||||
if (elsewhere.Length == 0) elsewhere = $"{l.Name} is in {InsideDungeonName(cell >> 16)}, not here";
|
||||
}
|
||||
Say("inside: " + (elsewhere.Length > 0 ? elsewhere : "none of these is someone inside a dungeon: " + text.Replace("||", ",")));
|
||||
}
|
||||
|
||||
/// <summary>The way into <paramref name="place"/>'s dungeon, started. True when it was handled (gone, or why not said).</summary>
|
||||
private bool GoInside(AtlasLocation place)
|
||||
{
|
||||
if (!Atlas.TryCell(place.Cell, out uint cell)) return false;
|
||||
uint lb = cell >> 16;
|
||||
string dungeon = InsideDungeonName(lb);
|
||||
if (!_hasPose) { Note("goto: no player position yet"); return true; }
|
||||
|
||||
// 1. Already there.
|
||||
if (CurrentLandblock == lb && (_cellId & 0xFFFF) >= 0x100)
|
||||
{
|
||||
_gotoName = place.Name;
|
||||
Host.Log($"[RynthNav] goto {place.Name}: already in {dungeon} (cell {cell:X8})");
|
||||
Say($"goto: arrived in {dungeon}: {place.Name} is inside{InsideTail(place.Name, cell)}");
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. A portal on the map into it.
|
||||
bool hasPos = PlayerMapPos(out double pns, out double pew);
|
||||
AtlasLocation? portal = Entrance.PortalInto(_atlas, lb, hasPos, pns, pew);
|
||||
bool inDungeonNow = InDungeon(_cellId) || ((_cellId & 0xFFFF) >= 0x100 && !hasPos);
|
||||
if (portal != null && !inDungeonNow)
|
||||
{
|
||||
_insideName = place.Name; _insideCell = cell;
|
||||
_nextEnterPortal = portal.Name;
|
||||
Say($"goto: {place.Name} is inside {dungeon}: going in by {portal.Name} at {NavCoords.Fmt(portal.Ns, portal.Ew)}");
|
||||
StartGoto(place.Name, place.Type, portal.Ns, portal.Ew, dungeon, "Dungeon");
|
||||
return true;
|
||||
}
|
||||
|
||||
// 3. A recall that lands in it.
|
||||
RecallOption? recall = RecallInto(lb);
|
||||
if (recall != null)
|
||||
{
|
||||
StartRecallInto(place, cell, dungeon, recall);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (portal != null)
|
||||
Note($"goto: {place.Name} is inside {dungeon}; its portal is at {NavCoords.Fmt(portal.Ns, portal.Ew)}, but there's no navmesh where you are: walk out of this dungeon first");
|
||||
else
|
||||
Note($"goto: {place.Name} is inside {dungeon}, and no portal on the map or recall you know leads in there");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The dungeon's name: the route hub's or the Atlas's dungeon (DungeonName), else where its portals or recalls lead.</summary>
|
||||
private string InsideDungeonName(uint lb)
|
||||
{
|
||||
string n = DungeonName(lb);
|
||||
if (!n.StartsWith("dungeon ", StringComparison.Ordinal)) return n;
|
||||
foreach (AtlasLocation l in _atlas.Locations)
|
||||
if (l.HasDest && l.DestName.Length > 0 && Atlas.TryCell(l.DestCell, out uint dc) && dc >> 16 == lb) return l.DestName;
|
||||
foreach (AtlasRecall r in _atlas.Recalls)
|
||||
if (!r.OnMap && r.Cell >> 16 == lb && r.In.Length > 0) return r.In;
|
||||
return lb == 0x009C ? "the Bur" : n;
|
||||
}
|
||||
|
||||
/// <summary>A recall in this character's spellbook (or a learned personal one) that lands in landblock <paramref name="lb"/>.</summary>
|
||||
private RecallOption? RecallInto(uint lb)
|
||||
{
|
||||
if (!RecallsRouting || _known == null) return null;
|
||||
foreach (AtlasRecall r in _atlas.Recalls)
|
||||
if (!r.OnMap && r.Cell != 0 && r.Cell >> 16 == lb && _known.Contains(r.SpellId))
|
||||
return new RecallOption { Name = r.Name, SpellId = r.SpellId, CastSeconds = RecallPlanner.SpellCastSeconds, Into = r.In };
|
||||
(int Spell, string Name, RecallSlot Slot)[] personal =
|
||||
{
|
||||
(RecallPlanner.LifestoneRecall, "Lifestone Recall", RecallSlot.Lifestone),
|
||||
(RecallPlanner.PortalRecall, "Portal Recall", RecallSlot.LastPortal),
|
||||
(RecallPlanner.PrimaryPortalTieRecall, "Primary Portal Tie Recall", RecallSlot.Tie1),
|
||||
(RecallPlanner.SecondaryPortalTieRecall, "Secondary Portal Tie Recall", RecallSlot.Tie2),
|
||||
};
|
||||
foreach (var (spell, name, slot) in personal)
|
||||
{
|
||||
if (!_known.Contains(spell)) continue;
|
||||
RecallSpot? spot = _memory.Get(_charKey, slot);
|
||||
if (spot != null && !spot.OnMap && spot.Cell != 0 && spot.Cell >> 16 == lb)
|
||||
return new RecallOption { Name = name, SpellId = spell, CastSeconds = RecallPlanner.SpellCastSeconds, Learned = true, Into = spot.Label };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A goto of one recall step: cast it, wait for the teleport, arrive (the usual recall step and settle).</summary>
|
||||
private void StartRecallInto(AtlasLocation place, uint cell, string dungeon, RecallOption recall)
|
||||
{
|
||||
if (_gotoActive) { _gotoActive = false; _route = null; _portalWait = false; ResetHub(); AutoRun.Stop(); HideMarkers("a new goto"); }
|
||||
if (_recallWait) EndRecall();
|
||||
_goJobId = 0;
|
||||
_landReplanned = false; _enterPortal = ""; _nextEnterPortal = "";
|
||||
_portalWait = false; _portalWaitTicks = 0; _wasPortaling = false; _settling = false;
|
||||
_enterName = ""; _enterType = "";
|
||||
_finalTew = _wx; _finalTns = _wy;
|
||||
ResetHub();
|
||||
_routeRecalls = new List<RecallOption> { recall };
|
||||
bool hasPos = PlayerMapPos(out double pns, out double pew);
|
||||
_route = new List<RouteStep> { new(hasPos ? pns : 0, hasPos ? pew : 0, usePortal: false, useRecall: true, recall.Name, 0, double.NaN, double.NaN) };
|
||||
_routeIdx = 0;
|
||||
_insideName = place.Name; _insideCell = cell;
|
||||
_gotoActive = true;
|
||||
_gotoName = place.Name; _gotoType = place.Type;
|
||||
_walkHaveLast = false;
|
||||
AutoRun.Forget();
|
||||
Host.Log($"[RynthNav] goto {place.Name} (inside {dungeon}, cell {cell:X8}) by {recall.Name}");
|
||||
Say($"goto: {place.Name} is inside {dungeon}: casting {recall.Name} — /rnav stop to cancel");
|
||||
BeginRecallStep();
|
||||
}
|
||||
|
||||
/// <summary>FinishGoto: the arrival line's tail for a target inside a dungeon (and the target forgotten).</summary>
|
||||
private string TakeInsideTail(string status)
|
||||
{
|
||||
string name = _insideName;
|
||||
uint cell = _insideCell;
|
||||
_insideName = ""; _insideCell = 0;
|
||||
if (cell == 0 || !status.StartsWith("arrived", StringComparison.Ordinal)) return "";
|
||||
if (CurrentLandblock != cell >> 16) return "";
|
||||
return InsideTail(name, cell);
|
||||
}
|
||||
}
|
||||
119
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Jump.cs
Normal file
119
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Jump.cs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Jumps that know the character and the obstacle (2026-11-07, Silentkelpie: "the jump on routes should take
|
||||
// your buffed jump into account as well as your burden to plan a route and a jump to get over things to by
|
||||
// pass doors and other obstacles"). When the walk is stuck, or a door on the way is locked:
|
||||
// - how high this character jumps now (JumpModel: the buffed Jump skill, the burden),
|
||||
// - how high the thing in front is (RynthAi's ObstacleAhead: rays through the dats' static geometry),
|
||||
// then the jump that just clears it (and a full one), or none when it can't (step round at once, or
|
||||
// plan round the locked door). Tick thread.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
/// <summary>How far ahead the stuck walk looks for what stopped it (world units).</summary>
|
||||
private const double ObstacleLookAhead = 3.0;
|
||||
/// <summary>The highest obstacle measured (higher is "too high").</summary>
|
||||
private const double ObstacleMaxMeasure = 8.0;
|
||||
/// <summary>A locked door: the fence beside it is measured this far to either side.</summary>
|
||||
private const double DoorSideOffset = 1.6;
|
||||
private const uint StrengthAttr = 1, BurdenProp = 5, CarryAugsProp = 230;
|
||||
|
||||
private string _jumpModelSaid = "";
|
||||
|
||||
/// <summary>The character's jump now: the buffed Jump skill and the burden (NaN when not readable).</summary>
|
||||
private JumpModel ReadJumpModel()
|
||||
{
|
||||
uint pid = Host.HasGetPlayerId ? Host.GetPlayerId() : 0;
|
||||
if (pid == 0) return new JumpModel(0, double.NaN);
|
||||
int skill = 0;
|
||||
if (Host.HasGetObjectSkillBuffed && Host.TryGetObjectSkillLevel(pid, JumpModel.JumpSkillId, 0, out int lvl)) skill = lvl;
|
||||
else if (Host.HasGetObjectSkill && Host.TryGetObjectSkill(pid, JumpModel.JumpSkillId, out int buffed, out _)) skill = buffed;
|
||||
double burden = double.NaN;
|
||||
if (Host.HasGetObjectIntProperty && Host.HasGetObjectAttribute
|
||||
&& Host.TryGetObjectIntProperty(pid, BurdenProp, out int carried)
|
||||
&& Host.TryGetObjectAttribute(pid, StrengthAttr, 0, out uint str) && str > 0)
|
||||
{
|
||||
int augs = Host.TryGetObjectIntProperty(pid, CarryAugsProp, out int a) ? Math.Clamp(a, 0, 5) : 0;
|
||||
burden = carried / (150.0 * str + augs * 30.0 * str);
|
||||
}
|
||||
var m = new JumpModel(skill, burden);
|
||||
string said = m.Known ? $"Jump {m.Skill}, burden {(m.BurdenKnown ? (m.Burden * 100).ToString("F0") + "%" : "?")}: a full jump clears about {m.FullHeight - JumpModel.Clearance:F1} m" : "";
|
||||
if (said.Length > 0 && said != _jumpModelSaid) { _jumpModelSaid = said; Host.Log("[RynthNav] jump: " + said); }
|
||||
return m;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How high the static thing in front of (x, y) heading <paramref name="headingDeg"/> is (m above the feet):
|
||||
/// true with it; false when nothing static is there or RynthAi can't tell (no dats, older RynthAi).
|
||||
/// </summary>
|
||||
private unsafe bool ObstacleTop(double x, double y, double headingDeg, double ahead, out double top)
|
||||
{
|
||||
top = double.NaN;
|
||||
RynthAiDungeonPathApiV1* t = DungeonPathTable();
|
||||
if (t == null || t->Version < 3 || t->StructSize < 32 || t->ObstacleAhead == null) return false;
|
||||
double v;
|
||||
int r = t->ObstacleAhead(_cellId, x, y, _wz, headingDeg, ahead, ObstacleMaxMeasure, &v);
|
||||
if (r != RynthAiDungeonPathApiV1.ResultOk) return false;
|
||||
top = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The jumps for the spot the walk is stuck at: measured when it can be.</summary>
|
||||
private void PlanJumpHere(string at)
|
||||
{
|
||||
JumpModel m = ReadJumpModel();
|
||||
if (!m.Known) return; // no skill to go on: the default plan
|
||||
double top = ObstacleTop(_wx, _wy, _lastDriveDeg, ObstacleLookAhead, out double t) ? t : double.NaN;
|
||||
int[] plan = m.PlanFor(top, _jump.Hard, out string why);
|
||||
_jump.SetSpot(plan);
|
||||
Host.Log($"[RynthNav] walk: stuck at {at}: {why}{(plan.Length == 0 ? ": stepping round it" : "")}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A locked door on the way: the fence or wall it sits in, measured to either side of it. Low enough for
|
||||
/// this character's jump: jump it (true; StepBlocked flies the jump). Else false: plan round the door.
|
||||
/// </summary>
|
||||
private bool TryJumpLockedDoor()
|
||||
{
|
||||
if (!_lockedDoorHere || !(Host.HasCommenceJump || Host.HasTapJump)) return false;
|
||||
_lockedDoorHere = false;
|
||||
double dx = _lockedDoorX - _wx, dy = _lockedDoorY - _wy, d = Math.Sqrt(dx * dx + dy * dy);
|
||||
if (d > 12) return false;
|
||||
double heading = Math.Atan2(dx, dy) * 180.0 / Math.PI;
|
||||
if (heading < 0) heading += 360;
|
||||
JumpModel m = ReadJumpModel();
|
||||
if (!m.Known) return false;
|
||||
// The fence beside the door: from points beside us, square to the door.
|
||||
double px = Math.Cos(heading * Math.PI / 180.0), py = -Math.Sin(heading * Math.PI / 180.0);
|
||||
double top = double.NaN;
|
||||
foreach (int side in new[] { -1, 1 })
|
||||
{
|
||||
if (!ObstacleTop(_wx + px * DoorSideOffset * side, _wy + py * DoorSideOffset * side, heading, d + 2.0, out double t)) continue;
|
||||
top = double.IsNaN(top) ? t : Math.Max(top, t);
|
||||
}
|
||||
string at = NavCoords.Fmt(NavCoords.NsFromWorld(_wy), NavCoords.EwFromWorld(_wx));
|
||||
if (double.IsNaN(top)) { Host.Log($"[RynthNav] door: locked; the wall beside it can't be measured: planning round it"); return false; }
|
||||
int c = m.ChargeFor(top);
|
||||
if (c == 0)
|
||||
{
|
||||
Host.Log($"[RynthNav] door: locked; the wall beside it is {top:F1} m, your jump clears about {m.FullHeight - JumpModel.Clearance:F1} m: planning round it");
|
||||
return false;
|
||||
}
|
||||
_jumpDeg = heading;
|
||||
_jump.Reset();
|
||||
_jump.SetSpot(c >= 1000 ? new[] { 1000, 1000 } : new[] { c, 1000 });
|
||||
DriveTo(_jumpDeg);
|
||||
if (Host.HasCommenceJump && Host.CommenceJump()) _jump.StartCharged(NowMs);
|
||||
else { Host.TapJump(); _jump.StartTap(NowMs); }
|
||||
Host.Log($"[RynthNav] door: locked at {at}; the wall beside it is {top:F1} m: jumping it ({c} ms; Jump {m.Skill})");
|
||||
Say($"goto: the door is locked; jumping the {top:F1} m wall beside it");
|
||||
lock (_gate) _status = "jumping a locked door's wall";
|
||||
return true;
|
||||
}
|
||||
|
||||
// The locked door the door walk just gave up on (world units), for TryJumpLockedDoor.
|
||||
private bool _lockedDoorHere;
|
||||
private double _lockedDoorX, _lockedDoorY;
|
||||
}
|
||||
491
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.LearnPortals.cs
Normal file
491
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.LearnPortals.cs
Normal file
|
|
@ -0,0 +1,491 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Learn portals (2026-10-29): RynthNav maps a server's portals by itself. From where you start it
|
||||
// (the home spot), it scans the portals within the learn range, walks into the nearest one it hasn't
|
||||
// tried, lets the teleport teach where that portal lands (CustomPortals.cs), comes back to the home
|
||||
// spot by a route (portals and recalls, whatever the switches say), and goes on with the next one,
|
||||
// until every portal in range has been tried or you stop it (Stop, any movement key, or
|
||||
// "/rnav portals learn stop"). The range is editable: "/rnav portals learn range <yd>" and the
|
||||
// panel's - / + (rynthnav.json "learnRange").
|
||||
//
|
||||
// States (tick thread):
|
||||
// Pick at home: scan, choose the nearest untried portal in range (live ones and saved ones
|
||||
// without a landing), or finish;
|
||||
// Going walking into it; a teleport means it was taken, the goto ending without one means
|
||||
// it wouldn't take you (tried, failed);
|
||||
// Landed a short settle after the teleport (the landing is learned in OnTeleported);
|
||||
// Return the route back to the home spot; arriving there goes back to Pick. Two failed returns
|
||||
// stop learning (no route back from where the portal went: a recall it doesn't have).
|
||||
//
|
||||
// Inside dungeons (2026-10-29, later): landing in a dungeon, it writes down the portals there and
|
||||
// walks straight to the nearest one it hasn't tried (DungeonGoing; dungeons have no navmesh, so a
|
||||
// portal round a corner may not be reachable this way and is given up when the walk sticks). The
|
||||
// walk is recorded (DungeonWalks), so a portal taken this way makes the dungeon routable. Up to
|
||||
// three dungeon portals in a row (one dungeon into the next), then back home. From home, a dungeon
|
||||
// with portals still untried is gone back into through its learned entry portal (a revisit).
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
public const double LearnRangeMin = 20, LearnRangeMax = 2000, LearnRangeDefault = 200;
|
||||
private const double LearnHomeUnits = 25.0; // this close to the home spot counts as back
|
||||
private const long LearnSettleMs = 3000; // after a teleport before planning the way back
|
||||
private const long LearnGoTimeoutMs = 180_000; // one portal attempt, walk included
|
||||
private const long LearnReturnTimeoutMs = 600_000; // one way back
|
||||
private const int LearnMaxPortals = 150; // a session's cap, so nothing runs forever
|
||||
|
||||
private enum LearnState { Off, Pick, Going, Landed, Return, DungeonGoing }
|
||||
|
||||
private const double LearnDungeonReach = 60.0; // a dungeon portal this far (straight line) is tried
|
||||
private const double LearnDungeonHeight = 8.0; // ...on about this floor
|
||||
private const int LearnDungeonHops = 3; // dungeon portals taken in a row before going home
|
||||
private const int LearnDungeonTries = 6; // dungeon portals tried on one visit
|
||||
private const int LearnMaxRevisits = 6; // times one entry portal is gone back into
|
||||
|
||||
private HubWalker? _dunWalker;
|
||||
private double _dunLastX, _dunLastY;
|
||||
private int _dunHops, _dunTries;
|
||||
private bool _learnTargetInDungeon, _learnRevisit;
|
||||
private uint _learnTargetLb;
|
||||
private double _learnTargetX, _learnTargetY;
|
||||
private readonly HashSet<uint> _learnDeadDungeons = new();
|
||||
private readonly Dictionary<string, int> _learnRevisits = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private LearnState _learn = LearnState.Off;
|
||||
private bool LearningPortals => _learn != LearnState.Off;
|
||||
private double _learnRange = LearnRangeDefault;
|
||||
private double _homeNs, _homeEw;
|
||||
private string _homeLabel = "";
|
||||
private long _learnStepMs;
|
||||
private string _learnTarget = "";
|
||||
private double _learnTargetNs, _learnTargetEw;
|
||||
private int _learnTried, _learnLearned, _learnFailed, _learnReturnFails;
|
||||
private readonly HashSet<string> _learnDone = new(StringComparer.OrdinalIgnoreCase);
|
||||
private string _learnLine = ""; // the panel's line; read under _gate
|
||||
|
||||
/// <summary>Route planning uses portals: the switch, or while learning (the way back may need them).</summary>
|
||||
private bool PortalsRouting => _portalsEnabled || LearningPortals;
|
||||
/// <summary>Recalls in routes: the switch, or while learning (the way back out of a dungeon is a recall).</summary>
|
||||
private bool RecallsRouting => _recallsEnabled || LearningPortals;
|
||||
|
||||
private void InitLearn() =>
|
||||
_learnRange = Math.Clamp(NavDataConfig.ReadNumber("learnRange", LearnRangeDefault), LearnRangeMin, LearnRangeMax);
|
||||
|
||||
private static string LearnKey(string name, double ns, double ew) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{name}|{ns:0.00}|{ew:0.00}");
|
||||
|
||||
private void SetLearnLine(string text)
|
||||
{
|
||||
lock (_gate) _learnLine = text;
|
||||
}
|
||||
|
||||
// ── Start / stop ───────────────────────────────────────────────────────
|
||||
|
||||
private void StartLearn()
|
||||
{
|
||||
if (LearningPortals) { Say("already learning portals — /rnav portals learn stop"); return; }
|
||||
string server = CurrentServer();
|
||||
if (server.Length == 0) { Note("learn portals: not logged in yet (no server name)"); return; }
|
||||
if (!_customLoaded) { Note("learn portals: the saved portals are still loading; try again in a moment"); return; }
|
||||
if (!Host.HasGetLiveObjectIds || !Host.HasUseObject) { Note("learn portals: this RynthCore engine can't see or use the objects around you"); return; }
|
||||
if (!PlayerMapPos(out double ns, out double ew)) { Note("learn portals: stand somewhere on the map (not in a dungeon) to start"); return; }
|
||||
_homeNs = ns; _homeEw = ew; _homeLabel = NearLabel(ns, ew);
|
||||
_learnDone.Clear();
|
||||
_learnDeadDungeons.Clear();
|
||||
_learnRevisits.Clear();
|
||||
_dunWalker = null; _dunHops = _dunTries = 0; _learnRevisit = false;
|
||||
_learnTried = _learnLearned = _learnFailed = _learnReturnFails = 0;
|
||||
_learn = LearnState.Pick;
|
||||
_learnStepMs = NowMs;
|
||||
Note($"learning portals within {_learnRange:0} yd of {NavCoords.Fmt(ns, ew)} on {server} — Stop (or any movement key) ends it");
|
||||
Host.Log($"[RynthNav] learn: start at {NavCoords.Fmt(ns, ew)} ({_homeLabel}), range {_learnRange:0} yd, server {server}");
|
||||
SetLearnLine("starting");
|
||||
}
|
||||
|
||||
/// <summary>Ends learning (said in chat and on the panel). Stops a walk it started only when <paramref name="stopWalk"/>.</summary>
|
||||
private void StopLearn(string why, bool stopWalk = false)
|
||||
{
|
||||
if (!LearningPortals) return;
|
||||
if (_learn == LearnState.DungeonGoing) AutoRun.Halt();
|
||||
_dunWalker = null;
|
||||
_learn = LearnState.Off;
|
||||
if (stopWalk && _gotoActive) FinishGoto("stopped (learning portals ended)");
|
||||
string summary = $"learning portals ended: {why} — tried {_learnTried}, learned {_learnLearned} landing(s), {_learnFailed} wouldn't take you";
|
||||
Note(summary);
|
||||
Host.Log("[RynthNav] learn: " + summary);
|
||||
SetLearnLine(summary);
|
||||
}
|
||||
|
||||
private void SetLearnRange(double yards)
|
||||
{
|
||||
_learnRange = Math.Clamp(Math.Round(yards), LearnRangeMin, LearnRangeMax);
|
||||
NavDataConfig.WriteNumber("learnRange", _learnRange);
|
||||
Say($"learn range {_learnRange:0} yd" + (LearningPortals ? " (the next pick uses it)" : ""));
|
||||
}
|
||||
|
||||
// ── Tick ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>One step of learning. Tick thread, after the teleport tracker.</summary>
|
||||
private void TickLearn(bool teleported)
|
||||
{
|
||||
if (!LearningPortals) return;
|
||||
long now = NowMs;
|
||||
if (CurrentServer().Length == 0) { StopLearn("logged out"); return; }
|
||||
switch (_learn)
|
||||
{
|
||||
case LearnState.Pick:
|
||||
if (_gotoActive || !_hasPose || now - LastTeleportMs < LearnSettleMs) return;
|
||||
PickNextPortal(now);
|
||||
break;
|
||||
|
||||
case LearnState.Going:
|
||||
// Taken: a teleport since the walk began (the goto's own portal wait may see it first).
|
||||
if (teleported || LastTeleportMs >= _learnStepMs)
|
||||
{
|
||||
_learn = LearnState.Landed;
|
||||
_learnStepMs = now;
|
||||
SetLearnLine($"took '{_learnTarget}': learning where it lands");
|
||||
return;
|
||||
}
|
||||
if (_trkPortaling || (Host.HasIsPortaling && Host.IsPortaling())) return; // in portal space: wait for the landing
|
||||
if (!_gotoActive || now - _learnStepMs > LearnGoTimeoutMs)
|
||||
{
|
||||
_learnFailed++;
|
||||
Host.Log($"[RynthNav] learn: '{_learnTarget}' didn't take you ({(_gotoActive ? "timed out" : _goNote)})");
|
||||
if (_gotoActive) FinishGoto($"learn: gave up on '{_learnTarget}'");
|
||||
BeginReturn(now);
|
||||
}
|
||||
break;
|
||||
|
||||
case LearnState.Landed:
|
||||
// Portal space can follow the jump by a moment and last a while: settle from its end.
|
||||
if (_trkPortaling || (Host.HasIsPortaling && Host.IsPortaling())) { _learnStepMs = now; return; }
|
||||
if (now - _learnStepMs < LearnSettleMs || _gotoActive) return;
|
||||
if (!_learnRevisit) CountLearned();
|
||||
_learnRevisit = false;
|
||||
if (InLearnableDungeon() && _dunHops < LearnDungeonHops)
|
||||
{
|
||||
_dunTries = 0;
|
||||
if (TryDungeonPortal(now)) return;
|
||||
}
|
||||
BeginReturn(now);
|
||||
break;
|
||||
|
||||
case LearnState.DungeonGoing:
|
||||
StepDungeonTry(now, teleported);
|
||||
break;
|
||||
|
||||
case LearnState.Return:
|
||||
if (_gotoActive && now - _learnStepMs < LearnReturnTimeoutMs) return;
|
||||
if (_gotoActive) FinishGoto("learn: the way back timed out");
|
||||
if (AtHome())
|
||||
{
|
||||
_learnReturnFails = 0;
|
||||
_learn = LearnState.Pick;
|
||||
_learnStepMs = now;
|
||||
SetLearnLine($"back at the start — tried {_learnTried}, learned {_learnLearned}");
|
||||
return;
|
||||
}
|
||||
if (++_learnReturnFails >= 2) { StopLearn($"no way back to the start from here ({_goNote})"); return; }
|
||||
Host.Log($"[RynthNav] learn: not back yet ({_goNote}); trying the way back again");
|
||||
BeginReturn(now);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private bool AtHome() =>
|
||||
PlayerMapPos(out double ns, out double ew) && NavCoords.Distance(ns, ew, _homeNs, _homeEw) <= LearnHomeUnits;
|
||||
|
||||
private void CountLearned()
|
||||
{
|
||||
foreach (CustomPortal p in _custom.For(CurrentServer()))
|
||||
{
|
||||
if (!p.DestKnown || !p.Name.Equals(_learnTarget, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
bool same = _learnTargetInDungeon
|
||||
? !p.OnMap && p.Landblock == _learnTargetLb
|
||||
&& Math.Sqrt((p.X - _learnTargetX) * (p.X - _learnTargetX) + (p.Y - _learnTargetY) * (p.Y - _learnTargetY)) <= CustomPortalStore.SameDungeonUnits * 2
|
||||
: p.OnMap && NavCoords.Distance(p.Ns, p.Ew, _learnTargetNs, _learnTargetEw) <= CustomPortalStore.SameUnits * 2;
|
||||
if (same) { _learnLearned++; return; }
|
||||
}
|
||||
// Taken, but it wasn't written down: the world data has it, or the portal wasn't seen as portal space began.
|
||||
Host.Log($"[RynthNav] learn: took '{_learnTarget}' but no landing was saved for it (the world data has it, or it wasn't the portal beside you)");
|
||||
}
|
||||
|
||||
private void BeginReturn(long now)
|
||||
{
|
||||
if (AtHome())
|
||||
{
|
||||
_learn = LearnState.Pick;
|
||||
_learnStepMs = now;
|
||||
return;
|
||||
}
|
||||
_learn = LearnState.Return;
|
||||
_learnStepMs = now;
|
||||
SetLearnLine($"going back to the start (tried {_learnTried}, learned {_learnLearned})");
|
||||
StartWalk("the learning start", "", _homeNs, _homeEw);
|
||||
}
|
||||
|
||||
/// <summary>Scans, then walks into the nearest untried portal in range; none left = done.</summary>
|
||||
private void PickNextPortal(long now)
|
||||
{
|
||||
if (_learnTried >= LearnMaxPortals) { StopLearn($"tried {LearnMaxPortals} portals (the cap for one run)"); return; }
|
||||
string server = CurrentServer();
|
||||
EnsurePortalsLoaded();
|
||||
|
||||
// Live portals in range: written down (Saw), and candidates while they have no landing yet.
|
||||
var cands = new List<(string Name, double Ns, double Ew)>();
|
||||
DateTime utc = DateTime.UtcNow;
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!LivePortalAt(id, out uint cell, out double wx, out double wy, out string name)) continue;
|
||||
if (!IsOnMap(cell) || Entrance.IsDestroyed(name)) continue;
|
||||
double ns = NavCoords.NsFromWorld(wy), ew = NavCoords.EwFromWorld(wx);
|
||||
if (NavCoords.Distance(ns, ew, _homeNs, _homeEw) > _learnRange) continue;
|
||||
Host.TryGetObjectWcid(id, out uint wcid);
|
||||
if (_custom.Saw(server, name, wcid, cell, true, ns, ew, _portals, utc) == CustomScanResult.BuiltIn) continue;
|
||||
cands.Add((name, ns, ew));
|
||||
}
|
||||
// Saved ones in range with no landing yet (out of sight from here).
|
||||
foreach (CustomPortal p in _custom.For(server))
|
||||
if (p.OnMap && !p.DestKnown && NavCoords.Distance(p.Ns, p.Ew, _homeNs, _homeEw) <= _learnRange)
|
||||
cands.Add((p.Name, p.Ns, p.Ew));
|
||||
// Entry portals in range into a dungeon that still has portals nobody tried: go back in.
|
||||
var revisits = new List<(string Name, double Ns, double Ew)>();
|
||||
foreach (CustomPortal p in _custom.For(server))
|
||||
{
|
||||
if (!p.OnMap || !p.DestKnown || p.DestOnMap || p.DestCell == 0 || _learnDeadDungeons.Contains(p.DestLandblock)) continue;
|
||||
if (NavCoords.Distance(p.Ns, p.Ew, _homeNs, _homeEw) > _learnRange) continue;
|
||||
string rk = LearnKey(p.Name, p.Ns, p.Ew);
|
||||
if (_learnRevisits.TryGetValue(rk, out int rv) && rv >= LearnMaxRevisits) continue;
|
||||
if (UntriedIn(server, p.DestLandblock)) revisits.Add((p.Name, p.Ns, p.Ew));
|
||||
}
|
||||
|
||||
PlayerMapPos(out double hereNs, out double hereEw);
|
||||
(string Name, double Ns, double Ew)? best = null;
|
||||
double bestD = double.MaxValue;
|
||||
int left = 0;
|
||||
var counted = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var c in cands)
|
||||
{
|
||||
string key = LearnKey(c.Name, c.Ns, c.Ew);
|
||||
if (_learnDone.Contains(key) || !counted.Add(key)) continue;
|
||||
if (_custom.Find(server, c.Name, 0, true, c.Ns, c.Ew) is { DestKnown: true }) continue; // mapped already
|
||||
left++;
|
||||
double d = NavCoords.Distance(hereNs, hereEw, c.Ns, c.Ew);
|
||||
if (d < bestD) { bestD = d; best = c; }
|
||||
}
|
||||
bool revisit = false;
|
||||
foreach (var c in revisits)
|
||||
{
|
||||
left++;
|
||||
if (best != null) continue; // a portal not yet tried comes first
|
||||
double d = NavCoords.Distance(hereNs, hereEw, c.Ns, c.Ew);
|
||||
if (d < bestD) { bestD = d; best = c; revisit = true; }
|
||||
}
|
||||
if (best is not { } next)
|
||||
{
|
||||
StopLearn($"every portal within {_learnRange:0} yd of the start has been tried");
|
||||
return;
|
||||
}
|
||||
_dunHops = 0;
|
||||
_learnRevisit = revisit;
|
||||
_learnTargetInDungeon = false;
|
||||
if (revisit)
|
||||
{
|
||||
string rk = LearnKey(next.Name, next.Ns, next.Ew);
|
||||
_learnRevisits[rk] = (_learnRevisits.TryGetValue(rk, out int rv) ? rv : 0) + 1;
|
||||
_learnTarget = next.Name; _learnTargetNs = next.Ns; _learnTargetEw = next.Ew;
|
||||
_learn = LearnState.Going;
|
||||
_learnStepMs = now;
|
||||
SetLearnLine($"back into the dungeon by '{next.Name}' for the portals inside it not tried yet");
|
||||
Host.Log($"[RynthNav] learn: back into the dungeon by '{next.Name}' at {NavCoords.Fmt(next.Ns, next.Ew)} (portals inside not tried yet)");
|
||||
StartWalk(next.Name, "Portal", next.Ns, next.Ew, next.Name, "Portal");
|
||||
return;
|
||||
}
|
||||
_learnDone.Add(LearnKey(next.Name, next.Ns, next.Ew));
|
||||
_learnTried++;
|
||||
_learnTarget = next.Name; _learnTargetNs = next.Ns; _learnTargetEw = next.Ew;
|
||||
_learn = LearnState.Going;
|
||||
_learnStepMs = now;
|
||||
SetLearnLine($"trying '{next.Name}' ({_learnTried} tried, {left - 1} more in range)");
|
||||
Host.Log($"[RynthNav] learn: trying '{next.Name}' at {NavCoords.Fmt(next.Ns, next.Ew)} ({bestD:0} yd away, {left - 1} more in range)");
|
||||
StartWalk(next.Name, "Portal", next.Ns, next.Ew, next.Name, "Portal");
|
||||
}
|
||||
|
||||
// ── Inside a dungeon ───────────────────────────────────────────────────
|
||||
|
||||
private static string DungeonKey(string name, uint lb, double x, double y) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{name}|{lb:X4}|{x:0}|{y:0}");
|
||||
|
||||
/// <summary>In a dungeon (not the Town Network, which townnet.json maps already).</summary>
|
||||
private bool InLearnableDungeon() =>
|
||||
_hasPose && !IsOnMap(_cellId) && (_cellId & 0xFFFF) >= 0x100 && _baseTownNet?.Contains(CurrentLandblock) != true;
|
||||
|
||||
/// <summary>A dungeon portal saved in <paramref name="lb"/> that no one has taken and this run hasn't tried.</summary>
|
||||
private bool UntriedIn(string server, uint lb)
|
||||
{
|
||||
foreach (CustomPortal p in _custom.For(server))
|
||||
if (!p.OnMap && p.Landblock == lb && !p.DestKnown && !Entrance.IsDestroyed(p.Name)
|
||||
&& !_learnDone.Contains(DungeonKey(p.Name, lb, p.X, p.Y)))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes down this dungeon's portals and walks straight to the nearest untried one in reach.
|
||||
/// False when there's none (the dungeon is done for this run as far as a straight walk goes).
|
||||
/// </summary>
|
||||
private bool TryDungeonPortal(long now)
|
||||
{
|
||||
if (_dunTries >= LearnDungeonTries || _learnTried >= LearnMaxPortals || !Host.HasGetLiveObjectIds) return false;
|
||||
string server = CurrentServer();
|
||||
uint lb = CurrentLandblock;
|
||||
DateTime utc = DateTime.UtcNow;
|
||||
double hx = LocalX, hy = LocalY;
|
||||
bool dats = DungeonPathAvailable();
|
||||
var cands = new List<(string Name, uint Cell, double X, double Y, double Z, double D)>();
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
void Consider(string name, uint pc, double lx, double ly, double z)
|
||||
{
|
||||
if (Entrance.IsDestroyed(name)) return;
|
||||
if (_custom.FindInDungeon(server, name, pc, lx, ly, z) is { DestKnown: true }) return;
|
||||
string key = DungeonKey(name, lb, lx, ly);
|
||||
if (_learnDone.Contains(key) || !seen.Add(key)) return;
|
||||
double d = Math.Sqrt((lx - hx) * (lx - hx) + (ly - hy) * (ly - hy));
|
||||
// Without RynthAi's dungeon pathfinder only a straight walk is possible: near, on this floor.
|
||||
if (!dats && (d > LearnDungeonReach || Math.Abs(z - _wz) > LearnDungeonHeight)) return;
|
||||
cands.Add((name, pc, lx, ly, z, d));
|
||||
}
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!LivePortalAt(id, out uint pc, out double wx, out double wy, out double wz, out string name)) continue;
|
||||
if ((pc >> 16) != lb) continue;
|
||||
double lx = wx - ((pc >> 24) & 0xFF) * 192.0, ly = wy - ((pc >> 16) & 0xFF) * 192.0;
|
||||
Host.TryGetObjectWcid(id, out uint wcid);
|
||||
_custom.SawInDungeon(server, name, wcid, pc, lx, ly, wz, utc);
|
||||
Consider(name, pc, lx, ly, wz);
|
||||
}
|
||||
// Saved earlier but out of sight from here: with the dungeon pathfinder they can be walked to too.
|
||||
if (dats)
|
||||
foreach (CustomPortal p in _custom.For(server))
|
||||
if (!p.OnMap && p.Landblock == lb && !p.DestKnown) Consider(p.Name, p.Cell, p.X, p.Y, p.Z);
|
||||
cands.Sort((a, b) => a.D.CompareTo(b.D));
|
||||
|
||||
foreach (var t in cands)
|
||||
{
|
||||
List<TownNetPoint>? way = dats ? DungeonWayHere(t.X, t.Y, t.Z) : null;
|
||||
string how = way != null ? $"{TownNet.PathLength(way, 0):0} m by RynthAi's dungeon pathfinder" : $"{t.D:0} m straight";
|
||||
if (way == null)
|
||||
{
|
||||
if (t.D > LearnDungeonReach || Math.Abs(t.Z - _wz) > LearnDungeonHeight) { _learnDone.Add(DungeonKey(t.Name, lb, t.X, t.Y)); continue; }
|
||||
way = new List<TownNetPoint>
|
||||
{
|
||||
new() { Cell = _cellId, X = hx, Y = hy, Z = _wz },
|
||||
new() { Cell = t.Cell, X = t.X, Y = t.Y, Z = t.Z },
|
||||
};
|
||||
}
|
||||
int left = cands.Count - 1;
|
||||
_learnDone.Add(DungeonKey(t.Name, lb, t.X, t.Y));
|
||||
_learnTried++; _dunTries++;
|
||||
_learnTarget = t.Name; _learnTargetInDungeon = true; _learnTargetLb = lb; _learnTargetX = t.X; _learnTargetY = t.Y;
|
||||
_learnRevisit = false;
|
||||
_dunWalker = new HubWalker(way, LastTeleportMs > 0 ? LastTeleportMs : now - HubWalker.CooldownMs, now);
|
||||
ResetDoor();
|
||||
_dunLastX = hx; _dunLastY = hy;
|
||||
AutoRun.Forget();
|
||||
_learn = LearnState.DungeonGoing;
|
||||
_learnStepMs = now;
|
||||
SetLearnLine($"in the dungeon: trying '{t.Name}' ({how}, {left} more)");
|
||||
Host.Log($"[RynthNav] learn: dungeon 0x{lb:X4}: trying '{t.Name}' at {t.X:F1},{t.Y:F1} ({how}, {left} more)");
|
||||
return true;
|
||||
}
|
||||
_learnDeadDungeons.Add(lb); // nothing left, or the rest can't be reached from the landing
|
||||
Host.Log($"[RynthNav] learn: no untried portal reachable in dungeon 0x{lb:X4}{(dats ? "" : $" within {LearnDungeonReach:0} m straight (RynthAi's dungeon pathfinder isn't available: {_dunPathWhy})")}");
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>One tick walking straight to a dungeon portal: taken (a teleport), or given up (stuck, no teleport).</summary>
|
||||
private void StepDungeonTry(long now, bool teleported)
|
||||
{
|
||||
HubWalker? w = _dunWalker;
|
||||
bool portaling = _trkPortaling || (Host.HasIsPortaling && Host.IsPortaling());
|
||||
double jump = Math.Sqrt((LocalX - _dunLastX) * (LocalX - _dunLastX) + (LocalY - _dunLastY) * (LocalY - _dunLastY));
|
||||
_dunLastX = LocalX; _dunLastY = LocalY;
|
||||
if (w == null || teleported || portaling || LastTeleportMs >= _learnStepMs || CurrentLandblock != _learnTargetLb || jump > 15.0)
|
||||
{
|
||||
AutoRun.Halt();
|
||||
_dunWalker = null;
|
||||
_dunHops++;
|
||||
_learn = LearnState.Landed;
|
||||
_learnStepMs = now;
|
||||
SetLearnLine($"took '{_learnTarget}' in the dungeon: learning where it lands");
|
||||
return;
|
||||
}
|
||||
DoorAct door = WalkDoor(w, now, out string doorWhy);
|
||||
if (door == DoorAct.Busy) return;
|
||||
double heading = 0;
|
||||
string why = doorWhy;
|
||||
HubWalker.Act act = door == DoorAct.Blocked ? HubWalker.Act.Stop : w.Step(LocalX, LocalY, _wz, now, out heading, out why);
|
||||
switch (act)
|
||||
{
|
||||
case HubWalker.Act.Run:
|
||||
DriveTo(heading);
|
||||
return;
|
||||
case HubWalker.Act.Jump:
|
||||
WalkJump(heading, w);
|
||||
return;
|
||||
case HubWalker.Act.Hold:
|
||||
AutoRun.Halt();
|
||||
return;
|
||||
default:
|
||||
AutoRun.Halt();
|
||||
_dunWalker = null;
|
||||
_learnFailed++;
|
||||
Host.Log($"[RynthNav] learn: dungeon portal '{_learnTarget}' not reached or didn't take you ({(why.Length > 0 ? why : "no teleport")})");
|
||||
if (!TryDungeonPortal(now)) BeginReturn(now);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Panel ──────────────────────────────────────────────────────────────
|
||||
|
||||
// This server's custom portal counts for the panel (tick writes, the pump thread reads).
|
||||
private volatile int _customSaved, _customRoutable;
|
||||
private (string Server, int Version, TownNet? Net) _customCountKey = ("", -1, null);
|
||||
|
||||
/// <summary>
|
||||
/// Recounts this server's custom portals when the server, the store or the route hub changed:
|
||||
/// routable = map-to-map links plus learned dungeon entries and exits the planner can use. Tick thread.
|
||||
/// </summary>
|
||||
private void RefreshCustomCounts()
|
||||
{
|
||||
string server = _server;
|
||||
TownNet? net = _townNet;
|
||||
if (_customCountKey == (server, _custom.Version, net)) return;
|
||||
_customCountKey = (server, _custom.Version, net);
|
||||
IReadOnlyList<CustomPortal> list = server.Length > 0 ? _custom.For(server) : Array.Empty<CustomPortal>();
|
||||
int routable = 0;
|
||||
foreach (CustomPortal p in list) if (p.Routable) routable++;
|
||||
if (net != null) { var (e, x, _) = net.LearnedCounts(); routable += e + x; }
|
||||
_customSaved = list.Count;
|
||||
_customRoutable = routable;
|
||||
}
|
||||
|
||||
/// <summary>The panel's "learn" object: on, range, the line, this server's counts. Any thread.</summary>
|
||||
private void AppendLearnJson(StringBuilder sb)
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
string line, server = _server;
|
||||
lock (_gate) line = _learnLine;
|
||||
int saved = _customSaved, routable = _customRoutable;
|
||||
sb.Append(",\"learn\":{\"on\":").Append(LearningPortals ? 1 : 0)
|
||||
.Append(",\"range\":").Append(_learnRange.ToString("0", ci))
|
||||
.Append(",\"min\":").Append(LearnRangeMin.ToString("0", ci)).Append(",\"max\":").Append(LearnRangeMax.ToString("0", ci))
|
||||
.Append(",\"server\":\"").Append(Esc(server)).Append("\",\"saved\":").Append(saved).Append(",\"routable\":").Append(routable)
|
||||
.Append(",\"tried\":").Append(_learnTried).Append(",\"learned\":").Append(_learnLearned)
|
||||
.Append(",\"line\":\"").Append(Esc(line)).Append("\"}");
|
||||
}
|
||||
}
|
||||
|
|
@ -47,6 +47,7 @@ public sealed partial class RynthNavPlugin
|
|||
_markersOn = NavDataConfig.ReadSwitch("markers", true);
|
||||
_markerLabels = NavDataConfig.ReadSwitch("markerLabels", true);
|
||||
_markerGuide = NavDataConfig.ReadSwitch("markerGuide", false);
|
||||
_followTrip = NavDataConfig.ReadSwitch("followTrip", true);
|
||||
}
|
||||
|
||||
// ── The walking path, for the engine's World Map ─────────────────────
|
||||
|
|
@ -98,6 +99,47 @@ public sealed partial class RynthNavPlugin
|
|||
}
|
||||
}
|
||||
|
||||
// ── Following the trip's path (TripFollow.cs) ────────────────────────
|
||||
private TripFollow? _follow;
|
||||
private bool _aimOnTrip, _offTripSaid;
|
||||
private volatile bool _followTrip = true;
|
||||
|
||||
/// <summary>/rnav follow [on|off]: walk along the trip's path (the markers), or plan to the route graph's crossings as before.</summary>
|
||||
private void CmdFollow(string rest)
|
||||
{
|
||||
string a = rest.Trim().ToLowerInvariant();
|
||||
if (a is "on" or "off")
|
||||
{
|
||||
_followTrip = a == "on";
|
||||
NavDataConfig.WriteSwitch("followTrip", _followTrip);
|
||||
_follow = null;
|
||||
}
|
||||
else if (a.Length > 0) { SayFail("follow [on|off] — keep the walk on the trip's path (the markers)"); return; }
|
||||
Say(_followTrip ? "follow ON: walks keep to the trip's path (the markers)" : "follow OFF: walks plan their own way to the route's crossings");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The running goto's step's walk to follow, or null: no live trip, its path not worked out yet, no
|
||||
/// walk for this step, or a walk that is only a straight line (the path finder had nothing there).
|
||||
/// Tick thread.
|
||||
/// </summary>
|
||||
private TripFollow? CurrentFollow()
|
||||
{
|
||||
PlannedTrip? trip = _trip;
|
||||
TripPath? path = _tripPath;
|
||||
if (!_followTrip || trip == null || !trip.Live || path == null || path.TripId != trip.Id || !IsOnMap(_cellId)) return null;
|
||||
int step = _route != null ? _routeIdx : 0;
|
||||
if (step < 0 || step >= path.Walks.Length || path.Walks[step] is not WorldPt[] walk || walk.Length < 2) return null;
|
||||
if (_follow != null && _follow.TripId == trip.Id && _follow.Step == step) return _follow;
|
||||
string tag = $"step {step + 1}:";
|
||||
foreach (string n in path.Notes)
|
||||
if (n.StartsWith(tag, StringComparison.Ordinal) && n.Contains("straight line", StringComparison.Ordinal)) return null;
|
||||
_follow = new TripFollow(trip.Id, step, walk);
|
||||
_offTripSaid = false;
|
||||
Host.Log($"[RynthNav] walk: following the trip's path for step {step + 1} ({_follow.Length:F0}u, {walk.Length} points)");
|
||||
return _follow;
|
||||
}
|
||||
|
||||
// ── The trip ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -125,7 +167,7 @@ public sealed partial class RynthNavPlugin
|
|||
string enterName, bool live)
|
||||
{
|
||||
var tr = new List<TripRecall>();
|
||||
if (recalls != null) foreach (RecallOption o in recalls) tr.Add(new TripRecall(o.Name, o.SpellId, o.Command, o.CastSeconds));
|
||||
if (recalls != null) foreach (RecallOption o in recalls) tr.Add(new TripRecall(o.Name, o.SpellId, o.Command, o.CastSeconds, o.ToArrival));
|
||||
return new PlannedTrip(++_tripSeq, steps ?? new List<RouteStep>(), goal, goalNs, goalEw,
|
||||
IsOnMap(_cellId), new WorldPt(_wx, _wy, _wz), _cellId, tr,
|
||||
enterName.Length > 0 ? _enterPortal : "", enterName, live);
|
||||
|
|
|
|||
|
|
@ -94,7 +94,7 @@ public sealed partial class RynthNavPlugin
|
|||
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))}";
|
||||
if (NextStepIsHub) return $"going into {TheHub(HubExitOf(_routeIdx + 1))}";
|
||||
return last && _enterName.Length > 0 ? "going into " + _enterName : "taking portal " + label;
|
||||
case "town":
|
||||
return HubLine(left);
|
||||
|
|
@ -102,7 +102,7 @@ public sealed partial class RynthNavPlugin
|
|||
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))})";
|
||||
return $"walking to the portal into {TheHub(HubExitOf(_routeIdx + 1))}{far}";
|
||||
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}";
|
||||
|
|
@ -166,6 +166,7 @@ public sealed partial class RynthNavPlugin
|
|||
sb.Append(",\"save\":{\"can\":").Append(trip != null ? 1 : 0).Append(",\"for\":\"").Append(Esc(trip?.Goal ?? ""))
|
||||
.Append("\",\"name\":\"").Append(Esc(_saveDefault)).Append("\",\"conflict\":\"").Append(Esc(_saveConflict))
|
||||
.Append("\",\"busy\":").Append(_saveBusy ? 1 : 0).Append(",\"last\":\"").Append(Esc(_saveLast)).Append("\"}");
|
||||
AppendLearnJson(sb); // learning portals (RynthNavPlugin.LearnPortals.cs)
|
||||
}
|
||||
|
||||
// ── The character's own recall spots, for the Recalls section (travel JSON) ──
|
||||
|
|
|
|||
|
|
@ -38,14 +38,19 @@ public sealed partial class RynthNavPlugin
|
|||
/// 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)
|
||||
/// <param name="learnedFrom">Arrivals from this index on are learned dungeons' (TownNet.Merge): their entries always stay.</param>
|
||||
private static HubLinks ViaAphus(HubLinks hub, List<RecallOption> recalls, List<string> notes, int learnedFrom = int.MaxValue)
|
||||
{
|
||||
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 };
|
||||
int townEntries = 0;
|
||||
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
|
||||
{
|
||||
if (e.Arrival >= learnedFrom) { only.Entries.Add(e); continue; }
|
||||
if (Math.Abs(e.SrcNs - aphus.Ns) < 0.3 && Math.Abs(e.SrcEw - aphus.Ew) < 0.3) { only.Entries.Add(e); townEntries++; }
|
||||
}
|
||||
if (townEntries == 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;
|
||||
|
|
|
|||
|
|
@ -22,13 +22,24 @@ public sealed partial class RynthNavPlugin
|
|||
private const long HubPortalSpaceTimeoutMs = 60000; // ...or never ends
|
||||
private const long HubSettleMs = 1500; // out of portal space and inside this long = landed
|
||||
|
||||
/// <summary>townnet.json as loaded (null: none, or it failed its checks).</summary>
|
||||
private volatile TownNet? _baseTownNet;
|
||||
/// <summary>What routes and the walker use: townnet.json plus this server's learned dungeons (TownNet.Merge). Null: neither.</summary>
|
||||
private volatile TownNet? _townNet;
|
||||
private (TownNet? Base, int Version, string Server, Atlas? Atlas, bool Dats, int Retry, double Drop, int Locked) _mergedKey = (null, -1, "", null, false, 0, -1, -1);
|
||||
private int _mergeRetry; // bumped to plan again (the dats weren't loaded the last time)
|
||||
private long _mergeRetryAtMs;
|
||||
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;
|
||||
// Leaving by a portal into another dungeon (a chain): the jump and portal space seen, still inside a hub landblock.
|
||||
private bool _hubLeaving, _hubLeftPortal;
|
||||
private long _hubLeaveMs;
|
||||
private uint _hubLb;
|
||||
private double _hubLastX, _hubLastY;
|
||||
private long _hubSettleSince; // when the landing settled (inside, out of portal space); 0 = not yet
|
||||
private long _hubStepMs;
|
||||
private HubWalker? _hubWalker;
|
||||
|
|
@ -49,7 +60,7 @@ public sealed partial class RynthNavPlugin
|
|||
Host.Log($"[RynthNav] {_townNetStatus}");
|
||||
return;
|
||||
}
|
||||
_townNet = t;
|
||||
_baseTownNet = 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}");
|
||||
}
|
||||
|
|
@ -61,6 +72,36 @@ public sealed partial class RynthNavPlugin
|
|||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the route hub when townnet.json loads, the custom portals change, or the server does:
|
||||
/// the Town Network plus this server's learned dungeons. A running hub step keeps its exit number
|
||||
/// (learned exits are only ever appended while walking). Tick thread.
|
||||
/// </summary>
|
||||
private void RefreshMergedNet()
|
||||
{
|
||||
if (!_customLoaded) { if (_townNet == null && _baseTownNet != null) _townNet = _baseTownNet; return; }
|
||||
TownNet? b = _baseTownNet;
|
||||
string server = _server;
|
||||
Atlas atlas = _atlas;
|
||||
bool dats = DungeonPathAvailable();
|
||||
if (_mergeRetryAtMs != 0 && NowMs >= _mergeRetryAtMs) { _mergeRetryAtMs = 0; _mergeRetry++; }
|
||||
// The drop setting and the locked doors found change the planned walks (2026-10-30).
|
||||
var key = (b, _custom.Version, server, (Atlas?)atlas, dats, _mergeRetry, _dropMeters, _lockedDoorVersion);
|
||||
if (key == _mergedKey) return;
|
||||
_mergedKey = key;
|
||||
bool anyDungeonPortal = false;
|
||||
if (server.Length > 0) foreach (CustomPortal p in _custom.For(server)) if (!p.OnMap && p.DestKnown) { anyDungeonPortal = true; break; }
|
||||
if (server.Length == 0 || (_custom.WalksFor(server).Count == 0 && !(dats && anyDungeonPortal))) { _townNet = b; return; }
|
||||
_dunPathNoData = false;
|
||||
TownNet merged = TownNet.Merge(b, _custom, server, atlas, dats ? DungeonPath : null);
|
||||
var (e, x, w) = merged.LearnedCounts();
|
||||
int planned = merged.PlannedWalks();
|
||||
_townNet = merged.Exits.Count == 0 ? b : merged;
|
||||
Host.Log($"[RynthNav] learned dungeons for {server}: {e} entry portal(s), {x} exit portal(s), {w - planned} walk(s) inside"
|
||||
+ (dats ? $" + {planned} planned from the dats (RynthAi's dungeon pathfinder)" : " (RynthAi's dungeon pathfinder not available: walked ones only)"));
|
||||
if (_dunPathNoData) _mergeRetryAtMs = NowMs + 15000; // some dungeon wasn't readable yet: plan again shortly
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
|
|
@ -101,10 +142,46 @@ public sealed partial class RynthNavPlugin
|
|||
|
||||
private static string HubWhere(TownNetExit? x) => x?.Where ?? "the next town";
|
||||
|
||||
/// <summary>"the Town Network", "the Abandoned Mine": the place a hub step walks through, for what RynthNav says.</summary>
|
||||
private static string TheHub(TownNetExit? x) => TheHub(x?.Hub ?? "Town Network");
|
||||
private static string TheHub(string hub) =>
|
||||
hub.StartsWith("the ", StringComparison.OrdinalIgnoreCase) || hub.StartsWith("dungeon ", StringComparison.Ordinal) ? hub : "the " + hub;
|
||||
|
||||
/// <summary>The exit of hub step <paramref name="s"/> in the route hub, or null.</summary>
|
||||
private TownNetExit? HubExitOf(RouteStep s)
|
||||
{
|
||||
TownNet? t = _townNet;
|
||||
return t != null && s.IsHub && s.HubExit >= 0 && s.HubExit < t.Exits.Count ? t.Exits[s.HubExit] : null;
|
||||
}
|
||||
|
||||
/// <summary>Where a hub exit takes you: a spot on the map, or the dungeon it leads into.</summary>
|
||||
private string HubExitDest(TownNetExit? x)
|
||||
{
|
||||
if (x == null) return "the next place";
|
||||
if (x.DestOnMap) return NavCoords.Fmt(x.DestNs, x.DestEw) + (x.DestTown.Length > 0 ? $" ({x.DestTown})" : "");
|
||||
return TheHub(DungeonName(x.DestLandblock));
|
||||
}
|
||||
|
||||
/// <summary>A dungeon landblock's name: the route hub's (learned dungeons, the Atlas's), else "dungeon LLLL".</summary>
|
||||
private string DungeonName(uint lb)
|
||||
{
|
||||
TownNet? t = _townNet;
|
||||
if (t != null)
|
||||
foreach (TownNetExit e in t.Exits)
|
||||
if ((e.Cell >> 16) == lb && e.Hub.Length > 0 && !e.Hub.StartsWith("dungeon ", StringComparison.Ordinal)) return e.Hub;
|
||||
if (_baseTownNet?.Contains(lb) == true) return "Town Network";
|
||||
string hex = lb.ToString("X4", System.Globalization.CultureInfo.InvariantCulture);
|
||||
foreach (AtlasLocation l in _atlas.Locations)
|
||||
if (l.Type.Equals("Dungeon", StringComparison.Ordinal) && l.Lb.Equals(hex, StringComparison.OrdinalIgnoreCase)) return l.Name;
|
||||
return $"dungeon {hex}";
|
||||
}
|
||||
|
||||
private void ResetHub()
|
||||
{
|
||||
_hubActive = false; _hubLanded = false; _hubWaitSaid = false; _hubSettleSince = 0;
|
||||
_hubWalker = null;
|
||||
_hubLeaving = false; _hubLeftPortal = false; _hubLeaveMs = 0; _hubLb = 0;
|
||||
ResetDoor();
|
||||
}
|
||||
|
||||
private double LocalX => _wx - ((_cellId >> 24) & 0xFF) * 192.0;
|
||||
|
|
@ -118,13 +195,14 @@ public sealed partial class RynthNavPlugin
|
|||
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 (t == null || exit == null) { FinishGoto("stopped: the walks inside aren't loaded (townnet.json or the learned dungeons)"); return; }
|
||||
string hubName = exit.Hub;
|
||||
if (!_hubActive)
|
||||
{
|
||||
ResetHub();
|
||||
_hubActive = true;
|
||||
_hubStepMs = now;
|
||||
lock (_gate) _status = $"Town Network → {exit.Where}";
|
||||
lock (_gate) _status = $"{hubName} → {exit.Where}";
|
||||
}
|
||||
bool portaling = Host.HasIsPortaling && Host.IsPortaling();
|
||||
uint lb = CurrentLandblock;
|
||||
|
|
@ -142,33 +220,72 @@ public sealed partial class RynthNavPlugin
|
|||
{
|
||||
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})");
|
||||
FinishGoto($"stopped: the portal didn't take you into {hubName} (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");
|
||||
FinishGoto($"stopped: still in portal space a minute after taking the portal into {hubName}");
|
||||
return;
|
||||
}
|
||||
_hubLanded = true;
|
||||
_hubLb = lb;
|
||||
_hubLastX = LocalX; _hubLastY = LocalY;
|
||||
// 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 && exit.Learned)
|
||||
{
|
||||
// Away from every walk RynthNav knows to it: RynthAi's dungeon pathfinder (the dats) finds the way.
|
||||
way = DungeonWayHere(exit.X, exit.Y, exit.Z);
|
||||
if (way != null) from = "RynthAi's dungeon pathfinder (not walked before)";
|
||||
}
|
||||
if (way == null)
|
||||
{
|
||||
FinishGoto($"stopped in the Town Network: you landed at {x:F1}, {y:F1}, away from every walk to the {exit.Name}");
|
||||
FinishGoto($"stopped in {hubName}: you landed at {x:F1}, {y:F1}, away from every walk to the {exit.Name}"
|
||||
+ (exit.Learned && !_dunPathAvailable ? $" ({_dunPathWhy}: the dungeon pathfinder can't find one)" : ""));
|
||||
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}");
|
||||
Say($"{hubName}: walking to the {exit.Name} ({_hubWalker.Length:F0} m{(_hubWalker.Levels ? ", over more than one level" : "")}).");
|
||||
Host.Log($"[RynthNav] {hubName}: landed at {x:F1},{y:F1} (lb 0x{lb:X4}), walk from {from}: {way.Count} points, {_hubWalker.Length:F1} m to {exit.Name}");
|
||||
}
|
||||
|
||||
// An exit into another learned dungeon: still "inside" afterwards, so the teleport is the
|
||||
// landblock changing, a jump, or portal space (the jump can come a moment before it).
|
||||
bool chain = !exit.DestOnMap && exit.DestArrival >= 0;
|
||||
if (chain && inside && !_hubLeaving)
|
||||
{
|
||||
double jump = Math.Sqrt((LocalX - _hubLastX) * (LocalX - _hubLastX) + (LocalY - _hubLastY) * (LocalY - _hubLastY));
|
||||
if (portaling || lb != _hubLb || jump > 15.0) { _hubLeaving = true; _hubLeaveMs = now; }
|
||||
}
|
||||
_hubLastX = LocalX; _hubLastY = LocalY;
|
||||
|
||||
// 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");
|
||||
_hubLeftPortal |= _hubLeaving;
|
||||
if (now > _hubWalker!.LimitMs + HubPortalSpaceTimeoutMs) FinishGoto($"stopped: still in portal space a minute after {hubName}'s exit");
|
||||
return;
|
||||
}
|
||||
if (_hubLeaving)
|
||||
{
|
||||
HubHalt();
|
||||
_hubWalker!.Pause(now);
|
||||
// Out of portal space (or none came in 3 s): landed at the next dungeon's arrival.
|
||||
if (!_hubLeftPortal && now - _hubLeaveMs < 3000) return;
|
||||
if (exit.DestCell != 0 && lb != exit.DestLandblock)
|
||||
{
|
||||
FinishGoto($"stopped: the {exit.Name} sent you to landblock 0x{lb:X4}, not to 0x{exit.DestLandblock:X4}: wrong portal");
|
||||
return;
|
||||
}
|
||||
Say($"{hubName}: took the {exit.Name}.");
|
||||
Host.Log($"[RynthNav] {hubName}: took {exit.Name} into lb 0x{lb:X4} (a chained dungeon)");
|
||||
ResetHub();
|
||||
_lastLandMs = NowMs;
|
||||
if (_routeIdx >= _route!.Count - 1) { FinishGoto("arrived"); return; }
|
||||
AdvanceRoute();
|
||||
return;
|
||||
}
|
||||
if (!inside)
|
||||
|
|
@ -177,11 +294,11 @@ public sealed partial class RynthNavPlugin
|
|||
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");
|
||||
FinishGoto($"stopped: {hubName} 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})");
|
||||
Say($"{hubName}: took the {exit.Name}.");
|
||||
Host.Log($"[RynthNav] {hubName}: 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; }
|
||||
|
|
@ -189,23 +306,37 @@ public sealed partial class RynthNavPlugin
|
|||
return;
|
||||
}
|
||||
|
||||
switch (_hubWalker!.Step(LocalX, LocalY, now, out double heading, out string why))
|
||||
// A closed door across the walk: open it (or unlock it), else go round it (RynthNavPlugin.Doors.cs).
|
||||
switch (WalkDoor(_hubWalker!, now, out string doorWhy))
|
||||
{
|
||||
case DoorAct.Busy:
|
||||
return;
|
||||
case DoorAct.Blocked:
|
||||
if (exit.Learned && HubWalkRound(exit, now)) return;
|
||||
HubStop(exit, doorWhy);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (_hubWalker!.Step(LocalX, LocalY, _wz, now, out double heading, out string why))
|
||||
{
|
||||
case HubWalker.Act.Run:
|
||||
DriveTo(heading);
|
||||
return;
|
||||
case HubWalker.Act.Jump:
|
||||
WalkJump(heading, _hubWalker);
|
||||
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.");
|
||||
Say($"{hubName}: 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}");
|
||||
FinishGoto($"stopped in {hubName}: the {exit.Name} didn't take you{need}");
|
||||
return;
|
||||
}
|
||||
default:
|
||||
|
|
@ -214,8 +345,22 @@ public sealed partial class RynthNavPlugin
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A door on the walk nothing opens: the walk planned again from here (RynthAi's dungeon
|
||||
/// pathfinder, the locked doors' doorways left out). False when there is no other way.
|
||||
/// </summary>
|
||||
private bool HubWalkRound(TownNetExit exit, long now)
|
||||
{
|
||||
List<TownNetPoint>? way = DungeonWayHere(exit.X, exit.Y, exit.Z);
|
||||
if (way == null) return false;
|
||||
_hubWalker = new HubWalker(way, now - HubWalker.CooldownMs, now);
|
||||
Say($"{exit.Hub}: a door on the way won't open; going round it ({_hubWalker.Length:F0} m to the {exit.Name}).");
|
||||
Host.Log($"[RynthNav] {exit.Hub}: walk planned again round {_lockedDoors.Count} locked door(s): {way.Count} points, {_hubWalker.Length:F1} m");
|
||||
return true;
|
||||
}
|
||||
|
||||
private void HubStop(TownNetExit exit, string why) =>
|
||||
FinishGoto($"stopped in the Town Network: {why} on the way to the {exit.Name}");
|
||||
FinishGoto($"stopped in {exit.Hub}: {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;
|
||||
|
|
@ -224,10 +369,10 @@ public sealed partial class RynthNavPlugin
|
|||
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" : "")}";
|
||||
string name = exit?.Name ?? "exit portal", hub = TheHub(exit);
|
||||
if (!_hubLanded) return $"going into {hub} (then the {name})";
|
||||
if (HubIsWaiting) return $"in {hub}: waiting for the {name} to let you through";
|
||||
return $"in {hub}: 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>
|
||||
|
|
@ -239,13 +384,54 @@ public sealed partial class RynthNavPlugin
|
|||
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})";
|
||||
string hub = TheHub(exit), on = HubChainText(i);
|
||||
if (i == 0) return $"through {hub}: walking to the {exit.Name}{on}";
|
||||
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";
|
||||
if (entry.IsHub) return "";
|
||||
if (entry.UseRecall) return $"{entry.Label} into {hub}, then the {exit.Name}{on}";
|
||||
return $"through {hub}: its portal at {NavCoords.Fmt(entry.Ns, entry.Ew)}, then the {exit.Name} inside{on}";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rest of a run of hub steps from <paramref name="i"/>: ", into the Vault, then the Vault Exit to 40S, 40W"
|
||||
/// (each dungeon it goes on into), or " to <where the exit lands>" for one step.
|
||||
/// </summary>
|
||||
private string HubChainText(int i)
|
||||
{
|
||||
if (_route == null) return "";
|
||||
var sb = new System.Text.StringBuilder();
|
||||
for (int k = i; k < _route.Count && _route[k].IsHub; k++)
|
||||
{
|
||||
TownNetExit? x = HubExitOf(_route[k]);
|
||||
if (k > i) sb.Append($", then the {x?.Name ?? _route[k].Label}");
|
||||
if (x != null && !x.DestOnMap && k + 1 < _route.Count && _route[k + 1].IsHub) sb.Append($" into {HubExitDest(x)}");
|
||||
else if (x != null) sb.Append($" to {HubExitDest(x)}");
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Standing in a learned dungeon: per exit of <paramref name="hub"/> (its order), the walk from
|
||||
/// where you stand to that portal (a learned walk passing within HubOffRouteUnits), NaN for none.
|
||||
/// </summary>
|
||||
private double[]? StartHubWalks(HubLinks hub, out int walkable)
|
||||
{
|
||||
walkable = 0;
|
||||
TownNet? t = _townNet;
|
||||
if (t == null || !t.Contains(CurrentLandblock) || hub.Exits.Count == 0) return null;
|
||||
var walks = new double[hub.Exits.Count];
|
||||
double x = LocalX, y = LocalY;
|
||||
for (int i = 0; i < hub.Exits.Count; i++)
|
||||
{
|
||||
List<TownNetPoint>? way = t.WayTo(hub.Exits[i].Id, x, y, HubOffRouteUnits, out _);
|
||||
walks[i] = way == null ? double.NaN : TownNet.PathLength(way, 0);
|
||||
if (way != null) walkable++;
|
||||
}
|
||||
return walkable > 0 ? walks : null;
|
||||
}
|
||||
|
||||
/// <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
|
||||
|
|
@ -262,17 +448,18 @@ public sealed partial class RynthNavPlugin
|
|||
List<RouteStep>? best = null;
|
||||
double bestCost = double.MaxValue;
|
||||
int bestUsed = 0;
|
||||
if (_portalsEnabled) EnsurePortalsLoaded();
|
||||
if (PortalsRouting) EnsurePortalsLoaded();
|
||||
foreach (HubExit hx in links.Exits)
|
||||
{
|
||||
if (hx.ToArrival >= 0) continue; // into another dungeon: only planned from a landing
|
||||
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);
|
||||
if (PortalsRouting && RoutePortals() is { Count: > 0 } routePortals)
|
||||
rest = PortalRoute.Plan(routePortals, null, hx.DstNs, hx.DstEw, goalNs, goalEw, out restCost, out used);
|
||||
else
|
||||
{
|
||||
restCost = NavCoords.Distance(hx.DstNs, hx.DstEw, goalNs, goalEw);
|
||||
|
|
|
|||
|
|
@ -84,6 +84,11 @@ public sealed partial class RynthNavPlugin
|
|||
private double _trkLastWx, _trkLastWy, _trkPreWx, _trkPreWy;
|
||||
private long _trkLastTeleportMs, _trkPortalStartMs;
|
||||
private bool _trkPortalBeside; // a live portal stood right beside you as portal space began
|
||||
// Portal space that began just after a position jump already counted as the teleport (the client
|
||||
// often moves you a moment BEFORE portal space): its end isn't another teleport.
|
||||
private bool _trkTail;
|
||||
private double _trkLastWz;
|
||||
private const long TeleportTailMs = 3000;
|
||||
|
||||
// Route planning with recalls: the recalls the current route can use (by RouteStep.RecallIndex).
|
||||
private List<RecallOption> _routeRecalls = new();
|
||||
|
|
@ -120,6 +125,7 @@ public sealed partial class RynthNavPlugin
|
|||
|
||||
private void InitTravel()
|
||||
{
|
||||
LoadCustomPortals();
|
||||
string path = NavFile("locations.json");
|
||||
Task.Run(() =>
|
||||
{
|
||||
|
|
@ -156,7 +162,7 @@ public sealed partial class RynthNavPlugin
|
|||
|
||||
private void OnLoginTravel()
|
||||
{
|
||||
_charKey = ""; _playerName = ""; _known = null; _nextKnownMs = 0;
|
||||
_charKey = ""; _playerName = ""; _known = null; _nextKnownMs = 0; _server = ""; _usedPortalSeen = false;
|
||||
_pendingRecallSlot = null; _castRecallSpell = 0; _pendingTie = null; _selfCastMs = 0;
|
||||
_trkHaveLast = false; _trkPortaling = false;
|
||||
}
|
||||
|
|
@ -165,8 +171,12 @@ public sealed partial class RynthNavPlugin
|
|||
{
|
||||
_recallWait = false;
|
||||
_trkHaveLast = false; _trkPortaling = false;
|
||||
_known = null; _charKey = "";
|
||||
StopLearn("logged out");
|
||||
_known = null; _charKey = ""; _server = ""; _usedPortalSeen = false;
|
||||
SaveStores(force: true);
|
||||
TickCustomPortals(force: true);
|
||||
TickGems(NowMs, force: true);
|
||||
_packGems = new List<PackGem>(); _packSnap = new(); _gemSpentWcid = 0;
|
||||
}
|
||||
|
||||
// ── Tick ─────────────────────────────────────────────────────────────────
|
||||
|
|
@ -200,10 +210,17 @@ public sealed partial class RynthNavPlugin
|
|||
&& Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out _, out _, out _, out _) && maxHp > 0 && hp == 0)
|
||||
_selfCastDied = true; // died mid-cast: the trip to the lifestone that follows isn't a recall
|
||||
|
||||
TickNearPortal();
|
||||
bool teleported = TrackTeleport(now);
|
||||
TickDungeonTrail(teleported);
|
||||
UpdateArrow(teleported);
|
||||
TickLearn(teleported);
|
||||
|
||||
if (now >= _nextSaveMs) { _nextSaveMs = now + 3000; SaveStores(force: false); }
|
||||
TickGems(now);
|
||||
if (now >= _nextSaveMs) { _nextSaveMs = now + 3000; SaveStores(force: false); TickCustomPortals(); }
|
||||
else if (!_customLoaded) TickCustomPortals();
|
||||
RefreshMergedNet();
|
||||
RefreshCustomCounts();
|
||||
RebuildTravelJson();
|
||||
}
|
||||
|
||||
|
|
@ -214,6 +231,7 @@ public sealed partial class RynthNavPlugin
|
|||
Host.TryGetWorldName(out string world);
|
||||
_playerName = name;
|
||||
_charKey = (world.Length > 0 ? world : "?") + "|" + name;
|
||||
if (world.Trim().Length > 0) _server = world.Trim();
|
||||
}
|
||||
|
||||
private void RefreshKnownSpells(long now)
|
||||
|
|
@ -283,10 +301,13 @@ public sealed partial class RynthNavPlugin
|
|||
{
|
||||
_trkPortaling = true;
|
||||
_trkPortalStartMs = now;
|
||||
_trkTail = _trkLastTeleportMs > 0 && now - _trkLastTeleportMs < TeleportTailMs;
|
||||
if (_trkTail) return false; // the jump before it was the teleport; nothing beside you here was taken
|
||||
// Only worth the look after your own spell words (a hand-cast recall, or a portal used standing at it?).
|
||||
_trkPortalBeside = _selfCastMs != 0 && now - _selfCastMs < HandCastWindowMs && _trkHaveLast && LivePortalWithin(_trkLastWx, _trkLastWy, PortalBesideUnits);
|
||||
_trkHavePre = _trkHaveLast;
|
||||
_trkPreCell = _trkLastCell; _trkPreWx = _trkLastWx; _trkPreWy = _trkLastWy;
|
||||
NoteUsedPortal(_trkHaveLast, _trkLastCell, _trkLastWx, _trkLastWy, _trkLastWz); // a custom portal's landing (CustomPortals.cs)
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
|
@ -300,6 +321,22 @@ public sealed partial class RynthNavPlugin
|
|||
double preWx = _trkPortaling ? _trkPreWx : _trkLastWx, preWy = _trkPortaling ? _trkPreWy : _trkLastWy;
|
||||
long startMs = _trkPortaling ? _trkPortalStartMs : now;
|
||||
bool portalBeside = _trkPortaling && _trkPortalBeside;
|
||||
if (_trkPortaling && _trkTail)
|
||||
{
|
||||
// The end of the portal space that followed a jump: the same teleport. The landing counts from here.
|
||||
_trkPortaling = false; _trkTail = false;
|
||||
_trkLastTeleportMs = now;
|
||||
_trkHaveLast = true; _trkLastCell = _cellId; _trkLastWx = _wx; _trkLastWy = _wy; _trkLastWz = _wz;
|
||||
return false;
|
||||
}
|
||||
if (!_trkPortaling)
|
||||
{
|
||||
// A jump with no portal space seen (yet): the portal you stood at, if any, unless you were recalling.
|
||||
bool recalling = (_selfCastMs != 0 && now - _selfCastMs < HandCastWindowMs)
|
||||
|| (_castRecallSpell != 0 && now - _castRecallMs < RecallCastWindowMs) || _pendingRecallSlot != null || _recallWait;
|
||||
if (!recalling && now - _trkLastTeleportMs > 2000) NoteUsedPortal(_trkHaveLast, _trkLastCell, _trkLastWx, _trkLastWy, _trkLastWz);
|
||||
else _usedPortalSeen = false;
|
||||
}
|
||||
_trkPortaling = false;
|
||||
if (now - _trkLastTeleportMs > 2000)
|
||||
{
|
||||
|
|
@ -308,7 +345,7 @@ public sealed partial class RynthNavPlugin
|
|||
OnTeleported(havePre, preCell, preWx, preWy, startMs, portalBeside);
|
||||
}
|
||||
}
|
||||
_trkHaveLast = true; _trkLastCell = _cellId; _trkLastWx = _wx; _trkLastWy = _wy;
|
||||
_trkHaveLast = true; _trkLastCell = _cellId; _trkLastWx = _wx; _trkLastWy = _wy; _trkLastWz = _wz;
|
||||
return teleported;
|
||||
}
|
||||
|
||||
|
|
@ -325,6 +362,8 @@ public sealed partial class RynthNavPlugin
|
|||
&& Math.Sqrt((preWx - _selfCastWx) * (preWx - _selfCastWx) + (preWy - _selfCastWy) * (preWy - _selfCastWy)) < HandCastStillUnits;
|
||||
_selfCastMs = 0; _selfCastDied = false;
|
||||
if (who.Length == 0) return;
|
||||
// A portal gem used up just before (by you or a route's gem step): its landing (RynthNavPlugin.Gems.cs).
|
||||
if (TryLearnGem(landing, now)) { _usedPortalSeen = false; _pendingRecallSlot = null; return; }
|
||||
|
||||
if (_pendingRecallSlot is RecallSlot slot && now - _pendingRecallMs < RecallAnnounceWindowMs)
|
||||
{
|
||||
|
|
@ -362,7 +401,8 @@ public sealed partial class RynthNavPlugin
|
|||
// Not a recall we know of: a portal, most likely. Portal Recall goes back to where
|
||||
// the last portal dropped you. A landing at a known recall's spot (a recall cast by
|
||||
// hand, or dying and waking at the lifestone) isn't a portal.
|
||||
if (landing.OnMap && LandsLikeARecall(landing)) return;
|
||||
if (landing.OnMap && LandsLikeARecall(landing)) { _usedPortalSeen = false; return; }
|
||||
LearnCustomPortal(landing);
|
||||
string label = landing.Label;
|
||||
if (havePre && IsOnMap(preCell))
|
||||
{
|
||||
|
|
@ -485,7 +525,12 @@ public sealed partial class RynthNavPlugin
|
|||
{
|
||||
var s = new RecallSpot();
|
||||
if (PlayerMapPos(out double ns, out double ew)) { s.OnMap = true; s.Ns = Math.Round(ns, 2); s.Ew = Math.Round(ew, 2); s.Label = NearLabel(ns, ew); }
|
||||
else s.Label = $"a dungeon (landblock {(_cellId >> 16):X4})";
|
||||
else
|
||||
{
|
||||
s.Label = $"a dungeon (landblock {(_cellId >> 16):X4})";
|
||||
// Where in it: a recall or gem landing here routes on through the dungeon's learned walks.
|
||||
if (_hasPose) { s.Cell = _cellId; s.HasPos = true; s.X = Math.Round(LocalX, 2); s.Y = Math.Round(LocalY, 2); s.Z = Math.Round(_wz, 2); }
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
|
|
@ -503,6 +548,7 @@ public sealed partial class RynthNavPlugin
|
|||
{
|
||||
RecallEvent e = RecallMemory.Classify(text, _playerName, chatType);
|
||||
if (e != RecallEvent.None) _recallEvents.Enqueue((e, NowMs));
|
||||
NoteDoorText(text);
|
||||
}
|
||||
|
||||
private void OnRecallEvent(RecallEvent e, long ms)
|
||||
|
|
@ -719,9 +765,9 @@ public sealed partial class RynthNavPlugin
|
|||
/// <summary>The recalls this character can use right now, and notes on the ones left out.</summary>
|
||||
private List<RecallOption> CurrentRecalls(List<string>? notes)
|
||||
{
|
||||
if (!_recallsEnabled) { notes?.Add("Recalls are off (/rnav recalls on)."); return new List<RecallOption>(); }
|
||||
if (!RecallsRouting) { notes?.Add("Recalls are off (/rnav recalls on)."); return new List<RecallOption>(); }
|
||||
if (_charKey.Length == 0) { notes?.Add("Not logged in yet."); return new List<RecallOption>(); }
|
||||
return RecallPlanner.Build(_atlas, _known, _memory, _charKey, notes);
|
||||
return AllRecalls(_atlas, notes);
|
||||
}
|
||||
|
||||
// ── Recall steps of a route ──────────────────────────────────────────────
|
||||
|
|
@ -732,6 +778,7 @@ public sealed partial class RynthNavPlugin
|
|||
_recallStartMs = NowMs;
|
||||
_recallLastCastMs = 0; _recallLastStanceMs = 0;
|
||||
_recallWandTried = false; _recallChangedStance = false; _recallSent = false; _recallWasPortaling = false;
|
||||
_gemLastUseMs = 0;
|
||||
_recallPreLb = CurrentLandblock; _recallPreWx = _wx; _recallPreWy = _wy;
|
||||
BeginWand();
|
||||
AutoRun.Stop();
|
||||
|
|
@ -780,6 +827,12 @@ public sealed partial class RynthNavPlugin
|
|||
return;
|
||||
}
|
||||
|
||||
if (o.IsGem)
|
||||
{
|
||||
// A portal gem from the pack: use it (no stance, no wand), again after a while.
|
||||
if (!UseRouteGem(o, now)) { EndRecall(); FinishGoto($"stopped: no {o.ItemName} left in your pack"); }
|
||||
return;
|
||||
}
|
||||
if (o.SpellId == 0)
|
||||
{
|
||||
// A command recall (@lifestone, @house recall): send it once, again after 20 s.
|
||||
|
|
@ -970,7 +1023,7 @@ public sealed partial class RynthNavPlugin
|
|||
|
||||
// Recalls this character can use, and why others are left out
|
||||
var notes = new List<string>();
|
||||
List<RecallOption> recalls = _charKey.Length == 0 ? new List<RecallOption>() : RecallPlanner.Build(atlas, _known, _memory, _charKey, notes);
|
||||
List<RecallOption> recalls = _charKey.Length == 0 ? new List<RecallOption>() : AllRecalls(atlas, notes);
|
||||
if (_charKey.Length == 0) notes.Add("Not logged in yet.");
|
||||
sb.Append(",\"recalls\":[");
|
||||
for (int i = 0; i < recalls.Count; i++)
|
||||
|
|
@ -979,7 +1032,7 @@ public sealed partial class RynthNavPlugin
|
|||
if (i > 0) sb.Append(',');
|
||||
sb.Append("{\"n\":\"").Append(Esc(r.Name)).Append("\",\"ns\":").Append(r.Ns.ToString("F2", ci))
|
||||
.Append(",\"ew\":").Append(r.Ew.ToString("F2", ci)).Append(",\"how\":\"")
|
||||
.Append(Esc(r.SpellId != 0 ? "spell " + r.SpellId.ToString(ci) : r.Command)).Append("\",\"learned\":").Append(r.Learned ? 1 : 0).Append('}');
|
||||
.Append(Esc((r.SpellId != 0 ? "spell " + r.SpellId.ToString(ci) : r.Command) + (r.ToArrival >= 0 ? " → " + r.Where : ""))).Append("\",\"learned\":").Append(r.Learned ? 1 : 0).Append('}');
|
||||
}
|
||||
sb.Append("],\"recallNotes\":[");
|
||||
for (int i = 0; i < notes.Count; i++) { if (i > 0) sb.Append(','); sb.Append('"').Append(Esc(notes[i])).Append('"'); }
|
||||
|
|
@ -1018,6 +1071,11 @@ public sealed partial class RynthNavPlugin
|
|||
"/rnav route <place|coords> — plan a route (portals and recalls), no walking\n" +
|
||||
"/rnav atlas <search> — find places | fav [place] — favorite | recalls [on|off] | tie 1|2|lifestone\n" +
|
||||
"/rnav goto <coords> | preview <coords> | portals on|off | stop | here | load | test | navdata\n" +
|
||||
"/rnav portals scan [yd] | list | forget <name> | clear confirm — this server's own portals (a landing is learned the first time you take one)\n" +
|
||||
"/rnav portals learn | learn stop | learn range <yd> — try every portal in range by itself, learn each landing, come back, repeat\n" +
|
||||
"/rnav gems [list] | on | off | cost <yd> | forget <name> — portal/recall gems in your pack as route steps (a gem's landing is learned the first time you use one)\n" +
|
||||
"/rnav doors [on|off] | unlock on|off | drops <m>|off | forget — walks open doors (dungeons, towns, buildings), unlock with keys/lockpicks, drop down ledges\n" +
|
||||
"/rnav follow [on|off] — walks keep to the trip's path (the markers); off: plan to the route's crossings\n" +
|
||||
"/rnav avoid — show; avoid portals on|off|<m> | walls on|off|<m> | corners <m>\n" +
|
||||
"/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" +
|
||||
"/rnav mesh on|off | floor on|off | walls on|off | radius <m> | triangles <n> — draw the navmesh: green floor, red walls\n" +
|
||||
|
|
@ -1036,6 +1094,8 @@ public sealed partial class RynthNavPlugin
|
|||
// "go a || b || c" (Oracle's Dynamic Stamps, any caller): the first candidate on the map.
|
||||
if (cmd is "go" or "goto" or "route" or "arrow" && rest.Contains("||", StringComparison.Ordinal))
|
||||
{
|
||||
// Someone inside a dungeon (2026-11-11), when no earlier candidate is on the map: the way in.
|
||||
if (cmd is "go" or "goto" && TryGoInsideAlternative(rest)) return;
|
||||
if (!PickAlternative(rest, out string picked, out string why)) { Note(why); return; }
|
||||
rest = picked;
|
||||
}
|
||||
|
|
@ -1054,17 +1114,17 @@ public sealed partial class RynthNavPlugin
|
|||
case "navdata": Say($"tiles and Atlas folder: {NavDataDir} ({NavConfig.Source}); route graph: {_graphStatus}; Town Network: {_townNetStatus}"); break;
|
||||
case "avoid": CmdAvoid(rest); break;
|
||||
case "aphus": CmdAphus(rest.Trim().ToLowerInvariant()); break;
|
||||
case "portals":
|
||||
_portalsEnabled = !rest.Equals("off", StringComparison.OrdinalIgnoreCase);
|
||||
NavDataConfig.WriteSwitch("portals", _portalsEnabled);
|
||||
Say($"portal and recall routing {(_portalsEnabled ? "ON" : "OFF")} for walking (go/goto)");
|
||||
break;
|
||||
case "portals": CmdPortals(rest); break;
|
||||
case "gems": CmdGems(rest); break;
|
||||
case "doors": CmdDoors(rest); break;
|
||||
case "follow": CmdFollow(rest); break;
|
||||
case "stop": DoMove(5); Say("stopped"); break;
|
||||
case "goto":
|
||||
case "go":
|
||||
CmdGo(rest);
|
||||
break;
|
||||
case "route": CmdRoute(rest); break;
|
||||
case "inside": CmdInside(rest); break; // which of these is in this dungeon (RynthNavPlugin.Inside.cs)
|
||||
case "arrow": CmdArrow(rest); break;
|
||||
case "atlas": CmdAtlas(rest); break;
|
||||
case "fav": CmdFav(rest); break;
|
||||
|
|
@ -1113,7 +1173,7 @@ public sealed partial class RynthNavPlugin
|
|||
List<RouteStep>? steps = PlanAndShow(n, rns, rew, out int used, out double est, out string refusal);
|
||||
if (refusal.Length > 0) Note("arrow route: " + refusal);
|
||||
if (steps == null || used == 0) { SetArrow(n, t, rns, rew, announce: true); return; }
|
||||
_arrow.SetRoute(steps, n, t, rns, rew);
|
||||
_arrow.SetRoute(steps, n, t, rns, rew, s => TheHub(HubExitOf(s)));
|
||||
_store.Touch(new SavedPlace { Name = n, Type = t, Ns = rns, Ew = rew });
|
||||
_openArrowSeq++;
|
||||
Say($"arrow route to {n}: {used} teleport(s). First: {StepText(_arrow.Current!)}.");
|
||||
|
|
@ -1125,6 +1185,8 @@ public sealed partial class RynthNavPlugin
|
|||
|
||||
private void CmdGo(string rest)
|
||||
{
|
||||
// Someone inside a dungeon (2026-11-11), when the map has nothing better for the name: the way in.
|
||||
if (rest.Length > 0 && _store.FindFavorite(rest) == null && !NavCoords.TrySplitCoordsAndName(rest, out _, out _, out _) && TryGoInside(rest)) return;
|
||||
if (!ResolveGo(rest, out string name, out string type, out double ns, out double ew, out string enter, out string enterType, out string error))
|
||||
{
|
||||
Note(error);
|
||||
|
|
@ -1197,8 +1259,10 @@ public sealed partial class RynthNavPlugin
|
|||
{
|
||||
RouteStep s = steps[i];
|
||||
string act = s.UseRecall ? $"recall: {s.Label}"
|
||||
: s.IsHub ? $"in the Town Network, walk to the {s.Label} and take it to {NavCoords.Fmt(s.LandNs, s.LandEw)}"
|
||||
: s.UsePortal ? $"walk to {NavCoords.Fmt(s.Ns, s.Ew)}, take '{Trunc(s.Label)}'" : $"walk to {NavCoords.Fmt(s.Ns, s.Ew)}";
|
||||
: s.IsHub ? $"in {TheHub(HubExitOf(s))}, walk to the {s.Label} and take it to {HubExitDest(HubExitOf(s))}"
|
||||
: s.UsePortal ? $"walk to {NavCoords.Fmt(s.Ns, s.Ew)}, take '{Trunc(s.Label)}'" + (i + 1 < steps.Count && steps[i + 1].IsHub ? $" into {TheHub(HubExitOf(steps[i + 1]))}" : "")
|
||||
: $"walk to {NavCoords.Fmt(s.Ns, s.Ew)}";
|
||||
if (s.UseRecall && i + 1 < steps.Count && steps[i + 1].IsHub) act += $" (lands in {TheHub(HubExitOf(steps[i + 1]))})";
|
||||
Say($" {i + 1}. {act}");
|
||||
}
|
||||
}
|
||||
|
|
@ -1254,7 +1318,7 @@ public sealed partial class RynthNavPlugin
|
|||
var notes = new List<string>();
|
||||
List<RecallOption> list = CurrentRecalls(notes);
|
||||
Say(list.Count == 0 ? "no recall can be used for routes yet" : $"{list.Count} recall(s) for routes:");
|
||||
foreach (var o in list) Say($" {o.Name} → {NavCoords.Fmt(o.Ns, o.Ew)}{(o.SpellId == 0 ? " (" + o.Command + ")" : "")}");
|
||||
foreach (var o in list) Say($" {o.Name} → {o.Where}{(o.ToArrival >= 0 ? " (then out through its learned portals)" : "")}{(o.SpellId == 0 ? " (" + o.Command + ")" : "")}");
|
||||
foreach (string n in notes) Say(" " + n);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ namespace RynthCore.Plugin.RynthNav;
|
|||
public sealed partial class RynthNavPlugin : RynthPluginBase
|
||||
{
|
||||
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthNav");
|
||||
internal const string PluginVersion = "0.6.8"; // 0.6.8: the route maker (makeroute, makeloop, makepath, routeinfo, "RynthNav.Routes")
|
||||
internal const string PluginVersion = "0.6.14"; // upstream 0.6.8 (the route maker: makeroute, makeloop, makepath, routeinfo, "RynthNav.Routes") merged into the test branch's 0.6.13
|
||||
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginVersion);
|
||||
|
||||
/// <summary>Lets PluginExports log through this plugin's host (the base Log is protected).</summary>
|
||||
|
|
@ -144,6 +144,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// The panel's switches survive reloads and relogs (rynthnav.json, next to navDataDir).
|
||||
_portalsEnabled = NavDataConfig.ReadSwitch("portals", false);
|
||||
_recallsEnabled = NavDataConfig.ReadSwitch("recalls", true);
|
||||
InitLearn();
|
||||
InitGems();
|
||||
InitDoors();
|
||||
LoadAvoidSettings();
|
||||
LoadMarkerSettings();
|
||||
LoadMeshSettings();
|
||||
|
|
@ -381,6 +384,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
if (cancel)
|
||||
{
|
||||
if (_gotoActive) _goNote = "stopped"; // the panel's status line (the d-pad and Stop say nothing in chat)
|
||||
StopLearn("stopped"); // Stop, or any movement key, ends learning portals too
|
||||
_gotoActive = false; _route = null; _portalWait = false; if (_recallWait) EndRecall();
|
||||
ResetHub();
|
||||
HideMarkers("cancelled");
|
||||
|
|
@ -491,9 +495,11 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// legs; otherwise StepGoto just navmesh-walks straight to the final target.
|
||||
// Inside the Town Network there is no navmesh: the way on is one of its exits.
|
||||
ResetHub();
|
||||
bool inHub = _townNet?.Contains(CurrentLandblock) == true;
|
||||
// In a dungeon RynthNav learned (custom portals) the plan itself weighs its walks to each of
|
||||
// its portals (and on through other learned dungeons) against your recalls (PlanRoute).
|
||||
bool inTownNet = _baseTownNet?.Contains(CurrentLandblock) == true;
|
||||
int portalsUsed; double est; List<RecallOption> recalls;
|
||||
if (inHub)
|
||||
if (inTownNet)
|
||||
{
|
||||
recalls = new List<RecallOption>();
|
||||
_route = PlanFromInsideHub(tns, tew, out est, out portalsUsed);
|
||||
|
|
@ -513,7 +519,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
_route = null;
|
||||
return;
|
||||
}
|
||||
_route = plan.Steps; portalsUsed = plan.Teleports; est = plan.Est;
|
||||
else { _route = plan.Steps; portalsUsed = plan.Teleports; est = plan.Est; }
|
||||
}
|
||||
_routeRecalls = recalls;
|
||||
|
||||
|
|
@ -525,7 +531,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
_shownRoute = _route ?? new List<RouteStep> { new(tns, tew, false, false, "walk") };
|
||||
_shownRouteFor = name; _shownRouteEst = est; _shownRouteLive = true; _routeVersion++;
|
||||
SetSubGoalToCurrentLeg();
|
||||
if (_route != null && portalsUsed > 0) _arrow.SetRoute(_route, name, type, tns, tew);
|
||||
if (_route != null && portalsUsed > 0) _arrow.SetRoute(_route, name, type, tns, tew, s => TheHub(HubExitOf(s)));
|
||||
else _arrow.SetTarget(name, type, tns, tew);
|
||||
_openArrowSeq++;
|
||||
|
||||
|
|
@ -721,6 +727,22 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
FinishGoto($"stopped: no progress for 30 s, {toGoal:F0}u short ({why})");
|
||||
return;
|
||||
}
|
||||
// A closed door across the path ahead, or one we ran into: open it, unlock it, or go round it
|
||||
// (RynthNavPlugin.Doors.cs; until 2026-11-01 only the dungeon walks opened doors).
|
||||
switch (GotoDoor(NowMs, out string doorWhy))
|
||||
{
|
||||
case DoorAct.Busy:
|
||||
AutoRun.Halt();
|
||||
return;
|
||||
case DoorAct.Blocked:
|
||||
// A locked door in a wall this character jumps: over it (2026-11-07); else round it.
|
||||
if (TryJumpLockedDoor()) return;
|
||||
Host.Log($"[RynthNav] walk: {doorWhy}; planning again round it");
|
||||
lock (_gotoGate) _gotoPath = null;
|
||||
_replanTick = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
// Running into something (RynthNavPlugin.Blocked.cs): turn away, plan again, or stop and say where.
|
||||
if (StepBlocked()) return;
|
||||
|
||||
|
|
@ -760,11 +782,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// goal for a moment, which carries us over a seam, then stand and keep re-planning.
|
||||
// Before, autorun stayed on with the old heading and nothing steering: the bot
|
||||
// ran off in a straight line, or (no plan at all) stood forcing autorun off.
|
||||
if (_blindTicks < BlindPushTicks)
|
||||
// Following a trip's path (TripFollow: the aim is on the walk the markers draw), it keeps
|
||||
// pushing along it (or the route graph's next crossing) rather than standing (2026-11-07: it stood 25 s against a wall at Yaraq
|
||||
// until the progress watchdog stopped the goto): running into something there is what the
|
||||
// stuck watch, the jumps and the stepping round are for.
|
||||
if (_blindTicks < BlindPushTicks || _aimOnTrip || _coarse != null)
|
||||
{
|
||||
_blindTicks++;
|
||||
// Straight at the goal, or along the route at its next crossing.
|
||||
double bh = (_coarse != null ? Math.Atan2(_aimEw - _wx, _aimNs - _wy) : Math.Atan2(fdew, fdns)) * 180.0 / Math.PI;
|
||||
double bh = (_coarse != null || _aimOnTrip ? Math.Atan2(_aimEw - _wx, _aimNs - _wy) : Math.Atan2(fdew, fdns)) * 180.0 / Math.PI;
|
||||
bh = SteerRoundPortals(bh < 0 ? bh + 360.0 : bh, 10.0);
|
||||
WalkDrive(bh);
|
||||
if (_blindTicks % 10 == 0) lock (_gotoGate) _gotoPath = null; // re-plan soon
|
||||
|
|
@ -854,7 +880,8 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
lock (_gate) _status = status;
|
||||
_gotoEndStatus = status; _gotoEndSeq++; // a route maker go job reads how it ended (RynthNavPlugin.RouteMaker.cs)
|
||||
Host.Log($"[RynthNav] goto: {status}");
|
||||
Say(status == "arrived" && _gotoName.Length > 0 ? $"goto: arrived at {_gotoName}" : $"goto: {status}");
|
||||
string inside = TakeInsideTail(status); // a target inside a dungeon: where in it (RynthNavPlugin.Inside.cs)
|
||||
Say((status == "arrived" && _gotoName.Length > 0 ? $"goto: arrived at {_gotoName}" : $"goto: {status}") + inside);
|
||||
_goNote = status == "arrived" && _gotoName.Length > 0 ? $"arrived at {_gotoName}" : status;
|
||||
_enterName = ""; _enterType = "";
|
||||
HideMarkers(status == "arrived" ? "arrived" : "the goto ended");
|
||||
|
|
@ -957,15 +984,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
/// </summary>
|
||||
private TravelPlan.Result PlanRoute(string name, double goalNs, double goalEw, out List<RecallOption> recalls, bool? portals = null)
|
||||
{
|
||||
bool portalsOn = portals ?? _portalsEnabled;
|
||||
bool portalsOn = portals ?? PortalsRouting; // the switch, or learning portals (RynthNavPlugin.LearnPortals.cs)
|
||||
double startNs = NavCoords.NsFromWorld(_wy), startEw = NavCoords.EwFromWorld(_wx);
|
||||
bool startOnMap = IsOnMap(_cellId);
|
||||
var recallNotes = new List<string>();
|
||||
recalls = _charKey.Length == 0 ? new List<RecallOption>() : RecallPlanner.Build(_atlas, _known, _memory, _charKey, recallNotes);
|
||||
recalls = _charKey.Length == 0 ? new List<RecallOption>() : RecallsRouting ? AllRecalls(_atlas, recallNotes) : RecallPlanner.Build(_atlas, _known, _memory, _charKey, recallNotes);
|
||||
if (_charKey.Length == 0) recallNotes.Add("not logged in yet");
|
||||
var hubNotes = new List<string>();
|
||||
HubLinks? hub = portalsOn ? CurrentHubLinks(hubNotes) : null;
|
||||
if (hub != null && _preferAphus && _recallsEnabled) hub = ViaAphus(hub, recalls, hubNotes);
|
||||
if (hub != null && _preferAphus && RecallsRouting) hub = ViaAphus(hub, recalls, hubNotes, _baseTownNet?.Arrivals.Count ?? 0);
|
||||
if (portalsOn) EnsurePortalsLoaded();
|
||||
// Walks that can't be done over land (another landmass) are left out, so an island or the
|
||||
// far side of water is only reached by a portal, a recall or the Town Network.
|
||||
|
|
@ -975,10 +1002,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
NavGraph.LandblockAt(NavCoords.WorldX(bew), NavCoords.WorldY(bns))) != false;
|
||||
bool? land = startOnMap && g != null ? g.SameLand(CurrentLandblock, NavGraph.LandblockAt(NavCoords.WorldX(goalEw), NavCoords.WorldY(goalNs))) : null;
|
||||
|
||||
TravelPlan.Result r = TravelPlan.Plan(portalsOn ? _portals : null, RecallPlanner.Links(recalls), hub,
|
||||
portalsOn, _recallsEnabled, startOnMap, startNs, startEw, goalNs, goalEw, canWalk, land, name);
|
||||
List<PortalLink>? routePortals = portalsOn ? RoutePortals() : null;
|
||||
// Standing in a dungeon RynthNav learned walks in: the walk from here to each of its portals.
|
||||
int walkable = 0;
|
||||
double[]? startWalks = !startOnMap && hub != null ? StartHubWalks(hub, out walkable) : null;
|
||||
if (startWalks != null) Host.Log($"[RynthNav] plan: in a learned dungeon (0x{CurrentLandblock:X4}): {walkable} of its portal(s) reachable by a learned walk from here");
|
||||
TravelPlan.Result r = TravelPlan.Plan(routePortals, RecallPlanner.Links(recalls), hub,
|
||||
portalsOn, RecallsRouting, startOnMap, startNs, startEw, goalNs, goalEw, canWalk, land, name, startWalks);
|
||||
|
||||
Host.Log($"[RynthNav] plan {name}: {r.Basis}; {(portalsOn ? $"{_portals?.Count ?? 0} portals" : "no portals")}, "
|
||||
Host.Log($"[RynthNav] plan {name}: {r.Basis}; {(portalsOn ? $"{routePortals?.Count ?? 0} portals ({(routePortals?.Count ?? 0) - (_portals?.Count ?? 0)} custom for {(_server.Length > 0 ? _server : "?")})" : "no portals")}, "
|
||||
+ $"{recalls.Count} recall(s) ready" + (recalls.Count > 0 ? " (" + string.Join(", ", recalls.ConvertAll(o => o.Name)) + ")" : "")
|
||||
+ $", Town Network {(hub == null ? (portalsOn ? "not loaded" : "unused") : $"{hub.Entries.Count} entries / {hub.Exits.Count} exits")}"
|
||||
+ $", land check {(canWalk == null ? "off (no route graph)" : "on")}"
|
||||
|
|
@ -1017,11 +1049,31 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
var steer = CoarseSteer(sRef, sPt, ref loadedMore);
|
||||
if (loadedMore) _query = new DtNavMeshQuery(_navMesh!);
|
||||
|
||||
// The trip's own path (TripFollow.cs, 2026-11-01): when this step has one, plan a few metres
|
||||
// along it rather than to the route graph's next crossing, so the walk keeps to the path the
|
||||
// markers show instead of finding its own way round.
|
||||
bool onTrip = false;
|
||||
if (CurrentFollow() is TripFollow follow)
|
||||
{
|
||||
var (fx, fy) = follow.Aim(_wx, _wy, out double off, out bool nearEnd);
|
||||
if (!nearEnd)
|
||||
{
|
||||
steer = ((float)fx, (float)_wz, (float)fy);
|
||||
onTrip = true;
|
||||
if (off > TripFollow.OffPathUnits && !_offTripSaid)
|
||||
{
|
||||
_offTripSaid = true;
|
||||
Host.Log($"[RynthNav] walk: {off:F0}u off the trip's path at {NavCoords.Fmt(NavCoords.NsFromWorld(_wy), NavCoords.EwFromWorld(_wx))}: heading back to it");
|
||||
}
|
||||
else if (off <= TripFollow.OffPathUnits) _offTripSaid = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Prefer a DIRECT path to the actual target when its tile is loaded — one stable
|
||||
// corridor we follow steadily. Only fall back to the 500u line-probe leapfrog when
|
||||
// the target is too far to be loaded yet (that probe jitters and must stay a last resort).
|
||||
double aimEw = steer?.Ew ?? _gotoTew, aimNs = steer?.Ns ?? _gotoTns;
|
||||
_aimEw = aimEw; _aimNs = aimNs;
|
||||
_aimEw = aimEw; _aimNs = aimNs; _aimOnTrip = onTrip;
|
||||
// The route's last stretch ends on the ground its search ended on: the spot itself, or the
|
||||
// nearest ground a walk can end on when the spot is fenced in (NavCoarse.ProbeReachable).
|
||||
// Planned to the spot itself, the nearest polygon is the fenced-in one again.
|
||||
|
|
@ -1034,7 +1086,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// (AllowB below). Through the avoid filter, a big open-ground polygon that also reaches
|
||||
// another portal's circle hid the goal: 10-02 16:05, Lucy at the Lady Maila Estates Portal
|
||||
// in a cluster of housing portals: "no tile ahead", 74u short, on the collision-built tiles.
|
||||
_query.FindNearestPoly(targetP, steer != null ? new RcVec3f(8, 32, 8) : new RcVec3f(12, 256, 12), filter, out long gRef, out RcVec3f gPt, out _);
|
||||
_query.FindNearestPoly(targetP, steer != null ? new RcVec3f(8, onTrip ? 64 : 32, 8) : new RcVec3f(12, 256, 12), filter, out long gRef, out RcVec3f gPt, out _);
|
||||
bool direct = gRef != 0 && steer == null;
|
||||
if (gRef == 0) gRef = FindGoalToward(aimEw, aimNs, out gPt);
|
||||
if (gRef == 0) { lock (_gate) _status = "no tile ahead — bake the route"; lock (_gotoGate) _gotoPath = null; return; }
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@ internal sealed class TownNetPoint
|
|||
{
|
||||
public uint Cell;
|
||||
public double X, Y, Z;
|
||||
/// <summary>The edge of a drop (2026-10-30): walk on off it; the next point is where you land, lower down.</summary>
|
||||
public bool Drop;
|
||||
}
|
||||
|
||||
internal sealed class TownNetArrival
|
||||
|
|
@ -67,6 +69,8 @@ internal sealed class TownNetEntry
|
|||
public double Ns, Ew;
|
||||
public int Arrival = -1;
|
||||
public readonly TownNetRules Rules = new();
|
||||
/// <summary>A portal into a dungeon RynthNav learned (custom portals), not townnet.json's.</summary>
|
||||
public bool Learned;
|
||||
}
|
||||
|
||||
internal sealed class TownNetExit
|
||||
|
|
@ -78,6 +82,12 @@ internal sealed class TownNetExit
|
|||
public double DestNs, DestEw;
|
||||
public uint DestCell;
|
||||
public readonly TownNetRules Rules = new();
|
||||
/// <summary>Lands at this arrival of the same (merged) network: a learned dungeon's portal into another learned dungeon. -1 = none.</summary>
|
||||
public int DestArrival = -1;
|
||||
/// <summary>The hub it stands in, for what RynthNav says: "Town Network", or a learned dungeon's name.</summary>
|
||||
public string Hub = "Town Network";
|
||||
/// <summary>A learned dungeon's portal (custom portals), not townnet.json's.</summary>
|
||||
public bool Learned;
|
||||
|
||||
/// <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;
|
||||
|
|
@ -91,6 +101,34 @@ internal sealed class TownNetWalk
|
|||
/// <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>();
|
||||
/// <summary>Worked out from the dats (RynthAi's dungeon pathfinder), not walked yet: walking it and taking the portal makes it a learned walk.</summary>
|
||||
public bool Planned;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A walk inside dungeon <c>landblock</c> between two landblock-local points (x, y, z), as x,y,z
|
||||
/// triples from the first to the second, or null when there is none (RynthAi's dungeon pathfinder).
|
||||
/// </summary>
|
||||
internal delegate DungeonWay? DungeonPather(uint landblock, double ax, double ay, double az, double bx, double by, double bz);
|
||||
|
||||
/// <summary>A walk from RynthAi's dungeon pathfinder: x,y,z triples (landblock-local), and which points are the edge of a drop.</summary>
|
||||
internal sealed class DungeonWay
|
||||
{
|
||||
public readonly double[] Points;
|
||||
/// <summary>Per point: the edge of a drop (the next point is the landing). Null: none.</summary>
|
||||
public readonly bool[]? Drops;
|
||||
public DungeonWay(double[] points, bool[]? drops = null) { Points = points; Drops = drops; }
|
||||
public int Count => Points.Length / 3;
|
||||
public bool HasDrop => Drops != null && Array.IndexOf(Drops, true) >= 0;
|
||||
|
||||
/// <summary>The walk as walker points in <paramref name="cell"/>.</summary>
|
||||
public TownNetPoint[] ToPoints(uint cell)
|
||||
{
|
||||
var tp = new TownNetPoint[Count];
|
||||
for (int i = 0; i < tp.Length; i++)
|
||||
tp[i] = new TownNetPoint { Cell = cell, X = Points[i * 3], Y = Points[i * 3 + 1], Z = Points[i * 3 + 2], Drop = Drops != null && Drops[i] };
|
||||
return tp;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class TownNet
|
||||
|
|
@ -258,7 +296,7 @@ internal sealed class TownNet
|
|||
for (int x = 0; x < Exits.Count; x++)
|
||||
{
|
||||
TownNetExit ex = Exits[x];
|
||||
if (!ex.DestOnMap) continue;
|
||||
if (!ex.DestOnMap && ex.DestArrival < 0) 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];
|
||||
|
|
@ -270,11 +308,239 @@ internal sealed class TownNet
|
|||
any |= w != null;
|
||||
}
|
||||
if (!any) continue;
|
||||
hub.Exits.Add(new HubExit(ex.DestNs, ex.DestEw, ex.Name, x, walk));
|
||||
hub.Exits.Add(ex.DestOnMap ? new HubExit(ex.DestNs, ex.DestEw, ex.Name, x, walk)
|
||||
: new HubExit(double.NaN, double.NaN, ex.Name, x, walk, ex.DestArrival));
|
||||
}
|
||||
return hub;
|
||||
}
|
||||
|
||||
// ── Learned dungeons (custom portals) ────────────────────────────────────
|
||||
|
||||
/// <summary>A landing within this of a learned arrival (and the height check) is that arrival.</summary>
|
||||
public const double LearnedArrivalUnits = 5.0;
|
||||
public const double LearnedArrivalHeight = 3.0;
|
||||
|
||||
/// <summary>Adds a walk; one already kept for the same arrival and exit stays if it is no longer.</summary>
|
||||
internal void AddWalk(TownNetWalk w)
|
||||
{
|
||||
if (_walk.TryGetValue((w.Arrival, w.Exit), out TownNetWalk? old))
|
||||
{
|
||||
if (old.Length <= w.Length) return;
|
||||
Walks.Remove(old);
|
||||
}
|
||||
Walks.Add(w);
|
||||
_walk[(w.Arrival, w.Exit)] = w;
|
||||
}
|
||||
|
||||
/// <summary>The learned arrivals (index from <paramref name="first"/> on) in that landblock.</summary>
|
||||
public int LearnedArrival(int first, uint landblock, double x, double y, double z)
|
||||
{
|
||||
for (int i = first; i < Arrivals.Count; i++)
|
||||
{
|
||||
TownNetArrival a = Arrivals[i];
|
||||
if ((a.Cell >> 16) != landblock) continue;
|
||||
if (Math.Sqrt((a.X - x) * (a.X - x) + (a.Y - y) * (a.Y - y)) <= LearnedArrivalUnits && Math.Abs(a.Z - z) <= LearnedArrivalHeight) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>A learned arrival (index from <paramref name="first"/> on) in exactly that cell, or -1.</summary>
|
||||
public int LearnedArrivalByCell(int first, uint cell)
|
||||
{
|
||||
for (int i = first; i < Arrivals.Count; i++) if (Arrivals[i].Cell == cell) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Town Network (townnet.json, may be null) with this server's learned dungeons added as more of
|
||||
/// the same hub: each walk recorded inside a dungeon gives an arrival (where it began) and an exit
|
||||
/// (the portal it ended at, with its landing), each map portal that lands at a learned arrival is an
|
||||
/// entry, and a learned exit that lands at another learned arrival chains into it. Exits keep
|
||||
/// townnet.json's numbers; learned ones follow. A landblock townnet.json has is never learned over.
|
||||
/// With the Atlas, its map portals into a learned dungeon (the world data's own, landing in the
|
||||
/// cell a learned walk starts in) are entries too. The result is read-only once returned.
|
||||
/// </summary>
|
||||
/// <param name="pather">
|
||||
/// The dungeon pathfinder (RynthAi's, from the dats). With it every learned arrival gets a planned
|
||||
/// walk to each portal of its dungeon whose landing is known and that nobody walked to from there
|
||||
/// (TownNetWalk.Planned, its length counted 15% longer), map portals landing where nobody walked
|
||||
/// from yet become entries, and portals with a known landing that nobody walked to become exits.
|
||||
/// </param>
|
||||
public static TownNet Merge(TownNet? baseNet, CustomPortalStore store, string server, Atlas? atlas = null, DungeonPather? pather = null)
|
||||
{
|
||||
var t = new TownNet { Version = SupportedVersion };
|
||||
if (baseNet != null)
|
||||
{
|
||||
t.Version = baseNet.Version; t.SetId = baseNet.SetId; t.Generated = baseNet.Generated;
|
||||
t.Landblocks.UnionWith(baseNet.Landblocks);
|
||||
t.Arrivals.AddRange(baseNet.Arrivals);
|
||||
t.Entries.AddRange(baseNet.Entries);
|
||||
t.Exits.AddRange(baseNet.Exits);
|
||||
foreach (TownNetWalk w in baseNet.Walks) t.AddWalk(w);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(server)) return t;
|
||||
var baseLbs = new HashSet<uint>(t.Landblocks);
|
||||
int firstArrival = t.Arrivals.Count;
|
||||
IReadOnlyList<CustomPortal> portals = store.For(server);
|
||||
|
||||
// A dungeon's name: the first map portal learned to lead into it.
|
||||
var hubName = new Dictionary<uint, string>();
|
||||
if (atlas != null) // the world data's name for the dungeon first ("Abandoned Mine")
|
||||
foreach (AtlasLocation l in atlas.Locations)
|
||||
if (l.Type.Equals("Dungeon", StringComparison.Ordinal) && uint.TryParse(l.Lb, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint dlb))
|
||||
hubName.TryAdd(dlb, l.Name);
|
||||
foreach (CustomPortal p in portals)
|
||||
if (p.OnMap && p.DestKnown && !p.DestOnMap && p.DestCell != 0) hubName.TryAdd(p.DestLandblock, p.Name);
|
||||
foreach (CustomPortal p in portals) // a dungeon only reached from another: named by the portal into it ("AC Storage")
|
||||
if (!p.OnMap && p.DestKnown && !p.DestOnMap && p.DestCell != 0) hubName.TryAdd(p.DestLandblock, PlaceOfPortal(p.Name));
|
||||
string HubOf(uint lb) => hubName.TryGetValue(lb, out string? n) ? n : $"dungeon {lb:X4}";
|
||||
|
||||
var walkedLbs = new HashSet<uint>();
|
||||
foreach (DungeonWalk w in store.WalksFor(server)) walkedLbs.Add(w.Landblock);
|
||||
bool LearnedDungeon(uint lb) => !baseLbs.Contains(lb) && (walkedLbs.Contains(lb) || pather != null);
|
||||
|
||||
int ArrivalAt(uint cell, double x, double y, double z)
|
||||
{
|
||||
int a = t.LearnedArrival(firstArrival, cell >> 16, x, y, z);
|
||||
if (a >= 0) return a;
|
||||
t.Arrivals.Add(new TownNetArrival
|
||||
{
|
||||
Id = string.Create(CultureInfo.InvariantCulture, $"{cell >> 16:X4}@{x:0.#},{y:0.#}"),
|
||||
Cell = cell, X = x, Y = y, Z = z,
|
||||
});
|
||||
t.Landblocks.Add(cell >> 16);
|
||||
return t.Arrivals.Count - 1;
|
||||
}
|
||||
|
||||
var exitOf = new Dictionary<CustomPortal, int>();
|
||||
int ExitFor(CustomPortal p)
|
||||
{
|
||||
if (exitOf.TryGetValue(p, out int x)) return x;
|
||||
var ex = new TownNetExit
|
||||
{
|
||||
Guid = string.Create(CultureInfo.InvariantCulture, $"learned:{p.Cell:X8}:{p.X:0.#},{p.Y:0.#}"),
|
||||
Name = p.Name, Cell = p.Cell, X = p.X, Y = p.Y, Z = p.Z,
|
||||
DestOnMap = p.DestOnMap, DestNs = p.DestNs, DestEw = p.DestEw, DestCell = p.DestCell,
|
||||
Hub = HubOf(p.Landblock), Learned = true,
|
||||
};
|
||||
t.Exits.Add(ex);
|
||||
x = t.Exits.Count - 1;
|
||||
exitOf[p] = x;
|
||||
return x;
|
||||
}
|
||||
foreach (DungeonWalk w in store.WalksFor(server))
|
||||
{
|
||||
if (baseLbs.Contains(w.Landblock) || w.Count < 2) continue;
|
||||
CustomPortal? p = store.FindInDungeon(server, w.ExitName, w.ExitCell, w.ExitX, w.ExitY, w.ExitZ);
|
||||
if (p == null || !p.DestKnown) continue; // forgotten, or its landing isn't known
|
||||
int x = ExitFor(p);
|
||||
int a = ArrivalAt(w.ArrivalCell != 0 ? w.ArrivalCell : (w.Landblock << 16) | 0x100, w.ArrivalX, w.ArrivalY, w.ArrivalZ);
|
||||
uint cell = t.Arrivals[a].Cell;
|
||||
var pts = new TownNetPoint[w.Count];
|
||||
for (int i = 0; i < w.Count; i++)
|
||||
{
|
||||
var (px, py, pz) = w[i];
|
||||
pts[i] = new TownNetPoint { Cell = cell, X = px, Y = py, Z = pz };
|
||||
}
|
||||
t.AddWalk(new TownNetWalk { Arrival = a, Exit = x, Points = pts, Length = PathLength(pts, 0) });
|
||||
}
|
||||
|
||||
// Map portals into a learned dungeon: entries at the arrival they land on.
|
||||
foreach (CustomPortal p in portals)
|
||||
{
|
||||
if (!p.OnMap || !p.DestKnown || p.DestOnMap || !p.DestHasPos || baseLbs.Contains(p.DestLandblock)) continue;
|
||||
int a = t.LearnedArrival(firstArrival, p.DestLandblock, p.DestX, p.DestY, p.DestZ);
|
||||
if (a < 0 && pather != null && LearnedDungeon(p.DestLandblock)) a = ArrivalAt(p.DestCell, p.DestX, p.DestY, p.DestZ);
|
||||
if (a < 0) continue; // nothing walked from where it lands yet (and no way to plan one)
|
||||
t.Entries.Add(new TownNetEntry
|
||||
{
|
||||
Guid = string.Create(CultureInfo.InvariantCulture, $"learned:{p.Cell:X8}:{p.Ns:0.##},{p.Ew:0.##}"),
|
||||
Name = p.Name, Place = HubOf(p.DestLandblock), OnMap = true, Ns = p.Ns, Ew = p.Ew, Arrival = a, Learned = true,
|
||||
});
|
||||
}
|
||||
|
||||
// The world data's map portals into a learned dungeon (the Atlas: dest cell = a learned arrival's cell).
|
||||
if (atlas != null)
|
||||
foreach (AtlasLocation l in atlas.Locations)
|
||||
{
|
||||
if (!l.OnMap || !l.HasDest || l.DestOnMap || l.Closed || l.Quest || !l.Type.Equals("Portal", StringComparison.Ordinal)) continue;
|
||||
if (!uint.TryParse(l.DestCell, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint dc) || baseLbs.Contains(dc >> 16)) continue;
|
||||
int a = t.LearnedArrivalByCell(firstArrival, dc);
|
||||
if (a < 0) continue;
|
||||
bool dup = false;
|
||||
foreach (TownNetEntry en in t.Entries)
|
||||
if (en.Learned && en.Arrival == a && NavCoords.Distance(en.Ns, en.Ew, l.Ns, l.Ew) < 2.0) { dup = true; break; }
|
||||
if (dup) continue;
|
||||
var entry = new TownNetEntry
|
||||
{
|
||||
Guid = string.Create(CultureInfo.InvariantCulture, $"atlas:{l.Id}"),
|
||||
Name = l.Name, Place = l.DestName.Length > 0 ? l.DestName : HubOf(dc >> 16), OnMap = true, Ns = l.Ns, Ew = l.Ew, Arrival = a, Learned = true,
|
||||
};
|
||||
entry.Rules.MinLevel = l.MinLevel; entry.Rules.MaxLevel = l.MaxLevel;
|
||||
t.Entries.Add(entry);
|
||||
hubName.TryAdd(dc >> 16, l.DestName.Length > 0 ? l.DestName : l.Name);
|
||||
}
|
||||
|
||||
// A learned exit into another learned dungeon: lands at that arrival (a chain).
|
||||
foreach (var (p, x) in new List<KeyValuePair<CustomPortal, int>>(exitOf))
|
||||
if (!p.DestOnMap && p.DestHasPos)
|
||||
{
|
||||
int a = t.LearnedArrival(firstArrival, p.DestLandblock, p.DestX, p.DestY, p.DestZ);
|
||||
if (a < 0 && pather != null && LearnedDungeon(p.DestLandblock)) a = ArrivalAt(p.DestCell, p.DestX, p.DestY, p.DestZ);
|
||||
t.Exits[x].DestArrival = a;
|
||||
}
|
||||
|
||||
// The dats fill the gaps: a planned walk from each learned arrival to each portal of its
|
||||
// dungeon (with a known landing) that nobody walked to from there.
|
||||
if (pather != null)
|
||||
{
|
||||
foreach (CustomPortal p in portals)
|
||||
if (!p.OnMap && p.DestKnown && !baseLbs.Contains(p.Landblock) && LearnedDungeon(p.Landblock)) ExitFor(p);
|
||||
for (int x = 0; x < t.Exits.Count; x++)
|
||||
if (t.Exits[x].Learned && !t.Exits[x].DestOnMap && t.Exits[x].DestArrival < 0)
|
||||
foreach (CustomPortal p in portals)
|
||||
if (exitOf.TryGetValue(p, out int px) && px == x && p.DestHasPos && LearnedDungeon(p.DestLandblock))
|
||||
t.Exits[x].DestArrival = ArrivalAt(p.DestCell, p.DestX, p.DestY, p.DestZ);
|
||||
for (int a = firstArrival; a < t.Arrivals.Count; a++)
|
||||
{
|
||||
TownNetArrival ar = t.Arrivals[a];
|
||||
uint lb = ar.Cell >> 16;
|
||||
for (int x = 0; x < t.Exits.Count; x++)
|
||||
{
|
||||
TownNetExit ex = t.Exits[x];
|
||||
if (!ex.Learned || (ex.Cell >> 16) != lb || t.Walk(a, x) != null) continue;
|
||||
DungeonWay? dw = pather(lb, ar.X, ar.Y, ar.Z, ex.X, ex.Y, ex.Z);
|
||||
if (dw == null || dw.Count < 2) continue;
|
||||
TownNetPoint[] tp = dw.ToPoints(ar.Cell);
|
||||
t.AddWalk(new TownNetWalk { Arrival = a, Exit = x, Points = tp, Length = PathLength(tp, 0) * 1.15, Planned = true });
|
||||
}
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/// <summary>How many entries, exits and walks were learned (not townnet.json's).</summary>
|
||||
/// <summary>"AC Storage" for the AC Storage Portal, "Lighthouse" for the Portal to Lighthouse.</summary>
|
||||
public static string PlaceOfPortal(string name)
|
||||
{
|
||||
string s = (name ?? "").Trim();
|
||||
if (s.StartsWith("Portal to ", StringComparison.OrdinalIgnoreCase)) s = s.Substring(10);
|
||||
if (s.EndsWith(" Portal", StringComparison.OrdinalIgnoreCase)) s = s.Substring(0, s.Length - 7);
|
||||
return s.Length > 0 ? s : name ?? "";
|
||||
}
|
||||
|
||||
/// <summary>How many walks were planned from the dats (not walked yet).</summary>
|
||||
public int PlannedWalks() { int n = 0; foreach (TownNetWalk w in Walks) if (w.Planned) n++; return n; }
|
||||
|
||||
public (int Entries, int Exits, int Walks) LearnedCounts()
|
||||
{
|
||||
int e = 0, x = 0, w = 0;
|
||||
foreach (TownNetEntry en in Entries) if (en.Learned) e++;
|
||||
foreach (TownNetExit ex in Exits) if (ex.Learned) x++;
|
||||
foreach (TownNetWalk wk in Walks) if (wk.Exit >= 0 && wk.Exit < Exits.Count && Exits[wk.Exit].Learned) w++;
|
||||
return (e, x, w);
|
||||
}
|
||||
|
||||
// ── The walker's view (landblock coordinates inside the network) ─────────
|
||||
|
||||
/// <summary>The arrival within <see cref="ArrivalNearUnits"/> of (x, y), or -1.</summary>
|
||||
|
|
@ -400,8 +666,17 @@ internal sealed class HubWalker
|
|||
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;
|
||||
/// <summary>No progress this long: jump (still running), over a lip, a step or a railing (2026-10-30).</summary>
|
||||
public const long JumpAfterMs = 2000;
|
||||
/// <summary>Jumps per stuck spot before StuckMs gives up.</summary>
|
||||
public const int MaxJumps = 2;
|
||||
/// <summary>On a walk over more than one level, a point counts as reached only within this height of it.</summary>
|
||||
public const double LevelUnits = 3.0;
|
||||
/// <summary>The walk's points span more than this in height: a walk over levels (ramps, stairs, drops).</summary>
|
||||
public const double LevelSpanUnits = 2.5;
|
||||
|
||||
public enum Act { Run, Hold, Stop, NoTeleport }
|
||||
/// <summary>Run = run with the heading; Jump = run with it and jump now; Hold = stand; Stop; NoTeleport.</summary>
|
||||
public enum Act { Run, Hold, Stop, NoTeleport, Jump }
|
||||
|
||||
private readonly List<TownNetPoint> _way;
|
||||
private readonly long _landMs;
|
||||
|
|
@ -410,9 +685,17 @@ internal sealed class HubWalker
|
|||
private long _bestMs, _atPortalMs;
|
||||
private bool _retried, _backing;
|
||||
private readonly double[] _radius; // per waypoint: how close counts as reached (sharper turn, closer)
|
||||
private readonly bool _levels; // the walk goes over more than one level: heights count
|
||||
private int _jumps; // jumps at this stuck spot
|
||||
private long _jumpMs;
|
||||
|
||||
/// <summary>The walk goes up or down levels (its points span more than LevelSpanUnits in height).</summary>
|
||||
public bool Levels => _levels;
|
||||
/// <summary>Jumps so far on this walk (the log).</summary>
|
||||
public int JumpsTotal { get; private set; }
|
||||
|
||||
public double Length { get; }
|
||||
public long LimitMs { get; }
|
||||
public long LimitMs { get; private set; }
|
||||
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; }
|
||||
|
|
@ -443,6 +726,21 @@ internal sealed class HubWalker
|
|||
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;
|
||||
double zMin = double.MaxValue, zMax = double.MinValue;
|
||||
foreach (TownNetPoint p in way) { zMin = Math.Min(zMin, p.Z); zMax = Math.Max(zMax, p.Z); }
|
||||
_levels = zMax - zMin > LevelSpanUnits;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Point <paramref name="i"/> reached in height: always on a one-level walk or with no height;
|
||||
/// otherwise within LevelUnits of it, or below the edge of a drop (falling off it).
|
||||
/// </summary>
|
||||
private bool LevelOk(int i, double z)
|
||||
{
|
||||
if (!_levels || double.IsNaN(z)) return true;
|
||||
TownNetPoint p = _way[i];
|
||||
if (p.Drop && z < p.Z + LevelUnits) return true;
|
||||
return Math.Abs(z - p.Z) < LevelUnits;
|
||||
}
|
||||
|
||||
/// <summary>Metres left to the exit's centre from (x, y).</summary>
|
||||
|
|
@ -458,9 +756,24 @@ internal sealed class HubWalker
|
|||
/// 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 void Pause(long now) { _bestMs = now; _best = double.MaxValue; _jumps = 0; }
|
||||
|
||||
public Act Step(double x, double y, long now, out double heading, out string why)
|
||||
/// <summary>A hold through no fault of the walk (a door opening): the stuck clock and the time limit wait too.</summary>
|
||||
public void Hold(long now, long heldMs) { Pause(now); LimitMs += heldMs; }
|
||||
|
||||
/// <summary>The points still ahead, from the one being walked to (index, point).</summary>
|
||||
public IEnumerable<(int Index, TownNetPoint Point)> Ahead()
|
||||
{
|
||||
for (int i = Math.Max(1, _idx); i < _way.Count; i++) yield return (i, _way[i]);
|
||||
}
|
||||
|
||||
/// <summary>The point the walk was at before the one being walked to.</summary>
|
||||
public TownNetPoint Previous => _way[Math.Max(0, _idx - 1)];
|
||||
|
||||
public Act Step(double x, double y, long now, out double heading, out string why) => Step(x, y, double.NaN, now, out heading, out why);
|
||||
|
||||
/// <param name="z">Your height (NaN: unknown; heights then don't count).</param>
|
||||
public Act Step(double x, double y, double z, long now, out double heading, out string why)
|
||||
{
|
||||
heading = 0; why = "";
|
||||
JustStartedWaiting = false;
|
||||
|
|
@ -473,8 +786,10 @@ internal sealed class HubWalker
|
|||
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;
|
||||
// Over levels: a point right above or below (a ramp's turn, the floor under a walkway) isn't reached yet.
|
||||
if (!LevelOk(_idx, z)) break;
|
||||
_idx++;
|
||||
_best = double.MaxValue; _bestMs = now;
|
||||
_best = double.MaxValue; _bestMs = now; _jumps = 0;
|
||||
}
|
||||
TownNetPoint tgt = _way[_idx], prev = _way[_idx - 1];
|
||||
double off = TownNet.SegmentDistance(x, y, prev, tgt, out double tSeg);
|
||||
|
|
@ -529,13 +844,19 @@ internal sealed class HubWalker
|
|||
aimX = prev.X + sx * tt; aimY = prev.Y + sy * tt;
|
||||
}
|
||||
|
||||
// Stuck: no StuckProgress closer to where we're heading in StuckMs.
|
||||
// Stuck: no StuckProgress closer to where we're heading in StuckMs. Before that, jump
|
||||
// (running on): a lip, a step up or a low railing the walk runs into.
|
||||
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;
|
||||
if (dAim < _best - StuckProgress) { _best = dAim; _bestMs = now; _jumps = 0; }
|
||||
else if (now - _bestMs > StuckMs) { why = $"stuck near {x:F1}, {y:F1}" + (_jumps > 0 ? $" (jumped {_jumps}x)" : ""); return Act.Stop; }
|
||||
else if (_jumps < MaxJumps && now - _bestMs > JumpAfterMs * (_jumps + 1) && now - _jumpMs > JumpAfterMs)
|
||||
{
|
||||
_jumps++; JumpsTotal++;
|
||||
_jumpMs = now;
|
||||
return Act.Jump;
|
||||
}
|
||||
return Act.Run;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,7 +33,8 @@ internal static class TravelPlan
|
|||
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)
|
||||
Func<double, double, double, double, bool>? canWalk, bool? landReachable, string goalName,
|
||||
IReadOnlyList<double>? startHubWalks = null)
|
||||
{
|
||||
var r = new Result { Est = NavCoords.Distance(startNs, startEw, goalNs, goalEw) };
|
||||
recalls ??= Array.Empty<RecallLink>();
|
||||
|
|
@ -43,16 +44,19 @@ internal static class TravelPlan
|
|||
|
||||
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; }
|
||||
// No walking start: a recall gets you out, or a walk RynthNav learned in this dungeon to one of its portals.
|
||||
bool walkOut = false;
|
||||
if (startHubWalks != null) foreach (double w in startHubWalks) if (!double.IsNaN(w) && w >= 0) { walkOut = true; break; }
|
||||
if (!portalsOn) { r.Refusal = "you're in a dungeon, so the way out is a recall or a portal: turn on Use portals and recalls"; return r; }
|
||||
if (!walkOut && !recallsOn) { r.Refusal = "you're in a dungeon, so the way out is a recall: turn on Recalls"; return r; }
|
||||
if (!walkOut && 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);
|
||||
out r.Est, out r.Teleports, canWalk, startOnMap: false, startHubWalks: startHubWalks);
|
||||
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}";
|
||||
r.Refusal = walkOut ? $"you're in a dungeon and neither its learned portals nor your recalls lead on to {goalName}"
|
||||
: $"you're in a dungeon and none of your recalls leads on to {goalName}";
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
|
|
|||
109
Plugins/RynthCore.Plugin.RynthNav/TripFollow.cs
Normal file
109
Plugins/RynthCore.Plugin.RynthNav/TripFollow.cs
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// Keeps a goto on the trip's own path (2026-11-01). The trip's walk (TripPath, the path the markers
|
||||
/// draw) is worked out once for the whole step. The walker used to plan its own way to the route graph's
|
||||
/// next border crossing every 0.7 s instead, so it went its own way: across fields, round the other side
|
||||
/// of a building. Players saw it wander off the path the markers showed. Now each plan aims at a point
|
||||
/// <see cref="LookAhead"/> along the step's walk past where we are on it. The navmesh still plans those
|
||||
/// few metres, so walls and portals are still kept out of. Off the path by more than
|
||||
/// <see cref="OffPathUnits"/> (knocked off it, stepped round something), it aims back at the path first.
|
||||
/// Progress along the walk only goes forward, so a path that doubles back is never cut across.
|
||||
/// Host-free: the route tests drive it.
|
||||
/// </summary>
|
||||
internal sealed class TripFollow
|
||||
{
|
||||
/// <summary>How far ahead along the walk each plan aims (yards).</summary>
|
||||
public const double LookAhead = 28.0;
|
||||
/// <summary>Farther than this from the walk is off it: aim back at it.</summary>
|
||||
public const double OffPathUnits = 14.0;
|
||||
/// <summary>Back on the walk, aim this far ahead of the nearest point on it.</summary>
|
||||
public const double RejoinAhead = 6.0;
|
||||
/// <summary>How far back along the walk (yards) the nearest point may be looked for.</summary>
|
||||
public const double SearchBack = 12.0;
|
||||
/// <summary>...and how far ahead of it (a walk that comes back close to itself isn't cut across).</summary>
|
||||
public const double SearchAhead = 90.0;
|
||||
|
||||
private readonly WorldPt[] _pts;
|
||||
private readonly double[] _cum;
|
||||
private double _progress;
|
||||
|
||||
public int TripId { get; }
|
||||
public int Step { get; }
|
||||
public double Length => _cum[^1];
|
||||
/// <summary>How far along the walk we are (yards; only goes forward).</summary>
|
||||
public double Progress => _progress;
|
||||
/// <summary>The last Aim's distance from the walk.</summary>
|
||||
public double LastOff { get; private set; }
|
||||
|
||||
public TripFollow(int tripId, int step, WorldPt[] pts)
|
||||
{
|
||||
if (pts.Length < 2) throw new ArgumentException("a walk has two points at least", nameof(pts));
|
||||
TripId = tripId; Step = step;
|
||||
_pts = pts;
|
||||
_cum = new double[pts.Length];
|
||||
for (int i = 1; i < pts.Length; i++) _cum[i] = _cum[i - 1] + pts[i].FlatDistance(pts[i - 1]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The point to plan to from (x, y): <see cref="LookAhead"/> along the walk past where we are on it,
|
||||
/// or, off the walk, a little past the nearest point on it. <paramref name="off"/> is how far from the
|
||||
/// walk we are; <paramref name="nearEnd"/> is true when the aim is the walk's end.
|
||||
/// </summary>
|
||||
public (double X, double Y) Aim(double x, double y, out double off, out bool nearEnd)
|
||||
{
|
||||
double s = Nearest(x, y, out off);
|
||||
LastOff = off;
|
||||
double aimAt;
|
||||
if (off > OffPathUnits) aimAt = s + RejoinAhead;
|
||||
else
|
||||
{
|
||||
if (s > _progress) _progress = s;
|
||||
aimAt = _progress + LookAhead;
|
||||
}
|
||||
if (aimAt >= Length) { nearEnd = true; return (_pts[^1].X, _pts[^1].Y); }
|
||||
nearEnd = false;
|
||||
return At(aimAt);
|
||||
}
|
||||
|
||||
/// <summary>The point <paramref name="s"/> yards along the walk.</summary>
|
||||
public (double X, double Y) At(double s)
|
||||
{
|
||||
s = Math.Clamp(s, 0, Length);
|
||||
int i = Array.BinarySearch(_cum, s);
|
||||
if (i >= 0) return (_pts[i].X, _pts[i].Y);
|
||||
i = ~i; // the first point past s
|
||||
if (i <= 0) return (_pts[0].X, _pts[0].Y);
|
||||
if (i >= _pts.Length) return (_pts[^1].X, _pts[^1].Y);
|
||||
double seg = _cum[i] - _cum[i - 1];
|
||||
double t = seg < 1e-9 ? 0 : (s - _cum[i - 1]) / seg;
|
||||
return (_pts[i - 1].X + (_pts[i].X - _pts[i - 1].X) * t, _pts[i - 1].Y + (_pts[i].Y - _pts[i - 1].Y) * t);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The nearest point on the walk to (x, y), not more than <see cref="SearchBack"/> behind the progress
|
||||
/// so far (a walk that passes close to itself isn't jumped back along): how far along it is.
|
||||
/// </summary>
|
||||
private double Nearest(double x, double y, out double dist)
|
||||
{
|
||||
double from = Math.Max(0, _progress - SearchBack);
|
||||
double best = double.MaxValue, bestS = _progress;
|
||||
for (int i = 1; i < _pts.Length; i++)
|
||||
{
|
||||
if (_cum[i] < from) continue;
|
||||
if (_cum[i - 1] > _progress + SearchAhead) break;
|
||||
double ax = _pts[i - 1].X, ay = _pts[i - 1].Y, bx = _pts[i].X, by = _pts[i].Y;
|
||||
double vx = bx - ax, vy = by - ay, len2 = vx * vx + vy * vy;
|
||||
double t = len2 < 1e-9 ? 0 : Math.Clamp(((x - ax) * vx + (y - ay) * vy) / len2, 0, 1);
|
||||
double sAt = _cum[i - 1] + Math.Sqrt(len2) * t;
|
||||
if (sAt < from) { t = (from - _cum[i - 1]) / Math.Max(Math.Sqrt(len2), 1e-9); sAt = from; }
|
||||
double px = ax + vx * t - x, py = ay + vy * t - y;
|
||||
double d = Math.Sqrt(px * px + py * py);
|
||||
if (d < best) { best = d; bestS = sAt; }
|
||||
}
|
||||
dist = best;
|
||||
return bestS;
|
||||
}
|
||||
}
|
||||
|
|
@ -26,7 +26,8 @@ internal readonly record struct WorldPt(double X, double Y, double H)
|
|||
}
|
||||
|
||||
/// <summary>A recall of the plan, as the plan was made (RouteStep.RecallIndex indexes these).</summary>
|
||||
internal readonly record struct TripRecall(string Name, int SpellId, string Command, double CastSeconds);
|
||||
/// <summary>A recall the trip may cast. ToArrival >= 0: it lands in a learned dungeon, at that arrival of the route hub.</summary>
|
||||
internal readonly record struct TripRecall(string Name, int SpellId, string Command, double CastSeconds, int ToArrival = -1);
|
||||
|
||||
/// <summary>
|
||||
/// One trip RynthNav planned (Route) or is walking (Go), frozen when it was planned: the steps,
|
||||
|
|
@ -191,13 +192,28 @@ internal sealed class PlannedTrip
|
|||
pts = net.Walk(best.Arrival, exit)?.Points;
|
||||
if (pts == null) { why = $"townnet.json has no walk from {best.Name}'s arrival to the {net.Exits[exit].Name}"; return null; }
|
||||
}
|
||||
else if (i > 0 && Steps[i - 1].IsHub)
|
||||
{
|
||||
// Chained from the hub step before: its exit lands at an arrival here (a learned dungeon's portal into another).
|
||||
int prevExit = Steps[i - 1].HubExit;
|
||||
int arrival = prevExit >= 0 && prevExit < net.Exits.Count ? net.Exits[prevExit].DestArrival : -1;
|
||||
if (arrival < 0) { why = "the portal before it doesn't say where it lands"; return null; }
|
||||
pts = net.Walk(arrival, exit)?.Points;
|
||||
if (pts == null) { why = $"no walk is known from where the {net.Exits[prevExit].Name} lands to the {net.Exits[exit].Name}"; return null; }
|
||||
}
|
||||
else if (i > 0 && Steps[i - 1].UseRecall && RecallOf(i - 1) is { ToArrival: >= 0 } into)
|
||||
{
|
||||
// A recall or portal gem into a learned dungeon: the walk from where it lands.
|
||||
pts = net.Walk(into.ToArrival, exit)?.Points;
|
||||
if (pts == null) { why = $"no walk is known from where {into.Name} lands to the {net.Exits[exit].Name}"; return null; }
|
||||
}
|
||||
else if (i == 0 && !StartOnMap && net.Contains((StartCell >> 16) & 0xFFFF))
|
||||
{
|
||||
double lx = Start.X - ((StartCell >> 24) & 0xFF) * 192.0, ly = Start.Y - ((StartCell >> 16) & 0xFF) * 192.0;
|
||||
pts = net.WayTo(exit, lx, ly, HubWalker.OffRouteUnits, out _);
|
||||
if (pts == null) { why = "no Town Network walk to that exit passes where the trip started"; return null; }
|
||||
if (pts == null) { why = "no walk to that exit passes where the trip started"; return null; }
|
||||
}
|
||||
else { why = "the plan doesn't say how it gets into the Town Network"; return null; }
|
||||
else { why = "the plan doesn't say how it gets in there"; return null; }
|
||||
|
||||
var list = new List<WorldPt>(pts.Count);
|
||||
foreach (TownNetPoint p in pts)
|
||||
|
|
|
|||
99
Plugins/RynthCore.Plugin.RynthNav/WalkDoors.cs
Normal file
99
Plugins/RynthCore.Plugin.RynthNav/WalkDoors.cs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Doors on RynthNav's walks inside dungeons (2026-10-30): which closed door stands across the walk
|
||||
// ahead, and which pack items may unlock one. No host calls: the offline tests compile this file.
|
||||
// RynthNavPlugin.Doors.cs does the using.
|
||||
internal static class WalkDoors
|
||||
{
|
||||
/// <summary>A door this far (metres, flat) from the walk's line stands across it.</summary>
|
||||
public const double CorridorUnits = 1.8;
|
||||
/// <summary>Only the walk this far ahead (metres along it) is looked at.</summary>
|
||||
public const double LookAheadUnits = 10.0;
|
||||
/// <summary>A door more than this above or below the walk at that spot is on another level.</summary>
|
||||
public const double LevelUnits = 3.0;
|
||||
|
||||
/// <summary>
|
||||
/// How far along the walk (metres, from (x, y)) a door at (dx, dy, dz) stands across it, or -1:
|
||||
/// within CorridorUnits of a leg in the first LookAheadUnits, on the leg's level when the walk
|
||||
/// has heights (<paramref name="levels"/>). <paramref name="ahead"/>: the points still ahead, in order.
|
||||
/// </summary>
|
||||
public static double AlongWalk(double x, double y, double z, IReadOnlyList<TownNetPoint> ahead, bool levels,
|
||||
double dx, double dy, double dz)
|
||||
{
|
||||
double along = 0, px = x, py = y, pz = z;
|
||||
foreach (TownNetPoint p in ahead)
|
||||
{
|
||||
double sx = p.X - px, sy = p.Y - py, len = Math.Sqrt(sx * sx + sy * sy);
|
||||
double t = len < 1e-6 ? 0 : Math.Clamp(((dx - px) * sx + (dy - py) * sy) / (len * len), 0, 1);
|
||||
double cx = px + sx * t - dx, cy = py + sy * t - dy;
|
||||
double off = Math.Sqrt(cx * cx + cy * cy);
|
||||
double legZ = double.IsNaN(pz) ? p.Z : pz + (p.Z - pz) * t;
|
||||
bool level = !levels || double.IsNaN(dz) || Math.Abs(legZ - dz) < LevelUnits;
|
||||
if (off <= CorridorUnits && level) return along + len * t <= LookAheadUnits ? along + len * t : -1;
|
||||
along += len;
|
||||
if (along > LookAheadUnits) break;
|
||||
px = p.X; py = p.Y; pz = p.Z;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>A door this close (metres, flat) in front of us is what a blocked walk ran into.</summary>
|
||||
public const double InFrontUnits = 4.5;
|
||||
/// <summary>...within this angle either side of the heading (degrees).</summary>
|
||||
public const double InFrontHalfAngle = 65.0;
|
||||
|
||||
/// <summary>
|
||||
/// The door at (dx, dy, dz) is in front of us at (x, y, z) facing (hx, hy) (a unit vector): within
|
||||
/// InFrontUnits, InFrontHalfAngle of the heading and LevelUnits up or down; <paramref name="dist"/> how far.
|
||||
/// </summary>
|
||||
public static bool InFront(double x, double y, double z, double hx, double hy, double dx, double dy, double dz, out double dist)
|
||||
{
|
||||
double vx = dx - x, vy = dy - y;
|
||||
dist = Math.Sqrt(vx * vx + vy * vy);
|
||||
if (dist > InFrontUnits) return false;
|
||||
if (!double.IsNaN(z) && !double.IsNaN(dz) && Math.Abs(dz - z) >= LevelUnits) return false;
|
||||
if (dist < 0.5) return true; // on top of it
|
||||
double cos = (vx * hx + vy * hy) / dist;
|
||||
return cos >= Math.Cos(InFrontHalfAngle * Math.PI / 180.0);
|
||||
}
|
||||
|
||||
/// <summary>What a pack item can do to a lock.</summary>
|
||||
public enum Unlocker { None, Key, Lockpick }
|
||||
|
||||
private static readonly Regex KeyName = new(@"\bkey(ring)?s?\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
private static readonly Regex PickName = new(@"\block\s?picks?\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>A key (or keyring) or a lockpick, by its name.</summary>
|
||||
public static Unlocker UnlockerOf(string? name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name)) return Unlocker.None;
|
||||
if (PickName.IsMatch(name)) return Unlocker.Lockpick;
|
||||
if (KeyName.IsMatch(name)) return Unlocker.Key;
|
||||
return Unlocker.None;
|
||||
}
|
||||
|
||||
private static readonly Regex LockedText = new(@"^\s*the\s.+\sis\s+locked\s*[.!]?\s*$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>The server's "The door is locked!" (ACE Door.ActOnUse).</summary>
|
||||
public static bool IsLockedText(string? text) =>
|
||||
!string.IsNullOrEmpty(text) && text.Length <= 120 && LockedText.IsMatch(text);
|
||||
|
||||
/// <summary>The order to try unlockers in: keys first (they aren't used up), then lockpicks.</summary>
|
||||
public static List<(uint Id, string Name, Unlocker Kind)> TryOrder(IEnumerable<(uint Id, string Name)> pack)
|
||||
{
|
||||
var keys = new List<(uint, string, Unlocker)>();
|
||||
var picks = new List<(uint, string, Unlocker)>();
|
||||
foreach (var (id, name) in pack)
|
||||
{
|
||||
Unlocker k = UnlockerOf(name);
|
||||
if (k == Unlocker.Key) keys.Add((id, name, k));
|
||||
else if (k == Unlocker.Lockpick) picks.Add((id, name, k));
|
||||
}
|
||||
keys.AddRange(picks);
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
243
Plugins/RynthCore.Plugin.RynthNav/WallStuck.cs
Normal file
243
Plugins/RynthCore.Plugin.RynthNav/WallStuck.cs
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// Is the walk stuck (2026-11-07)? Until now only a tick that ran counted: a tick turning in place
|
||||
/// started the watch again. On 11-07 at Yaraq the walk swung between headings 58, 113, 338 and 119,
|
||||
/// running a moment and turning a moment, for three seconds against a wall, and the watch never saw
|
||||
/// 1.2 s of running in a row; then it stood for 25 s and the 30 s progress watchdog stopped the goto.
|
||||
/// Now every tick the walk wants to move counts (running or turning): moved less than
|
||||
/// <see cref="MoveUnits"/> over <see cref="RunWindowMs"/> with some running in it, or over
|
||||
/// <see cref="TurnWindowMs"/> of turning only, is stuck. A tick that doesn't want to move (opening a
|
||||
/// door, waiting for a plan) starts the watch again. Host-free: the route tests drive it.
|
||||
/// </summary>
|
||||
internal sealed class StuckWatch
|
||||
{
|
||||
/// <summary>A window with running in it: this long...</summary>
|
||||
public const long RunWindowMs = 1200;
|
||||
/// <summary>...or this long turning only (a half turn on the spot takes about a second).</summary>
|
||||
public const long TurnWindowMs = 3000;
|
||||
/// <summary>...and moved less than this = stuck (a run covers 4+ u/s).</summary>
|
||||
public const double MoveUnits = 0.6;
|
||||
/// <summary>No drive asked for this long: the walk isn't trying to move.</summary>
|
||||
public const long WantGapMs = 150;
|
||||
|
||||
private long _winMs;
|
||||
private double _x, _y;
|
||||
private bool _ranInWindow;
|
||||
private long _lastWantMs = long.MinValue / 2;
|
||||
|
||||
/// <summary>The walk drove this tick: running, or turning in place.</summary>
|
||||
public void Wanted(long now, bool running)
|
||||
{
|
||||
_lastWantMs = now;
|
||||
if (running) _ranInWindow = true;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_winMs = 0;
|
||||
_ranInWindow = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Once a walking tick, before steering: true when stuck (the window is over and the character moved
|
||||
/// less than <see cref="MoveUnits"/> in it). <paramref name="moved"/> is how far it went in the window and
|
||||
/// <paramref name="windowMs"/> how long the window was, both 0 while no window has ended this tick.
|
||||
/// </summary>
|
||||
public bool Check(long now, double x, double y, out double moved, out long windowMs)
|
||||
{
|
||||
moved = 0;
|
||||
windowMs = 0;
|
||||
bool wanted = now - _lastWantMs <= WantGapMs;
|
||||
if (!wanted || _winMs == 0)
|
||||
{
|
||||
_winMs = now; _x = x; _y = y; _ranInWindow = false;
|
||||
return false;
|
||||
}
|
||||
long need = _ranInWindow ? RunWindowMs : TurnWindowMs;
|
||||
long elapsed = now - _winMs;
|
||||
if (elapsed < need) return false;
|
||||
windowMs = elapsed; // only when a window ended
|
||||
moved = Math.Sqrt((x - _x) * (x - _x) + (y - _y) * (y - _y));
|
||||
_winMs = now; _x = x; _y = y; _ranInWindow = false;
|
||||
return moved < MoveUnits;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The running jump at a spot the walk is stuck at (2026-11-07). It used to be one tap of the jump
|
||||
/// key: a tap is the smallest hop AC has (jump height is how long the key is held), and in every
|
||||
/// log the character had moved 0.0 u 1.2 s after it. Now it charges like a held spacebar
|
||||
/// (<see cref="ChargeMs"/>: a medium jump, then a full one), released with forward and run held so it
|
||||
/// carries the run's momentum (the engine's LaunchJumpWithMotion, as RynthAi's /mt jump does; full
|
||||
/// jumps only, three of them, when jumping <see cref="Hard"/>), then
|
||||
/// <see cref="FlightMs"/> in the air before the stuck watch starts again. Only after both jumps at
|
||||
/// one spot does the walk step round it. Host-free: the route tests drive it.
|
||||
/// </summary>
|
||||
internal sealed class WallJump
|
||||
{
|
||||
/// <summary>The charge of each try at one spot (ms; 1000 is a full bar): a strong jump, then a full one.</summary>
|
||||
public static readonly int[] ChargeMs = { 700, 1000 };
|
||||
/// <summary>
|
||||
/// Jumping hard (2026-11-07, "it should use more power to jump if needed"): where the route graph has no
|
||||
/// walking way to a spot on the same land (a wall or a ledge the navmesh doesn't cross), every jump is a
|
||||
/// full one, three at each spot.
|
||||
/// </summary>
|
||||
public static readonly int[] HardChargeMs = { 1000, 1000, 1000 };
|
||||
|
||||
/// <summary>Jumping hard: <see cref="HardChargeMs"/> instead of <see cref="ChargeMs"/>.</summary>
|
||||
public bool Hard { get; set; }
|
||||
private int[]? _spot;
|
||||
/// <summary>The charges tried at one spot, in order: this spot's own plan (<see cref="SetSpot"/>), else the default.</summary>
|
||||
public int[] Plan => _spot ?? (Hard ? HardChargeMs : ChargeMs);
|
||||
|
||||
/// <summary>
|
||||
/// This spot's jumps, worked out from the character's jump and what is in the way (JumpModel.PlanFor):
|
||||
/// empty when no jump clears it (too high, too burdened), so the walk steps round at once.
|
||||
/// </summary>
|
||||
public void SetSpot(int[] plan) { _spot = plan; }
|
||||
/// <summary>Time in the air before the walk looks again.</summary>
|
||||
public const long FlightMs = 900;
|
||||
|
||||
public enum Phase { Idle, Charging, Flying }
|
||||
public enum Step { Hold, Release, Landed }
|
||||
|
||||
private long _releaseAt, _landAt;
|
||||
|
||||
public Phase Now { get; private set; } = Phase.Idle;
|
||||
/// <summary>Jumps tried at this spot.</summary>
|
||||
public int Tries { get; private set; }
|
||||
public bool Busy => Now != Phase.Idle;
|
||||
public bool CanTry => Tries < Plan.Length;
|
||||
/// <summary>The charge of the jump under way (0 for a tap).</summary>
|
||||
public int Charge { get; private set; }
|
||||
|
||||
/// <summary>A charged jump: the jump key is down from now. Returns the charge (ms).</summary>
|
||||
public int StartCharged(long now)
|
||||
{
|
||||
Charge = Plan[Math.Min(Tries, Plan.Length - 1)];
|
||||
Tries++;
|
||||
Now = Phase.Charging;
|
||||
_releaseAt = now + Charge;
|
||||
return Charge;
|
||||
}
|
||||
|
||||
/// <summary>A tap (no charged jump in this engine): already in the air.</summary>
|
||||
public void StartTap(long now)
|
||||
{
|
||||
Charge = 0;
|
||||
Tries++;
|
||||
Now = Phase.Flying;
|
||||
_landAt = now + FlightMs;
|
||||
}
|
||||
|
||||
/// <summary>Each tick while <see cref="Busy"/>: Release once (let go of the key), then Landed once.</summary>
|
||||
public Step Tick(long now)
|
||||
{
|
||||
if (Now == Phase.Charging && now >= _releaseAt)
|
||||
{
|
||||
Now = Phase.Flying;
|
||||
_landAt = now + FlightMs;
|
||||
return Step.Release;
|
||||
}
|
||||
if (Now == Phase.Flying && now >= _landAt)
|
||||
{
|
||||
Now = Phase.Idle;
|
||||
return Step.Landed;
|
||||
}
|
||||
return Step.Hold;
|
||||
}
|
||||
|
||||
/// <summary>It moved on: the next stuck spot gets its jumps again.</summary>
|
||||
public void Moved() { if (!Busy) { Tries = 0; _spot = null; } }
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
Now = Phase.Idle;
|
||||
Tries = 0;
|
||||
Charge = 0;
|
||||
_spot = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How high this character jumps right now (2026-11-07, Silentkelpie: "the jump on routes should take your
|
||||
/// buffed jump into account as well as your burden"). AC's jump, as the server works it out (ACE's
|
||||
/// MovementSystem.GetJumpHeight): height = burden factor x (Jump / (Jump + 1300) x 22.2 + 0.05) x power, at
|
||||
/// least 0.35 m, power being how full the bar is (held 0 to 1 s). The burden factor is 1 up to 100% burden,
|
||||
/// falls to 0 at 200%, where no jump leaves the ground. Jump is the buffed skill. Burden is what you carry over
|
||||
/// what your Strength carries (150 per point, 30 more per point for each carrying augmentation).
|
||||
/// Host-free: the route tests drive it.
|
||||
/// </summary>
|
||||
internal sealed class JumpModel
|
||||
{
|
||||
/// <summary>The Jump skill's id.</summary>
|
||||
public const uint JumpSkillId = 22;
|
||||
/// <summary>Feet over the top of what is jumped (m).</summary>
|
||||
public const double Clearance = 0.35;
|
||||
/// <summary>The navmesh climbs 1 m (RynthNav.Baker agentMaxClimb): what stops the walk is higher.</summary>
|
||||
public const double MeshClimb = 1.0;
|
||||
/// <summary>The least charge sent (a shorter press is a tap).</summary>
|
||||
public const int MinChargeMs = 200;
|
||||
|
||||
/// <summary>The buffed Jump skill (0: not known).</summary>
|
||||
public int Skill { get; }
|
||||
/// <summary>Burden over capacity (1.0 = 100%; NaN: not known).</summary>
|
||||
public double Burden { get; }
|
||||
|
||||
public JumpModel(int skill, double burden) { Skill = Math.Max(0, skill); Burden = burden; }
|
||||
|
||||
public bool Known => Skill > 0;
|
||||
public bool BurdenKnown => !double.IsNaN(Burden);
|
||||
/// <summary>Too burdened to jump at all (200% or more).</summary>
|
||||
public bool TooBurdened => BurdenKnown && Burden >= 2.0;
|
||||
|
||||
public static double BurdenFactor(double burden) =>
|
||||
double.IsNaN(burden) || burden < 1.0 ? 1.0 : burden < 2.0 ? 2.0 - burden : 0.0;
|
||||
|
||||
/// <summary>The jump's height at <paramref name="power"/> (0..1), in metres.</summary>
|
||||
public double Height(double power)
|
||||
{
|
||||
double p = Math.Clamp(power, 0, 1);
|
||||
double h = BurdenFactor(Burden) * (Skill / (Skill + 1300.0) * 22.2 + 0.05) * p;
|
||||
return Math.Max(h, 0.35);
|
||||
}
|
||||
|
||||
/// <summary>A full jump's height.</summary>
|
||||
public double FullHeight => Height(1.0);
|
||||
|
||||
/// <summary>The bar to fill (ms) for feet <see cref="Clearance"/> over something <paramref name="top"/> m high; 0 = none does.</summary>
|
||||
public int ChargeFor(double top)
|
||||
{
|
||||
double need = top + Clearance;
|
||||
double full = BurdenFactor(Burden) * (Skill / (Skill + 1300.0) * 22.2 + 0.05);
|
||||
if (TooBurdened || full <= 0 || need > full) return 0;
|
||||
return Math.Clamp((int)Math.Ceiling(need / full * 1000.0 / 50.0) * 50, MinChargeMs, 1000);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The jumps for one stuck spot. <paramref name="top"/>: how high the thing in the way is (NaN: not known,
|
||||
/// a live object or no geometry). Known and jumpable: just enough, then a full one. Too high or too
|
||||
/// burdened: none (step round at once). Not known: from the mesh's climb up, then full ones.
|
||||
/// </summary>
|
||||
public int[] PlanFor(double top, bool hard, out string why)
|
||||
{
|
||||
if (TooBurdened) { why = $"too burdened to jump ({Burden * 100:F0}%)"; return Array.Empty<int>(); }
|
||||
if (!double.IsNaN(top))
|
||||
{
|
||||
int c = ChargeFor(top);
|
||||
if (c == 0) { why = $"{top:F1} m high; your jump clears about {FullHeight - Clearance:F1} m (Jump {Skill}{BurdenNote})"; return Array.Empty<int>(); }
|
||||
why = $"{top:F1} m high; a {c} ms jump clears it (Jump {Skill}{BurdenNote})";
|
||||
return c >= 1000 ? new[] { 1000, 1000 } : new[] { c, 1000 };
|
||||
}
|
||||
int first = Math.Max(ChargeFor(MeshClimb + 0.6), 700);
|
||||
if (first == 0 || hard) first = 1000;
|
||||
why = $"height not known; from {first} ms (Jump {Skill}{BurdenNote}: a full jump clears about {FullHeight - Clearance:F1} m)";
|
||||
return hard ? new[] { 1000, 1000, 1000 } : new[] { first, 1000 };
|
||||
}
|
||||
|
||||
private string BurdenNote => BurdenKnown ? $", burden {Burden * 100:F0}%" : "";
|
||||
}
|
||||
|
||||
Loading…
Reference in a new issue