using System; using System.Collections.Generic; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Text.Json; using RynthNav.Routing; namespace RynthCore.Plugin.RynthNav; // The Town Network (NavData\townnet.json, made by RynthCore's tools\navdata\gen_townnet.py from the // world database plus RynthNav.TownNet's walks from the dats): the "Portal to Town Network" in many // towns, the arrival points inside, the exit portal to each town, and the walk from every arrival // to every exit. RynthNav's route planner uses it as a hub (PortalRoute's HubLinks) and the walker // follows the stored walks inside, where there is no navmesh. Read-only once loaded. // No host calls: the offline tests compile this file. internal sealed class TownNetPoint { public uint Cell; public double X, Y, Z; /// The edge of a drop (2026-10-30): walk on off it; the next point is where you land, lower down. public bool Drop; } internal sealed class TownNetArrival { public string Id = ""; public uint Cell; public double X, Y, Z; } /// Restrictions the server checks before it lets a character through a portal. internal sealed class TownNetRules { public int MinLevel, MaxLevel, AccountRequirements; public string Quest = ""; public bool Closed, NoOlthoi, OnlyOlthoi, AdvocateOnly, NoPk, NoPkLite, NoNpk, NoVitae, NoNewAccounts; /// /// Why this character can't use the portal ("" = it can). Level 0 = not known yet: a portal with a /// level rule is then left out, since it can't be shown to be open. Rules the plugin can't check /// (quests, player killer status, vitae) leave the portal out too. /// public string Blocks(int level, bool olthoi) { if (Closed) return "closed"; if (AdvocateOnly) return "advocates only"; if (Quest.Length > 0) return "needs a quest flag"; if (olthoi && NoOlthoi) return "no Olthoi"; if (!olthoi && OnlyOlthoi) return "Olthoi only"; if (MinLevel > 0 || MaxLevel > 0) { if (level <= 0) return MinLevel > 0 ? $"needs level {MinLevel} (your level isn't known yet)" : $"level {MaxLevel} or lower (your level isn't known yet)"; if (MinLevel > 0 && level < MinLevel) return $"needs level {MinLevel}"; if (MaxLevel > 0 && level > MaxLevel) return $"level {MaxLevel} or lower"; } if (NoPk || NoPkLite || NoNpk) return "player killer rules"; if (NoVitae) return "no vitae"; if (NoNewAccounts || AccountRequirements > 1) return "account rules"; return ""; } } internal sealed class TownNetEntry { public string Guid = "", Name = "", Place = "", Town = ""; public bool OnMap; public double Ns, Ew; public int Arrival = -1; public readonly TownNetRules Rules = new(); /// A portal into a dungeon RynthNav learned (custom portals), not townnet.json's. public bool Learned; } internal sealed class TownNetExit { public string Guid = "", Name = "", Label = "", DestTown = "", DestPlace = ""; public uint Cell; public double X, Y, Z; public bool DestOnMap; public double DestNs, DestEw; public uint DestCell; public readonly TownNetRules Rules = new(); /// Lands at this arrival of the same (merged) network: a learned dungeon's portal into another learned dungeon. -1 = none. public int DestArrival = -1; /// The hub it stands in, for what RynthNav says: "Town Network", or a learned dungeon's name. public string Hub = "Town Network"; /// A learned dungeon's portal (custom portals), not townnet.json's. public bool Learned; /// "Yaraq" for the Portal to Yaraq: the town or place it leads to. public string Where => Label.Length > 0 ? Label : DestTown.Length > 0 ? DestTown : Name; public uint DestLandblock => DestCell >> 16; } internal sealed class TownNetWalk { public int Arrival, Exit; public double Length; /// The least room on the walk from the walker's centre to a wall or object (m); 0 = not given. public double MinClear; public TownNetPoint[] Points = Array.Empty(); /// Worked out from the dats (RynthAi's dungeon pathfinder), not walked yet: walking it and taking the portal makes it a learned walk. public bool Planned; } /// /// A walk inside dungeon landblock 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). /// internal delegate DungeonWay? DungeonPather(uint landblock, double ax, double ay, double az, double bx, double by, double bz); /// A walk from RynthAi's dungeon pathfinder: x,y,z triples (landblock-local), and which points are the edge of a drop. internal sealed class DungeonWay { public readonly double[] Points; /// Per point: the edge of a drop (the next point is the landing). Null: none. 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; /// The walk as walker points in . 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 { public const string FileName = "townnet.json"; public const int SupportedVersion = 1; /// Landing within this of an arrival point counts as landing there (metres = yards here). public const double ArrivalNearUnits = 3.0; public int Version; public string SetId = "", Generated = ""; /// The network's landblocks (0x0007 on our data). public readonly HashSet Landblocks = new(); public readonly List Arrivals = new(); public readonly List Entries = new(); public readonly List Exits = new(); public readonly List Walks = new(); private readonly Dictionary<(int, int), TownNetWalk> _walk = new(); public bool Contains(uint landblock) => Landblocks.Contains(landblock); public TownNetWalk? Walk(int arrival, int exit) => _walk.TryGetValue((arrival, exit), out var w) ? w : null; public override string ToString() => $"{Entries.Count} entry portals, {Exits.Count} exits, {Walks.Count} walks (set {SetId})"; /// /// The first 16 hex digits of the SHA-256 of the text without its "setId" and "generated" lines, /// carriage returns dropped: the same id gen_townnet.py and RynthNav.TownNet write. /// public static string ComputeSetId(string text) { var kept = new List(); foreach (string l in text.Replace("\r", "").Split('\n')) if (!l.StartsWith(" \"setId\":", StringComparison.Ordinal) && !l.StartsWith(" \"generated\":", StringComparison.Ordinal)) kept.Add(l); byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(string.Join("\n", kept))); return Convert.ToHexString(hash, 0, 8).ToLowerInvariant(); } /// /// Reads townnet.json. Null, with , when it can't be used: another version, /// a set id that doesn't match the contents (edited or damaged), or no walks. Routing then works /// as if there were no file. /// public static TownNet? Parse(string text, out string why) { why = ""; var t = new TownNet(); using JsonDocument doc = JsonDocument.Parse(text, new JsonDocumentOptions { AllowTrailingCommas = true }); JsonElement r = doc.RootElement; if (r.ValueKind != JsonValueKind.Object) { why = "not a townnet.json"; return null; } t.Version = Int(r, "version"); if (t.Version != SupportedVersion) { why = $"version {t.Version}, this RynthNav reads version {SupportedVersion}"; return null; } t.SetId = Str(r, "setId"); t.Generated = Str(r, "generated"); string actual = ComputeSetId(text); if (t.SetId.Length == 0 || !t.SetId.Equals(actual, StringComparison.OrdinalIgnoreCase)) { why = $"its set id ({(t.SetId.Length > 0 ? t.SetId : "none")}) doesn't match its contents ({actual}): edited or damaged"; return null; } if (r.TryGetProperty("landblocks", out var lbs) && lbs.ValueKind == JsonValueKind.Array) foreach (var e in lbs.EnumerateArray()) if (e.ValueKind == JsonValueKind.String && uint.TryParse(e.GetString(), NumberStyles.HexNumber, null, out uint lb)) t.Landblocks.Add(lb); var arrivalIndex = new Dictionary(StringComparer.Ordinal); foreach (var e in Arr(r, "arrivals")) { var a = new TownNetArrival { Id = Str(e, "id"), Cell = Hex(e, "cell"), X = Num(e, "x"), Y = Num(e, "y"), Z = Num(e, "z") }; arrivalIndex[a.Id] = t.Arrivals.Count; t.Arrivals.Add(a); t.Landblocks.Add(a.Cell >> 16); } foreach (var e in Arr(r, "entries")) { var en = new TownNetEntry { Guid = Str(e, "guid"), Name = Str(e, "name"), Place = Str(e, "place") }; en.OnMap = TryNum(e, "ns", out en.Ns) & TryNum(e, "ew", out en.Ew); if (e.TryGetProperty("town", out var town) && town.ValueKind == JsonValueKind.Object) en.Town = Str(town, "name"); en.Arrival = arrivalIndex.TryGetValue(Str(e, "arrival"), out int ai) ? ai : -1; ReadRules(e, en.Rules); t.Entries.Add(en); } var exitIndex = new Dictionary(StringComparer.Ordinal); foreach (var e in Arr(r, "exits")) { var x = new TownNetExit { Guid = Str(e, "guid"), Name = Str(e, "name"), Label = Str(e, "label"), Cell = Hex(e, "cell"), X = Num(e, "x"), Y = Num(e, "y"), Z = Num(e, "z"), }; if (e.TryGetProperty("dest", out var d) && d.ValueKind == JsonValueKind.Object) { x.DestCell = Hex(d, "cell"); x.DestPlace = Str(d, "place"); x.DestOnMap = TryNum(d, "ns", out x.DestNs) & TryNum(d, "ew", out x.DestEw); if (d.TryGetProperty("town", out var town) && town.ValueKind == JsonValueKind.Object) x.DestTown = Str(town, "name"); } ReadRules(e, x.Rules); exitIndex[x.Guid] = t.Exits.Count; t.Exits.Add(x); } foreach (var e in Arr(r, "walks")) { if (!arrivalIndex.TryGetValue(Str(e, "from"), out int a) || !exitIndex.TryGetValue(Str(e, "to"), out int x)) continue; var pts = new List(); if (e.TryGetProperty("points", out var ps) && ps.ValueKind == JsonValueKind.Array) foreach (var p in ps.EnumerateArray()) { if (p.ValueKind != JsonValueKind.Array || p.GetArrayLength() < 3) continue; var pt = new TownNetPoint { Cell = p[0].ValueKind == JsonValueKind.String && uint.TryParse(p[0].GetString(), NumberStyles.HexNumber, null, out uint c) ? c : 0, X = p[1].GetDouble(), Y = p[2].GetDouble(), Z = p.GetArrayLength() > 3 ? p[3].GetDouble() : 0, }; pts.Add(pt); } if (pts.Count < 2) continue; var w = new TownNetWalk { Arrival = a, Exit = x, Length = Num(e, "length"), MinClear = Num(e, "minClear"), Points = pts.ToArray() }; if (w.Length <= 0) w.Length = PathLength(w.Points, 0); t.Walks.Add(w); t._walk[(a, x)] = w; } if (t.Arrivals.Count == 0 || t.Exits.Count == 0 || t.Walks.Count == 0) { why = "it has no arrivals, exits or walks"; return null; } return t; } private static void ReadRules(JsonElement e, TownNetRules r) { r.MinLevel = Int(e, "minLevel"); r.MaxLevel = Int(e, "maxLevel"); r.AccountRequirements = Int(e, "accountRequirements"); r.Quest = Str(e, "quest"); r.Closed = Bool(e, "closed"); r.NoOlthoi = Bool(e, "noOlthoi"); r.OnlyOlthoi = Bool(e, "onlyOlthoi"); r.AdvocateOnly = Bool(e, "advocateOnly"); r.NoPk = Bool(e, "noPk"); r.NoPkLite = Bool(e, "noPkLite"); r.NoNpk = Bool(e, "noNpk"); r.NoVitae = Bool(e, "noVitae"); r.NoNewAccounts = Bool(e, "noNewAccounts"); } // ── The planner's view ─────────────────────────────────────────────────── /// /// The network as the route planner sees it, for a character of (0 = not /// known) who is (or isn't) an Olthoi: the entry portals on the map, the exits that lead onto the /// map, and the walks inside. A portal the character can't use is left out, with a note. Entries /// and exits in dungeons have no map position and are left out too (silently: they never could /// be on a map route). is the index into . /// public HubLinks Links(int level, bool olthoi, List? notes) { var hub = new HubLinks { Name = "Town Network", Arrivals = Arrivals.Count }; int entriesBlocked = 0; string entryWhy = ""; foreach (TownNetEntry e in Entries) { if (!e.OnMap || e.Arrival < 0) continue; string why = e.Rules.Blocks(level, olthoi); if (why.Length > 0) { entriesBlocked++; entryWhy = why; continue; } hub.Entries.Add(new HubEntry(e.Ns, e.Ew, e.Arrival, e.Name)); } if (entriesBlocked > 0) notes?.Add($"Town Network: {entriesBlocked} entry portal(s) left out ({entryWhy})."); for (int x = 0; x < Exits.Count; x++) { TownNetExit ex = Exits[x]; if (!ex.DestOnMap && 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]; bool any = false; for (int a = 0; a < Arrivals.Count; a++) { TownNetWalk? w = Walk(a, x); walk[a] = w != null ? w.Length : double.NaN; any |= w != null; } if (!any) continue; hub.Exits.Add(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) ──────────────────────────────────── /// A landing within this of a learned arrival (and the height check) is that arrival. public const double LearnedArrivalUnits = 5.0; public const double LearnedArrivalHeight = 3.0; /// Adds a walk; one already kept for the same arrival and exit stays if it is no longer. 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; } /// The learned arrivals (index from on) in that landblock. 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; } /// A learned arrival (index from on) in exactly that cell, or -1. public int LearnedArrivalByCell(int first, uint cell) { for (int i = first; i < Arrivals.Count; i++) if (Arrivals[i].Cell == cell) return i; return -1; } /// /// 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. /// /// /// 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. /// 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(t.Landblocks); int firstArrival = t.Arrivals.Count; IReadOnlyList portals = store.For(server); // A dungeon's name: the first map portal learned to lead into it. var hubName = new Dictionary(); 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(); 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(); 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>(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; } /// How many entries, exits and walks were learned (not townnet.json's). /// "AC Storage" for the AC Storage Portal, "Lighthouse" for the Portal to Lighthouse. 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 ?? ""; } /// How many walks were planned from the dats (not walked yet). 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) ───────── /// The arrival within of (x, y), or -1. public int ArrivalNear(double x, double y) { int best = -1; double bestD = ArrivalNearUnits; for (int i = 0; i < Arrivals.Count; i++) { double d = Math.Sqrt((Arrivals[i].X - x) * (Arrivals[i].X - x) + (Arrivals[i].Y - y) * (Arrivals[i].Y - y)); if (d <= bestD) { best = i; bestD = d; } } return best; } /// /// The way from (x, y) to exit : the walk from the arrival you stand on, /// else the walk (from any arrival) that passes nearest, joined at that point. The first point /// returned is where you stand. Null when no walk to that exit comes within /// of you. /// public List? WayTo(int exit, double x, double y, double maxOff, out string from) { from = ""; int a = ArrivalNear(x, y); TownNetWalk? w = a >= 0 ? Walk(a, exit) : null; if (w != null) { from = Arrivals[a].Id; var list = new List { new() { Cell = w.Points[0].Cell, X = x, Y = y, Z = w.Points[0].Z } }; for (int i = 1; i < w.Points.Length; i++) list.Add(w.Points[i]); return list; } TownNetWalk? best = null; int bestSeg = -1; double bestD = maxOff; foreach (TownNetWalk cand in Walks) { if (cand.Exit != exit) continue; for (int i = 1; i < cand.Points.Length; i++) { double d = SegmentDistance(x, y, cand.Points[i - 1], cand.Points[i], out _); if (d <= bestD) { bestD = d; best = cand; bestSeg = i; } } } if (best == null) return null; from = "the nearest walk (from " + Arrivals[best.Arrival].Id + ")"; var way = new List { new() { Cell = best.Points[bestSeg - 1].Cell, X = x, Y = y, Z = best.Points[bestSeg - 1].Z } }; for (int i = bestSeg; i < best.Points.Length; i++) way.Add(best.Points[i]); return way; } /// Distance from (x, y) to the segment a→b, and how far along it the nearest point is (0..1). public static double SegmentDistance(double x, double y, TownNetPoint a, TownNetPoint b, out double t) { double dx = b.X - a.X, dy = b.Y - a.Y, len2 = dx * dx + dy * dy; t = len2 < 1e-9 ? 1 : Math.Clamp(((x - a.X) * dx + (y - a.Y) * dy) / len2, 0, 1); double px = a.X + dx * t - x, py = a.Y + dy * t - y; return Math.Sqrt(px * px + py * py); } /// Straight-segment length of from index on. public static double PathLength(IReadOnlyList pts, int from) { double len = 0; for (int i = Math.Max(1, from + 1); i < pts.Count; i++) len += Math.Sqrt((pts[i].X - pts[i - 1].X) * (pts[i].X - pts[i - 1].X) + (pts[i].Y - pts[i - 1].Y) * (pts[i].Y - pts[i - 1].Y)); return len; } // ── JSON helpers ───────────────────────────────────────────────────────── private static IEnumerable Arr(JsonElement e, string name) { if (!e.TryGetProperty(name, out var v) || v.ValueKind != JsonValueKind.Array) yield break; foreach (var x in v.EnumerateArray()) if (x.ValueKind == JsonValueKind.Object) yield return x; } private static string Str(JsonElement e, string name) => e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; private static int Int(JsonElement e, string name) => e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : 0; private static bool Bool(JsonElement e, string name) => e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.True; private static double Num(JsonElement e, string name) => TryNum(e, name, out double d) ? d : 0; private static bool TryNum(JsonElement e, string name, out double d) { d = 0; return e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out d); } private static uint Hex(JsonElement e, string name) => uint.TryParse(Str(e, name), NumberStyles.HexNumber, null, out uint v) ? v : 0; } /// /// Follows one stored walk inside the Town Network: straight segments, steering at the next waypoint /// every tick; a waypoint counts once within 0.5 m or passed along its segment (never circled); more /// than 2 m off the line steers back to it, more than 6 m stops. It holds short of the exit portal /// until 4 s after landing (ACE refuses a portal within 3.5 s of a teleport), then walks into its /// centre; standing there with no teleport it backs off and walks in once more. No 0.5 m of progress /// in 3 s, or more than length ÷ 3 + 10 s (plus the hold) in all, stops with a reason. The teleport /// itself is the caller's to notice. Host-free: the route tests drive it. /// internal sealed class HubWalker { public const double WaypointUnits = 0.5; /// /// A corner is cut by about (radius × sin of the turn); the walks keep 0.15 m of spare room, so a /// sharp corner counts as reached closer in: radius = min(0.5, MaxCutUnits / sin(turn)). /// public const double MaxCutUnits = 0.1; public const double SteerBackUnits = 2.0; public const double OffRouteUnits = 6.0; /// Hold this far from the exit's centre (portal reach 1.36 m + body 0.48 m + room) during the cooldown. public const double HoldUnits = 2.6; public const double BackOffUnits = 3.0; public const double StuckProgress = 0.5; public const long CooldownMs = 4000; public const long StuckMs = 8000; // 3 s stopped a walk that had only just landed (10-01 20:13: the client holds you a moment after portal space; a turn in place takes time too) public const long TouchWaitMs = 3000; /// No progress this long: jump (still running), over a lip, a step or a railing (2026-10-30). public const long JumpAfterMs = 2000; /// Jumps per stuck spot before StuckMs gives up. public const int MaxJumps = 2; /// On a walk over more than one level, a point counts as reached only within this height of it. public const double LevelUnits = 3.0; /// The walk's points span more than this in height: a walk over levels (ramps, stairs, drops). public const double LevelSpanUnits = 2.5; /// Run = run with the heading; Jump = run with it and jump now; Hold = stand; Stop; NoTeleport. public enum Act { Run, Hold, Stop, NoTeleport, Jump } private readonly List _way; private readonly long _landMs; private int _idx = 1; private double _best = double.MaxValue; private long _bestMs, _atPortalMs; private bool _retried, _backing; private readonly double[] _radius; // per waypoint: how close counts as reached (sharper turn, closer) 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; /// The walk goes up or down levels (its points span more than LevelSpanUnits in height). public bool Levels => _levels; /// Jumps so far on this walk (the log). public int JumpsTotal { get; private set; } public double Length { get; } public long LimitMs { get; private set; } public bool Waiting { get; private set; } /// True on the tick the cooldown hold began (say so once). public bool JustStartedWaiting { get; private set; } /// Whole seconds of cooldown left when the hold began. public long WaitSeconds { get; private set; } public int Index => _idx; public int Count => _way.Count; /// From where you stand to the exit portal's centre (TownNet.WayTo). /// When you landed in the network (the cooldown counts from it). public HubWalker(List way, long landMs, long nowMs) { if (way.Count < 2) throw new ArgumentException("a walk needs two points", nameof(way)); _way = way; _landMs = landMs; _bestMs = nowMs; Length = TownNet.PathLength(way, 0); _radius = new double[way.Count]; for (int i = 0; i < way.Count; i++) { _radius[i] = WaypointUnits; if (i == 0 || i == way.Count - 1) continue; double ax = way[i].X - way[i - 1].X, ay = way[i].Y - way[i - 1].Y, bx = way[i + 1].X - way[i].X, by = way[i + 1].Y - way[i].Y; double la = Math.Sqrt(ax * ax + ay * ay), lb = Math.Sqrt(bx * bx + by * by); if (la < 1e-6 || lb < 1e-6) continue; double cos = (ax * bx + ay * by) / (la * lb); double sin = cos < 0 ? 1.0 : Math.Sqrt(Math.Max(0, 1 - cos * cos)); // past 90 degrees: as sharp as it gets if (sin > 1e-6) _radius[i] = Math.Min(WaypointUnits, Math.Max(0.05, MaxCutUnits / sin)); } LimitMs = nowMs + (long)((Length / 3.0 + 10.0) * 1000) + CooldownMs; 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; } /// /// Point 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). /// 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; } /// Metres left to the exit's centre from (x, y). public double Left(double x, double y) { TownNetPoint t = _way[_idx]; return Math.Sqrt((t.X - x) * (t.X - x) + (t.Y - y) * (t.Y - y)) + TownNet.PathLength(_way, _idx); } /// /// One tick at (x, y): Run with (degrees, 0 = north, 90 = east), Hold /// (stand still), Stop (), or NoTeleport (stood on the exit twice and /// nothing happened). /// /// Not moving through no fault of the walk (portal space): the stuck clock starts again. public void Pause(long now) { _bestMs = now; _best = double.MaxValue; _jumps = 0; } /// A hold through no fault of the walk (a door opening): the stuck clock and the time limit wait too. public void Hold(long now, long heldMs) { Pause(now); LimitMs += heldMs; } /// The points still ahead, from the one being walked to (index, point). public IEnumerable<(int Index, TownNetPoint Point)> Ahead() { for (int i = Math.Max(1, _idx); i < _way.Count; i++) yield return (i, _way[i]); } /// The point the walk was at before the one being walked to. 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); /// Your height (NaN: unknown; heights then don't count). public Act Step(double x, double y, double z, long now, out double heading, out string why) { heading = 0; why = ""; JustStartedWaiting = false; if (now > LimitMs) { why = "it took too long"; return Act.Stop; } int last = _way.Count - 1; while (_idx < last) { TownNetPoint b = _way[_idx]; double db = Math.Sqrt((b.X - x) * (b.X - x) + (b.Y - y) * (b.Y - y)); TownNet.SegmentDistance(x, y, _way[_idx - 1], b, out double along); if (db >= _radius[_idx] && along < 1.0) break; // 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; _jumps = 0; } TownNetPoint tgt = _way[_idx], prev = _way[_idx - 1]; double off = TownNet.SegmentDistance(x, y, prev, tgt, out double tSeg); if (off > OffRouteUnits) { why = $"{off:F1} m off the way"; return Act.Stop; } double toExit = Math.Sqrt((_way[last].X - x) * (_way[last].X - x) + (_way[last].Y - y) * (_way[last].Y - y)); // The portal cooldown: hold short of the exit until CooldownMs after landing. if (_idx == last && !_backing && now - _landMs < CooldownMs && toExit < HoldUnits) { if (!Waiting) { Waiting = true; JustStartedWaiting = true; WaitSeconds = (CooldownMs - (now - _landMs) + 999) / 1000; } _bestMs = now; // waiting isn't being stuck return Act.Hold; } if (Waiting) { Waiting = false; _best = double.MaxValue; _bestMs = now; } // On the exit's centre with no teleport: back off and walk in again, once. if (_idx == last && !_backing && toExit < WaypointUnits) { if (_atPortalMs == 0) _atPortalMs = now; _bestMs = now; if (now - _atPortalMs < TouchWaitMs) return Act.Hold; if (_retried) return Act.NoTeleport; _retried = true; _backing = true; _atPortalMs = 0; _best = double.MaxValue; } double aimX = tgt.X, aimY = tgt.Y; if (_backing) { // A point BackOffUnits back along the last segment (or its start, if it's shorter). TownNetPoint a = _way[last - 1], e = _way[last]; double sx = a.X - e.X, sy = a.Y - e.Y, sl = Math.Sqrt(sx * sx + sy * sy); double k = sl > BackOffUnits ? BackOffUnits / sl : 1.0; aimX = e.X + sx * k; aimY = e.Y + sy * k; if (Math.Sqrt((aimX - x) * (aimX - x) + (aimY - y) * (aimY - y)) < WaypointUnits) { _backing = false; _best = double.MaxValue; _bestMs = now; aimX = tgt.X; aimY = tgt.Y; } } else if (off > SteerBackUnits) { // Drifted off the line: steer back to it, a metre ahead of the nearest point. double sx = tgt.X - prev.X, sy = tgt.Y - prev.Y, sl = Math.Sqrt(sx * sx + sy * sy); double tt = sl > 1e-6 ? Math.Min(1.0, tSeg + 1.0 / sl) : 1.0; aimX = prev.X + sx * tt; aimY = prev.Y + sy * tt; } // Stuck: no StuckProgress closer to where we're heading in StuckMs. 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)); 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; } }