using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using RynthNav.Routing; namespace RynthCore.Plugin.RynthNav; // This server's own portals (CustomPortals.cs, 2026-11-27): written down by a scan or when you take one, and given // to the route planner as plain portal links next to portals.tsv's, so go / route / the arrow use them. Our graph is // PortalRoute's (the same plan, costs and rules as every other portal); the walk to a custom portal aims at the // spot the live object stood on, as for a portals.tsv portal with a spot. Tick thread. // /rnav portals scan [yd] | list | forget | clear confirm | custom on|off // Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here. public sealed partial class RynthNavPlugin { private const string CustomPortalsFile = "custom-portals.txt"; private const long NearPortalEveryMs = 400; /// A live portal this close to you (yards) is the one you'd be taking. private const double NearPortalUnits = 6.0; /// The portal seen beside you counts for a teleport this long after it was seen. private const long NearPortalFreshMs = 5000; public const double ScanDefaultUnits = 250.0; private CustomPortalStore _custom = new(); private volatile CustomPortalStore? _loadedCustom; private bool _customLoaded; private int _savedCustomVersion = -1; private volatile bool _customOn = true; // rynthnav.json customPortals private string _server = ""; private List? _tsvPortals; // portals.tsv only (the "built in" ones) private string _routeLinksKey = ""; private string _customLast = ""; // the panel's line: what the last scan or learn did private volatile int _customSaved, _customRoutable; // this server's counts, for the panel (counted on the tick) private string _countedKey = ""; private long _lastDeadMs; // HP 0 seen: the trip to the lifestone that follows isn't a portal // The live portal right beside you, looked for every NearPortalEveryMs on the map (a teleport then is that portal). private long _nextNearPortalMs; private (string Name, uint Wcid, uint Cell, double X, double Y, double Z, double Wx, double Wy, long Ms)? _nearPortal; private void LoadCustomPortals() { _customOn = NavDataConfig.ReadSwitch("customPortals", true); string path = NavFile(CustomPortalsFile); Task.Run(() => { CustomPortalStore s = new(); try { if (File.Exists(path)) s = CustomPortalStore.Parse(File.ReadAllText(path)); } catch (Exception ex) { Host.Log($"[RynthNav] {CustomPortalsFile}: {ex.Message}"); } _loadedCustom = s; }); } /// Every tick: the loaded file taken in, the server, the portal beside you, the route links, the save. private void TickCustomPortals(long now, bool save) { if (!_customLoaded && _loadedCustom is CustomPortalStore loaded) { _custom = loaded; _customLoaded = true; _savedCustomVersion = loaded.Version; int n = loaded.All.Count; if (n > 0) Host.Log($"[RynthNav] {CustomPortalsFile}: {n} custom portal(s)"); } if (_server.Length == 0 && Host.TryGetWorldName(out string world) && world.Trim().Length > 0) _server = world.Trim(); if (now >= _nextNearPortalMs) { _nextNearPortalMs = now + NearPortalEveryMs; NoteNearPortal(now); } RefreshRoutePortals(); string ck = $"{_server}|{_custom.Version}|{_customLoaded}"; if (ck != _countedKey) { _countedKey = ck; var (saved, routable) = _server.Length > 0 && _customLoaded ? _custom.Counts(_server) : (0, 0); _customSaved = saved; _customRoutable = routable; } if (save && _customLoaded && _custom.Version != _savedCustomVersion) SaveCustomPortals(); } private void OnLogoutCustom() { if (_customLoaded && _custom.Version != _savedCustomVersion) SaveCustomPortals(); _server = ""; _nearPortal = null; } private void SaveCustomPortals() { // Every client writes the one file: take in what the others saved since, then write. try { string path = NavFile(CustomPortalsFile); if (File.Exists(path)) _custom.MergeFrom(CustomPortalStore.Parse(File.ReadAllText(path))); } catch (Exception ex) { Host.Log($"[RynthNav] {CustomPortalsFile} (merging before a save): {ex.Message}"); } _savedCustomVersion = _custom.Version; WriteLater(CustomPortalsFile, _custom.Serialize()); } /// /// The route planner's portals: portals.tsv's, then this server's custom ones with both ends on the map (custom /// on). Rebuilt when they change; the tsv ones keep their place, so a trip's portal keys stay the same. /// private void RefreshRoutePortals() { if (_tsvPortals == null) return; string key = _customOn ? $"{_server}|{_custom.Version}" : "off"; if (key == _routeLinksKey && _portals != null) return; _routeLinksKey = key; var all = new List(_tsvPortals); if (_customOn && _server.Length > 0) { List mine = _custom.Links(_server); all.AddRange(mine); if (mine.Count > 0) Host.Log($"[RynthNav] routes: {mine.Count} custom portal(s) for {_server} with the {_tsvPortals.Count} of portals.tsv"); } _portals = all; } /// The nearest live portal object within NearPortalUnits, on the map, noted with its spot. private void NoteNearPortal(long now) { if (Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out _, out _, out _, out _) && maxHp > 0 && hp == 0) _lastDeadMs = now; if (!_hasPose || !IsOnMap(_cellId) || !Host.HasGetLiveObjectIds || (Host.HasIsPortaling && Host.IsPortaling())) return; double best = NearPortalUnits * NearPortalUnits; uint bestId = 0, bestCell = 0; float bx = 0, by = 0, bz = 0; foreach (uint id in Host.GetLiveObjectIds()) { if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue; if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out float z) || cell == 0 || !IsOnMap(cell)) continue; double ox = ((cell >> 24) & 0xFF) * 192.0 + x, oy = ((cell >> 16) & 0xFF) * 192.0 + y; double d2 = (ox - _wx) * (ox - _wx) + (oy - _wy) * (oy - _wy); if (d2 >= best) continue; best = d2; bestId = id; bestCell = cell; bx = x; by = y; bz = z; } if (bestId == 0) return; // the last one stays until it is too old to count Host.TryGetObjectName(bestId, out string name); Host.TryGetObjectWcid(bestId, out uint wcid); if (name.Length == 0) return; _nearPortal = (name, wcid, bestCell, bx, by, bz, ((bestCell >> 24) & 0xFF) * 192.0 + bx, ((bestCell >> 16) & 0xFF) * 192.0 + by, now); } /// /// OnTeleported, a portal (not a recall): the live portal seen right beside where you stood before the jump /// was the one taken; its landing is learned (CustomPortalStore.Learned). portals.tsv's are left alone. /// /// : your own spell words just before (a recall cast beside a portal isn't the portal). private void LearnCustomPortal(bool havePre, uint preCell, double preWx, double preWy, long startMs, RecallSpot landing, bool spellWords) { if (!_customLoaded || _server.Length == 0 || !havePre || !IsOnMap(preCell) || _nearPortal is not { } near) return; if (spellWords || (_lastDeadMs != 0 && startMs - _lastDeadMs < 60000)) { _nearPortal = null; return; } if (startMs - near.Ms > NearPortalFreshMs || near.Ms > startMs + 500) return; if ((near.Cell >> 16) != (preCell >> 16) && Math.Abs(near.Wx - preWx) + Math.Abs(near.Wy - preWy) > 2 * NearPortalUnits) return; double dx = near.Wx - preWx, dy = near.Wy - preWy; if (dx * dx + dy * dy > NearPortalUnits * NearPortalUnits) return; _nearPortal = null; double ns = NavCoords.NsFromWorld(near.Wy), ew = NavCoords.EwFromWorld(near.Wx); CustomLearn r = _custom.Learned(_server, near.Name, near.Wcid, near.Cell, near.X, near.Y, near.Z, ns, ew, landing.OnMap, landing.Ns, landing.Ew, landing.OnMap ? 0 : _cellId, _tsvPortals, DateTime.UtcNow, out CustomPortal? p); switch (r) { case CustomLearn.New: case CustomLearn.LandingChanged: string what = r == CustomLearn.New ? "learned" : "updated"; _customLast = $"{what} {p!.Name} → {p.Where}"; Host.Log($"[RynthNav] custom portal {what}: {p.Name} at {NavCoords.Fmt(ns, ew)} → {p.Where} ({_server})"); Say($"{what} portal {p.Name}: it goes to {p.Where}" + (p.Routable ? "; routes can use it now" : "")); break; case CustomLearn.AlreadyKnown: Host.Log($"[RynthNav] custom portal {near.Name}: already known ({p?.Where})"); break; } } // ── /rnav portals ... ──────────────────────────────────────────────── private void CmdPortals(string rest) { string[] a = rest.Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); string verb = a.Length > 0 ? a[0].ToLowerInvariant() : ""; string arg = a.Length > 1 ? a[1] : ""; switch (verb) { case "on": case "off": _portalsEnabled = verb == "on"; NavDataConfig.WriteSwitch("portals", _portalsEnabled); Say($"portal and recall routing {(_portalsEnabled ? "ON" : "OFF")} for walking (go/goto)"); return; case "": Say($"portal and recall routing {(_portalsEnabled ? "ON" : "OFF")}; {CustomSummary()} — /rnav portals on|off | scan [yd] | list | forget | clear confirm | custom on|off"); return; case "custom": string v = arg.ToLowerInvariant(); if (v is "on" or "off") { _customOn = v == "on"; NavDataConfig.WriteSwitch("customPortals", _customOn); } else if (v.Length > 0) { SayFail("/rnav portals custom on|off — this server's own portals in routes"); return; } Say($"custom portals in routes: {(_customOn ? "ON" : "OFF")}; {CustomSummary()}"); return; case "scan": CmdPortalScan(arg); return; case "list": CmdPortalList(); return; case "forget": if (!CustomReady(out string server)) return; if (arg.Length == 0) { SayFail("/rnav portals forget "); return; } int n = _custom.Forget(server, arg); if (n == 0) SayFail($"portals: no custom portal called {arg} on {server}"); else Say($"portals: forgot {n} custom portal(s) called {arg} on {server}"); return; case "clear": if (!CustomReady(out server)) return; if (!arg.Equals("confirm", StringComparison.OrdinalIgnoreCase)) { var (saved, _) = _custom.Counts(server); SayFail($"portals: /rnav portals clear confirm forgets all {saved} custom portal(s) of {server}"); return; } Say($"portals: forgot all {_custom.Clear(server)} custom portal(s) of {server}"); _customLast = "cleared"; return; default: SayFail("/rnav portals on|off | scan [yd] | list | forget | clear confirm | custom on|off"); return; } } private bool CustomReady(out string server) { server = _server; if (!_customLoaded) { SayFail($"portals: {CustomPortalsFile} isn't loaded yet"); return false; } if (server.Length == 0) { SayFail("portals: not logged in to a server yet"); return false; } return true; } private string CustomSummary() { if (_server.Length == 0) return "custom portals: not logged in yet"; var (saved, routable) = _custom.Counts(_server); return $"{saved} custom portal(s) saved for {_server}, {routable} routable{(_customOn ? "" : " (not used: custom off)")}"; } /// /rnav portals scan [yd]: every live portal object on the map within that range, written down. private void CmdPortalScan(string arg) { if (!CustomReady(out string server)) return; if (!_hasPose) { SayFail("portals scan: no player position yet"); return; } double range = ScanDefaultUnits; if (arg.Length > 0 && (!double.TryParse(arg, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out range) || range <= 0)) { SayFail("/rnav portals scan [yards] — e.g. /rnav portals scan 200"); return; } range = Math.Clamp(range, 10, 2000); if (!Host.HasGetLiveObjectIds) { SayFail("portals scan: this RynthCore can't list objects"); return; } EnsurePortalsLoaded(); int added = 0, refreshed = 0, builtIn = 0, inDungeon = 0; var names = new List(); DateTime now = DateTime.UtcNow; foreach (uint id in Host.GetLiveObjectIds()) { if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue; if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out float z) || cell == 0) continue; if (!IsOnMap(cell)) { inDungeon++; continue; } double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y; if (Math.Sqrt((wx - _wx) * (wx - _wx) + (wy - _wy) * (wy - _wy)) > range) continue; if (!Host.TryGetObjectName(id, out string name) || name.Length == 0 || Entrance.IsDestroyed(name)) continue; Host.TryGetObjectWcid(id, out uint wcid); switch (_custom.Saw(server, name, wcid, cell, x, y, z, NavCoords.NsFromWorld(wy), NavCoords.EwFromWorld(wx), _tsvPortals, now)) { case CustomSeen.Added: added++; if (names.Count < 6) names.Add(name); break; case CustomSeen.Refreshed: refreshed++; break; default: builtIn++; break; } } var (saved, routable) = _custom.Counts(server); _customLast = $"scan: {added} new, {refreshed} known, {builtIn} in the world data"; Host.Log($"[RynthNav] portals scan ({range:F0} yd, {server}): {added} new, {refreshed} known, {builtIn} in portals.tsv, {inDungeon} in dungeons (not mapped)"); Say($"portals scan ({range:F0} yd): {added} new{(names.Count > 0 ? " (" + string.Join(", ", names) + (added > names.Count ? ", …" : "") + ")" : "")}, " + $"{refreshed} already saved, {builtIn} already in the world data. {saved} saved for {server}, {routable} routable" + (added > 0 ? "; take each once and routes can use it" : "")); } private void CmdPortalList() { if (!CustomReady(out string server)) return; List list = _custom.For(server); if (list.Count == 0) { Say($"portals: no custom portals saved for {server} — /rnav portals scan writes down the ones around you"); return; } Say($"portals: {CustomSummary()}:"); bool hasPos = PlayerMapPos(out double pns, out double pew); list.Sort((x, y) => (hasPos ? NavCoords.Distance(pns, pew, x.Ns, x.Ew) : 0).CompareTo(hasPos ? NavCoords.Distance(pns, pew, y.Ns, y.Ew) : 0)); int shown = 0; foreach (CustomPortal p in list) { if (++shown > 20) { Say($" … and {list.Count - 20} more"); break; } Say($" {p.Name} at {NavCoords.Fmt(p.Ns, p.Ew)}{(hasPos ? ", " + NavCoords.FmtDistance(NavCoords.Distance(pns, pew, p.Ns, p.Ew)) : "")} → {p.Where}"); } } /// The panel's custom portals fields (status JSON "custom"). Any thread: the counts are the tick's. private void AppendCustomJson(StringBuilder sb) { string server = _server; int saved = _customSaved, routable = _customRoutable; sb.Append(",\"custom\":{\"on\":").Append(_customOn ? 1 : 0).Append(",\"server\":\"").Append(Esc(server)) .Append("\",\"saved\":").Append(saved).Append(",\"routable\":").Append(routable) .Append(",\"range\":").Append(((int)ScanDefaultUnits).ToString(System.Globalization.CultureInfo.InvariantCulture)) .Append(",\"last\":\"").Append(Esc(_customLast)).Append("\"}"); } }