RynthSuite as of 2026-10-04 (internal c94715f): RynthOracle (based on Oracle of Dereth by Advis Eveldan) and RynthInventory, RynthAi patrol doorways and rooms, healing priority, strict monster priority, finish the wounded target, slayer weapons, arcs when clear, blasts like rings, learn unknown spells, looting fixes, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:29 -04:00
commit 12ca25f911
426 changed files with 108239 additions and 7521 deletions

View file

@ -0,0 +1,333 @@
using System;
using System.Collections.Generic;
using System.Globalization;
namespace RynthCore.Plugin.RynthInventory.Data;
/// <summary>One character in the merged view.</summary>
internal sealed class CharacterInfo
{
public CharacterSnapshot Snapshot = null!;
public string Server => Snapshot.Server;
public string Account => Snapshot.Account;
public string Name => Snapshot.Character;
public string Key => Snapshot.Key;
public DateTime ScannedUtc => Snapshot.ScannedUtc;
public bool IsCurrentServer;
public bool IsCurrentCharacter;
public int ItemCount;
public int StorageCount;
/// <summary>Storage this character saw, merged over all its files (newest copy of each container).</summary>
public List<StorageRecord> Storage = new();
/// <summary>The same character's file under another account folder lost to this newer one.</summary>
public List<string> ShadowedFiles = new();
}
/// <summary>One item in the merged view: whose it is and where.</summary>
internal sealed class InventoryRow
{
public CharacterInfo Owner = null!;
public ItemRecord Item = null!;
/// <summary>The storage it is in, or null when carried.</summary>
public StorageRecord? Storage;
/// <summary>"Main pack > Sack", "Equipped: Head", "Storage near 42.1N, 33.6E > Sack".</summary>
public string Where = string.Empty;
/// <summary>Lower-case name (and, for the wide search, material, set and spell names).</summary>
public string SearchName = string.Empty;
public string SearchWide = string.Empty;
/// <summary>When this row's data was seen (the scan, or the storage's last opening).</summary>
public DateTime SeenUtc;
}
internal enum InventorySort { Name, Character, Count, Value, Burden, Category, Age }
internal sealed class InventoryQuery
{
public string Text = string.Empty;
/// <summary>Null = every server.</summary>
public string? Server;
/// <summary>A <see cref="CharacterSnapshot.Key"/>, or null = every character.</summary>
public string? CharacterKey;
/// <summary>An <see cref="ItemCategory"/> id, or null = every category.</summary>
public string? Category;
public bool IncludeEquipped = true;
public bool IncludeStorage = true;
/// <summary>Also match material, set and spell names, not just the item's name.</summary>
public bool SearchSpells;
public InventorySort Sort = InventorySort.Name;
public bool Descending;
}
/// <summary>A total for one item name over the results: "Pyreal: 12,345 across 4 characters".</summary>
internal sealed class InventoryTotal
{
public string Name = string.Empty;
public long Count;
public int Characters;
public int Servers;
public int Rows;
public readonly List<InventoryRow> Holders = new();
}
internal sealed class InventoryResult
{
public readonly List<InventoryRow> Rows = new();
/// <summary>Per item name, biggest count first.</summary>
public readonly List<InventoryTotal> Totals = new();
public long TotalCount;
public int CharacterCount;
}
/// <summary>
/// The merged view of every character file: one row per item (carried, worn, in storage).
/// Merging rules: a character (server + name) appears once, its newest snapshot wins (the
/// live one in this client always does); a storage container (server + object id) appears
/// once, from whichever character saw it open most recently. Pure: no files, no game.
/// </summary>
internal sealed class InventoryIndex
{
public readonly List<CharacterInfo> Characters = new();
public readonly List<InventoryRow> Rows = new();
public readonly List<string> Servers = new();
public string CurrentServer = string.Empty;
public static InventoryIndex Build(IEnumerable<CharacterSnapshot> files, CharacterSnapshot? live, string currentServer, string currentCharacter)
{
var index = new InventoryIndex { CurrentServer = currentServer ?? string.Empty };
string liveKey = live?.Key ?? CharacterSnapshot.MakeKey(currentServer ?? "", currentCharacter ?? "");
// 1. One snapshot per character: the live one, else the newest scan.
var byKey = new Dictionary<string, CharacterInfo>();
var all = new List<CharacterSnapshot>(files);
if (live != null) all.Add(live);
foreach (CharacterSnapshot s in all)
{
if (string.IsNullOrWhiteSpace(s.Character)) continue;
bool isLive = ReferenceEquals(s, live);
if (byKey.TryGetValue(s.Key, out CharacterInfo? have))
{
bool haveLive = ReferenceEquals(have.Snapshot, live);
bool replace = isLive || (!haveLive && s.ScannedUtc > have.Snapshot.ScannedUtc);
CharacterSnapshot loser = replace ? have.Snapshot : s;
if (!string.IsNullOrEmpty(loser.FilePath) && !ReferenceEquals(loser, live)) have.ShadowedFiles.Add(loser.FilePath);
// Storage either copy saw is kept (newest copy of each container).
MergeStorage(have.Storage, s.Storage);
if (replace) have.Snapshot = s;
continue;
}
var info = new CharacterInfo { Snapshot = s };
MergeStorage(info.Storage, s.Storage);
byKey[s.Key] = info;
}
// 2. One copy per storage container per server: the most recently seen.
var storageOwner = new Dictionary<(string, uint), (CharacterInfo Owner, StorageRecord Storage)>();
foreach (CharacterInfo c in byKey.Values)
{
string server = c.Server.Trim().ToLowerInvariant();
foreach (StorageRecord st in c.Storage)
{
var key = (server, st.Id);
if (!storageOwner.TryGetValue(key, out var have) || st.SeenUtc > have.Storage.SeenUtc)
storageOwner[key] = (c, st);
}
}
// 3. Rows.
foreach (CharacterInfo c in byKey.Values)
{
c.IsCurrentServer = SameName(c.Server, index.CurrentServer);
c.IsCurrentCharacter = c.Key == liveKey;
c.ItemCount = c.Snapshot.Items.Count;
foreach (ItemRecord it in c.Snapshot.Items)
index.Rows.Add(MakeRow(c, it, null, c.Snapshot.ScannedUtc));
index.Characters.Add(c);
if (!index.Servers.Exists(x => SameName(x, c.Server))) index.Servers.Add(c.Server);
}
foreach (var (owner, st) in storageOwner.Values)
{
owner.StorageCount++;
foreach (ItemRecord it in st.Items)
index.Rows.Add(MakeRow(owner, it, st, st.SeenUtc));
}
// Current server first, then by name.
index.Servers.Sort((a, b) =>
{
int ca = SameName(a, index.CurrentServer) ? 0 : 1, cb = SameName(b, index.CurrentServer) ? 0 : 1;
return ca != cb ? ca - cb : string.Compare(a, b, StringComparison.OrdinalIgnoreCase);
});
index.Characters.Sort(CompareCharacters);
return index;
}
/// <summary>Adds the records of <paramref name="from"/> that <paramref name="into"/> lacks or has older. Snapshots are never changed.</summary>
private static void MergeStorage(List<StorageRecord> into, List<StorageRecord> from)
{
foreach (StorageRecord st in from)
{
int i = into.FindIndex(x => x.Id == st.Id);
if (i < 0) into.Add(st);
else if (st.SeenUtc > into[i].SeenUtc) into[i] = st;
}
}
private static int CompareCharacters(CharacterInfo a, CharacterInfo b)
{
if (a.IsCurrentServer != b.IsCurrentServer) return a.IsCurrentServer ? -1 : 1;
int s = string.Compare(a.Server, b.Server, StringComparison.OrdinalIgnoreCase);
if (s != 0) return s;
return string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
}
public static bool SameName(string? a, string? b) =>
string.Equals((a ?? "").Trim(), (b ?? "").Trim(), StringComparison.OrdinalIgnoreCase);
private static InventoryRow MakeRow(CharacterInfo c, ItemRecord it, StorageRecord? st, DateTime seen)
{
string where;
if (st != null)
{
string label = string.IsNullOrEmpty(st.Label) ? (string.IsNullOrEmpty(st.Name) ? "Storage" : st.Name) : st.Label;
where = it.Path.Length > 0 ? label + " > " + it.PathText : label;
}
else if (it.Place == ItemPlace.Equipped)
{
string slot = ItemNames.Slot(it.Slot);
where = slot.Length > 0 ? "Equipped: " + slot : "Equipped";
}
else where = it.Path.Length > 0 ? it.PathText : "Main pack";
string name = it.Name.ToLowerInvariant();
string wide = name;
string material = ItemNames.Material(it.Material), set = ItemNames.Set(it.SetId);
if (material.Length > 0) wide += "\n" + material.ToLowerInvariant();
if (set.Length > 0) wide += "\n" + set.ToLowerInvariant();
foreach (string sn in it.SpellNames) wide += "\n" + sn.ToLowerInvariant();
return new InventoryRow { Owner = c, Item = it, Storage = st, Where = where, SearchName = name, SearchWide = wide, SeenUtc = seen };
}
/// <summary>Search terms: whitespace separated, each must appear; "quoted text" is one term.</summary>
public static List<string> Terms(string text)
{
var terms = new List<string>();
if (string.IsNullOrWhiteSpace(text)) return terms;
string t = text.Trim().ToLowerInvariant();
int i = 0;
while (i < t.Length)
{
while (i < t.Length && char.IsWhiteSpace(t[i])) i++;
if (i >= t.Length) break;
if (t[i] == '"')
{
int end = t.IndexOf('"', i + 1);
if (end < 0) end = t.Length;
string q = t.Substring(i + 1, end - i - 1).Trim();
if (q.Length > 0) terms.Add(q);
i = end + 1;
}
else
{
int start = i;
while (i < t.Length && !char.IsWhiteSpace(t[i])) i++;
terms.Add(t.Substring(start, i - start));
}
}
return terms;
}
public InventoryResult Query(InventoryQuery q)
{
var result = new InventoryResult();
List<string> terms = Terms(q.Text);
foreach (InventoryRow r in Rows)
{
if (q.Server != null && !SameName(r.Owner.Server, q.Server)) continue;
if (q.CharacterKey != null && r.Owner.Key != q.CharacterKey) continue;
if (q.Category != null && r.Item.Category != q.Category) continue;
if (!q.IncludeStorage && r.Storage != null) continue;
if (!q.IncludeEquipped && r.Storage == null && r.Item.Place == ItemPlace.Equipped) continue;
if (terms.Count > 0)
{
string hay = q.SearchSpells ? r.SearchWide : r.SearchName;
bool all = true;
foreach (string term in terms)
if (!hay.Contains(term, StringComparison.Ordinal)) { all = false; break; }
if (!all) continue;
}
result.Rows.Add(r);
}
Comparison<InventoryRow> cmp = q.Sort switch
{
InventorySort.Character => (a, b) => Chain(string.Compare(a.Owner.Name, b.Owner.Name, StringComparison.OrdinalIgnoreCase), ByName(a, b)),
InventorySort.Count => (a, b) => Chain(a.Item.Stack.CompareTo(b.Item.Stack), ByName(a, b)),
InventorySort.Value => (a, b) => Chain(a.Item.Value.CompareTo(b.Item.Value), ByName(a, b)),
InventorySort.Burden => (a, b) => Chain(a.Item.Burden.CompareTo(b.Item.Burden), ByName(a, b)),
InventorySort.Category => (a, b) => Chain(string.CompareOrdinal(ItemCategory.Label(a.Item.Category), ItemCategory.Label(b.Item.Category)), ByName(a, b)),
InventorySort.Age => (a, b) => Chain(b.SeenUtc.CompareTo(a.SeenUtc), ByName(a, b)), // newest first
_ => ByName,
};
bool desc = q.Descending;
result.Rows.Sort((a, b) =>
{
// The server you're on comes first whatever the sort.
if (a.Owner.IsCurrentServer != b.Owner.IsCurrentServer) return a.Owner.IsCurrentServer ? -1 : 1;
int c = cmp(a, b);
if (desc) c = -c;
if (c != 0) return c;
int o = string.Compare(a.Owner.Name, b.Owner.Name, StringComparison.OrdinalIgnoreCase);
return o != 0 ? o : a.Item.Id.CompareTo(b.Item.Id);
});
// Totals per name.
var byName = new Dictionary<string, InventoryTotal>(StringComparer.OrdinalIgnoreCase);
var chars = new HashSet<string>();
foreach (InventoryRow r in result.Rows)
{
if (!byName.TryGetValue(r.Item.Name, out InventoryTotal? t))
byName[r.Item.Name] = t = new InventoryTotal { Name = r.Item.Name };
t.Count += Math.Max(1, r.Item.Stack);
t.Rows++;
t.Holders.Add(r);
result.TotalCount += Math.Max(1, r.Item.Stack);
chars.Add(r.Owner.Key);
}
foreach (InventoryTotal t in byName.Values)
{
var cs = new HashSet<string>();
var ss = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (InventoryRow r in t.Holders) { cs.Add(r.Owner.Key); ss.Add(r.Owner.Server.Trim()); }
t.Characters = cs.Count;
t.Servers = ss.Count;
result.Totals.Add(t);
}
result.Totals.Sort((a, b) => a.Count != b.Count ? b.Count.CompareTo(a.Count) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
result.CharacterCount = chars.Count;
return result;
}
private static int ByName(InventoryRow a, InventoryRow b) => string.Compare(a.Item.Name, b.Item.Name, StringComparison.OrdinalIgnoreCase);
private static int Chain(int first, int then) => first != 0 ? first : then;
/// <summary>"Pyreal: 12,345 across 4 characters" (", 2 servers" when more than one).</summary>
public static string TotalText(InventoryTotal t)
{
string s = $"{t.Name}: {t.Count.ToString("N0", CultureInfo.InvariantCulture)} across {t.Characters} character{(t.Characters == 1 ? "" : "s")}";
if (t.Servers > 1) s += $" on {t.Servers} servers";
return s;
}
/// <summary>"just now", "12 min", "5 h", "3 days" ago.</summary>
public static string Age(DateTime utc, DateTime nowUtc)
{
if (utc == default) return "never";
TimeSpan d = nowUtc - utc;
if (d < TimeSpan.FromMinutes(1)) return "just now";
if (d < TimeSpan.FromHours(1)) return $"{(int)d.TotalMinutes} min ago";
if (d < TimeSpan.FromDays(1)) return $"{(int)d.TotalHours} h ago";
int days = (int)d.TotalDays;
return days == 1 ? "1 day ago" : $"{days} days ago";
}
}

View file

@ -0,0 +1,299 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.RynthInventory.Data;
/// <summary>
/// The file format (see the plugin's report for the field list). Written by hand, one item
/// per line so a file stays readable and diffable; read with JsonDocument. Never through
/// System.Text.Json's serializer: plugin types must not reach it (it roots them across hot
/// reloads). Unknown fields are ignored and missing ones keep their defaults, so newer and
/// older plugins read each other's files.
/// </summary>
internal static class InventoryJson
{
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
// ── Write ───────────────────────────────────────────────────────────────
public static string Write(CharacterSnapshot s)
{
var sb = new StringBuilder(64 * 1024);
sb.Append("{\n");
sb.Append(" \"format\": \"").Append(CharacterSnapshot.FormatTag).Append("\",\n");
sb.Append(" \"version\": ").Append(CharacterSnapshot.CurrentFormat.ToString(Inv)).Append(",\n");
sb.Append(" \"server\": "); Str(sb, s.Server); sb.Append(",\n");
sb.Append(" \"account\": "); Str(sb, s.Account); sb.Append(",\n");
sb.Append(" \"character\": "); Str(sb, s.Character); sb.Append(",\n");
sb.Append(" \"characterId\": ").Append(s.CharacterId.ToString(Inv)).Append(",\n");
sb.Append(" \"scannedUtc\": "); Time(sb, s.ScannedUtc); sb.Append(",\n");
sb.Append(" \"plugin\": "); Str(sb, s.PluginVersion); sb.Append(",\n");
sb.Append(" \"items\": [");
ItemList(sb, s.Items, " ");
sb.Append("],\n");
sb.Append(" \"storage\": [");
for (int i = 0; i < s.Storage.Count; i++)
{
StorageRecord st = s.Storage[i];
sb.Append(i == 0 ? "\n" : ",\n");
sb.Append(" {\"id\": ").Append(st.Id.ToString(Inv));
sb.Append(", \"name\": "); Str(sb, st.Name);
sb.Append(", \"label\": "); Str(sb, st.Label);
sb.Append(", \"cell\": ").Append(st.Cell.ToString(Inv));
sb.Append(", \"seenUtc\": "); Time(sb, st.SeenUtc);
sb.Append(", \"items\": [");
ItemList(sb, st.Items, " ");
sb.Append("]}");
}
if (s.Storage.Count > 0) sb.Append("\n ");
sb.Append("]\n");
sb.Append("}\n");
return sb.ToString();
}
private static void ItemList(StringBuilder sb, List<ItemRecord> items, string indent)
{
for (int i = 0; i < items.Count; i++)
{
sb.Append(i == 0 ? "\n" : ",\n").Append(indent);
Item(sb, items[i]);
}
if (items.Count > 0) sb.Append('\n').Append(indent, 0, indent.Length - 2);
}
private static void Item(StringBuilder sb, ItemRecord it)
{
sb.Append("{\"id\": ").Append(it.Id.ToString(Inv));
sb.Append(", \"name\": "); Str(sb, it.Name);
if (it.Wcid != 0) sb.Append(", \"wcid\": ").Append(it.Wcid.ToString(Inv));
sb.Append(", \"icon\": ").Append(it.Icon.ToString(Inv));
if (it.Underlay != 0) sb.Append(", \"underlay\": ").Append(it.Underlay.ToString(Inv));
if (it.Overlay != 0) sb.Append(", \"overlay\": ").Append(it.Overlay.ToString(Inv));
sb.Append(", \"stack\": ").Append(it.Stack.ToString(Inv));
if (it.MaxStack != 0) sb.Append(", \"maxStack\": ").Append(it.MaxStack.ToString(Inv));
sb.Append(", \"type\": ").Append(it.ItemType.ToString(Inv));
sb.Append(", \"category\": "); Str(sb, it.Category);
sb.Append(", \"place\": "); Str(sb, it.Place);
sb.Append(", \"container\": ").Append(it.ContainerId.ToString(Inv));
sb.Append(", \"path\": [");
for (int i = 0; i < it.Path.Length; i++)
{
if (i > 0) sb.Append(", ");
Str(sb, it.Path[i]);
}
sb.Append(']');
if (it.Slot != 0) sb.Append(", \"slot\": ").Append(it.Slot.ToString(Inv));
if (it.Material != 0) sb.Append(", \"material\": ").Append(it.Material.ToString(Inv));
if (it.Workmanship != 0) sb.Append(", \"workmanship\": ").Append(it.Workmanship.ToString(Inv));
sb.Append(", \"value\": ").Append(it.Value.ToString(Inv));
sb.Append(", \"burden\": ").Append(it.Burden.ToString(Inv));
if (it.ArmorLevel != 0) sb.Append(", \"armor\": ").Append(it.ArmorLevel.ToString(Inv));
if (it.MaxUses != 0)
{
sb.Append(", \"uses\": ").Append(it.Uses.ToString(Inv));
sb.Append(", \"maxUses\": ").Append(it.MaxUses.ToString(Inv));
}
if (it.SetId != 0) sb.Append(", \"set\": ").Append(it.SetId.ToString(Inv));
if (it.Spells.Length > 0)
{
sb.Append(", \"spells\": [");
for (int i = 0; i < it.Spells.Length; i++)
{
if (i > 0) sb.Append(", ");
sb.Append(it.Spells[i].ToString(Inv));
}
sb.Append(']');
if (it.SpellNames.Length == it.Spells.Length)
{
sb.Append(", \"spellNames\": [");
for (int i = 0; i < it.SpellNames.Length; i++)
{
if (i > 0) sb.Append(", ");
Str(sb, it.SpellNames[i]);
}
sb.Append(']');
}
}
if (it.Identified) sb.Append(", \"identified\": true");
sb.Append('}');
}
private static void Time(StringBuilder sb, DateTime utc)
{
sb.Append('"');
if (utc != default)
sb.Append(DateTime.SpecifyKind(utc, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ssZ", Inv));
sb.Append('"');
}
/// <summary>A JSON string literal (quotes included), escaping what JSON requires.</summary>
public static void Str(StringBuilder sb, string? s)
{
sb.Append('"');
if (s != null)
{
foreach (char c in s)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 0x20 || c == '\u2028' || c == '\u2029')
sb.Append("\\u").Append(((int)c).ToString("x4", Inv));
else
sb.Append(c);
break;
}
}
}
sb.Append('"');
}
// ── Read ────────────────────────────────────────────────────────────────
/// <summary>Parses a file's text. Null (with a reason) for anything that isn't one of ours.</summary>
public static CharacterSnapshot? Read(string json, out string? error)
{
error = null;
try
{
using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
JsonElement r = doc.RootElement;
if (r.ValueKind != JsonValueKind.Object || GetString(r, "format") != CharacterSnapshot.FormatTag)
{
error = "not a RynthInventory file";
return null;
}
var s = new CharacterSnapshot
{
Format = GetInt(r, "version", CharacterSnapshot.CurrentFormat),
Server = GetString(r, "server"),
Account = GetString(r, "account"),
Character = GetString(r, "character"),
CharacterId = GetUInt(r, "characterId"),
ScannedUtc = GetTime(r, "scannedUtc"),
PluginVersion = GetString(r, "plugin"),
};
if (string.IsNullOrWhiteSpace(s.Character) || string.IsNullOrWhiteSpace(s.Server))
{
error = "no character or server name";
return null;
}
if (r.TryGetProperty("items", out JsonElement items) && items.ValueKind == JsonValueKind.Array)
foreach (JsonElement e in items.EnumerateArray())
if (ReadItem(e) is ItemRecord it) s.Items.Add(it);
if (r.TryGetProperty("storage", out JsonElement storage) && storage.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement e in storage.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
var st = new StorageRecord
{
Id = GetUInt(e, "id"),
Name = GetString(e, "name"),
Label = GetString(e, "label"),
Cell = GetUInt(e, "cell"),
SeenUtc = GetTime(e, "seenUtc"),
};
if (e.TryGetProperty("items", out JsonElement si) && si.ValueKind == JsonValueKind.Array)
foreach (JsonElement ie in si.EnumerateArray())
if (ReadItem(ie) is ItemRecord it) st.Items.Add(it);
if (st.Id != 0) s.Storage.Add(st);
}
}
return s;
}
catch (JsonException ex)
{
error = "broken JSON: " + ex.Message;
return null;
}
}
private static ItemRecord? ReadItem(JsonElement e)
{
if (e.ValueKind != JsonValueKind.Object) return null;
var it = new ItemRecord
{
Id = GetUInt(e, "id"),
Name = GetString(e, "name"),
Wcid = GetUInt(e, "wcid"),
Icon = GetUInt(e, "icon"),
Underlay = GetUInt(e, "underlay"),
Overlay = GetUInt(e, "overlay"),
Stack = Math.Max(1, GetInt(e, "stack", 1)),
MaxStack = GetInt(e, "maxStack", 0),
ItemType = GetUInt(e, "type"),
Category = GetString(e, "category"),
Place = GetString(e, "place"),
ContainerId = GetUInt(e, "container"),
Slot = GetUInt(e, "slot"),
Material = GetInt(e, "material", 0),
Workmanship = GetInt(e, "workmanship", 0),
Value = GetInt(e, "value", 0),
Burden = GetInt(e, "burden", 0),
ArmorLevel = GetInt(e, "armor", 0),
Uses = GetInt(e, "uses", 0),
MaxUses = GetInt(e, "maxUses", 0),
SetId = GetInt(e, "set", 0),
Identified = e.TryGetProperty("identified", out JsonElement idf) && idf.ValueKind == JsonValueKind.True,
};
if (string.IsNullOrEmpty(it.Name)) return null;
if (string.IsNullOrEmpty(it.Category)) it.Category = ItemCategory.FromItemType(it.ItemType);
if (string.IsNullOrEmpty(it.Place)) it.Place = ItemPlace.Pack;
it.Path = GetStrings(e, "path");
if (e.TryGetProperty("spells", out JsonElement sp) && sp.ValueKind == JsonValueKind.Array)
{
var list = new List<uint>();
foreach (JsonElement x in sp.EnumerateArray())
if (x.ValueKind == JsonValueKind.Number && x.TryGetUInt32(out uint id)) list.Add(id);
it.Spells = list.ToArray();
}
string[] names = GetStrings(e, "spellNames");
it.SpellNames = names.Length == it.Spells.Length ? names : Array.Empty<string>();
return it;
}
private static string GetString(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty;
private static int GetInt(JsonElement e, string name, int fallback)
{
if (!e.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return fallback;
if (v.TryGetInt32(out int i)) return i;
if (v.TryGetInt64(out long l)) return (int)Math.Clamp(l, int.MinValue, int.MaxValue);
return fallback;
}
private static uint GetUInt(JsonElement e, string name)
{
if (!e.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return 0;
if (v.TryGetUInt32(out uint u)) return u;
if (v.TryGetInt32(out int i)) return unchecked((uint)i); // tolerate ids written signed
return 0;
}
private static DateTime GetTime(JsonElement e, string name)
{
string s = GetString(e, name);
return s.Length > 0 && DateTime.TryParse(s, Inv, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t)
? DateTime.SpecifyKind(t, DateTimeKind.Utc)
: default;
}
private static string[] GetStrings(JsonElement e, string name)
{
if (!e.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Array) return Array.Empty<string>();
var list = new List<string>();
foreach (JsonElement x in v.EnumerateArray())
if (x.ValueKind == JsonValueKind.String) list.Add(x.GetString() ?? string.Empty);
return list.ToArray();
}
}

View file

@ -0,0 +1,164 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthInventory.Data;
// The saved data: one CharacterSnapshot per character per server, one file each.
// Dependency-free on purpose (no plugin SDK types): Tools\RynthInventory.Tests compiles the
// Data folder directly.
/// <summary>Where an item is: worn or wielded, carried (main pack or a side pack), or in storage.</summary>
internal static class ItemPlace
{
public const string Equipped = "equipped";
public const string Pack = "pack";
public const string Storage = "storage";
}
/// <summary>One item, as read from the client without asking the server for anything.</summary>
internal sealed class ItemRecord
{
public uint Id;
public uint Wcid;
public string Name = string.Empty;
/// <summary>Icon, underlay and overlay texture ids (0x06xxxxxx; 0 = none).</summary>
public uint Icon, Underlay, Overlay;
public int Stack = 1;
public int MaxStack;
/// <summary>AC ItemType flags (STypeInt 1).</summary>
public uint ItemType;
/// <summary>A <see cref="ItemCategory"/> name.</summary>
public string Category = ItemCategory.Misc;
/// <summary>An <see cref="ItemPlace"/> value.</summary>
public string Place = ItemPlace.Pack;
public uint ContainerId;
/// <summary>Display path inside the character, outermost first: "Main pack", "Sack" (a side pack) ...</summary>
public string[] Path = Array.Empty<string>();
/// <summary>Equip mask of the slot(s) worn in (CurrentWieldedLocation); 0 when not equipped.</summary>
public uint Slot;
/// <summary>MaterialType (STypeInt 131); 0 unknown or none.</summary>
public int Material;
/// <summary>ItemWorkmanship (STypeInt 105), known once the item was identified; 0 unknown.</summary>
public int Workmanship;
public int Value;
public int Burden;
/// <summary>ArmorLevel (STypeInt 28) once identified; 0 unknown.</summary>
public int ArmorLevel;
/// <summary>Uses left / most uses (Structure 92 / MaxStructure 91): kits, essences; 0 = none.</summary>
public int Uses, MaxUses;
/// <summary>EquipmentSetId (STypeInt 265) once identified; 0 none.</summary>
public int SetId;
public uint[] Spells = Array.Empty<uint>();
/// <summary>Names for <see cref="Spells"/> when the scanner knew them (same order).</summary>
public string[] SpellNames = Array.Empty<string>();
/// <summary>The client had appraisal data for it when scanned (spells, workmanship, set are then known).</summary>
public bool Identified;
public string PathText => Path.Length == 0 ? string.Empty : string.Join(" > ", Path);
}
/// <summary>A container outside the character (house storage, a bank or vault) as last seen open.</summary>
internal sealed class StorageRecord
{
public uint Id;
public string Name = string.Empty;
/// <summary>Where it is, for people: "Storage near 42.1N, 33.6E".</summary>
public string Label = string.Empty;
/// <summary>The landcell it was seen in (0 unknown).</summary>
public uint Cell;
public DateTime SeenUtc;
public List<ItemRecord> Items = new();
}
/// <summary>Everything one character owned when last scanned, plus the storage it opened.</summary>
internal sealed class CharacterSnapshot
{
public const int CurrentFormat = 1;
public const string FormatTag = "rynthinventory";
public int Format = CurrentFormat;
public string Server = string.Empty;
public string Account = string.Empty;
public string Character = string.Empty;
public uint CharacterId;
/// <summary>When the carried inventory (Items) was last scanned.</summary>
public DateTime ScannedUtc;
public string PluginVersion = string.Empty;
public List<ItemRecord> Items = new();
public List<StorageRecord> Storage = new();
// Not saved: where it was read from.
public string FilePath = string.Empty;
/// <summary>Server + character, the identity readers merge on (names are unique per server).</summary>
public string Key => MakeKey(Server, Character);
public static string MakeKey(string server, string character) =>
(server ?? string.Empty).Trim().ToLowerInvariant() + "\u001f" + (character ?? string.Empty).Trim().ToLowerInvariant();
/// <summary>The newest time anything in this snapshot was seen.</summary>
public DateTime NewestUtc
{
get
{
DateTime t = ScannedUtc;
foreach (StorageRecord s in Storage) if (s.SeenUtc > t) t = s.SeenUtc;
return t;
}
}
/// <summary>A hash over everything saved except the times, so an unchanged scan doesn't rewrite the file.</summary>
public ulong ContentHash()
{
var h = new Fnv64();
h.Add(Server); h.Add(Account); h.Add(Character); h.Add(CharacterId);
h.Add((uint)Items.Count);
foreach (ItemRecord i in Items) HashItem(ref h, i);
h.Add((uint)Storage.Count);
foreach (StorageRecord s in Storage)
{
h.Add(s.Id); h.Add(s.Name); h.Add(s.Label); h.Add(s.Cell); h.Add((uint)s.Items.Count);
foreach (ItemRecord i in s.Items) HashItem(ref h, i);
}
return h.Value;
}
internal static void HashItem(ref Fnv64 h, ItemRecord i)
{
h.Add(i.Id); h.Add(i.Wcid); h.Add(i.Name); h.Add(i.Icon); h.Add(i.Underlay); h.Add(i.Overlay);
h.Add((uint)i.Stack); h.Add((uint)i.MaxStack); h.Add(i.ItemType); h.Add(i.Category); h.Add(i.Place);
h.Add(i.ContainerId); h.Add((uint)i.Path.Length);
foreach (string p in i.Path) h.Add(p);
h.Add(i.Slot); h.Add((uint)i.Material); h.Add((uint)i.Workmanship); h.Add((uint)i.Value); h.Add((uint)i.Burden);
h.Add((uint)i.ArmorLevel); h.Add((uint)i.Uses); h.Add((uint)i.MaxUses); h.Add((uint)i.SetId);
h.Add((uint)i.Spells.Length);
foreach (uint s in i.Spells) h.Add(s);
h.Add(i.Identified ? 1u : 0u);
}
}
/// <summary>FNV-1a, 64 bit. Strings are hashed as UTF-16 code units with a terminator.</summary>
internal struct Fnv64
{
private ulong _h;
private bool _started;
public ulong Value => _started ? _h : 14695981039346656037UL;
public void Add(uint v)
{
if (!_started) { _h = 14695981039346656037UL; _started = true; }
for (int i = 0; i < 4; i++)
{
_h ^= (byte)(v >> (i * 8));
_h *= 1099511628211UL;
}
}
public void Add(string? s)
{
if (s != null)
foreach (char c in s) Add(c);
Add(0xFFFFFFFFu);
}
}

View file

@ -0,0 +1,196 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
namespace RynthCore.Plugin.RynthInventory.Data;
/// <summary>One inventory file as found on disk (for the change check and the reload).</summary>
internal readonly record struct InventoryFileStamp(string Path, long Length, DateTime WriteUtc);
/// <summary>
/// The files: &lt;root&gt;\&lt;server&gt;\&lt;account&gt;\&lt;character&gt;.json, root
/// %APPDATA%\RynthCore\inventory. Each client writes only its own character's file, through a
/// temp file in the same folder and an atomic replace (MoveFileEx REPLACE_EXISTING), so a
/// reader in another client sees the old file or the new one, never half of one. Readers open
/// with share read/write/delete so they never block a writer's replace.
/// </summary>
internal sealed class InventoryStore
{
public const string ForgottenFolder = "_forgotten";
public string Root { get; }
private static int _tmpSeq;
private const int MoveAttempts = 10;
public InventoryStore(string? root = null)
{
Root = root ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "inventory");
}
/// <summary>A name made safe for one path segment ("unknown" when empty).</summary>
public static string Segment(string? name)
{
string s = (name ?? string.Empty).Trim();
var sb = new StringBuilder(s.Length);
char[] bad = Path.GetInvalidFileNameChars();
foreach (char c in s)
sb.Append(Array.IndexOf(bad, c) >= 0 || c < 0x20 ? '_' : c);
string r = sb.ToString().Trim().TrimEnd('.', ' ');
if (r.Length == 0 || r == "." || r == "..") return "unknown";
if (r.Length > 64) r = r.Substring(0, 64);
string stem = r.Split('.')[0].ToUpperInvariant();
if (stem is "CON" or "PRN" or "AUX" or "NUL" || (stem.Length == 4 && (stem.StartsWith("COM") || stem.StartsWith("LPT")) && char.IsDigit(stem[3])))
r = "_" + r;
if (r.StartsWith("_forgotten", StringComparison.OrdinalIgnoreCase)) r = "-" + r;
return r;
}
public string PathFor(string server, string account, string character) =>
System.IO.Path.Combine(Root, Segment(server), Segment(account), Segment(character) + ".json");
/// <summary>Writes the snapshot to its file (atomic replace). Returns the path, or throws IOException.</summary>
public string Save(CharacterSnapshot s)
{
string path = PathFor(s.Server, s.Account, s.Character);
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!);
// Unique per process and per write, so two writes can never share a temp file.
string tmp = path + "." + Environment.ProcessId.ToString() + "." + Interlocked.Increment(ref _tmpSeq).ToString() + ".tmp";
byte[] bytes = new UTF8Encoding(false).GetBytes(InventoryJson.Write(s));
using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None))
{
fs.Write(bytes, 0, bytes.Length);
fs.Flush(flushToDisk: true);
}
// Windows refuses to replace a file another process has open at that instant (a
// reader in another client): try again for up to about a quarter of a second, then
// give up until the next save. Runs on a worker, except the final save at logout.
for (int attempt = 1; ; attempt++)
{
try
{
File.Move(tmp, path, overwrite: true);
break;
}
catch (Exception ex) when ((ex is IOException || ex is UnauthorizedAccessException) && attempt < MoveAttempts)
{
Thread.Sleep(5 * attempt);
}
catch
{
try { File.Delete(tmp); } catch { }
throw;
}
}
s.FilePath = path;
return path;
}
/// <summary>Reads one file. Null (with a reason) when missing, unreadable or not ours.</summary>
public static CharacterSnapshot? Load(string path, out string? error)
{
error = null;
try
{
string text;
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
using (var reader = new StreamReader(fs, Encoding.UTF8, detectEncodingFromByteOrderMarks: true))
text = reader.ReadToEnd();
CharacterSnapshot? s = InventoryJson.Read(text, out error);
if (s != null) s.FilePath = path;
return s;
}
catch (FileNotFoundException) { error = "missing"; return null; }
catch (DirectoryNotFoundException) { error = "missing"; return null; }
catch (Exception ex) { error = ex.GetType().Name + ": " + ex.Message; return null; }
}
/// <summary>Every character file under the root (server\account\character.json), forgotten ones excluded.</summary>
public List<InventoryFileStamp> ListFiles()
{
var list = new List<InventoryFileStamp>();
try
{
if (!Directory.Exists(Root)) return list;
foreach (string serverDir in Directory.EnumerateDirectories(Root))
{
if (System.IO.Path.GetFileName(serverDir).Equals(ForgottenFolder, StringComparison.OrdinalIgnoreCase)) continue;
foreach (string accountDir in SafeDirs(serverDir))
{
foreach (string file in SafeFiles(accountDir))
{
try
{
var fi = new FileInfo(file);
list.Add(new InventoryFileStamp(file, fi.Length, fi.LastWriteTimeUtc));
}
catch { }
}
}
}
}
catch { }
list.Sort((a, b) => string.CompareOrdinal(a.Path, b.Path));
return list;
}
private static IEnumerable<string> SafeDirs(string dir)
{
try { return Directory.GetDirectories(dir); }
catch { return Array.Empty<string>(); }
}
private static IEnumerable<string> SafeFiles(string dir)
{
try { return Directory.GetFiles(dir, "*.json"); }
catch { return Array.Empty<string>(); }
}
/// <summary>Loads every file. Broken ones are skipped and counted.</summary>
public List<CharacterSnapshot> LoadAll(out int broken)
{
broken = 0;
var result = new List<CharacterSnapshot>();
foreach (InventoryFileStamp f in ListFiles())
{
CharacterSnapshot? s = Load(f.Path, out _);
if (s != null) result.Add(s);
else broken++;
}
return result;
}
/// <summary>
/// Forgets a character: its file moves to &lt;root&gt;\_forgotten\... (kept, not deleted,
/// so a mistake can be undone by moving it back). True when it moved.
/// </summary>
public bool Forget(string filePath, out string? error)
{
error = null;
try
{
string full = System.IO.Path.GetFullPath(filePath);
string root = System.IO.Path.GetFullPath(Root).TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar;
if (!full.StartsWith(root, StringComparison.OrdinalIgnoreCase))
{
error = "not an inventory file";
return false;
}
if (!File.Exists(full))
{
error = "already gone";
return false;
}
string dest = System.IO.Path.Combine(Root, ForgottenFolder, full.Substring(root.Length));
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(dest)!);
File.Move(full, dest, overwrite: true);
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
}

View file

@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthInventory.Data;
/// <summary>The category filter groups. Stored by name in the files.</summary>
internal static class ItemCategory
{
public const string Weapon = "weapon";
public const string Armor = "armor";
public const string Clothing = "clothing";
public const string Jewelry = "jewelry";
public const string Caster = "caster";
public const string Salvage = "salvage";
public const string Components = "components";
public const string Gem = "gem";
public const string ManaStone = "manastone";
public const string Money = "money";
public const string Key = "key";
public const string Food = "food";
public const string Container = "container";
public const string Crafting = "crafting";
public const string Misc = "misc";
/// <summary>Filter order and labels.</summary>
public static readonly (string Id, string Label)[] All =
{
(Weapon, "Weapons"), (Caster, "Casters"), (Armor, "Armor"), (Clothing, "Clothing"), (Jewelry, "Jewelry"),
(Salvage, "Salvage"), (Components, "Spell components"), (Gem, "Gems"), (ManaStone, "Mana stones"),
(Money, "Money and notes"), (Key, "Keys"), (Food, "Food"), (Container, "Packs"), (Crafting, "Crafting"),
(Misc, "Misc"),
};
public static string Label(string id)
{
foreach (var (i, l) in All) if (i == id) return l;
return "Misc";
}
// AC ItemType flags (STypeInt 1).
private const uint MeleeWeapon = 0x00000001, ArmorT = 0x00000002, ClothingT = 0x00000004, JewelryT = 0x00000008,
FoodT = 0x00000020, MoneyT = 0x00000040, MissileWeapon = 0x00000100, ContainerT = 0x00000200,
GemT = 0x00000800, SpellComponents = 0x00001000, KeyT = 0x00004000, CasterT = 0x00008000,
PromissoryNote = 0x00040000, ManaStoneT = 0x00080000, CraftCookingBase = 0x00400000,
CraftAlchemyBase = 0x00800000, CraftFletchingBase = 0x02000000, CraftAlchemyIntermediate = 0x04000000,
CraftFletchingIntermediate = 0x08000000, TinkeringTool = 0x20000000, TinkeringMaterial = 0x40000000;
public const uint ContainerFlag = ContainerT;
/// <summary>The category for an ItemType, most specific flag first (the order RynthAi classifies in).</summary>
public static string FromItemType(uint t)
{
if ((t & PromissoryNote) != 0) return Money;
if ((t & ManaStoneT) != 0) return ManaStone;
if ((t & SpellComponents) != 0) return Components;
if ((t & GemT) != 0) return Gem;
if ((t & KeyT) != 0) return Key;
if ((t & TinkeringMaterial) != 0) return Salvage;
if ((t & (TinkeringTool | CraftCookingBase | CraftAlchemyBase | CraftFletchingBase
| CraftAlchemyIntermediate | CraftFletchingIntermediate)) != 0) return Crafting;
if ((t & ContainerT) != 0) return Container;
if ((t & CasterT) != 0) return Caster;
if ((t & (MissileWeapon | MeleeWeapon)) != 0) return Weapon;
if ((t & ArmorT) != 0) return Armor;
if ((t & ClothingT) != 0) return Clothing;
if ((t & JewelryT) != 0) return Jewelry;
if ((t & FoodT) != 0) return Food;
if ((t & MoneyT) != 0) return Money;
return Misc;
}
}
/// <summary>Names for equip slots, materials and armor sets.</summary>
internal static class ItemNames
{
private static readonly (uint Bit, string Name)[] SlotBits =
{
(0x00000001, "Head"), (0x00000002, "Chest (shirt)"), (0x00000004, "Abdomen (pants)"),
(0x00000008, "Upper arms (shirt)"), (0x00000010, "Lower arms (shirt)"), (0x00000020, "Hands"),
(0x00000040, "Upper legs (pants)"), (0x00000080, "Lower legs (pants)"), (0x00000100, "Feet"),
(0x00000200, "Chest"), (0x00000400, "Abdomen"), (0x00000800, "Upper arms"), (0x00001000, "Lower arms"),
(0x00002000, "Upper legs"), (0x00004000, "Lower legs"), (0x00008000, "Neck"),
(0x00010000, "Left wrist"), (0x00020000, "Right wrist"), (0x00040000, "Left ring"), (0x00080000, "Right ring"),
(0x00100000, "Melee weapon"), (0x00200000, "Shield"), (0x00400000, "Missile weapon"), (0x00800000, "Ammunition"),
(0x01000000, "Held"), (0x02000000, "Two-handed"), (0x04000000, "Trinket"), (0x08000000, "Cloak"),
(0x10000000, "Blue aetheria"), (0x20000000, "Yellow aetheria"), (0x40000000, "Red aetheria"),
};
/// <summary>"Chest, Upper arms" for a multi-slot piece; "" for 0.</summary>
public static string Slot(uint mask)
{
if (mask == 0) return string.Empty;
var sb = new StringBuilder();
foreach (var (bit, name) in SlotBits)
{
if ((mask & bit) == 0) continue;
if (sb.Length > 0) sb.Append(", ");
sb.Append(name);
}
return sb.Length > 0 ? sb.ToString() : "0x" + mask.ToString("X");
}
private static readonly Dictionary<int, string> Materials = new()
{
{ 1, "Ceramic" }, { 2, "Porcelain" }, { 3, "Cloth" }, { 4, "Linen" }, { 5, "Satin" }, { 6, "Silk" },
{ 7, "Velvet" }, { 8, "Wool" }, { 9, "Gem" }, { 10, "Agate" }, { 11, "Amber" }, { 12, "Amethyst" },
{ 13, "Aquamarine" }, { 14, "Azurite" }, { 15, "Black Garnet" }, { 16, "Black Opal" }, { 17, "Bloodstone" },
{ 18, "Carnelian" }, { 19, "Citrine" }, { 20, "Diamond" }, { 21, "Emerald" }, { 22, "Fire Opal" },
{ 23, "Green Garnet" }, { 24, "Green Jade" }, { 25, "Hematite" }, { 26, "Imperial Topaz" }, { 27, "Jet" },
{ 28, "Lapis Lazuli" }, { 29, "Lavender Jade" }, { 30, "Malachite" }, { 31, "Moonstone" }, { 32, "Onyx" },
{ 33, "Opal" }, { 34, "Peridot" }, { 35, "Red Garnet" }, { 36, "Red Jade" }, { 37, "Rose Quartz" },
{ 38, "Ruby" }, { 39, "Sapphire" }, { 40, "Smoky Quartz" }, { 41, "Sunstone" }, { 42, "Tiger Eye" },
{ 43, "Tourmaline" }, { 44, "Turquoise" }, { 45, "White Jade" }, { 46, "White Quartz" },
{ 47, "White Sapphire" }, { 48, "Yellow Garnet" }, { 49, "Yellow Topaz" }, { 50, "Zircon" }, { 51, "Ivory" },
{ 52, "Leather" }, { 53, "Armoredillo Hide" }, { 54, "Gromnie Hide" }, { 55, "Reedshark Hide" },
{ 56, "Metal" }, { 57, "Brass" }, { 58, "Bronze" }, { 59, "Copper" }, { 60, "Gold" }, { 61, "Iron" },
{ 62, "Pyreal" }, { 63, "Silver" }, { 64, "Steel" }, { 65, "Stone" }, { 66, "Alabaster" }, { 67, "Granite" },
{ 68, "Marble" }, { 69, "Obsidian" }, { 70, "Sandstone" }, { 71, "Serpentine" }, { 72, "Wood" },
{ 73, "Ebony" }, { 74, "Mahogany" }, { 75, "Oak" }, { 76, "Pine" }, { 77, "Teak" },
};
public static string Material(int id) => id <= 0 ? string.Empty : Materials.TryGetValue(id, out string? n) ? n : $"Material {id}";
// Only the sets whose ids are certain (loot armor sets and Aetheria); others show their number.
private static readonly Dictionary<int, string> Sets = new()
{
{ 13, "Soldier's" }, { 14, "Adept's" }, { 15, "Archer's" }, { 16, "Defender's" }, { 17, "Tinker's" },
{ 18, "Crafter's" }, { 19, "Hearty" }, { 20, "Dexterous" }, { 21, "Wise" }, { 22, "Swift" },
{ 23, "Hardened" }, { 24, "Reinforced" }, { 25, "Interlocking" }, { 26, "Flame Proof" },
{ 27, "Acid Proof" }, { 28, "Cold Proof" }, { 29, "Lightning Proof" },
{ 35, "Aetheria: Defense" }, { 36, "Aetheria: Destruction" }, { 37, "Aetheria: Fury" },
{ 38, "Aetheria: Growth" }, { 39, "Aetheria: Vigor" },
};
public static string Set(int id) => id <= 0 ? string.Empty : Sets.TryGetValue(id, out string? n) ? n + " set" : $"Set {id}";
}