RynthSuite as of 2026-10-04 (internal c94715f): RynthOracle (based on Oracle of Dereth by Advis Eveldan) and RynthInventory, RynthAi patrol doorways and rooms, healing priority, strict monster priority, finish the wounded target, slayer weapons, arcs when clear, blasts like rings, learn unknown spells, looting fixes, release 2026.10.4.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c33e24a610
commit
12ca25f911
426 changed files with 108239 additions and 7521 deletions
333
Plugins/RynthCore.Plugin.RynthInventory/Data/InventoryIndex.cs
Normal file
333
Plugins/RynthCore.Plugin.RynthInventory/Data/InventoryIndex.cs
Normal 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";
|
||||
}
|
||||
}
|
||||
299
Plugins/RynthCore.Plugin.RynthInventory/Data/InventoryJson.cs
Normal file
299
Plugins/RynthCore.Plugin.RynthInventory/Data/InventoryJson.cs
Normal 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();
|
||||
}
|
||||
}
|
||||
164
Plugins/RynthCore.Plugin.RynthInventory/Data/InventoryModel.cs
Normal file
164
Plugins/RynthCore.Plugin.RynthInventory/Data/InventoryModel.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
196
Plugins/RynthCore.Plugin.RynthInventory/Data/InventoryStore.cs
Normal file
196
Plugins/RynthCore.Plugin.RynthInventory/Data/InventoryStore.cs
Normal 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: <root>\<server>\<account>\<character>.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 <root>\_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;
|
||||
}
|
||||
}
|
||||
}
|
||||
137
Plugins/RynthCore.Plugin.RynthInventory/Data/ItemNames.cs
Normal file
137
Plugins/RynthCore.Plugin.RynthInventory/Data/ItemNames.cs
Normal 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}";
|
||||
}
|
||||
48
Plugins/RynthCore.Plugin.RynthInventory/InventoryContext.cs
Normal file
48
Plugins/RynthCore.Plugin.RynthInventory/InventoryContext.cs
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthInventory.Data;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthInventory;
|
||||
|
||||
/// <summary>What the window reads and the actions it can take. Plugin pump thread only.</summary>
|
||||
internal sealed class InventoryContext
|
||||
{
|
||||
public RynthCoreHost Host;
|
||||
public readonly InventorySettings Settings = new();
|
||||
public InventoryStore Store = new();
|
||||
|
||||
/// <summary>The merged view of every file (and this client's live snapshot); null until first built.</summary>
|
||||
public InventoryIndex? Index;
|
||||
/// <summary>Bumped whenever <see cref="Index"/> is replaced.</summary>
|
||||
public int IndexRevision;
|
||||
public int BrokenFiles;
|
||||
public bool Loading;
|
||||
|
||||
public bool InWorld;
|
||||
public uint Player;
|
||||
public string Server = string.Empty;
|
||||
public string Account = string.Empty;
|
||||
public string Character = string.Empty;
|
||||
/// <summary>This character's latest snapshot (never changed once published; a change makes a new one).</summary>
|
||||
public CharacterSnapshot? Live;
|
||||
public DateTime LastSavedUtc;
|
||||
public string LastSaveError = string.Empty;
|
||||
/// <summary>The storage container open right now, if it is being recorded (0 none).</summary>
|
||||
public uint OpenStorage;
|
||||
public string OpenStorageLabel = string.Empty;
|
||||
|
||||
/// <summary>The engine draws icons in script windows (op level 2).</summary>
|
||||
public bool IconsAvailable;
|
||||
public DateTime UtcNow;
|
||||
|
||||
public Action RequestRescan = () => { };
|
||||
public Action RequestReload = () => { };
|
||||
/// <summary>Forgets a character (moves its file aside). Returns a message for the player.</summary>
|
||||
public Func<CharacterInfo, string> Forget = _ => string.Empty;
|
||||
|
||||
public void Print(string text)
|
||||
{
|
||||
if (!Host.WriteToChat("[RynthInventory] " + text, 1))
|
||||
Host.Log("[RynthInventory] " + text);
|
||||
}
|
||||
}
|
||||
146
Plugins/RynthCore.Plugin.RynthInventory/InventorySettings.cs
Normal file
146
Plugins/RynthCore.Plugin.RynthInventory/InventorySettings.cs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthInventory.Data;
|
||||
|
||||
namespace RynthCore.Plugin.RynthInventory;
|
||||
|
||||
/// <summary>
|
||||
/// RynthInventory's settings, in %APPDATA%\RynthCore\rynthinventory.json. Written by hand and
|
||||
/// read with JsonDocument (plugin types never go through System.Text.Json's serializer, which
|
||||
/// roots them across hot reloads). Shared by every client; each re-reads it at login.
|
||||
/// </summary>
|
||||
internal sealed class InventorySettings
|
||||
{
|
||||
public bool MainWindowOpen;
|
||||
/// <summary>A snapshot older than this many days is shown as stale.</summary>
|
||||
public int StaleDays = 7;
|
||||
/// <summary>An opened container whose name holds one of these words is recorded as storage (house storage always is).</summary>
|
||||
public string StorageWords = "storage, vault, bank, locker, stash";
|
||||
/// <summary>Containers recorded with /ginv keep: "server|objectId".</summary>
|
||||
public List<string> KeptStorage = new();
|
||||
public bool SearchSpells;
|
||||
public bool IncludeStorage = true;
|
||||
public bool IncludeEquipped = true;
|
||||
public bool GroupByName;
|
||||
public int Sort;
|
||||
public bool Descending;
|
||||
public bool ShowIcons = true;
|
||||
|
||||
/// <summary>Tests point this at a scratch file so they never touch the real settings.</summary>
|
||||
internal static string? PathOverride { get; set; }
|
||||
|
||||
private static string FilePath => PathOverride ?? Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthinventory.json");
|
||||
|
||||
public string[] StorageWordList()
|
||||
{
|
||||
var list = new List<string>();
|
||||
foreach (string w in StorageWords.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
string t = w.Trim().ToLowerInvariant();
|
||||
if (t.Length > 0) list.Add(t);
|
||||
}
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
public bool IsKept(string server, uint id) => KeptStorage.Contains(KeepKey(server, id));
|
||||
|
||||
public static string KeepKey(string server, uint id) =>
|
||||
server.Trim().ToLowerInvariant() + "|" + id.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
public void Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath)) return;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(FilePath));
|
||||
JsonElement r = doc.RootElement;
|
||||
if (r.ValueKind != JsonValueKind.Object) return;
|
||||
MainWindowOpen = Bool(r, "mainWindowOpen", MainWindowOpen);
|
||||
StaleDays = Math.Clamp(Int(r, "staleDays", StaleDays), 1, 3650);
|
||||
if (r.TryGetProperty("storageWords", out JsonElement sw) && sw.ValueKind == JsonValueKind.String)
|
||||
StorageWords = sw.GetString() ?? StorageWords;
|
||||
if (r.TryGetProperty("keptStorage", out JsonElement ks) && ks.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
KeptStorage.Clear();
|
||||
foreach (JsonElement e in ks.EnumerateArray())
|
||||
if (e.ValueKind == JsonValueKind.String && e.GetString() is string k && k.Length > 0) KeptStorage.Add(k);
|
||||
}
|
||||
SearchSpells = Bool(r, "searchSpells", SearchSpells);
|
||||
IncludeStorage = Bool(r, "includeStorage", IncludeStorage);
|
||||
IncludeEquipped = Bool(r, "includeEquipped", IncludeEquipped);
|
||||
GroupByName = Bool(r, "groupByName", GroupByName);
|
||||
Sort = Int(r, "sort", Sort);
|
||||
Descending = Bool(r, "descending", Descending);
|
||||
ShowIcons = Bool(r, "showIcons", ShowIcons);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A broken file means defaults; the next save rewrites it.
|
||||
}
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Every client shares this file: keep containers another client added with /ginv keep.
|
||||
try
|
||||
{
|
||||
if (File.Exists(FilePath))
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(FilePath));
|
||||
if (doc.RootElement.ValueKind == JsonValueKind.Object
|
||||
&& doc.RootElement.TryGetProperty("keptStorage", out JsonElement ks) && ks.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement e in ks.EnumerateArray())
|
||||
if (e.ValueKind == JsonValueKind.String && e.GetString() is string k && k.Length > 0 && !KeptStorage.Contains(k))
|
||||
KeptStorage.Add(k);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("{\n");
|
||||
sb.Append(" \"mainWindowOpen\": ").Append(B(MainWindowOpen)).Append(",\n");
|
||||
sb.Append(" \"staleDays\": ").Append(StaleDays.ToString(CultureInfo.InvariantCulture)).Append(",\n");
|
||||
sb.Append(" \"storageWords\": "); InventoryJson.Str(sb, StorageWords); sb.Append(",\n");
|
||||
sb.Append(" \"keptStorage\": [");
|
||||
for (int i = 0; i < KeptStorage.Count; i++)
|
||||
{
|
||||
if (i > 0) sb.Append(", ");
|
||||
InventoryJson.Str(sb, KeptStorage[i]);
|
||||
}
|
||||
sb.Append("],\n");
|
||||
sb.Append(" \"searchSpells\": ").Append(B(SearchSpells)).Append(",\n");
|
||||
sb.Append(" \"includeStorage\": ").Append(B(IncludeStorage)).Append(",\n");
|
||||
sb.Append(" \"includeEquipped\": ").Append(B(IncludeEquipped)).Append(",\n");
|
||||
sb.Append(" \"groupByName\": ").Append(B(GroupByName)).Append(",\n");
|
||||
sb.Append(" \"sort\": ").Append(Sort.ToString(CultureInfo.InvariantCulture)).Append(",\n");
|
||||
sb.Append(" \"descending\": ").Append(B(Descending)).Append(",\n");
|
||||
sb.Append(" \"showIcons\": ").Append(B(ShowIcons)).Append('\n');
|
||||
sb.Append("}\n");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
|
||||
string tmp = FilePath + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
|
||||
File.WriteAllText(tmp, sb.ToString());
|
||||
File.Move(tmp, FilePath, overwrite: true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Settings are a convenience; a failed write keeps the old file.
|
||||
}
|
||||
}
|
||||
|
||||
private static string B(bool v) => v ? "true" : "false";
|
||||
|
||||
private static bool Bool(JsonElement r, string name, bool fallback) =>
|
||||
r.TryGetProperty(name, out JsonElement v) && (v.ValueKind == JsonValueKind.True || v.ValueKind == JsonValueKind.False)
|
||||
? v.GetBoolean()
|
||||
: fallback;
|
||||
|
||||
private static int Int(JsonElement r, string name, int fallback) =>
|
||||
r.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback;
|
||||
}
|
||||
66
Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs
Normal file
66
Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthInventory;
|
||||
|
||||
/// <summary>
|
||||
/// C ABI exports. Nothing may throw out of an [UnmanagedCallersOnly] method (it would take
|
||||
/// acclient.exe down): every export goes through RynthPluginRuntime, which catches and logs.
|
||||
/// RynthInventory draws through the engine's script windows (host calls from its own tick),
|
||||
/// so it exports no render callback and keeps no buffer the engine reads later.
|
||||
/// </summary>
|
||||
public static unsafe class PluginExports
|
||||
{
|
||||
private static readonly RynthPluginRuntime<RynthInventoryPlugin> Runtime = new();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void Shutdown() => Runtime.Shutdown();
|
||||
|
||||
// UTF-8 literals live in the module's read-only data: nothing to allocate or free.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetName() => LiteralPointer("RynthInventory"u8);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8);
|
||||
|
||||
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
|
||||
{
|
||||
fixed (byte* p = literal)
|
||||
return (IntPtr)p;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void Tick() => Runtime.OnTick();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnLoginComplete() => Runtime.OnLoginComplete();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnLogout() => Runtime.OnLogout();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
|
||||
|
||||
// Inventory change triggers (the scan's poll catches the rest, e.g. moves from a corpse).
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObjectInventory", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnUpdateObjectInventory(uint objectId) => Runtime.OnUpdateObjectInventory(objectId);
|
||||
|
||||
// Storage: a container opened (house storage, a bank...) and closed again.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnViewObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnViewObjectContents(uint objectId) => Runtime.OnViewObjectContents(objectId);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnStopViewingObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnStopViewingObjectContents(uint objectId) => Runtime.OnStopViewingObjectContents(objectId);
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
RynthInventory: a searchable inventory across every character on every server (like
|
||||
Virindi Global Inventory). Each client scans its own character and writes one JSON file
|
||||
per character per server under %APPDATA%\RynthCore\inventory; the /ginv window merges
|
||||
all of them. UI: the engine's script windows (ImGui), no Avalonia.
|
||||
-->
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
|
||||
<OutputType>Library</OutputType>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>enable</Nullable>
|
||||
<PublishAot>true</PublishAot>
|
||||
<NativeLib>Shared</NativeLib>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
|
||||
<StripSymbols>false</StripSymbols>
|
||||
<RootNamespace>RynthCore.Plugin.RynthInventory</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthInventory</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Spell names for item spells: RynthAi's spell table, shared rather than copied. -->
|
||||
<EmbeddedResource Include="..\RynthCore.Plugin.RynthAi\Combat\SpellData.txt" LogicalName="RynthInventory.SpellData.txt" Link="Shared\SpellData.txt" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
673
Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs
Normal file
673
Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs
Normal file
|
|
@ -0,0 +1,673 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using RynthCore.Plugin.RynthInventory.Data;
|
||||
using RynthCore.Plugin.RynthInventory.Scanning;
|
||||
using RynthCore.Plugin.RynthInventory.Ui;
|
||||
using RynthCore.Plugin.RynthInventory.Views;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthInventory;
|
||||
|
||||
/// <summary>
|
||||
/// RynthInventory: a searchable inventory across all of a player's characters on every server
|
||||
/// (like Virindi Global Inventory). Each client scans the character it is logged into (a full
|
||||
/// scan after login, then whenever the inventory changes, debounced) and writes one file per
|
||||
/// character per server; storage the character opens (house storage, banks, vaults) is
|
||||
/// recorded when it is opened. /ginv opens a window that merges every file.
|
||||
///
|
||||
/// Everything runs on the plugin pump (OnTick and the events the engine drains into it)
|
||||
/// except OnChatBarEnter, which the engine may call on AC's thread: it only queues the
|
||||
/// command. File reads for the merged view and file writes run on worker tasks; they touch
|
||||
/// no game state.
|
||||
/// </summary>
|
||||
public sealed class RynthInventoryPlugin : RynthPluginBase
|
||||
{
|
||||
public const string Version = "0.1.0";
|
||||
|
||||
private const long IdentityRetryMs = 1000;
|
||||
private const long AccountWaitMs = 15_000;
|
||||
private const long FileCheckMs = 5000;
|
||||
private const long StorageFirstScanMs = 700;
|
||||
private const long StorageRescanMs = 3000;
|
||||
private const long StorageSettleScans = 3;
|
||||
/// <summary>An online character's file is rewritten at least this often, so its "scanned" time stays honest.</summary>
|
||||
private const long RefreshWriteMs = 10 * 60_000;
|
||||
/// <summary>Within this long after login an empty scan means "not loaded yet", never "owns nothing".</summary>
|
||||
private const long EmptyScanGraceMs = 90_000;
|
||||
|
||||
private readonly InventoryContext _c = new();
|
||||
private readonly InventoryScanner _scanner = new();
|
||||
private readonly ScanScheduler _scheduler = new();
|
||||
private readonly UiHost _ui = new();
|
||||
private UiWindow? _window;
|
||||
private InventoryView? _view;
|
||||
private readonly ConcurrentQueue<string> _commands = new();
|
||||
|
||||
private bool _identityKnown;
|
||||
private long _loginMs;
|
||||
private long _nextIdentityTryMs;
|
||||
private bool _noUiLogged;
|
||||
private bool _oldAccountChecked;
|
||||
private bool _forceWrite;
|
||||
|
||||
// Write in flight (one at a time).
|
||||
private Task? _writeTask;
|
||||
private long _lastWriteMs;
|
||||
|
||||
// Storage being watched.
|
||||
private uint _lastViewed;
|
||||
private uint _openStorage;
|
||||
private string _openStorageName = string.Empty;
|
||||
private string _openStorageLabel = string.Empty;
|
||||
private uint _openStorageCell;
|
||||
private long _nextStorageScanMs;
|
||||
private int _storageScans;
|
||||
|
||||
// Merged view: files parsed once and re-read only when they change.
|
||||
private Dictionary<string, (InventoryFileStamp Stamp, CharacterSnapshot? Snapshot)> _files = new(StringComparer.OrdinalIgnoreCase);
|
||||
private Task<(Dictionary<string, (InventoryFileStamp, CharacterSnapshot?)> Files, int Broken)>? _loadTask;
|
||||
private long _nextFileCheckMs;
|
||||
private bool _indexDirty = true;
|
||||
private bool _reloadWanted = true;
|
||||
|
||||
public override int Initialize()
|
||||
{
|
||||
_c.Host = Host;
|
||||
_c.Settings.Load();
|
||||
_c.RequestRescan = () => { _scheduler.RequestFullScan(); _forceWrite = true; };
|
||||
_c.RequestReload = () => { _reloadWanted = true; _files.Clear(); };
|
||||
_c.Forget = ForgetCharacter;
|
||||
_ui.Log = msg => Host.Log(msg);
|
||||
|
||||
_view = new InventoryView(_c);
|
||||
_window = _ui.Add(new UiWindow("RynthInventory/Main", "Global Inventory")
|
||||
{
|
||||
DefaultWidth = 640f, DefaultHeight = 600f, MinWidth = 420f, MinHeight = 300f,
|
||||
});
|
||||
|
||||
Host.Log($"[RynthInventory] {Version} initialized. /ginv opens the window. Files: {_c.Store.Root}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The engine calls this on a real login and on a freshly (re)loaded plugin already in game.
|
||||
public override void OnLoginComplete()
|
||||
{
|
||||
_c.InWorld = true;
|
||||
_c.Settings.Load();
|
||||
_identityKnown = false;
|
||||
_oldAccountChecked = false;
|
||||
_loginMs = Environment.TickCount64;
|
||||
_nextIdentityTryMs = _loginMs;
|
||||
_c.Live = null;
|
||||
_c.LastSavedUtc = default;
|
||||
_c.LastSaveError = string.Empty;
|
||||
_scanner.Reset();
|
||||
CloseStorage();
|
||||
_lastViewed = 0;
|
||||
_lastWriteMs = 0;
|
||||
_carriedIds.Clear();
|
||||
_carriedPacks.Clear();
|
||||
RefreshIconSupport();
|
||||
if (_window != null) { _window.Visible = _c.Settings.MainWindowOpen; _window.NeedsPass = true; }
|
||||
}
|
||||
|
||||
public override void OnLogout()
|
||||
{
|
||||
// Last word for this character: write what it has now (also refreshes its "scanned" time).
|
||||
FlushNow(final: true);
|
||||
_c.InWorld = false;
|
||||
_identityKnown = false;
|
||||
_scheduler.Logout();
|
||||
CloseStorage();
|
||||
if (_window != null) { _window.Visible = false; _window.NeedsPass = true; }
|
||||
_ui.SubmitEmpty(Host);
|
||||
_c.Live = null;
|
||||
_indexDirty = true;
|
||||
}
|
||||
|
||||
public override void Shutdown()
|
||||
{
|
||||
FlushNow(final: true);
|
||||
_ui.SubmitEmpty(Host);
|
||||
try { _loadTask?.Wait(2000); } catch { }
|
||||
}
|
||||
|
||||
// ── Events (pump thread) ────────────────────────────────────────────────
|
||||
|
||||
public override void OnCreateObject(uint objectId)
|
||||
{
|
||||
if (!_identityKnown || _c.Player == 0) return;
|
||||
// Only objects that landed in the character's inventory matter (most creates are the landscape).
|
||||
if (Host.TryGetObjectOwnershipInfo(objectId, out uint container, out uint wielder, out _)
|
||||
&& (container == _c.Player || wielder == _c.Player || IsCarriedPack(container)))
|
||||
_scheduler.InventoryEvent(Environment.TickCount64);
|
||||
}
|
||||
|
||||
public override void OnDeleteObject(uint objectId)
|
||||
{
|
||||
if (!_identityKnown) return;
|
||||
if (_carriedIds.Contains(objectId)) _scheduler.InventoryEvent(Environment.TickCount64);
|
||||
}
|
||||
|
||||
public override void OnUpdateObjectInventory(uint objectId)
|
||||
{
|
||||
if (!_identityKnown) return;
|
||||
long now = Environment.TickCount64;
|
||||
if (objectId == _openStorage && _openStorage != 0)
|
||||
_nextStorageScanMs = Math.Min(_nextStorageScanMs, now + 300);
|
||||
else if (objectId == _c.Player || IsCarriedPack(objectId))
|
||||
_scheduler.InventoryEvent(now);
|
||||
}
|
||||
|
||||
public override void OnViewObjectContents(uint objectId)
|
||||
{
|
||||
if (!_identityKnown || objectId == 0) return;
|
||||
_lastViewed = objectId;
|
||||
bool kept = _c.Settings.IsKept(_c.Server, objectId);
|
||||
if (!InventoryScanner.IsStorage(Host, objectId, _c.Player, _c.Settings.StorageWordList(), kept, out string name, out string why))
|
||||
{
|
||||
if (why == "carried") _scheduler.InventoryEvent(Environment.TickCount64);
|
||||
return;
|
||||
}
|
||||
BeginStorage(objectId, name, why);
|
||||
}
|
||||
|
||||
public override void OnStopViewingObjectContents(uint objectId)
|
||||
{
|
||||
if (objectId != 0 && objectId == _openStorage)
|
||||
{
|
||||
ScanStorage(Environment.TickCount64, final: true);
|
||||
CloseStorage();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Chat ────────────────────────────────────────────────────────────────
|
||||
|
||||
// May run on AC's thread: classify and queue only.
|
||||
public override void OnChatBarEnter(string? text, ref int eat)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return;
|
||||
string t = text.Trim();
|
||||
if (!t.StartsWith("/ginv", StringComparison.OrdinalIgnoreCase) || (t.Length > 5 && !char.IsWhiteSpace(t[5])))
|
||||
return;
|
||||
eat = 1;
|
||||
_commands.Enqueue(t.Length > 5 ? t.Substring(5).Trim() : string.Empty);
|
||||
}
|
||||
|
||||
private void RunCommand(string arg)
|
||||
{
|
||||
string lower = arg.ToLowerInvariant();
|
||||
switch (lower)
|
||||
{
|
||||
case "":
|
||||
if (_window != null) { _window.Visible = !_window.Visible; _window.NeedsPass = true; }
|
||||
break;
|
||||
case "scan":
|
||||
case "rescan":
|
||||
_scheduler.RequestFullScan();
|
||||
_forceWrite = true;
|
||||
_c.Print("Rescanning this character; it saves within a few seconds.");
|
||||
break;
|
||||
case "keep":
|
||||
KeepOpenContainer();
|
||||
break;
|
||||
case "reload":
|
||||
_reloadWanted = true;
|
||||
_files.Clear();
|
||||
_c.Print("Reading the inventory files again.");
|
||||
break;
|
||||
case "status":
|
||||
PrintStatus();
|
||||
break;
|
||||
case "help":
|
||||
case "?":
|
||||
_c.Print("/ginv (window), /ginv <text> (search), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv reload, /ginv status");
|
||||
break;
|
||||
default:
|
||||
_view?.SetSearch(arg);
|
||||
if (_window != null) { _window.Visible = true; _window.NeedsPass = true; }
|
||||
break;
|
||||
}
|
||||
if (_window != null && _window.Visible && !Host.HasUi && !_noUiLogged)
|
||||
{
|
||||
_noUiLogged = true;
|
||||
_c.Print("This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Scanning and saving still work; /ginv status shows what was saved.");
|
||||
}
|
||||
}
|
||||
|
||||
private void PrintStatus()
|
||||
{
|
||||
string who = _identityKnown ? $"{_c.Character} on {_c.Server} (account {_c.Account})" : "no character yet";
|
||||
int items = _c.Live?.Items.Count ?? 0, storage = _c.Live?.Storage.Count ?? 0;
|
||||
string saved = _c.LastSavedUtc == default ? "not saved yet" : "saved " + InventoryIndex.Age(_c.LastSavedUtc, DateTime.UtcNow);
|
||||
_c.Print($"{who}: {items} items carried, {storage} storage container(s), {saved}. {_c.Index?.Characters.Count ?? 0} characters in {_c.Store.Root}.");
|
||||
if (_c.LastSaveError.Length > 0) _c.Print("Last save failed: " + _c.LastSaveError);
|
||||
}
|
||||
|
||||
private void KeepOpenContainer()
|
||||
{
|
||||
if (!_identityKnown || _lastViewed == 0)
|
||||
{
|
||||
_c.Print("Open the container first, then type /ginv keep while it is open.");
|
||||
return;
|
||||
}
|
||||
string name = Host.TryGetObjectName(_lastViewed, out string n) ? n : "container";
|
||||
if (!InventoryScanner.IsStorage(Host, _lastViewed, _c.Player, Array.Empty<string>(), kept: true, out name, out string why))
|
||||
{
|
||||
_c.Print($"{name} can't be kept as storage ({why}).");
|
||||
return;
|
||||
}
|
||||
string key = InventorySettings.KeepKey(_c.Server, _lastViewed);
|
||||
if (!_c.Settings.KeptStorage.Contains(key))
|
||||
{
|
||||
_c.Settings.KeptStorage.Add(key);
|
||||
_c.Settings.Save();
|
||||
}
|
||||
_c.Print($"{name} will be recorded as storage whenever it is opened.");
|
||||
BeginStorage(_lastViewed, name, why);
|
||||
}
|
||||
|
||||
// ── Tick ────────────────────────────────────────────────────────────────
|
||||
|
||||
public override void OnTick()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
_c.UtcNow = DateTime.UtcNow;
|
||||
|
||||
while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd);
|
||||
_ui.Poll(Host);
|
||||
|
||||
if (_c.InWorld)
|
||||
{
|
||||
try { TickScan(now); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log($"[RynthInventory] scan failed: {ex.GetType().Name}: {ex.Message}");
|
||||
_scheduler.FullScanDone(now, _c.Live?.ContentHash() ?? 0, 0); // don't retry every tick
|
||||
}
|
||||
}
|
||||
TickWrite(now);
|
||||
TickIndex(now);
|
||||
|
||||
if (!Host.HasUi || _window == null || _view == null) return;
|
||||
Record(_window, now, 2000, _view.Draw);
|
||||
_ui.Submit(Host, now);
|
||||
|
||||
if (_c.InWorld && _window.Visible != _c.Settings.MainWindowOpen)
|
||||
{
|
||||
_c.Settings.MainWindowOpen = _window.Visible;
|
||||
_c.Settings.Save();
|
||||
}
|
||||
}
|
||||
|
||||
private void TickScan(long now)
|
||||
{
|
||||
if (!_identityKnown)
|
||||
{
|
||||
if (now < _nextIdentityTryMs) return;
|
||||
_nextIdentityTryMs = now + IdentityRetryMs;
|
||||
if (!InventoryScanner.TryReadIdentity(Host, out uint player, out string server, out string account, out string character))
|
||||
return;
|
||||
// The engine learns the account name on AC's thread during login; give it a moment
|
||||
// so the file lands in the account's folder rather than "unknown".
|
||||
if (account == "unknown" && now - _loginMs < AccountWaitMs)
|
||||
return;
|
||||
StartCharacter(now, player, server, account, character);
|
||||
}
|
||||
|
||||
_scanner.WarmUp(Host, _c.Player);
|
||||
if (_scheduler.ShouldFullScan(now))
|
||||
FullScan(now);
|
||||
else if (_scheduler.ShouldPoll(now))
|
||||
_scheduler.PollResult(now, _scanner.Fingerprint(Host, _c.Player));
|
||||
|
||||
if (_openStorage != 0 && now >= _nextStorageScanMs)
|
||||
ScanStorage(now, final: false);
|
||||
}
|
||||
|
||||
private void StartCharacter(long now, uint player, string server, string account, string character)
|
||||
{
|
||||
_identityKnown = true;
|
||||
_c.Player = player;
|
||||
_c.Server = server;
|
||||
_c.Account = account;
|
||||
_c.Character = character;
|
||||
_scheduler.Login(now);
|
||||
|
||||
// Start from this character's saved file: it keeps the storage seen on earlier visits.
|
||||
string path = _c.Store.PathFor(server, account, character);
|
||||
CharacterSnapshot? saved = InventoryStore.Load(path, out _);
|
||||
if (saved == null && account != "unknown")
|
||||
saved = InventoryStore.Load(_c.Store.PathFor(server, "unknown", character), out _);
|
||||
if (saved != null && InventoryIndex.SameName(saved.Character, character))
|
||||
{
|
||||
saved.Account = account;
|
||||
saved.CharacterId = player;
|
||||
_c.Live = saved;
|
||||
if (saved.FilePath == path) _scheduler.KnownSaved(saved.ContentHash());
|
||||
}
|
||||
_indexDirty = true;
|
||||
Host.Log($"[RynthInventory] tracking {character} on {server} (account {account}); file {path}");
|
||||
}
|
||||
|
||||
private readonly HashSet<uint> _carriedIds = new();
|
||||
private readonly HashSet<uint> _carriedPacks = new();
|
||||
|
||||
private bool IsCarriedPack(uint id) => id != 0 && _carriedPacks.Contains(id);
|
||||
|
||||
private void FullScan(long now)
|
||||
{
|
||||
List<ItemRecord> items = _scanner.ScanCarried(Host, _c.Player);
|
||||
ulong fingerprint = _scanner.Fingerprint(Host, _c.Player);
|
||||
if (items.Count == 0 && now - _loginMs < EmptyScanGraceMs)
|
||||
{
|
||||
// The client hasn't got the inventory yet; never save "owns nothing" for that.
|
||||
_scheduler.FullScanDone(now, _c.Live?.ContentHash() ?? 0, fingerprint);
|
||||
return;
|
||||
}
|
||||
|
||||
_carriedIds.Clear();
|
||||
_carriedPacks.Clear();
|
||||
foreach (ItemRecord it in items)
|
||||
{
|
||||
_carriedIds.Add(it.Id);
|
||||
if (it.Place == ItemPlace.Pack && it.Path.Length == 1 && it.Category == ItemCategory.Container) _carriedPacks.Add(it.Id);
|
||||
}
|
||||
|
||||
var snap = NewSnapshot(items, _c.Live?.Storage ?? new List<StorageRecord>());
|
||||
snap.ScannedUtc = DateTime.UtcNow;
|
||||
_c.Live = snap;
|
||||
_indexDirty = true;
|
||||
_scheduler.FullScanDone(now, snap.ContentHash(), fingerprint);
|
||||
}
|
||||
|
||||
private CharacterSnapshot NewSnapshot(List<ItemRecord> items, List<StorageRecord> storage) => new()
|
||||
{
|
||||
Server = _c.Server,
|
||||
Account = _c.Account,
|
||||
Character = _c.Character,
|
||||
CharacterId = _c.Player,
|
||||
ScannedUtc = _c.Live?.ScannedUtc ?? default,
|
||||
PluginVersion = Version,
|
||||
Items = items,
|
||||
Storage = new List<StorageRecord>(storage),
|
||||
};
|
||||
|
||||
// ── Storage ─────────────────────────────────────────────────────────────
|
||||
|
||||
private void BeginStorage(uint id, string name, string why)
|
||||
{
|
||||
_openStorage = id;
|
||||
_openStorageName = name;
|
||||
_openStorageLabel = InventoryScanner.StorageLabel(Host, id, name, out _openStorageCell);
|
||||
_storageScans = 0;
|
||||
_nextStorageScanMs = Environment.TickCount64 + StorageFirstScanMs;
|
||||
_c.OpenStorage = id;
|
||||
_c.OpenStorageLabel = _openStorageLabel;
|
||||
Host.Log($"[RynthInventory] recording {_openStorageLabel} (0x{id:X8}): {why}");
|
||||
}
|
||||
|
||||
private void CloseStorage()
|
||||
{
|
||||
_openStorage = 0;
|
||||
_c.OpenStorage = 0;
|
||||
_c.OpenStorageLabel = string.Empty;
|
||||
}
|
||||
|
||||
private void ScanStorage(long now, bool final)
|
||||
{
|
||||
if (_openStorage == 0 || _c.Live == null) { _nextStorageScanMs = now + StorageRescanMs; return; }
|
||||
List<ItemRecord> items = _scanner.ScanContainer(Host, _openStorage);
|
||||
_storageScans++;
|
||||
_nextStorageScanMs = now + (_storageScans < StorageSettleScans ? 1500 : StorageRescanMs);
|
||||
// Contents arrive a moment after the container opens, and are gone right after it
|
||||
// closes: an empty read is only believed once the container has been open a while.
|
||||
if (items.Count == 0 && (final || _storageScans < StorageSettleScans)) return;
|
||||
|
||||
var record = new StorageRecord
|
||||
{
|
||||
Id = _openStorage,
|
||||
Name = _openStorageName,
|
||||
Label = _openStorageLabel,
|
||||
Cell = _openStorageCell,
|
||||
SeenUtc = DateTime.UtcNow,
|
||||
Items = items,
|
||||
};
|
||||
var storage = new List<StorageRecord>(_c.Live.Storage);
|
||||
int i = storage.FindIndex(s => s.Id == record.Id);
|
||||
if (i >= 0) storage[i] = record; else storage.Add(record);
|
||||
var snap = NewSnapshot(_c.Live.Items, storage);
|
||||
_c.Live = snap;
|
||||
_indexDirty = true;
|
||||
_scheduler.ContentChanged(now, snap.ContentHash());
|
||||
}
|
||||
|
||||
// ── Writing ─────────────────────────────────────────────────────────────
|
||||
|
||||
private void TickWrite(long now)
|
||||
{
|
||||
if (_writeTask != null)
|
||||
{
|
||||
if (!_writeTask.IsCompleted) return;
|
||||
_writeTask = null;
|
||||
}
|
||||
if (!_identityKnown || _c.Live == null || !_scheduler.Active) return;
|
||||
// Rewrite now and then even when nothing changed, so other clients see this character
|
||||
// as current (once a minute after login, then every RefreshWriteMs).
|
||||
bool refresh = _lastWriteMs == 0 ? now - _loginMs >= 60_000 : now - _lastWriteMs >= RefreshWriteMs;
|
||||
if (!_forceWrite && !refresh && !_scheduler.ShouldWrite(now)) return;
|
||||
if (_forceWrite && _scheduler.ShouldFullScan(now)) return; // /ginv scan: write after the scan
|
||||
_forceWrite = false;
|
||||
StartWrite(now, _c.Live);
|
||||
}
|
||||
|
||||
private void StartWrite(long now, CharacterSnapshot snap)
|
||||
{
|
||||
// The worker only reads the snapshot; published snapshots are never changed (a change makes a new one).
|
||||
if (snap.ScannedUtc == default) snap.ScannedUtc = DateTime.UtcNow;
|
||||
ulong hash = snap.ContentHash();
|
||||
_lastWriteMs = now;
|
||||
InventoryStore store = _c.Store;
|
||||
bool checkOld = !_oldAccountChecked && snap.Account != "unknown";
|
||||
_oldAccountChecked = true;
|
||||
string server = snap.Server, character = snap.Character;
|
||||
_writeTask = Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
store.Save(snap);
|
||||
if (checkOld)
|
||||
{
|
||||
// The same character saved earlier without an account name: that file is superseded.
|
||||
string old = store.PathFor(server, "unknown", character);
|
||||
if (File.Exists(old)) store.Forget(old, out _);
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return ex.Message;
|
||||
}
|
||||
}).ContinueWith(t =>
|
||||
{
|
||||
string error = t.IsFaulted ? (t.Exception?.GetBaseException().Message ?? "failed") : t.Result;
|
||||
_writeResult = new WriteResult(hash, error);
|
||||
}, TaskScheduler.Default);
|
||||
}
|
||||
|
||||
private sealed record WriteResult(ulong Hash, string Error);
|
||||
private volatile WriteResult? _writeResult;
|
||||
|
||||
private void TakeWriteResult(long now)
|
||||
{
|
||||
WriteResult? r = _writeResult;
|
||||
if (r == null) return;
|
||||
_writeResult = null;
|
||||
if (r.Error.Length == 0)
|
||||
{
|
||||
_scheduler.Written(r.Hash);
|
||||
_c.LastSavedUtc = DateTime.UtcNow;
|
||||
_c.LastSaveError = string.Empty;
|
||||
_reloadWanted = true; // other views pick the new file up; ours already has it live
|
||||
}
|
||||
else
|
||||
{
|
||||
_scheduler.WriteFailed(now);
|
||||
_c.LastSaveError = r.Error;
|
||||
Host.Log("[RynthInventory] save failed: " + r.Error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Logout and shutdown: write now, on this thread, if anything is unsaved (or always at logout).</summary>
|
||||
private void FlushNow(bool final)
|
||||
{
|
||||
try
|
||||
{
|
||||
try { _writeTask?.Wait(3000); } catch { }
|
||||
_writeTask = null;
|
||||
TakeWriteResult(Environment.TickCount64);
|
||||
if (!_identityKnown || _c.Live == null) return;
|
||||
if (!final && !_scheduler.Dirty) return;
|
||||
CharacterSnapshot snap = _c.Live;
|
||||
if (snap.ScannedUtc == default) snap.ScannedUtc = DateTime.UtcNow;
|
||||
_c.Store.Save(snap);
|
||||
_scheduler.Written(snap.ContentHash());
|
||||
_c.LastSavedUtc = DateTime.UtcNow;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { Host.Log("[RynthInventory] final save failed: " + ex.Message); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private string ForgetCharacter(CharacterInfo ci)
|
||||
{
|
||||
int moved = 0;
|
||||
string? error = null;
|
||||
var paths = new List<string>(ci.ShadowedFiles);
|
||||
if (!string.IsNullOrEmpty(ci.Snapshot.FilePath)) paths.Add(ci.Snapshot.FilePath);
|
||||
else paths.Add(_c.Store.PathFor(ci.Server, ci.Account, ci.Name)); // the live one: its own file
|
||||
foreach (string p in paths)
|
||||
{
|
||||
if (_c.Store.Forget(p, out string? e)) moved++;
|
||||
else if (e != "already gone") error = e;
|
||||
}
|
||||
_reloadWanted = true;
|
||||
_files.Clear();
|
||||
if (ci.IsCurrentCharacter)
|
||||
{
|
||||
// Back at the next write; start from a clean slate so the old storage isn't re-saved.
|
||||
if (_c.Live != null) _c.Live = NewSnapshot(_c.Live.Items, new List<StorageRecord>());
|
||||
_scheduler.ContentChanged(Environment.TickCount64, 1);
|
||||
}
|
||||
_indexDirty = true;
|
||||
if (moved > 0) return $"Forgot {ci.Name} on {ci.Server} (moved to {InventoryStore.ForgottenFolder}).";
|
||||
return error != null ? $"Couldn't forget {ci.Name}: {error}" : $"{ci.Name} had no file to move.";
|
||||
}
|
||||
|
||||
// ── Merged view ─────────────────────────────────────────────────────────
|
||||
|
||||
private void TickIndex(long now)
|
||||
{
|
||||
TakeWriteResult(now);
|
||||
|
||||
if (_loadTask != null && _loadTask.IsCompleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
var (files, broken) = _loadTask.Result;
|
||||
_files = new Dictionary<string, (InventoryFileStamp, CharacterSnapshot?)>(files, StringComparer.OrdinalIgnoreCase);
|
||||
_c.BrokenFiles = broken;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log("[RynthInventory] reading files failed: " + ex.Message);
|
||||
}
|
||||
_loadTask = null;
|
||||
_c.Loading = false;
|
||||
_indexDirty = true;
|
||||
}
|
||||
|
||||
// Files are only listed and read while the window is open (and once at start).
|
||||
bool visible = _window?.Visible ?? false;
|
||||
if (_loadTask == null && (visible || _c.Index == null) && (_reloadWanted || now >= _nextFileCheckMs))
|
||||
{
|
||||
_nextFileCheckMs = now + FileCheckMs;
|
||||
_reloadWanted = false;
|
||||
StartLoad();
|
||||
}
|
||||
|
||||
if (_indexDirty && (visible || _c.Index == null) && _loadTask == null)
|
||||
{
|
||||
_indexDirty = false;
|
||||
var snaps = new List<CharacterSnapshot>();
|
||||
foreach (var (_, snap) in _files.Values) if (snap != null) snaps.Add(snap);
|
||||
_c.Index = InventoryIndex.Build(snaps, _c.InWorld ? _c.Live : null, _c.Server, _c.Character);
|
||||
_c.IndexRevision++;
|
||||
if (_window != null) _window.NeedsPass = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Lists the files and re-reads the ones that changed, on a worker.</summary>
|
||||
private void StartLoad()
|
||||
{
|
||||
InventoryStore store = _c.Store;
|
||||
var known = new Dictionary<string, (InventoryFileStamp Stamp, CharacterSnapshot? Snapshot)>(_files, StringComparer.OrdinalIgnoreCase);
|
||||
_c.Loading = _c.Index == null;
|
||||
_loadTask = Task.Run(() =>
|
||||
{
|
||||
var result = new Dictionary<string, (InventoryFileStamp, CharacterSnapshot?)>(StringComparer.OrdinalIgnoreCase);
|
||||
int broken = 0;
|
||||
foreach (InventoryFileStamp f in store.ListFiles())
|
||||
{
|
||||
if (known.TryGetValue(f.Path, out var have) && have.Stamp == f)
|
||||
{
|
||||
result[f.Path] = (f, have.Snapshot);
|
||||
if (have.Snapshot == null) broken++;
|
||||
continue;
|
||||
}
|
||||
CharacterSnapshot? s = InventoryStore.Load(f.Path, out _);
|
||||
if (s == null) broken++;
|
||||
result[f.Path] = (f, s);
|
||||
}
|
||||
return (result, broken);
|
||||
});
|
||||
}
|
||||
|
||||
private void RefreshIconSupport()
|
||||
{
|
||||
_c.IconsAvailable = Host.HasUi && Host.TryGetUiInfo(out UiInfoNative info) && info.OpLevel >= 2;
|
||||
}
|
||||
|
||||
/// <summary>A pass when one is wanted, or on the refresh interval while visible (ages tick on).</summary>
|
||||
private void Record(UiWindow w, long now, long interval, Action<UiWindow> draw)
|
||||
{
|
||||
if (_c.Index != null && _view != null && w.Visible && _c.IndexRevision != _lastDrawnRevision)
|
||||
{
|
||||
_lastDrawnRevision = _c.IndexRevision;
|
||||
w.NeedsPass = true;
|
||||
}
|
||||
bool due = w.NeedsPass || (w.Visible && now >= w.NextPassMs);
|
||||
if (!due) return;
|
||||
if (!_c.IconsAvailable && Host.HasUi) RefreshIconSupport();
|
||||
w.NeedsPass = false;
|
||||
w.NextPassMs = now + interval;
|
||||
w.Begin();
|
||||
try
|
||||
{
|
||||
draw(w);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
w.TextWrapped($"Something went wrong drawing this window: {ex.GetType().Name}: {ex.Message}");
|
||||
Host.Log($"[RynthInventory] {w.Key} pass failed: {ex}");
|
||||
}
|
||||
w.End();
|
||||
}
|
||||
|
||||
private int _lastDrawnRevision = -1;
|
||||
}
|
||||
|
|
@ -0,0 +1,324 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using RynthCore.Plugin.RynthInventory.Data;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthInventory.Scanning;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the character's inventory from the client through the plugin API. Plugin pump thread
|
||||
/// only. Everything comes from what the client already has (the engine's object snapshot and
|
||||
/// its property caches, filled by CreateObject and by the engine's own auto-identify); nothing
|
||||
/// here sends anything to the server.
|
||||
///
|
||||
/// GetContainerContents(player) returns everything the player owns directly: the main pack's
|
||||
/// items, the side packs, and the worn and wielded items (wielder = player). Each side pack's
|
||||
/// contents come from GetContainerContents(pack).
|
||||
/// </summary>
|
||||
internal sealed class InventoryScanner
|
||||
{
|
||||
// STypeInt
|
||||
private const uint StackSize = 12, MaxStackSize = 11, Value = 19, EncumbranceVal = 5, ItemsCapacity = 6,
|
||||
CurrentWieldedLocation = 10, MaterialType = 131, ItemWorkmanship = 105, ArmorLevel = 28,
|
||||
Structure = 92, MaxStructure = 91, EquipmentSetId = 265;
|
||||
// STypeDID
|
||||
private const uint DidIcon = 8, DidSpell = 28, DidIconOverlay = 50, DidIconUnderlay = 52;
|
||||
// STypeIID
|
||||
private const uint IidContainer = 2, IidWielder = 3, IidHouseOwner = 32;
|
||||
// ObjectDescriptionFlag
|
||||
private const uint BitfieldCorpse = 0x00002000, BitfieldVendor = 0x00000200, BitfieldPlayer = 0x00000008;
|
||||
|
||||
private const int MaxContents = 1024;
|
||||
private const int MaxNesting = 3;
|
||||
|
||||
private readonly uint[] _contents = new uint[MaxContents];
|
||||
private readonly uint[] _spellBuf = new uint[64];
|
||||
private readonly Dictionary<uint, bool> _isPack = new();
|
||||
|
||||
public bool Warmed;
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_isPack.Clear();
|
||||
Warmed = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The engine's object-table probes run on the first property reads; RynthAi touches them
|
||||
/// with a position and an int read before bulk scanning (WorldObjectCache.ScanFullInventory).
|
||||
/// </summary>
|
||||
public void WarmUp(RynthCoreHost host, uint player)
|
||||
{
|
||||
if (Warmed || player == 0) return;
|
||||
host.TryGetObjectPosition(player, out _, out _, out _, out _);
|
||||
host.TryGetObjectIntProperty(player, 1, out _);
|
||||
Warmed = true;
|
||||
}
|
||||
|
||||
public static bool TryReadIdentity(RynthCoreHost host, out uint player, out string server, out string account, out string character)
|
||||
{
|
||||
player = host.HasGetPlayerId ? host.GetPlayerId() : 0;
|
||||
server = host.TryGetWorldName(out string w) ? w.Trim() : string.Empty;
|
||||
account = host.TryGetAccountName(out string a) ? a.Trim() : string.Empty;
|
||||
character = player != 0 && host.TryGetObjectName(player, out string n) ? n.Trim() : string.Empty;
|
||||
if (account.Length == 0) account = "unknown";
|
||||
return player != 0 && character.Length > 0 && server.Length > 0;
|
||||
}
|
||||
|
||||
// ── Fingerprint ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A hash of what the character carries: ids, where each is, stack sizes. Cheap enough to run every poll.</summary>
|
||||
public ulong Fingerprint(RynthCoreHost host, uint player)
|
||||
{
|
||||
var h = new Fnv64();
|
||||
h.Add(player);
|
||||
FingerprintContainer(host, player, player, ref h, 0);
|
||||
return h.Value;
|
||||
}
|
||||
|
||||
private void FingerprintContainer(RynthCoreHost host, uint player, uint container, ref Fnv64 h, int depth)
|
||||
{
|
||||
int n = host.GetContainerContents(container, _contents);
|
||||
if (n <= 0) { h.Add(0xDEADu); return; }
|
||||
uint[] ids = new uint[n];
|
||||
Array.Copy(_contents, ids, n);
|
||||
h.Add((uint)n);
|
||||
foreach (uint id in ids)
|
||||
{
|
||||
Ownership(host, id, out uint c, out uint w, out uint loc);
|
||||
host.TryGetObjectIntProperty(id, StackSize, out int stack);
|
||||
h.Add(id); h.Add(c); h.Add(w); h.Add(loc); h.Add((uint)stack);
|
||||
if (depth < MaxNesting && w == 0 && c == container && IsPack(host, id))
|
||||
FingerprintContainer(host, player, id, ref h, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Full scan ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Everything the character carries and wears.</summary>
|
||||
public List<ItemRecord> ScanCarried(RynthCoreHost host, uint player)
|
||||
{
|
||||
var items = new List<ItemRecord>();
|
||||
int n = host.GetContainerContents(player, _contents);
|
||||
if (n <= 0) return items;
|
||||
uint[] top = new uint[n];
|
||||
Array.Copy(_contents, top, n);
|
||||
|
||||
var packs = new List<(uint Id, string Label)>();
|
||||
var packNames = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
string[] mainPath = { "Main pack" };
|
||||
foreach (uint id in top)
|
||||
{
|
||||
Ownership(host, id, out uint c, out uint w, out uint loc);
|
||||
if (w == player && w != 0)
|
||||
{
|
||||
if (loc == 0 && host.TryGetObjectIntProperty(id, CurrentWieldedLocation, out int l3)) loc = unchecked((uint)l3);
|
||||
ItemRecord? eq = Read(host, id, ItemPlace.Equipped, player, Array.Empty<string>(), loc);
|
||||
if (eq != null) items.Add(eq);
|
||||
continue;
|
||||
}
|
||||
if (c != player && c != 0) continue; // moved away since the engine's snapshot
|
||||
ItemRecord? it = Read(host, id, ItemPlace.Pack, player, mainPath, 0);
|
||||
if (it == null) continue;
|
||||
items.Add(it);
|
||||
if (IsPack(host, id))
|
||||
{
|
||||
// Side packs are labelled by name ("Sack", "Sack 2" ...); the client's slot order isn't known here.
|
||||
packNames.TryGetValue(it.Name, out int seen);
|
||||
packNames[it.Name] = seen + 1;
|
||||
packs.Add((id, seen == 0 ? it.Name : it.Name + " " + (seen + 1).ToString(CultureInfo.InvariantCulture)));
|
||||
}
|
||||
}
|
||||
foreach (var (packId, label) in packs)
|
||||
ScanInto(host, packId, ItemPlace.Pack, new[] { "Main pack", label }, items, 1);
|
||||
return items;
|
||||
}
|
||||
|
||||
/// <summary>A container outside the character (storage): its items and any packs inside it.</summary>
|
||||
public List<ItemRecord> ScanContainer(RynthCoreHost host, uint containerId)
|
||||
{
|
||||
var items = new List<ItemRecord>();
|
||||
ScanInto(host, containerId, ItemPlace.Storage, Array.Empty<string>(), items, 0);
|
||||
return items;
|
||||
}
|
||||
|
||||
private void ScanInto(RynthCoreHost host, uint container, string place, string[] path, List<ItemRecord> items, int depth)
|
||||
{
|
||||
int n = host.GetContainerContents(container, _contents);
|
||||
if (n <= 0) return;
|
||||
uint[] ids = new uint[n];
|
||||
Array.Copy(_contents, ids, n);
|
||||
var packs = new List<(uint, string)>();
|
||||
var names = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (uint id in ids)
|
||||
{
|
||||
Ownership(host, id, out uint c, out uint w, out _);
|
||||
if (w != 0 || (c != container && c != 0)) continue;
|
||||
ItemRecord? it = Read(host, id, place, container, path, 0);
|
||||
if (it == null) continue;
|
||||
items.Add(it);
|
||||
if (depth < MaxNesting && IsPack(host, id))
|
||||
{
|
||||
names.TryGetValue(it.Name, out int seen);
|
||||
names[it.Name] = seen + 1;
|
||||
packs.Add((id, seen == 0 ? it.Name : it.Name + " " + (seen + 1).ToString(CultureInfo.InvariantCulture)));
|
||||
}
|
||||
}
|
||||
foreach (var (packId, label) in packs)
|
||||
{
|
||||
var sub = new string[path.Length + 1];
|
||||
Array.Copy(path, sub, path.Length);
|
||||
sub[path.Length] = label;
|
||||
ScanInto(host, packId, place, sub, items, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
private ItemRecord? Read(RynthCoreHost host, uint id, string place, uint container, string[] path, uint slot)
|
||||
{
|
||||
if (!host.TryGetObjectName(id, out string name) || string.IsNullOrWhiteSpace(name)) return null;
|
||||
var it = new ItemRecord
|
||||
{
|
||||
Id = id,
|
||||
Name = name.Trim(),
|
||||
Place = place,
|
||||
ContainerId = container,
|
||||
Path = path,
|
||||
Slot = slot,
|
||||
};
|
||||
if (host.TryGetItemType(id, out uint type)) it.ItemType = type;
|
||||
it.Category = ItemCategory.FromItemType(it.ItemType);
|
||||
if (host.HasGetObjectWcid && host.TryGetObjectWcid(id, out uint wcid)) it.Wcid = wcid;
|
||||
if (host.HasGetObjectDataIdProperty)
|
||||
{
|
||||
if (host.TryGetObjectDataIdProperty(id, DidIcon, out uint icon)) it.Icon = icon;
|
||||
if (host.TryGetObjectDataIdProperty(id, DidIconUnderlay, out uint under)) it.Underlay = under;
|
||||
if (host.TryGetObjectDataIdProperty(id, DidIconOverlay, out uint over)) it.Overlay = over;
|
||||
}
|
||||
if (host.TryGetObjectIntProperty(id, StackSize, out int stack) && stack > 0) it.Stack = stack;
|
||||
if (host.TryGetObjectIntProperty(id, MaxStackSize, out int maxStack)) it.MaxStack = Math.Max(0, maxStack);
|
||||
if (host.TryGetObjectIntProperty(id, Value, out int value)) it.Value = value;
|
||||
if (host.TryGetObjectIntProperty(id, EncumbranceVal, out int burden)) it.Burden = burden;
|
||||
if (host.TryGetObjectIntProperty(id, MaterialType, out int material)) it.Material = Math.Max(0, material);
|
||||
if (host.TryGetObjectIntProperty(id, ItemWorkmanship, out int work)) it.Workmanship = Math.Max(0, work);
|
||||
if (host.TryGetObjectIntProperty(id, ArmorLevel, out int al)) it.ArmorLevel = Math.Max(0, al);
|
||||
if (host.TryGetObjectIntProperty(id, MaxStructure, out int maxUses) && maxUses > 0)
|
||||
{
|
||||
it.MaxUses = maxUses;
|
||||
if (host.TryGetObjectIntProperty(id, Structure, out int uses)) it.Uses = Math.Max(0, uses);
|
||||
}
|
||||
if (host.TryGetObjectIntProperty(id, EquipmentSetId, out int set)) it.SetId = Math.Max(0, set);
|
||||
it.Identified = host.HasHasAppraisalData && host.HasAppraisalData(id);
|
||||
|
||||
if (host.HasGetObjectSpellIds)
|
||||
{
|
||||
int count = host.GetObjectSpellIds(id, _spellBuf, _spellBuf.Length);
|
||||
if (count > 0)
|
||||
{
|
||||
count = Math.Min(count, _spellBuf.Length);
|
||||
it.Spells = new uint[count];
|
||||
Array.Copy(_spellBuf, it.Spells, count);
|
||||
}
|
||||
}
|
||||
// A scroll, gem or potion that casts one spell carries it in its PublicWeenieDesc.
|
||||
if (it.Spells.Length == 0 && host.HasGetObjectDataIdProperty
|
||||
&& host.TryGetObjectDataIdProperty(id, DidSpell, out uint spell) && spell != 0 && spell < 0x10000)
|
||||
it.Spells = new[] { spell };
|
||||
if (it.Spells.Length > 0)
|
||||
{
|
||||
it.SpellNames = new string[it.Spells.Length];
|
||||
for (int i = 0; i < it.Spells.Length; i++) it.SpellNames[i] = SpellTable.Name(it.Spells[i]);
|
||||
}
|
||||
return it;
|
||||
}
|
||||
|
||||
// ── Storage ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Whether an opened container counts as storage worth remembering.</summary>
|
||||
public static bool IsStorage(RynthCoreHost host, uint id, uint player, string[] words, bool kept, out string name, out string why)
|
||||
{
|
||||
why = string.Empty;
|
||||
name = host.TryGetObjectName(id, out string n) ? n.Trim() : string.Empty;
|
||||
if (id == 0 || id == player || name.Length == 0) { why = "no name"; return false; }
|
||||
if (host.TryGetObjectBitfield(id, out uint bf) && (bf & (BitfieldCorpse | BitfieldVendor | BitfieldPlayer)) != 0)
|
||||
{
|
||||
why = "a corpse or vendor";
|
||||
return false;
|
||||
}
|
||||
if (name.StartsWith("Corpse of ", StringComparison.OrdinalIgnoreCase)) { why = "a corpse"; return false; }
|
||||
if (IsOwnedBy(host, id, player)) { why = "carried"; return false; }
|
||||
if (kept) { why = "kept with /ginv keep"; return true; }
|
||||
if (host.HasGetObjectInstanceIdProperty && host.TryGetObjectInstanceIdProperty(id, IidHouseOwner, out uint houseOwner) && houseOwner != 0)
|
||||
{
|
||||
why = "house storage";
|
||||
return true;
|
||||
}
|
||||
string lower = name.ToLowerInvariant();
|
||||
foreach (string word in words)
|
||||
{
|
||||
if (word.Length > 0 && lower.Contains(word, StringComparison.Ordinal))
|
||||
{
|
||||
why = $"name has \"{word}\"";
|
||||
return true;
|
||||
}
|
||||
}
|
||||
why = "not storage (use /ginv keep while it is open to record it anyway)";
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>"Storage near 42.1N, 33.6E" (the player's position when it opened), or the cell when there are no coordinates.</summary>
|
||||
public static string StorageLabel(RynthCoreHost host, uint id, string name, out uint cell)
|
||||
{
|
||||
cell = 0;
|
||||
if (host.TryGetObjectPosition(id, out uint c, out _, out _, out _)) cell = c;
|
||||
string baseName = name.Length > 0 ? name : "Storage";
|
||||
if (host.HasGetCurCoords && host.TryGetCurCoords(out double ns, out double ew) && !(ns == 0 && ew == 0))
|
||||
return $"{baseName} near {Coord(ns, 'N', 'S')}, {Coord(ew, 'E', 'W')}";
|
||||
return cell != 0 ? $"{baseName} (cell 0x{cell:X8})" : baseName;
|
||||
}
|
||||
|
||||
private static string Coord(double v, char pos, char neg) =>
|
||||
Math.Abs(v).ToString("0.0", CultureInfo.InvariantCulture) + (v >= 0 ? pos : neg);
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static bool IsOwnedBy(RynthCoreHost host, uint id, uint player)
|
||||
{
|
||||
uint cur = id;
|
||||
for (int i = 0; i < 4 && cur != 0; i++)
|
||||
{
|
||||
Ownership(host, cur, out uint c, out uint w, out _);
|
||||
if (c == player || w == player) return true;
|
||||
cur = c;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void Ownership(RynthCoreHost host, uint id, out uint container, out uint wielder, out uint location)
|
||||
{
|
||||
container = wielder = location = 0;
|
||||
if (host.HasGetObjectOwnershipInfo && host.TryGetObjectOwnershipInfo(id, out container, out wielder, out location))
|
||||
return;
|
||||
if (host.HasGetObjectInstanceIdProperty)
|
||||
{
|
||||
host.TryGetObjectInstanceIdProperty(id, IidContainer, out container);
|
||||
host.TryGetObjectInstanceIdProperty(id, IidWielder, out wielder);
|
||||
}
|
||||
if (host.HasGetObjectWielderInfo && host.TryGetObjectWielderInfo(id, out uint w2, out uint l2))
|
||||
{
|
||||
if (wielder == 0) wielder = w2;
|
||||
location = l2;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A side pack (or a pack inside storage): a container with item slots. Cached; it never changes.</summary>
|
||||
private bool IsPack(RynthCoreHost host, uint id)
|
||||
{
|
||||
if (_isPack.TryGetValue(id, out bool known)) return known;
|
||||
if (!host.TryGetItemType(id, out uint type) || type == 0) return false; // not known yet: ask again later
|
||||
bool pack = (type & ItemCategory.ContainerFlag) != 0
|
||||
&& host.TryGetObjectIntProperty(id, ItemsCapacity, out int cap) && cap > 0;
|
||||
_isPack[id] = pack;
|
||||
return pack;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthInventory.Scanning;
|
||||
|
||||
/// <summary>
|
||||
/// When to look at the inventory, when to scan it fully and when to write the file. Pure
|
||||
/// timing logic (milliseconds in, decisions out) so Tools\RynthInventory.Tests can drive it.
|
||||
///
|
||||
/// Poll a cheap fingerprint (ids, containers, wielders, stack sizes) every
|
||||
/// <see cref="PollMs"/>, sooner after an inventory event.
|
||||
/// Full scan every item's details. After login (three times while the client settles and
|
||||
/// the engine's auto-identify fills in spells), once the fingerprint has changed
|
||||
/// and then held still for <see cref="SettleMs"/> (or kept changing for
|
||||
/// <see cref="MaxSettleMs"/>), and every <see cref="PeriodicMs"/> to pick up
|
||||
/// details that arrive without a visible change.
|
||||
/// Write only when a scan's content differs from what was last written, after
|
||||
/// <see cref="WriteQuietMs"/> without another change or at most
|
||||
/// <see cref="WriteMaxDelayMs"/> after the first unsaved one. A loot spree or a
|
||||
/// salvage run therefore writes about twice a minute, not once per item.
|
||||
/// </summary>
|
||||
internal sealed class ScanScheduler
|
||||
{
|
||||
public const long PollMs = 1500;
|
||||
public const long EventPollDelayMs = 400;
|
||||
public const long SettleMs = 2000;
|
||||
public const long MaxSettleMs = 10_000;
|
||||
public const long PeriodicMs = 60_000;
|
||||
public const long WriteQuietMs = 5000;
|
||||
public const long WriteMaxDelayMs = 30_000;
|
||||
public static readonly long[] LoginScansMs = { 3000, 12_000, 40_000 };
|
||||
|
||||
private bool _active;
|
||||
private long _nextPollMs;
|
||||
private ulong _fingerprint;
|
||||
private bool _haveFingerprint;
|
||||
private long _changeFirstMs = -1, _changeLastMs = -1;
|
||||
/// <summary>The last time the poll saw the inventory change (the write waits for this to go quiet).</summary>
|
||||
private long _activityMs = -1;
|
||||
private long _nextPeriodicMs;
|
||||
private int _loginScan;
|
||||
private long _loginMs;
|
||||
private bool _fullScanWanted;
|
||||
|
||||
private ulong _savedHash;
|
||||
private bool _haveSaved;
|
||||
private ulong _pendingHash;
|
||||
private long _dirtyFirstMs = -1, _dirtyLastMs = -1;
|
||||
|
||||
public bool Active => _active;
|
||||
public bool Dirty => _dirtyFirstMs >= 0;
|
||||
|
||||
/// <summary>A character is in the world: start over (nothing carries over from the last one).</summary>
|
||||
public void Login(long now)
|
||||
{
|
||||
_active = true;
|
||||
_loginMs = now;
|
||||
_loginScan = 0;
|
||||
_nextPollMs = now + LoginScansMs[0];
|
||||
_haveFingerprint = false;
|
||||
_changeFirstMs = _changeLastMs = -1;
|
||||
_activityMs = -1;
|
||||
_nextPeriodicMs = long.MaxValue;
|
||||
_fullScanWanted = false;
|
||||
_haveSaved = false;
|
||||
_dirtyFirstMs = _dirtyLastMs = -1;
|
||||
}
|
||||
|
||||
public void Logout()
|
||||
{
|
||||
_active = false;
|
||||
_dirtyFirstMs = _dirtyLastMs = -1;
|
||||
}
|
||||
|
||||
/// <summary>The file on disk already holds content with this hash (loaded at login, or just written).</summary>
|
||||
public void KnownSaved(ulong hash)
|
||||
{
|
||||
_savedHash = hash;
|
||||
_haveSaved = true;
|
||||
}
|
||||
|
||||
/// <summary>Something that may have touched the inventory happened (an object created, deleted, a container's contents).</summary>
|
||||
public void InventoryEvent(long now)
|
||||
{
|
||||
if (!_active) return;
|
||||
long at = now + EventPollDelayMs;
|
||||
if (at < _nextPollMs && now >= _loginMs + LoginScansMs[0]) _nextPollMs = at;
|
||||
}
|
||||
|
||||
/// <summary>Asks for a full scan at the next tick (the player's /ginv scan).</summary>
|
||||
public void RequestFullScan() => _fullScanWanted = true;
|
||||
|
||||
public bool ShouldPoll(long now) => _active && now >= _nextPollMs;
|
||||
|
||||
/// <summary>The fingerprint the poll computed.</summary>
|
||||
public void PollResult(long now, ulong fingerprint)
|
||||
{
|
||||
_nextPollMs = now + PollMs;
|
||||
if (!_haveFingerprint)
|
||||
{
|
||||
_haveFingerprint = true;
|
||||
_fingerprint = fingerprint;
|
||||
return;
|
||||
}
|
||||
if (fingerprint == _fingerprint) return;
|
||||
_fingerprint = fingerprint;
|
||||
if (_changeFirstMs < 0) _changeFirstMs = now;
|
||||
_changeLastMs = now;
|
||||
_activityMs = now;
|
||||
}
|
||||
|
||||
public bool ShouldFullScan(long now)
|
||||
{
|
||||
if (!_active) return false;
|
||||
if (_fullScanWanted) return true;
|
||||
if (_loginScan < LoginScansMs.Length && now >= _loginMs + LoginScansMs[_loginScan]) return true;
|
||||
if (_changeFirstMs >= 0 && (now - _changeLastMs >= SettleMs || now - _changeFirstMs >= MaxSettleMs)) return true;
|
||||
return now >= _nextPeriodicMs;
|
||||
}
|
||||
|
||||
/// <summary>A full scan finished with this content hash (and fingerprint, so the next poll doesn't re-trigger).</summary>
|
||||
public void FullScanDone(long now, ulong contentHash, ulong fingerprint)
|
||||
{
|
||||
_fullScanWanted = false;
|
||||
while (_loginScan < LoginScansMs.Length && now >= _loginMs + LoginScansMs[_loginScan]) _loginScan++;
|
||||
_changeFirstMs = _changeLastMs = -1;
|
||||
_fingerprint = fingerprint;
|
||||
_haveFingerprint = true;
|
||||
_nextPeriodicMs = now + PeriodicMs;
|
||||
if (_nextPollMs < now + PollMs) _nextPollMs = now + PollMs;
|
||||
ContentChanged(now, contentHash);
|
||||
}
|
||||
|
||||
/// <summary>The saved content changed outside a full scan (a storage container was read).</summary>
|
||||
public void ContentChanged(long now, ulong contentHash)
|
||||
{
|
||||
if (_haveSaved && contentHash == _savedHash)
|
||||
{
|
||||
// Back to what's on disk (e.g. an item moved out and back): nothing to write.
|
||||
_dirtyFirstMs = _dirtyLastMs = -1;
|
||||
return;
|
||||
}
|
||||
if (_dirtyFirstMs >= 0 && contentHash == _pendingHash) return;
|
||||
_pendingHash = contentHash;
|
||||
if (_dirtyFirstMs < 0) _dirtyFirstMs = now;
|
||||
_dirtyLastMs = now;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unsaved content, and either nothing has changed for <see cref="WriteQuietMs"/> (neither
|
||||
/// the content nor what the poll sees: during a loot spree the scans only run every
|
||||
/// <see cref="MaxSettleMs"/>, so the content alone would look quiet in between) or the
|
||||
/// first unsaved change is <see cref="WriteMaxDelayMs"/> old.
|
||||
/// </summary>
|
||||
public bool ShouldWrite(long now)
|
||||
{
|
||||
if (_dirtyFirstMs < 0) return false;
|
||||
long last = Math.Max(_dirtyLastMs, _activityMs);
|
||||
return now - last >= WriteQuietMs || now - _dirtyFirstMs >= WriteMaxDelayMs;
|
||||
}
|
||||
|
||||
public void Written(ulong contentHash)
|
||||
{
|
||||
KnownSaved(contentHash);
|
||||
_dirtyFirstMs = _dirtyLastMs = -1;
|
||||
}
|
||||
|
||||
/// <summary>A write failed: try again after the quiet time.</summary>
|
||||
public void WriteFailed(long now)
|
||||
{
|
||||
if (_dirtyFirstMs < 0) return;
|
||||
_dirtyFirstMs = now;
|
||||
_dirtyLastMs = now;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
|
||||
namespace RynthCore.Plugin.RynthInventory.Scanning;
|
||||
|
||||
internal readonly record struct SpellInfo(string Name, double Duration, bool IsDebuff);
|
||||
|
||||
/// <summary>
|
||||
/// Spell names and base durations from RynthAi's embedded spell table (SpellData.txt, linked
|
||||
/// into this plugin): tab separated, id, name, category, family, words, duration (s, -1 none),
|
||||
/// difficulty, then three flags, the second of which marks a debuff. Loaded on first use.
|
||||
/// </summary>
|
||||
internal static class SpellTable
|
||||
{
|
||||
private static Dictionary<uint, SpellInfo>? _spells;
|
||||
|
||||
public static bool TryGet(uint id, out SpellInfo info)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _spells!.TryGetValue(id, out info);
|
||||
}
|
||||
|
||||
public static string Name(uint id) => TryGet(id, out SpellInfo s) ? s.Name : $"Spell {id}";
|
||||
|
||||
public static int Count
|
||||
{
|
||||
get { EnsureLoaded(); return _spells!.Count; }
|
||||
}
|
||||
|
||||
private static void EnsureLoaded()
|
||||
{
|
||||
if (_spells != null) return;
|
||||
var map = new Dictionary<uint, SpellInfo>();
|
||||
try
|
||||
{
|
||||
using Stream? s = Assembly.GetExecutingAssembly().GetManifestResourceStream("RynthInventory.SpellData.txt");
|
||||
if (s != null)
|
||||
{
|
||||
using var reader = new StreamReader(s, detectEncodingFromByteOrderMarks: true);
|
||||
while (reader.ReadLine() is string line)
|
||||
{
|
||||
string[] c = line.Split('\t');
|
||||
if (c.Length < 2 || !uint.TryParse(c[0].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out uint id)) continue;
|
||||
double duration = c.Length > 5 && double.TryParse(c[5].Trim(), NumberStyles.Float | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out double d) ? d : -1;
|
||||
bool debuff = c.Length > 8 && c[8].Trim().Equals("True", StringComparison.OrdinalIgnoreCase);
|
||||
map[id] = new SpellInfo(c[1].Trim(), duration, debuff);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A missing table only costs names ("Spell 1234").
|
||||
}
|
||||
_spells = map;
|
||||
}
|
||||
}
|
||||
120
Plugins/RynthCore.Plugin.RynthInventory/Ui/UiFormat.cs
Normal file
120
Plugins/RynthCore.Plugin.RynthInventory/Ui/UiFormat.cs
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthInventory.Ui;
|
||||
|
||||
/// <summary>
|
||||
/// Display-list format 1 for the engine's script windows (RynthSuite
|
||||
/// Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2-4.3; the engine's DisplayListParser.cs is the source of
|
||||
/// truth). Little-endian. Only the ops RynthInventory draws are listed.
|
||||
/// </summary>
|
||||
internal static class UiFormat
|
||||
{
|
||||
public const uint Magic = 0x31575352; // 'RSW1'
|
||||
public const ushort FormatVersion = 1;
|
||||
public const uint BodyUnchanged = 0xFFFFFFFF;
|
||||
public const int MaxString = 4096;
|
||||
public const int MaxStr8 = 128;
|
||||
public const int MaxOps = 1500; // engine limit per window
|
||||
public const int MaxBodyBytes = 64 * 1024; // engine limit per window
|
||||
public const byte OpHasBlock = 1;
|
||||
|
||||
// Ops
|
||||
public const byte OpEnd = 0x00;
|
||||
public const byte OpText = 0x01;
|
||||
public const byte OpTextColored = 0x02;
|
||||
public const byte OpTextWrapped = 0x03;
|
||||
public const byte OpTextDisabled = 0x04;
|
||||
public const byte OpBulletText = 0x05;
|
||||
public const byte OpSeparatorText = 0x06;
|
||||
public const byte OpSeparator = 0x10;
|
||||
public const byte OpSameLine = 0x11;
|
||||
public const byte OpSpacing = 0x13;
|
||||
public const byte OpDummy = 0x14;
|
||||
public const byte OpButton = 0x20;
|
||||
public const byte OpCheckbox = 0x21;
|
||||
public const byte OpInputText = 0x24;
|
||||
public const byte OpCombo = 0x25;
|
||||
public const byte OpSelectable = 0x26;
|
||||
public const byte OpProgressBar = 0x27;
|
||||
public const byte OpImage = 0x28; // op level 2 (engines from 2026-09-30)
|
||||
public const byte OpPushID = 0x30;
|
||||
public const byte OpPopID = 0x31;
|
||||
public const byte OpPushStyleColor = 0x32;
|
||||
public const byte OpPopStyleColor = 0x33;
|
||||
public const byte OpSetItemTooltip = 0x38;
|
||||
public const byte OpChild = 0x40;
|
||||
public const byte OpCollapsingHeader = 0x41;
|
||||
|
||||
// Window flags
|
||||
public const uint FlagVisible = 1u << 0;
|
||||
public const uint FlagShowInBar = 1u << 1;
|
||||
public const uint FlagNoScrollbar = 1u << 5;
|
||||
|
||||
// Image icon kinds (op level 2)
|
||||
public const byte IconKindIcon = 0; // a 0x06 texture id
|
||||
public const byte IconKindObject = 1; // a live object's icon with underlay and overlay
|
||||
|
||||
// Selectable flags
|
||||
public const uint SelectableAllowDoubleClick = 4;
|
||||
|
||||
// Event types
|
||||
public const ushort EvClicked = 1;
|
||||
public const ushort EvBool = 2;
|
||||
public const ushort EvInt = 3;
|
||||
public const ushort EvText = 5;
|
||||
public const ushort EvOpen = 6;
|
||||
public const ushort EvVisibility = 8;
|
||||
public const ushort EvError = 10;
|
||||
|
||||
// ImGuiCol ids the engine accepts in PushStyleColor (ImGui.NET 1.91.6.1)
|
||||
public const int ColText = 0;
|
||||
public const int ColButton = 21;
|
||||
public const int ColButtonHovered = 22;
|
||||
public const int ColHeader = 24;
|
||||
|
||||
// InputText flags
|
||||
public const uint InputAutoSelectAll = 4096;
|
||||
|
||||
// CollapsingHeader flags
|
||||
public const uint TreeDefaultOpen = 32;
|
||||
|
||||
public static uint Fnv1a(ReadOnlySpan<byte> bytes, uint hash = 2166136261)
|
||||
{
|
||||
foreach (byte b in bytes)
|
||||
{
|
||||
hash ^= b;
|
||||
hash *= 16777619;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/// <summary>The length of <paramref name="s"/> cut to at most <paramref name="max"/> bytes without splitting a character.</summary>
|
||||
public static int CutUtf8(ReadOnlySpan<byte> s, int max)
|
||||
{
|
||||
if (s.Length <= max) return s.Length;
|
||||
int n = Math.Max(0, max);
|
||||
while (n > 0 && (s[n] & 0xC0) == 0x80) n--;
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>An ImGui U32 colour (0xAABBGGRR) from RGB bytes.</summary>
|
||||
public static uint Rgb(byte r, byte g, byte b, byte a = 255) =>
|
||||
((uint)a << 24) | ((uint)b << 16) | ((uint)g << 8) | r;
|
||||
}
|
||||
|
||||
/// <summary>Colours RynthInventory uses (0xAABBGGRR).</summary>
|
||||
internal static class UiColors
|
||||
{
|
||||
public static readonly uint Green = UiFormat.Rgb(110, 210, 110);
|
||||
public static readonly uint Red = UiFormat.Rgb(225, 95, 95);
|
||||
public static readonly uint Yellow = UiFormat.Rgb(235, 205, 90);
|
||||
public static readonly uint Grey = UiFormat.Rgb(150, 150, 150);
|
||||
public static readonly uint Gold = UiFormat.Rgb(230, 180, 60);
|
||||
/// <summary>Upstream's "destruction" highlight: deep pink brightened by half (255, 30, 220).</summary>
|
||||
public static readonly uint Destruction = UiFormat.Rgb(255, 30, 220);
|
||||
public static readonly uint TabActive = UiFormat.Rgb(60, 110, 170);
|
||||
public static readonly uint TabActiveHover = UiFormat.Rgb(75, 130, 195);
|
||||
public static readonly uint OtherServer = UiFormat.Rgb(150, 185, 235);
|
||||
public static readonly uint Stale = UiFormat.Rgb(225, 150, 80);
|
||||
public static readonly uint White = UiFormat.Rgb(255, 255, 255);
|
||||
}
|
||||
202
Plugins/RynthCore.Plugin.RynthInventory/Ui/UiHost.cs
Normal file
202
Plugins/RynthCore.Plugin.RynthInventory/Ui/UiHost.cs
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthInventory.Ui;
|
||||
|
||||
/// <summary>
|
||||
/// The plugin's side of the engine's script windows (API v71): polls the engine's events into
|
||||
/// the windows' handlers and submits the window set when something changed. Plugin pump thread
|
||||
/// only (inside the plugin's own tick), as the engine requires.
|
||||
/// </summary>
|
||||
internal sealed class UiHost
|
||||
{
|
||||
private readonly List<UiWindow> _windows = new();
|
||||
private readonly Dictionary<uint, UiWindow> _byHash = new();
|
||||
private byte[] _events = new byte[8192];
|
||||
private byte[] _submit = new byte[64 * 1024];
|
||||
private uint _lastSeq;
|
||||
private bool _submittedSomething;
|
||||
private long _retryAtMs;
|
||||
private long _lastErrorLogMs;
|
||||
|
||||
public Action<string>? Log;
|
||||
|
||||
public IReadOnlyList<UiWindow> Windows => _windows;
|
||||
|
||||
public UiWindow Add(UiWindow w)
|
||||
{
|
||||
_windows.Add(w);
|
||||
_byHash[w.Hash] = w;
|
||||
return w;
|
||||
}
|
||||
|
||||
/// <summary>Drains the engine's queued events into the windows' handlers.</summary>
|
||||
public void Poll(RynthCoreHost host)
|
||||
{
|
||||
if (!host.HasUi || !_submittedSomething) return;
|
||||
for (int round = 0; round < 8; round++)
|
||||
{
|
||||
int n = host.UiPollEvents(_events, out int remaining);
|
||||
if (n > 0) Apply(_events.AsSpan(0, n));
|
||||
if (remaining == 0) break;
|
||||
if (n == 0) Array.Resize(ref _events, _events.Length * 2); // one event didn't fit
|
||||
}
|
||||
}
|
||||
|
||||
private void Apply(ReadOnlySpan<byte> data)
|
||||
{
|
||||
int pos = 0;
|
||||
while (data.Length - pos >= 16)
|
||||
{
|
||||
ushort type = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]);
|
||||
int size = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]);
|
||||
if (size < 16 || size > data.Length - pos) break;
|
||||
uint seq = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 4)..]);
|
||||
uint window = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 8)..]);
|
||||
uint key = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 12)..]);
|
||||
ReadOnlySpan<byte> p = data.Slice(pos + 16, size - 16);
|
||||
pos += size;
|
||||
if (seq > _lastSeq) _lastSeq = seq;
|
||||
|
||||
_byHash.TryGetValue(window, out UiWindow? w);
|
||||
switch (type)
|
||||
{
|
||||
case UiFormat.EvClicked when w != null && p.Length >= 2:
|
||||
int count = BinaryPrimitives.ReadUInt16LittleEndian(p);
|
||||
for (int i = 0; i < Math.Min(count, 4); i++) w.Dispatch(key, new UiEvent(type));
|
||||
break;
|
||||
case UiFormat.EvBool when w != null && p.Length >= 1:
|
||||
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
|
||||
break;
|
||||
case UiFormat.EvInt when w != null && p.Length >= 4:
|
||||
w.Dispatch(key, new UiEvent(type, i: BinaryPrimitives.ReadInt32LittleEndian(p)));
|
||||
break;
|
||||
case UiFormat.EvText when w != null && p.Length >= 3:
|
||||
{
|
||||
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p[1..]), p.Length - 3);
|
||||
w.Dispatch(key, new UiEvent(type, text: Encoding.UTF8.GetString(p.Slice(3, n)), submitted: p[0] != 0));
|
||||
break;
|
||||
}
|
||||
case UiFormat.EvOpen when w != null && p.Length >= 1:
|
||||
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
|
||||
break;
|
||||
case UiFormat.EvVisibility when w != null && p.Length >= 1:
|
||||
// The player closed it (X) or opened it (bar menu / command): theirs wins.
|
||||
w.Visible = p[0] != 0;
|
||||
w.NeedsPass = true;
|
||||
break;
|
||||
case UiFormat.EvError when p.Length >= 2:
|
||||
{
|
||||
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p), p.Length - 2);
|
||||
Log?.Invoke("[RynthInventory] window error: " + Encoding.UTF8.GetString(p.Slice(2, n)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sends the window set when any window's list or header changed.</summary>
|
||||
public void Submit(RynthCoreHost host, long nowMs)
|
||||
{
|
||||
if (!host.HasUi || nowMs < _retryAtMs) return;
|
||||
bool changed = !_submittedSomething && _windows.Count > 0;
|
||||
foreach (UiWindow w in _windows)
|
||||
if (w.BodyDirty || w.HeaderDirty) { changed = true; break; }
|
||||
if (!changed) return;
|
||||
|
||||
int pos = Write();
|
||||
int rc = host.UiSubmit(_submit.AsSpan(0, pos));
|
||||
if (rc == 0)
|
||||
{
|
||||
foreach (UiWindow w in _windows) w.MarkSubmitted(w.BodyDirty);
|
||||
_submittedSomething = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Nothing was applied; the engine keeps the previous lists. Try again in a second.
|
||||
_retryAtMs = nowMs + 1000;
|
||||
if (nowMs - _lastErrorLogMs > 10_000)
|
||||
{
|
||||
_lastErrorLogMs = nowMs;
|
||||
Log?.Invoke($"[RynthInventory] the engine refused the window list ({rc}).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Removes every window from the engine (logout, shutdown). Their placement is kept by the engine.</summary>
|
||||
public void SubmitEmpty(RynthCoreHost host)
|
||||
{
|
||||
if (!host.HasUi || !_submittedSomething) return;
|
||||
Span<byte> b = stackalloc byte[16];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], 16);
|
||||
if (host.UiSubmit(b) == 0)
|
||||
{
|
||||
_submittedSomething = false;
|
||||
foreach (UiWindow w in _windows) w.ForgetSubmitted();
|
||||
}
|
||||
}
|
||||
|
||||
private int Write()
|
||||
{
|
||||
int size = 16;
|
||||
foreach (UiWindow w in _windows) size += 2 * (1 + UiFormat.MaxStr8) + 4 + 32 + 8 + (w.BodyDirty ? w.Body.Length : 0);
|
||||
if (_submit.Length < size) _submit = new byte[Math.Max(size, _submit.Length * 2)];
|
||||
Span<byte> b = _submit;
|
||||
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], (ushort)_windows.Count);
|
||||
// Every event polled so far has been applied (handlers run as they arrive).
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
|
||||
int pos = 16;
|
||||
foreach (UiWindow w in _windows)
|
||||
{
|
||||
pos = Str8(b, pos, w.KeyUtf8);
|
||||
pos = Str8(b, pos, Encoding.UTF8.GetBytes(w.Title ?? string.Empty));
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.Flags); pos += 4;
|
||||
pos = F32(b, pos, w.DefaultWidth);
|
||||
pos = F32(b, pos, w.DefaultHeight);
|
||||
pos = F32(b, pos, w.MinWidth);
|
||||
pos = F32(b, pos, w.MinHeight);
|
||||
pos = F32(b, pos, float.NaN); // RequestSize: none
|
||||
pos = F32(b, pos, float.NaN);
|
||||
pos = F32(b, pos, float.NaN); // RequestPos: none
|
||||
pos = F32(b, pos, float.NaN);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.ListSeq); pos += 4;
|
||||
if (w.BodyDirty)
|
||||
{
|
||||
ReadOnlySpan<byte> body = w.Body;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], (uint)body.Length); pos += 4;
|
||||
body.CopyTo(b[pos..]);
|
||||
pos += body.Length;
|
||||
}
|
||||
else
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], UiFormat.BodyUnchanged); pos += 4;
|
||||
}
|
||||
}
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], (uint)pos);
|
||||
return pos;
|
||||
}
|
||||
|
||||
private static int Str8(Span<byte> b, int pos, ReadOnlySpan<byte> s)
|
||||
{
|
||||
int n = UiFormat.CutUtf8(s, UiFormat.MaxStr8);
|
||||
b[pos] = (byte)n;
|
||||
s[..n].CopyTo(b[(pos + 1)..]);
|
||||
return pos + 1 + n;
|
||||
}
|
||||
|
||||
private static int F32(Span<byte> b, int pos, float v)
|
||||
{
|
||||
BinaryPrimitives.WriteSingleLittleEndian(b[pos..], v);
|
||||
return pos + 4;
|
||||
}
|
||||
}
|
||||
474
Plugins/RynthCore.Plugin.RynthInventory/Ui/UiWindow.cs
Normal file
474
Plugins/RynthCore.Plugin.RynthInventory/Ui/UiWindow.cs
Normal file
|
|
@ -0,0 +1,474 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthInventory.Ui;
|
||||
|
||||
/// <summary>One input from the engine for a widget (a click, a new value, an open state).</summary>
|
||||
internal readonly struct UiEvent
|
||||
{
|
||||
public readonly ushort Type;
|
||||
public readonly bool Bool;
|
||||
public readonly int Int;
|
||||
public readonly string Text;
|
||||
public readonly bool Submitted;
|
||||
|
||||
public UiEvent(ushort type, bool b = false, int i = 0, string? text = null, bool submitted = false)
|
||||
{
|
||||
Type = type;
|
||||
Bool = b;
|
||||
Int = i;
|
||||
Text = text ?? string.Empty;
|
||||
Submitted = submitted;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One script window (engine API v71) and its recorder. A render pass records ImGui-style calls
|
||||
/// into a display list; every widget's handler (click, value change) is kept by its widget key
|
||||
/// until the next pass, so an event from the engine runs the code that drew that widget.
|
||||
///
|
||||
/// Widget keys are FNV-1a(id, window hash): RynthInventory names every widget itself, so it needs
|
||||
/// no ID stack. ImGui sees "label###id": its ID comes from the id alone, so labels can change.
|
||||
/// The engine echoes the key in events and keys its per-widget local values by it.
|
||||
/// </summary>
|
||||
internal sealed class UiWindow
|
||||
{
|
||||
public readonly string Key;
|
||||
public readonly byte[] KeyUtf8;
|
||||
public readonly uint Hash;
|
||||
|
||||
public string Title;
|
||||
public bool Visible;
|
||||
public bool ShowInBar = true;
|
||||
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
|
||||
|
||||
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
|
||||
public bool NeedsPass = true;
|
||||
public long NextPassMs;
|
||||
|
||||
// The list as recorded by the last pass, and what the engine last accepted.
|
||||
private byte[] _body = new byte[16 * 1024];
|
||||
private int _len;
|
||||
private int _ops;
|
||||
private bool _cut;
|
||||
private byte[] _sentBody = Array.Empty<byte>();
|
||||
private int _sentLen = -1;
|
||||
public uint ListSeq { get; private set; }
|
||||
internal bool BodyDirty;
|
||||
|
||||
// Header as last accepted by the engine.
|
||||
private string? _sentTitle;
|
||||
private uint _sentFlags;
|
||||
private float _sentDw = float.NaN, _sentDh, _sentMw, _sentMh;
|
||||
|
||||
private Dictionary<uint, Action<UiEvent>> _handlers = new();
|
||||
private Dictionary<uint, Action<UiEvent>> _next = new();
|
||||
private readonly Dictionary<uint, bool> _openStates = new();
|
||||
|
||||
// Child blocks: where each open block's u32 length sits, or -1 when the block was dropped.
|
||||
private readonly int[] _blocks = new int[16];
|
||||
private int _blockDepth;
|
||||
private byte[] _tmp = new byte[512];
|
||||
|
||||
public UiWindow(string key, string title)
|
||||
{
|
||||
Key = key;
|
||||
KeyUtf8 = Encoding.UTF8.GetBytes(key);
|
||||
Hash = UiFormat.Fnv1a(KeyUtf8);
|
||||
Title = title;
|
||||
}
|
||||
|
||||
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0);
|
||||
|
||||
public bool HeaderDirty =>
|
||||
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight
|
||||
|| _sentMw != MinWidth || _sentMh != MinHeight;
|
||||
|
||||
public ReadOnlySpan<byte> Body => _body.AsSpan(0, _len);
|
||||
|
||||
// ── Pass ────────────────────────────────────────────────────────────────
|
||||
|
||||
public void Begin()
|
||||
{
|
||||
_len = 0;
|
||||
_ops = 0;
|
||||
_cut = false;
|
||||
_blockDepth = 0;
|
||||
_next.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Ends the pass: closes open blocks, writes End, and notes whether the list changed.</summary>
|
||||
public void End()
|
||||
{
|
||||
while (_blockDepth > 0) EndChild();
|
||||
if (_cut)
|
||||
{
|
||||
// Room was kept for this line (see Room).
|
||||
int p = BeginOp(UiFormat.OpTextDisabled);
|
||||
Str("(more than fits in one window; narrow the list)");
|
||||
EndOp(p);
|
||||
}
|
||||
Ensure(4);
|
||||
_body[_len++] = UiFormat.OpEnd;
|
||||
_body[_len++] = 0;
|
||||
_body[_len++] = 0;
|
||||
_body[_len++] = 0;
|
||||
|
||||
(_handlers, _next) = (_next, _handlers);
|
||||
bool differs = _sentLen != _len || !_body.AsSpan(0, _len).SequenceEqual(_sentBody.AsSpan(0, _sentLen));
|
||||
if (differs && !BodyDirty) ListSeq++;
|
||||
BodyDirty = differs;
|
||||
}
|
||||
|
||||
/// <summary>The engine accepted the last submit: remember what it now has.</summary>
|
||||
internal void MarkSubmitted(bool bodySent)
|
||||
{
|
||||
if (bodySent)
|
||||
{
|
||||
if (_sentBody.Length < _len) _sentBody = new byte[_body.Length];
|
||||
_body.AsSpan(0, _len).CopyTo(_sentBody);
|
||||
_sentLen = _len;
|
||||
BodyDirty = false;
|
||||
}
|
||||
_sentTitle = Title;
|
||||
_sentFlags = Flags;
|
||||
_sentDw = DefaultWidth; _sentDh = DefaultHeight; _sentMw = MinWidth; _sentMh = MinHeight;
|
||||
}
|
||||
|
||||
/// <summary>The engine dropped every window (logout, empty submit): send everything again next time.</summary>
|
||||
internal void ForgetSubmitted()
|
||||
{
|
||||
_sentLen = -1;
|
||||
_sentTitle = null;
|
||||
BodyDirty = _len > 0;
|
||||
}
|
||||
|
||||
internal void Dispatch(uint widgetKey, in UiEvent e)
|
||||
{
|
||||
if (_handlers.TryGetValue(widgetKey, out Action<UiEvent>? h))
|
||||
h(e);
|
||||
NeedsPass = true;
|
||||
}
|
||||
|
||||
// ── Widgets ─────────────────────────────────────────────────────────────
|
||||
|
||||
public uint KeyOf(string id)
|
||||
{
|
||||
int max = Encoding.UTF8.GetMaxByteCount(id.Length);
|
||||
if (_tmp.Length < max) _tmp = new byte[Math.Max(max, _tmp.Length * 2)];
|
||||
int n = Encoding.UTF8.GetBytes(id, _tmp);
|
||||
return UiFormat.Fnv1a(_tmp.AsSpan(0, n), Hash);
|
||||
}
|
||||
|
||||
public void Text(string text) => WriteText(UiFormat.OpText, text);
|
||||
public void TextDisabled(string text) => WriteText(UiFormat.OpTextDisabled, text);
|
||||
public void TextWrapped(string text) => WriteText(UiFormat.OpTextWrapped, text);
|
||||
public void BulletText(string text) => WriteText(UiFormat.OpBulletText, text);
|
||||
public void SeparatorText(string text) => WriteText(UiFormat.OpSeparatorText, text);
|
||||
|
||||
public void TextColored(uint abgr, string text)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpTextColored);
|
||||
U32(abgr);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Separator()
|
||||
{
|
||||
if (!Room()) return;
|
||||
EndOp(BeginOp(UiFormat.OpSeparator));
|
||||
}
|
||||
|
||||
public void Spacing()
|
||||
{
|
||||
if (!Room()) return;
|
||||
EndOp(BeginOp(UiFormat.OpSpacing));
|
||||
}
|
||||
|
||||
/// <summary>Next item on the same line, <paramref name="x"/> logical units from the content start (0 = right after).</summary>
|
||||
public void SameLine(float x = 0f, float spacing = -1f)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpSameLine);
|
||||
F32(x);
|
||||
F32(spacing);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Dummy(float w, float h)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpDummy);
|
||||
F32(w);
|
||||
F32(h);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Button(string label, string id, Action onClick, float w = 0f, float h = 0f, bool small = false)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpButton);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
U8(small ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
|
||||
}
|
||||
|
||||
public void SmallButton(string label, string id, Action onClick) => Button(label, id, onClick, small: true);
|
||||
|
||||
/// <summary>A button drawn highlighted when <paramref name="active"/> (tabs, toggles).</summary>
|
||||
public void ToggleButton(string label, string id, bool active, Action onClick, bool small = false)
|
||||
{
|
||||
if (active)
|
||||
{
|
||||
PushStyleColor(UiFormat.ColButton, UiColors.TabActive);
|
||||
PushStyleColor(UiFormat.ColButtonHovered, UiColors.TabActiveHover);
|
||||
}
|
||||
Button(label, id, onClick, small: small);
|
||||
if (active) PopStyleColor(2);
|
||||
}
|
||||
|
||||
public void Checkbox(string label, string id, bool value, Action<bool> set)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpCheckbox);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U8(value ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvBool) set(e.Bool); };
|
||||
}
|
||||
|
||||
/// <summary>A text box; <paramref name="set"/> gets every edit (submitted = Enter was pressed).</summary>
|
||||
public void InputText(string label, string id, string value, int maxLen, Action<string> set, uint flags = 0)
|
||||
{
|
||||
if (!Room()) return;
|
||||
maxLen = Math.Clamp(maxLen, 1, UiFormat.MaxString);
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpInputText);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
Str(value ?? string.Empty, maxLen);
|
||||
U16((ushort)maxLen);
|
||||
U32(flags);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text); };
|
||||
}
|
||||
|
||||
public void Combo(string label, string id, int index, IReadOnlyList<string> items, Action<int> set)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int count = Math.Min(items.Count, 512);
|
||||
int p = BeginOp(UiFormat.OpCombo);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
I32(index);
|
||||
U16((ushort)count);
|
||||
for (int i = 0; i < count; i++) Str(items[i]);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvInt) set(e.Int); };
|
||||
}
|
||||
|
||||
public void Selectable(string label, string id, bool selected, Action onClick, float w = 0f, float h = 0f)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpSelectable);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U8(selected ? (byte)1 : (byte)0);
|
||||
U32(0);
|
||||
F32(w);
|
||||
F32(h);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
|
||||
}
|
||||
|
||||
public void ProgressBar(float fraction, float w, float h, string overlay)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpProgressBar);
|
||||
F32(float.IsFinite(fraction) ? Math.Clamp(fraction, 0f, 1f) : 0f);
|
||||
F32(w);
|
||||
F32(h);
|
||||
Str(overlay ?? string.Empty);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An icon (op level 2): <paramref name="kind"/> <see cref="UiFormat.IconKindIcon"/> = a 0x06
|
||||
/// texture id, <see cref="UiFormat.IconKindObject"/> = a live object. Engines without op level
|
||||
/// 2 skip it (the caller checks first so the layout doesn't shift).
|
||||
/// </summary>
|
||||
public void Image(byte kind, uint id, float w, float h)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpImage);
|
||||
U8(kind);
|
||||
U32(id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
F32(0f); F32(0f); // uv0
|
||||
F32(1f); F32(1f); // uv1
|
||||
U32(0xFFFFFFFFu); // tint: as is
|
||||
U32(0u); // border: none
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>Tooltip for the item just drawn.</summary>
|
||||
public void Tooltip(string text)
|
||||
{
|
||||
if (!Room() || string.IsNullOrEmpty(text)) return;
|
||||
int p = BeginOp(UiFormat.OpSetItemTooltip);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void PushStyleColor(int colId, uint abgr)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpPushStyleColor);
|
||||
U16((ushort)colId);
|
||||
U32(abgr);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>Pops are dropped when the list is cut short; the engine pops leftovers at the scope's end.</summary>
|
||||
public void PopStyleColor(int count = 1)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpPopStyleColor);
|
||||
U8((byte)Math.Clamp(count, 1, 255));
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A collapsing header; returns whether to record its contents. The open state is the
|
||||
/// player's (kept from the engine's Open events), so a header stays as they left it.
|
||||
/// </summary>
|
||||
public bool CollapsingHeader(string label, string id, bool defaultOpen = false)
|
||||
{
|
||||
uint key = KeyOf(id);
|
||||
bool open = _openStates.TryGetValue(key, out bool o) ? o : defaultOpen;
|
||||
if (!Room()) return false;
|
||||
int p = BeginOp(UiFormat.OpCollapsingHeader);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U32(defaultOpen ? UiFormat.TreeDefaultOpen : 0);
|
||||
U8(open ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvOpen) _openStates[key] = e.Bool; };
|
||||
return open;
|
||||
}
|
||||
|
||||
/// <summary>A scrolling region; h 0 = fill the rest of the window. Must be closed with <see cref="EndChild"/>.</summary>
|
||||
public void BeginChild(string id, float w = 0f, float h = 0f, bool border = true)
|
||||
{
|
||||
if (_blockDepth >= _blocks.Length) throw new InvalidOperationException("child regions nested too deep");
|
||||
if (!Room())
|
||||
{
|
||||
_blocks[_blockDepth++] = -1;
|
||||
return;
|
||||
}
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpChild, UiFormat.OpHasBlock);
|
||||
U32(key);
|
||||
Str(id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
U8(border ? (byte)1 : (byte)0);
|
||||
U32(0);
|
||||
EndOp(p);
|
||||
_blocks[_blockDepth++] = _len;
|
||||
U32(0); // BlockLength, patched by EndChild
|
||||
}
|
||||
|
||||
public void EndChild()
|
||||
{
|
||||
if (_blockDepth == 0) return;
|
||||
int at = _blocks[--_blockDepth];
|
||||
if (at < 0) return;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(at), (uint)(_len - (at + 4)));
|
||||
}
|
||||
|
||||
// ── Writing ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Whether another op fits. Room is kept for the closing "list cut short" line and the End
|
||||
/// op, so the list never goes over the engine's limits (it refuses an over-limit list whole).
|
||||
/// </summary>
|
||||
private bool Room()
|
||||
{
|
||||
if (_cut) return false;
|
||||
if (_ops < UiFormat.MaxOps - 8 && _len < UiFormat.MaxBodyBytes - 4096) return true;
|
||||
_cut = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void WriteText(byte code, string text)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(code);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
private int BeginOp(byte code, byte opFlags = 0)
|
||||
{
|
||||
_ops++;
|
||||
Ensure(4);
|
||||
_body[_len++] = code;
|
||||
_body[_len++] = opFlags;
|
||||
_len += 2; // PayloadLength, patched by EndOp
|
||||
return _len;
|
||||
}
|
||||
|
||||
private void EndOp(int payloadStart)
|
||||
{
|
||||
int length = _len - payloadStart;
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(payloadStart - 2), (ushort)Math.Min(length, ushort.MaxValue));
|
||||
}
|
||||
|
||||
private void Ensure(int extra)
|
||||
{
|
||||
if (_len + extra <= _body.Length) return;
|
||||
int size = _body.Length;
|
||||
while (size < _len + extra) size *= 2;
|
||||
Array.Resize(ref _body, size);
|
||||
}
|
||||
|
||||
private void U8(byte v) { Ensure(1); _body[_len++] = v; }
|
||||
private void U16(ushort v) { Ensure(2); BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), v); _len += 2; }
|
||||
private void U32(uint v) { Ensure(4); BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
|
||||
private void I32(int v) { Ensure(4); BinaryPrimitives.WriteInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
|
||||
|
||||
private void F32(float v)
|
||||
{
|
||||
Ensure(4);
|
||||
BinaryPrimitives.WriteSingleLittleEndian(_body.AsSpan(_len), float.IsFinite(v) ? v : 0f);
|
||||
_len += 4;
|
||||
}
|
||||
|
||||
/// <summary>str: u16 length + UTF-8, cut to <paramref name="maxBytes"/> on a character boundary.</summary>
|
||||
private void Str(string s, int maxBytes = UiFormat.MaxString)
|
||||
{
|
||||
s ??= string.Empty;
|
||||
ReadOnlySpan<char> src = s.Length > maxBytes ? s.AsSpan(0, maxBytes) : s.AsSpan();
|
||||
Ensure(2 + Encoding.UTF8.GetMaxByteCount(src.Length));
|
||||
int at = _len + 2;
|
||||
Span<byte> dst = _body.AsSpan(at);
|
||||
int n = UiFormat.CutUtf8(dst[..Encoding.UTF8.GetBytes(src, dst)], maxBytes);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), (ushort)n);
|
||||
_len = at + n;
|
||||
}
|
||||
}
|
||||
401
Plugins/RynthCore.Plugin.RynthInventory/Views/InventoryView.cs
Normal file
401
Plugins/RynthCore.Plugin.RynthInventory/Views/InventoryView.cs
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using RynthCore.Plugin.RynthInventory.Data;
|
||||
using RynthCore.Plugin.RynthInventory.Ui;
|
||||
|
||||
namespace RynthCore.Plugin.RynthInventory.Views;
|
||||
|
||||
/// <summary>
|
||||
/// The Global Inventory window: a search page (every character on every server, filters,
|
||||
/// totals, results, details) and a characters page (snapshot ages, forget). Recorded on the
|
||||
/// pump thread, replayed by the engine.
|
||||
/// </summary>
|
||||
internal sealed class InventoryView
|
||||
{
|
||||
public const int TabSearch = 0, TabCharacters = 1;
|
||||
private const int PageSize = 100;
|
||||
private const float RowIcon = 18f, DetailIcon = 32f, DetailsHeight = 190f;
|
||||
|
||||
private static readonly string[] SortNames = { "Name", "Character", "Count", "Value", "Burden", "Category", "Last seen" };
|
||||
|
||||
private readonly InventoryContext _c;
|
||||
public int Tab;
|
||||
|
||||
private string _search = string.Empty;
|
||||
private string? _server; // null = all
|
||||
private string? _characterKey; // null = all
|
||||
private string? _category; // null = all
|
||||
private int _page;
|
||||
private string? _selectedKey;
|
||||
private string? _confirmForget;
|
||||
private string _message = string.Empty;
|
||||
|
||||
private InventoryResult? _result;
|
||||
private int _resultRevision = -1;
|
||||
private bool _resultDirty = true;
|
||||
|
||||
public InventoryView(InventoryContext c) => _c = c;
|
||||
|
||||
/// <summary>Opens on the search page with this text (from "/ginv text").</summary>
|
||||
public void SetSearch(string text)
|
||||
{
|
||||
_search = text ?? string.Empty;
|
||||
Tab = TabSearch;
|
||||
_page = 0;
|
||||
_resultDirty = true;
|
||||
}
|
||||
|
||||
private void Invalidate()
|
||||
{
|
||||
_resultDirty = true;
|
||||
_page = 0;
|
||||
}
|
||||
|
||||
public void Draw(UiWindow w)
|
||||
{
|
||||
w.ToggleButton("Search", "tab.search", Tab == TabSearch, () => Tab = TabSearch, small: true);
|
||||
w.SameLine();
|
||||
int chars = _c.Index?.Characters.Count ?? 0;
|
||||
w.ToggleButton($"Characters ({chars})", "tab.chars", Tab == TabCharacters, () => Tab = TabCharacters, small: true);
|
||||
w.SameLine();
|
||||
w.TextDisabled(StatusLine());
|
||||
w.Separator();
|
||||
|
||||
if (_c.Index == null)
|
||||
{
|
||||
w.TextDisabled(_c.Loading ? "Reading the inventory files..." : "No inventory read yet.");
|
||||
return;
|
||||
}
|
||||
if (Tab == TabCharacters) DrawCharacters(w, _c.Index);
|
||||
else DrawSearch(w, _c.Index);
|
||||
}
|
||||
|
||||
private string StatusLine()
|
||||
{
|
||||
if (!_c.InWorld) return "Not logged in.";
|
||||
if (_c.OpenStorage != 0) return "Recording " + _c.OpenStorageLabel;
|
||||
if (_c.Live == null) return "Scanning " + _c.Character + "...";
|
||||
if (_c.LastSaveError.Length > 0) return "Couldn't save: " + _c.LastSaveError;
|
||||
if (_c.LastSavedUtc == default) return _c.Character + ": not saved yet";
|
||||
return _c.Character + " saved " + InventoryIndex.Age(_c.LastSavedUtc, _c.UtcNow);
|
||||
}
|
||||
|
||||
// ── Search page ─────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawSearch(UiWindow w, InventoryIndex index)
|
||||
{
|
||||
InventorySettings s = _c.Settings;
|
||||
w.InputText("Search", "q", _search, 128, v => { _search = v; Invalidate(); }, UiFormat.InputAutoSelectAll);
|
||||
|
||||
// Servers: the one you're on first, the others labelled.
|
||||
w.ToggleButton("All servers", "srv.all", _server == null, () => { _server = null; _characterKey = null; Invalidate(); }, small: true);
|
||||
for (int i = 0; i < index.Servers.Count; i++)
|
||||
{
|
||||
string srv = index.Servers[i];
|
||||
bool here = InventoryIndex.SameName(srv, index.CurrentServer);
|
||||
w.SameLine();
|
||||
w.ToggleButton(here ? srv + " (here)" : srv, "srv." + i, _server != null && InventoryIndex.SameName(_server, srv),
|
||||
() => { _server = srv; _characterKey = null; Invalidate(); }, small: true);
|
||||
}
|
||||
|
||||
w.Checkbox("Storage", "opt.storage", s.IncludeStorage, v => { s.IncludeStorage = v; s.Save(); Invalidate(); });
|
||||
w.SameLine();
|
||||
w.Checkbox("Equipped", "opt.equipped", s.IncludeEquipped, v => { s.IncludeEquipped = v; s.Save(); Invalidate(); });
|
||||
w.SameLine();
|
||||
w.Checkbox("Spells and material too", "opt.spells", s.SearchSpells, v => { s.SearchSpells = v; s.Save(); Invalidate(); });
|
||||
w.Tooltip("Also match the search against material, armor set and spell names (e.g. \"legendary strength\").");
|
||||
w.SameLine();
|
||||
w.Checkbox("Group by name", "opt.group", s.GroupByName, v => { s.GroupByName = v; s.Save(); Invalidate(); _selectedKey = null; });
|
||||
|
||||
// Character filter (characters of the chosen server).
|
||||
var charKeys = new List<string?> { null };
|
||||
var charNames = new List<string> { "All characters" };
|
||||
foreach (CharacterInfo ci in index.Characters)
|
||||
{
|
||||
if (_server != null && !InventoryIndex.SameName(ci.Server, _server)) continue;
|
||||
charKeys.Add(ci.Key);
|
||||
charNames.Add(ci.IsCurrentServer ? ci.Name : $"{ci.Name} [{ci.Server}]");
|
||||
}
|
||||
int charIndex = Math.Max(0, charKeys.IndexOf(_characterKey));
|
||||
w.Combo("Character", "f.char", charIndex, charNames, i => { _characterKey = i > 0 && i < charKeys.Count ? charKeys[i] : null; Invalidate(); });
|
||||
|
||||
var catNames = new List<string> { "All categories" };
|
||||
int catIndex = 0;
|
||||
for (int i = 0; i < ItemCategory.All.Length; i++)
|
||||
{
|
||||
catNames.Add(ItemCategory.All[i].Label);
|
||||
if (ItemCategory.All[i].Id == _category) catIndex = i + 1;
|
||||
}
|
||||
w.Combo("Category", "f.cat", catIndex, catNames, i => { _category = i > 0 && i <= ItemCategory.All.Length ? ItemCategory.All[i - 1].Id : null; Invalidate(); });
|
||||
|
||||
w.Combo("Sort", "f.sort", Math.Clamp(s.Sort, 0, SortNames.Length - 1), SortNames, i => { s.Sort = i; s.Save(); Invalidate(); });
|
||||
w.SameLine();
|
||||
w.Checkbox("Descending", "f.desc", s.Descending, v => { s.Descending = v; s.Save(); Invalidate(); });
|
||||
|
||||
InventoryResult result = Result(index);
|
||||
w.Separator();
|
||||
if (result.Rows.Count == 0)
|
||||
{
|
||||
w.TextDisabled(index.Rows.Count == 0 ? "No items recorded yet. Each character is scanned when it logs in with RynthInventory loaded." : "Nothing found.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Totals: "Pyreal: 12,345 across 4 characters".
|
||||
int shownTotals = Math.Min(3, result.Totals.Count);
|
||||
for (int i = 0; i < shownTotals; i++)
|
||||
w.TextColored(UiColors.Gold, InventoryIndex.TotalText(result.Totals[i]));
|
||||
if (result.Totals.Count > shownTotals)
|
||||
w.TextDisabled($"...and {result.Totals.Count - shownTotals} more kinds of item; {result.TotalCount.ToString("N0", CultureInfo.InvariantCulture)} items in all.");
|
||||
|
||||
bool grouped = s.GroupByName;
|
||||
int count = grouped ? result.Totals.Count : result.Rows.Count;
|
||||
int pages = Math.Max(1, (count + PageSize - 1) / PageSize);
|
||||
_page = Math.Clamp(_page, 0, pages - 1);
|
||||
string what = grouped ? $"{count} item names" : $"{count} results";
|
||||
w.TextDisabled($"{what} on {result.CharacterCount} character{(result.CharacterCount == 1 ? "" : "s")}");
|
||||
if (pages > 1)
|
||||
{
|
||||
w.SameLine();
|
||||
if (_page > 0) { w.SmallButton("< Prev", "pg.prev", () => _page--); w.SameLine(); }
|
||||
w.TextDisabled($"page {_page + 1} of {pages}");
|
||||
if (_page < pages - 1) { w.SameLine(); w.SmallButton("Next >", "pg.next", () => _page++); }
|
||||
}
|
||||
|
||||
object? selected = FindSelected(result, grouped);
|
||||
w.BeginChild("results", 0f, selected != null ? -DetailsHeight : 0f, border: false);
|
||||
int start = _page * PageSize, end = Math.Min(count, start + PageSize);
|
||||
for (int i = start; i < end; i++)
|
||||
{
|
||||
if (grouped) DrawGroupRow(w, result.Totals[i]);
|
||||
else DrawRow(w, result.Rows[i]);
|
||||
}
|
||||
w.EndChild();
|
||||
|
||||
if (selected != null)
|
||||
{
|
||||
w.Separator();
|
||||
w.BeginChild("details", 0f, 0f, border: false);
|
||||
if (selected is InventoryRow row) DrawDetails(w, row);
|
||||
else if (selected is InventoryTotal total) DrawGroupDetails(w, total);
|
||||
w.EndChild();
|
||||
}
|
||||
}
|
||||
|
||||
private InventoryResult Result(InventoryIndex index)
|
||||
{
|
||||
if (_result != null && !_resultDirty && _resultRevision == _c.IndexRevision) return _result;
|
||||
InventorySettings s = _c.Settings;
|
||||
_result = index.Query(new InventoryQuery
|
||||
{
|
||||
Text = _search,
|
||||
Server = _server,
|
||||
CharacterKey = _characterKey,
|
||||
Category = _category,
|
||||
IncludeEquipped = s.IncludeEquipped,
|
||||
IncludeStorage = s.IncludeStorage,
|
||||
SearchSpells = s.SearchSpells,
|
||||
Sort = (InventorySort)Math.Clamp(s.Sort, 0, SortNames.Length - 1),
|
||||
Descending = s.Descending,
|
||||
});
|
||||
_resultRevision = _c.IndexRevision;
|
||||
_resultDirty = false;
|
||||
return _result;
|
||||
}
|
||||
|
||||
private static string RowKey(InventoryRow r) => r.Owner.Key + "|" + (r.Storage?.Id ?? 0).ToString(CultureInfo.InvariantCulture) + "|" + r.Item.Id.ToString(CultureInfo.InvariantCulture);
|
||||
private static string GroupKey(InventoryTotal t) => "g|" + t.Name.ToLowerInvariant();
|
||||
|
||||
private object? FindSelected(InventoryResult result, bool grouped)
|
||||
{
|
||||
if (_selectedKey == null) return null;
|
||||
if (grouped)
|
||||
{
|
||||
foreach (InventoryTotal t in result.Totals) if (GroupKey(t) == _selectedKey) return t;
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (InventoryRow r in result.Rows) if (RowKey(r) == _selectedKey) return r;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void Select(string key) => _selectedKey = _selectedKey == key ? null : key;
|
||||
|
||||
private void DrawRow(UiWindow w, InventoryRow r)
|
||||
{
|
||||
ItemRecord it = r.Item;
|
||||
bool icons = _c.Settings.ShowIcons && _c.IconsAvailable;
|
||||
if (icons) { DrawIcon(w, it, RowIcon); w.SameLine(); }
|
||||
|
||||
string owner = r.Owner.IsCurrentServer ? r.Owner.Name : $"[{r.Owner.Server}] {r.Owner.Name}";
|
||||
string label = $"{it.Name}{StackText(it)} - {owner}: {r.Where}";
|
||||
if (IsStale(r.SeenUtc)) label += $" (seen {InventoryIndex.Age(r.SeenUtc, _c.UtcNow)})";
|
||||
string key = RowKey(r);
|
||||
uint? color = !r.Owner.IsCurrentServer ? UiColors.OtherServer : IsStale(r.SeenUtc) ? UiColors.Stale : null;
|
||||
if (color != null) w.PushStyleColor(UiFormat.ColText, color.Value);
|
||||
w.Selectable(label, "r." + key, _selectedKey == key, () => Select(key), 0f, icons ? RowIcon : 0f);
|
||||
if (color != null) w.PopStyleColor();
|
||||
}
|
||||
|
||||
private void DrawGroupRow(UiWindow w, InventoryTotal t)
|
||||
{
|
||||
bool icons = _c.Settings.ShowIcons && _c.IconsAvailable;
|
||||
if (icons && t.Holders.Count > 0) { DrawIcon(w, t.Holders[0].Item, RowIcon); w.SameLine(); }
|
||||
string label = $"{t.Name} x{t.Count.ToString("N0", CultureInfo.InvariantCulture)} - {t.Characters} character{(t.Characters == 1 ? "" : "s")}";
|
||||
if (t.Servers > 1) label += $", {t.Servers} servers";
|
||||
string key = GroupKey(t);
|
||||
w.Selectable(label, "g." + key, _selectedKey == key, () => Select(key), 0f, icons ? RowIcon : 0f);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The item's picture: underlay, icon and overlay drawn over each other. Each layer after
|
||||
/// the first goes back to the row's start (SameLine at x 0.01: a borderless child has no
|
||||
/// padding, so that is where the row began). Only at the start of a row in a borderless child.
|
||||
/// </summary>
|
||||
private static void DrawIcon(UiWindow w, ItemRecord it, float size)
|
||||
{
|
||||
bool drew = false;
|
||||
if (it.Underlay != 0) { w.Image(UiFormat.IconKindIcon, it.Underlay, size, size); drew = true; }
|
||||
if (it.Icon != 0)
|
||||
{
|
||||
if (drew) w.SameLine(0.01f);
|
||||
w.Image(UiFormat.IconKindIcon, it.Icon, size, size);
|
||||
drew = true;
|
||||
}
|
||||
if (it.Overlay != 0)
|
||||
{
|
||||
if (drew) w.SameLine(0.01f);
|
||||
w.Image(UiFormat.IconKindIcon, it.Overlay, size, size);
|
||||
drew = true;
|
||||
}
|
||||
if (!drew) w.Dummy(size, size);
|
||||
}
|
||||
|
||||
private static string StackText(ItemRecord it) =>
|
||||
it.Stack > 1 ? " x" + it.Stack.ToString("N0", CultureInfo.InvariantCulture) : string.Empty;
|
||||
|
||||
private bool IsStale(DateTime seenUtc) =>
|
||||
seenUtc != default && (_c.UtcNow - seenUtc).TotalDays >= Math.Max(1, _c.Settings.StaleDays);
|
||||
|
||||
private void DrawDetails(UiWindow w, InventoryRow r)
|
||||
{
|
||||
ItemRecord it = r.Item;
|
||||
if (_c.Settings.ShowIcons && _c.IconsAvailable) { DrawIcon(w, it, DetailIcon); w.SameLine(); }
|
||||
w.TextColored(UiColors.Gold, it.Name + StackText(it));
|
||||
w.SameLine();
|
||||
w.SmallButton("Close", "d.close", () => _selectedKey = null);
|
||||
|
||||
string who = r.Owner.Name + " on " + r.Owner.Server;
|
||||
if (!string.IsNullOrEmpty(r.Owner.Account) && r.Owner.Account != "unknown") who += $" (account {r.Owner.Account})";
|
||||
if (r.Owner.IsCurrentCharacter) who += " - this character";
|
||||
else if (!r.Owner.IsCurrentServer) who += " - another server";
|
||||
w.Text("Owner: " + who);
|
||||
w.Text("Where: " + r.Where);
|
||||
if (r.Storage != null)
|
||||
w.TextDisabled($"Storage seen open {InventoryIndex.Age(r.Storage.SeenUtc, _c.UtcNow)}; it is only updated when a character opens it.");
|
||||
else
|
||||
w.Text("Seen: " + InventoryIndex.Age(r.SeenUtc, _c.UtcNow) + (IsStale(r.SeenUtc) ? " (stale: log that character in to refresh)" : ""));
|
||||
|
||||
var parts = new List<string> { ItemCategory.Label(it.Category) };
|
||||
if (it.Value != 0) parts.Add("value " + it.Value.ToString("N0", CultureInfo.InvariantCulture));
|
||||
if (it.Burden != 0) parts.Add("burden " + it.Burden.ToString("N0", CultureInfo.InvariantCulture));
|
||||
if (it.MaxStack > 1) parts.Add($"stack {it.Stack.ToString("N0", CultureInfo.InvariantCulture)}/{it.MaxStack.ToString("N0", CultureInfo.InvariantCulture)}");
|
||||
w.Text(string.Join(", ", parts));
|
||||
|
||||
var more = new List<string>();
|
||||
string material = ItemNames.Material(it.Material);
|
||||
if (material.Length > 0) more.Add(material);
|
||||
if (it.Workmanship > 0) more.Add("workmanship " + it.Workmanship.ToString(CultureInfo.InvariantCulture));
|
||||
if (it.ArmorLevel > 0) more.Add("armor level " + it.ArmorLevel.ToString(CultureInfo.InvariantCulture));
|
||||
if (it.MaxUses > 0) more.Add($"uses {it.Uses}/{it.MaxUses}");
|
||||
string set = ItemNames.Set(it.SetId);
|
||||
if (set.Length > 0) more.Add(set);
|
||||
if (more.Count > 0) w.Text(string.Join(", ", more));
|
||||
if (it.Place == ItemPlace.Equipped && it.Slot != 0) w.Text("Slot: " + ItemNames.Slot(it.Slot));
|
||||
if (it.SpellNames.Length > 0) w.TextWrapped("Spells: " + string.Join(", ", it.SpellNames));
|
||||
else if (it.Spells.Length > 0) w.TextWrapped("Spells: " + string.Join(", ", Array.ConvertAll(it.Spells, x => "#" + x.ToString(CultureInfo.InvariantCulture))));
|
||||
if (!it.Identified && it.Category is ItemCategory.Weapon or ItemCategory.Armor or ItemCategory.Clothing or ItemCategory.Jewelry or ItemCategory.Caster)
|
||||
w.TextDisabled("Not identified when scanned: spells, workmanship and set may be missing.");
|
||||
w.TextDisabled($"Item 0x{it.Id:X8}" + (it.Wcid != 0 ? $", class {it.Wcid}" : ""));
|
||||
}
|
||||
|
||||
private void DrawGroupDetails(UiWindow w, InventoryTotal t)
|
||||
{
|
||||
if (_c.Settings.ShowIcons && _c.IconsAvailable && t.Holders.Count > 0) { DrawIcon(w, t.Holders[0].Item, DetailIcon); w.SameLine(); }
|
||||
w.TextColored(UiColors.Gold, InventoryIndex.TotalText(t));
|
||||
w.SameLine();
|
||||
w.SmallButton("Close", "d.close", () => _selectedKey = null);
|
||||
int shown = 0;
|
||||
foreach (InventoryRow r in t.Holders)
|
||||
{
|
||||
if (shown++ >= 60) { w.TextDisabled($"...and {t.Holders.Count - 60} more."); break; }
|
||||
string owner = r.Owner.IsCurrentServer ? r.Owner.Name : $"[{r.Owner.Server}] {r.Owner.Name}";
|
||||
string line = $"{owner}: {r.Where}{StackText(r.Item)}";
|
||||
if (IsStale(r.SeenUtc)) w.TextColored(UiColors.Stale, line + $" (seen {InventoryIndex.Age(r.SeenUtc, _c.UtcNow)})");
|
||||
else if (!r.Owner.IsCurrentServer) w.TextColored(UiColors.OtherServer, line);
|
||||
else w.Text(line);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Characters page ─────────────────────────────────────────────────────
|
||||
|
||||
private void DrawCharacters(UiWindow w, InventoryIndex index)
|
||||
{
|
||||
w.SmallButton("Rescan now", "c.rescan", () => { _c.RequestRescan(); _message = "Rescanning this character; it saves within a few seconds."; });
|
||||
w.SameLine();
|
||||
w.SmallButton("Reload files", "c.reload", () => { _c.RequestReload(); _message = "Reading the inventory files again."; });
|
||||
w.SameLine();
|
||||
w.Checkbox("Icons", "c.icons", _c.Settings.ShowIcons, v => { _c.Settings.ShowIcons = v; _c.Settings.Save(); });
|
||||
if (!_c.IconsAvailable) { w.SameLine(); w.TextDisabled("(this engine can't draw icons in plugin windows)"); }
|
||||
if (_message.Length > 0) w.TextColored(UiColors.Green, _message);
|
||||
if (_c.BrokenFiles > 0) w.TextColored(UiColors.Red, $"{_c.BrokenFiles} file(s) couldn't be read and were skipped.");
|
||||
w.TextDisabled($"Snapshots older than {_c.Settings.StaleDays} days are shown as stale. Files: {_c.Store.Root}");
|
||||
|
||||
w.BeginChild("chars", 0f, 0f, border: false);
|
||||
string? lastServer = null;
|
||||
foreach (CharacterInfo ci in index.Characters)
|
||||
{
|
||||
if (lastServer == null || !InventoryIndex.SameName(lastServer, ci.Server))
|
||||
{
|
||||
lastServer = ci.Server;
|
||||
w.SeparatorText(ci.IsCurrentServer ? ci.Server + " (this server)" : ci.Server);
|
||||
}
|
||||
DrawCharacter(w, ci);
|
||||
}
|
||||
if (index.Characters.Count == 0) w.TextDisabled("No characters recorded yet.");
|
||||
w.EndChild();
|
||||
}
|
||||
|
||||
private void DrawCharacter(UiWindow w, CharacterInfo ci)
|
||||
{
|
||||
bool stale = IsStale(ci.ScannedUtc);
|
||||
string line = $"{ci.Name}{(ci.IsCurrentCharacter ? " (you)" : "")} - {ci.ItemCount} items"
|
||||
+ (ci.StorageCount > 0 ? $", {ci.StorageCount} storage" : "")
|
||||
+ $" - scanned {InventoryIndex.Age(ci.ScannedUtc, _c.UtcNow)}"
|
||||
+ (stale ? " (stale)" : "");
|
||||
if (stale) w.TextColored(UiColors.Stale, line);
|
||||
else w.Text(line);
|
||||
if (!string.IsNullOrEmpty(ci.Account) && ci.Account != "unknown") w.Tooltip("Account: " + ci.Account);
|
||||
w.SameLine();
|
||||
string key = ci.Key;
|
||||
w.SmallButton("Forget", "forget." + key, () => _confirmForget = key);
|
||||
if (_confirmForget == key)
|
||||
{
|
||||
string warn = ci.IsCurrentCharacter
|
||||
? $"Forget {ci.Name}? You're logged into it, so it comes back at the next scan."
|
||||
: $"Forget {ci.Name} on {ci.Server}? Use this for deleted or renamed characters. The file is moved to the _forgotten folder, not deleted.";
|
||||
w.TextColored(UiColors.Red, warn);
|
||||
w.SmallButton("Yes, forget", "forget.yes." + key, () =>
|
||||
{
|
||||
_message = _c.Forget(ci);
|
||||
_confirmForget = null;
|
||||
_selectedKey = null;
|
||||
});
|
||||
w.SameLine();
|
||||
w.SmallButton("Cancel", "forget.no." + key, () => _confirmForget = null);
|
||||
}
|
||||
foreach (StorageRecord st in ci.Storage)
|
||||
w.BulletText($"{(string.IsNullOrEmpty(st.Label) ? st.Name : st.Label)}: {st.Items.Count} items, seen {InventoryIndex.Age(st.SeenUtc, _c.UtcNow)}");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue