Snapshot for release 2026.10.23.1 (internal 7581cff)

This commit is contained in:
Tom Bohar 2026-10-23 16:34:02 -04:00
commit 92f28bd243
73 changed files with 12203 additions and 308 deletions

View file

@ -0,0 +1,85 @@
using System;
namespace RynthCore.Plugin.RynthDefective.Model;
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection }
/// <summary>A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).</summary>
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "");
internal static class DefCommandParser
{
public const string Usage =
"/rdef [use <slot or item name> | set <slot> [item name] | clear <slot> | bind <slot> <key> | unbind <slot> | "
+ "weapons [search] | fav | slots <count> | list | status | panels (the game panel buttons) | selection]";
/// <summary>Parses the arguments after "/rdef" (blank = show or hide the bar).</summary>
public static DefCommand Parse(string? args)
{
string a = (args ?? string.Empty).Trim();
if (a.Length == 0) return new DefCommand(DefVerb.Toggle);
int sp = a.IndexOf(' ');
string verb = (sp < 0 ? a : a[..sp]).ToLowerInvariant();
string rest = sp < 0 ? string.Empty : a[(sp + 1)..].Trim();
switch (verb)
{
case "help": case "?": return new DefCommand(DefVerb.Help);
case "list": case "ls": return new DefCommand(DefVerb.List);
case "status": return new DefCommand(DefVerb.Status);
case "panels": case "panel": return new DefCommand(DefVerb.Panels);
case "selection": case "target":
// "/rdef selection 0x80001234": select that object (a test hook for the Selection window).
return new DefCommand(DefVerb.Selection, Text: rest);
case "fav": case "favourite": case "favorite": return new DefCommand(DefVerb.Favourite);
case "weapons": case "weapon": case "picker": return new DefCommand(DefVerb.Weapons, Text: rest);
case "use": case "wield": case "equip":
if (rest.Length == 0) return Fail($"Use which slot or item? e.g. /rdef use 1 or /rdef use Peerless Healing Kit");
return TrySlot(rest, out int n) ? new DefCommand(DefVerb.Use, n) : new DefCommand(DefVerb.Use, Text: rest);
case "set":
{
SplitSlot(rest, out string? slotText, out string tail);
if (slotText == null || !TrySlot(slotText, out int slot)) return Fail("Which slot? e.g. /rdef set 3 (the item selected in the game goes in slot 3) or /rdef set 3 Peerless Healing Kit");
return new DefCommand(DefVerb.Set, slot, tail);
}
case "clear":
{
return TrySlot(rest, out int slot) ? new DefCommand(DefVerb.Clear, slot) : Fail("Which slot? e.g. /rdef clear 3");
}
case "bind":
{
SplitSlot(rest, out string? slotText, out string key);
if (slotText == null || !TrySlot(slotText, out int slot) || key.Length == 0)
return Fail("Usage: /rdef bind <slot> <key>, e.g. /rdef bind 3 F9 or /rdef bind 3 Ctrl+1");
return new DefCommand(DefVerb.Bind, slot, key);
}
case "unbind":
return TrySlot(rest, out int us) ? new DefCommand(DefVerb.Unbind, us) : Fail("Which slot? e.g. /rdef unbind 3");
case "slots":
return int.TryParse(rest, out int count) && count >= DefSettings.SlotsMin && count <= DefSettings.SlotsMax
? new DefCommand(DefVerb.Slots, count)
: Fail($"How many slots? {DefSettings.SlotsMin} to {DefSettings.SlotsMax}, e.g. /rdef slots 10");
default:
// "/rdef Stamina Kit" is a shorthand for use.
return new DefCommand(DefVerb.Use, Text: a);
}
}
/// <summary>The slot number a hotkey runs for slot <paramref name="slot"/> (1-based).</summary>
public static string UseCommand(int slot) => "/rdef use " + slot;
private static bool TrySlot(string text, out int slot)
{
slot = 0;
return int.TryParse(text.Trim(), out slot) && slot >= 1 && slot <= DefSettings.SlotsMax;
}
private static void SplitSlot(string rest, out string? first, out string tail)
{
int sp = rest.IndexOf(' ');
first = rest.Length == 0 ? null : (sp < 0 ? rest : rest[..sp]);
tail = sp < 0 ? string.Empty : rest[(sp + 1)..].Trim();
}
private static DefCommand Fail(string error) => new(DefVerb.Error, Error: error);
}

View file

@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>One slot of the bar: an item (or nothing) and how pressing it uses that item.</summary>
internal sealed class DefSlot
{
/// <summary>The item the slot holds; null = empty.</summary>
public ItemRef? Item;
/// <summary>How pressing it uses the item. <see cref="UseMode.Auto"/> picks by what the item is.</summary>
public UseMode Mode = UseMode.Auto;
public bool Empty => Item == null;
public DefSlot Clone() => new() { Item = Item?.Clone(), Mode = Mode };
}
/// <summary>The "use as" choice of a slot.</summary>
internal enum UseMode { Auto, Use, OnSelf, OnSelected, Equip }
internal static class UseModes
{
public static readonly string[] Labels =
{
"Automatic (by item)", "Use it", "Use it on me", "Use it on the selected target", "Wield / wear it",
};
/// <summary>The action for a slot's mode and the item's kind.</summary>
public static UseAction ActionFor(UseMode mode, ItemKind kind) => mode switch
{
UseMode.Use => UseAction.Use,
UseMode.OnSelf => UseAction.UseOnSelf,
UseMode.OnSelected => UseAction.UseOnSelected,
UseMode.Equip => UseAction.Equip,
_ => ItemKinds.DefaultAction(kind),
};
public static string Describe(UseAction a) => a switch
{
UseAction.Use => "used",
UseAction.UseOnSelf => "used on you",
UseAction.UseOnSelected => "used on the selected target",
_ => "wielded",
};
}
/// <summary>The kind of weapon the picker is narrowed to.</summary>
internal enum KindFilter { All, Melee, Missile, War, Void }
/// <summary>RynthDefective's settings for one character.</summary>
internal sealed class DefSettings
{
public const int SlotsMin = 1, SlotsMax = 24, PerRowMin = 1, PerRowMax = 12, ButtonMin = 20, ButtonMax = 64,
PickerIconMin = 20, PickerIconMax = 48;
/// <summary>
/// The shortcut bar (2026-10-22, plugin API v90): its first 18 slots are AC's own (the retail
/// toolbar's, its keys AC's keymap), the rest this plugin's own slots (Slots, keys the engine's
/// hotkeys). The player picks how many it shows.
/// </summary>
public const int RetailSlots = 18, BarSlotsMin = 1, BarSlotsMax = RetailSlots + SlotsMax;
public int BarSlots = RetailSlots;
public int SlotCount = 8;
public int SlotsPerRow = 8;
/// <summary>Icon size of the slot buttons, in logical units.</summary>
public int ButtonSize = 36;
/// <summary>Icon size in the weapon picker's rows.</summary>
public int PickerIconSize = 32;
public bool ShowIcons = true;
/// <summary>Counts and uses left under the slot buttons.</summary>
public bool ShowCounts = true;
/// <summary>The weapon kind the picker shows; All = every kind.</summary>
public KindFilter PreferredKind = KindFilter.All;
/// <summary>Weapon swaps are refused while RynthAi's macro runs (it picks the weapon itself); this lets them through.</summary>
public bool SwapWhileBotRuns;
public bool BarOpen;
public bool PickerOpen;
public void Clamp()
{
SlotCount = Math.Clamp(SlotCount, SlotsMin, SlotsMax);
BarSlots = Math.Clamp(BarSlots, BarSlotsMin, BarSlotsMax);
SlotsPerRow = Math.Clamp(SlotsPerRow, PerRowMin, PerRowMax);
ButtonSize = Math.Clamp(ButtonSize, ButtonMin, ButtonMax);
PickerIconSize = Math.Clamp(PickerIconSize, PickerIconMin, PickerIconMax);
if (!Enum.IsDefined(PreferredKind)) PreferredKind = KindFilter.All;
}
}
/// <summary>One character's slots, favourites, recent weapons and settings.</summary>
internal sealed class DefData
{
public const int MaxFavourites = 64, MaxRecent = 8;
public DefSettings Settings = new();
/// <summary>Always <see cref="DefSettings.SlotsMax"/> entries: shrinking the bar hides slots, it doesn't forget them.</summary>
public List<DefSlot> Slots = NewSlots();
public List<ItemRef> Favourites = new();
/// <summary>The weapons wielded from the picker or a slot, newest first.</summary>
public List<ItemRef> Recent = new();
public static List<DefSlot> NewSlots()
{
var l = new List<DefSlot>(DefSettings.SlotsMax);
for (int i = 0; i < DefSettings.SlotsMax; i++) l.Add(new DefSlot());
return l;
}
/// <summary>Pads or cuts the slot list to the fixed length.</summary>
public void FixLength()
{
while (Slots.Count < DefSettings.SlotsMax) Slots.Add(new DefSlot());
if (Slots.Count > DefSettings.SlotsMax) Slots.RemoveRange(DefSettings.SlotsMax, Slots.Count - DefSettings.SlotsMax);
}
public bool IsFavourite(ItemRef r) => Favourites.Exists(f => f.SameAs(r));
/// <summary>Adds or removes a favourite; returns whether it is one now.</summary>
public bool ToggleFavourite(ItemRef r)
{
int i = Favourites.FindIndex(f => f.SameAs(r));
if (i >= 0) { Favourites.RemoveAt(i); return false; }
if (Favourites.Count >= MaxFavourites) return false;
Favourites.Add(r.Clone());
return true;
}
/// <summary>Puts a weapon first in the recent list (once), at most <see cref="MaxRecent"/>.</summary>
public void NoteRecent(ItemRef r)
{
Recent.RemoveAll(x => x.SameAs(r));
Recent.Insert(0, r.Clone());
if (Recent.Count > MaxRecent) Recent.RemoveRange(MaxRecent, Recent.Count - MaxRecent);
}
/// <summary>The slot (1-based number) that holds an item of this identity, or 0.</summary>
public int SlotOf(ItemRef r)
{
for (int i = 0; i < Slots.Count; i++)
if (Slots[i].Item is { } x && x.SameAs(r)) return i + 1;
return 0;
}
}

View file

@ -0,0 +1,246 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>
/// Per-character files: &lt;SuiteDir&gt;\RynthDefective\characters\&lt;server_character&gt;.json, written by
/// hand and read with JsonDocument (plugin types never go through System.Text.Json's serializer,
/// which roots them across hot reloads). A broken or odd file reads as defaults for whatever is
/// wrong in it; the next save rewrites it.
/// </summary>
internal sealed class DefStore
{
/// <summary>RynthDefective's folder (tests point it at a temp folder).</summary>
public string Root;
public DefStore()
{
Root = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthDefective");
}
public DefStore(string root) => Root = root;
/// <summary>"server_character" made safe as a file name (the same rule RynthSort and RynthLua use).</summary>
public static string FileStem(string server, string character) => SafeFileName($"{server}_{character}");
public string PathFor(string server, string character) => Path.Combine(Root, "characters", FileStem(server, character) + ".json");
/// <summary>The character's data; defaults for a new character or a broken file (<paramref name="problem"/> says which).</summary>
public DefData Load(string server, string character, out string? problem)
{
problem = null;
string path = PathFor(server, character);
if (!File.Exists(path)) return new DefData();
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path),
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
return Parse(doc.RootElement);
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or InvalidOperationException)
{
problem = $"{Path.GetFileName(path)}: {ex.Message}";
return new DefData();
}
}
internal static DefData Parse(JsonElement root)
{
if (root.ValueKind != JsonValueKind.Object) throw new JsonException("the file isn't a JSON object");
var d = new DefData();
if (root.TryGetProperty("settings", out JsonElement s) && s.ValueKind == JsonValueKind.Object)
{
DefSettings st = d.Settings;
st.SlotCount = Int(s, "slotCount", st.SlotCount);
st.BarSlots = Int(s, "barSlots", st.BarSlots);
st.SlotsPerRow = Int(s, "slotsPerRow", st.SlotsPerRow);
st.ButtonSize = Int(s, "buttonSize", st.ButtonSize);
st.PickerIconSize = Int(s, "pickerIconSize", st.PickerIconSize);
st.ShowIcons = Bool(s, "showIcons", st.ShowIcons);
st.ShowCounts = Bool(s, "showCounts", st.ShowCounts);
st.PreferredKind = (KindFilter)Int(s, "preferredKind", (int)st.PreferredKind);
st.SwapWhileBotRuns = Bool(s, "swapWhileBotRuns", st.SwapWhileBotRuns);
st.BarOpen = Bool(s, "barOpen", st.BarOpen);
st.PickerOpen = Bool(s, "pickerOpen", st.PickerOpen);
st.Clamp();
}
if (root.TryGetProperty("slots", out JsonElement slots) && slots.ValueKind == JsonValueKind.Array)
{
int i = 0;
foreach (JsonElement e in slots.EnumerateArray())
{
if (i >= DefSettings.SlotsMax) break;
DefSlot slot = d.Slots[i++];
if (e.ValueKind != JsonValueKind.Object) continue;
slot.Item = ParseRef(e, "item");
int mode = Int(e, "mode", 0);
slot.Mode = mode >= 0 && mode <= (int)UseMode.Equip ? (UseMode)mode : UseMode.Auto;
}
}
ParseRefs(root, "favourites", d.Favourites, DefData.MaxFavourites);
ParseRefs(root, "recent", d.Recent, DefData.MaxRecent);
return d;
}
private static void ParseRefs(JsonElement root, string name, List<ItemRef> into, int max)
{
if (!root.TryGetProperty(name, out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) return;
foreach (JsonElement e in arr.EnumerateArray())
{
if (into.Count >= max) break;
ItemRef? r = ParseRefObject(e);
if (r != null) into.Add(r);
}
}
private static ItemRef? ParseRef(JsonElement owner, string name) =>
owner.TryGetProperty(name, out JsonElement e) ? ParseRefObject(e) : null;
private static ItemRef? ParseRefObject(JsonElement e)
{
if (e.ValueKind != JsonValueKind.Object) return null;
string name = Str(e, "name");
if (name.Length == 0) return null; // an item with no name can't be found again
return new ItemRef
{
Id = UInt(e, "id"),
Name = name,
Wcid = UInt(e, "wcid"),
Material = Int(e, "material", 0),
Icon = UInt(e, "icon"),
Underlay = UInt(e, "underlay"),
Overlay = UInt(e, "overlay"),
};
}
/// <summary>Writes the character's file (temp file, then moved over the old one). Returns an error or null.</summary>
public string? Save(string server, string character, DefData d)
{
string path = PathFor(server, character);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
File.WriteAllText(tmp, ToJson(d), new UTF8Encoding(false));
File.Move(tmp, path, overwrite: true);
return null;
}
catch (Exception ex)
{
return ex.Message;
}
}
internal static string ToJson(DefData d)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
w.WriteStartObject("settings");
DefSettings s = d.Settings;
w.WriteNumber("slotCount", s.SlotCount);
w.WriteNumber("barSlots", s.BarSlots);
w.WriteNumber("slotsPerRow", s.SlotsPerRow);
w.WriteNumber("buttonSize", s.ButtonSize);
w.WriteNumber("pickerIconSize", s.PickerIconSize);
w.WriteBoolean("showIcons", s.ShowIcons);
w.WriteBoolean("showCounts", s.ShowCounts);
w.WriteNumber("preferredKind", (int)s.PreferredKind);
w.WriteBoolean("swapWhileBotRuns", s.SwapWhileBotRuns);
w.WriteBoolean("barOpen", s.BarOpen);
w.WriteBoolean("pickerOpen", s.PickerOpen);
w.WriteEndObject();
w.WriteStartArray("slots");
foreach (DefSlot slot in d.Slots)
{
w.WriteStartObject();
if (slot.Item != null) WriteRef(w, "item", slot.Item);
w.WriteNumber("mode", (int)slot.Mode);
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteStartArray("favourites");
foreach (ItemRef r in d.Favourites) WriteRefValue(w, r);
w.WriteEndArray();
w.WriteStartArray("recent");
foreach (ItemRef r in d.Recent) WriteRefValue(w, r);
w.WriteEndArray();
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray()) + "\n";
}
private static void WriteRef(Utf8JsonWriter w, string name, ItemRef r)
{
w.WritePropertyName(name);
WriteRefValue(w, r);
}
private static void WriteRefValue(Utf8JsonWriter w, ItemRef r)
{
w.WriteStartObject();
w.WriteNumber("id", r.Id);
w.WriteString("name", r.Name);
if (r.Wcid != 0) w.WriteNumber("wcid", r.Wcid);
if (r.Material != 0) w.WriteNumber("material", r.Material);
if (r.Icon != 0) w.WriteNumber("icon", r.Icon);
if (r.Underlay != 0) w.WriteNumber("underlay", r.Underlay);
if (r.Overlay != 0) w.WriteNumber("overlay", r.Overlay);
w.WriteEndObject();
}
private static bool Bool(JsonElement o, string name, bool fallback) =>
o.TryGetProperty(name, out JsonElement v) && (v.ValueKind == JsonValueKind.True || v.ValueKind == JsonValueKind.False)
? v.GetBoolean()
: fallback;
private static string Str(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? (v.GetString() ?? string.Empty).Trim() : string.Empty;
private static uint UInt(JsonElement o, string name)
{
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return 0;
if (v.TryGetUInt32(out uint u)) return u;
return v.TryGetDouble(out double dbl) && dbl >= 0 && dbl <= uint.MaxValue && dbl == Math.Floor(dbl) ? (uint)dbl : 0;
}
private static int Int(JsonElement o, string name, int fallback)
{
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return fallback;
if (v.TryGetInt32(out int i)) return i;
return v.TryGetDouble(out double dbl) && dbl >= int.MinValue && dbl <= int.MaxValue ? (int)Math.Round(dbl) : fallback;
}
private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase)
{
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
};
/// <summary>RynthLua's LibraryStorage.SafeFileName, so the suite names a character's file one way.</summary>
public static string SafeFileName(string? name)
{
var invalid = Path.GetInvalidFileNameChars();
var chars = (name ?? string.Empty).Trim().ToCharArray();
for (int i = 0; i < chars.Length; i++)
if (Array.IndexOf(invalid, chars[i]) >= 0 || chars[i] < 32) chars[i] = '_';
string n = new string(chars).TrimEnd('.', ' ');
if (n.Length > 80) n = n[..80].TrimEnd('.', ' ');
if (n.Length == 0 || n.Trim('.').Length == 0) n = "_" + n;
string stem = n.Split('.')[0];
if (ReservedNames.Contains(stem)) n = "_" + n;
return n;
}
}

View file

@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>
/// Which keys the engine's hotkey system has bound to a chat command, read from its file
/// (%LOCALAPPDATA%\RynthCore\hotkeys.txt, one binding a line: "on|off TAB combo TAB command TAB text",
/// the action "command" for a chat command). Read only: the plugin adds and removes bindings by
/// typing "/rc hotkey add|remove ..." to the engine, never by writing the file. The file is
/// shared by every client on the PC and the engine picks up changes within 2 s, so a binding
/// shows here a moment after it was made.
/// </summary>
internal sealed class HotkeyLookup
{
public const string EnvOverride = "RYNTHCORE_HOTKEYS_FILE";
private readonly Func<string> _path;
private DateTime _stamp = DateTime.MinValue;
private long _nextCheckMs;
private List<(string Combo, string Command, bool On)> _bindings = new();
public HotkeyLookup() : this(DefaultPath) { }
public HotkeyLookup(Func<string> path) => _path = path;
public static string DefaultPath()
{
if (Environment.GetEnvironmentVariable(EnvOverride) is { Length: > 0 } p) return p;
string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(root, "RynthCore", "hotkeys.txt");
}
/// <summary>The combo bound to exactly this chat command ("/rdef use 3"), or null. Looks at the file at most once a second.</summary>
public string? KeyFor(string command, long nowMs)
{
Refresh(nowMs);
string want = Normalize(command);
foreach (var b in _bindings)
if (b.On && b.Command == want) return b.Combo;
foreach (var b in _bindings)
if (b.Command == want) return b.Combo + " (off)";
return null;
}
/// <summary>Forget what was read: the next lookup reads the file again.</summary>
public void Invalidate() { _stamp = DateTime.MinValue; _nextCheckMs = 0; }
private void Refresh(long nowMs)
{
if (nowMs < _nextCheckMs) return;
_nextCheckMs = nowMs + 1000;
try
{
string path = _path();
if (!File.Exists(path))
{
_bindings = new();
_stamp = DateTime.MinValue;
return;
}
DateTime stamp = File.GetLastWriteTimeUtc(path);
if (stamp == _stamp) return;
_stamp = stamp;
_bindings = Parse(File.ReadAllText(path));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The engine is writing it right now: the old list stays, the next look tries again.
}
}
internal static List<(string Combo, string Command, bool On)> Parse(string? text)
{
var list = new List<(string, string, bool)>();
if (string.IsNullOrEmpty(text)) return list;
foreach (string raw in text.Split('\n'))
{
string line = raw.TrimEnd('\r');
if (line.Trim().Length == 0 || line.TrimStart().StartsWith('#')) continue;
string[] f = line.Split('\t', 4);
if (f.Length < 4) continue;
if (!f[2].Trim().Equals("command", StringComparison.OrdinalIgnoreCase)) continue;
string combo = f[1].Trim();
if (combo.Length == 0) continue;
list.Add((combo, Normalize(f[3]), !f[0].Trim().Equals("off", StringComparison.OrdinalIgnoreCase)));
}
return list;
}
private static string Normalize(string command) =>
string.Join(' ', (command ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant();
}

View file

@ -0,0 +1,164 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>
/// One item identity, as a slot, a favourite or a recent weapon keeps it: the object id it was
/// last seen with, and what the item IS (name, wcid, material) so another carried item of the same
/// identity can stand in when the object is gone (a used-up kit stack, a replaced weapon). The
/// icon ids are the last ones seen, to draw the item dimmed while none is carried.
/// </summary>
internal sealed class ItemRef
{
public uint Id;
public string Name = string.Empty;
public uint Wcid;
public int Material;
public uint Icon, Underlay, Overlay;
public static ItemRef From(CarriedItem it)
{
var r = new ItemRef();
r.CopyFrom(it);
return r;
}
/// <summary>Takes the item's identity and picture (the slot follows the item it is bound to).</summary>
public void CopyFrom(CarriedItem it)
{
Id = it.Id;
Name = it.Name;
Wcid = it.Wcid;
Material = it.Material;
if (it.Icon != 0) { Icon = it.Icon; Underlay = it.Underlay; Overlay = it.Overlay; }
}
public ItemRef Clone() => (ItemRef)MemberwiseClone();
public string FullName => ItemNames.Full(Name, Material);
/// <summary>
/// Whether <paramref name="it"/> is this item or another of the same kind: the same name (any
/// case), and the same wcid and material wherever both sides know them. The id is not part of
/// it - that is how a stack that was used up is replaced by the next one.
/// </summary>
public bool Matches(CarriedItem it)
{
if (!string.Equals(Name, it.Name, StringComparison.OrdinalIgnoreCase)) return false;
if (Wcid != 0 && it.Wcid != 0 && Wcid != it.Wcid) return false;
if (Material != 0 && it.Material != 0 && Material != it.Material) return false;
return true;
}
/// <summary>Two references to the same thing (the same id, or the same identity).</summary>
public bool SameAs(ItemRef other) =>
(Id != 0 && Id == other.Id) || (string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
&& Wcid == other.Wcid && Material == other.Material);
}
/// <summary>What a slot shows: the item it is bound to now, how many of it there are, and its state.</summary>
internal readonly record struct SlotStatus(CarriedItem? Item, int Count, int Uses, bool Rebound)
{
public bool Missing => Item == null;
}
/// <summary>Finding the carried item for a reference, and the counts a slot shows.</summary>
internal static class ItemMatcher
{
/// <summary>
/// The carried item for <paramref name="r"/>: the very object when it is still carried (and still
/// the same kind of item - an id can be reused), else another item of the same identity:
/// not wielded before wielded, then the smaller stack (a used-up stack is gone sooner and the
/// pack stays tidier), then the lower id. Null when nothing matches.
/// </summary>
public static CarriedItem? Find(ItemRef r, IReadOnlyList<CarriedItem> items, out bool rebound)
{
rebound = false;
if (string.IsNullOrEmpty(r.Name)) return null;
CarriedItem? best = null;
foreach (CarriedItem it in items)
{
if (!r.Matches(it)) continue;
if (it.Id == r.Id) return it;
if (best == null || Better(it, best)) best = it;
}
rebound = best != null;
return best;
}
private static bool Better(CarriedItem a, CarriedItem b)
{
if (a.Wielded != b.Wielded) return !a.Wielded;
if (a.Stack != b.Stack) return a.Stack < b.Stack;
return a.Id < b.Id;
}
/// <summary>The slot's item, how many of it are carried (stack sizes added up) and the uses left on them all.</summary>
public static SlotStatus Status(ItemRef r, IReadOnlyList<CarriedItem> items)
{
CarriedItem? it = Find(r, items, out bool rebound);
if (it == null) return new SlotStatus(null, 0, 0, false);
int count = 0, uses = 0;
foreach (CarriedItem other in items)
{
if (!r.Matches(other)) continue;
count += Math.Max(1, other.Stack);
if (other.MaxUses > 0) uses += Math.Max(0, other.Uses);
}
return new SlotStatus(it, count, uses, rebound);
}
/// <summary>
/// Keeps a slot's reference up to date with what is carried: bound to the object found (a
/// replacement after the old one is gone), with that object's name, picture and so on. A
/// missing item changes nothing. Returns whether the reference changed (the caller saves).
/// </summary>
public static bool Maintain(ItemRef r, IReadOnlyList<CarriedItem> items)
{
CarriedItem? it = Find(r, items, out _);
if (it == null) return false;
uint id = r.Id, icon = r.Icon, under = r.Underlay, over = r.Overlay;
int material = r.Material;
uint wcid = r.Wcid;
r.CopyFrom(it);
return id != r.Id || icon != r.Icon || under != r.Underlay || over != r.Overlay || material != r.Material || wcid != r.Wcid;
}
/// <summary>
/// Finds an item by what the player typed (/rdef use Peerless Healing Kit): the full name, the
/// name, then names that start with the text, then ones that contain it (every word); the
/// first by the same order as <see cref="Find"/>.
/// </summary>
public static CarriedItem? FindByName(string text, IReadOnlyList<CarriedItem> items)
{
string q = (text ?? string.Empty).Trim();
if (q.Length == 0) return null;
string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries);
CarriedItem? best = null;
int bestRank = int.MaxValue;
foreach (CarriedItem it in items)
{
int rank = NameRank(it, q, words);
if (rank == int.MaxValue) continue;
if (best == null || rank < bestRank || (rank == bestRank && Better(it, best)))
{
best = it;
bestRank = rank;
}
}
return best;
}
private static int NameRank(CarriedItem it, string q, string[] words)
{
string full = it.FullName;
if (string.Equals(full, q, StringComparison.OrdinalIgnoreCase)) return 0;
if (string.Equals(it.Name, q, StringComparison.OrdinalIgnoreCase)) return 1;
if (full.StartsWith(q, StringComparison.OrdinalIgnoreCase) || it.Name.StartsWith(q, StringComparison.OrdinalIgnoreCase)) return 2;
foreach (string w in words)
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return int.MaxValue;
return 3;
}
}

View file

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>One line of the "pick from your pack" list: an item kind and how many of it are carried.</summary>
internal sealed record PackChoice(CarriedItem Item, int Count);
internal static class PackList
{
/// <summary>
/// The carried items for a slot to choose from: one line per kind of item (the same name, wcid
/// and material), with the stack sizes added up, A-Z, narrowed by the search words (all of them
/// must be in the name). At most <paramref name="max"/> lines; <paramref name="total"/> says how many matched.
/// </summary>
public static List<PackChoice> Build(IReadOnlyList<CarriedItem> items, string search, int max, out int total)
{
string[] words = (search ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
var byKind = new Dictionary<string, (CarriedItem Rep, int Count)>(StringComparer.OrdinalIgnoreCase);
foreach (CarriedItem it in items)
{
string full = it.FullName;
bool all = true;
foreach (string w in words)
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) { all = false; break; }
if (!all) continue;
string key = $"{full}|{it.Wcid}";
if (byKind.TryGetValue(key, out var have))
{
// The representative: not in hand, then the smaller stack (what a slot would pick).
CarriedItem rep = have.Rep;
if ((rep.Wielded && !it.Wielded) || (rep.Wielded == it.Wielded && it.Stack < rep.Stack)) rep = it;
byKind[key] = (rep, have.Count + Math.Max(1, it.Stack));
}
else byKind[key] = (it, Math.Max(1, it.Stack));
}
var list = new List<PackChoice>(byKind.Count);
foreach (var kv in byKind) list.Add(new PackChoice(kv.Value.Rep, kv.Value.Count));
list.Sort((a, b) => string.Compare(a.Item.FullName, b.Item.FullName, StringComparison.OrdinalIgnoreCase));
total = list.Count;
if (list.Count > max) list.RemoveRange(max, list.Count - max);
return list;
}
}

View file

@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>One row of the weapon picker.</summary>
internal sealed record PickerRow(CarriedItem Item, WeaponGroup Group, string Element, bool InHand, bool Favourite);
/// <summary>A picker group: a kind of weapon and the rows under it.</summary>
internal sealed record PickerGroup(WeaponGroup Group, List<PickerRow> Rows);
/// <summary>What the picker shows: favourites and recent weapons first, then every kind.</summary>
internal sealed class PickerModel
{
public List<PickerRow> Favourites = new();
public List<PickerRow> Recent = new();
public List<PickerGroup> Groups = new();
/// <summary>Weapons carried (before the search and kind filter).</summary>
public int Total;
/// <summary>Rows that passed the search and the kind filter.</summary>
public int Shown;
}
/// <summary>
/// The weapon picker's list, pure: the carried weapons and wands grouped by kind (melee, missile,
/// war magic, void magic, then shields and ammunition), narrowed by the search words and the kind
/// filter. Favourites and the recently wielded come first, as shortcuts: they are also listed under
/// their kind, so a weapon is always where its kind says. Inside a group, A-Z by full name.
/// </summary>
internal static class WeaponPicker
{
public static PickerModel Build(IReadOnlyList<CarriedItem> items, IReadOnlyList<ItemRef> favourites,
IReadOnlyList<ItemRef> recent, string search, KindFilter filter)
{
var model = new PickerModel();
string[] words = (search ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
var rows = new List<PickerRow>();
foreach (CarriedItem it in items)
{
ItemKind kind = ItemKinds.Classify(it);
if (ItemKinds.GroupOf(kind) is not { } group) continue;
model.Total++;
if (!PassesFilter(group, filter)) continue;
if (!MatchesSearch(it, group, words)) continue;
rows.Add(new PickerRow(it, group, ItemKinds.Element(it), it.Wielded, IsFavourite(it, favourites)));
}
model.Shown = rows.Count;
rows.Sort(CompareRows);
foreach (WeaponGroup g in Enum.GetValues<WeaponGroup>())
{
var inGroup = rows.Where(r => r.Group == g).ToList();
if (inGroup.Count > 0) model.Groups.Add(new PickerGroup(g, inGroup));
}
// Shortcuts keep their own order: favourites as the player listed them, recent newest first.
foreach (ItemRef f in favourites)
AddFirstMatch(model.Favourites, rows, f);
foreach (ItemRef r in recent)
AddFirstMatch(model.Recent, rows, r);
return model;
}
private static void AddFirstMatch(List<PickerRow> into, List<PickerRow> rows, ItemRef r)
{
PickerRow? best = null;
foreach (PickerRow row in rows)
{
if (!r.Matches(row.Item)) continue;
if (row.Item.Id == r.Id) { best = row; break; }
best ??= row;
}
if (best != null && !into.Contains(best)) into.Add(best);
}
public static bool IsFavourite(CarriedItem it, IReadOnlyList<ItemRef> favourites)
{
foreach (ItemRef f in favourites)
if (f.Id == it.Id || f.Matches(it)) return true;
return false;
}
private static bool PassesFilter(WeaponGroup g, KindFilter f) => f switch
{
KindFilter.Melee => g == WeaponGroup.Melee,
KindFilter.Missile => g == WeaponGroup.Missile || g == WeaponGroup.Ammo,
KindFilter.War => g == WeaponGroup.WarMagic,
KindFilter.Void => g == WeaponGroup.VoidMagic,
_ => true,
};
/// <summary>Every search word is in the weapon's full name, its element or its kind's label.</summary>
private static bool MatchesSearch(CarriedItem it, WeaponGroup group, string[] words)
{
if (words.Length == 0) return true;
string full = it.FullName;
string element = ItemKinds.Element(it);
string label = ItemKinds.Label(group);
foreach (string w in words)
{
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
if (element.Length > 0 && element.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
if (label.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
return false;
}
return true;
}
private static int CompareRows(PickerRow a, PickerRow b)
{
int c = string.Compare(a.Item.FullName, b.Item.FullName, StringComparison.OrdinalIgnoreCase);
return c != 0 ? c : a.Item.Id.CompareTo(b.Item.Id);
}
public static string KindLabel(KindFilter f) => f switch
{
KindFilter.Melee => "Melee",
KindFilter.Missile => "Missile",
KindFilter.War => "War",
KindFilter.Void => "Void",
_ => "All",
};
}