RynthSuite as of 2026-11-26 (internal 1db112e): release 2026.11.26.1

This commit is contained in:
Tom Bohar 2026-11-26 22:32:31 -05:00
commit 25552fa794
175 changed files with 23428 additions and 494 deletions

View file

@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.Json;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Views;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
@ -29,6 +31,17 @@ internal sealed unsafe class HostSortWorld : ISortWorld
public SortInventory? ReadInventory() => _reader.Read(_host);
/// <summary>The item selected in the game, looked up in the packs as they are now (for "Add selected").</summary>
public SelectedItem ReadSelected()
{
if (!_host.HasGetSelectedItemId) return SelectedItem.Of(SelectionKind.Unavailable);
uint id = _host.GetSelectedItemId();
if (id == 0) return SelectedItem.Of(SelectionKind.Nothing);
SortInventory? inv = _reader.Read(_host);
if (inv == null) return SelectedItem.Of(SelectionKind.NoInventory, id);
return SelectionLookup.Find(inv, id, _host.TryGetObjectName(id, out string name) ? name : string.Empty);
}
// PutItemInContainer answered "not bound" once: plain moves from then on.
private bool _putUnbound;
@ -129,6 +142,102 @@ internal sealed unsafe class HostSortWorld : ISortWorld
public int ErrorSeqNow() =>
_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
// ── Pack jobs: RynthAi's answers (RynthAi.Hub, read only) ─────────────
/// <summary>How long RynthAi's answers are used before they are asked again (the items the same).</summary>
private const long JobAskMs = 3000;
private JobAnswers? _jobAnswers;
private long _jobAskedMs = long.MinValue / 2;
private string _jobKey = string.Empty;
/// <summary>
/// RynthAi's answers for the jobs <paramref name="wanted"/>: asked again every few seconds, or at
/// once when the items carried, the jobs or the mule change. RynthAi not loaded, too old (no
/// RynthAi.Hub answers), or with no profile: that job is unknown and says why. Pump thread.
/// </summary>
public JobAnswers? AskJobs(SortInventory inv, IReadOnlyList<JobKind> wanted, string mule, long nowMs)
{
var ids = new List<uint>(inv.Main.Items.Count + 64);
foreach (SortItem it in inv.Main.Items) if (SortPlanner.Sortable(it)) ids.Add(it.Id);
foreach (SortPack p in inv.Packs)
foreach (SortItem it in p.Items) if (SortPlanner.Sortable(it)) ids.Add(it.Id);
var key = new System.Text.StringBuilder();
foreach (JobKind k in wanted) key.Append((int)k).Append(',');
key.Append(mule).Append('|').Append(ids.Count);
uint sum = 0;
foreach (uint id in ids) sum = unchecked(sum * 31 + id);
key.Append('|').Append(sum);
string k2 = key.ToString();
if (_jobAnswers != null && k2 == _jobKey && nowMs - _jobAskedMs < JobAskMs) return _jobAnswers;
_jobKey = k2;
_jobAskedMs = nowMs;
_jobAnswers = AskRynthAi(_host, ids.ToArray(), wanted, mule);
return _jobAnswers;
}
/// <summary>Asks RynthAi.Hub for each job (resolved again every call: a RynthAi reload frees nothing but changes the table's version).</summary>
internal static JobAnswers AskRynthAi(RynthCoreHost host, uint[] ids, IReadOnlyList<JobKind> wanted, string mule)
{
var answers = new JobAnswers { Mule = mule };
RynthAiHubApiV1* hub = null;
string? why = null;
if (!host.HasGetPluginInterface) why = "This RynthCore can't reach RynthAi";
else
{
try { hub = (RynthAiHubApiV1*)host.GetPluginInterface(RynthAiHub.PluginName, RynthAiHubApiV1.InterfaceName, RynthAiHubApiV1.InterfaceVersion); }
catch { hub = null; }
if (hub == null || hub->Version == 0) { hub = null; why = "RynthAi isn't loaded"; }
}
foreach (JobKind kind in wanted)
{
if (hub == null) { answers.ByKind[kind] = JobAnswer.Unknown(why!); continue; }
int offset = kind switch
{
JobKind.Salvage => RynthAiHubApiV1.LootActionsOffset,
JobKind.Sell => RynthAiHubApiV1.VendorSellsOffset,
_ => RynthAiHubApiV1.TradeGivesOffset,
};
if (!RynthAiHubApiV1.Has(hub, offset)) { answers.ByKind[kind] = JobAnswer.Unknown("This RynthAi is too old to say which items (update RynthAi)"); continue; }
answers.ByKind[kind] = Ask(hub, kind, ids, mule);
}
return answers;
}
private static JobAnswer Ask(RynthAiHubApiV1* hub, JobKind kind, uint[] ids, string mule)
{
var result = new byte[Math.Max(1, ids.Length)];
byte* text = stackalloc byte[256];
text[0] = 0;
int ok;
fixed (uint* pi = ids)
fixed (byte* pr = result)
{
switch (kind)
{
case JobKind.Salvage:
ok = hub->LootActions == null ? 0 : hub->LootActions(pi, ids.Length, pr, text, 256);
break;
case JobKind.Sell:
ok = hub->VendorSells == null ? 0 : hub->VendorSells(pi, ids.Length, pr, text, 256);
break;
default:
{
byte[] who = System.Text.Encoding.UTF8.GetBytes(mule + "\0");
fixed (byte* pw = who)
ok = hub->TradeGives == null ? 0 : hub->TradeGives(pw, pi, ids.Length, pr, text, 256);
break;
}
}
}
string said = Marshal.PtrToStringUTF8((IntPtr)text) ?? string.Empty;
if (ok != 1) return JobAnswer.Unknown(said.Length > 0 ? said.TrimEnd('.') : "RynthAi gave no answer");
var a = new JobAnswer { Known = true, Text = said };
const byte Salvage = 2; // VTankLootAction.Salvage
for (int i = 0; i < ids.Length; i++)
if (kind == JobKind.Salvage ? result[i] == Salvage : result[i] == 1) a.Marked.Add(ids[i]);
return a;
}
// ── RynthAi ─────────────────────────────────────────────────────────────
/// <summary>

View file

@ -9,8 +9,9 @@ namespace RynthCore.Plugin.RynthSort;
/// <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.
/// RynthSort 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.
/// RynthSort draws its window itself (plugin API v90, RynthSortPlugin.Window.cs): the sections
/// manifest names it and RynthPluginRenderEmbed draws it. On older engines it draws through the
/// script windows (host calls from its own tick) and the manifest is empty.
/// </summary>
public static unsafe class PluginExports
{
@ -27,7 +28,7 @@ public static unsafe class PluginExports
public static IntPtr GetName() => LiteralPointer("RynthSort"u8);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => LiteralPointer("0.3.1"u8);
public static IntPtr GetVersion() => LiteralPointer("0.6.1"u8);
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
{
@ -102,6 +103,60 @@ public static unsafe class PluginExports
catch { }
}
// -- The window (plugin API v90; RynthSortPlugin.Window.cs) --
private static string? _sectionsJson;
private static IntPtr _sectionsPtr;
/// <summary>The sections manifest (polled every ~2 s): the window. Kept until it changes.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetSectionsJson()
{
try
{
RynthSortPlugin? plugin = Runtime.Plugin;
if (plugin == null) return IntPtr.Zero;
string json = plugin.SectionsJson();
if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr;
_sectionsJson = json;
IntPtr fresh = Marshal.StringToCoTaskMemUTF8(json);
IntPtr old = System.Threading.Interlocked.Exchange(ref _sectionsPtr, fresh);
if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old);
return fresh;
}
catch { return IntPtr.Zero; }
}
/// <summary>The window's body ("window:rynthsort"; ":popout" when popped out). 1 drawn, 0 not ready, -2 failed.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight)
{
try
{
if (surface == null) return 0;
ReadOnlySpan<byte> name = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(surface);
bool popped = name.EndsWith(":popout"u8);
if (popped) name = name[..^":popout"u8.Length];
if (!name.SequenceEqual("window:rynthsort"u8)) return 0;
RynthSortPlugin? plugin = Runtime.Plugin;
if (plugin == null) return 0;
int result = plugin.RenderWindow(popped, out float wantH);
if (result != 1) return result;
if (wantWidth != null) *wantWidth = width;
if (wantHeight != null) *wantHeight = wantH > 0 ? wantH : height;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorClose", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnVendorClose(uint vendorId) => Runtime.OnVendorClose(vendorId);
// AC's drag and drop (API v77; delivered on the plugin pump): an item the player drags is left
// alone for a while ("leave items I use alone", Sorting/TouchWatch.cs). Older engines never call them.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDragStart", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnDragStart(uint objectId, uint spellId, uint iconId) => Runtime.OnDragStart(objectId, spellId, iconId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnItemDropped", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnItemDropped(uint objectId, uint spellId, uint targetElementId) => Runtime.OnItemDropped(objectId, spellId, targetElementId);
}

View file

@ -6,8 +6,10 @@
time; misplaced items move to theirs, stacks are joined and items are put in order inside
each pack (slot orders, API v80); Sort now, Clean and Unpack on demand; /rsort. Replaces the RynthSort Lua script (its saved
rules are imported on first run). Pack moves wait for RynthAi through its read-only
"RynthAi.Activity" interface (Shared/RynthAiActivityApi.cs). UI: the engine's script
windows (ImGui), no Avalonia.
"RynthAi.Activity" interface (Shared/RynthAiActivityApi.cs). UI (0.5.0): its own window drawn with
ImGui.NET (plugin API v90), else the engine's script windows; no Avalonia. 0.6.0: pack names in
the feed, drops from RynthCore's Inventory, handy items at the front of the main pack, pack jobs
(Salvage, Sell, Mule: RynthAi.Hub's read-only answers, Shared/RynthAiHubApi.cs) and full-pack warnings.
-->
<PropertyGroup>
@ -24,10 +26,13 @@
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthSort</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthSort</AssemblyName>
<!-- The DLL's version (its ProductVersion reads 0.6.1+<commit>); RynthSortPlugin.Version and GetVersion say the same. -->
<Version>0.6.1</Version>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi) draw the
window; vendor info (v67), plugin interfaces (v68), refusals (v70), trade (v72) and slot
highest API use NOT behind a Has*/version check. Frameless plugin windows (v90,
HasFramelessWindows, HasShortcuts for item pictures) draw its own window, else script
windows (v71, HasUi) draw the old one; vendor info (v67), plugin interfaces (v68), refusals (v70), trade (v72) and slot
orders / moves to a slot (v80: in-pack order, top-to-bottom pack numbers) are each checked first. Below v71 it still sorts (/rsort on|off|now|tidy|clean|unpack). -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Keeps your packs sorted: new loot goes to the pack its rule names.</RynthPluginDescription>
@ -38,11 +43,26 @@
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<!-- An older RynthAi without RynthAi.Activity: its RynthAi.Status bot state instead. -->
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- Pack jobs (0.6.0): RynthAi's read-only answers about items (loot profile actions, AutoVendor, AutoTrade). -->
<Compile Include="..\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.cs" />
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
<ItemGroup>
<!-- The window (2026-11-26): drawn with ImGui.NET bound to the engine's cimgui, in the engine's
look (Shared\RynthUi; plugin API v90 hosts the frameless window and gives item pictures),
as RynthDefective's shortcut bar. -->
<Compile Include="..\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<Compile Include="..\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
<Compile Include="..\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
<TrimmerRootAssembly Include="ImGui.NET" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />

View file

@ -0,0 +1,337 @@
// ============================================================================
// RynthSort - RynthSortPlugin.Window.cs
// The window drawn with ImGui (2026-11-26, the approved design for #rynth-issues
// "The bag sort feature is lacking in UX"): RynthCore hosts a frameless window
// (sections manifest, plugin API v90, "chrome": "none", "scale": "draw") and
// RynthSort draws it (Window/SortWindow.cs) through RynthPluginRenderEmbed, as
// RynthDefective draws its shortcut bar. On an engine without v90's frameless
// windows and item pictures the script-window panel (Views/SortPanel.cs,
// Ui/UiWindow.cs) stays.
//
// The tick builds the window's view-model (Screen/ScreenBuilder.cs) while the
// window shows (it was drawn in the last 2 s), twice a second and at once after
// anything the window or a command changed, and publishes it whole; the render
// thread reads it and queues every click for the tick (WindowActions).
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Globalization;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Views;
using RynthCore.Plugin.RynthSort.Window;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthSort;
public sealed partial class RynthSortPlugin
{
internal const string WindowSurface = "window:rynthsort";
private const long ScreenBuildMs = 500, ScreenShownMs = 2000, OpenWhenHostedMs = 8000, WindowSyncMs = 1000;
/// <summary>
/// The engine hosts frameless plugin windows and hands out item pictures and its look (plugin API
/// v90): the window drawn with ImGui. Else the script-window panel. Decided once, at Initialize.
/// </summary>
private bool _direct;
private SortWindow? _sortWindow; // render thread
private int _drawFailures; // render thread
private volatile ScreenModel _screen = ScreenModel.Empty; // tick writes, render reads
private readonly ConcurrentQueue<Action> _windowActions = new();
private readonly ScreenSession _session = new();
private long _screenDrawnMs = long.MinValue / 2; // render writes (Volatile), tick reads
private long _nextScreenMs;
private bool _screenDirty = true;
private volatile bool _wantLayouts;
private long _openUntilMs, _nextSyncMs;
internal bool UsesDirectWindow(RynthCoreHost host) =>
host.HasFramelessWindows && host.HasShortcuts && host.HasSetPanelOpen && host.HasUiTheme;
internal static readonly string Manifest =
"{\"version\":1,\"windows\":[{\"id\":\"sort\",\"title\":\"" + SortWindow.Title + "\",\"surface\":\"" + WindowSurface +
"\",\"icon\":\"\\u" + ((int)RynthIcons.SortAscending[0]).ToString("X4", CultureInfo.InvariantCulture) +
"\",\"width\":1060,\"height\":660,\"minWidth\":340,\"minHeight\":240,\"bar\":false,\"edgeToEdge\":true," +
"\"chrome\":\"none\",\"scale\":\"draw\"}]}";
/// <summary>The sections manifest: the window, on an engine that can host it. Any thread.</summary>
internal string SectionsJson() => _direct ? Manifest : "{\"version\":1}";
/// <summary>RynthPluginRenderEmbed "window:rynthsort". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
internal int RenderWindow(bool popped, out float wantHeight)
{
wantHeight = 0;
if (!_direct) return 0;
System.Threading.Volatile.Write(ref _screenDrawnMs, Environment.TickCount64);
try
{
_sortWindow ??= new SortWindow(Host, new WindowActions(this));
wantHeight = _sortWindow.Draw(_screen, popped);
_drawFailures = 0;
return 1;
}
catch (Exception ex)
{
Host.Log($"[RynthSort] window draw failed: {ex.GetType().Name}: {ex.Message}");
return ++_drawFailures >= 3 ? -2 : 0;
}
}
/// <summary>Plugin tick: the window's clicks, then its view while it shows.</summary>
private void TickWindow(long now)
{
while (_windowActions.TryDequeue(out Action? act))
{
try { act(); }
catch (Exception ex) { Host.Log($"[RynthSort] window action failed: {ex.GetType().Name}: {ex.Message}"); }
_screenDirty = true;
}
if (!_direct) return;
_session.Expire(now);
OpenWhenHosted(now);
SyncWindowOpen(now);
bool shown = now - System.Threading.Volatile.Read(ref _screenDrawnMs) < ScreenShownMs;
if (!shown || (!_screenDirty && now < _nextScreenMs)) return;
_screenDirty = false;
_nextScreenMs = now + ScreenBuildMs;
try
{
_screen = ScreenBuilder.Build(_sort, new ScreenInputs
{
Character = _identityKnown ? _character : string.Empty,
Server = _identityKnown ? _server : string.Empty,
Warnings = _warnings,
CanAddSelected = Host.HasGetSelectedItemId,
CanSelect = Host.HasSelectItem,
WantLayouts = _wantLayouts,
Session = _session,
});
}
catch (Exception ex)
{
Host.Log($"[RynthSort] window view failed: {ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>The window was open when this character was last seen: open it again once the engine hosts it.</summary>
private void OpenWhenHosted(long now)
{
if (_openUntilMs == 0) return;
int state = Host.SetPanelOpen(SortWindow.Title, RynthPanelOpen.Open);
if (state >= 0 || now > _openUntilMs) _openUntilMs = 0;
}
/// <summary>Keeps the saved "window open" in step with the engine's window (closed with its x, opened from the Inventory).</summary>
private void SyncWindowOpen(long now)
{
if (!_identityKnown || _openUntilMs != 0 || now < _nextSyncMs) return;
_nextSyncMs = now + WindowSyncMs;
int state = Host.SetPanelOpen(SortWindow.Title, RynthPanelOpen.Ask);
if (state < 0) return;
bool open = state == 1;
if (open == _sort.Data.Settings.WindowOpen) return;
_sort.Data.Settings.WindowOpen = open;
RequestSave();
}
/// <summary>/rsort: shows or hides the window. Returns its state afterwards (-1: not hosted yet).</summary>
private int ToggleWindow() => Host.SetPanelOpen(SortWindow.Title, RynthPanelOpen.Toggle);
/// <summary>"+ Add selected" through the window's toast (and /rsort add): the selected item's name into side pack <paramref name="number"/>'s rules.</summary>
private AddOutcome AddSelectedHere(int number)
{
AddOutcome outcome = new() { Status = AddStatus.Refused, Message = "Nothing was added." };
_session.Edit(_sort.Data.Rules, rules =>
{
outcome = AddSelectedRules.Apply(rules, _sort.Planner.View, number, _world?.ReadSelected() ?? SelectedItem.Of(SelectionKind.Unavailable));
return new EditResult(outcome.Status == AddStatus.Added, outcome.Message);
}, Environment.TickCount64);
if (outcome.Status == AddStatus.Added) RequestSave();
_screenDirty = true;
return outcome;
}
private void QueueWindow(Action action)
{
if (_windowActions.Count < 64) _windowActions.Enqueue(action);
}
/// <summary>What the window asks (render thread: queue only; everything runs on the tick).</summary>
private sealed class WindowActions : ISortWindowActions
{
private readonly RynthSortPlugin _p;
public WindowActions(RynthSortPlugin plugin) => _p = plugin;
private SortController C => _p._sort;
private static long Now => Environment.TickCount64;
private void Q(Action a) => _p.QueueWindow(a);
/// <summary>A rule change with its toast and Undo; saved when it changed something.</summary>
private void Edit(Func<System.Collections.Generic.List<SortRule>, EditResult> change) => Q(() =>
{
if (!_p._identityKnown) return;
if (_p._session.Edit(C.Data.Rules, change, Now)) _p.RequestSave();
});
public void SetAuto(bool on) => Q(() => { C.SetAuto(on); _p.RequestSave(); });
public void SortNow() => Q(() => C.StartJob(SortScope.All));
public void Clean() => Q(() => C.StartJob(SortScope.Clean));
public void PutBack() => Q(() =>
{
int n = C.PutBackCount;
if (C.StartPutBack()) _p._session.Show($"Putting back {SortPanel.Count(n, "item")}; auto-sort is off so nothing moves again.", false, Now);
});
public void SendKind(int pack, int cls) => Edit(rules => RuleEdits.SendKind(rules, C.Planner.View, pack, cls));
public void AddOverflow(int pack, int cls) => Edit(rules => RuleEdits.AddOverflow(rules, C.Planner.View, pack, cls));
public void SetJob(int pack, int kind, string mule) => Q(() =>
{
SortInventory? inv = C.LastInventory;
if (!_p._identityKnown || inv == null) return;
var k = (JobKind)kind;
if (!PackJobs.Set(C.Data.Jobs, inv, pack, k, mule))
{
_p._session.Show("Nothing changed.", false, Now);
return;
}
_p.RequestSave();
string where = PackNames.Label(inv, pack);
_p._session.Show(k switch
{
JobKind.Salvage => $"{where} now takes what RynthAi's loot profile marks Salvage. Nothing has moved yet.",
JobKind.Sell => $"{where} now takes what RynthAi's AutoVendor would sell. Nothing has moved yet.",
JobKind.Mule => $"{where} now holds what RynthAi's AutoTrade would give {(mule.Trim().Length > 0 ? mule.Trim() : "a mule")}. Nothing has moved yet.",
_ => $"{where} has no job now: only its rules.",
}, false, Now);
});
public void SendName(int pack, uint itemId) => Edit(rules =>
{
SortItem? item = Find(itemId);
return item == null ? EditResult.Nothing("That item isn't in your packs now.") : RuleEdits.SendName(rules, C.Planner.View, pack, item);
});
public void MoveOnce(uint itemId, int pack) => Q(() =>
{
SortInventory? inv = C.LastInventory;
SortItem? item = Find(itemId);
if (inv == null || item == null) { _p._session.Show("That item isn't in your packs now.", false, Now); return; }
uint dest = pack == 0 ? inv.Main.Id : pack <= inv.Packs.Count ? inv.Packs[pack - 1].Id : 0;
if (!C.StartSend(itemId, dest)) { _p._session.Show("That pack isn't carried now.", false, Now); return; }
string where = pack == 0 ? "the main pack" : inv.Packs[pack - 1].Name.Length > 0 ? inv.Packs[pack - 1].Name : "pack " + pack;
int hold = C.Data.Settings.HoldMin;
_p._session.Show(hold > 0
? $"{Name(item)} goes to {where} now and is left alone for {hold} min."
: $"{Name(item)} goes to {where} now. Leaving items alone is off, so a sort may move it back.", false, Now);
});
public void Hold(uint itemId) => Q(() =>
{
C.Touch.Hold(itemId, C.Clock, TouchKind.Chosen);
SortItem? item = Find(itemId);
_p._session.Show($"{(item != null ? Name(item) : "It")} is left alone for {C.Data.Settings.HoldMin} min.", false, Now);
});
public void Release(uint itemId) => Q(() =>
{
C.Touch.Release(itemId);
SortItem? item = Find(itemId);
_p._session.Show($"RynthSort may move {(item != null ? Name(item) : "it")} again.", false, Now);
});
public void Unhold(uint itemId) => Q(() => C.Touch.Release(itemId));
public void RemoveChip(int ruleUid, bool isName, int cls, string name) =>
Edit(rules => RuleEdits.RemoveEntry(rules, C.Planner.View, ruleUid, isName, cls, name));
public void TurnOn(int ruleUid) => Edit(rules => RuleEdits.TurnOn(rules, ruleUid));
public void AddSelected(int pack) => Q(() => _p.AddSelectedHere(pack));
public void UseLayout(string key) => Edit(rules =>
{
StarterLayout? l = StarterLayouts.Find(key);
return l == null ? EditResult.Nothing("That layout is gone.") : RuleEdits.UseLayout(rules, C.LastInventory, l);
});
public void Undo() => Q(() => { if (_p._session.Undo(C.Data.Rules, Now)) _p.RequestSave(); });
public void DismissToast() => Q(() => _p._session.Show(string.Empty, false, Now));
public void SetSettle(int seconds) => Setting(s => s.SettleSec = seconds);
public void SetHold(int minutes) => Setting(s => s.HoldMin = minutes);
public void SetGap(int ms) => Setting(s => s.GapMs = ms);
public void SetCombat(bool on) => Setting(s => s.SortInCombat = on);
public void SetOrder(bool on) => Setting(s => s.OrderInPacks = on);
public void SetKindFirst(bool on) => Setting(s => s.OrderKindFirst = on);
public void SetHandy(bool on) => Setting(s => s.HandyFront = on);
public void HandyKind(int cls, bool add) => Setting(s => { if (add) HandyItems.AddClass(s, cls); else s.HandyClasses.Remove(cls); });
public void HandyName(string name, bool add) => Setting(s => { if (add) HandyItems.AddName(s, name); else HandyItems.RemoveName(s, name); });
private void Setting(Action<SortSettings> set) => Q(() =>
{
if (!_p._identityKnown) return;
set(C.Data.Settings);
C.Data.Settings.Clamp();
_p.RequestSave();
});
public void EmptySidePacks() => Q(() =>
{
C.StartUnpack(null);
_p._session.Show("Emptying the side packs; auto-sort is off so nothing moves back.", false, Now);
});
public void SelectInGame(uint objectId) => Q(() =>
{
if (_p.Host.HasSelectItem) _p.Host.SelectItem(objectId);
});
public void WantLayouts(bool open) => Q(() => _p._wantLayouts = open);
public void SendNameText(int pack, string text) => Edit(rules => RuleEdits.SendNameText(rules, C.Planner.View, pack, text));
public void SetCollapsed(uint packId, bool collapsed) => Fold(s => s.SetCollapsed(packId, collapsed));
public void SetMainCollapsed(bool collapsed) => Fold(s =>
{
if (s.MainCollapsed == collapsed) return false;
s.MainCollapsed = collapsed;
return true;
});
public void SetAllCollapsed(bool collapsed) => Fold(s =>
{
SortInventory? inv = C.LastInventory;
if (inv == null) return false;
bool changed = false;
foreach (SortPack pk in inv.Packs) changed |= s.SetCollapsed(pk.Id, collapsed);
return changed;
});
/// <summary>A card folded or opened: saved, and the window's model made again at once (no toast, no Undo).</summary>
private void Fold(Func<SortSettings, bool> change) => Q(() =>
{
if (!_p._identityKnown || !change(C.Data.Settings)) return;
_p.RequestSave();
_p._screenDirty = true;
});
private SortItem? Find(uint id)
{
SortInventory? inv = C.LastInventory;
if (inv == null || id == 0) return null;
foreach (SortItem it in inv.Main.Items) if (it.Id == id) return it;
foreach (SortPack p in inv.Packs)
foreach (SortItem it in p.Items) if (it.Id == id) return it;
return null;
}
private static string Name(SortItem it) => it.Name.Length > 0 ? it.Name : "the item";
}
}

View file

@ -19,7 +19,15 @@ namespace RynthCore.Plugin.RynthSort;
/// each pack. Clean also sends items no rule wants back to the main pack; Unpack empties the side
/// packs. A rule lists classes and parts of names and the pack they go to; a name match beats a
/// class match. Rules and settings are kept per character; the RynthSort Lua script's saved rules
/// are taken over on a character's first run.
/// are taken over on a character's first run. A character it hasn't seen starts with auto-sort off
/// and no rules; the window offers starter layouts fitted to its packs (Sorting/StarterLayouts.cs),
/// previews what a sort would move, and Put back undoes the last sort. Items the player is using
/// (moved, selected, dragged, taken off, picked up) are left alone for a few minutes
/// (Sorting/TouchWatch.cs; the selection is polled each tick, drags come from the v77 UI hooks).
///
/// The window (0.5.0, 2026-11-26): drawn by RynthSort with ImGui in RynthCore's frameless plugin
/// window (RynthSortPlugin.Window.cs, Window/SortWindow.cs) on engines with plugin API v90; the
/// script-window panel (Views/SortPanel.cs) on older ones.
///
/// It stays out of the way (Sorting/SortGate.cs): nothing moves while a corpse or chest is being
/// looted, a vendor or trade window is open, the character is busy or animating, in portal space,
@ -29,9 +37,9 @@ namespace RynthCore.Plugin.RynthSort;
/// 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.
/// </summary>
public sealed class RynthSortPlugin : RynthPluginBase
public sealed partial class RynthSortPlugin : RynthPluginBase
{
public const string Version = "0.3.1";
public const string Version = "0.6.1";
private const long IdentityRetryMs = 1000;
private const long SaveDelayMs = 750;
private const long PassIntervalMs = 500;
@ -95,22 +103,35 @@ public sealed class RynthSortPlugin : RynthPluginBase
_world = new HostSortWorld(Host, _reader, _loot, () => _vendorOpen);
_sort.SettingsChanged = RequestSave;
_sort.PacksFixed = OnPacksFixed;
_sort.Warn = text => _reply.Fail(text); // what didn't fit, once per sort
_direct = UsesDirectWindow(Host);
if (_direct)
{
// The window drawn with ImGui.NET bound to the engine's cimgui, in the engine's look (as RynthDefective's bar).
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthSort] " + msg));
RynthCore.Plugin.Shared.RynthUi.RynthUi.Init(Host);
}
_panel = new SortPanel(_sort, RequestSave)
{
Warnings = () => _warnings,
Character = () => _identityKnown ? _character : string.Empty,
Icons = IconsOn,
OpLevel = OpLevelNow,
CanSelect = () => Host.HasSelectItem,
SelectInGame = id => Host.HasSelectItem && Host.SelectItem(id),
ReadSelected = () => _world?.ReadSelected() ?? SelectedItem.Of(SelectionKind.Unavailable),
};
// No bar button of its own: opened from the engine Inventory window's Sort button, the
// Scripts menu or /rsort.
_window = _ui.Add(new UiWindow("RynthSort/Main", "RynthSort")
{
DefaultWidth = 360f, DefaultHeight = 420f, MinWidth = 300f, MinHeight = 200f,
BarButton = false,
});
Host.Log($"[RynthSort] {Version} initialized. /rsort shows or hides the window; /rsort on|off|now|tidy|clean|unpack. Files: {_store.Root}");
// Scripts menu or /rsort. Only on an engine without frameless plugin windows: the window
// drawn with ImGui takes the "RynthSort" title, which a script window would hold.
if (!_direct)
_window = _ui.Add(new UiWindow("RynthSort/Main", "RynthSort")
{
// Room for the status lines, the four page buttons and a pack's buttons on one line each.
DefaultWidth = 440f, DefaultHeight = 560f, MinWidth = 330f, MinHeight = 260f,
BarButton = false,
});
Host.Log($"[RynthSort] {Version} initialized ({(_direct ? "its own window" : "script window")}). /rsort shows or hides the window; /rsort on|off|now|tidy|clean|unpack|back|add. Files: {_store.Root}");
return 0;
}
@ -124,6 +145,8 @@ public sealed class RynthSortPlugin : RynthPluginBase
_reader.Reset();
_loot.Reset();
_warnings.Clear();
_session.Reset();
_screenDirty = true;
}
public override void OnLogout()
@ -148,6 +171,17 @@ public sealed class RynthSortPlugin : RynthPluginBase
public override void OnVendorOpen(uint vendorId) => _vendorOpen = true;
public override void OnVendorClose(uint vendorId) => _vendorOpen = false;
// The player's own hands on an item (API v77 drag and drop, on the pump): left alone for a while.
public override void OnDragStart(uint objectId, uint spellId, uint iconId)
{
if (objectId != 0 && _identityKnown) _sort.Touch.NoteDrag(objectId, Environment.TickCount64);
}
public override void OnItemDropped(uint objectId, uint spellId, uint targetElementId)
{
if (objectId != 0 && _identityKnown) _sort.Touch.NoteDrop(objectId, Environment.TickCount64);
}
// ── Chat ────────────────────────────────────────────────────────────────
// May run on AC's thread: classify and queue only.
@ -175,7 +209,13 @@ public sealed class RynthSortPlugin : RynthPluginBase
switch (c.Verb)
{
case SortVerb.Window:
if (_window != null)
if (_direct)
{
int state = ToggleWindow();
if (state >= 0) Print(SortCommand.Window(state == 1));
else PrintFail("The RynthSort window isn't ready yet; try again in a moment.");
}
else if (_window != null)
{
_window.Visible = !_window.Visible; _window.NeedsPass = true;
if (Host.HasUi) Print(SortCommand.Window(_window.Visible));
@ -202,6 +242,30 @@ public sealed class RynthSortPlugin : RynthPluginBase
case SortVerb.Status:
PrintStatus();
break;
case SortVerb.Back:
{
int count = _sort.PutBackCount;
if (_sort.StartPutBack()) Print(SortCommand.PuttingBack(count));
else PrintFail(SortCommand.PuttingBack(0));
break;
}
case SortVerb.Add:
// The selected item's name into a pack's rules: the window's "+ Add selected".
if (c.Pack == null) PrintFail(SortCommand.AddUsage);
else if (_direct)
{
AddOutcome added = AddSelectedHere(c.Pack.Value);
if (added.Status == AddStatus.Refused) PrintFail(added.Message);
else Print(added.Message);
}
else if (_panel == null) PrintFail("The RynthSort window isn't ready yet.");
else
{
AddOutcome added = _panel.AddSelected(c.Pack.Value);
if (added.Status == AddStatus.Refused) PrintFail(added.Message);
else Print(added.Message);
}
break;
case SortVerb.Help:
Print(SortCommand.Usage);
break;
@ -210,13 +274,15 @@ public sealed class RynthSortPlugin : RynthPluginBase
break;
}
if (_window != null) _window.NeedsPass = true;
_screenDirty = true;
}
private void PrintStatus()
{
SortView v = _sort.Planner.View;
string held = v.Held.Count > 0 ? $", {v.Held.Count} left alone (you used them)" : string.Empty;
Print($"{_character}: auto-sort {(_sort.Data.Settings.Auto ? "on" : "off")}, {_sort.Status}; {_sort.Data.Rules.Count} rules, "
+ $"{v.Packs.Count} side packs, main pack {v.MainUsed}/{v.MainCapacity}; moved {_sort.Moved}, failed {_sort.Failed} this session.");
+ $"{v.Packs.Count} side packs, main pack {v.MainUsed}/{v.MainCapacity}{held}; moved {_sort.Moved}, failed {_sort.Failed} this session.");
}
// Chat lines wait in the shared reply queue (the host drops a line within 100 ms of another
@ -241,6 +307,8 @@ public sealed class RynthSortPlugin : RynthPluginBase
if (!_identityKnown && now >= _nextIdentityTryMs) TryStartCharacter(now);
if (_identityKnown && _world != null)
{
// The item selected in the game counts as in use while it is selected (and for the hold after).
if (Host.HasGetSelectedItemId) _sort.Touch.NoteSelected(Host.GetSelectedItemId(), now);
try { _sort.Tick(_world, now); }
catch (Exception ex)
{
@ -254,7 +322,8 @@ public sealed class RynthSortPlugin : RynthPluginBase
_movedSeen = _sort.Moved;
_moving = _inWorld && _identityKnown && (_sort.HasMoveOut || (_lastMoveMs != 0 && now - _lastMoveMs < MovingHoldMs));
if (!Host.HasUi || _window == null || _panel == null) return;
TickWindow(now);
if (_direct || !Host.HasUi || _window == null || _panel == null) return;
Record(_window, now);
_ui.Submit(Host, now);
@ -265,14 +334,17 @@ public sealed class RynthSortPlugin : RynthPluginBase
}
}
// Item icons in script windows need op level 2 (engines from 2026-09-30); asked until it says yes.
private bool _icons;
private bool IconsOn()
// The engine's script-window op level: 2 draws item icons (engines from 2026-09-30), 3 tables
// and fonts (not released yet). Asked until it answers.
private int _opLevel = -1;
private int OpLevelNow()
{
if (!_icons) _icons = Host.HasUi && Host.TryGetUiInfo(out RynthCore.PluginSdk.UiInfoNative info) && info.OpLevel >= 2;
return _icons;
if (_opLevel < 0 && Host.HasUi && Host.TryGetUiInfo(out RynthCore.PluginSdk.UiInfoNative info)) _opLevel = info.OpLevel;
return Math.Max(_opLevel, 0);
}
private bool IconsOn() => OpLevelNow() >= 2;
private void TryStartCharacter(long now)
{
_nextIdentityTryMs = now + IdentityRetryMs;
@ -283,10 +355,10 @@ public sealed class RynthSortPlugin : RynthPluginBase
_server = server;
_character = name;
CharacterSortData data = _store.Load(server, name, out string? problem);
if (problem != null) Host.Log($"[RynthSort] couldn't read the saved rules ({problem}); using defaults.");
if (problem != null) Host.Log($"[RynthSort] couldn't read the saved rules ({problem}); starting with none (the file is kept as .bak at the next save).");
_sort.Data = data;
_identityKnown = true;
_backupOnSave = false;
_backupOnSave = problem != null; // a broken file is kept beside the new one (.bak)
string own = _store.PathFor(server, name);
if (data.ImportedFrom.Length > 0 && !File.Exists(own))
@ -299,6 +371,12 @@ public sealed class RynthSortPlugin : RynthPluginBase
}
CheckLuaScriptAutostart(server, name);
if (_window != null) { _window.Visible = data.Settings.WindowOpen; _window.NeedsPass = true; }
if (_direct)
{
_session.Reset();
_screenDirty = true;
_openUntilMs = data.Settings.WindowOpen ? now + OpenWhenHostedMs : 0;
}
Host.Log($"[RynthSort] sorting for {name} on {server}: {data.Rules.Count} rules, auto-sort {(data.Settings.Auto ? "on" : "off")}; file {own}");
}
@ -363,6 +441,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
private void RequestSave()
{
if (_window != null) _window.NeedsPass = true;
_screenDirty = true;
if (_saveDueMs == 0) _saveDueMs = Environment.TickCount64 + SaveDelayMs;
}

View file

@ -0,0 +1,56 @@
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Screen;
/// <summary>
/// Which tiles just arrived in another pack, for the window's pop-in: each new view-model is
/// compared with the last one (an item whose pack changed arrived now). The first view of a
/// character arrives nothing. Render thread only (the renderer owns one); pure, so the tests drive it.
/// </summary>
internal sealed class Arrivals
{
/// <summary>How long the pop-in lasts (seconds).</summary>
public const double PopSeconds = 0.6;
private readonly Dictionary<uint, int> _where = new();
private readonly Dictionary<uint, double> _arrived = new();
private int _version = -1;
private string _who = string.Empty;
/// <summary>Compares <paramref name="m"/> with the last view (once per build); <paramref name="now"/> in seconds.</summary>
public void Update(ScreenModel m, double now)
{
if (m.Version == _version) return;
_version = m.Version;
if (!m.Ready) return;
bool fresh = _who != m.Who || _where.Count == 0;
_who = m.Who;
foreach (KeyValuePair<uint, TileModel> kv in m.TilesById)
if (!fresh && _where.TryGetValue(kv.Key, out int was) && was != kv.Value.Where) _arrived[kv.Key] = now;
_where.Clear();
foreach (KeyValuePair<uint, TileModel> kv in m.TilesById) _where[kv.Key] = kv.Value.Where;
if (_arrived.Count > 64)
{
var old = new List<uint>();
foreach (KeyValuePair<uint, double> kv in _arrived) if (now - kv.Value > PopSeconds) old.Add(kv.Key);
foreach (uint id in old) _arrived.Remove(id);
}
}
/// <summary>How far the pop-in of <paramref name="itemId"/> is (0 just arrived, 1 done or none).</summary>
public float Progress(uint itemId, double now)
{
if (!_arrived.TryGetValue(itemId, out double at)) return 1f;
double t = (now - at) / PopSeconds;
if (t >= 1) { _arrived.Remove(itemId); return 1f; }
return t <= 0 ? 0f : (float)t;
}
public void Clear()
{
_where.Clear();
_arrived.Clear();
_version = -1;
_who = string.Empty;
}
}

View file

@ -0,0 +1,33 @@
namespace RynthCore.Plugin.RynthSort.Screen;
/// <summary>
/// One drop, one set of choices. An item dragged out of RynthCore's Inventory window and let go
/// over a pack card reaches the window twice: as the ImGui payload the Inventory publishes
/// ("RYNTH_INV_ITEM") and through the engine's drop target (the Inventory offers a drop outside
/// itself to every panel that takes items). A drag out of AC's own windows comes one way or the
/// other, depending on the engine. The second arrival of the same item within
/// <see cref="WindowSec"/> is the same drop. Pure; the window keeps one.
/// </summary>
internal sealed class DropOnce
{
public const double WindowSec = 1.0;
private uint _item;
private double _at = double.MinValue;
/// <summary>True when <paramref name="itemId"/> dropped at <paramref name="now"/> (seconds) is a new drop, not the echo of the last one.</summary>
public bool Take(uint itemId, double now)
{
if (itemId == 0) return false;
if (itemId == _item && now - _at < WindowSec && now >= _at) return false;
_item = itemId;
_at = now;
return true;
}
public void Reset()
{
_item = 0;
_at = double.MinValue;
}
}

View file

@ -0,0 +1,93 @@
using System.Collections.Generic;
using System.Globalization;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthCore.Plugin.RynthSort.Screen;
/// <summary>
/// How the window names and colours a kind of item (an ObjectClass): the approved design's
/// sentence-case labels ("Spell components", "Mana stones") and its kind colours (ARGB), used for
/// rule chips, the layout bars, the plan rows' fallback squares and a tile whose picture isn't made
/// yet. Pure.
/// </summary>
internal static class Kinds
{
// The design's palette (rynthsort-packs.html KINDS), ARGB.
public const uint Components = 0xFF2F7FA6, Salvage = 0xFF9A7330, Gems = 0xFF7550B5, Keys = 0xFFA87B30,
Stones = 0xFF2E95AD, Kits = 0xFF3F8F50, Picks = 0xFF68737F, Food = 0xFFA44A60, Notes = 0xFF8F8A33,
Coins = 0xFFB18F30, Gear = 0xFF56606C, Weapons = 0xFF5D5568, Scrolls = 0xFF85563F, Crafting = 0xFF6A7F3A;
/// <summary>The kind's colour (ARGB).</summary>
public static uint Color(int cls) => cls switch
{
ObjectClasses.SpellComponent => Components,
ObjectClasses.Salvage => Salvage,
ObjectClasses.Gem => Gems,
ObjectClasses.Key => Keys,
ObjectClasses.ManaStone => Stones,
ObjectClasses.HealingKit => Kits,
ObjectClasses.Lockpick => Picks,
ObjectClasses.Food => Food,
ObjectClasses.TradeNote => Notes,
ObjectClasses.Money => Coins,
ObjectClasses.Armor or ObjectClasses.Clothing or ObjectClasses.Jewelry => Gear,
ObjectClasses.MeleeWeapon or ObjectClasses.MissileWeapon or ObjectClasses.WandStaffOrb or ObjectClasses.Bundle => Weapons,
ObjectClasses.Scroll or ObjectClasses.Book or ObjectClasses.Journal => Scrolls,
ObjectClasses.Plant or ObjectClasses.BaseAlchemy or ObjectClasses.BaseCooking or ObjectClasses.BaseFletching
or ObjectClasses.CraftedAlchemy or ObjectClasses.CraftedCooking or ObjectClasses.CraftedFletching or ObjectClasses.Ust => Crafting,
_ => Gear,
};
private static readonly Dictionary<int, string> LabelCache = new();
/// <summary>"Spell components", "Mana stones", "Melee weapons": what a chip or a layout row says.</summary>
public static string Label(int cls)
{
lock (LabelCache)
{
if (LabelCache.TryGetValue(cls, out string? s)) return s;
s = cls == ObjectClasses.SpellComponent ? "Spell components" : Sentence(ObjectClasses.Plural(cls));
LabelCache[cls] = s;
return s;
}
}
/// <summary>"Mana Stones" to "Mana stones": the first letter as it is, the rest of each word's first letters small.</summary>
internal static string Sentence(string text)
{
if (text.Length < 2) return text;
char[] a = text.ToCharArray();
for (int i = 1; i < a.Length; i++)
if (a[i - 1] == ' ') a[i] = char.ToLowerInvariant(a[i]);
return new string(a);
}
/// <summary>A name rule's chip: <c>named "Opal"</c>.</summary>
public static string NameChip(string name) => "named \"" + name + "\"";
private static readonly Dictionary<int, string> QtyCache = new();
/// <summary>A stack's count as the tile's corner shows it: "" for one, "75", "2.4k" from 1000.</summary>
public static string Qty(int stack)
{
if (stack <= 1) return string.Empty;
lock (QtyCache)
{
if (QtyCache.TryGetValue(stack, out string? s)) return s;
s = stack < 1000
? stack.ToString(CultureInfo.InvariantCulture)
: (System.Math.Round(stack / 100.0) / 10.0).ToString("0.#", CultureInfo.InvariantCulture) + "k";
if (QtyCache.Count < 4096) QtyCache[stack] = s;
return s;
}
}
/// <summary>"AO" for "Amuli Shadow Coat": the letters a tile shows while its picture is being made.</summary>
public static string Initials(string name)
{
if (string.IsNullOrWhiteSpace(name)) return "?";
string[] words = name.Split(' ', System.StringSplitOptions.RemoveEmptyEntries);
if (words.Length >= 2) return string.Concat(char.ToUpperInvariant(words[0][0]), char.ToUpperInvariant(words[^1][0]));
return name.Length <= 3 ? name : name[..3];
}
}

View file

@ -0,0 +1,277 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Views;
namespace RynthCore.Plugin.RynthSort.Screen;
/// <summary>What a rule change did: whether anything changed, and the toast that says so.</summary>
internal readonly record struct EditResult(bool Changed, string Text)
{
public static EditResult Nothing(string text) => new(false, text);
}
/// <summary>
/// The window's rule changes, in the design's terms: a pack card's chips are the kinds and names its
/// rules hold. A kind sent to a pack leaves every other pack ("All gems"); a name sent to a pack
/// leaves every other pack's rules too and, being a name, beats any kind ("Only \"Black Opal\"");
/// a chip's × takes that one entry out of its rule (an emptied rule goes). Nothing here moves an
/// item. Pure: works on the rule list and the planner's view (the packs as numbered now).
/// </summary>
internal static class RuleEdits
{
/// <summary>The side pack's name for a toast ("Satchel", "Satchel (2)" when two share it), or "pack 3".</summary>
internal static string PackName(SortView view, int number) => PackNames.Label(view, number);
/// <summary>
/// "All &lt;kind&gt;": class <paramref name="cls"/> goes to side pack <paramref name="number"/>,
/// into one of its rules (a new one when it has none with room), and out of every other pack's.
/// </summary>
public static EditResult SendKind(List<SortRule> rules, SortView view, int number, int cls)
{
if (number < 1 || number > view.Packs.Count) return EditResult.Nothing("That pack isn't carried now.");
string label = Kinds.Label(cls);
string pack = PackName(view, number);
bool already = false;
foreach (SortRule r in rules)
if (r.On && r.HasClass(cls) && SortPanel.ShownPack(view, r) == number) { already = true; break; }
var taken = new List<string>();
for (int i = rules.Count - 1; i >= 0; i--)
{
SortRule r = rules[i];
int at = SortPanel.ShownPack(view, r);
if (at == number || !r.HasClass(cls)) continue;
r.RemoveClass(cls);
string from = at > 0 ? PackName(view, at) : "a pack you don't carry";
if (!taken.Contains(from)) taken.Add(from);
if (r.IsEmpty) rules.RemoveAt(i);
}
if (already && taken.Count == 0) return EditResult.Nothing($"{label} already go to {pack}.");
if (!already)
{
SortRule? target = null;
foreach (SortRule r in rules)
if (SortPanel.ShownPack(view, r) == number && r.On && r.Classes.Count > 0 && r.Classes.Count < SortRule.MaxClasses) { target = r; break; }
if (target == null)
foreach (SortRule r in rules)
if (SortPanel.ShownPack(view, r) == number && r.On && r.Classes.Count < SortRule.MaxClasses) { target = r; break; }
if (target == null)
{
if (rules.Count >= SortStore.MaxRules)
return new EditResult(taken.Count > 0, $"There is no room for another rule (the limit is {SortStore.MaxRules}).");
target = new SortRule();
SortPanel.SetPack(target, view, number);
rules.Add(target);
}
target.AddClass(cls);
}
string fromText = taken.Count == 0 ? string.Empty : " (taken from " + string.Join(", ", taken) + ")";
return new EditResult(true, $"All {label.ToLowerInvariant()} now go to {pack}{fromText}. Nothing has moved yet.");
}
/// <summary>
/// "Overflow": class <paramref name="cls"/> stays with the pack that has it, and side pack
/// <paramref name="number"/> takes it when that pack is full (the planner spills into the next
/// pack with the same rule). A new rule at the end of the list, so the pack that has the kind
/// keeps it first. Nothing when no other carried pack has the kind (that is "All &lt;kind&gt;").
/// </summary>
public static EditResult AddOverflow(List<SortRule> rules, SortView view, int number, int cls)
{
if (number < 1 || number > view.Packs.Count) return EditResult.Nothing("That pack isn't carried now.");
string label = Kinds.Label(cls);
int firstPack = 0;
foreach (SortRule r in rules)
if (r.On && r.HasClass(cls)) { firstPack = SortPanel.ShownPack(view, r); break; }
if (firstPack <= 0) return EditResult.Nothing($"No pack you carry takes {label.ToLowerInvariant()} yet: add the kind to a pack first.");
if (firstPack == number) return EditResult.Nothing($"{label} already go to {PackName(view, number)}.");
foreach (SortRule r in rules)
if (r.On && r.HasClass(cls) && SortPanel.ShownPack(view, r) == number)
return EditResult.Nothing($"{PackName(view, number)} already takes {label.ToLowerInvariant()} when {PackName(view, firstPack)} is full.");
if (rules.Count >= SortStore.MaxRules) return EditResult.Nothing($"There is no room for another rule (the limit is {SortStore.MaxRules}).");
var rule = new SortRule();
SortPanel.SetPack(rule, view, number);
rule.AddClass(cls);
rules.Add(rule);
return new EditResult(true, $"{label} go to {PackName(view, firstPack)}, and to {PackName(view, number)} when it is full. Nothing has moved yet.");
}
/// <summary>
/// "Only &lt;name&gt;": the item's name (without a "(100)" count) goes into side pack
/// <paramref name="number"/>'s rules, and the same name comes out of every other pack's.
/// </summary>
public static EditResult SendName(List<SortRule> rules, SortView view, int number, SortItem item)
{
if (number < 1 || number > view.Packs.Count) return EditResult.Nothing("That pack isn't carried now.");
string entry = AddSelectedRules.EntryFor(item.Name);
if (entry.Length == 0) return EditResult.Nothing("That item has no name the client can read yet; try again in a moment.");
bool removed = false;
for (int i = rules.Count - 1; i >= 0; i--)
{
SortRule r = rules[i];
if (SortPanel.ShownPack(view, r) == number || !r.HasName(entry)) continue;
r.RemoveName(entry);
removed = true;
if (r.IsEmpty) rules.RemoveAt(i);
}
var sel = new SelectedItem { Kind = SelectionKind.Item, Id = item.Id, Name = item.Name, Item = item };
AddOutcome o = AddSelectedRules.Apply(rules, view, number, sel);
string pack = PackName(view, number);
return o.Status switch
{
AddStatus.Added => new EditResult(true, $"\"{entry}\" now goes to {pack}. Nothing has moved yet."),
AddStatus.AlreadyThere when removed => new EditResult(true, $"\"{entry}\" now goes to {pack}. Nothing has moved yet."),
AddStatus.AlreadyThere => EditResult.Nothing($"\"{entry}\" already goes to {pack}."),
_ => new EditResult(removed, o.Message),
};
}
/// <summary>
/// A name typed into "+ Add a rule" (0.6.1): items whose name has <paramref name="text"/> in it go
/// to side pack <paramref name="number"/>, and the same name comes out of every other pack's rules.
/// No item needed (before, a name rule took an item dragged on, or the one selected in the game).
/// </summary>
public static EditResult SendNameText(List<SortRule> rules, SortView view, int number, string text)
{
if (number < 1 || number > view.Packs.Count) return EditResult.Nothing("That pack isn't carried now.");
string entry = (text ?? string.Empty).Trim();
if (entry.Length > SortRule.MaxNameLength) entry = entry.Substring(0, SortRule.MaxNameLength).Trim();
if (entry.Length == 0) return EditResult.Nothing("Type part of a name first.");
string pack = PackName(view, number);
SortRule? here = rules.Find(r => SortPanel.ShownPack(view, r) == number && r.HasName(entry));
if (here != null && !here.On) return EditResult.Nothing($"\"{entry}\" is in a rule of {pack} that is turned off: click it to turn it on.");
bool removed = false;
for (int i = rules.Count - 1; i >= 0; i--)
{
SortRule r = rules[i];
if (SortPanel.ShownPack(view, r) == number || !r.HasName(entry)) continue;
r.RemoveName(entry);
removed = true;
if (r.IsEmpty) rules.RemoveAt(i);
}
if (here != null)
return removed
? new EditResult(true, $"\"{entry}\" now goes to {pack} only. Nothing has moved yet.")
: EditResult.Nothing($"\"{entry}\" already goes to {pack}.");
SortRule? target = null;
// This pack's rule that is on and already lists names, else a new rule, else any of its rules with room.
foreach (SortRule r in rules)
if (SortPanel.ShownPack(view, r) == number && r.On && r.Names.Count > 0 && r.Names.Count < SortRule.MaxNames) { target = r; break; }
if (target == null && rules.Count < SortStore.MaxRules)
{
target = new SortRule();
SortPanel.SetPack(target, view, number);
rules.Add(target);
}
if (target == null)
foreach (SortRule r in rules)
if (SortPanel.ShownPack(view, r) == number && r.On && r.Names.Count < SortRule.MaxNames) { target = r; break; }
if (target == null || !target.AddName(entry))
return removed
? new EditResult(true, $"\"{entry}\" left the other packs' rules, but {pack}'s rules are full.")
: EditResult.Nothing($"There is no room in {pack}'s rules.");
return new EditResult(true, $"Items with \"{entry}\" in their name now go to {pack}. Nothing has moved yet.");
}
/// <summary>A chip's ×: the kind or name comes out of rule <paramref name="uid"/> (the rule goes when nothing is left in it).</summary>
public static EditResult RemoveEntry(List<SortRule> rules, SortView view, int uid, bool isName, int cls, string name)
{
int i = rules.FindIndex(r => r.Uid == uid);
if (i < 0) return EditResult.Nothing("That rule is gone already.");
SortRule r = rules[i];
int at = SortPanel.ShownPack(view, r);
string where = at > 0 ? PackName(view, at) : "that pack";
bool done = isName ? r.RemoveName(name) : r.RemoveClass(cls);
if (!done) return EditResult.Nothing("That is gone from the rule already.");
if (r.IsEmpty) rules.RemoveAt(i);
return new EditResult(true, isName
? $"\"{name}\" no longer goes to {where}."
: $"{Kinds.Label(cls)} no longer go to {where}.");
}
/// <summary>A faded chip's click: its rule is turned on.</summary>
public static EditResult TurnOn(List<SortRule> rules, int uid)
{
SortRule? r = rules.Find(x => x.Uid == uid);
if (r == null) return EditResult.Nothing("That rule is gone already.");
if (r.On) return EditResult.Nothing("That rule is on already.");
r.On = true;
return new EditResult(true, $"Rule turned on: {SortRules.Describe(r)}.");
}
/// <summary>"Use this layout": the layout's rules, fitted to the packs carried, replace the character's.</summary>
public static EditResult UseLayout(List<SortRule> rules, SortInventory? inv, StarterLayout layout)
{
if (inv == null) return EditResult.Nothing("Your packs aren't read yet; try again in a moment.");
if (inv.Packs.Count == 0) return EditResult.Nothing("You carry no side packs, so a layout has nowhere to put things.");
LayoutPlan plan = StarterLayouts.Fit(layout, inv);
rules.Clear();
rules.AddRange(plan.Rules);
return new EditResult(true, $"Rules set from {layout.Name}. Press Sort now when you're ready.");
}
}
/// <summary>
/// The window's tick-side state: the toast after a change and the one Undo it offers (the rules as
/// they were before the last change). Pure; the plugin owns one per session.
/// </summary>
internal sealed class ScreenSession
{
public const long ToastMs = 6000;
private List<SortRule>? _undo;
private int _seq;
/// <summary>The toast showing, or null.</summary>
public ToastModel? Toast { get; private set; }
/// <summary>Bumped by every change the window should show at once.</summary>
public int Version { get; private set; }
public bool CanUndo => _undo != null;
public void Reset()
{
_undo = null;
Toast = null;
Version++;
}
/// <summary>
/// Runs a rule change on <paramref name="rules"/>: on a change the rules as they were become the
/// Undo and the toast offers it; otherwise the toast just says why nothing changed. True on a change.
/// </summary>
public bool Edit(List<SortRule> rules, Func<List<SortRule>, EditResult> change, long nowMs)
{
List<SortRule> before = rules.ConvertAll(r => r.Clone());
EditResult result = change(rules);
if (result.Changed) _undo = before;
Show(result.Text, result.Changed, nowMs);
return result.Changed;
}
/// <summary>Shows <paramref name="text"/> (with Undo when <paramref name="undo"/> and there is one).</summary>
public void Show(string text, bool undo, long nowMs)
{
Version++;
if (string.IsNullOrEmpty(text)) { Toast = null; return; }
Toast = new ToastModel { Text = text, CanUndo = undo && _undo != null, Seq = ++_seq, UntilMs = nowMs + ToastMs };
}
/// <summary>Undo: the rules as they were before the last change. False when there is nothing to undo.</summary>
public bool Undo(List<SortRule> rules, long nowMs)
{
if (_undo == null) return false;
rules.Clear();
foreach (SortRule r in _undo) rules.Add(r.Clone());
_undo = null;
Show("Rules put back as they were.", false, nowMs);
return true;
}
/// <summary>The toast is past its time (or dismissed).</summary>
public void Expire(long nowMs)
{
if (Toast != null && nowMs >= Toast.UntilMs) { Toast = null; Version++; }
}
}

View file

@ -0,0 +1,643 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Views;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthSort.Screen;
/// <summary>What the builder needs besides the controller (the plugin fills it; the tests make one).</summary>
internal sealed class ScreenInputs
{
public string Character = string.Empty;
public string Server = string.Empty;
/// <summary>The plugin's own warnings (the RynthSort Lua script set to start too).</summary>
public IReadOnlyList<string> Warnings = Array.Empty<string>();
public bool CanAddSelected;
public bool CanSelect;
/// <summary>The Layouts popup is open: fill <see cref="ScreenModel.Layouts"/>.</summary>
public bool WantLayouts;
public ScreenSession? Session;
}
/// <summary>
/// Builds the window's <see cref="ScreenModel"/> from the controller: the packs as last read, the
/// rules, what a sort would move now (<see cref="SortPreview"/>, as Sort now would go), what is
/// left alone, what settles, the feed. Pure (no host calls): the plugin calls it on its tick while
/// the window shows and publishes the result; the tests call it on hand-made inventories.
/// </summary>
internal static class ScreenBuilder
{
/// <summary>The most Next moves and Left alone rows listed (the rest are counted).</summary>
public const int MaxRows = 30;
private static int _version;
public static ScreenModel Build(SortController c, ScreenInputs input)
{
if (input.Character.Length == 0) return ScreenModel.Empty;
SortInventory? inv = c.LastInventory;
string who = input.Server.Length > 0 ? input.Character + " · " + input.Server : input.Character;
if (inv == null)
return new ScreenModel { Who = who, NotReady = "Reading your packs...", Version = ++_version, Toast = input.Session?.Toast };
List<SortRule> rules = c.Data.Rules;
SortSettings s = c.Data.Settings;
bool clean = c.Job == SortScope.Clean;
SortPreview p = SortPreview.Build(inv, rules, c.CurrentOptions, c.IsHeld, clean);
SortView view = p.View; // the packs as numbered now (the preview planned on this read)
SortView real = c.Planner.View; // the real planner's: what settles, what waits
bool busy = c.Job != null || c.HasMoveOut || c.Status == "sorting" || c.Send != null;
JobPlan? jobs = c.Jobs;
var m = new ScreenModel
{
Ready = true,
Who = who,
Auto = s.Auto,
Busy = busy,
PutBack = c.PutBackCount,
NoRules = rules.Count == 0,
CanAddSelected = input.CanAddSelected,
CanSelect = input.CanSelect,
Toast = input.Session?.Toast,
Version = ++_version,
};
m.PutBackTip = $"Undo the last sort: the {SortPanel.Count(m.PutBack, "item")} it moved go back where they were. "
+ "Turns auto-sort off first, so nothing moves again. Also: /rsort back";
var outgoing = new HashSet<uint>();
foreach (SortMove mv in p.Moves) outgoing.Add(mv.Item.Id);
uint flying = c.InFlightItem;
TileModel Tile(SortItem it, int where)
{
var t = new TileModel
{
Id = it.Id,
Name = it.Name.Length > 0 ? it.Name : "(not known yet)",
Stack = Math.Max(1, it.Stack),
Qty = Kinds.Qty(it.Stack),
Cls = it.ObjectClass,
KindColor = Kinds.Color(it.ObjectClass),
KindLabel = Kinds.Label(it.ObjectClass),
Initials = Kinds.Initials(it.Name),
Where = where,
Outgoing = outgoing.Contains(it.Id),
Settling = real.Settling.Contains(it.Id),
};
t.Moving = it.Id == flying || (busy && t.Outgoing);
SortRule? r = SortRules.RuleFor(rules, it);
if (r != null)
{
int to = SortPanel.ShownPack(view, r);
t.Rule = to > 0 ? TileRule.Pack : TileRule.Missing;
t.RulePack = to;
t.ByName = SortRules.MatchesName(r, it);
t.RuleText = t.ByName ? Kinds.NameChip(MatchedName(r, it)) : Kinds.Label(it.ObjectClass);
}
if (jobs != null && !t.ByName)
{
// A pack whose job picks it comes before a kind rule (a name rule beats both).
foreach (int jp in jobs.PacksFor(it))
{
t.Rule = TileRule.Job;
t.RulePack = jp;
t.RuleText = PackJobs.Label(jobs.Packs[jp]);
break;
}
}
if (c.Touch.TryGetHeld(it.Id, c.Clock, c.HoldMs, out long at, out TouchKind kind))
{
t.Held = true;
t.HeldWhy = Capital(TouchWatch.Words(kind)) + " " + SortPanel.Ago(c.Clock - at);
}
m.TilesById[it.Id] = t;
return t;
}
// Main pack.
int mainCap = SortPlanner.CapacityOf(inv.Main, SortPlanner.MainCapacityFallback);
var mainTiles = new TileModel[inv.Main.Items.Count];
for (int i = 0; i < mainTiles.Length; i++) mainTiles[i] = Tile(inv.Main.Items[i], 0);
m.Main = new MainModel
{
Tiles = mainTiles,
Used = mainTiles.Length,
Capacity = mainCap,
Count = $"{mainTiles.Length} / {mainCap}",
Fill = mainCap > 0 ? Math.Clamp(mainTiles.Length / (float)mainCap, 0f, 1f) : 0f,
NearlyFull = mainCap > 0 && mainTiles.Length > mainCap * 0.88f,
Full = mainCap > 0 && mainTiles.Length >= mainCap,
Wells = MainWells(mainTiles.Length, mainCap),
Handy = s.HandyFront && c.Abilities.ReadOrder && c.Abilities.PlaceMoves
? "Handy at the front: " + HandyItems.Describe(s.HandyClasses, s.HandyNames) + "."
: string.Empty,
Collapsed = s.MainCollapsed,
};
// Side packs.
int packs = inv.Packs.Count;
m.Packs = new PackModel[packs];
m.PacksNote = packs == 0 ? "none carried" : packs + " carried";
var chips = ChipsByPack(rules, view, packs, out List<ChipModel> orphans);
m.Orphans = orphans.ToArray();
for (int i = 0; i < packs; i++)
{
SortPack sp = inv.Packs[i];
int n = i + 1;
int cap = SortPlanner.CapacityOf(sp, SortPlanner.SideCapacityFallback);
var tiles = new TileModel[sp.Items.Count];
for (int k = 0; k < tiles.Length; k++) tiles[k] = Tile(sp.Items[k], n);
var ghosts = new List<GhostModel>();
foreach (SortMove mv in p.Moves)
if (mv.DestIndex == n) ghosts.Add(new GhostModel { ItemId = mv.Item.Id, Tip = $"{ItemName(mv.Item)} is coming here" });
var warnings = new List<string>();
int waiting = 0;
foreach (NoFitLine l in view.NoFit) if (l.Pack == n) waiting++;
if (waiting > 0) warnings.Add($"Full: {SortPanel.Count(waiting, "item")} for it {(waiting == 1 ? "waits" : "wait")} where {(waiting == 1 ? "it is" : "they are")}.");
else if (view.Full.Contains(n) || real.Full.Contains(n)) warnings.Add("Full: the next pack with the same rule takes the rest.");
warnings.AddRange(SortPanel.FallbackWarnings(view, n));
float fill = cap > 0 ? Math.Clamp(tiles.Length / (float)cap, 0f, 1f) : 0f;
m.Packs[i] = new PackModel
{
Number = n,
Id = sp.Id,
Name = sp.Name.Length > 0 ? sp.Name : "Pack " + n,
Label = PackNames.Label(inv, n),
Badge = n.ToString(System.Globalization.CultureInfo.InvariantCulture),
Where = WhereWords(view, n, packs),
Used = tiles.Length,
Capacity = cap,
Count = $"{tiles.Length}/{cap}",
Fill = fill,
NearlyFull = fill > 0.85f,
Full = cap > 0 && tiles.Length >= cap,
Incoming = ghosts.Count > 0 ? $"+{ghosts.Count} coming" : string.Empty,
Tiles = tiles,
Ghosts = ghosts.ToArray(),
Chips = chips[n].ToArray(),
Warnings = warnings.ToArray(),
Tip = SortPanel.PackHeaderTooltip(view, n),
Collapsed = s.CollapsedPacks.Contains(sp.Id),
};
JobOnCard(m.Packs[i], c, inv, n);
}
// The plan column.
m.MovesCount = p.Moves.Count;
var moves = new List<RowModel>(Math.Min(p.Moves.Count, MaxRows));
for (int i = 0; i < p.Moves.Count && i < MaxRows; i++)
{
SortMove mv = p.Moves[i];
SortRule? r = SortRules.RuleFor(rules, mv.Item);
int jobAt = JobPackFor(jobs, mv.Item, r);
string ruleText = jobAt > 0 ? "Job: " + PackJobs.Label(jobs!.Packs[jobAt])
: r == null ? "No rule: back to the main pack"
: "Rule: " + (SortRules.MatchesName(r, mv.Item) ? Kinds.NameChip(MatchedName(r, mv.Item)) : Kinds.Label(mv.Item.ObjectClass));
string to = mv.DestIndex == 0 ? "main pack" : m.PackName(mv.DestIndex);
moves.Add(new RowModel
{
ItemId = mv.Item.Id,
KindColor = Kinds.Color(mv.Item.ObjectClass),
Name = ItemName(mv.Item),
Sub = ruleText,
Right = to,
Tip = $"{ItemName(mv.Item)} goes from the {m.PackName(Math.Max(mv.FromIndex, 0))} to the {to}.",
});
}
m.Moves = moves.ToArray();
if (p.Moves.Count > 0 && !s.Auto && c.Job == null)
m.MovesHint = "Nothing moves until you press Sort now or turn on Auto-sort.";
if (p.ToOrder > 0 && !view.Ordering && view.Handy)
m.OrderHint = p.Moves.Count > 0
? "Then handy items go to the front of the main pack."
: $"{SortPanel.Count(p.ToOrder, "handy item")} still to go to the front of the main pack.";
else if (p.ToOrder > 0)
m.OrderHint = p.Moves.Count > 0
? "Then stacks are joined and items put in order inside each pack."
: $"{SortPanel.Count(p.ToOrder, "item")} still to put in order inside packs.";
var held = new List<RowModel>();
for (int i = 0; i < view.Held.Count && i < MaxRows; i++)
{
HeldLine h = view.Held[i];
m.TilesById.TryGetValue(h.Item.Id, out TileModel? t);
string why = t != null && t.HeldWhy.Length > 0 ? t.HeldWhy : "You used it";
string to = h.To != h.From ? " · would go to " + (h.To == 0 ? "the main pack" : m.PackName(h.To)) : string.Empty;
held.Add(new RowModel
{
ItemId = h.Item.Id,
KindColor = Kinds.Color(h.Item.ObjectClass),
Name = ItemName(h.Item),
Sub = why + to,
Tip = "Left alone: a sort doesn't move it until the time is up. Sort it lets RynthSort move it now.",
});
}
m.Held = held.ToArray();
m.HoldNote = s.HoldMin > 0 ? s.HoldMin + " min" : "off";
var feed = new RowModel[c.Feed.Count];
for (int i = 0; i < feed.Length; i++)
{
FeedLine f = c.Feed[i];
m.TilesById.TryGetValue(f.ItemId, out TileModel? t);
feed[i] = new RowModel { ItemId = f.ItemId, KindColor = t?.KindColor ?? 0, Name = f.Text, Right = f.Time };
}
m.Feed = feed;
m.KindChoices = KindChoices(rules, view);
m.Status = Status(c, real, p, rules.Count == 0, view.Held.Count, busy);
m.Warnings = Warnings(c, real, view, input.Warnings);
m.NoFit = NoFitLines(view, inv);
m.Settings = new SettingsModel
{
SettleSec = s.SettleSec,
HoldMin = s.HoldMin,
GapMs = s.GapMs,
SortInCombat = s.SortInCombat,
OrderInPacks = s.OrderInPacks,
KindFirst = s.OrderKindFirst,
CanOrder = c.Abilities.ReadOrder && c.Abilities.PlaceMoves,
HandyOn = s.HandyFront,
HandyChips = HandyChips(s),
HandyChoices = HandyChoices(s),
};
if (input.WantLayouts) m.Layouts = Layouts(c, inv, rules);
return m;
}
/// <summary>The empty wells after <paramref name="used"/> main-pack tiles: at least three rows of six, and a row past the last item, never past the capacity.</summary>
internal static int MainWells(int used, int capacity)
{
int shown = Math.Max(18, (used + 1 + 5) / 6 * 6);
if (capacity > 0) shown = Math.Min(shown, Math.Max(capacity, used));
return Math.Max(0, shown - used);
}
/// <summary>"Top of your pack column", "Pack 2 from the top", "Bottom of your pack column".</summary>
internal static string WhereWords(SortView view, int number, int packs)
{
if (!view.PackOrderKnown) return "Place in the pack column not known";
if (packs == 1) return "Your only side pack";
if (number == 1) return "Top of your pack column";
if (number == packs) return "Bottom of your pack column";
return $"Pack {number} from the top";
}
/// <summary>The name part of <paramref name="r"/> that <paramref name="it"/>'s name contains (the first), or "".</summary>
internal static string MatchedName(SortRule r, SortItem it)
{
foreach (string n in r.Names)
if (n.Length > 0 && it.Name.Contains(n, StringComparison.OrdinalIgnoreCase)) return n;
return string.Empty;
}
/// <summary>Each side pack's chips ([1..packs]): its rules' kinds (A-Z) then names (A-Z), rule by rule; rules for packs not carried in <paramref name="orphans"/>.</summary>
internal static List<ChipModel>[] ChipsByPack(List<SortRule> rules, SortView view, int packs, out List<ChipModel> orphans)
{
var byPack = new List<ChipModel>[packs + 1];
for (int i = 0; i <= packs; i++) byPack[i] = new List<ChipModel>();
var ordered = new List<SortRule>(rules);
ordered.Sort(SortRules.CompareForList);
// The rule (that is on) each kind follows first; another rule with the same kind is an overflow pack's.
var firstFor = new Dictionary<int, SortRule>();
foreach (SortRule r in rules)
if (r.On)
foreach (int cls in r.Classes) firstFor.TryAdd(cls, r);
foreach (SortRule r in ordered)
{
int n = SortPanel.ShownPack(view, r);
if (n > packs) n = 0;
List<ChipModel> list = byPack[n];
foreach (int cls in SortRules.SortedClasses(r))
{
SortRule? first = firstFor.GetValueOrDefault(cls);
int firstPack = first != null ? SortPanel.ShownPack(view, first) : 0;
bool overflow = r.On && n > 0 && first != null && first != r && firstPack > 0 && firstPack != n;
list.Add(new ChipModel
{
Pack = n, RuleUid = r.Uid, Cls = cls, Dot = Kinds.Color(cls), Off = !r.On, Overflow = overflow,
Label = overflow ? Kinds.Label(cls) + " (overflow)" : Kinds.Label(cls),
Tip = !r.On ? "This rule is turned off: click to turn it on. The x takes it out."
: overflow ? $"{Kinds.Label(cls)} come here when {RuleEdits.PackName(view, firstPack)} is full. The x takes it out (Undo brings it back)."
: n > 0 ? $"Every {Kinds.Label(cls).ToLowerInvariant()} item goes here. The x takes it out (Undo brings it back)."
: $"{Kinds.Label(cls)}: its pack ({(r.PackNote.Length > 0 ? r.PackNote : "pack " + r.Pack)}) isn't carried, so these stay where they are.",
});
}
foreach (string name in SortRules.SortedNames(r))
list.Add(new ChipModel
{
Pack = n, RuleUid = r.Uid, IsName = true, Name = name, Label = Kinds.NameChip(name), Off = !r.On,
Tip = !r.On ? "This rule is turned off: click to turn it on. The x takes it out."
: n > 0 ? $"Items with \"{name}\" in their name go here, whatever their kind (a name beats a kind)."
: $"\"{name}\": its pack ({(r.PackNote.Length > 0 ? r.PackNote : "pack " + r.Pack)}) isn't carried, so these stay where they are.",
});
}
orphans = byPack[0];
return byPack;
}
/// <summary>Every kind the picker offers, and which pack has it now.</summary>
internal static KindChoice[] KindChoices(List<SortRule> rules, SortView view)
{
var a = new KindChoice[ObjectClasses.Choices.Length];
for (int i = 0; i < a.Length; i++)
{
int cls = ObjectClasses.Choices[i];
int at = 0;
foreach (SortRule r in rules)
{
if (!r.On || !r.HasClass(cls)) continue;
int n = SortPanel.ShownPack(view, r);
at = n > 0 ? n : -1;
break;
}
a[i] = new KindChoice { Cls = cls, Label = Kinds.Label(cls), Dot = Kinds.Color(cls), InPack = at };
}
return a;
}
/// <summary>The job pack an item goes to (a name rule beats a job), or 0.</summary>
internal static int JobPackFor(JobPlan? jobs, SortItem it, SortRule? r)
{
if (jobs == null || (r != null && SortRules.MatchesName(r, it))) return 0;
foreach (int n in jobs.PacksFor(it)) return n;
return 0;
}
/// <summary>A side pack's job as its card says it: the pill, the line under the bar, and whether it works now.</summary>
internal static void JobOnCard(PackModel pk, SortController c, SortInventory inv, int number)
{
PackJob? job = PackJobs.On(c.Data.Jobs, inv, number);
if (job == null) return;
pk.Job = job.Kind;
pk.JobMule = job.Mule;
pk.JobLabel = job.Kind == JobKind.Mule && job.Mule.Length > 0 ? "Mule: " + job.Mule : PackJobs.Label(job.Kind);
JobAnswer? a = c.Jobs?.Answers.Of(job.Kind);
if (a == null)
{
pk.JobLine = "Asking RynthAi which items belong here...";
return;
}
if (!a.Known)
{
pk.JobLine = $"{PackJobs.Label(job.Kind)} can't work now: {a.Text}. What is in this pack stays put until it can.";
pk.JobProblem = true;
return;
}
string profile = a.Text.Length > 0 ? " (" + a.Text + ")" : string.Empty;
pk.JobLine = job.Kind switch
{
JobKind.Salvage => $"Takes what RynthAi's loot profile{profile} marks Salvage.",
JobKind.Sell => $"Takes what RynthAi's AutoVendor would sell{profile}.",
_ => $"Takes what RynthAi's AutoTrade would give {(job.Mule.Length > 0 ? job.Mule : "a mule")}{profile}.",
};
}
/// <summary>The handy list as chips: its kinds (in the list's order), then its names.</summary>
internal static ChipModel[] HandyChips(SortSettings s)
{
var list = new List<ChipModel>(s.HandyClasses.Count + s.HandyNames.Count);
foreach (int cls in s.HandyClasses)
list.Add(new ChipModel { Cls = cls, Label = Kinds.Label(cls), Dot = Kinds.Color(cls), Tip = $"{Kinds.Label(cls)} sit at the front of the main pack. The x takes the kind off the list." });
foreach (string n in s.HandyNames)
list.Add(new ChipModel { IsName = true, Name = n, Label = Kinds.NameChip(n), Tip = $"Items with \"{n}\" in their name sit at the front of the main pack, whatever their kind. The x takes it off the list." });
return list.ToArray();
}
/// <summary>The kinds the handy list's picker offers: every kind the rule picker offers that isn't on the list.</summary>
internal static KindChoice[] HandyChoices(SortSettings s)
{
var list = new List<KindChoice>();
foreach (int cls in ObjectClasses.Choices)
if (!s.HandyClasses.Contains(cls))
list.Add(new KindChoice { Cls = cls, Label = Kinds.Label(cls), Dot = Kinds.Color(cls) });
return list.ToArray();
}
/// <summary>The status line and its pill (the design's Off / Moving / Waiting / All tidy).</summary>
internal static StatusModel Status(SortController c, SortView v, SortPreview? p, bool noRules, int held, bool busy)
{
int moves = p?.Moves.Count ?? 0;
string line;
string pill;
PillTone tone;
if (c.Paused)
{
(tone, pill) = (PillTone.Waiting, "Waiting");
line = "Paused: " + SortPanel.PausedWords(c.Status["paused: ".Length..]) + ".";
}
else if (c.Job is SortScope job)
{
(tone, pill) = (PillTone.Moving, "Moving");
line = job switch
{
SortScope.Unpack => "Emptying side packs...",
SortScope.PutBack => "Putting items back...",
SortScope.Clean => "Cleaning packs...",
_ => "Moving items to their packs...",
};
}
else if (c.Send != null || (c.HasMoveOut && !c.Data.Settings.Auto))
{
(tone, pill) = (PillTone.Moving, "Moving");
line = "Moving the item you sent...";
}
else if (!c.Data.Settings.Auto)
{
(tone, pill) = (PillTone.Off, "Off");
line = moves > 0 ? $"Nothing moves by itself. A sort would move {SortPanel.Count(moves, "item")}." : "Nothing moves by itself.";
}
else if (c.Status == "sorting" || c.HasMoveOut)
{
(tone, pill) = (PillTone.Moving, "Moving");
line = "Moving items to their packs...";
}
else if (c.Status is "starting" or "reading your packs" or "waiting for the inventory")
{
(tone, pill) = (PillTone.Waiting, "Reading");
line = "Reading your packs...";
}
else if (v.WaitFull + v.WaitNoPack + v.WaitMainFull > 0)
{
(tone, pill) = (PillTone.Waiting, "Waiting");
var why = new List<string>(3);
if (v.WaitFull > 0) why.Add("a pack is full");
if (v.WaitNoPack > 0) why.Add("a rule's pack isn't carried");
if (v.WaitMainFull > 0) why.Add("the main pack is full");
line = $"{SortPanel.Count(v.WaitFull + v.WaitNoPack + v.WaitMainFull, "item")} can't move: {string.Join(", ", why)}.";
}
else if (v.WaitSettle > 0)
{
(tone, pill) = (PillTone.Waiting, "Waiting");
line = v.WaitSettle == 1
? "1 new item settling, then it goes to its pack."
: $"{v.WaitSettle} new items settling, then they go to their packs.";
}
else if (noRules)
{
(tone, pill) = (PillTone.Waiting, "No rules");
line = "No rules yet: pick a layout, or add a kind to a pack.";
}
else if (moves > 0)
{
(tone, pill) = (PillTone.Waiting, "On");
line = $"{moves} to move.";
}
else
{
(tone, pill) = (PillTone.Tidy, "All tidy");
line = $"New loot goes to its pack {c.Data.Settings.SettleSec} s after it lands.";
}
if (held > 0 && !busy) line += $" {held} left alone.";
return new StatusModel
{
Line = line,
Pill = pill,
Tone = tone,
Tip = line + "\n\n" + SortPanel.AutoTooltip,
};
}
/// <summary>The red banner: per full pack, what didn't fit ("Satchel is full: Black Opal and Fire Opal stay where they are.").</summary>
internal static string[] NoFitLines(SortView view, SortInventory inv)
{
var packs = new List<int>();
foreach (NoFitLine l in view.NoFit) if (!packs.Contains(l.Pack)) packs.Add(l.Pack);
var lines = new string[packs.Count];
for (int i = 0; i < packs.Count; i++)
lines[i] = SortController.NoFitText(view.NoFit.FindAll(l => l.Pack == packs[i]), inv);
return lines;
}
/// <summary>The amber lines under the header.</summary>
internal static string[] Warnings(SortController c, SortView real, SortView view, IReadOnlyList<string> own)
{
var list = new List<string>();
foreach (string w in own) list.Add(w);
if (real.MainFull) list.Add("The main pack is full.");
if (c.Data.Settings.Auto && c.LastBot is RynthAiActivity bot && (bot & RynthAiActivity.AutoCram) != 0 && (bot & RynthAiActivity.MacroRunning) != 0)
list.Add("RynthAi's AutoCram also moves loot out of the main pack; turn one of them off.");
string numbering = SortPanel.NumberingNote(view);
if (numbering.Length > 0) list.Add(numbering);
return list.ToArray();
}
/// <summary>The starter layouts fitted to these packs, with what each would move.</summary>
internal static LayoutCard[] Layouts(SortController c, SortInventory inv, List<SortRule> rules)
{
if (inv.Packs.Count == 0) return Array.Empty<LayoutCard>();
// The kinds carried (any pack), in the order met: what a layout leaves in the main pack.
var carried = new List<int>();
void See(SortItem it)
{
if (SortPlanner.Sortable(it) && !carried.Contains(it.ObjectClass)) carried.Add(it.ObjectClass);
}
foreach (SortItem it in inv.Main.Items) See(it);
foreach (SortPack sp in inv.Packs) foreach (SortItem it in sp.Items) See(it);
var cards = new LayoutCard[StarterLayouts.All.Length];
for (int k = 0; k < cards.Length; k++)
{
StarterLayout l = StarterLayouts.All[k];
LayoutPlan plan = StarterLayouts.Fit(l, inv);
SortPreview pv = SortPreview.Build(inv, plan.Rules, c.CurrentOptions, c.IsHeld);
var bars = new uint[inv.Packs.Count][];
var rows = new LayoutRow[inv.Packs.Count];
var used = new HashSet<int>();
for (int n = 1; n <= inv.Packs.Count; n++)
{
StarterGroup? g = null;
foreach (var (group, pack) in plan.Placed) if (pack == n) { g = group; break; }
int[] classes = g?.Classes ?? Array.Empty<int>();
bars[n - 1] = new uint[classes.Length];
var chips = new ChipModel[classes.Length];
for (int j = 0; j < classes.Length; j++)
{
used.Add(classes[j]);
bars[n - 1][j] = Kinds.Color(classes[j]);
chips[j] = new ChipModel { Pack = n, Cls = classes[j], Label = Kinds.Label(classes[j]), Dot = Kinds.Color(classes[j]) };
}
SortPack sp = inv.Packs[n - 1];
rows[n - 1] = new LayoutRow
{
Pack = n,
Badge = n.ToString(System.Globalization.CultureInfo.InvariantCulture),
PackName = sp.Name.Length > 0 ? sp.Name : "Pack " + n,
Chips = chips,
};
}
var left = new List<string>();
foreach (int cls in carried)
if (!used.Contains(cls))
{
string label = Kinds.Label(cls).ToLowerInvariant();
if (!left.Contains(label)) left.Add(label);
}
cards[k] = new LayoutCard
{
Key = l.Key,
Name = l.Name,
Blurb = l.Blurb,
Bars = bars,
Meta = pv.Moves.Count > 0 ? $"{pv.Moves.Count} would move" : "nothing to move",
Rows = rows,
Left = left.Count > 0 ? "Stay in the main pack: " + string.Join(", ", left) + "." : "Every kind you carry has a pack.",
Replaces = rules.Count > 0 ? " This replaces your rules; Undo brings them back." : string.Empty,
};
}
return cards;
}
private static string ItemName(SortItem it) => it.Name.Length > 0 ? it.Name : $"(item 0x{it.Id:X8})";
private static string Capital(string s) => s.Length > 0 ? char.ToUpperInvariant(s[0]) + s[1..] : s;
}
/// <summary>The words the detail popup builds when it opens (pure, so the tests read them).</summary>
internal static class ScreenText
{
/// <summary>One run of the "why" line: its text, and whether it is bold.</summary>
internal readonly record struct Run(string Text, bool Bold);
/// <summary>
/// Why <paramref name="t"/> is where it is: in its pack by which rule, goes to X by rule Y, or
/// no rule names it so it stays in the main pack.
/// </summary>
public static Run[] Why(TileModel t, ScreenModel m)
{
switch (t.Rule)
{
case TileRule.Pack when t.RulePack == t.Where:
return new[] { new Run("In its pack: ", false), new Run(m.PackName(t.RulePack), true), new Run(", by the rule ", false), new Run(t.RuleText, true), new Run(".", false) };
case TileRule.Pack:
return new[]
{
new Run("Goes to ", false), new Run(m.PackName(t.RulePack), true), new Run(" by the rule ", false), new Run(t.RuleText, true),
new Run(t.Held ? ", once it's no longer left alone." : ".", false),
};
case TileRule.Job when t.RulePack == t.Where:
return new[] { new Run("In its pack: ", false), new Run(m.PackName(t.RulePack), true), new Run(", by its job ", false), new Run(t.RuleText, true), new Run(".", false) };
case TileRule.Job:
return new[]
{
new Run("Goes to ", false), new Run(m.PackName(t.RulePack), true), new Run(": its job is ", false), new Run(t.RuleText, true),
new Run(t.Held ? ", once it's no longer left alone." : ", and RynthAi says this item is one.", false),
};
case TileRule.Missing:
return new[] { new Run("Its rule ", false), new Run(t.RuleText, true), new Run(" names a pack you don't carry, so it stays where it is.", false) };
default:
return t.Where == 0
? new[] { new Run("No rule names it, so it stays in the main pack.", false) }
: new[] { new Run("No rule names it. It stays in ", false), new Run(m.PackName(t.Where), true), new Run("; Clean sends it back to the main pack.", false) };
}
}
/// <summary>"Gems · in Satchel": the detail popup's line under the name.</summary>
public static string KindAndPlace(TileModel t, ScreenModel m) =>
t.KindLabel + " · in " + (t.Where == 0 ? "the main pack" : m.PackName(t.Where));
/// <summary>Whether <paramref name="t"/>'s name has <paramref name="query"/> in it (any case); an empty query matches nothing (no highlight).</summary>
public static bool Matches(TileModel t, string query) =>
query.Length > 0 && t.Name.Contains(query, StringComparison.OrdinalIgnoreCase);
}

View file

@ -0,0 +1,316 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Screen;
// What the RynthSort window shows (2026-11-26, the approved design for #rynth-issues "The bag sort
// feature is lacking in UX"): built on the plugin tick by ScreenBuilder from the controller, the
// last read of the packs and the rules, published whole, and drawn by Window/SortWindow on AC's
// render thread. Never changed after it is published: the renderer only reads it. Every string the
// renderer draws is made here (or once when a popup opens), not per frame.
/// <summary>The coloured pill beside the status line.</summary>
internal enum PillTone : byte
{
/// <summary>Grey: auto-sort is off.</summary>
Off,
/// <summary>Blue: items are moving.</summary>
Moving,
/// <summary>Amber: something waits (settling, paused, stuck, no rules).</summary>
Waiting,
/// <summary>Teal: on and tidy.</summary>
Tidy,
}
internal sealed class StatusModel
{
public string Line = string.Empty;
public string Pill = "Off";
public PillTone Tone;
/// <summary>The status line's tooltip (the whole line, and what the colours mean).</summary>
public string Tip = string.Empty;
}
/// <summary>Where a tile's item belongs by the rules.</summary>
internal enum TileRule : byte
{
/// <summary>No rule names it: it stays in the main pack.</summary>
None,
/// <summary>A rule sends it to a side pack the character carries (<see cref="TileModel.RulePack"/>).</summary>
Pack,
/// <summary>Its rule names a pack the character doesn't carry: it stays where it is.</summary>
Missing,
/// <summary>A side pack's job picks it (<see cref="TileModel.RulePack"/>, the job in <see cref="TileModel.RuleText"/>).</summary>
Job,
}
/// <summary>One item in a pack: its picture, count and what is happening to it.</summary>
internal sealed class TileModel
{
public uint Id;
public string Name = string.Empty;
/// <summary>The count in the corner ("", "75", "2.4k").</summary>
public string Qty = string.Empty;
public int Stack = 1;
public int Cls;
/// <summary>The kind's colour (ARGB): the tile's background while its picture is being made.</summary>
public uint KindColor;
/// <summary>"Gems": the kind as a chip says it.</summary>
public string KindLabel = string.Empty;
/// <summary>"AO": the letters shown while its picture is being made.</summary>
public string Initials = string.Empty;
/// <summary>The pack it is in: 0 = main pack, n = side pack n.</summary>
public int Where;
public TileRule Rule;
/// <summary>The side pack its rule sends it to (1-based) when <see cref="Rule"/> is Pack.</summary>
public int RulePack;
/// <summary>The rule entry it follows, as a chip says it ("Gems", <c>named "Opal"</c>), or "".</summary>
public string RuleText = string.Empty;
/// <summary>It follows a name rule (a name beats a kind).</summary>
public bool ByName;
/// <summary>Left alone: the player used it lately (or asked).</summary>
public bool Held;
/// <summary>Why it is left alone ("you selected it just now").</summary>
public string HeldWhy = string.Empty;
/// <summary>A sort would move it to another pack now (it is in the Next moves list).</summary>
public bool Outgoing;
/// <summary>It is being moved, or the sort running now is about to move it: the tile lifts and pulses.</summary>
public bool Moving;
/// <summary>New in the main pack and still inside the settle time: the spinner ring.</summary>
public bool Settling;
}
/// <summary>A slot an item a sort would bring will take (the dashed "incoming" ghost).</summary>
internal sealed class GhostModel
{
public uint ItemId;
/// <summary>"Black Opal is coming here".</summary>
public string Tip = string.Empty;
}
/// <summary>One entry of a pack's rules: a kind or a name, with its ×.</summary>
internal sealed class ChipModel
{
/// <summary>The side pack it sends to (1-based); 0 for a rule whose pack isn't carried.</summary>
public int Pack;
/// <summary>The rule it belongs to (SortRule.Uid).</summary>
public int RuleUid;
public bool IsName;
public int Cls;
/// <summary>The name part (name chips).</summary>
public string Name = string.Empty;
/// <summary>"Gems", <c>named "Opal"</c>.</summary>
public string Label = string.Empty;
/// <summary>The kind's colour (ARGB) for the dot (kind chips).</summary>
public uint Dot;
/// <summary>The rule is turned off (shown faded; a click turns it on).</summary>
public bool Off;
/// <summary>An overflow pack's kind: another pack's rule has it first, and this pack takes them when that one is full.</summary>
public bool Overflow;
public string Tip = string.Empty;
}
internal sealed class PackModel
{
/// <summary>1-based, top pack first when the pack column's order is known.</summary>
public int Number;
public uint Id;
public string Name = string.Empty;
/// <summary>What a sentence calls it: <see cref="Name"/>, with its number when another pack has the same name ("Satchel (2)").</summary>
public string Label = string.Empty;
/// <summary>The bag badge's number ("1").</summary>
public string Badge = string.Empty;
/// <summary>"Top of your pack column", "Pack 2 from the top".</summary>
public string Where = string.Empty;
/// <summary>"12/24".</summary>
public string Count = string.Empty;
public int Used;
public int Capacity;
public float Fill;
/// <summary>Over 85 % full: the meter turns amber.</summary>
public bool NearlyFull;
/// <summary>Every slot taken (its real capacity): the meter turns red.</summary>
public bool Full;
/// <summary>"+3 coming", or "".</summary>
public string Incoming = string.Empty;
public TileModel[] Tiles = Array.Empty<TileModel>();
public GhostModel[] Ghosts = Array.Empty<GhostModel>();
public ChipModel[] Chips = Array.Empty<ChipModel>();
/// <summary>Amber lines under the grid (full, a rule that uses this pack only because its own isn't carried).</summary>
public string[] Warnings = Array.Empty<string>();
/// <summary>The header's tooltip: which pack in the game this is.</summary>
public string Tip = string.Empty;
/// <summary>Its job (Salvage, Sell, Mule), None when it has none.</summary>
public Sorting.JobKind Job;
/// <summary>"Salvage", "Mule: Name": the pill on the card, "" with no job.</summary>
public string JobLabel = string.Empty;
public string JobMule = string.Empty;
/// <summary>What the job takes, or why it can't work now (RynthAi not loaded, too old, no profile).</summary>
public string JobLine = string.Empty;
/// <summary><see cref="JobLine"/> says why it can't work (amber).</summary>
public bool JobProblem;
/// <summary>Folded down to its header and rules (0.6.1): no slot grid.</summary>
public bool Collapsed;
}
internal sealed class MainModel
{
/// <summary>"12 / 102".</summary>
public string Count = string.Empty;
public int Used;
public int Capacity;
public float Fill;
public bool NearlyFull;
/// <summary>Every slot taken: the meter turns red.</summary>
public bool Full;
public TileModel[] Tiles = Array.Empty<TileModel>();
/// <summary>Empty wells after the tiles (at least three rows in all, a row past the last item).</summary>
public int Wells;
/// <summary>"Handy at the front: healing kits, mana stones and food." while that option works, else "".</summary>
public string Handy = string.Empty;
/// <summary>Folded down to its header (0.6.1): no slot grid.</summary>
public bool Collapsed;
}
/// <summary>A Next moves row, a Left alone row or a feed row: picture, name, a line under it, and what is on the right.</summary>
internal sealed class RowModel
{
/// <summary>The item (its picture); 0 = none (a feed line about a sort).</summary>
public uint ItemId;
public uint KindColor;
public string Name = string.Empty;
public string Sub = string.Empty;
/// <summary>"Satchel" (Next moves: where it goes), the time (the feed), or "".</summary>
public string Right = string.Empty;
public string Tip = string.Empty;
}
/// <summary>A kind the "+ Add a kind..." picker offers.</summary>
internal sealed class KindChoice
{
public int Cls;
public string Label = string.Empty;
public uint Dot;
/// <summary>The side pack whose rules (that are on) have it now (1-based), 0 = none, -1 = a pack not carried.</summary>
public int InPack;
}
/// <summary>A starter layout as the Layouts popup shows it.</summary>
internal sealed class LayoutCard
{
public string Key = string.Empty;
public string Name = string.Empty;
public string Blurb = string.Empty;
/// <summary>Per side pack (as carried), the kind colours (ARGB) of the mini bar; an empty array = the pack stays free.</summary>
public uint[][] Bars = Array.Empty<uint[]>();
/// <summary>"5 would move", "nothing to move".</summary>
public string Meta = string.Empty;
public LayoutRow[] Rows = Array.Empty<LayoutRow>();
/// <summary>"Stay in the main pack: armor, trade notes." or "Every kind you carry has a pack."</summary>
public string Left = string.Empty;
/// <summary>" This replaces your rules; Undo brings them back." when the character has rules, else "".</summary>
public string Replaces = string.Empty;
}
internal sealed class LayoutRow
{
public int Pack;
public string Badge = string.Empty;
public string PackName = string.Empty;
public ChipModel[] Chips = Array.Empty<ChipModel>();
}
/// <summary>The settings popup's values (the renderer keeps its own copy while a slider is dragged).</summary>
internal sealed class SettingsModel
{
public int SettleSec;
public int HoldMin;
public int GapMs;
public bool SortInCombat;
public bool OrderInPacks;
public bool KindFirst;
/// <summary>The engine can read the order inside packs (API v80).</summary>
public bool CanOrder;
/// <summary>"Keep handy items at the front of the main pack" is on.</summary>
public bool HandyOn;
/// <summary>The kinds and names that count as handy, as chips (IsName for a name part), with their ×.</summary>
public ChipModel[] HandyChips = Array.Empty<ChipModel>();
/// <summary>The kinds the handy list's picker offers (the ones not in it yet).</summary>
public KindChoice[] HandyChoices = Array.Empty<KindChoice>();
}
/// <summary>The line at the bottom after a change: what happened, and Undo when it can be undone.</summary>
internal sealed class ToastModel
{
public string Text = string.Empty;
public bool CanUndo;
/// <summary>Changes with every new toast (the renderer restarts its fade).</summary>
public int Seq;
/// <summary>Shown until (the tick's clock, ms).</summary>
public long UntilMs;
}
internal sealed class ScreenModel
{
/// <summary>Logged in and the packs read: everything below is filled.</summary>
public bool Ready;
/// <summary>What to say instead ("Log in to sort your packs.").</summary>
public string NotReady = string.Empty;
/// <summary>"Character · Server".</summary>
public string Who = string.Empty;
public StatusModel Status = new();
public bool Auto;
/// <summary>A sort, Put back or Empty is running (Sort now is greyed).</summary>
public bool Busy;
/// <summary>How many items Put back would move back (0: no button).</summary>
public int PutBack;
public string PutBackTip = string.Empty;
/// <summary>Amber lines under the header (the Lua script set to start too, AutoCram, numbering, main pack full).</summary>
public string[] Warnings = Array.Empty<string>();
/// <summary>The red banner: per full pack, the items that didn't fit (they stay where they are).</summary>
public string[] NoFit = Array.Empty<string>();
public MainModel Main = new();
public PackModel[] Packs = Array.Empty<PackModel>();
/// <summary>"4 carried".</summary>
public string PacksNote = string.Empty;
public RowModel[] Moves = Array.Empty<RowModel>();
public int MovesCount;
/// <summary>"Nothing moves until you press Sort now or turn on Auto-sort.", or "".</summary>
public string MovesHint = string.Empty;
/// <summary>"Then stacks are joined and 3 items put in order inside packs.", or "".</summary>
public string OrderHint = string.Empty;
public RowModel[] Held = Array.Empty<RowModel>();
/// <summary>"3 min" (the Left alone eyebrow), "off".</summary>
public string HoldNote = string.Empty;
public RowModel[] Feed = Array.Empty<RowModel>();
/// <summary>Rules whose pack isn't carried (their entries as chips, × removes).</summary>
public ChipModel[] Orphans = Array.Empty<ChipModel>();
public KindChoice[] KindChoices = Array.Empty<KindChoice>();
/// <summary>The starter layouts, filled only while the Layouts popup is open.</summary>
public LayoutCard[] Layouts = Array.Empty<LayoutCard>();
public SettingsModel Settings = new();
public ToastModel? Toast;
/// <summary>The game's selection can be read (the picker's "The item selected in the game").</summary>
public bool CanAddSelected;
/// <summary>Items can be selected in the game (the bag badge selects its pack).</summary>
public bool CanSelect;
/// <summary>The character has no rules yet (the window suggests a layout).</summary>
public bool NoRules;
/// <summary>Every tile by item id (the detail and drop popups look items up here).</summary>
public Dictionary<uint, TileModel> TilesById = new();
/// <summary>Changes with every build.</summary>
public int Version;
public static readonly ScreenModel Empty = new() { NotReady = "Log in to sort your packs." };
/// <summary>The side pack numbered <paramref name="number"/> (1-based), or null.</summary>
public PackModel? Pack(int number) => number >= 1 && number <= Packs.Length ? Packs[number - 1] : null;
/// <summary>"main pack" for 0, else the side pack's name ("Satchel", "Satchel (2)" when two share it), or "pack 5" past the packs carried.</summary>
public string PackName(int index)
{
if (index == 0) return "main pack";
PackModel? p = Pack(index);
return p != null ? (p.Label.Length > 0 ? p.Label : p.Name) : "pack " + index;
}
}

View file

@ -3,7 +3,7 @@ using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthSort;
internal enum SortVerb { Window, On, Off, Now, Clean, Unpack, Status, Help, Unknown }
internal enum SortVerb { Window, On, Off, Now, Clean, Unpack, Back, Add, Status, Help, Unknown }
/// <summary>
/// A parsed "/rsort ..." and the lines it answers with (2026-10-28: every command answers,
@ -26,6 +26,8 @@ internal readonly record struct SortCommand(SortVerb Verb, int? Pack = null, boo
"now" or "tidy" => new(SortVerb.Now),
"clean" => new(SortVerb.Clean),
"unpack" => new(SortVerb.Unpack, words.Length > 1 && int.TryParse(words[1], out int p) && p > 0 ? p : null),
"back" or "undo" => new(SortVerb.Back),
"add" => new(SortVerb.Add, words.Length > 1 && int.TryParse(words[1], out int a) && a > 0 ? a : null),
"status" => new(SortVerb.Status),
"help" or "?" => new(SortVerb.Help),
_ => new(SortVerb.Unknown, Word: word),
@ -35,10 +37,12 @@ internal readonly record struct SortCommand(SortVerb Verb, int? Pack = null, boo
/// <summary>The window and help work before the character is known; everything else waits for it.</summary>
public bool NeedsLogin => Verb is not (SortVerb.Window or SortVerb.Help);
public const string Usage = "/rsort [on | off | now | tidy | clean | unpack [pack] | status]";
public const string Usage = "/rsort [on | off | now | tidy | clean | unpack [pack] | back | add <pack> | status]";
public const string AddUsage = "/rsort add <pack>: puts the item selected in the game into that pack's rules (pack numbers as the window shows them).";
public const string NoWindows =
"This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Sorting still runs: /rsort on|off|now|tidy|clean|unpack.";
"This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Sorting still runs: /rsort on|off|now|tidy|clean|unpack|back.";
public static string Window(bool shown) => CommandReply.Shown("RynthSort window", shown);
@ -50,5 +54,10 @@ internal readonly record struct SortCommand(SortVerb Verb, int? Pack = null, boo
public static string Unpacking(int? pack) =>
(pack != null ? $"Emptying pack {pack}" : "Emptying your side packs") + " into the main pack; auto-sort is off (/rsort on when done).";
/// <summary>"/rsort back": Put back starts, or there is nothing to put back.</summary>
public static string PuttingBack(int count) => count > 0
? $"Putting back the {count} item{(count == 1 ? "" : "s")} the last sort moved; auto-sort is off (/rsort on when done)."
: "Nothing to put back: RynthSort hasn't moved anything to another pack lately.";
public static string Unknown(string word) => $"Unknown '/rsort {word}'. Usage: {Usage}";
}

View file

@ -11,10 +11,16 @@ namespace RynthCore.Plugin.RynthSort;
/// <summary>RynthSort's settings for one character (the Lua script's DEFAULTS, plus what the plugin adds).</summary>
internal sealed class SortSettings
{
public const int SettleMin = 0, SettleMax = 30, GapMin = 100, GapMax = 3000;
public const int SettleMin = 0, SettleMax = 30, GapMin = 100, GapMax = 3000, HoldMinMin = 0, HoldMinMax = 30;
/// <summary>The hold a character gets until it changes it (minutes).</summary>
public const int HoldMinDefault = 3;
/// <summary>Auto-sort: keeps every pack tidy (new items from the main pack after the settle time, misplaced items, stacks, order).</summary>
public bool Auto = true;
/// <summary>
/// Auto-sort: keeps every pack tidy (new items from the main pack after the settle time, misplaced items, stacks, order).
/// Off for a character RynthSort hasn't seen: players found items moving out from under them before they had
/// set up any rules (#rynth-issues "The bag sort feature is lacking in UX"). A saved file keeps its own choice.
/// </summary>
public bool Auto;
/// <summary>How long a new item sits in the main pack before it moves (seconds).</summary>
public int SettleSec = 5;
/// <summary>Auto-sort's pause between two moves (ms), to leave the bot room.</summary>
@ -32,24 +38,72 @@ internal sealed class SortSettings
/// script's rules, to show them.
/// </summary>
public bool WindowOpen;
/// <summary>
/// "Leave items I use alone": an item the player moved, selected, dragged, took off or picked up
/// isn't sorted for this many minutes (0 = off). Files from before it have the default.
/// </summary>
public int HoldMin = HoldMinDefault;
/// <summary>
/// "Keep handy items at the front of the main pack" (0.6.0, <see cref="HandyItems"/>). Off for a
/// file from before it and for a new character: it moves items in the main pack, so the player
/// turns it on.
/// </summary>
public bool HandyFront;
/// <summary>The kinds that count as handy (ObjectClass numbers), each once.</summary>
public List<int> HandyClasses = new(HandyItems.DefaultClasses);
/// <summary>Parts of names that count as handy whatever their kind ("Potion"), each once.</summary>
public List<string> HandyNames = new(HandyItems.DefaultNames);
/// <summary>
/// Side packs folded down to their header and rules in the window (0.6.1, by the pack's object
/// id, so it stays with the pack when packs are reordered), newest last, at most
/// <see cref="MaxCollapsed"/>.
/// </summary>
public List<uint> CollapsedPacks = new();
/// <summary>The main pack's card folded down to its header in the window.</summary>
public bool MainCollapsed;
public const int MaxCollapsed = 64;
/// <summary>Side pack <paramref name="id"/> folded or not; true when that changed something.</summary>
public bool SetCollapsed(uint id, bool collapsed)
{
if (id == 0) return false;
bool has = CollapsedPacks.Contains(id);
if (has == collapsed) return false;
if (collapsed)
{
if (CollapsedPacks.Count >= MaxCollapsed) CollapsedPacks.RemoveAt(0);
CollapsedPacks.Add(id);
}
else CollapsedPacks.Remove(id);
return true;
}
public void Clamp()
{
SettleSec = Math.Clamp(SettleSec, SettleMin, SettleMax);
GapMs = Math.Clamp(GapMs, GapMin, GapMax);
HoldMin = Math.Clamp(HoldMin, HoldMinMin, HoldMinMax);
}
}
/// <summary>One character's rules and settings.</summary>
internal sealed class CharacterSortData
{
public List<SortRule> Rules = SortRules.Defaults();
/// <summary>
/// None for a character RynthSort hasn't seen (2026-11-26): the window offers starter layouts
/// fitted to the packs it carries instead of rules by pack number that may name the wrong packs
/// (#rynth-issues "The bag sort feature is lacking in UX": "there is no common-sense default").
/// A saved file, or the Lua script's, keeps its own rules.
/// </summary>
public List<SortRule> Rules = new();
/// <summary>Side packs with a job (0.6.0: Salvage, Sell, Mule; <see cref="PackJobs"/>). None for a file from before them.</summary>
public List<PackJob> Jobs = new();
public SortSettings Settings = new();
/// <summary>Where these came from on first run ("" = defaults, else the Lua script's file).</summary>
/// <summary>Where these came from on first run ("" = RynthSort's own, or none yet; else the Lua script's file).</summary>
public string ImportedFrom = string.Empty;
/// <summary>
/// The rules are tied to pack ids (<see cref="PackFix"/> ran once). False for files saved
/// before pack ids, a new character's defaults and a fresh import from the Lua script.
/// before pack ids and a fresh import from the Lua script.
/// </summary>
public bool PacksFixed;
/// <summary>
@ -99,7 +153,7 @@ internal sealed class SortStore
/// <summary>
/// The character's rules and settings: RynthSort's own file; else the Lua script's (imported:
/// <see cref="CharacterSortData.ImportedFrom"/> says so, and the caller saves it as RynthSort's);
/// else the defaults. A broken file reads as the defaults (the next save rewrites it).
/// else no rules (the window offers starter layouts). A broken file reads as no rules (the plugin keeps a .bak of it at the next save).
/// </summary>
public CharacterSortData Load(string server, string character, out string? problem)
{
@ -179,8 +233,42 @@ internal sealed class SortStore
st.OrderInPacks = Bool(s, "orderInPacks", st.OrderInPacks);
st.OrderKindFirst = Bool(s, "orderKindFirst", st.OrderKindFirst);
st.WindowOpen = Bool(s, "windowOpen", st.WindowOpen);
st.HoldMin = Int(s, "holdMin", st.HoldMin);
st.HandyFront = Bool(s, "handyFront", false);
st.MainCollapsed = Bool(s, "mainCollapsed", false);
if (s.TryGetProperty("collapsed", out JsonElement cp) && cp.ValueKind == JsonValueKind.Array)
foreach (JsonElement c in cp.EnumerateArray())
if (c.ValueKind == JsonValueKind.Number && c.TryGetUInt32(out uint id)) st.SetCollapsed(id, true);
if (s.TryGetProperty("handyClasses", out JsonElement hc) && hc.ValueKind == JsonValueKind.Array)
{
st.HandyClasses.Clear();
foreach (JsonElement c in hc.EnumerateArray())
if (c.ValueKind == JsonValueKind.Number && c.TryGetDouble(out double v) && v >= 0 && v <= 1000) HandyItems.AddClass(st, (int)Math.Round(v));
}
if (s.TryGetProperty("handyNames", out JsonElement hn) && hn.ValueKind == JsonValueKind.Array)
{
st.HandyNames.Clear();
foreach (JsonElement n in hn.EnumerateArray())
if (n.ValueKind == JsonValueKind.String) HandyItems.AddName(st, n.GetString());
}
st.Clamp();
}
if (root.TryGetProperty("jobs", out JsonElement jobs) && jobs.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement e in jobs.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object || d.Jobs.Count >= MaxPack) continue;
JobKind kind = PackJobs.Parse(e.TryGetProperty("job", out JsonElement jk) && jk.ValueKind == JsonValueKind.String ? jk.GetString() : null);
if (kind == JobKind.None) continue;
d.Jobs.Add(new PackJob
{
Kind = kind,
PackId = UInt(e, "packId"),
Pack = Math.Clamp(Int(e, "pack", 1), 1, MaxPack),
Mule = kind == JobKind.Mule && e.TryGetProperty("mule", out JsonElement mu) && mu.ValueKind == JsonValueKind.String ? SortRule.Clean(mu.GetString()) : string.Empty,
});
}
}
if (root.TryGetProperty("importedFrom", out JsonElement f) && f.ValueKind == JsonValueKind.String)
d.ImportedFrom = f.GetString() ?? string.Empty;
// Missing (a version 1 file, the Lua script's file): rules by number only, not fixed yet.
@ -288,7 +376,38 @@ internal sealed class SortStore
w.WriteBoolean("orderInPacks", d.Settings.OrderInPacks);
w.WriteBoolean("orderKindFirst", d.Settings.OrderKindFirst);
w.WriteBoolean("windowOpen", d.Settings.WindowOpen);
// 2026-11-26: an older RynthSort reading this file skips it (it keeps no hold).
w.WriteNumber("holdMin", d.Settings.HoldMin);
// 0.6.0: handy items at the front of the main pack (an older RynthSort skips these).
w.WriteBoolean("handyFront", d.Settings.HandyFront);
w.WriteStartArray("handyClasses");
foreach (int c in d.Settings.HandyClasses) w.WriteNumberValue(c);
w.WriteEndArray();
w.WriteStartArray("handyNames");
foreach (string n in d.Settings.HandyNames) w.WriteStringValue(n);
w.WriteEndArray();
// 0.6.1: packs folded in the window (an older RynthSort skips these).
w.WriteBoolean("mainCollapsed", d.Settings.MainCollapsed);
w.WriteStartArray("collapsed");
foreach (uint id in d.Settings.CollapsedPacks) w.WriteNumberValue(id);
w.WriteEndArray();
w.WriteEndObject();
// 0.6.0: side packs with a job (an older RynthSort skips this).
if (d.Jobs.Count > 0)
{
w.WriteStartArray("jobs");
foreach (PackJob j in d.Jobs)
{
if (j.Kind == JobKind.None) continue;
w.WriteStartObject();
w.WriteString("job", PackJobs.Key(j.Kind));
if (j.PackId != 0) w.WriteNumber("packId", j.PackId);
w.WriteNumber("pack", j.Pack);
if (j.Kind == JobKind.Mule && j.Mule.Length > 0) w.WriteString("mule", j.Mule);
w.WriteEndObject();
}
w.WriteEndArray();
}
if (d.ImportedFrom.Length > 0) w.WriteString("importedFrom", d.ImportedFrom);
w.WriteBoolean("packsFixed", d.PacksFixed);
w.WriteEndObject();

View file

@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>
/// "Keep handy items at the front of the main pack": the things a player reaches for (healing
/// kits, mana stones, food, potions and elixirs; the list is the player's to change) sit in the main
/// pack's first slots. Only items that live in the main pack anyway: a kind a side pack's rule names
/// still goes to that pack. It needs moves to a slot (plugin API v80). Items left alone (held) and
/// items that can't move now are never moved for it: handy items go after them. Pure.
/// </summary>
internal static class HandyItems
{
public const int MaxClasses = 16, MaxNames = 12;
/// <summary>The kinds a character starts with.</summary>
public static readonly int[] DefaultClasses = { ObjectClasses.HealingKit, ObjectClasses.ManaStone, ObjectClasses.Food };
/// <summary>
/// Parts of names that count as handy whatever their kind: potions and elixirs (the client
/// calls most of them Food already, but not every server's do).
/// </summary>
public static readonly string[] DefaultNames = { "Potion", "Elixir" };
/// <summary>Whether <paramref name="it"/> is handy by these kinds and names (a name part matches any case).</summary>
public static bool Matches(IReadOnlyList<int> classes, IReadOnlyList<string> names, SortItem it)
{
for (int i = 0; i < classes.Count; i++)
if (classes[i] == it.ObjectClass) return true;
string name = it.Name ?? string.Empty;
if (name.Length == 0) return false;
for (int i = 0; i < names.Count; i++)
if (names[i].Length > 0 && name.Contains(names[i], StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>The planner's test for the settings now (a copy of the lists: later edits don't change a plan under way), or null when the option is off.</summary>
public static Func<SortItem, bool>? For(SortSettings s)
{
if (!s.HandyFront || (s.HandyClasses.Count == 0 && s.HandyNames.Count == 0)) return null;
int[] classes = s.HandyClasses.ToArray();
string[] names = s.HandyNames.ToArray();
return it => Matches(classes, names, it);
}
/// <summary>"healing kits, mana stones, food, potions and elixirs": the list in a sentence (names as they are typed).</summary>
public static string Describe(IReadOnlyList<int> classes, IReadOnlyList<string> names)
{
var parts = new List<string>(classes.Count + names.Count);
foreach (int c in classes) parts.Add(ObjectClasses.Plural(c).ToLowerInvariant());
foreach (string n in names) parts.Add(Plural(n).ToLowerInvariant());
if (parts.Count == 0) return "nothing";
if (parts.Count == 1) return parts[0];
return string.Join(", ", parts.GetRange(0, parts.Count - 1)) + " and " + parts[^1];
}
private static string Plural(string n) => n.EndsWith("s", StringComparison.OrdinalIgnoreCase) ? n : n + "s";
/// <summary>Adds a kind (false when it is there, the list is full, or it isn't one the picker offers).</summary>
public static bool AddClass(SortSettings s, int cls)
{
if (ObjectClasses.ChoiceIndex(cls) < 0 || s.HandyClasses.Contains(cls) || s.HandyClasses.Count >= MaxClasses) return false;
s.HandyClasses.Add(cls);
return true;
}
/// <summary>Adds a part of a name, trimmed (false when blank, there already, or the list is full).</summary>
public static bool AddName(SortSettings s, string? text)
{
string t = SortRule.Clean(text);
if (t.Length == 0 || s.HandyNames.Count >= MaxNames) return false;
foreach (string n in s.HandyNames) if (string.Equals(n, t, StringComparison.OrdinalIgnoreCase)) return false;
s.HandyNames.Add(t);
return true;
}
public static bool RemoveName(SortSettings s, string text) =>
s.HandyNames.RemoveAll(n => string.Equals(n, text, StringComparison.OrdinalIgnoreCase)) > 0;
}

View file

@ -72,7 +72,12 @@ internal sealed class InventoryReader
bool capRead = isContainer && host.TryGetObjectIntProperty(id, IntItemsCapacity, out cap);
// Every container entry, foci too and before the wielded check: the Lua script's count.
if (isContainer) inv.Slots.Add(new SortSlot(id, capRead ? Math.Max(cap, 0) : -1));
if (Wielded(host, id)) continue;
if (Wielded(host, id))
{
// Kept so taking an item off reads as the player's doing (TouchWatch).
inv.Worn.Add(id);
continue;
}
if (isContainer)
{
// A side pack holds items; foci (containers that hold none) aren't packs or items.

View file

@ -0,0 +1,190 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>What a side pack is for besides its rules (0.6.0): items another tool picks.</summary>
internal enum JobKind : byte
{
None = 0,
/// <summary>Items RynthAi's loot profile in use marks Salvage (its first matching rule).</summary>
Salvage = 1,
/// <summary>Items RynthAi's AutoVendor would sell (its default.utl and its safety checks).</summary>
Sell = 2,
/// <summary>Items set aside for a mule: what RynthAi's AutoTrade would give it (its &lt;mule&gt;.utl, else default.utl).</summary>
Mule = 3,
}
/// <summary>A side pack's job, kept by the pack's id (its number when the id isn't carried, as a rule).</summary>
internal sealed class PackJob
{
public uint PackId;
public int Pack = 1;
public JobKind Kind;
/// <summary>The mule's character name for <see cref="JobKind.Mule"/> ("" = AutoTrade's default.utl).</summary>
public string Mule = string.Empty;
public PackJob Clone() => new() { PackId = PackId, Pack = Pack, Kind = Kind, Mule = Mule };
}
/// <summary>What RynthAi answered for one job: whether there is an answer, and if not, why (the window says it).</summary>
internal sealed class JobAnswer
{
/// <summary>RynthAi answered: <see cref="Marked"/> is the whole list of items it picks.</summary>
public bool Known;
/// <summary>The items it picks (object ids).</summary>
public readonly HashSet<uint> Marked = new();
/// <summary>Known: the profile it used ("Hunting.utl"); not known: why ("RynthAi isn't loaded").</summary>
public string Text = string.Empty;
public static JobAnswer Unknown(string why) => new() { Text = why };
}
/// <summary>RynthAi's answers for the jobs the carried packs have (the plugin asks; the tests make them).</summary>
internal sealed class JobAnswers
{
public readonly Dictionary<JobKind, JobAnswer> ByKind = new();
/// <summary>The mule a Mule pack asked about (one mule at a time: the first Mule pack's).</summary>
public string Mule = string.Empty;
public JobAnswer? Of(JobKind kind) => ByKind.TryGetValue(kind, out JobAnswer? a) ? a : null;
}
/// <summary>
/// Pack jobs (0.6.0, #rynth-issues "The bag sort feature is lacking in UX" follow-up): a side pack can
/// hold what another tool picks: Salvage (RynthAi's loot profile), Sell (RynthAi's AutoVendor), or a
/// Mule (RynthAi's AutoTrade). Where an item goes: a name rule first (the player named it), then a
/// job that picks it, then a kind rule. A job pack whose answer isn't known (RynthAi not loaded, too
/// old, no profile) changes nothing: items in it stay, nothing new goes in. Pure.
/// </summary>
internal static class PackJobs
{
public static string Label(JobKind k) => k switch
{
JobKind.Salvage => "Salvage",
JobKind.Sell => "Sell",
JobKind.Mule => "Mule",
_ => "No job",
};
/// <summary>"salvage", "sell", "mule": how the file says it.</summary>
public static string Key(JobKind k) => k switch
{
JobKind.Salvage => "salvage",
JobKind.Sell => "sell",
JobKind.Mule => "mule",
_ => string.Empty,
};
public static JobKind Parse(string? key) => (key ?? string.Empty).Trim().ToLowerInvariant() switch
{
"salvage" => JobKind.Salvage,
"sell" => JobKind.Sell,
"mule" => JobKind.Mule,
_ => JobKind.None,
};
/// <summary>The side pack (1-based) job <paramref name="j"/> is on: its id when carried, else its number; 0 when neither.</summary>
public static int Resolve(PackJob j, SortInventory inv)
{
int byId = inv.IndexOf(j.PackId);
if (byId > 0) return byId;
return j.PackId == 0 && j.Pack >= 1 && j.Pack <= inv.Packs.Count ? j.Pack : 0;
}
/// <summary>Each carried side pack's job ([n] for pack n, None when it has none).</summary>
public static JobKind[] ByPack(IReadOnlyList<PackJob> jobs, SortInventory inv)
{
var a = new JobKind[inv.Packs.Count + 1];
foreach (PackJob j in jobs)
{
int n = Resolve(j, inv);
if (n > 0 && j.Kind != JobKind.None && a[n] == JobKind.None) a[n] = j.Kind;
}
return a;
}
/// <summary>The job on pack <paramref name="number"/>, or null.</summary>
public static PackJob? On(IReadOnlyList<PackJob> jobs, SortInventory inv, int number)
{
foreach (PackJob j in jobs)
if (j.Kind != JobKind.None && Resolve(j, inv) == number) return j;
return null;
}
/// <summary>
/// Sets pack <paramref name="number"/>'s job (None takes it off). One job a pack; the pack is kept
/// by its id. False when nothing changed or the pack isn't carried.
/// </summary>
public static bool Set(List<PackJob> jobs, SortInventory inv, int number, JobKind kind, string? mule)
{
if (number < 1 || number > inv.Packs.Count) return false;
string m = SortRule.Clean(mule);
PackJob? have = On(jobs, inv, number);
if (kind == JobKind.None)
{
if (have == null) return false;
jobs.RemoveAll(j => Resolve(j, inv) == number);
return true;
}
if (have != null && have.Kind == kind && (kind != JobKind.Mule || string.Equals(have.Mule, m, StringComparison.Ordinal))) return false;
jobs.RemoveAll(j => Resolve(j, inv) == number);
jobs.Add(new PackJob { PackId = inv.Packs[number - 1].Id, Pack = number, Kind = kind, Mule = kind == JobKind.Mule ? m : string.Empty });
return true;
}
/// <summary>The jobs the carried packs have, each once (what to ask RynthAi), and the first Mule pack's mule.</summary>
public static List<JobKind> Wanted(IReadOnlyList<PackJob> jobs, SortInventory inv, out string mule)
{
mule = string.Empty;
var list = new List<JobKind>();
bool muleSet = false;
foreach (PackJob j in jobs)
{
if (j.Kind == JobKind.None || Resolve(j, inv) == 0) continue;
if (!list.Contains(j.Kind)) list.Add(j.Kind);
if (j.Kind == JobKind.Mule && !muleSet) { mule = j.Mule; muleSet = true; }
}
return list;
}
}
/// <summary>The jobs as the planner sees them for one pass: each carried pack's job and RynthAi's answers.</summary>
internal sealed class JobPlan
{
/// <summary>[n] = side pack n's job.</summary>
public JobKind[] Packs = Array.Empty<JobKind>();
public JobAnswers Answers = new();
public bool Any
{
get
{
foreach (JobKind k in Packs) if (k != JobKind.None) return true;
return false;
}
}
public static JobPlan? For(IReadOnlyList<PackJob> jobs, SortInventory inv, JobAnswers? answers)
{
if (jobs.Count == 0) return null;
var p = new JobPlan { Packs = PackJobs.ByPack(jobs, inv), Answers = answers ?? new JobAnswers() };
return p.Any ? p : null;
}
/// <summary>Pack <paramref name="index"/> has a job whose answer isn't known: what is in it stays.</summary>
public bool Frozen(int index) =>
index > 0 && index < Packs.Length && Packs[index] != JobKind.None && Answers.Of(Packs[index])?.Known != true;
/// <summary>The job packs (pack order) whose job picks <paramref name="it"/>, best first.</summary>
public IEnumerable<int> PacksFor(SortItem it)
{
for (int n = 1; n < Packs.Length; n++)
{
JobKind k = Packs[n];
if (k == JobKind.None) continue;
JobAnswer? a = Answers.Of(k);
if (a != null && a.Known && a.Marked.Contains(it.Id)) yield return n;
}
}
}

View file

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>
/// What the window calls a pack in a sentence (the activity feed, toasts, Next moves): "main pack",
/// the side pack's own name ("Satchel"), and, when another carried pack has the same name, its
/// number too, as its card's badge shows it ("Satchel (2)"). A pack the client hasn't named yet is
/// "pack 3". Pure.
/// </summary>
internal static class PackNames
{
public const string Main = "main pack";
/// <summary>Pack <paramref name="index"/> (0 = the main pack, n = side pack n) among <paramref name="names"/> (side packs, pack 1 first).</summary>
public static string Label(IReadOnlyList<string> names, int index)
{
if (index == 0) return Main;
if (index < 1 || index > names.Count) return "pack " + index;
string name = Clean(names[index - 1]);
if (name.Length == 0) return "pack " + index;
for (int i = 0; i < names.Count; i++)
if (i != index - 1 && string.Equals(Clean(names[i]), name, StringComparison.OrdinalIgnoreCase))
return name + " (" + index.ToString(System.Globalization.CultureInfo.InvariantCulture) + ")";
return name;
}
/// <summary>As <see cref="Label(IReadOnlyList{string}, int)"/>, for the packs as read.</summary>
public static string Label(SortInventory? inv, int index)
{
if (index == 0) return Main;
if (inv == null) return "pack " + index;
var names = new string[inv.Packs.Count];
for (int i = 0; i < names.Length; i++) names[i] = inv.Packs[i].Name;
return Label(names, index);
}
/// <summary>As <see cref="Label(IReadOnlyList{string}, int)"/>, for the packs a planning pass listed.</summary>
public static string Label(SortView view, int index)
{
if (index == 0) return Main;
var names = new string[view.Packs.Count];
for (int i = 0; i < names.Length; i++) names[i] = view.Packs[i].Name;
return Label(names, index);
}
private static string Clean(string? s) => (s ?? string.Empty).Trim();
}

View file

@ -49,12 +49,15 @@ internal static class PackOrder
}
/// <summary>Each item's place in the target order (0 = first), in the items' current order.</summary>
public static int[] Ranks(IReadOnlyList<SortItem> items, bool kindFirst)
public static int[] Ranks(IReadOnlyList<SortItem> items, bool kindFirst) => Ranks(items, (a, b) => Compare(a, b, kindFirst));
/// <summary>As <see cref="Ranks(IReadOnlyList{SortItem}, bool)"/>, for any total order (the main pack's, handy items first).</summary>
public static int[] Ranks(IReadOnlyList<SortItem> items, Comparison<SortItem> order)
{
int n = items.Count;
var idx = new int[n];
for (int i = 0; i < n; i++) idx[i] = i;
Array.Sort(idx, (x, y) => Compare(items[x], items[y], kindFirst));
Array.Sort(idx, (x, y) => order(items[x], items[y]));
var rank = new int[n];
for (int r = 0; r < n; r++) rank[idx[r]] = r;
return rank;
@ -85,10 +88,13 @@ internal static class PackOrder
}
/// <summary>How many items are out of place (would move): 0 = in order.</summary>
public static int OutOfPlace(IReadOnlyList<SortItem> items, bool kindFirst)
public static int OutOfPlace(IReadOnlyList<SortItem> items, bool kindFirst) => OutOfPlace(items, (a, b) => Compare(a, b, kindFirst));
/// <summary>As <see cref="OutOfPlace(IReadOnlyList{SortItem}, bool)"/>, for any total order.</summary>
public static int OutOfPlace(IReadOnlyList<SortItem> items, Comparison<SortItem> order)
{
if (items.Count < 2) return 0;
bool[] kept = Kept(Ranks(items, kindFirst));
bool[] kept = Kept(Ranks(items, order));
int n = 0;
foreach (bool k in kept) if (!k) n++;
return n;
@ -99,13 +105,17 @@ internal static class PackOrder
/// that <paramref name="movable"/> allows, and the slot it goes to (counted without it). False
/// when the pack is in order, or only items that can't move now are out of place.
/// </summary>
public static bool NextMove(IReadOnlyList<SortItem> items, bool kindFirst, Func<SortItem, bool> movable, out SortItem item, out int placement)
public static bool NextMove(IReadOnlyList<SortItem> items, bool kindFirst, Func<SortItem, bool> movable, out SortItem item, out int placement) =>
NextMove(items, (a, b) => Compare(a, b, kindFirst), movable, out item, out placement);
/// <summary>As <see cref="NextMove(IReadOnlyList{SortItem}, bool, Func{SortItem, bool}, out SortItem, out int)"/>, for any total order.</summary>
public static bool NextMove(IReadOnlyList<SortItem> items, Comparison<SortItem> order, Func<SortItem, bool> movable, out SortItem item, out int placement)
{
item = null!;
placement = -1;
int n = items.Count;
if (n < 2) return false;
int[] rank = Ranks(items, kindFirst);
int[] rank = Ranks(items, order);
bool[] kept = Kept(rank);
int pick = -1;
for (int i = 0; i < n; i++)
@ -125,14 +135,68 @@ internal static class PackOrder
/// The slot an item arriving in a pack should take so it lands where the order wants it: after
/// every item there that comes before it. In a pack already in order that is its final place.
/// </summary>
public static int InsertAt(IReadOnlyList<SortItem> items, SortItem arriving, bool kindFirst)
public static int InsertAt(IReadOnlyList<SortItem> items, SortItem arriving, bool kindFirst) => InsertAt(items, arriving, (a, b) => Compare(a, b, kindFirst));
/// <summary>As <see cref="InsertAt(IReadOnlyList{SortItem}, SortItem, bool)"/>, for any total order.</summary>
public static int InsertAt(IReadOnlyList<SortItem> items, SortItem arriving, Comparison<SortItem> order)
{
int at = 0;
for (int i = 0; i < items.Count; i++)
if (Compare(items[i], arriving, kindFirst) < 0) at = i + 1;
if (order(items[i], arriving) < 0) at = i + 1;
return at;
}
// ── Handy items at the front of the main pack ──────────────────────────
/// <summary>The main pack's order with handy items first: handy items before the rest, each part in the usual order (<see cref="Compare"/>).</summary>
public static Comparison<SortItem> HandyFirst(Func<SortItem, bool> handy, bool kindFirst) => (a, b) =>
{
if (ReferenceEquals(a, b)) return 0;
bool ha = handy(a), hb = handy(b);
if (ha != hb) return ha ? -1 : 1;
return Compare(a, b, kindFirst);
};
/// <summary>
/// How many slots at the front are taken by handy items, or by items that can't move now (left
/// alone, blocked): those are the player's, so handy items go after them rather than push them on.
/// </summary>
public static int FrontRun(IReadOnlyList<SortItem> items, Func<SortItem, bool> handy, Func<SortItem, bool> movable)
{
int front = 0;
while (front < items.Count && (handy(items[front]) || !movable(items[front]))) front++;
return front;
}
/// <summary>
/// Handy items to the front without putting the pack in order (the "order inside packs" setting
/// off): the first handy item behind the front run that can move goes to the end of the run. The
/// other items keep their order; each move makes the run one longer, so a pack needs at most one
/// move per handy item. False when every handy item that can move is in front.
/// </summary>
public static bool FrontMove(IReadOnlyList<SortItem> items, Func<SortItem, bool> handy, Func<SortItem, bool> movable, out SortItem item, out int placement)
{
item = null!;
placement = -1;
int front = FrontRun(items, handy, movable);
for (int i = front; i < items.Count; i++)
{
if (!handy(items[i]) || !movable(items[i])) continue;
item = items[i];
placement = front;
return true;
}
return false;
}
/// <summary>Handy items that can move and aren't in front yet (0 = done).</summary>
public static int HandyBehind(IReadOnlyList<SortItem> items, Func<SortItem, bool> handy, Func<SortItem, bool> movable)
{
int front = FrontRun(items, handy, movable), n = 0;
for (int i = front; i < items.Count; i++) if (handy(items[i]) && movable(items[i])) n++;
return n;
}
/// <summary>
/// The list after moving <paramref name="item"/> to <paramref name="placement"/> as ACE does it
/// (taken out, the others close up, put in at that index, clamped to the end). For the tests'

View file

@ -19,8 +19,23 @@ internal interface ISortWorld
int ErrorSeqNow();
/// <summary>What this engine lets the planner do beyond moving items to their packs.</summary>
SortAbilities Abilities { get; }
/// <summary>
/// What RynthAi says about the items for the jobs <paramref name="wanted"/> (<see cref="PackJobs"/>):
/// the plugin asks RynthAi.Hub. Null = nothing known (the jobs' packs then stay as they are).
/// </summary>
JobAnswers? AskJobs(SortInventory inv, IReadOnlyList<JobKind> wanted, string mule, long nowMs) => null;
}
/// <summary>
/// One line of the window's activity feed: what happened, the item it was about (0 = none: a sort,
/// a setting), and the wall-clock time it happened ("14:05").
/// </summary>
internal readonly record struct FeedLine(string Text, uint ItemId, string Time);
/// <summary>An item the player sent to a pack from the window ("Just move it", "Send to"), waiting for the way to clear.</summary>
internal readonly record struct PendingSend(uint ItemId, uint DestId, long UntilMs);
/// <summary>What the engine can do for RynthSort (the plugin asks the host; the tests say).</summary>
internal struct SortAbilities
{
@ -57,6 +72,23 @@ internal sealed class SortController
public CharacterSortData Data = new();
public readonly SortPlanner Planner = new();
public readonly SortGate Gate = new();
/// <summary>What the player touched lately (left alone for <see cref="HoldMs"/>). The plugin adds the selection and drags.</summary>
public readonly TouchWatch Touch = new();
/// <summary>How long an item the player touched is left alone (the "leave items I use alone" setting; 0 = off).</summary>
public long HoldMs => Math.Max(0, Data.Settings.HoldMin) * 60_000L;
/// <summary>The packs as last read (the window's preview plans from it), or null before the first read.</summary>
public SortInventory? LastInventory { get; private set; }
/// <summary>The time of the last tick (ms).</summary>
public long Clock { get; private set; }
public SortController()
{
Planner.Held = id => Touch.IsHeld(id, Clock, HoldMs);
}
/// <summary>Whether the player touched <paramref name="itemId"/> recently enough that it is left alone.</summary>
public bool IsHeld(uint itemId) => Touch.IsHeld(itemId, Clock, HoldMs);
/// <summary>"watching", "off", "sorting", "unpacking", "paused: ..."; shown beside the auto-sort box.</summary>
public string Status { get; private set; } = "starting";
@ -69,11 +101,29 @@ internal sealed class SortController
public RynthAiActivity? LastBot { get; private set; }
/// <summary>The last few moves and job results, newest first.</summary>
public readonly List<string> Log = new();
/// <summary>The window's activity feed, newest first (<see cref="FeedMax"/> lines): <see cref="Log"/>'s lines with their times, and a few more (auto-sort on and off).</summary>
public readonly List<FeedLine> Feed = new();
public const int FeedMax = 12;
/// <summary>The wall clock the feed's times come from (the tests set it).</summary>
public Func<DateTime> WallClock = () => DateTime.Now;
/// <summary>Bumped whenever the feed changes (the window rebuilds its view then).</summary>
public int FeedVersion { get; private set; }
/// <summary>What the engine allowed at the last tick (the window says when ordering isn't possible).</summary>
public SortAbilities Abilities { get; private set; }
public int Moved { get; private set; }
public int Failed { get; private set; }
/// <summary>
/// The last sort's moves to other packs, oldest first, for "Put back": a run of moves, a new run
/// starting when a move lands more than <see cref="RunGapMs"/> after the one before. Kept
/// <see cref="HistoryKeepMs"/> at most. Joins into stacks aren't kept (the item is gone).
/// </summary>
public readonly List<MadeMove> History = new();
public const long RunGapMs = 60_000;
public const long HistoryKeepMs = 30 * 60_000;
public const int HistoryMax = 250;
private int _putBackDone, _putBackPlanned;
/// <summary>Settings changed by a command (auto-sort off for Unpack): the plugin saves.</summary>
public Action? SettingsChanged;
/// <summary>The one-time pack fix ran (<see cref="PackFix"/>): its lines and how many rules it changed. The plugin logs and saves.</summary>
@ -90,12 +140,24 @@ internal sealed class SortController
private long _fixLayoutSince;
public bool HasMoveOut => _inFlight != null;
/// <summary>The item being moved now (0 = none): the window lifts its tile.</summary>
public uint InFlightItem => _inFlight?.Move.Item.Id ?? 0;
// "Just move it" / "Send to" from the window: one item to one pack, then left alone.
private PendingSend? _send;
private bool _sendInFlight;
/// <summary>How long a send waits for the way to clear before it is dropped.</summary>
public const long SendWaitMs = 30_000;
/// <summary>An item the player sent from the window that hasn't gone yet, or null.</summary>
public PendingSend? Send => _send;
/// <summary>Forget the character (logout, another character's data).</summary>
public void Reset()
{
Planner.Reset();
Gate.Reset();
Touch.Reset();
LastInventory = null;
_inFlight = null;
_nextStepMs = _nextViewMs = 0;
_failuresInARow = 0;
@ -105,6 +167,13 @@ internal sealed class SortController
LastBot = null;
Status = "starting";
Log.Clear();
Feed.Clear();
FeedVersion++;
_send = null;
_sendInFlight = false;
History.Clear();
_noFitSaid.Clear();
_jobs = null;
Moved = Failed = 0;
}
@ -112,18 +181,57 @@ internal sealed class SortController
public void SetAuto(bool on)
{
bool was = Data.Settings.Auto;
Data.Settings.Auto = on;
if (was != on) NoteFeed(on ? "Auto-sort on" : "Auto-sort off");
SettingsChanged?.Invoke();
}
/// <summary>
/// "Just move it" / "Send to" (the window): item <paramref name="itemId"/> goes to the pack
/// <paramref name="destId"/> names (the player's id: the main pack) as soon as the way is clear, by
/// itself, and is left alone afterwards for the hold time so no sort pulls it back. No rule changes.
/// It is left alone from now on too, so auto-sort doesn't move it meanwhile. Replaces a send not
/// made yet. False for no item or no pack.
/// </summary>
public bool StartSend(uint itemId, uint destId)
{
if (itemId == 0 || destId == 0) return false;
_send = new PendingSend(itemId, destId, Clock + SendWaitMs);
Touch.Hold(itemId, Clock, TouchKind.Sent);
_nextStepMs = Math.Min(_nextStepMs, Clock);
return true;
}
/// <summary>Sort now (Main), Tidy (All) or Clean, as soon as the way is clear.</summary>
public void StartJob(SortScope scope)
{
if (scope == SortScope.Unpack) { StartUnpack(null); return; }
if (scope == SortScope.PutBack) { StartPutBack(); return; }
Job = scope;
_nextStepMs = 0;
}
/// <summary>
/// "Put back": the items the last sort moved go back where they were. Auto-sort goes off first
/// (it would move them straight back); false when there is nothing to put back.
/// </summary>
public bool StartPutBack()
{
if (History.Count == 0) return false;
Data.Settings.Auto = false;
Job = SortScope.PutBack;
UnpackWhich = null;
_putBackDone = 0;
_putBackPlanned = History.Count;
_nextStepMs = 0;
SettingsChanged?.Invoke();
return true;
}
/// <summary>How many items Put back would try to move back now.</summary>
public int PutBackCount => History.Count;
/// <summary>Empty every side pack (or pack <paramref name="which"/>) into the main pack; auto-sort goes off first so nothing moves straight back.</summary>
public void StartUnpack(int? which)
{
@ -144,25 +252,62 @@ internal sealed class SortController
{
_reorderRunCount++;
Log[0] = _reorderRunLine = $"{_reorderRunCount} items put in order in {m.DestLabel}";
if (Feed.Count > 0)
{
Feed[0] = Feed[0] with { Text = $"{_reorderRunCount} items put in order in {PackLabel(m.DestIndex)}", ItemId = 0 };
FeedVersion++;
}
return;
}
_reorderRunPack = m.DestIndex;
_reorderRunCount = 1;
string name = m.Item.Name.Length > 0 ? m.Item.Name : $"0x{m.Item.Id:X8}";
Note($"{name} {m.Done}");
Note($"{name} {m.Done}", 0, $"{name} {FeedDone(m)}");
_reorderRunLine = Log[0];
}
public void Note(string line)
/// <summary>
/// A line for the log (/rsort status, the older window) and the window's feed. The feed can say
/// it in other words (<paramref name="feed"/>: pack names instead of numbers); null = the same line.
/// </summary>
public void Note(string line, uint itemId = 0, string? feed = null)
{
Log.Insert(0, line);
while (Log.Count > LogLines) Log.RemoveAt(Log.Count - 1);
NoteFeed(feed ?? line, itemId);
}
/// <summary>What the feed calls pack <paramref name="index"/> (0 = main pack): its name, with its number when two share it (<see cref="PackNames"/>).</summary>
internal string PackLabel(int index) => PackNames.Label(LastInventory, index);
/// <summary>"-> Satchel", "stacked in Satchel", "put in order in main pack": <see cref="SortMove.Done"/> with the pack's name.</summary>
internal string FeedDone(in SortMove m)
{
string where = PackLabel(m.DestIndex);
return m.Kind switch
{
MoveKind.Stack => "stacked in " + where,
MoveKind.Reorder => "put in order in " + where,
_ => "-> " + where,
};
}
/// <summary>A line for the window's feed only (not <see cref="Log"/>, which /rsort status and the old window show).</summary>
public void NoteFeed(string text, uint itemId = 0)
{
string time;
try { time = WallClock().ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture); }
catch { time = string.Empty; }
Feed.Insert(0, new FeedLine(text, itemId, time));
while (Feed.Count > FeedMax) Feed.RemoveAt(Feed.Count - 1);
FeedVersion++;
}
// ── The loop ────────────────────────────────────────────────────────────
public void Tick(ISortWorld world, long nowMs)
{
Clock = nowMs;
Abilities = world.Abilities;
if (_inFlight != null)
{
@ -174,6 +319,7 @@ internal sealed class SortController
return;
}
if (nowMs < _nextStepMs) return;
if (_send != null && TickSend(world, nowMs)) return;
SortScope? scope = Job ?? (Data.Settings.Auto ? SortScope.All : null);
if (scope == null)
@ -191,7 +337,7 @@ internal sealed class SortController
if (why != null)
{
Status = "paused: " + why;
RefreshView(world, scope == SortScope.Unpack ? SortScope.Main : scope.Value, nowMs);
RefreshView(world, scope is SortScope.Unpack or SortScope.PutBack ? SortScope.Main : scope.Value, nowMs);
_nextStepMs = nowMs + PollMs;
return;
}
@ -203,6 +349,7 @@ internal sealed class SortController
_nextStepMs = nowMs + ViewMs;
return;
}
Seen(inv, nowMs, world);
_nextViewMs = nowMs + ViewMs;
if (!AfterRead(inv, nowMs))
{
@ -212,13 +359,18 @@ internal sealed class SortController
_nextStepMs = nowMs + PollMs;
return;
}
List<SortMove> moves = scope == SortScope.Unpack
? Planner.PlanUnpack(inv, UnpackWhich, nowMs)
: Planner.Plan(inv, Data.Rules, scope.Value, force: Job != null, nowMs, Data.Settings.SettleSec * 1000, Options(world));
List<SortMove> moves = scope switch
{
SortScope.Unpack => Planner.PlanUnpack(inv, UnpackWhich, nowMs),
SortScope.PutBack => Planner.PlanPutBack(inv, History, nowMs),
_ => Planner.Plan(inv, Data.Rules, scope.Value, force: Job != null, nowMs, Data.Settings.SettleSec * 1000, Options(world)),
};
NoteNoFit(jobDone: moves.Count == 0 && Job != null);
if (moves.Count == 0)
{
if (Job != null) NoteJobDone(Job.Value);
if (Job == SortScope.PutBack) History.Clear(); // what couldn't go back is gone or was moved since
Job = null;
UnpackWhich = null;
Status = Data.Settings.Auto ? "watching" : "off";
@ -226,10 +378,11 @@ internal sealed class SortController
return;
}
Status = scope == SortScope.Unpack ? "unpacking" : "sorting";
Status = scope switch { SortScope.Unpack => "unpacking", SortScope.PutBack => "putting back", _ => "sorting" };
SortMove m = moves[0];
int seq = world.ErrorSeqNow();
int stack = m.Item.Stack; // as read before the send (a merge's answer is a smaller stack)
Touch.NoteOwnMove(m.Item.Id, m.Dest.Id, nowMs);
if (!world.SendMove(in m))
{
Finish(m, MoveOutcome.Refused, nowMs, "the engine refused the move");
@ -238,24 +391,168 @@ internal sealed class SortController
_inFlight = new MoveInFlight { Move = m, SentMs = nowMs, ErrorSeqAtSend = seq, StackAtSend = stack };
}
/// <summary>What the planner may do: the engine's abilities and the settings.</summary>
internal PlanOptions Options(ISortWorld world)
/// <summary>
/// The window's send (<see cref="StartSend"/>), before anything else: through the same gate as a
/// sort, one plain move, then the item is held. True when this tick is used up by it.
/// </summary>
private bool TickSend(ISortWorld world, long nowMs)
{
PendingSend send = _send!.Value;
if (nowMs > send.UntilMs)
{
_send = null;
Note("A move you asked for was dropped: the way didn't clear in time", send.ItemId);
return false;
}
GateInputs g = world.ReadGate(Data.Settings.SortInCombat, nowMs);
LastBot = g.Bot;
string? why = Gate.Evaluate(in g, nowMs);
if (why != null)
{
Status = "paused: " + why;
_nextStepMs = nowMs + PollMs;
return true;
}
SortInventory? inv = world.ReadInventory();
if (inv == null)
{
Status = "waiting for the inventory";
_nextStepMs = nowMs + PollMs;
return true;
}
Seen(inv, nowMs, world);
_send = null;
SortItem? item = null;
int from = -1;
foreach (SortItem it in inv.Main.Items) if (it.Id == send.ItemId) { item = it; from = 0; break; }
for (int i = 0; item == null && i < inv.Packs.Count; i++)
foreach (SortItem it in inv.Packs[i].Items) if (it.Id == send.ItemId) { item = it; from = i + 1; break; }
int to = send.DestId == inv.Main.Id ? 0 : inv.IndexOf(send.DestId);
if (item == null || !SortPlanner.Sortable(item))
{
Note("A move you asked for was dropped: the item isn't in your packs now", send.ItemId);
return false;
}
string name = item.Name.Length > 0 ? item.Name : $"0x{item.Id:X8}";
if (to == 0 && send.DestId != inv.Main.Id)
{
Note($"{name}: not moved (that pack isn't carried now)", item.Id);
return false;
}
Touch.Hold(item.Id, nowMs, TouchKind.Sent);
if (to == from) return false; // there already: just left alone
SortPack dest = to == 0 ? inv.Main : inv.Packs[to - 1];
int cap = SortPlanner.CapacityOf(dest, to == 0 ? SortPlanner.MainCapacityFallback : SortPlanner.SideCapacityFallback);
if (dest.Items.Count >= cap)
{
Note($"{name}: not moved ({(to == 0 ? "the main pack" : PackLabel(to))} is full)", item.Id);
return false;
}
var m = new SortMove(item, dest, to, 0, -1, MoveKind.Route, from == 0 ? inv.Main.Id : inv.Packs[from - 1].Id, from);
Status = "sorting";
int seq = world.ErrorSeqNow();
Touch.NoteOwnMove(item.Id, dest.Id, nowMs);
_sendInFlight = true;
if (!world.SendMove(in m))
{
Finish(m, MoveOutcome.Refused, nowMs, "the engine refused the move");
return true;
}
_inFlight = new MoveInFlight { Move = m, SentMs = nowMs, ErrorSeqAtSend = seq, StackAtSend = item.Stack };
return true;
}
/// <summary>What the planner may do: the engine's abilities and the settings.</summary>
internal PlanOptions Options(ISortWorld world) => OptionsFor(world.Abilities);
/// <summary>What the planner may do with the engine as it was at the last tick (the window's preview).</summary>
internal PlanOptions CurrentOptions => OptionsFor(Abilities);
private PlanOptions OptionsFor(SortAbilities a)
{
SortAbilities a = world.Abilities;
return new PlanOptions
{
Order = a.ReadOrder && a.PlaceMoves && Data.Settings.OrderInPacks,
KindFirst = Data.Settings.OrderKindFirst,
Place = a.ReadOrder && a.PlaceMoves,
Merge = a.Merge,
Handy = a.ReadOrder && a.PlaceMoves ? HandyItems.For(Data.Settings) : null,
Jobs = _jobs,
};
}
/// <summary>A chat line (the plugin writes it, with RynthSort's tag): what didn't fit. Null in the tests that don't look.</summary>
public Action<string>? Warn;
// The items the last "didn't fit" line named: a line goes out when one not named yet doesn't fit.
private readonly HashSet<uint> _noFitSaid = new();
/// <summary>
/// Items whose pack (and every overflow pack) is full: one chat line and a feed line per sort,
/// not per tick. Auto-sort says it when an item that wasn't named yet doesn't fit; a job (Sort now,
/// Clean) says it once, when it ends. An item that fits again is forgotten, so it is named again
/// if it stops fitting later.
/// </summary>
private void NoteNoFit(bool jobDone)
{
List<NoFitLine> nf = Planner.View.NoFit;
if (nf.Count == 0) { _noFitSaid.Clear(); return; }
var ids = new HashSet<uint>();
foreach (NoFitLine l in nf) ids.Add(l.Item.Id);
_noFitSaid.RemoveWhere(id => !ids.Contains(id));
if (Job != null && !jobDone) return;
bool fresh = false;
foreach (uint id in ids) if (!_noFitSaid.Contains(id)) { fresh = true; break; }
if (!fresh && !jobDone) return;
foreach (uint id in ids) _noFitSaid.Add(id);
string text = NoFitText(nf, LastInventory);
NoteFeed(text);
Warn?.Invoke(text);
}
/// <summary>
/// "Satchel is full: Black Opal, Fire Opal and 2 more stay where they are." One sentence per
/// full pack, the pack by name (<see cref="PackNames"/>), at most three item names each.
/// </summary>
internal static string NoFitText(IReadOnlyList<NoFitLine> nf, SortInventory? inv)
{
var packs = new List<int>();
foreach (NoFitLine l in nf) if (!packs.Contains(l.Pack)) packs.Add(l.Pack);
var sb = new System.Text.StringBuilder();
foreach (int pack in packs)
{
var names = new List<string>();
int count = 0;
foreach (NoFitLine l in nf)
{
if (l.Pack != pack) continue;
count++;
string n = l.Item.Name.Length > 0 ? l.Item.Name : $"0x{l.Item.Id:X8}";
if (names.Count < 3 && !names.Contains(n)) names.Add(n);
}
int more = count - names.Count;
string list = more > 0 ? string.Join(", ", names) + $" and {more} more"
: names.Count > 1 ? string.Join(", ", names.GetRange(0, names.Count - 1)) + " and " + names[^1] : names[0];
if (sb.Length > 0) sb.Append(' ');
string label = PackNames.Label(inv, pack);
sb.Append(char.ToUpperInvariant(label[0])).Append(label, 1, label.Length - 1)
.Append(" is full: ").Append(list).Append(count == 1 ? " stays where it is." : " stay where they are.");
}
return sb.ToString();
}
private void NoteJobDone(SortScope job)
{
SortView v = Planner.View;
switch (job)
{
case SortScope.PutBack:
{
int left = _putBackPlanned - _putBackDone;
Note(_putBackDone == 0 ? "Nothing could be put back (gone, or moved since)"
: left > 0 ? $"Put back {_putBackDone} items ({left} gone, moved since, or no room)" : $"Put back {_putBackDone} items");
break;
}
case SortScope.Unpack: Note(v.MainFull ? "Main pack is full: unpacking stopped" : "Side packs emptied"); break;
case SortScope.Clean: Note(v.MainFull ? "Main pack is full: some strays left" : "Packs cleaned"); break;
case SortScope.All: Note(v.Waiting > 0 ? $"Packs sorted ({v.Waiting} can't move yet)" : "Packs sorted"); break;
@ -266,12 +563,24 @@ internal sealed class SortController
private void Finish(SortMove m, MoveOutcome outcome, long nowMs, string? why = null)
{
string name = m.Item.Name.Length > 0 ? m.Item.Name : $"0x{m.Item.Id:X8}";
long gap = Job != null ? JobGapMs : Data.Settings.GapMs;
bool sent = _sendInFlight;
_sendInFlight = false;
long gap = Job != null || sent ? JobGapMs : Data.Settings.GapMs;
switch (outcome)
{
case MoveOutcome.Done when sent:
// The player's own move from the window: not a sort (Put back leaves it), and left alone from now.
Moved++;
_failuresInARow = 0;
Touch.Hold(m.Item.Id, nowMs, TouchKind.Sent);
_reorderRunLine = null;
Note($"{name} {m.Done} (you sent it)", m.Item.Id, $"{name} {FeedDone(m)} (you sent it)");
_nextStepMs = nowMs + gap;
return;
case MoveOutcome.Done:
Moved++;
_failuresInARow = 0;
Remember(m, nowMs);
if (m.Kind == MoveKind.Reorder)
{
Planner.NoteReorder(m.Item.Id, nowMs);
@ -280,14 +589,14 @@ internal sealed class SortController
else
{
_reorderRunLine = null;
Note($"{name} {m.Done}");
Note($"{name} {m.Done}", m.Item.Id, $"{name} {FeedDone(m)}");
}
_nextStepMs = nowMs + gap;
return;
case MoveOutcome.TooBusy:
// Not the item's fault: no block, just a longer hold.
_failuresInARow++;
Note($"{name}: the server is busy, trying again");
Note($"{name}: the server is busy, trying again", m.Item.Id);
_nextStepMs = nowMs + Math.Max(gap, MoveTracker.BackoffMs(_failuresInARow));
return;
default:
@ -295,7 +604,7 @@ internal sealed class SortController
_failuresInARow++;
Planner.Block(m.Item.Id, nowMs + MoveTracker.BlockMs);
why ??= outcome == MoveOutcome.TimedOut ? "no answer from the server" : "the server refused it";
Note($"{name}: not moved ({why})");
Note($"{name}: not moved ({why})", m.Item.Id);
_nextStepMs = nowMs + Math.Max(gap, MoveTracker.BackoffMs(_failuresInARow));
return;
}
@ -327,6 +636,63 @@ internal sealed class SortController
return true;
}
/// <summary>A move landed: kept for Put back (a move Put back made takes its item off the list instead).</summary>
private void Remember(in SortMove m, long nowMs)
{
if (m.Kind != MoveKind.Route || m.FromId == 0) return;
if (Job == SortScope.PutBack)
{
uint id = m.Item.Id;
if (History.RemoveAll(h => h.ItemId == id) > 0) _putBackDone++;
return;
}
if (m.MergeInto != 0) return; // joined a stack: nothing to put back
if (History.Count > 0 && nowMs - History[^1].AtMs > RunGapMs) History.Clear(); // a new sort
// Moved twice in one sort: the first place is where it goes back to.
uint from = m.FromId;
uint itemId = m.Item.Id;
int earlier = History.FindIndex(h => h.ItemId == itemId);
if (earlier >= 0)
{
from = History[earlier].FromId;
History.RemoveAt(earlier);
}
if (from == m.Dest.Id) return; // back where it started
History.Add(new MadeMove(itemId, m.Item.Name, from, m.Dest.Id, nowMs));
while (History.Count > HistoryMax) History.RemoveAt(0);
}
/// <summary>Old moves fall off the Put back list.</summary>
private void ForgetOldMoves(long nowMs)
{
if (Job == SortScope.PutBack) return;
while (History.Count > 0 && nowMs - History[0].AtMs > HistoryKeepMs) History.RemoveAt(0);
}
/// <summary>
/// Every read: what the player moved since the last one, the packs for the window's preview, and
/// RynthAi's answers for the jobs the carried packs have (<see cref="PackJobs"/>).
/// </summary>
private void Seen(SortInventory inv, long nowMs, ISortWorld world)
{
Touch.Observe(inv, nowMs);
LastInventory = inv;
ForgetOldMoves(nowMs);
List<JobKind> wanted = PackJobs.Wanted(Data.Jobs, inv, out string mule);
JobAnswers? answers = null;
if (wanted.Count > 0)
{
try { answers = world.AskJobs(inv, wanted, mule, nowMs); }
catch { answers = null; } // RynthAi mid-reload: nothing known this time
}
_jobs = JobPlan.For(Data.Jobs, inv, answers);
}
private JobPlan? _jobs;
/// <summary>The carried packs' jobs and what RynthAi answered at the last read (null: no pack has a job).</summary>
public JobPlan? Jobs => _jobs;
/// <summary>Re-reads the packs for the window now and then while nothing moves.</summary>
private void RefreshView(ISortWorld world, SortScope scope, long nowMs)
{
@ -334,6 +700,7 @@ internal sealed class SortController
_nextViewMs = nowMs + ViewMs;
SortInventory? inv = world.ReadInventory();
if (inv == null) return;
Seen(inv, nowMs, world);
AfterRead(inv, nowMs);
if (scope == SortScope.Unpack) Planner.PlanUnpack(inv, UnpackWhich, nowMs);
else Planner.Plan(inv, Data.Rules, scope, force: false, nowMs, Data.Settings.SettleSec * 1000, Options(world));

View file

@ -155,6 +155,8 @@ internal sealed class SortInventory
/// fix of imported Lua pack numbers (<see cref="PackFix"/>) reads the Lua numbers through it.
/// </summary>
public readonly List<SortSlot> Slots = new();
/// <summary>Worn and wielded things (never sorted): an item that was here and is now in a pack was taken off by the player.</summary>
public readonly HashSet<uint> Worn = new();
/// <summary><see cref="Packs"/> are in the pack column's order, top first.</summary>
public bool PackOrderKnown;
/// <summary>Why the packs are numbered the way they are.</summary>

View file

@ -18,8 +18,13 @@ internal enum SortScope
Clean,
/// <summary>Every side pack (or one) emptied into the main pack ("Unpack").</summary>
Unpack,
/// <summary>The items the last sort moved go back to the packs they came from ("Put back").</summary>
PutBack,
}
/// <summary>A move RynthSort made (an item to another pack), kept so "Put back" can undo it.</summary>
internal readonly record struct MadeMove(uint ItemId, string Name, uint FromId, uint ToId, long AtMs);
/// <summary>What a move does.</summary>
internal enum MoveKind : byte
{
@ -42,8 +47,13 @@ internal readonly struct SortMove
/// <summary>The slot in <see cref="Dest"/> it should end at (counted without it), or -1: the first empty slot.</summary>
public readonly int Placement;
public readonly MoveKind Kind;
/// <summary>The pack the item is in before the move (its object id; the player for the main pack), 0 when not known. "Put back" uses it.</summary>
public readonly uint FromId;
/// <summary>The pack it is in before the move: 0 = main pack, else the side pack's number (1-based); -1 when not known.</summary>
public readonly int FromIndex;
public SortMove(SortItem item, SortPack dest, int destIndex, uint mergeInto, int placement = -1, MoveKind kind = MoveKind.Route)
public SortMove(SortItem item, SortPack dest, int destIndex, uint mergeInto, int placement = -1, MoveKind kind = MoveKind.Route,
uint fromId = 0, int fromIndex = -1)
{
Item = item;
Dest = dest;
@ -51,6 +61,8 @@ internal readonly struct SortMove
MergeInto = mergeInto;
Placement = placement;
Kind = kind;
FromId = fromId;
FromIndex = fromIndex;
}
/// <summary>The item is already in <see cref="Dest"/> (a stack joined or a slot changed there).</summary>
@ -78,6 +90,13 @@ internal struct PlanOptions
public bool Place;
/// <summary>Stacks of the same kind in one pack are joined (the engine can merge stacks).</summary>
public bool Merge;
/// <summary>
/// Handy items (<see cref="HandyItems"/>) are kept in the main pack's first slots: null = off.
/// Only with <see cref="Place"/> (moves to a slot) and the main pack's slot order known.
/// </summary>
public Func<SortItem, bool>? Handy;
/// <summary>The carried packs' jobs and RynthAi's answers (<see cref="PackJobs"/>): null = no pack has a job.</summary>
public JobPlan? Jobs;
/// <summary>Everything on: an engine with API v80 and the default settings.</summary>
public static PlanOptions Full => new() { Order = true, Place = true, Merge = true };
@ -139,8 +158,39 @@ internal sealed class SortView
public readonly List<RulePackIssue> Issues = new();
/// <summary>Clean or Unpack found the main pack full.</summary>
public bool MainFull;
/// <summary>
/// Items a rule wants in a side pack that is full, with no overflow pack (another pack with the
/// same rule) that has room: they stay where they are. In the order met, main pack first.
/// </summary>
public readonly List<NoFitLine> NoFit = new();
/// <summary>Handy items are kept at the front of the main pack (the option is on and the engine can do it).</summary>
public bool Handy;
/// <summary>Handy items that could move and aren't in the main pack's front slots yet.</summary>
public int HandyBehind;
// Why items wait (they add up to Waiting).
/// <summary>New items in the main pack still inside the settle time.</summary>
public int WaitSettle;
/// <summary>Items whose pack is full.</summary>
public int WaitFull;
/// <summary>Items whose rule's pack isn't carried.</summary>
public int WaitNoPack;
/// <summary>Items Clean or Unpack can't put in the full main pack.</summary>
public int WaitMainFull;
/// <summary>How long until the next settling item may move (ms), or -1 when none is settling.</summary>
public long NextSettleMs = -1;
/// <summary>The new main-pack items counted in <see cref="WaitSettle"/> (their ids): the window's settling rings.</summary>
public readonly HashSet<uint> Settling = new();
/// <summary>Items a rule (or Clean) would move that the player touched lately: left where they are.</summary>
public readonly List<HeldLine> Held = new();
}
/// <summary>An item left alone because the player touched it lately: in pack <see cref="From"/>, it would go to <see cref="To"/> (0 = main pack).</summary>
internal readonly record struct HeldLine(SortItem Item, int From, int To);
/// <summary>An item that didn't fit: its rule's side pack <see cref="Pack"/> (and every overflow pack) is full; it stays in <see cref="From"/> (0 = main pack).</summary>
internal readonly record struct NoFitLine(SortItem Item, int Pack, int From);
/// <summary>
/// The sorting rules applied to the packs: which items move where, one planning pass at a time.
/// Each item has one place: the pack of the rule it follows (<see cref="SortRules.RuleFor"/>; the
@ -174,6 +224,15 @@ internal sealed class SortPlanner
public SortView View { get; private set; } = new();
/// <summary>
/// Items the player touched lately (<see cref="TouchWatch"/>): they don't move, stacks don't
/// join into them and they aren't put in order (other items still are, around them). Unpack
/// and Put back ignore it (the player asked to move everything). Null = nothing held.
/// </summary>
public Func<uint, bool>? Held;
private bool IsHeld(SortItem it) => Held != null && Held(it.Id);
/// <summary>Forget everything (logout, another character).</summary>
public void Reset()
{
@ -216,12 +275,12 @@ internal sealed class SortPlanner
/// A stack in <paramref name="pack"/> that <paramref name="it"/> can join (the same kind, with room
/// left), or 0. That is what lets a full pack still take the item.
/// </summary>
public static uint StackTarget(SortItem it, SortPack pack)
public static uint StackTarget(SortItem it, SortPack pack, Func<uint, bool>? skip = null)
{
if (it.MaxStack <= 1) return 0;
foreach (SortItem other in pack.Items)
{
if (other.Id == it.Id || !SameKind(it, other)) continue;
if (other.Id == it.Id || !SameKind(it, other) || (skip != null && skip(other.Id))) continue;
int max = other.MaxStack > 1 ? other.MaxStack : it.MaxStack;
if (other.Stack < max) return other.Id;
}
@ -239,25 +298,27 @@ internal sealed class SortPlanner
/// the pack's order; the same answer for the same pack. False when every kind has at most one
/// stack with room.
/// </summary>
public static bool StackJoin(SortPack pack, Func<SortItem, bool> movable, out SortItem from, out SortItem into)
public static bool StackJoin(SortPack pack, Func<SortItem, bool> movable, out SortItem from, out SortItem into, Func<SortItem, bool>? joinable = null)
{
from = into = null!;
List<SortItem> items = pack.Items;
var seen = new bool[items.Count];
// A stack that may take part at all (joinable: not one the player is holding).
bool Part(SortItem it) => HasRoom(it) && Sortable(it) && (joinable == null || joinable(it));
for (int i = 0; i < items.Count; i++)
{
if (seen[i] || !HasRoom(items[i]) || !Sortable(items[i])) continue;
if (seen[i] || !Part(items[i])) continue;
SortItem? small = null, big = null;
for (int j = i; j < items.Count; j++)
{
SortItem it = items[j];
if (j > i && (seen[j] || !HasRoom(it) || !Sortable(it) || !SameKind(items[i], it))) continue;
if (j > i && (seen[j] || !Part(it) || !SameKind(items[i], it))) continue;
seen[j] = true;
if (big == null || it.Stack > big.Stack || (it.Stack == big.Stack && it.Id < big.Id)) big = it;
}
foreach (SortItem it in items)
{
if (ReferenceEquals(it, big) || !HasRoom(it) || !Sortable(it) || !SameKind(items[i], it) || !movable(it)) continue;
if (ReferenceEquals(it, big) || !Part(it) || !SameKind(items[i], it) || !movable(it)) continue;
if (small == null || it.Stack < small.Stack || (it.Stack == small.Stack && it.Id > small.Id)) small = it;
}
if (small != null && big != null) { from = small; into = big; return true; }
@ -288,27 +349,99 @@ internal sealed class SortPlanner
int mainUsed = inv.Main.Items.Count;
int mainCap = CapacityOf(inv.Main, MainCapacityFallback);
bool kindFirst = opt.KindFirst;
Func<SortItem, bool>? handy = opt.Place ? opt.Handy : null;
Comparison<SortItem>? mainOrder = handy != null ? PackOrder.HandyFirst(handy, kindFirst) : null;
bool MovableNow(SortItem it) => Sortable(it) && !IsBlocked(it.Id, nowMs) && !IsHeld(it);
int PlaceIn(SortPack dest, SortItem wo, uint joins) =>
opt.Place && joins == 0 && dest.OrderKnown ? PackOrder.InsertAt(dest.Items, wo, kindFirst) : -1;
int PlaceIn(SortPack dest, SortItem wo, uint joins)
{
if (!opt.Place || joins != 0 || !dest.OrderKnown) return -1;
if (handy != null && ReferenceEquals(dest, inv.Main))
{
// Into the main pack with handy items kept in front: in order (handy first), or a
// handy item at the end of the handy run and anything else at the end.
if (opt.Order) return PackOrder.InsertAt(dest.Items, wo, mainOrder!);
return handy(wo) ? PackOrder.FrontRun(dest.Items, handy, MovableNow) : -1;
}
return PackOrder.InsertAt(dest.Items, wo, kindFirst);
}
void Consider(SortItem wo, int from, bool settled)
uint PackIdOf(int index) => index == 0 ? inv.Main.Id : inv.Packs[index - 1].Id;
// The next pack with the same rule as the item's (another rule that is on and matches it, in
// the order RuleFor ranks them) when the first one's pack (first) is full: one with room, or a
// stack the item can join; the pack it is in already when that is one of them (it stays). 0 = none.
int Overflow(SortItem wo, int first, int from, out uint into)
{
into = 0;
foreach (SortRule other in SortRules.RulesFor(rules, wo))
{
int n = SortRules.Resolve(other, inv, out _);
if (n == 0 || n == first) continue;
if (n == from) return n;
SortPack p = inv.Packs[n - 1];
uint join = StackTarget(wo, p, Held);
if (used[n] < CapacityOf(p, SideCapacityFallback) || join != 0) { into = join; return n; }
}
return 0;
}
void Consider(SortItem wo, int from, bool settled, long settleLeftMs)
{
if (!Sortable(wo) || IsBlocked(wo.Id, nowMs)) return;
bool held = IsHeld(wo);
SortRule? r = SortRules.RuleFor(rules, wo);
JobPlan? jobs = opt.Jobs;
if (jobs != null && (r == null || !SortRules.MatchesName(r, wo)))
{
// A name rule first (the player named it), then a pack whose job picks it, then a kind rule.
if (jobs.Frozen(from)) return; // its pack's job can't be told now (RynthAi): it stays
int firstJob = 0, jobTo = 0;
uint jobInto = 0;
foreach (int n in jobs.PacksFor(wo))
{
if (n == from) return; // in a pack whose job takes it already
if (firstJob == 0) firstJob = n;
if (jobTo != 0) continue;
SortPack jp = inv.Packs[n - 1];
uint join = StackTarget(wo, jp, Held);
if (used[n] < CapacityOf(jp, SideCapacityFallback) || join != 0) { jobTo = n; jobInto = join; }
}
if (firstJob != 0)
{
if (held) { view.Held.Add(new HeldLine(wo, from, firstJob)); return; }
if (jobTo == 0)
{
view.Full.Add(firstJob);
view.Waiting++;
view.WaitFull++;
view.NoFit.Add(new NoFitLine(wo, firstJob, from));
return;
}
if (jobTo != firstJob) view.Full.Add(firstJob);
Go(wo, from, jobTo, jobInto, settled, settleLeftMs);
return;
}
}
if (r == null && evict && from > 0)
{
// In a side pack and no rule wants it: back to the main pack, while there is room.
uint joins = StackTarget(wo, inv.Main);
if (held)
{
view.Held.Add(new HeldLine(wo, from, 0));
return;
}
uint joins = StackTarget(wo, inv.Main, Held);
if (mainUsed < mainCap || joins != 0)
{
moves.Add(new SortMove(wo, inv.Main, 0, joins, PlaceIn(inv.Main, wo, joins)));
moves.Add(new SortMove(wo, inv.Main, 0, joins, PlaceIn(inv.Main, wo, joins), MoveKind.Route, PackIdOf(from), from));
if (joins == 0) mainUsed++;
}
else
{
view.MainFull = true;
view.Waiting++;
view.WaitMainFull++;
}
return;
}
@ -317,23 +450,49 @@ internal sealed class SortPlanner
if (to == 0)
{
view.Waiting++; // reported once per rule below (Issues / Missing)
view.WaitNoPack++;
return;
}
if (to == from) return;
SortPack dest = inv.Packs[to - 1];
uint into = StackTarget(wo, dest);
if (used[to] >= CapacityOf(dest, SideCapacityFallback) && into == 0)
if (held)
{
view.Full.Add(to);
view.Waiting++;
view.Held.Add(new HeldLine(wo, from, to));
return;
}
SortPack dest = inv.Packs[to - 1];
uint into = StackTarget(wo, dest, Held);
if (used[to] >= CapacityOf(dest, SideCapacityFallback) && into == 0)
{
// Its pack is full: the next pack with the same rule (an overflow pack) that has room,
// else it waits where it is and the window and chat say what didn't fit.
view.Full.Add(to);
int first = to;
to = Overflow(wo, first, from, out into);
if (to == from && to != 0) return; // in an overflow pack already: it stays there
if (to == 0)
{
view.Waiting++;
view.WaitFull++;
view.NoFit.Add(new NoFitLine(wo, first, from));
return;
}
}
Go(wo, from, to, into, settled, settleLeftMs);
}
// The item goes to side pack `to` (joining stack `into`), once it has settled.
void Go(SortItem wo, int from, int to, uint into, bool settled, long settleLeftMs)
{
if (!settled)
{
view.Waiting++;
view.WaitSettle++;
view.Settling.Add(wo.Id);
if (view.NextSettleMs < 0 || settleLeftMs < view.NextSettleMs) view.NextSettleMs = Math.Max(0, settleLeftMs);
return;
}
moves.Add(new SortMove(wo, dest, to, into, PlaceIn(dest, wo, into)));
SortPack dest = inv.Packs[to - 1];
moves.Add(new SortMove(wo, dest, to, into, PlaceIn(dest, wo, into), MoveKind.Route, PackIdOf(from), from));
if (into == 0) used[to]++;
}
@ -345,7 +504,7 @@ internal sealed class SortPlanner
if (!_firstSeen.TryGetValue(wo.Id, out long seen)) _firstSeen[wo.Id] = seen = nowMs;
bool settled = force || nowMs - seen >= settleMs;
if (!settled) mainSettled = false;
Consider(wo, 0, settled);
Consider(wo, 0, settled, settleMs - (nowMs - seen));
}
if (_firstSeen.Count > inMain.Count)
{
@ -356,7 +515,7 @@ internal sealed class SortPlanner
if (everyPack)
{
for (int i = 0; i < inv.Packs.Count; i++)
foreach (SortItem wo in inv.Packs[i].Items) Consider(wo, i + 1, true);
foreach (SortItem wo in inv.Packs[i].Items) Consider(wo, i + 1, true, 0);
}
bool ordering = inPack && opt.Order;
@ -364,7 +523,8 @@ internal sealed class SortPlanner
{
// Nothing changes packs: tidy each pack in place. Side packs first, then the main pack
// once nothing in it is new (loot still settling there would be ordered twice).
bool Movable(SortItem it) => Sortable(it) && !IsBlocked(it.Id, nowMs);
bool Movable(SortItem it) => Sortable(it) && !IsBlocked(it.Id, nowMs) && !IsHeld(it);
bool Joinable(SortItem it) => !IsHeld(it);
var stacks = new List<SortMove>();
var reorders = new List<SortMove>();
for (int i = 0; i <= inv.Packs.Count; i++)
@ -373,20 +533,29 @@ internal sealed class SortPlanner
if (main && !mainSettled) break;
SortPack pack = main ? inv.Main : inv.Packs[i];
int index = main ? 0 : i + 1;
if (opt.Merge && StackJoin(pack, Movable, out SortItem from, out SortItem into))
if (opt.Merge && StackJoin(pack, Movable, out SortItem from, out SortItem into, Joinable))
{
stacks.Add(new SortMove(from, pack, index, into.Id, -1, MoveKind.Stack));
stacks.Add(new SortMove(from, pack, index, into.Id, -1, MoveKind.Stack, pack.Id, index));
continue;
}
bool Reorderable(SortItem it) => Movable(it) && !ReorderLimited(it.Id, nowMs);
if (main && handy != null && pack.OrderKnown)
{
// Handy items at the front: in order with them first, or (ordering off) only them moved.
if (ordering ? PackOrder.AllNamed(pack.Items) && PackOrder.NextMove(pack.Items, mainOrder!, Reorderable, out SortItem hi, out int hat)
: PackOrder.FrontMove(pack.Items, handy, Reorderable, out hi, out hat))
reorders.Add(new SortMove(hi, pack, index, 0, hat, MoveKind.Reorder, pack.Id, index));
continue;
}
if (ordering && pack.OrderKnown && PackOrder.AllNamed(pack.Items)
&& PackOrder.NextMove(pack.Items, kindFirst, it => Movable(it) && !ReorderLimited(it.Id, nowMs), out SortItem item, out int at))
reorders.Add(new SortMove(item, pack, index, 0, at, MoveKind.Reorder));
&& PackOrder.NextMove(pack.Items, kindFirst, Reorderable, out SortItem item, out int at))
reorders.Add(new SortMove(item, pack, index, 0, at, MoveKind.Reorder, pack.Id, index));
}
moves.AddRange(stacks);
moves.AddRange(reorders);
}
FillPacks(view, inv, ordering, kindFirst);
FillPacks(view, inv, ordering, kindFirst, handy, MovableNow);
FillIssues(view, inv, rules);
View = view;
return moves;
@ -411,13 +580,63 @@ internal sealed class SortPlanner
uint joins = StackTarget(wo, inv.Main);
if (used < cap || joins != 0)
{
moves.Add(new SortMove(wo, inv.Main, 0, joins));
moves.Add(new SortMove(wo, inv.Main, 0, joins, -1, MoveKind.Route, inv.Packs[i].Id, i + 1));
if (joins == 0) used++;
}
else waiting++;
}
}
var view = new SortView { Waiting = waiting, MainFull = waiting > 0 };
var view = new SortView { Waiting = waiting, WaitMainFull = waiting, MainFull = waiting > 0 };
FillPacks(view, inv, false, false);
View = view;
return moves;
}
/// <summary>
/// Putting back what the last sort moved (<paramref name="made"/>, oldest first): newest first,
/// each item still in the pack it was sent to goes back to the pack it came from, while that pack
/// is carried and has room. An item gone (sold, joined into a stack) or moved since is skipped.
/// Never joins stacks (it was a stack of its own), never holds (the player asked).
/// </summary>
public List<SortMove> PlanPutBack(SortInventory inv, IReadOnlyList<MadeMove> made, long nowMs)
{
var moves = new List<SortMove>();
var used = new int[inv.Packs.Count + 1];
used[0] = inv.Main.Items.Count;
for (int i = 0; i < inv.Packs.Count; i++) used[i + 1] = inv.Packs[i].Items.Count;
var where = new Dictionary<uint, (SortItem Item, int Index)>();
foreach (SortItem it in inv.Main.Items) where[it.Id] = (it, 0);
for (int i = 0; i < inv.Packs.Count; i++)
foreach (SortItem it in inv.Packs[i].Items) where[it.Id] = (it, i + 1);
var view = new SortView();
var taken = new HashSet<uint>();
for (int k = made.Count - 1; k >= 0; k--)
{
MadeMove m = made[k];
if (!taken.Add(m.ItemId)) continue; // only its latest move counts
if (!where.TryGetValue(m.ItemId, out var at) || !Sortable(at.Item) || IsBlocked(m.ItemId, nowMs)) continue;
SortPack here = at.Index == 0 ? inv.Main : inv.Packs[at.Index - 1];
if (here.Id != m.ToId) continue; // moved since: not ours to undo
int to = m.FromId == inv.Main.Id ? 0 : inv.IndexOf(m.FromId);
if (to == 0 && m.FromId != inv.Main.Id)
{
view.Waiting++;
view.WaitNoPack++;
continue;
}
SortPack dest = to == 0 ? inv.Main : inv.Packs[to - 1];
if (used[to] >= CapacityOf(dest, to == 0 ? MainCapacityFallback : SideCapacityFallback))
{
if (to == 0) { view.MainFull = true; view.WaitMainFull++; }
else { view.Full.Add(to); view.WaitFull++; }
view.Waiting++;
continue;
}
moves.Add(new SortMove(at.Item, dest, to, 0, -1, MoveKind.Route, here.Id, at.Index));
used[to]++;
used[at.Index]--;
}
FillPacks(view, inv, false, false);
View = view;
return moves;
@ -435,12 +654,21 @@ internal sealed class SortPlanner
ColumnSlot = p.ColumnSlot,
};
private static void FillPacks(SortView view, SortInventory inv, bool ordering, bool kindFirst)
private static void FillPacks(SortView view, SortInventory inv, bool ordering, bool kindFirst,
Func<SortItem, bool>? handy = null, Func<SortItem, bool>? movable = null)
{
view.MainUsed = inv.Main.Items.Count;
view.MainCapacity = CapacityOf(inv.Main, MainCapacityFallback);
view.Main = LineOf(inv.Main, MainCapacityFallback, ordering, kindFirst);
view.Main.Name = "Main pack";
view.Handy = handy != null && inv.Main.OrderKnown;
if (view.Handy)
{
// What is left to do in the main pack: out of the order with handy items first, or the handy items not in front yet.
Func<SortItem, bool> canMove = movable ?? Sortable;
view.HandyBehind = PackOrder.HandyBehind(inv.Main.Items, handy!, canMove);
view.Main.OutOfPlace = ordering ? PackOrder.OutOfPlace(inv.Main.Items, PackOrder.HandyFirst(handy!, kindFirst)) : view.HandyBehind;
}
view.PackOrderKnown = inv.PackOrderKnown;
view.OrderSource = inv.OrderSource;
view.Ordering = ordering;

View file

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>
/// What a sort would do now, before anything moves: every item that would go to another pack
/// (from where, to where), the items left alone because the player touched them, what waits and
/// why, and how much tidying inside the packs follows. Planned on a planner of its own (no settle
/// clocks, no blocks), so it never disturbs the real one. Pure: the window builds one from the
/// last read, with the rules as they are or with a starter layout's rules.
/// </summary>
internal sealed class SortPreview
{
/// <summary>Moves to another pack, in the order a sort would make them.</summary>
public readonly List<SortMove> Moves = new();
/// <summary>The view of this plan: the packs, what waits and why, the held items.</summary>
public SortView View = new();
/// <summary>How many items go into each pack: [0] the main pack, [n] side pack n.</summary>
public int[] Into = Array.Empty<int>();
/// <summary>How many items leave each pack, as <see cref="Into"/>.</summary>
public int[] OutOf = Array.Empty<int>();
/// <summary>Items out of place inside their packs now (put in order once every item is in its pack); 0 when ordering is off.</summary>
public int ToOrder;
public bool Empty => Moves.Count == 0;
/// <summary>
/// The preview for <paramref name="rules"/> on <paramref name="inv"/>: as Sort now (or Clean,
/// with <paramref name="clean"/>) would go, holds included.
/// </summary>
public static SortPreview Build(SortInventory inv, IReadOnlyList<SortRule> rules, PlanOptions opt, Func<uint, bool>? held, bool clean = false)
{
var planner = new SortPlanner { Held = held };
List<SortMove> moves = planner.Plan(inv, rules, clean ? SortScope.Clean : SortScope.All, force: true, 0, 0, opt);
var p = new SortPreview { View = planner.View, Into = new int[inv.Packs.Count + 1], OutOf = new int[inv.Packs.Count + 1] };
foreach (SortMove m in moves)
{
if (m.Kind != MoveKind.Route) continue;
p.Moves.Add(m);
p.Into[m.DestIndex]++;
if (m.FromIndex >= 0 && m.FromIndex < p.OutOf.Length) p.OutOf[m.FromIndex]++;
}
if (p.View.Ordering)
{
p.ToOrder = p.View.Main.OutOfPlace;
foreach (PackLine line in p.View.Packs) p.ToOrder += line.OutOfPlace;
}
else if (p.View.Handy) p.ToOrder = p.View.HandyBehind; // ordering off: only the handy items move to the front
return p;
}
}

View file

@ -255,6 +255,21 @@ internal static class SortRules
return null;
}
/// <summary>
/// Every rule (that is on) the item matches, in the order <see cref="RuleFor"/> picks them: name
/// matches first, then class matches, each in rule order. The first is the item's rule; the
/// others name the overflow packs it may go to when that rule's pack is full.
/// </summary>
public static List<SortRule> RulesFor(IReadOnlyList<SortRule> rules, SortItem item)
{
var list = new List<SortRule>(2);
for (int i = 0; i < rules.Count; i++)
if (rules[i].On && MatchesName(rules[i], item)) list.Add(rules[i]);
for (int i = 0; i < rules.Count; i++)
if (rules[i].On && !list.Contains(rules[i]) && MatchesClass(rules[i], item)) list.Add(rules[i]);
return list;
}
/// <summary>"Gem, Key, Mana Stone, name has "Opal"": the classes (A-Z), then the names (A-Z).</summary>
public static string Describe(SortRule r)
{

View file

@ -0,0 +1,176 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>One kind of thing a starter layout gives a pack of its own ("Spell components").</summary>
internal sealed class StarterGroup
{
public readonly string Key;
/// <summary>What the window calls it.</summary>
public readonly string Label;
public readonly int[] Classes;
public StarterGroup(string key, string label, params int[] classes)
{
Key = key;
Label = label;
Classes = classes;
}
public bool Takes(SortItem it) => Array.IndexOf(Classes, it.ObjectClass) >= 0;
}
/// <summary>A one-click set of rules: kinds of things, most wanted first, one side pack each.</summary>
internal sealed class StarterLayout
{
public readonly string Key;
public readonly string Name;
/// <summary>One plain line: who it suits and what it does.</summary>
public readonly string Blurb;
public readonly StarterGroup[] Groups;
public StarterLayout(string key, string name, string blurb, params StarterGroup[] groups)
{
Key = key;
Name = name;
Blurb = blurb;
Groups = groups;
}
}
/// <summary>A layout fitted to the packs a character carries: which kind goes in which pack, and the rules that say so.</summary>
internal sealed class LayoutPlan
{
public StarterLayout Layout = null!;
/// <summary>Each kind that got a pack, and the pack (1-based, as the window numbers them), top pack first.</summary>
public readonly List<(StarterGroup Group, int Pack)> Placed = new();
/// <summary>Kinds with no pack left (they stay in the main pack).</summary>
public readonly List<StarterGroup> Left = new();
/// <summary>Packs no kind went to (free for the player's own rules), 1-based.</summary>
public readonly List<int> Spare = new();
/// <summary>The rules the layout makes, each tied to its pack's id.</summary>
public readonly List<SortRule> Rules = new();
/// <summary>Items already in the pack their kind gets (they won't move).</summary>
public int AlreadyThere;
}
/// <summary>
/// Starter layouts (#rynth-issues "The bag sort feature is lacking in UX": the rules are complex
/// and there is no common-sense default). A layout is a list of kinds, most wanted first; fitted to
/// a character it gives each kind one side pack while packs last. Kinds a pack already holds come
/// first, wherever they are in the list: each goes to the pack that holds most of it (so the fewest
/// items move; 2026-11-26, the approved window design: a pack already holding kits and food keeps
/// them in Everyday). Then the kinds no pack holds, most wanted first, into the emptiest packs left,
/// top first. Kinds past the packs carried stay in the main pack, as does anything no kind names
/// (loot gear, unusual items).
/// Nothing is applied here: the window shows the fit and a preview first. Pure.
/// </summary>
internal static class StarterLayouts
{
public static readonly StarterGroup Components = new("components", "Spell components", ObjectClasses.SpellComponent);
public static readonly StarterGroup Salvage = new("salvage", "Salvage", ObjectClasses.Salvage);
public static readonly StarterGroup GemsKeys = new("gems", "Gems, mana stones and keys", ObjectClasses.Gem, ObjectClasses.ManaStone, ObjectClasses.Key);
public static readonly StarterGroup Notes = new("notes", "Trade notes and coins", ObjectClasses.TradeNote, ObjectClasses.Money);
public static readonly StarterGroup Supplies = new("supplies", "Healing kits, lockpicks and food", ObjectClasses.HealingKit, ObjectClasses.Lockpick, ObjectClasses.Food);
public static readonly StarterGroup Scrolls = new("scrolls", "Scrolls and books", ObjectClasses.Scroll, ObjectClasses.Book, ObjectClasses.Journal);
public static readonly StarterGroup Crafting = new("crafting", "Crafting supplies",
ObjectClasses.BaseAlchemy, ObjectClasses.BaseCooking, ObjectClasses.BaseFletching,
ObjectClasses.CraftedAlchemy, ObjectClasses.CraftedCooking, ObjectClasses.CraftedFletching, ObjectClasses.Plant, ObjectClasses.Ust);
public static readonly StarterGroup Gear = new("gear", "Armor, weapons and jewelry",
ObjectClasses.Armor, ObjectClasses.Clothing, ObjectClasses.Jewelry, ObjectClasses.MeleeWeapon, ObjectClasses.MissileWeapon, ObjectClasses.WandStaffOrb);
public static readonly StarterLayout Everyday = new("everyday", "Everyday",
"A good start: components, gems and keys, salvage, then kits, notes or scrolls in a pack that already holds them.",
Components, GemsKeys, Salvage, Notes, Supplies, Scrolls);
public static readonly StarterLayout Hunting = new("hunting", "Hunting",
"For hunts: loot gear gets a pack of its own, so the main pack stays free for new loot.",
Components, Salvage, Gear, GemsKeys, Notes, Supplies);
public static readonly StarterLayout CraftingLayout = new("crafting", "Crafting",
"For tinkers and cooks: salvage and crafting supplies first, then components, gems and kits.",
Salvage, Crafting, Components, GemsKeys, Supplies, Scrolls);
public static readonly StarterLayout Basics = new("basics", "Just the basics",
"Three packs only: components, salvage, and gems with keys. Everything else stays put.",
Components, Salvage, GemsKeys);
/// <summary>Every layout, the one to suggest first.</summary>
public static readonly StarterLayout[] All = { Everyday, Hunting, CraftingLayout, Basics };
public static StarterLayout? Find(string? key)
{
foreach (StarterLayout l in All)
if (string.Equals(l.Key, key, StringComparison.OrdinalIgnoreCase)) return l;
return null;
}
/// <summary>The layout fitted to <paramref name="inv"/>'s side packs (see the class summary).</summary>
public static LayoutPlan Fit(StarterLayout layout, SortInventory inv)
{
var plan = new LayoutPlan { Layout = layout };
int packs = inv.Packs.Count;
int kinds = layout.Groups.Length;
var packOf = new int[kinds]; // 1-based, 0 = no pack
var taken = new bool[packs + 1];
// How many of each kind each pack holds now.
var score = new int[kinds, packs + 1];
for (int p = 1; p <= packs; p++)
foreach (SortItem it in inv.Packs[p - 1].Items)
for (int g = 0; g < kinds; g++)
if (layout.Groups[g].Takes(it)) { score[g, p]++; break; }
// Kinds a pack already holds win their packs first, whatever their place in the list: the
// pack that holds most of a kind gets it (more wanted kinds first on a tie, then the top pack).
int placed = 0;
while (placed < packs)
{
int bestG = -1, bestP = -1, best = 0;
for (int g = 0; g < kinds; g++)
{
if (packOf[g] != 0) continue;
for (int p = 1; p <= packs; p++)
if (!taken[p] && score[g, p] > best) { best = score[g, p]; bestG = g; bestP = p; }
}
if (bestG < 0) break;
packOf[bestG] = bestP;
taken[bestP] = true;
placed++;
}
// Then the kinds no pack holds, most wanted first, into the packs with the most room (top first on a tie).
var free = new List<int>();
for (int p = 1; p <= packs; p++) if (!taken[p]) free.Add(p);
free.Sort((a, b) =>
{
int ra = Room(inv.Packs[a - 1]), rb = Room(inv.Packs[b - 1]);
return ra != rb ? rb.CompareTo(ra) : a.CompareTo(b);
});
int next = 0;
for (int g = 0; g < kinds && next < free.Count; g++)
if (packOf[g] == 0) packOf[g] = free[next++];
for (; next < free.Count; next++) plan.Spare.Add(free[next]);
plan.Spare.Sort();
for (int g = 0; g < kinds; g++)
{
if (packOf[g] == 0) { plan.Left.Add(layout.Groups[g]); continue; }
plan.Placed.Add((layout.Groups[g], packOf[g]));
plan.AlreadyThere += score[g, packOf[g]];
}
plan.Placed.Sort((a, b) => a.Pack.CompareTo(b.Pack));
foreach (var (group, pack) in plan.Placed)
{
SortPack sp = inv.Packs[pack - 1];
var rule = new SortRule { Pack = pack, PackId = sp.Id, PackNote = PackFix.NoteOf(sp) };
foreach (int c in group.Classes) rule.AddClass(c);
plan.Rules.Add(rule);
}
return plan;
}
private static int Room(SortPack p) => SortPlanner.CapacityOf(p, SortPlanner.SideCapacityFallback) - p.Items.Count;
}

View file

@ -0,0 +1,195 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>How the player last touched an item (what the window says).</summary>
internal enum TouchKind : byte
{
/// <summary>It changed packs, and RynthSort didn't move it.</summary>
Moved,
/// <summary>It is (or was) selected in the game.</summary>
Selected,
/// <summary>It was dragged in AC's windows.</summary>
Dragged,
/// <summary>It was worn or wielded and is in a pack now.</summary>
TakenOff,
/// <summary>It turned up in a pack just after a drop (picked up, or a stack split off).</summary>
PickedUp,
/// <summary>The player asked RynthSort to leave it alone (the window's "Leave it alone").</summary>
Chosen,
/// <summary>The player sent it to a pack from RynthSort's window, without a rule ("Just move it").</summary>
Sent,
}
/// <summary>
/// "Leave my items alone": which items the player used lately, so sorting leaves them where they
/// are for the hold time (#rynth-issues "The bag sort feature is lacking in UX": "it moves the
/// items you're working with into one of 9 bags"). An item counts as touched when
/// <list type="bullet">
/// <item>it is selected in the game (the plugin polls the selection every tick, so it stays
/// touched while it is selected and for the hold time after);</item>
/// <item>the player drags it in AC's windows (engine API v77 drag and drop hooks);</item>
/// <item>between two reads of the packs it changed packs and RynthSort didn't send it there
/// (the player, or another plugin, moved it);</item>
/// <item>it was worn or wielded at the last read and is in a pack now (taken off);</item>
/// <item>it is new in the packs within <see cref="DropWindowMs"/> of a drop (picked up from the
/// ground, or a stack split off one being dragged: the new stack has a new id).</item>
/// </list>
/// Moves inside one pack (a slot change) aren't seen by the reads; a drag catches those. Pure (no
/// host calls): the controller feeds it the reads and its own moves, the plugin the selection and
/// the drags; the tests drive it by hand.
/// </summary>
internal sealed class TouchWatch
{
/// <summary>A pack change this soon after RynthSort's own move of the item to that pack is RynthSort's.</summary>
public const long OwnMoveMs = 30_000;
/// <summary>New items this soon after a drop are the player's.</summary>
public const long DropWindowMs = 3000;
/// <summary>An item missing from the reads is remembered this long (a pack not listed for a moment).</summary>
public const long ForgetMs = 60_000;
/// <summary>The "container" of a worn or wielded item.</summary>
public const uint WornMarker = 0xFFFFFFFE;
/// <summary>The longest hold the settings offer (old touches are dropped after it).</summary>
public const long MaxHoldMs = 60 * 60_000;
private readonly Dictionary<uint, (uint Container, long SeenMs)> _where = new();
private readonly Dictionary<uint, (long AtMs, TouchKind Kind)> _touched = new();
private readonly Dictionary<uint, (uint Dest, long AtMs)> _ours = new();
private long _droppedAtMs = long.MinValue / 2;
private bool _primed;
/// <summary>Forget everything (logout, another character).</summary>
public void Reset()
{
_where.Clear();
_touched.Clear();
_ours.Clear();
_droppedAtMs = long.MinValue / 2;
_primed = false;
}
/// <summary>"Sort them too": every item is fair game again (new touches still count).</summary>
public void ReleaseAll() => _touched.Clear();
/// <summary>"Let RynthSort move it": <paramref name="itemId"/> is fair game again (a new touch still counts). False when it wasn't held.</summary>
public bool Release(uint itemId) => _touched.Remove(itemId);
/// <summary>The player asked for <paramref name="itemId"/> to be left alone from now (the window's "Leave it alone", "Just move it").</summary>
public void Hold(uint itemId, long nowMs, TouchKind kind)
{
if (itemId != 0) Touch(itemId, nowMs, kind);
}
/// <summary>RynthSort sent <paramref name="itemId"/> to <paramref name="destId"/>: its arrival there isn't the player's.</summary>
public void NoteOwnMove(uint itemId, uint destId, long nowMs) => _ours[itemId] = (destId, nowMs);
/// <summary>The game's selection now (0 = none). Only items in the packs count (not monsters, corpses or packs).</summary>
public void NoteSelected(uint objectId, long nowMs)
{
if (objectId == 0 || !_where.TryGetValue(objectId, out var at) || at.Container == WornMarker) return;
Touch(objectId, nowMs, TouchKind.Selected);
}
/// <summary>The player started dragging <paramref name="objectId"/> (OnDragStart).</summary>
public void NoteDrag(uint objectId, long nowMs)
{
if (objectId != 0) Touch(objectId, nowMs, TouchKind.Dragged);
}
/// <summary>The player dropped <paramref name="objectId"/> somewhere (OnItemDropped): new items for a moment after are theirs too.</summary>
public void NoteDrop(uint objectId, long nowMs)
{
if (objectId != 0) Touch(objectId, nowMs, TouchKind.Dragged);
_droppedAtMs = nowMs;
}
/// <summary>
/// A read of the packs: items that changed packs without RynthSort, were taken off, or are new
/// just after a drop count as touched. The first read after a reset only learns where things are.
/// </summary>
public void Observe(SortInventory inv, long nowMs)
{
void See(uint id, uint container)
{
if (_primed)
{
if (_where.TryGetValue(id, out var was))
{
if (was.Container != container)
{
if (_ours.TryGetValue(id, out var own) && own.Dest == container && nowMs - own.AtMs < OwnMoveMs)
_ours.Remove(id);
else
Touch(id, nowMs, was.Container == WornMarker ? TouchKind.TakenOff : TouchKind.Moved);
}
}
else if (nowMs - _droppedAtMs < DropWindowMs)
{
Touch(id, nowMs, TouchKind.PickedUp);
}
}
_where[id] = (container, nowMs);
}
foreach (SortItem it in inv.Main.Items) See(it.Id, inv.Main.Id);
foreach (SortPack p in inv.Packs)
foreach (SortItem it in p.Items) See(it.Id, p.Id);
foreach (uint id in inv.Worn) See(id, WornMarker);
_primed = true;
Prune(nowMs);
}
/// <summary>Whether <paramref name="itemId"/> was touched within <paramref name="holdMs"/> (0 = holding is off).</summary>
public bool IsHeld(uint itemId, long nowMs, long holdMs) => TryGetHeld(itemId, nowMs, holdMs, out _, out _);
/// <summary>When and how <paramref name="itemId"/> was last touched, if that is within <paramref name="holdMs"/>.</summary>
public bool TryGetHeld(uint itemId, long nowMs, long holdMs, out long atMs, out TouchKind kind)
{
atMs = 0;
kind = TouchKind.Moved;
if (holdMs <= 0 || !_touched.TryGetValue(itemId, out var t) || nowMs - t.AtMs >= holdMs) return false;
atMs = t.AtMs;
kind = t.Kind;
return true;
}
/// <summary>How many touches are still within <paramref name="holdMs"/> (items anywhere, not only in the packs).</summary>
public int HeldCount(long nowMs, long holdMs)
{
if (holdMs <= 0) return 0;
int n = 0;
foreach (var t in _touched.Values) if (nowMs - t.AtMs < holdMs) n++;
return n;
}
private void Touch(uint id, long nowMs, TouchKind kind) => _touched[id] = (nowMs, kind);
private List<uint>? _gone;
private void Prune(long nowMs)
{
_gone ??= new List<uint>();
_gone.Clear();
foreach (var kv in _where) if (nowMs - kv.Value.SeenMs > ForgetMs) _gone.Add(kv.Key);
foreach (uint id in _gone) _where.Remove(id);
_gone.Clear();
foreach (var kv in _touched) if (nowMs - kv.Value.AtMs > MaxHoldMs) _gone.Add(kv.Key);
foreach (uint id in _gone) _touched.Remove(id);
_gone.Clear();
foreach (var kv in _ours) if (nowMs - kv.Value.AtMs > OwnMoveMs) _gone.Add(kv.Key);
foreach (uint id in _gone) _ours.Remove(id);
}
/// <summary>"you moved it", "you have it selected" ...: how the window says it.</summary>
public static string Words(TouchKind kind) => kind switch
{
TouchKind.Selected => "you selected it",
TouchKind.Dragged => "you dragged it",
TouchKind.TakenOff => "you took it off",
TouchKind.PickedUp => "you picked it up",
TouchKind.Chosen => "you asked to leave it",
TouchKind.Sent => "you sent it there",
_ => "you moved it",
};
}

View file

@ -48,6 +48,28 @@ internal static class UiFormat
public const byte OpChild = 0x40;
public const byte OpCollapsingHeader = 0x41;
// Op level 3 (a newer engine, not released yet; Docs/RYNTHLUA_WINDOWS_DESIGN.md §10.2 on
// feature/lua-rich-windows). Only recorded when UiGetInfo says OpLevel >= 3: an older engine
// would skip them by length, which would leave a table's rows out.
public const int OpLevelRich = 3;
public const byte OpPushFont = 0x36;
public const byte OpPopFont = 0x37;
public const byte OpTable = 0x50;
public const byte OpTableSetupColumn = 0x51;
public const byte OpTableHeadersRow = 0x52;
public const byte OpTableNextRow = 0x53;
public const byte OpTableNextColumn = 0x54;
// PushFont faces (the engine's baked fonts by number).
public const byte FontBold = 4;
// ImGuiTableFlags / ImGuiTableColumnFlags (ImGui.NET 1.91.6.1) the engine's whitelist keeps.
public const uint TableRowBg = 1u << 6;
public const uint TableBordersInnerH = 1u << 7;
public const uint TableSizingStretchProp = 3u << 13;
public const uint ColumnWidthStretch = 1u << 3;
public const uint ColumnWidthFixed = 1u << 4;
// Window flags
public const uint FlagVisible = 1u << 0;
public const uint FlagShowInBar = 1u << 1;
@ -127,4 +149,8 @@ internal static class UiColors
public static readonly uint White = UiFormat.Rgb(255, 255, 255);
/// <summary>The Lua script's amber (paused, full packs): 1.0, 0.75, 0.25.</summary>
public static readonly uint Amber = UiFormat.Rgb(255, 191, 64);
/// <summary>Something is happening now (moving items).</summary>
public static readonly uint Blue = UiFormat.Rgb(120, 175, 240);
/// <summary>Text a little quieter than normal, louder than disabled (hints).</summary>
public static readonly uint Soft = UiFormat.Rgb(185, 185, 185);
}

View file

@ -434,7 +434,9 @@ internal sealed class UiWindow
U32(0); // BlockLength, patched by EndChild
}
public void EndChild()
public void EndChild() => EndBlock();
private void EndBlock()
{
if (_blockDepth == 0) return;
int at = _blocks[--_blockDepth];
@ -442,6 +444,86 @@ internal sealed class UiWindow
BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(at), (uint)(_len - (at + 4)));
}
// ── Op level 3 (the caller checks the engine's level first) ─────────────
/// <summary>Text in one of the engine's faces (<see cref="UiFormat.FontBold"/> ...) until <see cref="PopFont"/>. Op level 3.</summary>
public void PushFont(byte font)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpPushFont);
U8(font);
EndOp(p);
}
/// <summary>The engine pops what is left at the scope's end, so a pop cut off with the list is harmless.</summary>
public void PopFont(int count = 1)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpPopFont);
U8((byte)Math.Clamp(count, 1, 255));
EndOp(p);
}
/// <summary>
/// A table (op level 3): columns set up with <see cref="TableSetupColumn"/>, then rows of cells
/// (<see cref="TableNextRow"/>, <see cref="TableNextColumn"/>), closed with <see cref="EndTable"/>.
/// Anything before the first row or cell is dropped by the engine.
/// </summary>
public void BeginTable(string id, int columns, uint flags, float outerW = 0f, float outerH = 0f)
{
if (_blockDepth >= _blocks.Length) throw new InvalidOperationException("tables nested too deep");
if (!Room())
{
_blocks[_blockDepth++] = -1;
return;
}
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpTable, UiFormat.OpHasBlock);
U32(key);
Str(id);
U8((byte)Math.Clamp(columns, 1, 32));
U32(flags);
F32(outerW);
F32(outerH);
F32(0f); // inner width
I32(-1); // known sort: none (not sortable)
EndOp(p);
_blocks[_blockDepth++] = _len;
U32(0); // BlockLength, patched by EndTable
}
public void EndTable() => EndBlock();
public void TableSetupColumn(string label, uint flags = 0, float widthOrWeight = 0f)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpTableSetupColumn);
Str(label);
U32(flags);
F32(widthOrWeight);
EndOp(p);
}
public void TableHeadersRow()
{
if (!Room()) return;
EndOp(BeginOp(UiFormat.OpTableHeadersRow));
}
public void TableNextRow(float minHeight = 0f)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpTableNextRow);
F32(minHeight);
EndOp(p);
}
public void TableNextColumn()
{
if (!Room()) return;
EndOp(BeginOp(UiFormat.OpTableNextColumn));
}
// ── Writing ─────────────────────────────────────────────────────────────
/// <summary>

View file

@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthCore.Plugin.RynthSort.Views;
/// <summary>What the game has selected, as far as a rule can use it.</summary>
internal enum SelectionKind
{
/// <summary>This RynthCore can't say what is selected.</summary>
Unavailable,
/// <summary>The packs can't be read yet (not loaded).</summary>
NoInventory,
Nothing,
/// <summary>A pack or focus (it holds items; it isn't one).</summary>
Pack,
/// <summary>Something else: on the ground, a monster, another player, a worn or wielded item.</summary>
NotInPacks,
/// <summary>A loose item in the main pack or a side pack.</summary>
Item,
}
/// <summary>The selected object: its kind, and for an item the item as the packs were just read.</summary>
internal sealed class SelectedItem
{
public SelectionKind Kind;
public uint Id;
/// <summary>The object's name as the client has it (blank when unknown); for an item, its name in the pack read.</summary>
public string Name = string.Empty;
public SortItem? Item;
public static SelectedItem Of(SelectionKind kind, uint id = 0, string name = "") => new() { Kind = kind, Id = id, Name = name ?? string.Empty };
}
internal static class SelectionLookup
{
/// <summary>
/// What <paramref name="id"/> is in the packs just read: a loose item (the reader leaves out
/// worn and wielded items, packs and foci), a pack or focus, or nothing the packs hold.
/// </summary>
public static SelectedItem Find(SortInventory inv, uint id, string name)
{
if (id == 0) return SelectedItem.Of(SelectionKind.Nothing);
SortItem? item = inv.Main.Items.Find(x => x.Id == id);
if (item == null)
foreach (SortPack p in inv.Packs)
{
item = p.Items.Find(x => x.Id == id);
if (item != null) break;
}
if (item != null) return new SelectedItem { Kind = SelectionKind.Item, Id = id, Name = item.Name, Item = item };
foreach (SortSlot s in inv.Slots)
if (s.Id == id) return SelectedItem.Of(SelectionKind.Pack, id, name);
foreach (SortPack p in inv.Packs)
if (p.Id == id) return SelectedItem.Of(SelectionKind.Pack, id, name);
return SelectedItem.Of(SelectionKind.NotInPacks, id, name);
}
}
internal enum AddStatus
{
/// <summary>A name went into one of the pack's rules.</summary>
Added,
/// <summary>The pack's rules already take the item: nothing changed.</summary>
AlreadyThere,
/// <summary>Nothing selected, not an item in the packs, no such pack, no room: nothing changed.</summary>
Refused,
}
internal sealed class AddOutcome
{
public AddStatus Status;
/// <summary>What to tell the player (the window's line under the pack's buttons; the chat for /rsort add).</summary>
public string Message = string.Empty;
/// <summary>The rule the name went into (null unless <see cref="Status"/> is Added).</summary>
public SortRule? Rule;
}
/// <summary>
/// "Add selected": the item selected in the game goes into one of a pack's rules by name, in the
/// rules' own words ("name has ..."). The name is the item's name without a count: a rule's name
/// is part of an item's name, so the item's own name takes every item called that (a bag of
/// "Salvaged Iron (100)" becomes "Salvaged Iron", whatever the bag holds), and it needs no more
/// than the name the planner already matches on. A class would take every item of that kind,
/// and rules have no wcid or material to match by. Pure (no host calls): the plugin reads the
/// selection, the tests hand one in.
/// </summary>
internal static class AddSelectedRules
{
/// <summary>The name an item's rule entry holds: the name without a trailing "(100)" count, as a rule keeps it.</summary>
public static string EntryFor(string? itemName)
{
string n = (itemName ?? string.Empty).Trim();
int open = n.LastIndexOf('(');
if (open > 0 && n.EndsWith(')') && IsCount(n.AsSpan(open + 1, n.Length - open - 2)))
n = n[..open].TrimEnd();
return SortRule.Clean(n);
}
private static bool IsCount(ReadOnlySpan<char> s)
{
if (s.Length == 0) return false;
foreach (char c in s) if (c < '0' || c > '9') return false;
return true;
}
/// <summary>
/// Puts the selected item into pack <paramref name="number"/>'s rules (1-based, as the window
/// numbers them). Never moves anything: an item another pack's rule takes still gets its name
/// in this pack's rules (the player pressed Add for this pack), and the message says which
/// pack had it and whether this pack's rule now wins.
/// </summary>
public static AddOutcome Apply(List<SortRule> rules, SortView view, int number, SelectedItem sel)
{
AddOutcome Refuse(string text) => new() { Status = AddStatus.Refused, Message = text };
string called = sel.Name.Length > 0 ? $"\"{sel.Name}\"" : "The selected object";
switch (sel.Kind)
{
case SelectionKind.Unavailable: return Refuse("This RynthCore can't say which item is selected, Nothing was added.");
case SelectionKind.NoInventory: return Refuse("Your packs aren't loaded yet; try again in a moment. Nothing was added.");
case SelectionKind.Nothing: return Refuse("Nothing is selected. Click an item in your inventory, then press Add selected. Nothing was added.");
case SelectionKind.Pack: return Refuse($"{called} is a pack, not an item. Select an item inside your packs. Nothing was added.");
case SelectionKind.NotInPacks:
return Refuse($"{called} isn't an item in your packs (on the ground, worn, or not yours). Select an item in your inventory. Nothing was added.");
}
if (sel.Item == null) return Refuse("Nothing is selected. Nothing was added.");
if (number < 1 || number > view.Packs.Count)
return Refuse(view.Packs.Count == 0 ? "You carry no side packs. Nothing was added." : $"You don't carry a pack {number} (you have {view.Packs.Count}). Nothing was added.");
SortItem item = sel.Item;
string entry = EntryFor(item.Name);
if (entry.Length == 0) return Refuse("The selected item has no name the client can read yet; try again in a moment. Nothing was added.");
string packName = PackWords(view, number);
var here = new List<SortRule>();
foreach (SortRule r in rules) if (SortPanel.ShownPack(view, r) == number) here.Add(r);
here.Sort(SortRules.CompareForList);
// Already named by one of this pack's rules (the entry itself, or a shorter name inside it)?
SortRule? offRule = null;
foreach (SortRule r in here)
{
if (!SortRules.MatchesName(r, item)) continue;
if (r.On) return AlreadyThere(rules, view, number, item, $"\"{entry}\" is already in {packName}'s rules ({SortRules.Describe(r)}). Nothing was added.");
offRule ??= r;
}
if (offRule != null)
return AlreadyThere(rules, view, number, item,
$"\"{entry}\" is already in {packName}'s rules ({SortRules.Describe(offRule)}), but that rule is turned off: turn it on. Nothing was added.");
// Already sent here by a class rule of this pack (no other rule beats it)?
SortRule? before = SortRules.RuleFor(rules, item);
if (before != null && SortPanel.ShownPack(view, before) == number)
return new AddOutcome { Status = AddStatus.AlreadyThere, Message = $"\"{entry}\" already goes to {packName} ({SortRules.Describe(before)}). Nothing was added." };
// Where the name goes: a rule of this pack that is on and already lists names, else a new
// rule (one row per item would run into the rule limit), else any rule of the pack with room.
SortRule? target = null;
foreach (SortRule r in here)
if (r.On && r.Names.Count > 0 && r.Names.Count < SortRule.MaxNames) { target = r; break; }
bool created = false;
if (target == null && rules.Count < SortStore.MaxRules)
{
target = new SortRule();
SortPanel.SetPack(target, view, number);
created = true;
}
if (target == null)
foreach (SortRule r in here)
if (r.On && r.Names.Count < SortRule.MaxNames) { target = r; break; }
if (target == null)
return Refuse($"There is no room in {packName}'s rules (the limit of {SortStore.MaxRules} rules is reached and its rules hold {SortRule.MaxNames} names each). Nothing was added.");
target.AddName(entry);
if (created) rules.Add(target);
string text = created
? $"Added \"{entry}\" to {packName} as a new rule."
: $"Added \"{entry}\" to {packName}'s rule {SortRules.Describe(target)}.";
if (before != null)
text += $" It was going to {WhereWords(view, before)} ({SortRules.Describe(before)}).";
SortRule? after = SortRules.RuleFor(rules, item);
if (after != null && SortPanel.ShownPack(view, after) != number)
text += $" The rule for {WhereWords(view, after)} ({SortRules.Describe(after)}) still wins, as it matches the same way and comes first: change that rule to send the item here.";
else if (before != null) text += " Now it goes here.";
return new AddOutcome { Status = AddStatus.Added, Message = text, Rule = target };
}
/// <summary>"Already there", and a word when another pack's rule is the one that takes the item.</summary>
private static AddOutcome AlreadyThere(List<SortRule> rules, SortView view, int number, SortItem item, string text)
{
SortRule? winner = SortRules.RuleFor(rules, item);
if (winner != null && SortPanel.ShownPack(view, winner) != number)
text = text.Replace(" Nothing was added.", $" But the rule for {WhereWords(view, winner)} ({SortRules.Describe(winner)}) comes first and wins. Nothing was added.");
return new AddOutcome { Status = AddStatus.AlreadyThere, Message = text };
}
/// <summary>"pack 2 (Sack)".</summary>
private static string PackWords(SortView view, int number) => $"pack {number} ({view.Packs[number - 1].Name})";
private static string WhereWords(SortView view, SortRule r)
{
int n = SortPanel.ShownPack(view, r);
return n > 0 ? PackWords(view, n) : "a pack you don't have";
}
}

View file

@ -0,0 +1,154 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Ui;
namespace RynthCore.Plugin.RynthSort.Views;
// The Layouts page: starter layouts fitted to the packs carried, previewed before anything changes.
internal sealed partial class SortPanel
{
private string? _layoutKey;
private string _layoutNote = string.Empty;
private bool _layoutNoteGood;
private long _layoutNoteUntilMs;
/// <summary>The layout picked to look at (not used yet), or null.</summary>
public string? PickedLayout => _layoutKey;
private void DrawLayoutsTab(UiWindow w, List<SortRule> rules)
{
DrawLayoutNote(w);
w.PushStyleColor(UiFormat.ColText, UiColors.Soft);
w.TextWrapped("A layout gives each kind of item a side pack of its own, choosing the pack that already holds most of it. "
+ "Pick one to see where things would go. Nothing changes until you press Use this layout, and nothing moves until you sort.");
w.PopStyleColor();
SortInventory? inv = _c.LastInventory;
if (inv == null)
{
w.TextDisabled("Reading your packs...");
return;
}
if (inv.Packs.Count == 0)
{
w.TextColored(UiColors.Amber, "You carry no side packs, so a layout has nowhere to put things. Get a pack and come back.");
return;
}
foreach (StarterLayout l in StarterLayouts.All)
{
bool picked = string.Equals(_layoutKey, l.Key, StringComparison.Ordinal);
string key = l.Key;
w.Selectable(l == StarterLayouts.All[0] ? l.Name + " (a good start)" : l.Name, "layout." + l.Key, picked,
() => _layoutKey = picked ? null : key);
w.Tooltip(picked ? "Click to close the preview" : "Click to see where things would go");
w.Indent(EditorIndent);
w.PushStyleColor(UiFormat.ColText, UiColors.Grey);
w.TextWrapped(l.Blurb);
w.PopStyleColor();
w.Unindent(EditorIndent);
if (picked) DrawLayoutPreview(w, l, inv, rules);
}
}
private void DrawLayoutPreview(UiWindow w, StarterLayout l, SortInventory inv, List<SortRule> rules)
{
LayoutPlan plan = StarterLayouts.Fit(l, inv);
SortPreview p = SortPreview.Build(inv, plan.Rules, _c.CurrentOptions, _c.IsHeld);
w.Indent(EditorIndent);
w.SeparatorText($"{l.Name} on your {Count(inv.Packs.Count, "pack")}");
if (Rich)
{
w.BeginTable("layout." + l.Key + ".table", 3, UiFormat.TableRowBg | UiFormat.TableBordersInnerH | UiFormat.TableSizingStretchProp);
w.TableSetupColumn("Pack", UiFormat.ColumnWidthStretch, 1.6f);
w.TableSetupColumn("Gets", UiFormat.ColumnWidthStretch, 2.6f);
w.TableSetupColumn("Moves in", UiFormat.ColumnWidthStretch, 1f);
w.TableHeadersRow();
foreach (var (group, pack) in plan.Placed)
{
w.TableNextRow();
w.TableNextColumn();
PackCell(w, inv, pack);
w.TableNextColumn();
w.Text(group.Label);
w.TableNextColumn();
w.Text(p.Into[pack].ToString(System.Globalization.CultureInfo.InvariantCulture));
}
w.EndTable();
}
else
{
foreach (var (group, pack) in plan.Placed)
{
PackCell(w, inv, pack);
w.SameLine();
w.Text(group.Label);
w.SameLine();
w.TextDisabled(p.Into[pack] == 0 ? "- nothing to move in" : $"- {p.Into[pack]} to move in");
}
}
foreach (int spare in plan.Spare)
w.TextDisabled($"Pack {spare} ({inv.Packs[spare - 1].Name}) stays free for your own rules.");
if (plan.Left.Count > 0)
{
var left = plan.Left.ConvertAll(g => g.Label.ToLowerInvariant());
w.PushStyleColor(UiFormat.ColText, UiColors.Grey);
w.TextWrapped($"No pack left for {string.Join("; ", left)}: they stay in the main pack.");
w.PopStyleColor();
}
string moved = p.Moves.Count == 0 ? "Nothing would move" : $"{Count(p.Moves.Count, "item")} would move";
w.Text(plan.AlreadyThere > 0 ? $"{moved}; {plan.AlreadyThere} already in place." : moved + ".");
if (p.View.Full.Count > 0) w.TextColored(UiColors.Amber, "Some packs would be full: those items wait in the main pack.");
if (rules.Count > 0)
w.TextColored(UiColors.Amber, $"This replaces your {Count(rules.Count, "rule")} (Undo brings them back).");
w.Button("Use this layout", "layout.use", () => UseLayout(l));
w.Tooltip("Set these rules. Nothing moves: press Sort now afterwards, or turn on Auto-sort.");
w.SameLine();
w.Button("Cancel", "layout.cancel", () => _layoutKey = null);
w.Unindent(EditorIndent);
}
private void PackCell(UiWindow w, SortInventory inv, int pack)
{
SortPack sp = inv.Packs[pack - 1];
if (Icons())
{
w.Image(UiFormat.IconKindObject, sp.Id, RowIcon, RowIcon);
w.SameLine();
}
w.Text($"Pack {pack}");
w.Tooltip($"{sp.Name}: {sp.Items.Count} of {SortPlanner.CapacityOf(sp, SortPlanner.SideCapacityFallback)} items ({sp.Summary()})");
}
/// <summary>The layout's rules replace the character's (Undo keeps the old ones); nothing moves.</summary>
internal void UseLayout(StarterLayout l)
{
SortInventory? inv = _c.LastInventory;
if (inv == null || inv.Packs.Count == 0) return;
List<SortRule> rules = _c.Data.Rules;
LayoutPlan plan = StarterLayouts.Fit(l, inv);
var before = Snapshot(rules);
rules.Clear();
rules.AddRange(plan.Rules);
KeepUndo(before, "the " + l.Name + " layout");
_selected = null;
_layoutKey = null;
_layoutNote = $"Rules set from {l.Name}: {Count(plan.Rules.Count, "pack")} {(plan.Rules.Count == 1 ? "has" : "have")} a kind of item. "
+ "Nothing has moved yet: press Sort now, or turn on Auto-sort.";
_layoutNoteGood = true;
_layoutNoteUntilMs = Now() + 3 * NoteMs;
ShowTab(PanelTab.Packs);
_save();
}
private void DrawLayoutNote(UiWindow w)
{
if (_layoutNote.Length == 0 || Now() >= _layoutNoteUntilMs) return;
w.PushStyleColor(UiFormat.ColText, _layoutNoteGood ? UiColors.Green : UiColors.Amber);
w.TextWrapped(_layoutNote);
w.PopStyleColor();
}
}

View file

@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Ui;
namespace RynthCore.Plugin.RynthSort.Views;
// The Moves page: what a sort would move now, what is left alone, what moved last.
internal sealed partial class SortPanel
{
private const float RowIcon = 16f;
/// <summary>The most moves listed (the rest are counted).</summary>
internal const int MoveRows = 30;
private void DrawMovesTab(UiWindow w, SortView view)
{
SortSettings s = _c.Data.Settings;
w.SeparatorText("Next moves");
SortPreview? p = _preview;
if (p == null)
{
w.TextDisabled("Reading your packs...");
}
else if (p.Empty)
{
w.TextColored(UiColors.Green, "Nothing to move: every item is in its pack.");
if (p.ToOrder > 0) w.TextDisabled($"{Count(p.ToOrder, "item")} still to put in order inside packs.");
}
else
{
w.Text(s.Auto || _c.Job != null
? $"{Count(p.Moves.Count, "item")} {(p.Moves.Count == 1 ? "goes" : "go")} to {(p.Moves.Count == 1 ? "its pack" : "their packs")}:"
: $"A sort would move {Count(p.Moves.Count, "item")}:");
if (Rich) DrawMoveTable(w, p);
else DrawMoveLines(w, p);
if (p.Moves.Count > MoveRows) w.TextDisabled($"... and {p.Moves.Count - MoveRows} more.");
if (p.ToOrder > 0) w.TextDisabled("Then stacks are joined and items put in order inside each pack.");
if (!s.Auto && _c.Job == null)
{
w.PushStyleColor(UiFormat.ColText, UiColors.Soft);
w.TextWrapped("Nothing moves until you press Sort now or turn on Auto-sort.");
w.PopStyleColor();
}
}
if (p != null) DrawWaiting(w, p.View);
if (p != null && p.View.Held.Count > 0) DrawHeld(w, p.View.Held);
w.SeparatorText("Done lately");
if (_c.Log.Count == 0) w.TextDisabled("Nothing moved yet.");
foreach (string line in _c.Log) w.TextDisabled(line);
int back = _c.PutBackCount;
if (back > 0)
{
w.SmallButton($"Put back {Count(back, "item")}", "moves.back", () => _c.StartPutBack());
w.Tooltip("Undo the last sort: those items go back where they were. Turns auto-sort off first, so nothing moves again.");
}
}
private void DrawMoveLines(UiWindow w, SortPreview p)
{
int n = Math.Min(p.Moves.Count, MoveRows);
for (int i = 0; i < n; i++)
{
SortMove m = p.Moves[i];
if (Icons())
{
w.Image(UiFormat.IconKindObject, m.Item.Id, RowIcon, RowIcon);
w.SameLine();
}
w.Text(ItemName(m.Item));
w.SameLine();
w.TextDisabled($"{PackWord(Math.Max(m.FromIndex, 0))} -> {PackWord(m.DestIndex)}");
w.Tooltip(MoveTooltip(m));
}
}
/// <summary>The same list as a table (op level 3): Item, From, To.</summary>
private void DrawMoveTable(UiWindow w, SortPreview p)
{
w.BeginTable("moves", 3, UiFormat.TableRowBg | UiFormat.TableBordersInnerH | UiFormat.TableSizingStretchProp);
w.TableSetupColumn("Item", UiFormat.ColumnWidthStretch, 3f);
w.TableSetupColumn("From", UiFormat.ColumnWidthStretch, 1.4f);
w.TableSetupColumn("To", UiFormat.ColumnWidthStretch, 1.4f);
w.TableHeadersRow();
int n = Math.Min(p.Moves.Count, MoveRows);
for (int i = 0; i < n; i++)
{
SortMove m = p.Moves[i];
w.TableNextRow();
w.TableNextColumn();
if (Icons())
{
w.Image(UiFormat.IconKindObject, m.Item.Id, RowIcon, RowIcon);
w.SameLine();
}
w.Text(ItemName(m.Item));
w.Tooltip(MoveTooltip(m));
w.TableNextColumn();
w.TextDisabled(PackWord(Math.Max(m.FromIndex, 0)));
w.TableNextColumn();
w.Text(PackWord(m.DestIndex));
}
w.EndTable();
}
private string MoveTooltip(in SortMove m)
{
SortRule? r = SortRules.RuleFor(_c.Data.Rules, m.Item);
string why = r != null ? $"Its rule: {SortRules.Describe(r)}." : "No rule wants it in a side pack (Clean sends it to the main pack).";
string dest = m.DestIndex == 0 ? "the main pack" : $"pack {m.DestIndex} ({m.Dest.Name})";
return $"{ItemName(m.Item)} goes to {dest}. {why}";
}
private static void DrawWaiting(UiWindow w, SortView v)
{
if (v.WaitSettle > 0)
w.TextDisabled($"{Count(v.WaitSettle, "new item")} {(v.WaitSettle == 1 ? "waits" : "wait")} out the settle time in the main pack.");
foreach (int pack in v.Full)
w.TextColored(UiColors.Amber, $"Pack {pack} is full: items for it wait where they are.");
if (v.WaitNoPack > 0)
w.TextColored(UiColors.Amber, $"{Count(v.WaitNoPack, "item")} {(v.WaitNoPack == 1 ? "has a rule" : "have rules")} for a pack you don't carry (see Packs).");
if (v.WaitMainFull > 0)
w.TextColored(UiColors.Amber, "The main pack is full: Clean can't bring everything back.");
}
private void DrawHeld(UiWindow w, List<HeldLine> held)
{
w.SeparatorText("Left alone");
w.PushStyleColor(UiFormat.ColText, UiColors.Soft);
w.TextWrapped($"You used these lately, so they stay where they are for {Count(_c.Data.Settings.HoldMin, "minute")} (Settings).");
w.PopStyleColor();
int n = Math.Min(held.Count, MoveRows);
long now = _c.Clock;
for (int i = 0; i < n; i++)
{
HeldLine h = held[i];
if (Icons())
{
w.Image(UiFormat.IconKindObject, h.Item.Id, RowIcon, RowIcon);
w.SameLine();
}
w.Text(ItemName(h.Item));
w.SameLine();
string how = _c.Touch.TryGetHeld(h.Item.Id, now, _c.HoldMs, out long at, out TouchKind kind)
? $"{TouchWatch.Words(kind)} {Ago(now - at)}" : "you used it";
w.TextDisabled($"- {how}; would go to {(h.To == 0 ? "the main pack" : "pack " + h.To)}");
}
if (held.Count > n) w.TextDisabled($"... and {held.Count - n} more.");
w.SmallButton("Sort them too", "hold.release", () => _c.Touch.ReleaseAll());
w.Tooltip("Stop leaving these items alone: the next sort moves them like any other. Items you use after this are left alone again.");
}
private static string ItemName(SortItem it) => it.Name.Length > 0 ? Shown(it.Name) : $"(item 0x{it.Id:X8})";
/// <summary>"just now", "2 min ago".</summary>
internal static string Ago(long ms) => ms < 60_000 ? "just now" : $"{ms / 60_000} min ago";
}

View file

@ -0,0 +1,442 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Ui;
namespace RynthCore.Plugin.RynthSort.Views;
// The Packs page: "what goes in this pack", one section per side pack.
internal sealed partial class SortPanel
{
private const float WhereIcon = 20f, KindIcon = 18f;
private const int KindIcons = 8;
// The last big rule change (a layout, a kind taken from another pack, a rule removed or merged), for Undo.
private List<SortRule>? _undo;
private string _undoWhat = string.Empty;
private Dictionary<SortRule, (int Here, int Coming)> _counts = new();
/// <summary>Whether Undo has something to put back, and what.</summary>
public string UndoWhat => _undo != null ? _undoWhat : string.Empty;
private void DrawPacksTab(UiWindow w, SortView view, List<SortRule> rules)
{
SortInventory? inv = _c.LastInventory;
_counts = RuleCounts(rules, view, inv, _preview);
if (_undo != null)
{
w.SmallButton("Undo: " + _undoWhat, "undo", Undo);
w.Tooltip("Put the rules back as they were before that change. Nothing moves.");
}
DrawLayoutNote(w);
if (rules.Count == 0)
{
w.PushStyleColor(UiFormat.ColText, UiColors.Soft);
w.TextWrapped("No rules yet. A starter layout fills them in one click (you see where things go first), "
+ "or pick a kind of item for each pack below.");
w.PopStyleColor();
w.SmallButton("Pick a starter layout", "go.layouts", () => ShowTab(PanelTab.Layouts));
w.Tooltip("Shows the starter layouts: Everyday, Hunting, Crafting and Just the basics");
}
w.TextDisabled($"Main pack ({view.Main.Used}/{view.Main.Capacity}){OrderNote(view, view.Main, " - ")}");
w.Tooltip("Items no rule names stay in the main pack");
string numbering = NumberingNote(view);
if (numbering.Length > 0)
{
w.PushStyleColor(UiFormat.ColText, UiColors.Grey);
w.TextWrapped(numbering);
w.PopStyleColor();
}
Dictionary<int, List<SortRule>> byPack = Group(rules, view);
Dictionary<int, List<string>> conflicts = Conflicts(rules, view);
for (int i = 1; i <= view.Packs.Count; i++)
DrawPack(w, view, inv, rules, i, byPack.TryGetValue(i, out List<SortRule>? list) ? list : new List<SortRule>(),
conflicts.TryGetValue(i, out List<string>? c) ? c : null);
if (byPack.TryGetValue(0, out List<SortRule>? missing)) DrawMissing(w, view, rules, missing);
if (view.Packs.Count == 0) w.TextDisabled("No side packs: items stay in the main pack.");
}
// ── Pack sections ───────────────────────────────────────────────────────
private void DrawPack(UiWindow w, SortView view, SortInventory? inv, List<SortRule> rules, int number, List<SortRule> packRules, List<string>? conflicts)
{
PackLine p = view.Packs[number - 1];
bool full = view.Full.Contains(number);
List<string> warnings = FallbackWarnings(view, number);
if (conflicts != null) warnings.AddRange(conflicts);
bool attention = full || warnings.Count > 0;
if (attention) w.PushStyleColor(UiFormat.ColText, UiColors.Amber);
bool open = w.CollapsingHeader($"Pack {number}: {p.Label}", $"pack.{p.Id:X8}", defaultOpen: true);
if (attention) w.PopStyleColor();
w.Tooltip(PackHeaderTooltip(view, number));
if (!open) return;
w.Indent(RowIndent);
DrawWhere(w, view, p, number);
DrawContents(w, inv, p);
if (full) w.TextColored(UiColors.Amber, "This pack is full: items for it wait where they are");
foreach (string line in warnings) w.TextColored(UiColors.Amber, line);
packRules.Sort(SortRules.CompareForList);
if (packRules.Count > 0)
{
w.TextDisabled("Goes here:");
foreach (SortRule r in packRules) DrawRule(w, view, rules, r);
}
else w.TextDisabled("Nothing goes here yet.");
uint id = p.Id;
DrawKindPicker(w, view, rules, number, packRules);
w.SmallButton("+ Add rule", $"add.{id:X8}", () => AddRule(rules, view, number));
w.Tooltip("A new rule for this pack, to fill in: pick kinds of items, or type part of a name (\"Opal\"). A name beats a kind.");
w.SameLine();
w.SmallButton("+ Add selected", $"addsel.{id:X8}", () => AddSelected(number));
w.Tooltip("Select an item in your inventory, then press this: its name goes into this pack's rules (\"name has ...\"), "
+ "so items called that go here. A count like \"(100)\" is left out. It says if the pack already takes the item or another pack does.");
// A second line: these two empty or change the pack, so they sit apart from the adds.
w.SmallButton("Empty this pack", $"unpack.{id:X8}", () => _c.StartUnpack(number));
w.Tooltip($"Move everything in pack {number} into the main pack. Turns auto-sort off first, so nothing moves back. Also: /rsort unpack {number}");
int on = 0;
foreach (SortRule r in packRules) if (r.On && !r.IsEmpty) on++;
if (on >= 2)
{
w.SameLine();
w.SmallButton("Merge rules", $"merge.{id:X8}", () => MergeRules(rules, packRules));
w.Tooltip("Make this pack's rules (the ones that are on) one rule with all their kinds and names");
}
if (_notePack == id && _note.Length > 0 && Now() < _noteUntilMs)
{
w.PushStyleColor(UiFormat.ColText, _noteGood ? UiColors.Green : UiColors.Amber);
w.TextWrapped(_note);
w.PopStyleColor();
}
string order = OrderNote(view, p, "");
if (order.Length > 0) w.TextDisabled(order);
w.Unindent(RowIndent);
}
/// <summary>The pack's first line: its icon, Select in game, and where it is in the pack column.</summary>
private void DrawWhere(UiWindow w, SortView view, PackLine p, int number)
{
if (Icons())
{
w.Image(UiFormat.IconKindObject, p.Id, WhereIcon, WhereIcon);
w.SameLine();
}
if (CanSelect())
{
uint id = p.Id;
string name = p.Name;
w.SmallButton("Select in game", $"select.{id:X8}", () =>
{
_selectedPack = id;
_selectNote = SelectInGame(id) ? $"Selected: the game has your {name} selected now" : "The game didn't take the selection";
});
w.Tooltip(SelectTooltip);
w.SameLine();
}
w.PushStyleColor(UiFormat.ColText, UiColors.Grey);
w.TextWrapped(WhereText(view, p, number));
if (_selectedPack == p.Id && _selectNote.Length > 0) w.TextWrapped(_selectNote);
w.PopStyleColor();
}
/// <summary>What is in the pack, as a strip of item icons (the commonest kinds; each icon's tooltip names it).</summary>
private void DrawContents(UiWindow w, SortInventory? inv, PackLine p)
{
if (!Icons() || inv == null) return;
int index = inv.IndexOf(p.Id);
if (index == 0) return;
SortPack pack = inv.Packs[index - 1];
if (pack.Items.Count == 0) return;
List<(SortItem First, int Count)> kinds = Kinds(pack, KindIcons);
for (int i = 0; i < kinds.Count; i++)
{
if (i > 0) w.SameLine();
w.Image(UiFormat.IconKindObject, kinds[i].First.Id, KindIcon, KindIcon);
string name = kinds[i].First.Name.Length > 0 ? kinds[i].First.Name : "(not known yet)";
w.Tooltip(kinds[i].Count > 1 ? $"{name}: {kinds[i].Count}" : name);
}
}
/// <summary>
/// "Add a kind of item...": the kind goes to this pack. If another pack's rule had it, it is
/// taken from there (pack-centric: what goes here is what this pack says), with Undo.
/// </summary>
private void DrawKindPicker(UiWindow w, SortView view, List<SortRule> rules, int number, List<SortRule> packRules)
{
var offered = new List<int>();
var labels = new List<string> { "Add a kind of item..." };
foreach (int cls in ObjectClasses.Choices)
{
bool here = false;
foreach (SortRule r in packRules) if (r.On && r.HasClass(cls)) { here = true; break; }
if (here) continue;
offered.Add(cls);
labels.Add(ObjectClasses.Label(cls));
}
if (offered.Count == 0) return;
uint id = view.Packs[number - 1].Id;
w.Combo("", $"kind.{id:X8}", 0, labels, v =>
{
if (v >= 1 && v <= offered.Count) SendKindHere(rules, view, number, offered[v - 1]);
});
w.Tooltip("Pick a kind of item to send to this pack. If another pack took that kind, it comes here instead (Undo puts it back).");
}
/// <summary>Sends class <paramref name="cls"/> to side pack <paramref name="number"/>: into its first rule with room, taken out of other packs' rules.</summary>
internal void SendKindHere(List<SortRule> rules, SortView view, int number, int cls)
{
var before = Snapshot(rules);
var taken = new List<int>();
foreach (SortRule r in rules)
{
int pack = ShownPack(view, r);
if (pack == number || !r.On || !r.HasClass(cls)) continue;
r.RemoveClass(cls);
if (pack > 0 && !taken.Contains(pack)) taken.Add(pack);
}
rules.RemoveAll(r => r.IsEmpty && !ReferenceEquals(r, _selected) && before.Exists(b => b.Uid == r.Uid && !b.Copy.IsEmpty));
SortRule? target = null;
foreach (SortRule r in rules)
if (ShownPack(view, r) == number && r.On && r.Classes.Count > 0 && r.Classes.Count < SortRule.MaxClasses) { target = r; break; }
if (target == null)
foreach (SortRule r in rules)
if (ShownPack(view, r) == number && r.On && r.Classes.Count < SortRule.MaxClasses) { target = r; break; }
if (target == null)
{
if (rules.Count >= SortStore.MaxRules) return;
target = new SortRule();
SetPack(target, view, number);
rules.Add(target);
}
target.AddClass(cls);
string label = ObjectClasses.Plural(cls);
KeepUndo(before, $"{label} to pack {number}");
_notePack = view.Packs[number - 1].Id;
_note = taken.Count > 0
? $"{label} now go here (taken from {(taken.Count == 1 ? "pack " + taken[0] : "packs " + string.Join(", ", taken))}). Nothing has moved yet."
: $"{label} now go here. Nothing has moved yet.";
_noteGood = true;
_noteUntilMs = Now() + NoteMs;
_save();
}
private void DrawMissing(UiWindow w, SortView view, List<SortRule> rules, List<SortRule> missing)
{
w.PushStyleColor(UiFormat.ColText, UiColors.Amber);
bool open = w.CollapsingHeader($"Rules for packs you don't have ({missing.Count})", "missing", defaultOpen: true);
w.PopStyleColor();
if (!open) return;
w.Indent(RowIndent);
w.TextWrapped("Their items stay where they are. Pick one of your packs in a rule's editor, or remove the rule.");
var groups = new List<List<SortRule>>();
foreach (SortRule r in missing)
{
List<SortRule>? g = groups.Find(x => SamePackOf(x[0], r));
if (g == null) groups.Add(g = new List<SortRule>());
g.Add(r);
}
foreach (List<SortRule> g in groups)
{
SortRule first = g[0];
w.TextColored(UiColors.Amber, first.PackNote.Length > 0 ? $"A pack you don't have (it was {first.PackNote}):" : $"Pack {first.Pack}, which you don't have:");
g.Sort(SortRules.CompareForList);
foreach (SortRule r in g) DrawRule(w, view, rules, r);
}
w.Unindent(RowIndent);
}
private static bool SamePackOf(SortRule a, SortRule b) =>
a.PackId != 0 || b.PackId != 0 ? a.PackId == b.PackId : a.Pack == b.Pack;
// ── Rules ───────────────────────────────────────────────────────────────
private void DrawRule(UiWindow w, SortView view, List<SortRule> rules, SortRule r)
{
string k = "r" + r.Uid;
w.Checkbox("", k + ".on", r.On, v => { r.On = v; _save(); });
w.Tooltip(r.On ? "Rule on: click to turn it off" : "Rule off: click to turn it on");
w.SameLine();
bool selected = ReferenceEquals(_selected, r);
w.Selectable(Shown(SortRules.Describe(r)) + CountWords(r), k + ".row", selected, () =>
{
_selected = ReferenceEquals(_selected, r) ? null : r;
_nameDraft = string.Empty;
});
w.Tooltip(selected ? "Click to close the editor" : "Click to change this rule");
if (selected) DrawEditor(w, view, rules, r);
}
/// <summary>" (12 here, 3 to move in)" after a rule's row, or nothing.</summary>
private string CountWords(SortRule r)
{
if (!r.On || !_counts.TryGetValue(r, out var c) || (c.Here == 0 && c.Coming == 0)) return string.Empty;
if (c.Coming == 0) return $" ({c.Here} here)";
return c.Here == 0 ? $" ({c.Coming} to move in)" : $" ({c.Here} here, {c.Coming} to move in)";
}
private void DrawEditor(UiWindow w, SortView view, List<SortRule> rules, SortRule r)
{
string k = "r" + r.Uid;
w.Indent(EditorIndent);
List<int> classes = SortRules.SortedClasses(r);
if (classes.Count > 0)
{
w.TextDisabled("Classes:");
for (int i = 0; i < classes.Count; i++)
{
if (i % ChipsPerLine != 0 || i == 0) w.SameLine();
int cls = classes[i];
string label = ObjectClasses.Label(cls);
w.SmallButton(label + " x", $"{k}.c{cls}", () => { r.RemoveClass(cls); _save(); });
w.Tooltip($"Take {label} out of this rule");
}
}
var offered = new List<int>();
var labels = new List<string> { "Add a class..." };
foreach (int cls in ObjectClasses.Choices)
{
if (r.HasClass(cls)) continue;
offered.Add(cls);
labels.Add(ObjectClasses.Label(cls));
}
if (offered.Count > 0 && r.Classes.Count < SortRule.MaxClasses)
w.Combo("Class", k + ".addclass", 0, labels, v =>
{
if (v >= 1 && v <= offered.Count && r.AddClass(offered[v - 1])) _save();
});
List<string> names = SortRules.SortedNames(r);
if (names.Count > 0)
{
w.TextDisabled("Names:");
for (int i = 0; i < names.Count; i++)
{
if (i % ChipsPerLine != 0 || i == 0) w.SameLine();
string name = names[i];
w.SmallButton($"\"{Shown(name)}\" x", $"{k}.n{i}", () => { r.RemoveName(name); _save(); });
w.Tooltip($"Take \"{name}\" out of this rule");
}
}
if (r.Names.Count < SortRule.MaxNames)
{
w.InputText("Name has", k + ".draft", _nameDraft, SortRule.MaxNameLength, (text, enter) =>
{
_nameDraft = text;
if (enter) AddDraft(r);
}, UiFormat.InputEnterReturnsTrue);
w.Tooltip("Part of an item's name, any case: \"Opal\" takes every item with Opal in its name. Enter or Add puts it in the rule.");
w.SameLine();
w.SmallButton("Add", k + ".addname", () => AddDraft(r));
}
int shown = ShownPack(view, r);
w.Combo("Pack", k + ".pack", Math.Max((shown > 0 ? shown : r.Pack) - 1, 0), PackChoices(view, r.Pack), v =>
{
SetPack(r, view, v + 1);
_save();
});
w.Tooltip("Where this rule sends items. " + PackTooltip(view));
w.SmallButton("Remove rule", k + ".remove", () =>
{
KeepUndo(Snapshot(rules), "rule removed");
rules.Remove(r);
if (ReferenceEquals(_selected, r)) _selected = null;
_save();
});
w.Tooltip("Take this rule out (Undo brings it back). Items it sent stay where they are.");
w.Unindent(EditorIndent);
}
private void AddDraft(SortRule r)
{
if (r.AddName(_nameDraft)) _save();
_nameDraft = string.Empty;
}
/// <summary>
/// "+ Add selected" (and /rsort add): the selected item's name goes into side pack
/// <paramref name="number"/>'s rules (<see cref="AddSelectedRules"/>); what happened is shown under the pack's buttons.
/// </summary>
public AddOutcome AddSelected(int number)
{
SortView view = _c.Planner.View;
AddOutcome o = AddSelectedRules.Apply(_c.Data.Rules, view, number, ReadSelected());
if (o.Rule != null)
{
_selected = o.Rule;
_nameDraft = string.Empty;
_save();
}
_notePack = number >= 1 && number <= view.Packs.Count ? view.Packs[number - 1].Id : 0;
_note = o.Message;
_noteGood = o.Status == AddStatus.Added;
_noteUntilMs = Now() + NoteMs;
if (_tab != PanelTab.Packs) ShowTab(PanelTab.Packs);
return o;
}
private void AddRule(List<SortRule> rules, SortView view, int number)
{
if (rules.Count >= SortStore.MaxRules) return;
var added = new SortRule();
SetPack(added, view, number);
rules.Add(added);
_selected = added;
_nameDraft = string.Empty;
_save();
}
/// <summary>The pack's rules that are on become one (the first A-Z keeps its place in the list, so a tie still goes its way).</summary>
private void MergeRules(List<SortRule> rules, List<SortRule> packRules)
{
var before = Snapshot(rules);
SortRule? keep = null;
foreach (SortRule r in rules)
{
if (!packRules.Contains(r) || !r.On || r.IsEmpty) continue;
if (keep == null) { keep = r; continue; }
keep.TakeEntriesOf(r);
}
if (keep == null) return;
rules.RemoveAll(r => !ReferenceEquals(r, keep) && packRules.Contains(r) && r.On && !r.IsEmpty);
KeepUndo(before, "rules merged");
_selected = keep;
_save();
}
// ── Undo ────────────────────────────────────────────────────────────────
private readonly record struct Kept(int Uid, SortRule Copy);
private static List<Kept> Snapshot(List<SortRule> rules) => rules.ConvertAll(r => new Kept(r.Uid, r.Clone()));
private void KeepUndo(List<Kept> before, string what)
{
_undo = before.ConvertAll(k => k.Copy);
_undoWhat = what;
}
/// <summary>The rules as they were before the last big change (nothing moves).</summary>
internal void Undo()
{
if (_undo == null) return;
List<SortRule> rules = _c.Data.Rules;
rules.Clear();
foreach (SortRule r in _undo) rules.Add(r.Clone());
_undo = null;
_undoWhat = string.Empty;
_selected = null;
_layoutNote = "Rules put back as they were.";
_layoutNoteGood = true;
_layoutNoteUntilMs = Now() + NoteMs;
_save();
}
}

View file

@ -0,0 +1,40 @@
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Ui;
namespace RynthCore.Plugin.RynthSort.Views;
// The Settings page.
internal sealed partial class SortPanel
{
private void DrawSettingsTab(UiWindow w)
{
SortSettings s = _c.Data.Settings;
w.SeparatorText("When items move");
w.Checkbox("Sort during fights", "combat", s.SortInCombat, v => { s.SortInCombat = v; _save(); });
w.Tooltip("Off: nothing moves while RynthAi fights. On: moves go between its attacks and casts (never while one is unanswered)");
w.SliderInt("Settle (s)", "settle", s.SettleSec, SortSettings.SettleMin, SortSettings.SettleMax, v => { s.SettleSec = v; _save(); });
w.Tooltip("How long a new item sits in the main pack before auto-sort moves it");
w.SliderInt("Leave alone (min)", "hold", s.HoldMin, SortSettings.HoldMinMin, SortSettings.HoldMinMax, v => { s.HoldMin = v; _save(); });
w.Tooltip("Items you use stay where they are this long: ones you move, select, drag, take off or pick up. 0 turns it off.");
w.PushStyleColor(UiFormat.ColText, UiColors.Grey);
w.TextWrapped(s.HoldMin == 0
? "Off: an item you take out of its pack goes back at the next sort."
: $"An item you move, select, drag, take off or pick up stays put for {Count(s.HoldMin, "minute")} (Empty side packs and Put back still move it).");
w.PopStyleColor();
w.SliderInt("Gap (ms)", "gap", s.GapMs, SortSettings.GapMin, SortSettings.GapMax, v => { s.GapMs = v; _save(); });
w.Tooltip("Auto-sort's pause between two moves, to leave the bot room. Sort now, Clean and Empty don't wait.");
w.SeparatorText("Inside packs");
w.Checkbox("Put items in order inside packs", "order", s.OrderInPacks, v => { s.OrderInPacks = v; _save(); });
w.Tooltip("Like items side by side, A-Z by name, in every pack. Off: items only go to their packs (and stacks are still joined).");
w.Checkbox("Group by kind first", "orderkind", s.OrderKindFirst, v => { s.OrderKindFirst = v; _save(); });
w.Tooltip("Order by kind (Armor, Gem, Spell Component ...) and then A-Z by name, instead of A-Z by name only");
if (!(_c.Abilities.ReadOrder && _c.Abilities.PlaceMoves))
w.TextWrapped("This RynthCore can't read the order inside packs (it needs plugin API 80): items go to their packs but aren't put in order.");
w.SeparatorText("Tools");
w.Button("Empty side packs", "job.unpack", () => _c.StartUnpack(null));
w.Tooltip("Move everything from your side packs into the main pack. Turns auto-sort off first, so nothing moves back. Also: /rsort unpack");
w.TextDisabled("Chat: /rsort on | off | now | clean | back | unpack [pack] | add <pack> | status");
}
}

View file

@ -6,17 +6,31 @@ using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthSort.Views;
/// <summary>The window's four pages.</summary>
internal enum PanelTab { Packs, Moves, Layouts, Settings }
/// <summary>
/// The RynthSort window: the auto-sort box and status, the job buttons, then one collapsing
/// section per side pack ("Pack 1: Sack (12/24) - Components", top pack first) holding a line
/// that says which pack in the game it is (its icon, "Select in game", and its place in the
/// pack column), that pack's warnings and its rules (A-Z), a section for rules whose pack isn't
/// carried, and the settings. A rule is one row (on/off box, its classes and names); selecting it opens its
/// editor beneath: the classes and names as chips (click one to take it out), a class picker and
/// a name box to add, the pack it sends to, and Remove. Recorded on the pump thread, replayed by
/// the engine.
/// The RynthSort window (redesigned 2026-11-26 after #rynth-issues "The bag sort feature is lacking
/// in UX"). Always on top: the Auto-sort box with one coloured line that says what it is doing
/// (off, on and tidy, moving, paused and why), a line or two on what waits and what is left alone,
/// the Sort now / Clean packs / Put back buttons and any warning. Below, four pages:
/// <list type="bullet">
/// <item>Packs (SortPanel.Packs.cs): "what goes in this pack", one section per side pack, top pack
/// first: which pack in the game it is (icon, Select in game, its place in the column), a strip of
/// what is in it, its rules with how many items they hold and bring, a kind picker, + Add rule,
/// + Add selected, Empty this pack, Merge rules; rules for packs not carried; an Undo for the last
/// big rule change.</item>
/// <item>Moves (SortPanel.Moves.cs): what a sort would move now (a table at op level 3), what waits,
/// the items left alone because the player used them (and "Sort them too"), the last moves and Put back.</item>
/// <item>Layouts (SortPanel.Layouts.cs): the starter layouts, fitted to the packs carried and
/// previewed before anything changes.</item>
/// <item>Settings (SortPanel.Settings.cs): when to sort, how long to leave used items alone, order
/// inside packs, Empty side packs.</item>
/// </list>
/// It works at script-window op level 2 (released engines); with op level 3 the status line is bold
/// and the move lists are tables. Recorded on the pump thread, replayed by the engine.
/// </summary>
internal sealed class SortPanel
internal sealed partial class SortPanel
{
private const float RowIndent = 6f, EditorIndent = 22f;
private const int ChipsPerLine = 3;
@ -32,13 +46,30 @@ internal sealed class SortPanel
public Func<string> Character = () => string.Empty;
/// <summary>The engine draws item icons in script windows (op level 2).</summary>
public Func<bool> Icons = () => false;
/// <summary>The engine's script-window op level (UiGetInfo; 0 when unknown). 3 adds tables and fonts.</summary>
public Func<int> OpLevel = () => 0;
/// <summary>The engine can select objects (else no Select button).</summary>
public Func<bool> CanSelect = () => false;
/// <summary>Selects an object in the game (Host.SelectItem); false when it couldn't.</summary>
public Func<uint, bool> SelectInGame = _ => false;
/// <summary>The item selected in the game, read against the packs now (the plugin's host read; "unavailable" by default).</summary>
public Func<SelectedItem> ReadSelected = () => SelectedItem.Of(SelectionKind.Unavailable);
/// <summary>The clock for notes that fade (the tests set it).</summary>
public Func<long> Now = () => Environment.TickCount64;
private uint _selectedPack;
private string _selectNote = string.Empty;
private const long NoteMs = 60_000;
private uint _notePack;
private string _note = string.Empty;
private bool _noteGood;
private long _noteUntilMs;
private PanelTab _tab = PanelTab.Packs;
private bool _tabChosen;
private string _forCharacter = string.Empty;
/// <summary>This pass's preview of a sort (from the last read), or null before the first read.</summary>
private SortPreview? _preview;
public SortPanel(SortController c, Action save)
{
@ -48,307 +79,206 @@ internal sealed class SortPanel
/// <summary>The rule whose editor is open, or null.</summary>
public SortRule? Selected => _selected;
/// <summary>The page shown.</summary>
public PanelTab Tab => _tab;
private bool Rich => OpLevel() >= UiFormat.OpLevelRich;
public void Draw(UiWindow w)
{
if (Character().Length == 0)
string who = Character();
if (who.Length == 0)
{
w.TextDisabled("Log in to sort your packs.");
return;
}
SortSettings s = _c.Data.Settings;
if (!string.Equals(who, _forCharacter, StringComparison.Ordinal)) ForgetCharacter(who);
List<SortRule> rules = _c.Data.Rules;
if (_selected != null && !rules.Contains(_selected)) _selected = null;
SortView view = _c.Planner.View;
w.Checkbox("Auto-sort", "auto", s.Auto, v => _c.SetAuto(v));
w.Tooltip("Keeps every pack tidy: new items go to their pack after the settle time, items in the wrong pack move to theirs, "
+ "stacks of one kind are joined and items are put in order (A-Z) inside each pack");
w.SameLine();
w.TextColored(_c.Paused ? UiColors.Amber : UiColors.Grey, _c.Status);
if (view.Waiting > 0)
if (!_tabChosen)
{
w.SameLine();
w.TextDisabled($"({view.Waiting} waiting)");
// A character with no rules yet starts on the layouts: the quickest way to a sensible setup.
_tab = rules.Count == 0 ? PanelTab.Layouts : PanelTab.Packs;
_tabChosen = true;
}
SortView view = _c.Planner.View;
SortInventory? inv = _c.LastInventory;
_preview = inv != null ? SortPreview.Build(inv, rules, _c.CurrentOptions, _c.IsHeld) : null;
DrawStatus(w, view, rules);
DrawTabs(w);
switch (_tab)
{
case PanelTab.Moves: DrawMovesTab(w, view); break;
case PanelTab.Layouts: DrawLayoutsTab(w, rules); break;
case PanelTab.Settings: DrawSettingsTab(w); break;
default: DrawPacksTab(w, view, rules); break;
}
}
/// <summary>Another character: the window starts fresh (its page, picks and undo are the last one's).</summary>
private void ForgetCharacter(string who)
{
_forCharacter = who;
_tabChosen = false;
_selected = null;
_nameDraft = string.Empty;
_layoutKey = null;
_layoutNote = string.Empty;
_undo = null;
_undoWhat = string.Empty;
_note = _selectNote = string.Empty;
}
/// <summary>Shows a page ("Pick a layout" and the like); the next pass draws it.</summary>
internal void ShowTab(PanelTab tab)
{
_tab = tab;
_tabChosen = true;
}
// ── Always on top ───────────────────────────────────────────────────────
private void DrawStatus(UiWindow w, SortView view, List<SortRule> rules)
{
SortSettings s = _c.Data.Settings;
w.Checkbox("Auto-sort", "auto", s.Auto, v => _c.SetAuto(v));
w.Tooltip(AutoTooltip);
w.SameLine();
var (text, color) = Headline(_c, view, rules.Count == 0);
// Wrapped beside the box (a narrow window wraps it in a column of its own, never off the edge).
if (Rich) w.PushFont(UiFormat.FontBold);
w.PushStyleColor(UiFormat.ColText, color);
w.TextWrapped(text);
w.PopStyleColor();
if (Rich) w.PopFont();
w.Tooltip(HeadlineTooltip);
List<string> details = Details(_c, view, _preview, rules.Count == 0);
if (details.Count > 0)
{
w.PushStyleColor(UiFormat.ColText, UiColors.Soft);
foreach (string line in details) w.TextWrapped(line);
w.PopStyleColor();
}
w.Button("Sort now", "job.all", () => _c.StartJob(SortScope.All));
w.Tooltip("Sort every pack now, without waiting for new items to settle");
w.Tooltip("Sort every pack once, now: items go to their packs, stacks are joined and packs put in order. "
+ "It doesn't wait for new items to settle; items you used lately are still left alone.");
w.SameLine();
w.Button("Clean packs", "job.clean", () => _c.StartJob(SortScope.Clean));
w.Tooltip("Sort now, and side-pack items no rule wants go back to the main pack");
w.SameLine();
w.Button("Empty side packs", "job.unpack", () => _c.StartUnpack(null));
w.Tooltip("Move everything from your side packs into the main pack. Turns auto-sort off first, so nothing moves back.");
int back = _c.PutBackCount;
if (back > 0)
{
w.SameLine();
w.Button("Put back", "job.back", () => _c.StartPutBack());
w.Tooltip($"Undo the last sort: the {Count(back, "item")} it moved go back where they were. "
+ "Turns auto-sort off first, so nothing moves again. Also: /rsort back");
}
w.TextDisabled($"Main pack ({view.Main.Used}/{view.Main.Capacity}){OrderNote(view, view.Main, " - ")}");
w.Tooltip("Items no rule names stay in the main pack");
if (view.MainFull) w.TextColored(UiColors.Amber, "The main pack is full");
if (s.Auto && _c.LastBot is RynthAiActivity bot && (bot & RynthAiActivity.AutoCram) != 0 && (bot & RynthAiActivity.MacroRunning) != 0)
w.TextColored(UiColors.Amber, "RynthAi's AutoCram also moves loot out of the main pack; turn one of them off");
foreach (string warning in Warnings()) w.TextColored(UiColors.Amber, warning);
string numbering = NumberingNote(view);
if (numbering.Length > 0)
{
w.PushStyleColor(UiFormat.ColText, UiColors.Grey);
w.TextWrapped(numbering);
w.PopStyleColor();
}
Dictionary<int, List<SortRule>> byPack = Group(rules, view);
Dictionary<int, List<string>> conflicts = Conflicts(rules, view);
for (int i = 1; i <= view.Packs.Count; i++)
DrawPack(w, view, rules, i, byPack.TryGetValue(i, out List<SortRule>? list) ? list : new List<SortRule>(),
conflicts.TryGetValue(i, out List<string>? c) ? c : null);
if (byPack.TryGetValue(0, out List<SortRule>? missing)) DrawMissing(w, view, rules, missing);
if (view.Packs.Count == 0) w.TextDisabled("No side packs: items stay in the main pack.");
if (w.CollapsingHeader("Settings", "settings"))
{
w.SliderInt("Settle (s)", "settle", s.SettleSec, SortSettings.SettleMin, SortSettings.SettleMax, v => { s.SettleSec = v; _save(); });
w.Tooltip("How long a new item sits in the main pack before it is moved");
w.SliderInt("Gap (ms)", "gap", s.GapMs, SortSettings.GapMin, SortSettings.GapMax, v => { s.GapMs = v; _save(); });
w.Tooltip("Auto-sort's pause between two moves, to leave the bot room. Sort now, Clean and Empty don't wait.");
w.Checkbox("Sort during fights", "combat", s.SortInCombat, v => { s.SortInCombat = v; _save(); });
w.Tooltip("Off: nothing moves while RynthAi fights. On: moves go between its attacks and casts (never while one is unanswered)");
w.Checkbox("Put items in order inside packs", "order", s.OrderInPacks, v => { s.OrderInPacks = v; _save(); });
w.Tooltip("Like items side by side, A-Z by name, in every pack. Off: items only go to their packs (and stacks are still joined).");
w.Checkbox("Group by kind first", "orderkind", s.OrderKindFirst, v => { s.OrderKindFirst = v; _save(); });
w.Tooltip("Order by kind (Armor, Gem, Spell Component ...) and then A-Z by name, instead of A-Z by name only");
if (!(_c.Abilities.ReadOrder && _c.Abilities.PlaceMoves))
w.TextWrapped("This RynthCore can't read the order inside packs (it needs plugin API 80): items go to their packs but aren't put in order.");
}
if (_c.Log.Count > 0)
{
w.Separator();
foreach (string line in _c.Log) w.TextDisabled(line);
}
}
// ── Pack sections ───────────────────────────────────────────────────────
private void DrawPack(UiWindow w, SortView view, List<SortRule> rules, int number, List<SortRule> packRules, List<string>? conflicts)
private void DrawTabs(UiWindow w)
{
PackLine p = view.Packs[number - 1];
bool full = view.Full.Contains(number);
List<string> warnings = FallbackWarnings(view, number);
if (conflicts != null) warnings.AddRange(conflicts);
bool attention = full || warnings.Count > 0;
if (attention) w.PushStyleColor(UiFormat.ColText, UiColors.Amber);
bool open = w.CollapsingHeader($"Pack {number}: {p.Label}", $"pack.{p.Id:X8}", defaultOpen: true);
if (attention) w.PopStyleColor();
w.Tooltip(PackHeaderTooltip(view, number));
if (!open) return;
w.Indent(RowIndent);
DrawWhere(w, view, p, number);
if (full) w.TextColored(UiColors.Amber, "This pack is full: items for it wait where they are");
foreach (string line in warnings) w.TextColored(UiColors.Amber, line);
packRules.Sort(SortRules.CompareForList);
foreach (SortRule r in packRules) DrawRule(w, view, rules, r);
if (packRules.Count == 0) w.TextDisabled("No rules send items here.");
uint id = p.Id;
w.SmallButton("+ Add rule", $"add.{id:X8}", () => AddRule(rules, view, number));
w.Tooltip("A rule sends items to this pack: items of any of its classes, or with any of its names in their name. A name beats a class.");
TabButton(w, "Packs", "tab.packs", PanelTab.Packs, "What goes in each pack: its rules, what is in it, and where it is in the game");
w.SameLine();
w.SmallButton("Empty this pack", $"unpack.{id:X8}", () => _c.StartUnpack(number));
w.Tooltip($"Move everything in pack {number} into the main pack. Turns auto-sort off first, so nothing moves back. Also: /rsort unpack {number}");
int on = 0;
foreach (SortRule r in packRules) if (r.On && !r.IsEmpty) on++;
if (on >= 2)
{
w.SameLine();
w.SmallButton("Merge rules", $"merge.{id:X8}", () => MergeRules(rules, packRules));
w.Tooltip("Make this pack's rules (the ones that are on) one rule with all their classes and names");
}
string order = OrderNote(view, p, "");
if (order.Length > 0) w.TextDisabled(order);
w.Unindent(RowIndent);
}
/// <summary>The pack's first line: its icon, Select in game, and where it is in the pack column.</summary>
private void DrawWhere(UiWindow w, SortView view, PackLine p, int number)
{
if (Icons())
{
w.Image(UiFormat.IconKindObject, p.Id, WhereIcon, WhereIcon);
w.SameLine();
}
if (CanSelect())
{
uint id = p.Id;
string name = p.Name;
w.SmallButton("Select in game", $"select.{id:X8}", () =>
{
_selectedPack = id;
_selectNote = SelectInGame(id) ? $"Selected: the game has your {name} selected now" : "The game didn't take the selection";
});
w.Tooltip(SelectTooltip);
w.SameLine();
}
w.TextDisabled(WhereText(view, p, number));
if (_selectedPack == p.Id && _selectNote.Length > 0) w.TextDisabled(_selectNote);
}
private const float WhereIcon = 20f;
internal const string SelectTooltip =
"Selects this pack in the game, as clicking it in your inventory would, so the game shows you which one it is "
+ "(its name in the selection bar). Nothing moves.";
private void DrawMissing(UiWindow w, SortView view, List<SortRule> rules, List<SortRule> missing)
{
w.PushStyleColor(UiFormat.ColText, UiColors.Amber);
bool open = w.CollapsingHeader($"Rules for packs you don't have ({missing.Count})", "missing", defaultOpen: true);
w.PopStyleColor();
if (!open) return;
w.Indent(RowIndent);
w.TextWrapped("Their items stay where they are. Pick one of your packs in a rule's editor, or remove the rule.");
var groups = new List<List<SortRule>>();
foreach (SortRule r in missing)
{
List<SortRule>? g = groups.Find(x => SamePackOf(x[0], r));
if (g == null) groups.Add(g = new List<SortRule>());
g.Add(r);
}
foreach (List<SortRule> g in groups)
{
SortRule first = g[0];
w.TextColored(UiColors.Amber, first.PackNote.Length > 0 ? $"A pack you don't have (it was {first.PackNote}):" : $"Pack {first.Pack}, which you don't have:");
g.Sort(SortRules.CompareForList);
foreach (SortRule r in g) DrawRule(w, view, rules, r);
}
w.Unindent(RowIndent);
}
private static bool SamePackOf(SortRule a, SortRule b) =>
a.PackId != 0 || b.PackId != 0 ? a.PackId == b.PackId : a.Pack == b.Pack;
// ── Rules ───────────────────────────────────────────────────────────────
private void DrawRule(UiWindow w, SortView view, List<SortRule> rules, SortRule r)
{
string k = "r" + r.Uid;
w.Checkbox("", k + ".on", r.On, v => { r.On = v; _save(); });
w.Tooltip(r.On ? "Rule on: click to turn it off" : "Rule off: click to turn it on");
int moves = _preview?.Moves.Count ?? 0;
TabButton(w, moves > 0 ? $"Moves ({moves})" : "Moves", "tab.moves", PanelTab.Moves,
"What a sort would move now, the items left alone because you used them, and the last moves");
w.SameLine();
bool selected = ReferenceEquals(_selected, r);
w.Selectable(Shown(SortRules.Describe(r)), k + ".row", selected, () =>
{
_selected = ReferenceEquals(_selected, r) ? null : r;
_nameDraft = string.Empty;
});
w.Tooltip(selected ? "Click to close the editor" : "Click to change this rule");
if (selected) DrawEditor(w, view, rules, r);
TabButton(w, "Layouts", "tab.layouts", PanelTab.Layouts, "Ready-made rules for typical packs: see where things would go, then use one in a click");
w.SameLine();
TabButton(w, "Settings", "tab.settings", PanelTab.Settings, "When to sort, how long to leave items you use alone, order inside packs");
w.Separator();
}
private void DrawEditor(UiWindow w, SortView view, List<SortRule> rules, SortRule r)
private void TabButton(UiWindow w, string label, string id, PanelTab tab, string tip)
{
string k = "r" + r.Uid;
w.Indent(EditorIndent);
List<int> classes = SortRules.SortedClasses(r);
if (classes.Count > 0)
{
w.TextDisabled("Classes:");
for (int i = 0; i < classes.Count; i++)
{
if (i % ChipsPerLine != 0 || i == 0) w.SameLine();
int cls = classes[i];
string label = ObjectClasses.Label(cls);
w.SmallButton(label + " x", $"{k}.c{cls}", () => { r.RemoveClass(cls); _save(); });
w.Tooltip($"Take {label} out of this rule");
}
}
var offered = new List<int>();
var labels = new List<string> { "Add a class..." };
foreach (int cls in ObjectClasses.Choices)
{
if (r.HasClass(cls)) continue;
offered.Add(cls);
labels.Add(ObjectClasses.Label(cls));
}
if (offered.Count > 0 && r.Classes.Count < SortRule.MaxClasses)
w.Combo("Class", k + ".addclass", 0, labels, v =>
{
if (v >= 1 && v <= offered.Count && r.AddClass(offered[v - 1])) _save();
});
List<string> names = SortRules.SortedNames(r);
if (names.Count > 0)
{
w.TextDisabled("Names:");
for (int i = 0; i < names.Count; i++)
{
if (i % ChipsPerLine != 0 || i == 0) w.SameLine();
string name = names[i];
w.SmallButton($"\"{Shown(name)}\" x", $"{k}.n{i}", () => { r.RemoveName(name); _save(); });
w.Tooltip($"Take \"{name}\" out of this rule");
}
}
if (r.Names.Count < SortRule.MaxNames)
{
w.InputText("Name has", k + ".draft", _nameDraft, SortRule.MaxNameLength, (text, enter) =>
{
_nameDraft = text;
if (enter) AddDraft(r);
}, UiFormat.InputEnterReturnsTrue);
w.Tooltip("Part of an item's name, any case: \"Opal\" takes every item with Opal in its name. Enter or Add puts it in the rule.");
w.SameLine();
w.SmallButton("Add", k + ".addname", () => AddDraft(r));
}
int shown = ShownPack(view, r);
w.Combo("Pack", k + ".pack", Math.Max((shown > 0 ? shown : r.Pack) - 1, 0), PackChoices(view, r.Pack), v =>
{
SetPack(r, view, v + 1);
_save();
});
w.Tooltip("Where this rule sends items. " + PackTooltip(view));
w.SmallButton("Remove rule", k + ".remove", () =>
{
rules.Remove(r);
if (ReferenceEquals(_selected, r)) _selected = null;
_save();
});
w.Unindent(EditorIndent);
w.ToggleButton(label, id, _tab == tab, () => ShowTab(tab));
w.Tooltip(tip);
}
private void AddDraft(SortRule r)
internal const string AutoTooltip =
"On: RynthSort keeps your packs tidy by itself. New items go to their pack once they have sat in the main pack for the settle time, "
+ "items in the wrong pack move to theirs, stacks are joined and items are put in order. "
+ "It waits while you loot, trade, use a vendor or cast, and leaves items you used lately alone. Off: nothing moves unless you press Sort now.";
internal const string HeadlineTooltip =
"What RynthSort is doing now. Green: all is well. Blue: moving items. Amber: something is in the way (see the line below). Grey: off.";
// ── Status words (pure, for the tests) ──────────────────────────────────
/// <summary>The coloured line beside the Auto-sort box: what it is doing, in a few words.</summary>
internal static (string Text, uint Color) Headline(SortController c, SortView v, bool noRules)
{
if (r.AddName(_nameDraft)) _save();
_nameDraft = string.Empty;
string status = c.Status;
if (c.Paused) return ("Paused: " + PausedWords(status["paused: ".Length..]), UiColors.Amber);
if (c.Job is SortScope job)
return (job switch
{
SortScope.Unpack => "Emptying side packs",
SortScope.PutBack => "Putting items back",
SortScope.Clean => "Cleaning packs",
_ => "Sorting now",
}, UiColors.Blue);
if (!c.Data.Settings.Auto) return ("Off: nothing moves by itself", UiColors.Grey);
if (status == "sorting") return ("On: moving items", UiColors.Blue);
if (status is "starting" or "reading your packs" or "waiting for the inventory") return ("On: reading your packs", UiColors.Grey);
int stuck = v.WaitFull + v.WaitNoPack + v.WaitMainFull;
if (stuck > 0) return ($"On: {Count(stuck, "item")} can't move", UiColors.Amber);
if (v.WaitSettle > 0)
return ($"On: {Count(v.WaitSettle, "new item")} {(v.WaitSettle == 1 ? "moves" : "move")} in {Seconds(v.NextSettleMs)}", UiColors.Green);
if (noRules) return ("On: no rules yet", UiColors.Amber);
return ("On: all tidy", UiColors.Green);
}
private void AddRule(List<SortRule> rules, SortView view, int number)
/// <summary>The lines under it: what waits and why, what is left alone, what moved last.</summary>
internal static List<string> Details(SortController c, SortView v, SortPreview? p, bool noRules)
{
if (rules.Count >= SortStore.MaxRules) return;
var added = new SortRule();
SetPack(added, view, number);
rules.Add(added);
_selected = added;
_nameDraft = string.Empty;
_save();
var lines = new List<string>();
if (noRules)
lines.Add("No rules yet, so nothing goes to your side packs. Pick a starter layout, or add rules to each pack.");
else if (!c.Data.Settings.Auto && c.Job == null && p != null && !p.Empty)
lines.Add($"{Count(p.Moves.Count, "item")} would move when you sort (see Moves).");
var wait = new List<string>();
if (v.WaitFull > 0) wait.Add($"{Count(v.WaitFull, "item")} {(v.WaitFull == 1 ? "waits" : "wait")} for a full pack");
if (v.WaitNoPack > 0) wait.Add($"{Count(v.WaitNoPack, "item")} for a pack you don't carry");
if (v.WaitMainFull > 0) wait.Add($"{Count(v.WaitMainFull, "item")} for room in the main pack");
if (wait.Count > 0) lines.Add(Capital(string.Join("; ", wait)) + ".");
int held = p?.View.Held.Count ?? v.Held.Count;
if (held > 0) lines.Add($"{Count(held, "item")} left alone because you used {(held == 1 ? "it" : "them")} lately (see Moves).");
if (c.Log.Count > 0) lines.Add("Last: " + c.Log[0]);
return lines;
}
/// <summary>The pack's rules that are on become one (the first A-Z keeps its place in the list, so a tie still goes its way).</summary>
private void MergeRules(List<SortRule> rules, List<SortRule> packRules)
/// <summary>Why it is paused, for a player: "a corpse or chest is open" for "looting".</summary>
internal static string PausedWords(string reason) => reason switch
{
SortRule? keep = null;
foreach (SortRule r in rules)
{
if (!packRules.Contains(r) || !r.On || r.IsEmpty) continue;
if (keep == null) { keep = r; continue; }
keep.TakeEntriesOf(r);
}
if (keep == null) return;
rules.RemoveAll(r => !ReferenceEquals(r, keep) && packRules.Contains(r) && r.On && !r.IsEmpty);
_selected = keep;
_save();
}
"portal space" => "in portal space",
"looting" => "a corpse or chest is open",
"vendor open" => "a vendor is open",
"trading" => "a trade is open",
"busy" => "you are casting or using something",
_ => reason,
};
/// <summary>"1 item", "3 items".</summary>
internal static string Count(int n, string what) => n == 1 ? "1 " + what : $"{n} {what}s";
/// <summary>"3 s", or "a moment" under a second.</summary>
internal static string Seconds(long ms) => ms < 1000 ? "a moment" : $"{(ms + 999) / 1000} s";
private static string Capital(string s) => s.Length > 0 ? char.ToUpperInvariant(s[0]) + s[1..] : s;
/// <summary>"main pack", "pack 3".</summary>
internal static string PackWord(int index) => index == 0 ? "main pack" : "pack " + index;
/// <summary>Text as a label shows it: "##" would start ImGui's id part.</summary>
private static string Shown(string text) => text.Replace("##", "# #");
@ -367,6 +297,10 @@ internal sealed class SortPanel
+ "go by the pack's name, its item count and what's in it, or open the pack here and use Select in game. "
+ "A rule remembers the pack itself, so items still go to the right one.";
internal const string SelectTooltip =
"Selects this pack in the game, as clicking it in your inventory would, so the game shows you which one it is "
+ "(its name in the selection bar). Nothing moves.";
/// <summary>The header's tooltip: which pack in the game this is, in plain words.</summary>
internal static string PackHeaderTooltip(SortView view, int number)
{
@ -531,4 +465,46 @@ internal sealed class SortPanel
}
return list;
}
/// <summary>
/// The kinds of item in a pack for its icon strip: one entry per kind (same class id, else the
/// same name), the commonest first (then A-Z), at most <paramref name="most"/>.
/// </summary>
internal static List<(SortItem First, int Count)> Kinds(SortPack pack, int most)
{
var kinds = new List<(SortItem First, int Count)>();
foreach (SortItem it in pack.Items)
{
int at = kinds.FindIndex(k => SortPlanner.SameKind(k.First, it));
if (at >= 0) kinds[at] = (kinds[at].First, kinds[at].Count + Math.Max(1, it.Stack));
else kinds.Add((it, Math.Max(1, it.Stack)));
}
kinds.Sort((a, b) => a.Count != b.Count ? b.Count.CompareTo(a.Count) : string.Compare(a.First.Name, b.First.Name, StringComparison.OrdinalIgnoreCase));
if (kinds.Count > most) kinds.RemoveRange(most, kinds.Count - most);
return kinds;
}
/// <summary>For each rule: how many items it keeps in its pack now, and how many a sort would bring in.</summary>
internal static Dictionary<SortRule, (int Here, int Coming)> RuleCounts(IReadOnlyList<SortRule> rules, SortView view, SortInventory? inv, SortPreview? preview)
{
var map = new Dictionary<SortRule, (int Here, int Coming)>(ReferenceEqualityComparer.Instance);
if (inv == null) return map;
for (int i = 0; i < inv.Packs.Count; i++)
foreach (SortItem it in inv.Packs[i].Items)
{
SortRule? r = SortRules.RuleFor(rules, it);
if (r == null || ShownPack(view, r) != i + 1) continue;
map.TryGetValue(r, out var c);
map[r] = (c.Here + 1, c.Coming);
}
if (preview != null)
foreach (SortMove m in preview.Moves)
{
SortRule? r = SortRules.RuleFor(rules, m.Item);
if (r == null || m.DestIndex == 0 || ShownPack(view, r) != m.DestIndex) continue;
map.TryGetValue(r, out var c);
map[r] = (c.Here, c.Coming + 1);
}
return map;
}
}

View file

@ -0,0 +1,854 @@
// RynthSort - Window/SortWindow.Packs.cs: the body's columns, the main pack, the side pack cards,
// item tiles (real pictures, counts, marks, motion), rule chips, and dragging items onto packs.
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthSort.Window;
internal sealed unsafe partial class SortWindow
{
/// <summary>A side pack's slots per row (the design's 6 x 4); fewer only when the card is too narrow.</summary>
private const int PackColumns = 6;
/// <summary>The main pack's most slots per row (a wide window shows more per row, so fewer rows).</summary>
private const int MainColumns = 12;
/// <summary>How many tiles fit across <paramref name="w"/>, between 3 and <paramref name="max"/>.</summary>
private int ColumnsFor(float w, int max) => Math.Clamp((int)MathF.Floor((w + TileGap) / (Tile40 + TileGap)), 3, max);
private bool _bodyHot;
private Vector2 _clipMin, _clipMax;
// The side pack cards this frame (screen rectangles, pack n at n-1): where a drag is let go.
private Vector2[] _cardMin = Array.Empty<Vector2>(), _cardMax = Array.Empty<Vector2>();
private int _cards;
/// <summary>The card a drag is over (from the last frame's rectangles): it lights up teal.</summary>
private int _dropCard;
/// <summary>The item being dragged inside the window (0 = none).</summary>
private uint _dragItem;
/// <summary>An item is being dragged out of AC's own windows (the engine's drop target says).</summary>
private bool _acDragging;
/// <summary>
/// The item RynthCore's Inventory window (or AC's own, carried by the engine's drag bridge) is
/// dragging as an ImGui payload, 0 = none. The card under the mouse lights up for it too.
/// </summary>
private uint _invDragItem;
/// <summary>The same drop arriving both as the payload and through the drop target opens one set of choices.</summary>
private readonly DropOnce _dropOnce = new();
/// <summary>
/// The ImGui payload RynthCore's Inventory window publishes while it drags an item (a uint object
/// id): RynthCore.Engine ImGui/Panels/InventoryFace.ItemPayloadType and ImGui/ItemDragBridge.PayloadType
/// (which also carries a drag out of AC's own item windows when the engine knows the dragged item).
/// RynthAi's Mini Remote takes the same payload.
/// </summary>
internal const string InvPayloadType = "RYNTH_INV_ITEM";
// A short note by the mouse ("That item isn't in your packs.").
private string _note = string.Empty;
private double _noteUntil;
private float Tile40 => D(40);
private float TileGap => D(5);
private void Body(Vector2 min, Vector2 size)
{
ImGui.SetCursorScreenPos(min);
bool visible = ImGui.BeginChild("##rs_body", size, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground);
try
{
if (visible) BodyContent();
}
finally
{
ImGui.EndChild();
}
if (_note.Length > 0 && _now < _noteUntil) SafeImGui.SetTooltip(_note);
}
private void BodyContent()
{
Vector2 o = Round(ImGui.GetCursorScreenPos());
float w = MathF.Floor(ImGui.GetContentRegionAvail().X);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
_bodyHot = ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows);
_clipMin = ImGui.GetWindowPos();
_clipMax = _clipMin + ImGui.GetWindowSize();
if (!_m.Ready)
{
ImFontPtr f = Font(RynthUiFont.Ui11);
string text = _m.NotReady.Length > 0 ? _m.NotReady : "Waiting for RynthSort...";
Vector2 ts = Measure(f, text);
Text(dl, f, new Vector2(o.X + (w - ts.X) * 0.5f, o.Y + D(40)), Ink3, text);
ImGui.Dummy(new Vector2(w, D(100)));
return;
}
// A drag in progress: ours (an item tile), or one out of AC's windows.
ImGuiPayloadPtr pl = ImGui.GetDragDropPayload();
uint dragging = 0;
_invDragItem = 0;
if (pl.NativePtr != null && pl.Data != IntPtr.Zero && pl.DataSize >= sizeof(uint))
{
if (pl.IsDataType(PayloadType)) dragging = *(uint*)pl.Data;
else if (pl.IsDataType(InvPayloadType)) _invDragItem = *(uint*)pl.Data;
}
_dragItem = dragging;
Vector2 mouse = ImGui.GetIO().MousePos;
_dropCard = dragging != 0 || _acDragging || _invDragItem != 0 ? CardUnder(mouse) : 0;
float h;
float top = o.Y;
if (w >= D(1140))
{
float mainW = MathF.Round(Math.Clamp(w * 0.24f, D(280), D(330)));
float planW = MathF.Round(Math.Clamp(w * 0.25f, D(280), D(340)));
float packsW = w - mainW - planW;
float h1 = MainColumn(dl, new Vector2(o.X, top), mainW);
float h2 = PacksColumn(dl, new Vector2(o.X + mainW, top), packsW, oneColumn: false);
float h3 = PlanColumn(dl, new Vector2(o.X + mainW + packsW, top), planW);
h = Math.Max(h1, Math.Max(h2, h3));
dl.AddLine(new Vector2(o.X + mainW, top), new Vector2(o.X + mainW, top + h), Line);
dl.AddLine(new Vector2(o.X + mainW + packsW, top), new Vector2(o.X + mainW + packsW, top + h), Line);
}
else if (w >= D(740))
{
float half = MathF.Floor(w * 0.5f);
float h1 = MainColumn(dl, new Vector2(o.X, top), half);
float h2 = PacksColumn(dl, new Vector2(o.X + half, top), w - half, oneColumn: true);
float row = Math.Max(h1, h2);
dl.AddLine(new Vector2(o.X + half, top), new Vector2(o.X + half, top + row), Line);
dl.AddLine(new Vector2(o.X, top + row), new Vector2(o.X + w, top + row), Line);
float h3 = PlanColumn(dl, new Vector2(o.X, top + row + 1), w);
h = row + 1 + h3;
}
else
{
float h1 = MainColumn(dl, new Vector2(o.X, top), w);
dl.AddLine(new Vector2(o.X, top + h1), new Vector2(o.X + w, top + h1), Line);
float h2 = PacksColumn(dl, new Vector2(o.X, top + h1 + 1), w, oneColumn: true);
dl.AddLine(new Vector2(o.X, top + h1 + 1 + h2), new Vector2(o.X + w, top + h1 + 1 + h2), Line);
float h3 = PlanColumn(dl, new Vector2(o.X, top + h1 + h2 + 2), w);
h = h1 + h2 + 2 + h3;
}
ImGui.SetCursorScreenPos(o);
ImGui.Dummy(new Vector2(w, Math.Max(1, h)));
// Let go over a pack card: the drop choices.
if (dragging != 0 && ImGui.IsMouseReleased(ImGuiMouseButton.Left))
{
int card = CardUnder(mouse);
if (card > 0 && _m.TilesById.TryGetValue(dragging, out TileModel? t))
{
if (t.Where == card) Note("It is in that pack already.");
else OpenDrop(dragging, card);
}
}
AcDropTarget(mouse);
if (SheetShowing) dl.AddRectFilled(_clipMin, _clipMax, A(Argb(0xFF020508), 0.62f));
}
/// <summary>Items dragged out of AC's own windows (the inventory, a pack) can be let go on a pack card too (plugin API v90).</summary>
private void AcDropTarget(Vector2 mouse)
{
if (!_host.HasDropTargets || _cards == 0) return;
Vector2 a = _cardMin[0], b = _cardMax[0];
for (int i = 1; i < _cards; i++)
{
a = Vector2.Min(a, _cardMin[i]);
b = Vector2.Max(b, _cardMax[i]);
}
// Only what shows: a drop below the window must still reach AC.
a = Vector2.Max(a, _clipMin);
b = Vector2.Min(b, _clipMax);
if (b.X <= a.X || b.Y <= a.Y) { _acDragging = false; return; }
int under = CardUnder(mouse);
uint dropped = _host.DropTarget(Title, a, b, under > 0 && !SheetShowing, out _acDragging);
if (dropped == 0 || under == 0) return;
DroppedFromOutside(dropped, under);
}
/// <summary>
/// An item let go over a pack card from outside the window (RynthCore's Inventory, AC's own item
/// windows): the same choices as an item dragged inside the window, once per drop.
/// </summary>
private void DroppedFromOutside(uint itemId, int card)
{
if (!_dropOnce.Take(itemId, _now) || SheetShowing) return;
if (!_m.TilesById.TryGetValue(itemId, out TileModel? t)) Note("That isn't a loose item in your packs.");
else if (t.Where == card) Note("It is in that pack already.");
else OpenDrop(itemId, card);
}
/// <summary>
/// The card as a drop target for RynthCore's Inventory payload (<see cref="InvPayloadType"/>):
/// an invisible item over the whole card, drawn after its own buttons, so it takes nothing else.
/// </summary>
private void CardDropTarget(int number, Vector2 p, Vector2 size)
{
if (_invDragItem == 0) return;
ImGui.SetCursorScreenPos(p);
ImGui.Dummy(size);
if (!ImGui.BeginDragDropTarget()) return;
try
{
ImGuiPayloadPtr got = ImGui.AcceptDragDropPayload(InvPayloadType, ImGuiDragDropFlags.AcceptNoDrawDefaultRect);
if (got.NativePtr != null && got.Data != IntPtr.Zero && got.DataSize >= sizeof(uint))
DroppedFromOutside(*(uint*)got.Data, number);
}
finally { ImGui.EndDragDropTarget(); }
}
// ── Folding (0.6.1) ──────────────────────────────────────────────────
// A click shows at once; the tick saves it and the next model carries it. Until then the
// window's own answer wins (key 0 = the main pack).
private readonly Dictionary<uint, bool> _folds = new();
private int _foldsVersion = -1;
private bool Folded(uint key, bool model)
{
if (_foldsVersion != _m.Version) { _foldsVersion = _m.Version; DropAgreedFolds(); }
return _folds.TryGetValue(key, out bool v) ? v : model;
}
private bool Folded(PackModel pk) => Folded(pk.Id, pk.Collapsed);
private bool MainFolded => Folded(0, _m.Main.Collapsed);
private void Fold(PackModel pk, bool folded)
{
_folds[pk.Id] = folded;
_act.SetCollapsed(pk.Id, folded);
}
private void FoldMain(bool folded)
{
_folds[0] = folded;
_act.SetMainCollapsed(folded);
}
private void FoldAll(bool folded)
{
foreach (PackModel pk in _m.Packs) _folds[pk.Id] = folded;
_act.SetAllCollapsed(folded);
}
// The model's answers that agree with the window's: forget those (no allocation: few entries).
private readonly List<uint> _agreed = new();
private void DropAgreedFolds()
{
if (_folds.Count == 0) return;
_agreed.Clear();
foreach (KeyValuePair<uint, bool> kv in _folds)
{
bool model = kv.Key == 0 ? _m.Main.Collapsed : PackCollapsed(kv.Key, kv.Value);
if (model == kv.Value) _agreed.Add(kv.Key);
}
foreach (uint k in _agreed) _folds.Remove(k);
}
/// <summary>The model's fold for pack <paramref name="id"/>; a pack no longer carried counts as agreeing.</summary>
private bool PackCollapsed(uint id, bool fallback)
{
foreach (PackModel pk in _m.Packs) if (pk.Id == id) return pk.Collapsed;
return fallback;
}
private void Note(string text)
{
_note = text;
_noteUntil = _now + 2.5;
}
private int CardUnder(Vector2 m)
{
if (m.X < _clipMin.X || m.Y < _clipMin.Y || m.X > _clipMax.X || m.Y > _clipMax.Y) return 0;
for (int i = 0; i < _cards; i++)
if (m.X >= _cardMin[i].X && m.Y >= _cardMin[i].Y && m.X < _cardMax[i].X && m.Y < _cardMax[i].Y) return i + 1;
return 0;
}
// ── The main pack ────────────────────────────────────────────────────
private const string MainHint = "Items no rule names stay here. Drag an item onto a pack to send its kind there, or click it.";
private float MainColumn(ImDrawListPtr dl, Vector2 p, float w)
{
float pad = D(16), inner = D(14);
float x = p.X + pad, y = p.Y + pad, cw = w - 2 * pad, iw = cw - 2 * inner;
MainModel main = _m.Main;
float tile = Tile40, gap = TileGap;
int cols = ColumnsFor(iw - D(12), MainColumns);
int slots = MainSlots(cols);
int rows = Math.Max(1, (slots + cols - 1) / cols);
float gridH = rows * tile + (rows - 1) * gap;
float gridW = cols * tile + (cols - 1) * gap;
float shownH = Math.Min(gridH, D(360));
ImFontPtr hf = Font(RynthUiFont.Ui10), bold = Font(RynthUiFont.UiBold11), nf = Font(RynthUiFont.Dash10);
float hintH = hf.CalcTextSizeA(Fs(hf), float.MaxValue, iw, MainHint).Y;
float handyH = main.Handy.Length > 0 ? D(6) + hf.CalcTextSizeA(Fs(hf), float.MaxValue, iw, main.Handy).Y : 0f;
float headH = Fs(bold);
bool folded = MainFolded;
float cardH = folded
? inner + headH + D(12) + D(6) + inner
: inner + headH + D(12) + D(6) + D(12) + shownH + D(12) + hintH + handyH + inner;
dl.AddRectFilled(new Vector2(x, y), new Vector2(x + cw, y + cardH), Card, D(14));
dl.AddRect(new Vector2(x, y), new Vector2(x + cw, y + cardH), Line, D(14));
float cx = x + inner, cy = y + inner;
Text(dl, bold, new Vector2(cx, cy), Ink, "Main pack");
Text(dl, nf, new Vector2(cx + Measure(bold, "Main pack").X + D(8), cy + (headH - Fs(nf)) * 0.5f + D(1)), Ink2, main.Count);
float fold = D(24);
if (IconButton("##rs_foldmain", folded ? RynthIcons.CaretRight : RynthIcons.CaretDown, new Vector2(cx + iw - fold, cy + (headH - fold) * 0.5f), new Vector2(fold, fold),
folded ? "Show the main pack's slots" : "Fold the main pack down to its name", quiet: true))
FoldMain(!folded);
cy += headH + D(12);
Meter(dl, new Vector2(cx, cy), iw, main.Fill, main.NearlyFull, main.Full);
if (folded) return pad + cardH + pad;
cy += D(6) + D(12);
if (gridH > shownH + 0.5f)
{
// Taller than the room it gets: a grid of its own that scrolls.
ImGui.SetCursorScreenPos(new Vector2(cx - D(4), cy));
bool open = ImGui.BeginChild("##rs_maingrid", new Vector2(Math.Min(iw + D(8), gridW + D(18)), shownH), ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground);
try
{
if (open)
{
Vector2 go = Round(ImGui.GetCursorScreenPos()) + new Vector2(D(4), 0);
ImDrawListPtr gdl = ImGui.GetWindowDrawList();
MainGrid(gdl, go, tile, gap, cols);
ImGui.SetCursorScreenPos(go);
ImGui.Dummy(new Vector2(gridW, gridH));
}
}
finally { ImGui.EndChild(); }
}
else MainGrid(dl, new Vector2(cx, cy), tile, gap, cols);
cy += shownH + D(12);
dl.AddText(hf, Fs(hf), Round(new Vector2(cx, cy)), Ink3, MainHint, iw);
if (main.Handy.Length > 0)
{
cy += hintH + D(6);
dl.AddText(hf, Fs(hf), Round(new Vector2(cx, cy)), DoneInk, main.Handy, iw);
}
return pad + cardH + pad;
}
/// <summary>The main pack's items and wells, the last row filled out to <paramref name="cols"/> (never past its capacity).</summary>
private int MainSlots(int cols)
{
MainModel main = _m.Main;
int slots = main.Tiles.Length + main.Wells;
int filled = (slots + cols - 1) / cols * cols;
return Math.Max(main.Tiles.Length, Math.Min(filled, Math.Max(main.Capacity, main.Tiles.Length)));
}
private void MainGrid(ImDrawListPtr dl, Vector2 o, float tile, float gap, int cols)
{
MainModel main = _m.Main;
int slots = MainSlots(cols);
for (int i = 0; i < slots; i++)
{
Vector2 at = new(MathF.Round(o.X + i % cols * (tile + gap)), MathF.Round(o.Y + i / cols * (tile + gap)));
if (!ImGui.IsRectVisible(at, at + new Vector2(tile, tile))) continue;
if (i < main.Tiles.Length) Tile(dl, main.Tiles[i], at, tile);
else EmptySlot(dl, at, tile);
}
}
// ── Side packs ───────────────────────────────────────────────────────
private float PacksColumn(ImDrawListPtr dl, Vector2 p, float w, bool oneColumn)
{
float pad = D(16), gap = D(14);
float x = p.X + pad, y = p.Y + pad, cw = w - 2 * pad;
float ey = y;
y = Eyebrow(dl, new Vector2(x, y), "SIDE PACKS", _m.PacksNote);
if (_m.Packs.Length > 1)
{
bool allFolded = true;
foreach (PackModel pk in _m.Packs) allFolded &= Folded(pk);
string label = allFolded ? "Open all" : "Fold all";
ImFontPtr lf = Font(RynthUiFont.Ui10);
Vector2 ls = Measure(lf, label);
Vector2 lp = new(x + cw - ls.X, ey + (y - D(10) - ey - ls.Y) * 0.5f);
ImGui.SetCursorScreenPos(lp - new Vector2(D(4), D(2)));
bool click = ImGui.InvisibleButton("##rs_foldall", ls + new Vector2(D(8), D(4)));
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(allFolded ? "Show every side pack's slots" : "Fold every side pack down to its name and rules");
Text(dl, lf, lp, hot ? TealHot : Teal, label);
if (click) FoldAll(!allFolded);
}
if (_m.NoRules && _m.Packs.Length > 0) y = NoRulesHint(dl, new Vector2(x, y), cw) + D(12);
else if (_m.Packs.Length > 0)
{
ImFontPtr hf = Font(RynthUiFont.Ui10);
dl.AddText(hf, Fs(hf), Round(new Vector2(x, y)), Ink3, RulesHint, cw);
y += hf.CalcTextSizeA(Fs(hf), float.MaxValue, cw, RulesHint).Y + D(12);
}
PackModel[] packs = _m.Packs;
if (_cardMin.Length != packs.Length)
{
_cardMin = new Vector2[packs.Length];
_cardMax = new Vector2[packs.Length];
}
_cards = 0;
if (packs.Length == 0)
{
ImFontPtr f = Font(RynthUiFont.Ui10);
const string none = "You carry no side packs, so items stay in the main pack.";
dl.AddText(f, Fs(f), Round(new Vector2(x, y)), Ink3, none, cw);
return y - p.Y + f.CalcTextSizeA(Fs(f), float.MaxValue, cw, none).Y + pad;
}
int perRow = oneColumn ? 1 : Math.Max(1, (int)MathF.Floor((cw + gap) / (D(300) + gap)));
float cardW = MathF.Floor((cw - gap * (perRow - 1)) / perRow);
for (int i = 0; i < packs.Length; i += perRow)
{
float rowH = 0;
for (int j = i; j < packs.Length && j < i + perRow; j++) rowH = Math.Max(rowH, CardHeight(packs[j], cardW));
for (int j = i; j < packs.Length && j < i + perRow; j++)
{
Vector2 cp = new(x + (j - i) * (cardW + gap), y);
_cardMin[j] = cp;
_cardMax[j] = cp + new Vector2(cardW, rowH);
_cards = j + 1;
if (ImGui.IsRectVisible(cp, cp + new Vector2(cardW, rowH)))
{
PackCard(dl, packs[j], cp, new Vector2(cardW, rowH));
CardDropTarget(packs[j].Number, cp, new Vector2(cardW, rowH));
}
}
y += rowH + gap;
}
return y - gap - p.Y + pad;
}
private const string RulesHint = "Each pack takes what its rules name. Use + Add a rule on a pack, or drag an item onto one.";
private const string NoRulesText = "No rules yet, so nothing goes to your side packs. A starter layout fills them in one click.";
private float NoRulesHint(ImDrawListPtr dl, Vector2 p, float w)
{
ImFontPtr f = Font(RynthUiFont.Ui10);
float bw = ButtonWidth("Pick a layout", true), pad = D(12);
float tw = w - 2 * pad - bw - D(12);
float th = f.CalcTextSizeA(Fs(f), float.MaxValue, tw, NoRulesText).Y;
float h = Math.Max(th, D(32)) + 2 * pad;
dl.AddRectFilled(p, p + new Vector2(w, h), A(Teal, 0.14f), D(12));
dl.AddText(f, Fs(f), Round(new Vector2(p.X + pad, p.Y + (h - th) * 0.5f)), DoneInk, NoRulesText, tw);
if (Button("##rs_pick", "Pick a layout", RynthIcons.SquaresFour, new Vector2(p.X + w - pad - bw, p.Y + (h - D(32)) * 0.5f), D(32), Look.Primary, true,
"Everyday, Hunting, Crafting or Just the basics, fitted to your packs. You see what would move first.", out _))
OpenLayouts("everyday");
return p.Y + h;
}
private float CardHeight(PackModel pk, float w)
{
float inner = D(14), iw = w - 2 * inner;
float h = inner + D(34) + D(11) + D(6) + D(11) + Chips(default, pk, Vector2.Zero, iw, draw: false);
if (!Folded(pk))
{
int slots = Math.Max(pk.Capacity, pk.Tiles.Length + pk.Ghosts.Length);
int cols = ColumnsFor(iw, PackColumns);
int rows = Math.Max(1, (slots + cols - 1) / cols);
h += D(12) + rows * Tile40 + (rows - 1) * TileGap;
}
if (pk.JobLine.Length > 0)
{
ImFontPtr jf = Font(RynthUiFont.Ui10);
h += jf.CalcTextSizeA(Fs(jf), float.MaxValue, iw, pk.JobLine).Y + D(9);
}
if (pk.Warnings.Length > 0)
{
ImFontPtr f = Font(RynthUiFont.Ui10);
h += D(8);
foreach (string line in pk.Warnings) h += f.CalcTextSizeA(Fs(f), float.MaxValue, iw, line).Y + D(2);
}
return h + inner;
}
private void PackCard(ImDrawListPtr dl, PackModel pk, Vector2 p, Vector2 size)
{
bool drop = _dropCard == pk.Number;
dl.AddRectFilled(p, p + size, drop ? DropBg : Card, D(14));
dl.AddRect(p, p + size, drop ? Teal : Line, D(14), ImDrawFlags.None, drop ? 2f : 1f);
ImGui.PushID(pk.Number);
try
{
float inner = D(14), iw = size.X - 2 * inner;
float x = p.X + inner, y = p.Y + inner;
// Header: the bag badge (selects the pack in the game), the names, "+N coming", the count.
float bag = D(34);
Vector2 bp = new(x, y);
if (_m.CanSelect)
{
ImGui.SetCursorScreenPos(bp);
if (ImGui.InvisibleButton("##bag", new Vector2(bag, bag))) _act.SelectInGame(pk.Id);
SafeImGui.SetItemTooltip("Select this pack in the game, as clicking it in your inventory would, so you can see which one it is. Nothing moves.");
}
Bag(dl, bp, bag, pk.Badge);
ImFontPtr nf = Font(RynthUiFont.Dash10), pf = Font(RynthUiFont.Narrow11);
float right = x + iw;
bool folded = Folded(pk);
float fold = D(24);
if (IconButton("##fold", folded ? RynthIcons.CaretRight : RynthIcons.CaretDown, new Vector2(right - fold, y + (bag - fold) * 0.5f), new Vector2(fold, fold),
folded ? "Show this pack's slots" : "Fold this pack down to its name and rules", quiet: true))
Fold(pk, !folded);
right -= fold + D(6);
float countW = Measure(nf, pk.Count).X;
Text(dl, nf, new Vector2(right - countW, y + (bag - Fs(nf)) * 0.5f), Ink2, pk.Count);
right -= countW + D(10);
right = JobButton(dl, pk, right, y, bag) - D(8);
if (pk.Incoming.Length > 0)
{
float iwid = Measure(pf, pk.Incoming).X + D(16), ih = Fs(pf) + D(9);
Vector2 ip = new(right - iwid, y + (bag - ih) * 0.5f);
dl.AddRectFilled(ip, ip + new Vector2(iwid, ih), A(Sky, 0.14f), ih * 0.5f);
Text(dl, pf, new Vector2(ip.X + D(8), ip.Y + (ih - Fs(pf)) * 0.5f), Sky, pk.Incoming);
right -= iwid + D(8);
}
ImFontPtr bold = Font(RynthUiFont.UiBold11), small = Font(RynthUiFont.Ui10);
float tx = x + bag + D(10), tw = Math.Max(10, right - tx);
float lines = Fs(bold) + D(2) + Fs(small), ty = y + (bag - lines) * 0.5f;
TextFit(dl, bold, new Vector2(tx, ty), Ink, pk.Name, tw);
TextFit(dl, small, new Vector2(tx, ty + Fs(bold) + D(2)), Ink3, pk.Where, tw);
if (_bodyHot && _dragItem == 0 && ImGui.IsMouseHoveringRect(new Vector2(tx, y), new Vector2(tx + tw, y + bag)))
SafeImGui.SetTooltip(pk.Tip);
y += bag + D(11);
Meter(dl, new Vector2(x, y), iw, pk.Fill, pk.NearlyFull, pk.Full);
y += D(6) + D(11);
if (pk.JobLine.Length > 0)
{
ImFontPtr jf = Font(RynthUiFont.Ui10);
dl.AddText(jf, Fs(jf), Round(new Vector2(x, y)), pk.JobProblem ? Amber : DoneInk, pk.JobLine, iw);
y += jf.CalcTextSizeA(Fs(jf), float.MaxValue, iw, pk.JobLine).Y + D(9);
}
// Its rules first (what goes here, and "+ Add a rule"), so they show on a folded card too.
y += Chips(dl, pk, new Vector2(x, y), iw, draw: true);
// The slots: its items, the ghosts of what a sort would bring, then empty wells.
if (!Folded(pk))
{
y += D(12);
float tile = Tile40, gap = TileGap;
int slots = Math.Max(pk.Capacity, pk.Tiles.Length + pk.Ghosts.Length);
int cols = ColumnsFor(iw, PackColumns);
for (int i = 0; i < slots; i++)
{
Vector2 at = new(MathF.Round(x + i % cols * (tile + gap)), MathF.Round(y + i / cols * (tile + gap)));
if (!ImGui.IsRectVisible(at, at + new Vector2(tile, tile))) continue;
if (i < pk.Tiles.Length) Tile(dl, pk.Tiles[i], at, tile);
else if (i < pk.Tiles.Length + pk.Ghosts.Length) Ghost(dl, pk.Ghosts[i - pk.Tiles.Length], at, tile, i);
else EmptySlot(dl, at, tile);
}
int rows = Math.Max(1, (slots + cols - 1) / cols);
y += rows * tile + (rows - 1) * gap;
}
if (pk.Warnings.Length > 0)
{
ImFontPtr f = Font(RynthUiFont.Ui10);
y += D(8);
foreach (string line in pk.Warnings)
{
dl.AddText(f, Fs(f), Round(new Vector2(x, y)), Amber, line, iw);
y += f.CalcTextSizeA(Fs(f), float.MaxValue, iw, line).Y + D(2);
}
}
}
finally { ImGui.PopID(); }
}
/// <summary>
/// The card header's job control, right-aligned at <paramref name="right"/>: the job's pill
/// (Salvage, Sell, Mule) or, with none, a small button. Opens the job popup. Returns its left edge.
/// </summary>
private float JobButton(ImDrawListPtr dl, PackModel pk, float right, float y, float rowH)
{
ImFontPtr pf = Font(RynthUiFont.Narrow11);
float h = Fs(pf) + D(9);
bool has = pk.JobLabel.Length > 0;
string icon = pk.Job switch { Sorting.JobKind.Salvage => RynthIcons.Hammer, Sorting.JobKind.Sell => RynthIcons.Coins, Sorting.JobKind.Mule => RynthIcons.User, _ => RynthIcons.Package };
float w = has ? D(8) + D(14) + D(5) + Math.Min(Measure(pf, pk.JobLabel).X, D(120)) + D(9) : h;
Vector2 p = new(right - w, y + (rowH - h) * 0.5f), s = new(w, h);
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton("##job", s);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(has
? "This pack's job: " + pk.JobLabel + ". Click to change it."
: "Give this pack a job: what RynthAi would salvage, sell, or give your mule goes here.");
uint tone = pk.JobProblem ? Amber : Brass;
if (has)
{
dl.AddRectFilled(p, p + s, A(tone, hot ? 0.24f : 0.14f), h * 0.5f);
DrawIcon(dl, icon, new Vector2(p.X + D(8), p.Y), new Vector2(D(14), h), D(13), tone);
TextFit(dl, pf, new Vector2(p.X + D(8) + D(14) + D(5), p.Y + (h - Fs(pf)) * 0.5f), tone, pk.JobLabel, D(120));
}
else
{
if (hot) dl.AddRectFilled(p, p + s, CardHot, h * 0.5f);
DrawIcon(dl, icon, p, s, D(13), hot ? Ink : Ink3);
}
if (clicked) OpenJob(pk.Number);
return p.X;
}
// ── Rule chips ───────────────────────────────────────────────────────
private const string AddKindLabel = "+ Add a kind…", AddRuleLabel = "+ Add a rule", NothingHere = "No rules yet: nothing goes here.";
/// <summary>The pack's chips, then "+ Add a kind...", flowing onto as many lines as they need. Returns the height; draws only when <paramref name="draw"/>.</summary>
private float Chips(ImDrawListPtr dl, PackModel pk, Vector2 p, float w, bool draw)
{
ImFontPtr f = Font(RynthUiFont.Ui10);
float h = D(26), gap = D(6), x = p.X, y = p.Y;
void Advance(float itemW)
{
if (x > p.X && x + itemW > p.X + w) { x = p.X; y += h + gap; }
}
for (int i = 0; i < pk.Chips.Length; i++)
{
ChipModel c = pk.Chips[i];
float cw = ChipWidth(f, c);
Advance(cw);
if (draw) Chip(dl, c, new Vector2(x, y), new Vector2(cw, h), i);
x += cw + gap;
}
if (pk.Chips.Length == 0)
{
float tw = Measure(f, NothingHere).X;
Advance(tw);
if (draw) Text(dl, f, new Vector2(x, y + (h - Fs(f)) * 0.5f), Ink3, NothingHere);
x += tw + gap;
}
float aw = Measure(f, AddRuleLabel).X + D(20);
Advance(aw);
if (draw)
{
Vector2 ap = new(x, y), asz = new(aw, h);
ImGui.SetCursorScreenPos(ap);
bool clicked = ImGui.InvisibleButton("##addkind", asz);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip("Say what goes to this pack: type part of a name, or pick a kind of item. You can also drag an item onto the pack.");
dl.AddRectFilled(ap, ap + asz, A(Teal, hot ? 0.20f : 0.10f), h * 0.5f);
dl.AddRect(ap, ap + asz, A(Teal, hot ? 1f : 0.55f), h * 0.5f);
Text(dl, f, new Vector2(ap.X + D(10), ap.Y + (h - Fs(f)) * 0.5f), hot ? TealHot : Teal, AddRuleLabel);
if (clicked) OpenKinds(pk.Number, new Vector2(ap.X, ap.Y + h + D(4)));
}
return y + h - p.Y;
}
private float ChipWidth(ImFontPtr f, ChipModel c) =>
D(9) + (c.IsName ? 0 : D(8) + D(6)) + Measure(f, c.Label).X + D(6) + D(18) + D(6);
private void Chip(ImDrawListPtr dl, ChipModel c, Vector2 p, Vector2 s, int index)
{
ImGui.PushID(index);
try
{
ImFontPtr f = Font(RynthUiFont.Ui10);
float alpha = c.Off ? 0.5f : 1f;
dl.AddRectFilled(p, p + s, Card2, s.Y * 0.5f);
if (c.IsName) Dashed(dl, p, p + s, Line2, D(3));
else dl.AddRect(p, p + s, Line2, s.Y * 0.5f);
float x = p.X + D(9);
if (!c.IsName)
{
dl.AddCircleFilled(new Vector2(x + D(4), p.Y + s.Y * 0.5f), D(4), A(Kinds2Abgr(c.Dot), alpha), 12);
x += D(8) + D(6);
}
Text(dl, f, new Vector2(x, p.Y + (s.Y - Fs(f)) * 0.5f), A(Ink, alpha), c.Label);
// The chip's body: its tooltip (and, for a rule that is off, a click turns it on); then the x.
Vector2 xs = new(D(18), D(18));
Vector2 xp = new(p.X + s.X - D(6) - xs.X, p.Y + (s.Y - xs.Y) * 0.5f);
ImGui.SetCursorScreenPos(p);
bool body = ImGui.InvisibleButton("##chip", new Vector2(Math.Max(1, xp.X - p.X), s.Y));
SafeImGui.SetItemTooltip(c.Tip);
if (body && c.Off) _act.TurnOn(c.RuleUid);
ImGui.SetCursorScreenPos(xp);
bool x2 = ImGui.InvisibleButton("##x", xs);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(c.IsName ? "Stop sending items with this name here (Undo brings it back)" : "Stop sending this kind here (Undo brings it back)");
if (hot) dl.AddCircleFilled(xp + xs * 0.5f, xs.X * 0.5f, Argb(0xFF24344A), 16);
DrawIcon(dl, RynthIcons.X, xp, xs, D(11), hot ? Ink : Ink3);
if (x2) _act.RemoveChip(c.RuleUid, c.IsName, c.Cls, c.Name);
}
finally { ImGui.PopID(); }
}
/// <summary>A model colour (ARGB) as ImGui's ABGR.</summary>
private static uint Kinds2Abgr(uint argb) => Argb(argb);
// ── Tiles ────────────────────────────────────────────────────────────
// Tooltips made once per tile (and model).
private readonly Dictionary<uint, string> _tips = new();
private int _tipsVersion = -1;
private string TileTip(TileModel t)
{
if (_tipsVersion != _m.Version) { _tips.Clear(); _tipsVersion = _m.Version; }
if (_tips.TryGetValue(t.Id, out string? tip)) return tip;
tip = t.Name + (t.Stack > 1 ? " (" + t.Stack + ")" : string.Empty)
+ (t.Held ? "\nLeft alone: " + t.HeldWhy : t.Settling ? "\nNew: it settles before it moves" : t.Outgoing ? "\nA sort would move it" : string.Empty)
+ "\nClick for more. Drag it onto a pack to send it there.";
_tips[t.Id] = tip;
return tip;
}
/// <summary>One item: its picture (or its kind's colour while the picture is made), count, marks and motion.</summary>
private void Tile(ImDrawListPtr dl, TileModel t, Vector2 p, float s)
{
ImGui.PushID(unchecked((int)t.Id));
try
{
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton("##t", new Vector2(s, s));
bool hot = ImGui.IsItemHovered() && _dragItem == 0;
IntPtr tex = _host.GetIconTexture(RynthIconKind.Object, t.Id);
if (ImGui.BeginDragDropSource(ImGuiDragDropFlags.None))
{
uint id = t.Id;
ImGui.SetDragDropPayload(PayloadType, (IntPtr)(&id), sizeof(uint));
if (tex != IntPtr.Zero)
{
ImGui.Image(tex, new Vector2(D(34), D(34)));
ImGui.SameLine();
}
SafeImGui.Text(t.Name);
ImGui.TextDisabled("Let go over a pack");
ImGui.EndDragDropSource();
}
if (hot) SafeImGui.SetTooltip(TileTip(t));
if (clicked && _dragItem == 0 && !ImGui.IsMouseDragging(ImGuiMouseButton.Left)) OpenItem(t.Id);
// Motion: a tile a move is about to send lifts and pulses; one that just arrived pops in.
float pulse = 0.5f - 0.5f * MathF.Cos((float)(_now * Math.PI * 2 / 1.4));
float lift = t.Moving ? D(4) * pulse : hot ? D(1) : 0f;
float pop = _arrivals.Progress(t.Id, _now);
float grow = pop < 1f ? 0.6f + 0.4f * EaseOut(pop) : 1f;
float alpha = (_searching && !_hits.Contains(t.Id) ? 0.28f : 1f) * (pop < 1f ? 0.2f + 0.8f * pop : 1f);
Vector2 c = p + new Vector2(s * 0.5f, s * 0.5f - lift);
Vector2 half = new(s * 0.5f * grow, s * 0.5f * grow);
Vector2 min = Round(c - half), max = Round(c + half);
float r = D(7) * grow;
dl.AddRectFilled(min + new Vector2(0, D(2)), max + new Vector2(0, D(2)), A(Black, (t.Moving ? 0.5f : 0.3f) * alpha), r);
if (tex != IntPtr.Zero)
{
dl.AddRectFilled(min, max, A(Well, alpha), r);
dl.AddImageRounded(tex, min + new Vector2(1, 1), max - new Vector2(1, 1), Vector2.Zero, Vector2.One, A(White, alpha), Math.Max(0, r - 1));
}
else
{
uint kind = Kinds2Abgr(t.KindColor);
dl.AddRectFilled(min, max, A(kind, alpha), r);
dl.AddRectFilled(new Vector2(min.X, (min.Y + max.Y) * 0.5f), max, A(Darken(Darken(kind)), alpha * 0.6f), r, ImDrawFlags.RoundCornersBottom);
ImFontPtr af = Font(RynthUiFont.Narrow10);
Vector2 ts = af.CalcTextSizeA(Fs(af), float.MaxValue, 0, t.Initials);
dl.AddText(af, Fs(af), Round(c - ts * 0.5f), A(White, 0.92f * alpha), t.Initials);
}
dl.AddRect(min, max, A(Black, 0.5f * alpha), r);
dl.AddLine(new Vector2(min.X + r, min.Y + 1), new Vector2(max.X - r, min.Y + 1), A(White, 0.18f * alpha));
if (hot) dl.AddRect(min, max, A(White, 0.25f), r);
bool hit = _searching && _hits.Contains(t.Id);
bool sel = _sheet == Sheet.Item && _sheetItem == t.Id;
if (hit) Glow(dl, min, max, r, Brass);
if (sel) Glow(dl, min, max, r, Teal);
if (t.Moving) dl.AddRect(min - new Vector2(1, 1), max + new Vector2(1, 1), A(Sky, 0.5f + 0.5f * pulse), r + 1, ImDrawFlags.None, 2f);
if (t.Qty.Length > 0)
{
ImFontPtr qf = Font(RynthUiFont.Dash9);
Vector2 qs = qf.CalcTextSizeA(Fs(qf), float.MaxValue, 0, t.Qty);
Vector2 qp = Round(new Vector2(max.X - qs.X - D(2), max.Y - qs.Y - D(1)));
dl.AddText(qf, Fs(qf), qp + new Vector2(1, 1), A(Black, 0.9f * alpha), t.Qty);
dl.AddText(qf, Fs(qf), qp, A(White, alpha), t.Qty);
}
if (t.Held) Badge(dl, new Vector2(max.X - D(3), min.Y + D(3)), Amber, Argb(0xFF3A2A06), RynthIcons.Lock, alpha);
else if (t.Moving) Badge(dl, new Vector2(max.X - D(3), min.Y + D(3)), Sky, Argb(0xFF06223A), RynthIcons.ArrowRight, alpha);
if (t.Settling) Spinner(dl, min, max);
}
finally { ImGui.PopID(); }
}
private static float EaseOut(float t) => 1f - (1f - t) * (1f - t) * (1f - t);
private void Glow(ImDrawListPtr dl, Vector2 min, Vector2 max, float r, uint col)
{
dl.AddRect(min - new Vector2(D(4), D(4)), max + new Vector2(D(4), D(4)), A(col, 0.18f), r + D(4), ImDrawFlags.None, D(4));
dl.AddRect(min - new Vector2(1, 1), max + new Vector2(1, 1), col, r + 1, ImDrawFlags.None, 2f);
}
/// <summary>A small round mark on a tile's top-right corner (.badge): left alone (a lock), or on its way (an arrow).</summary>
private void Badge(ImDrawListPtr dl, Vector2 c, uint fill, uint ink, string icon, float alpha)
{
float rad = D(8);
dl.AddCircleFilled(c, rad + D(2), A(Card, alpha), 16);
dl.AddCircleFilled(c, rad, A(fill, alpha), 16);
DrawIcon(dl, icon, c - new Vector2(rad, rad), new Vector2(2 * rad, 2 * rad), D(10), A(ink, alpha));
}
/// <summary>The settling ring (.settling::after): an amber arc running round the tile once a second.</summary>
private void Spinner(ImDrawListPtr dl, Vector2 min, Vector2 max)
{
Vector2 a = min - new Vector2(D(3), D(3)), b = max + new Vector2(D(3), D(3));
dl.AddRect(a, b, A(Amber, 0.18f), D(9), ImDrawFlags.None, 2f);
float t0 = (float)(_now % 1.0) * 4f;
const int steps = 10;
for (int i = 0; i <= steps; i++)
{
float t = t0 + 0.9f * i / steps;
dl.PathLineTo(Perimeter(a, b, t));
}
dl.PathStroke(Amber, ImDrawFlags.None, 2f);
}
/// <summary>A point <paramref name="t"/> sides (0-4, wrapping) round the box from its top-left corner, clockwise.</summary>
private static Vector2 Perimeter(Vector2 a, Vector2 b, float t)
{
t %= 4f;
if (t < 0) t += 4f;
int side = (int)t;
float f = t - side;
return side switch
{
0 => new Vector2(a.X + (b.X - a.X) * f, a.Y),
1 => new Vector2(b.X, a.Y + (b.Y - a.Y) * f),
2 => new Vector2(b.X - (b.X - a.X) * f, b.Y),
_ => new Vector2(a.X, b.Y - (b.Y - a.Y) * f),
};
}
/// <summary>A slot an item a sort would bring will take (.ghost).</summary>
private void Ghost(ImDrawListPtr dl, GhostModel g, Vector2 p, float s, int index)
{
Vector2 max = p + new Vector2(s, s);
dl.AddRectFilled(p, max, A(Sky, 0.14f), D(7));
Dashed(dl, p, max, Sky, D(3.5f), 1.5f);
DrawIcon(dl, RynthIcons.ArrowDown, p, new Vector2(s, s), D(16), A(Sky, 0.85f));
if (_bodyHot && _dragItem == 0 && ImGui.IsMouseHoveringRect(p, max)) SafeImGui.SetTooltip(g.Tip);
}
/// <summary>An empty slot (.slot): a dark well.</summary>
private void EmptySlot(ImDrawListPtr dl, Vector2 p, float s)
{
Vector2 max = p + new Vector2(s, s);
dl.AddRectFilled(p, max, Well, D(7));
dl.AddLine(new Vector2(p.X + D(5), p.Y + 1), new Vector2(max.X - D(5), p.Y + 1), A(Black, 0.6f));
dl.AddRect(p, max, A(White, 0.02f), D(7));
}
}

View file

@ -0,0 +1,230 @@
// RynthSort - Window/SortWindow.Plan.cs: the plan column. Next moves (picture, name, the rule,
// where it goes), Left alone (why, where it would go, Sort it), rules for packs not carried, and
// the activity feed with times; "Every item is in its pack" when nothing waits.
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthSort.Window;
internal sealed unsafe partial class SortWindow
{
private const string HeldText = "You used these lately, so they stay where you put them.";
private const string OrphanText = "Their items stay where they are. Remove them, or send their kinds to a pack you carry.";
private float PlanColumn(ImDrawListPtr dl, Vector2 p, float w)
{
float pad = D(16), x = p.X + pad, cw = w - 2 * pad, y = p.Y + pad;
ImFontPtr small = Font(RynthUiFont.Ui10);
// Next moves.
y = Eyebrow(dl, new Vector2(x, y), "NEXT MOVES", Num(_m.MovesCount));
if (_m.MovesCount > 0)
{
for (int i = 0; i < _m.Moves.Length; i++)
y = Row(dl, _m.Moves[i], new Vector2(x, y), cw, RowKind.Move, 100 + i) + D(2);
if (_m.MovesCount > _m.Moves.Length)
{
Text(dl, small, new Vector2(x + D(8), y + D(2)), Ink3, MoreText(_m.MovesCount - _m.Moves.Length));
y += Fs(small) + D(6);
}
if (_m.OrderHint.Length > 0) y = Wrapped(dl, small, new Vector2(x, y + D(6)), cw, Ink3, _m.OrderHint);
if (_m.MovesHint.Length > 0) y = Wrapped(dl, small, new Vector2(x, y + D(6)), cw, Ink3, _m.MovesHint);
}
else
{
float h = D(44);
dl.AddRectFilled(new Vector2(x, y), new Vector2(x + cw, y + h), A(Teal, 0.14f), D(12));
DrawIcon(dl, RynthIcons.Check, new Vector2(x + D(12), y), new Vector2(D(18), h), D(18), DoneInk);
Text(dl, Font(RynthUiFont.Ui11), new Vector2(x + D(40), y + (h - Fs(Font(RynthUiFont.Ui11))) * 0.5f), DoneInk, "Every item is in its pack.");
y += h;
if (_m.OrderHint.Length > 0) y = Wrapped(dl, small, new Vector2(x, y + D(6)), cw, Ink3, _m.OrderHint);
}
y += D(18);
// Left alone.
if (_m.Held.Length > 0)
{
y = Eyebrow(dl, new Vector2(x, y), "LEFT ALONE", _m.HoldNote);
float top = y, iw = cw - 2 * D(12);
float textH = small.CalcTextSizeA(Fs(small), float.MaxValue, iw, HeldText).Y;
float h = D(12) + textH + D(8) + _m.Held.Length * (RowHeight + D(2)) + D(10);
dl.AddRectFilled(new Vector2(x, top), new Vector2(x + cw, top + h), A(Amber, 0.12f), D(12));
dl.AddRect(new Vector2(x, top), new Vector2(x + cw, top + h), A(Amber, 0.25f), D(12));
dl.AddText(small, Fs(small), Round(new Vector2(x + D(12), top + D(12))), HeldInk, HeldText, iw);
float ry = top + D(12) + textH + D(8);
for (int i = 0; i < _m.Held.Length; i++)
ry = Row(dl, _m.Held[i], new Vector2(x + D(4), ry), cw - D(8), RowKind.Held, 400 + i) + D(2);
y = top + h + D(18);
}
// Rules for packs not carried.
if (_m.Orphans.Length > 0)
{
y = Eyebrow(dl, new Vector2(x, y), "RULES FOR PACKS YOU DON'T CARRY", Num(_m.Orphans.Length));
float top = y, iw = cw - 2 * D(12);
float textH = small.CalcTextSizeA(Fs(small), float.MaxValue, iw, OrphanText).Y;
float chipsH = OrphanChipsHeight(iw);
float h = D(12) + textH + D(8) + chipsH + D(12);
dl.AddRectFilled(new Vector2(x, top), new Vector2(x + cw, top + h), A(Amber, 0.12f), D(12));
dl.AddRect(new Vector2(x, top), new Vector2(x + cw, top + h), A(Amber, 0.25f), D(12));
dl.AddText(small, Fs(small), Round(new Vector2(x + D(12), top + D(12))), HeldInk, OrphanText, iw);
OrphanChips(dl, new Vector2(x + D(12), top + D(12) + textH + D(8)), iw);
y = top + h + D(18);
}
// Activity.
y = Eyebrow(dl, new Vector2(x, y), "ACTIVITY", string.Empty);
if (_m.Feed.Length == 0)
{
Text(dl, small, new Vector2(x, y), Ink3, "Nothing has happened yet.");
y += Fs(small);
}
else
for (int i = 0; i < _m.Feed.Length; i++)
y = Row(dl, _m.Feed[i], new Vector2(x, y), cw, RowKind.Feed, 700 + i) + D(2);
return y - p.Y + pad;
}
private enum RowKind { Move, Held, Feed }
private float RowHeight => D(40);
/// <summary>One list row (.row): picture, name, the line under it, and what is on the right. Returns the y under it.</summary>
private float Row(ImDrawListPtr dl, RowModel r, Vector2 p, float w, RowKind kind, int id)
{
float h = RowHeight;
Vector2 size = new(w, h);
ImGui.PushID(id);
try
{
bool hot = false, clicked = false;
float rightW = 0;
ImFontPtr nf = Font(RynthUiFont.Ui11), sf = Font(RynthUiFont.Ui10), mono = Font(RynthUiFont.Dash10), time = Font(RynthUiFont.Dash9);
// Left alone: a "Sort it" button on the right (it lets RynthSort move the item).
if (kind == RowKind.Held)
{
float bw = ButtonWidth("Sort it", false) - D(8);
Vector2 bp = new(p.X + w - bw - D(4), p.Y + (h - D(26)) * 0.5f);
if (SmallButton("##sortit", "Sort it", bp, new Vector2(bw, D(26)), "Stop leaving it alone: the next sort moves it like any other item."))
_act.Release(r.ItemId);
rightW = bw + D(10);
}
else if (kind == RowKind.Move)
{
rightW = Measure(mono, "→ ").X + Measure(mono, r.Right).X + D(4);
rightW = Math.Min(rightW, w * 0.45f);
}
else rightW = Measure(time, r.Right).X + D(4);
if (kind != RowKind.Feed && r.ItemId != 0)
{
ImGui.SetCursorScreenPos(p);
clicked = ImGui.InvisibleButton("##row", new Vector2(Math.Max(1, w - (kind == RowKind.Held ? rightW : 0)), h));
hot = ImGui.IsItemHovered() && _dragItem == 0;
if (r.Tip.Length > 0) SafeImGui.SetItemTooltip(r.Tip);
}
if (hot) dl.AddRectFilled(p, p + size, Card, D(9));
// The picture (the item's own, else a square in its kind's colour; a feed line about a sort: a check).
float mini = D(28);
Vector2 mp = new(p.X + D(8), p.Y + (h - mini) * 0.5f);
IntPtr tex = r.ItemId != 0 ? _host.GetIconTexture(RynthIconKind.Object, r.ItemId) : IntPtr.Zero;
if (tex != IntPtr.Zero) dl.AddImageRounded(tex, mp, mp + new Vector2(mini, mini), Vector2.Zero, Vector2.One, White, D(6));
else
{
dl.AddRectFilled(mp, mp + new Vector2(mini, mini), r.KindColor != 0 ? Kinds2Abgr(r.KindColor) : FeedDot, D(6));
if (r.ItemId == 0) DrawIcon(dl, RynthIcons.Check, mp, new Vector2(mini, mini), D(15), A(White, 0.92f));
}
dl.AddRect(mp, mp + new Vector2(mini, mini), A(Black, 0.5f), D(6));
float tx = mp.X + mini + D(10), tw = Math.Max(10, p.X + w - rightW - D(8) - tx);
if (kind == RowKind.Feed)
{
TextFit(dl, sf, new Vector2(tx, p.Y + (h - Fs(sf)) * 0.5f), Ink2, r.Name, tw);
Text(dl, time, new Vector2(p.X + w - rightW, p.Y + (h - Fs(time)) * 0.5f), Ink3, r.Right);
}
else
{
float lines = Fs(nf) + D(2) + Fs(sf), ty = p.Y + (h - lines) * 0.5f;
TextFit(dl, nf, new Vector2(tx, ty), Ink, r.Name, tw);
TextFit(dl, sf, new Vector2(tx, ty + Fs(nf) + D(2)), kind == RowKind.Held ? HeldInk : Ink3, r.Sub, tw);
if (kind == RowKind.Move)
{
float ax = p.X + w - rightW, ay = p.Y + (h - Fs(mono)) * 0.5f;
Text(dl, mono, new Vector2(ax, ay), Sky, "→");
float aw = Measure(mono, "→ ").X;
TextFit(dl, mono, new Vector2(ax + aw, ay), Sky, r.Right, rightW - aw);
}
}
if (clicked) OpenItem(r.ItemId);
}
finally { ImGui.PopID(); }
return p.Y + h;
}
/// <summary>A small quiet button (a row's "Sort it").</summary>
private bool SmallButton(string id, string label, Vector2 p, Vector2 s, string tip)
{
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton(id, s);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(tip);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
if (hot) dl.AddRectFilled(p, p + s, CardHot, D(8));
dl.AddRect(p, p + s, Line2, D(8));
ImFontPtr f = Font(RynthUiFont.UiBold11);
float fs = Fs(f) * 0.92f;
Vector2 ts = f.CalcTextSizeA(fs, float.MaxValue, 0, label);
dl.AddText(f, fs, Round(p + (s - ts) * 0.5f), Ink, label);
return clicked;
}
private float Wrapped(ImDrawListPtr dl, ImFontPtr f, Vector2 p, float w, uint col, string text)
{
dl.AddText(f, Fs(f), Round(p), col, text, w);
return p.Y + f.CalcTextSizeA(Fs(f), float.MaxValue, w, text).Y;
}
// "... and 12 more", made once per count.
private int _moreCount = -1;
private string _moreText = string.Empty;
private string MoreText(int n)
{
if (n != _moreCount) { _moreCount = n; _moreText = $"... and {n} more"; }
return _moreText;
}
// Rules whose pack isn't carried: their chips (with x) flowing in the amber card.
private float OrphanChipsHeight(float w) => OrphanFlow(default, Vector2.Zero, w, draw: false);
private void OrphanChips(ImDrawListPtr dl, Vector2 p, float w) => OrphanFlow(dl, p, w, draw: true);
private float OrphanFlow(ImDrawListPtr dl, Vector2 p, float w, bool draw)
{
ImFontPtr f = Font(RynthUiFont.Ui10);
float h = D(26), gap = D(6), x = p.X, y = p.Y;
if (draw) ImGui.PushID("orphans");
try
{
for (int i = 0; i < _m.Orphans.Length; i++)
{
ChipModel c = _m.Orphans[i];
float cw = ChipWidth(f, c);
if (x > p.X && x + cw > p.X + w) { x = p.X; y += h + gap; }
if (draw) Chip(dl, c, new Vector2(x, y), new Vector2(cw, h), i);
x += cw + gap;
}
}
finally { if (draw) ImGui.PopID(); }
return y + h - p.Y;
}
}

View file

@ -0,0 +1,934 @@
// RynthSort - Window/SortWindow.Sheets.cs: the popups over the window. One sheet at a time
// (an item's detail, the drop choices, the layouts, the settings), opened and drawn at the
// window's own level (never from inside the body's child windows, so the popup id always
// matches), centred on the window, and the kind picker under a pack's "+ Add a kind...".
// Their words are made when they open.
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthSort.Window;
internal sealed unsafe partial class SortWindow
{
private const string SheetId = "##rs_sheet", KindsId = "##rs_kinds";
private enum Sheet { None, Item, Drop, Layouts, Settings, Job }
private Sheet _sheet, _pendingSheet;
private uint _sheetItem;
private int _sheetPack;
private float _sheetH;
private bool _closeSheet;
private string _sheetTitle = string.Empty;
private bool SheetShowing => _sheet != Sheet.None;
private void OpenSheet(Sheet s) => _pendingSheet = s;
private void OpenItem(uint itemId)
{
if (!_m.TilesById.TryGetValue(itemId, out TileModel? t)) return;
_sheetItem = itemId;
_sheetTitle = t.Name;
_whyKey = default;
OpenSheet(Sheet.Item);
}
// The drop choices' words (made when it opens).
private string _dropKind = string.Empty, _dropKindText = string.Empty, _dropName = string.Empty, _dropOnceText = string.Empty;
private void OpenDrop(uint itemId, int pack)
{
if (!_m.TilesById.TryGetValue(itemId, out TileModel? t)) return;
PackModel? pk = _m.Pack(pack);
if (pk == null) return;
_sheetItem = itemId;
_sheetPack = pack;
_sheetTitle = "Send " + t.Name + " to " + PackWords(pk);
_dropKind = "All " + t.KindLabel.ToLowerInvariant();
_dropKindText = $"A rule: every item of this kind you carry or loot goes to {PackWords(pk)}. The kind leaves any other pack.";
_dropName = "Only “" + AddSelectedName(t.Name) + "”";
int hold = _m.Settings.HoldMin;
_dropOnceText = hold > 0
? $"It goes there now and is left alone for {hold} minute{(hold == 1 ? "" : "s")}, so a sort won’t pull it back."
: "It goes there now. Leaving items alone is off (Settings), so a sort may move it back.";
OpenSheet(Sheet.Drop);
}
/// <summary>A pack in a sentence: its name, with its number when another pack has the same name.</summary>
private static string PackWords(PackModel pk) => pk.Label.Length > 0 ? pk.Label : pk.Name;
/// <summary>The name a name rule keeps (the item's name without a "(100)" count).</summary>
private static string AddSelectedName(string name) => Views.AddSelectedRules.EntryFor(name);
private string? _layoutPicked;
private void OpenLayouts(string? picked)
{
_layoutPicked = picked;
_sheetTitle = "Start from a layout";
OpenSheet(Sheet.Layouts);
_act.WantLayouts(true);
}
private int _kindsPack;
private Vector2 _kindsAnchor;
private bool _openKinds;
private string _kindsTitle = string.Empty, _kindsAddTip = string.Empty, _kindsText = string.Empty;
private void OpenKinds(int pack, Vector2 anchor)
{
PackModel? pk = _m.Pack(pack);
if (pk == null) return;
_kindsPack = pack;
_kindsAnchor = anchor;
_kindsTitle = "What goes to " + PackWords(pk) + "?";
_kindsText = string.Empty;
_kindsAddTip = "Select an item in your inventory first: its name goes into this pack's rules, so items called that go here. Also: /rsort add " + pk.Badge;
_openKinds = true;
}
private void CloseSheet()
{
if (_sheet == Sheet.Layouts) _act.WantLayouts(false);
_sheet = Sheet.None;
_sheetItem = 0;
}
/// <summary>Opens what was asked for this frame, then draws the open sheet and the kind picker (at the window's level).</summary>
private void Sheets()
{
if (_pendingSheet != Sheet.None)
{
if (_sheet == Sheet.Layouts && _pendingSheet != Sheet.Layouts) _act.WantLayouts(false);
_sheet = _pendingSheet;
_pendingSheet = Sheet.None;
_sheetH = 0;
if (_sheet == Sheet.Settings) { _sheetTitle = "Settings"; CopySettings(); }
ImGui.OpenPopup(SheetId);
}
if (_openKinds)
{
_openKinds = false;
ImGui.OpenPopup(KindsId);
}
KindsPopup();
if (_sheet == Sheet.None) return;
float width = Math.Min(_sheet switch { Sheet.Layouts => D(860), Sheet.Settings => D(640), _ => D(600) }, Math.Max(D(260), _winSize.X - D(24)));
float maxH = Math.Max(_winSize.Y - D(24), D(320));
float h = _sheetH > 0 ? Math.Min(_sheetH, maxH) : Math.Min(D(360), maxH);
ImGui.SetNextWindowPos(_winMin + _winSize * 0.5f, ImGuiCond.Always, new Vector2(0.5f, 0.5f));
ImGui.SetNextWindowSize(new Vector2(width, h), ImGuiCond.Always);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
bool open = ImGui.BeginPopup(SheetId, ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoSavedSettings);
ImGui.PopStyleVar();
if (!open)
{
CloseSheet();
return;
}
try
{
_closeSheet = false;
Vector2 o = Round(ImGui.GetCursorScreenPos());
float w = MathF.Floor(ImGui.GetContentRegionAvail().X);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float y = SheetHeader(dl, o, w, _sheetTitle);
float x = o.X + D(18), cw = w - D(36);
y += D(16);
y = _sheet switch
{
Sheet.Item => ItemSheet(dl, x, y, cw),
Sheet.Drop => DropSheet(dl, x, y, cw),
Sheet.Layouts => LayoutsSheet(dl, x, y, cw),
Sheet.Job => JobSheet(dl, x, y, cw),
_ => SettingsSheet(dl, x, y, cw),
};
y += D(18);
ImGui.SetCursorScreenPos(o);
ImGui.Dummy(new Vector2(w, y - o.Y));
_sheetH = y - o.Y + 2;
if (_closeSheet)
{
ImGui.CloseCurrentPopup();
CloseSheet();
}
}
finally { ImGui.EndPopup(); }
}
/// <summary>The sheet's title row and its close button (.sheet header). Returns the y under it.</summary>
private float SheetHeader(ImDrawListPtr dl, Vector2 o, float w, string title)
{
float h = D(56);
ImFontPtr f = Font(RynthUiFont.UiBold14);
TextFit(dl, f, new Vector2(o.X + D(18), o.Y + (h - Fs(f)) * 0.5f), Ink, title, w - D(36) - D(40));
if (IconButton("##rs_sheetx", RynthIcons.X, new Vector2(o.X + w - D(18) - D(32), o.Y + (h - D(32)) * 0.5f), new Vector2(D(32), D(32)), "Close"))
_closeSheet = true;
dl.AddLine(new Vector2(o.X, o.Y + h), new Vector2(o.X + w, o.Y + h), Line);
return o.Y + h;
}
// ── An item's detail ─────────────────────────────────────────────────
// The "why" line laid out in words (bold runs too), made when it opens or the item's state changes.
private readonly List<(string Text, bool Bold, Vector2 At)> _why = new();
private (TileRule, int, int, bool, int) _whyKey;
private float _whyH;
private float ItemSheet(ImDrawListPtr dl, float x, float y, float w)
{
ImFontPtr small = Font(RynthUiFont.Ui10);
if (!_m.TilesById.TryGetValue(_sheetItem, out TileModel? t))
{
Text(dl, Font(RynthUiFont.Ui11), new Vector2(x, y), Ink2, "That item isn't in your packs now.");
return y + Fs(Font(RynthUiFont.Ui11));
}
// The picture, the name and count, the kind and where it is.
float big = D(56);
Vector2 bp = new(x, y);
IntPtr tex = _host.GetIconTexture(RynthIconKind.Object, t.Id);
if (tex != IntPtr.Zero)
{
dl.AddRectFilled(bp, bp + new Vector2(big, big), Well, D(12));
dl.AddImageRounded(tex, bp + new Vector2(D(4), D(4)), bp + new Vector2(big - D(4), big - D(4)), Vector2.Zero, Vector2.One, White, D(8));
}
else
{
dl.AddRectFilled(bp, bp + new Vector2(big, big), Kinds2Abgr(t.KindColor), D(12));
ImFontPtr af = Font(RynthUiFont.NarrowBold13);
Vector2 ts = af.CalcTextSizeA(Fs(af), float.MaxValue, 0, t.Initials);
dl.AddText(af, Fs(af), Round(bp + (new Vector2(big, big) - ts) * 0.5f), White, t.Initials);
}
dl.AddRect(bp, bp + new Vector2(big, big), A(Black, 0.5f), D(12));
ImFontPtr bold = Font(RynthUiFont.UiBold14), mono = Font(RynthUiFont.Dash10);
float tx = x + big + D(14), tw = w - big - D(14);
float ty = y + (big - (Fs(bold) + D(4) + Fs(small))) * 0.5f;
string qty = QtyText(t.Qty);
float qw = qty.Length > 0 ? Measure(mono, qty).X + D(8) : 0;
string name = Fit(bold, t.Name, tw - qw);
Text(dl, bold, new Vector2(tx, ty), Ink, name);
if (qty.Length > 0) Text(dl, mono, new Vector2(tx + Measure(bold, name).X + D(8), ty + (Fs(bold) - Fs(mono)) * 0.5f + D(1)), Ink2, qty);
TextFit(dl, small, new Vector2(tx, ty + Fs(bold) + D(4)), Ink3, KindAndPlace(t), tw);
y += big + D(14);
// Why it is where it is.
LayoutWhy(t, w - D(24));
dl.AddRectFilled(new Vector2(x, y), new Vector2(x + w, y + _whyH + D(20)), Card, D(10));
dl.AddRect(new Vector2(x, y), new Vector2(x + w, y + _whyH + D(20)), Line, D(10));
ImFontPtr wf = Font(RynthUiFont.Ui11), wb = Font(RynthUiFont.UiBold11);
foreach (var seg in _why)
Text(dl, seg.Bold ? wb : wf, new Vector2(x + D(12), y + D(10)) + seg.At, seg.Bold ? Ink : Ink2, seg.Text);
y += _whyH + D(20) + D(14);
// Send to a side pack (its own is greyed).
y = Eyebrow(dl, new Vector2(x, y), "SEND TO", string.Empty);
float gap = D(8), minW = D(130);
int per = Math.Max(1, (int)MathF.Floor((w + gap) / (minW + gap)));
float bw = MathF.Floor((w - gap * (per - 1)) / per), bh = D(36);
for (int i = 0; i < _m.Packs.Length; i++)
{
PackModel pk = _m.Packs[i];
Vector2 p = new(x + i % per * (bw + gap), y + i / per * (bh + gap));
ImGui.PushID(i);
bool here = t.Where == pk.Number;
if (PackButton(dl, p, new Vector2(bw, bh), pk, !here) && !here)
{
_act.MoveOnce(t.Id, pk.Number);
_closeSheet = true;
}
ImGui.PopID();
}
int rows = (_m.Packs.Length + per - 1) / per;
if (rows == 0)
{
Text(dl, small, new Vector2(x, y), Ink3, "You carry no side packs.");
y += Fs(small) + D(14);
}
else y += rows * (bh + gap) - gap + D(14);
// Leave it alone / let RynthSort move it; back to the main pack; select it in the game.
float bx = x, aby = y, abh = D(34);
bool holdOn = _m.Settings.HoldMin > 0;
if (t.Held)
{
if (Button("##rs_release", "Let RynthSort move it", null, new Vector2(bx, aby), abh, Look.Normal, true,
"Stop leaving it alone: the next sort moves it like any other item.", out float w1))
{ _act.Release(t.Id); _closeSheet = true; }
bx += w1 + D(8);
}
else
{
if (Button("##rs_hold", HoldLabel(), RynthIcons.Lock, new Vector2(bx, aby), abh, Look.Normal, holdOn,
holdOn ? "No sort moves it until the time is up (Settings: Leave items I use alone for)." : "Leaving items alone is off: turn it on in Settings.", out float w1))
{ _act.Hold(t.Id); _closeSheet = true; }
bx += w1 + D(8);
}
if (t.Where != 0)
{
if (Button("##rs_tomain", "Back to the main pack", null, new Vector2(bx, aby), abh, Look.Quiet, true,
"It goes to the main pack now and is left alone for a while, so a sort doesn't send it back.", out float w2))
{ _act.MoveOnce(t.Id, 0); _closeSheet = true; }
bx += w2 + D(8);
}
if (_m.CanSelect && bx + ButtonWidth("Select in game", false) <= x + w)
{
if (Button("##rs_select", "Select in game", null, new Vector2(bx, aby), abh, Look.Quiet, true,
"Selects it in the game, as clicking it in your inventory would. Nothing moves.", out _))
_act.SelectInGame(t.Id);
}
return aby + abh;
}
// "×320" for the open item, made once per count.
private string _qtyFor = string.Empty, _qtyText = string.Empty;
private string QtyText(string qty)
{
if (qty.Length == 0) return string.Empty;
if (!ReferenceEquals(qty, _qtyFor)) { _qtyFor = qty; _qtyText = "×" + qty; }
return _qtyText;
}
// "Leave it alone for 3 min", made once per setting.
private int _holdLabelFor = -1;
private string _holdLabel = string.Empty;
private string HoldLabel()
{
int m = _m.Settings.HoldMin;
if (m != _holdLabelFor) { _holdLabelFor = m; _holdLabel = m > 0 ? $"Leave it alone for {m} min" : "Leave it alone (off)"; }
return _holdLabel;
}
// "Gems · in Satchel" for the open item, made once per place.
private (uint, int) _kindPlaceFor;
private string _kindPlace = string.Empty;
private string KindAndPlace(TileModel t)
{
if (_kindPlaceFor != (t.Id, t.Where)) { _kindPlaceFor = (t.Id, t.Where); _kindPlace = ScreenText.KindAndPlace(t, _m); }
return _kindPlace;
}
/// <summary>Lays the "why" runs out in words across <paramref name="w"/> (only when the item's state or the width changes).</summary>
private void LayoutWhy(TileModel t, float w)
{
var key = (t.Rule, t.RulePack * 1000 + t.Where, (int)w, t.Held, t.RuleText.Length);
if (key == _whyKey && _why.Count > 0) return;
_whyKey = key;
_why.Clear();
ImFontPtr wf = Font(RynthUiFont.Ui11), wb = Font(RynthUiFont.UiBold11);
float lineH = Math.Max(Fs(wf), Fs(wb)) + D(4);
float x = 0, y = 0;
foreach (ScreenText.Run run in ScreenText.Why(t, _m))
{
ImFontPtr f = run.Bold ? wb : wf;
int start = 0;
string s = run.Text;
while (start < s.Length)
{
int sp = s.IndexOf(' ', start);
int end = sp < 0 ? s.Length : sp + 1;
string word = s.Substring(start, end - start);
float ww = f.CalcTextSizeA(Fs(f), float.MaxValue, 0, word).X;
float trimmed = f.CalcTextSizeA(Fs(f), float.MaxValue, 0, word.TrimEnd()).X;
if (x > 0 && x + trimmed > w) { x = 0; y += lineH; }
_why.Add((word, run.Bold, new Vector2(x, y)));
x += ww;
start = end;
}
}
_whyH = y + lineH - D(4);
}
/// <summary>A pack button (the detail popup's "Send to"): the bag badge and the pack's name.</summary>
private bool PackButton(ImDrawListPtr dl, Vector2 p, Vector2 s, PackModel pk, bool enabled)
{
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton("##pk", s) && enabled;
bool hot = enabled && ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(enabled ? pk.Tip : "It is in this pack.");
float alpha = enabled ? 1f : 0.45f;
dl.AddRectFilled(p, p + s, A(hot ? CardHot : Card2, alpha), D(10));
dl.AddRect(p, p + s, A(Line2, alpha), D(10));
float bag = D(20);
Bag(dl, new Vector2(p.X + D(10), p.Y + (s.Y - bag) * 0.5f), bag, pk.Badge);
ImFontPtr f = Font(RynthUiFont.UiBold11);
TextFit(dl, f, new Vector2(p.X + D(10) + bag + D(8), p.Y + (s.Y - Fs(f)) * 0.5f), A(Ink, alpha), pk.Name, s.X - bag - D(28));
return clicked;
}
// ── The drop choices ─────────────────────────────────────────────────
private const string NameRuleText = "A rule by name. A name beats a kind, so these go here even if their kind goes elsewhere.";
private float DropSheet(ImDrawListPtr dl, float x, float y, float w)
{
if (!_m.TilesById.TryGetValue(_sheetItem, out TileModel? t) || _m.Pack(_sheetPack) == null)
{
Text(dl, Font(RynthUiFont.Ui11), new Vector2(x, y), Ink2, "That item or pack isn't there now.");
return y + Fs(Font(RynthUiFont.Ui11));
}
IntPtr tex = _host.GetIconTexture(RynthIconKind.Object, t.Id);
if (Choice(dl, "##rs_kind", new Vector2(x, y), w, null, tex, _dropKind, _dropKindText, out float h))
{ _act.Unhold(t.Id); _act.SendKind(_sheetPack, t.Cls); _closeSheet = true; }
y += h + D(8);
if (Choice(dl, "##rs_name", new Vector2(x, y), w, RynthIcons.TextAa, IntPtr.Zero, _dropName, NameRuleText, out h))
{ _act.Unhold(t.Id); _act.SendName(_sheetPack, t.Id); _closeSheet = true; }
y += h + D(8);
if (Choice(dl, "##rs_once", new Vector2(x, y), w, RynthIcons.ArrowRight, IntPtr.Zero, "Just move it, no rule", _dropOnceText, out h))
{ _act.MoveOnce(t.Id, _sheetPack); _closeSheet = true; }
return y + h;
}
/// <summary>One of the drop choices (.choice): an icon box, a bold line and a line under it. True when clicked.</summary>
private bool Choice(ImDrawListPtr dl, string id, Vector2 p, float w, string? glyph, IntPtr tex, string strong, string desc, out float h)
{
ImFontPtr bf = Font(RynthUiFont.UiBold11), sf = Font(RynthUiFont.Ui10);
float pad = D(12), box = D(34), tw = w - 2 * pad - box - D(12);
float descH = sf.CalcTextSizeA(Fs(sf), float.MaxValue, tw, desc).Y;
h = Math.Max(box, Fs(bf) + D(3) + descH) + 2 * pad;
Vector2 s = new(w, h);
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton(id, s);
bool hot = ImGui.IsItemHovered();
dl.AddRectFilled(p, p + s, hot ? DropBg : Card, D(12));
dl.AddRect(p, p + s, hot ? Teal : Line2, D(12));
Vector2 bp = new(p.X + pad, p.Y + (h - box) * 0.5f);
dl.AddRectFilled(bp, bp + new Vector2(box, box), Card2, D(9));
if (tex != IntPtr.Zero) dl.AddImageRounded(tex, bp + new Vector2(D(3), D(3)), bp + new Vector2(box - D(3), box - D(3)), Vector2.Zero, Vector2.One, White, D(6));
else if (glyph != null) DrawIcon(dl, glyph, bp, new Vector2(box, box), D(18), Teal);
float tx = bp.X + box + D(12), ty = p.Y + (h - (Fs(bf) + D(3) + descH)) * 0.5f;
TextFit(dl, bf, new Vector2(tx, ty), Ink, strong, tw);
dl.AddText(sf, Fs(sf), Round(new Vector2(tx, ty + Fs(bf) + D(3))), Ink3, desc, tw);
return clicked;
}
// ── A pack's job ─────────────────────────────────────────────────────
private string _jobMule = string.Empty;
private void OpenJob(int pack)
{
PackModel? pk = _m.Pack(pack);
if (pk == null) return;
_sheetPack = pack;
_sheetTitle = "A job for " + PackWords(pk);
_jobMule = pk.JobMule;
OpenSheet(Sheet.Job);
}
private const string JobHint = "A job fills the pack with what another tool picks, besides its own rules. A name rule still comes first; a job comes before a kind. Nothing moves until you sort.";
private float JobSheet(ImDrawListPtr dl, float x, float y, float w)
{
PackModel? pk = _m.Pack(_sheetPack);
if (pk == null)
{
Text(dl, Font(RynthUiFont.Ui11), new Vector2(x, y), Ink2, "That pack isn't carried now.");
return y + Fs(Font(RynthUiFont.Ui11));
}
ImFontPtr small = Font(RynthUiFont.Ui10);
y = Wrapped(dl, small, new Vector2(x, y), w, Ink3, JobHint) + D(12);
if (pk.JobLine.Length > 0)
y = Wrapped(dl, small, new Vector2(x, y), w, pk.JobProblem ? Amber : DoneInk, pk.JobLine) + D(12);
bool Pick(string id, string glyph, string strong, string desc, Sorting.JobKind kind, ref float yy)
{
bool now = pk.Job == kind;
bool clicked = Choice(dl, id, new Vector2(x, yy), w, glyph, IntPtr.Zero, now ? strong + " (now)" : strong, desc, out float h);
yy += h + D(8);
return clicked;
}
if (Pick("##job_salvage", RynthIcons.Hammer, "Salvage", "Items RynthAi's loot profile marks Salvage. Needs RynthAi.", Sorting.JobKind.Salvage, ref y))
{ _act.SetJob(_sheetPack, (int)Sorting.JobKind.Salvage, string.Empty); _closeSheet = true; }
if (Pick("##job_sell", RynthIcons.Coins, "Sell", "Items RynthAi's AutoVendor would sell (its default.utl). Needs RynthAi. With AutoVendor set to sell from the main pack only, it won't sell them from here.", Sorting.JobKind.Sell, ref y))
{ _act.SetJob(_sheetPack, (int)Sorting.JobKind.Sell, string.Empty); _closeSheet = true; }
if (Pick("##job_mule", RynthIcons.User, "Mule", "Items set aside for your mule: what RynthAi's AutoTrade would give it (its <mule>.utl, else default.utl). Needs RynthAi.", Sorting.JobKind.Mule, ref y))
{ _act.SetJob(_sheetPack, (int)Sorting.JobKind.Mule, _jobMule); _closeSheet = true; }
// The mule's name (optional): AutoTrade's profile named after it, else its default.utl.
float fh = ImGui.GetFrameHeight();
ImGui.SetCursorScreenPos(new Vector2(x, y));
ImGui.SetNextItemWidth(w);
ImGui.InputTextWithHint("##jobmule", "The mule's name (optional)", ref _jobMule, 64);
y += fh + D(12);
if (pk.Job != Sorting.JobKind.None)
{
if (Button("##job_none", "No job: only its rules", null, new Vector2(x, y), D(34), Look.Quiet, true,
"Take the job off. Items already in the pack stay; Clean sends back what no rule wants.", out _))
{ _act.SetJob(_sheetPack, 0, string.Empty); _closeSheet = true; }
y += D(34);
}
return y;
}
// ── Layouts ──────────────────────────────────────────────────────────
private const string LayoutsHint = "Each kind goes to the pack that already holds most of it, so the fewest items move. Nothing moves until you sort.";
private readonly Dictionary<string, string> _layoutCaps = new();
private readonly Dictionary<string, string> _layoutLeft = new();
private int _layoutLeftVersion = -1;
private float LayoutsSheet(ImDrawListPtr dl, float x, float y, float w)
{
ImFontPtr small = Font(RynthUiFont.Ui10), bold = Font(RynthUiFont.UiBold11), mono = Font(RynthUiFont.Dash10);
y = Wrapped(dl, small, new Vector2(x, y), w, Ink3, LayoutsHint) + D(14);
LayoutCard[] cards = _m.Layouts;
if (_m.Packs.Length == 0)
{
Text(dl, Font(RynthUiFont.Ui11), new Vector2(x, y), Amber, "You carry no side packs, so a layout has nowhere to put things.");
return y + Fs(Font(RynthUiFont.Ui11));
}
if (cards.Length == 0)
{
Text(dl, small, new Vector2(x, y), Ink3, "Fitting the layouts to your packs…");
return y + Fs(small);
}
float gap = D(10), pad = D(12);
int per = Math.Max(1, (int)MathF.Floor((w + gap) / (D(260) + gap)));
float cw = MathF.Floor((w - gap * (per - 1)) / per), iw = cw - 2 * pad;
float barsH = D(30);
for (int i = 0; i < cards.Length; i += per)
{
float rowH = 0;
for (int j = i; j < cards.Length && j < i + per; j++)
rowH = Math.Max(rowH, pad + Fs(bold) + D(8) + small.CalcTextSizeA(Fs(small), float.MaxValue, iw, cards[j].Blurb).Y + D(8) + barsH + D(8) + Fs(mono) + pad);
for (int j = i; j < cards.Length && j < i + per; j++)
{
LayoutCard c = cards[j];
Vector2 p = new(x + (j - i) * (cw + gap), y), s = new(cw, rowH);
bool picked = _layoutPicked == c.Key;
ImGui.PushID(j);
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton("##lay", s);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(picked ? "Click to close the preview" : "Click to see which pack gets which kinds");
ImGui.PopID();
if (clicked) _layoutPicked = picked ? null : c.Key;
dl.AddRectFilled(p, p + s, picked ? DropBg : Card, D(12));
dl.AddRect(p, p + s, picked ? Teal : hot ? Argb(0xFF3C5970) : Line2, D(12));
float cy = p.Y + pad;
Text(dl, bold, new Vector2(p.X + pad, cy), Ink, c.Name);
cy += Fs(bold) + D(8);
dl.AddText(small, Fs(small), Round(new Vector2(p.X + pad, cy)), Ink3, c.Blurb, iw);
cy += small.CalcTextSizeA(Fs(small), float.MaxValue, iw, c.Blurb).Y + D(8);
Bars(dl, new Vector2(p.X + pad, cy), iw, barsH, c.Bars);
cy = p.Y + rowH - pad - Fs(mono);
Text(dl, mono, new Vector2(p.X + pad, cy), Sky, c.Meta);
}
y += rowH + gap;
}
y -= gap;
LayoutCard? chosen = null;
foreach (LayoutCard c in cards) if (c.Key == _layoutPicked) { chosen = c; break; }
if (chosen == null) return y;
// The preview: which pack gets which kinds, what stays in the main pack, then Use / Cancel.
y += D(14);
dl.AddLine(new Vector2(x, y), new Vector2(x + w, y), Line);
y += D(14);
if (!_layoutCaps.TryGetValue(chosen.Key, out string? caps)) _layoutCaps[chosen.Key] = caps = chosen.Name.ToUpperInvariant() + " ON YOUR PACKS";
y = Eyebrow(dl, new Vector2(x, y), caps, string.Empty);
ImFontPtr nf = Font(RynthUiFont.Ui11);
float nameW = D(110), chipsX = x + D(24) + D(10) + nameW + D(10), chipsW = x + w - chipsX;
foreach (LayoutRow row in chosen.Rows)
{
float rh = Math.Max(D(26), PreviewChips(default, row, Vector2.Zero, chipsW, draw: false));
Bag(dl, new Vector2(x, y + (rh - D(24)) * 0.5f), D(24), row.Badge);
TextFit(dl, nf, new Vector2(x + D(24) + D(10), y + (rh - Fs(nf)) * 0.5f), Ink, row.PackName, nameW);
if (row.Chips.Length == 0) Text(dl, small, new Vector2(chipsX, y + (rh - Fs(small)) * 0.5f), Ink3, "Stays free");
else PreviewChips(dl, row, new Vector2(chipsX, y), chipsW, draw: true);
y += rh + D(8);
}
if (_layoutLeftVersion != _m.Version) { _layoutLeft.Clear(); _layoutLeftVersion = _m.Version; }
if (!_layoutLeft.TryGetValue(chosen.Key, out string? left)) _layoutLeft[chosen.Key] = left = chosen.Left + chosen.Replaces;
y = Wrapped(dl, small, new Vector2(x, y), w, Ink3, left) + D(12);
if (Button("##rs_uselay", "Use this layout", null, new Vector2(x, y), D(34), Look.Primary, true,
"Set these rules. Nothing moves: press Sort now afterwards, or turn on Auto-sort. Undo brings your rules back.", out float uw))
{
_act.UseLayout(chosen.Key);
_closeSheet = true;
}
if (Button("##rs_laycancel", "Cancel", null, new Vector2(x + uw + D(8), y), D(34), Look.Normal, true, null, out _))
_layoutPicked = null;
return y + D(34);
}
/// <summary>A layout card's mini bars (.lay .bars): a well per pack with a square per kind.</summary>
private void Bars(ImDrawListPtr dl, Vector2 p, float w, float h, uint[][] bars)
{
int n = Math.Max(1, bars.Length);
float gap = D(4), bw = (w - gap * (n - 1)) / n, sq = D(7), sgap = D(2);
for (int i = 0; i < bars.Length; i++)
{
Vector2 bp = new(p.X + i * (bw + gap), p.Y);
dl.AddRectFilled(bp, bp + new Vector2(bw, h), Well, D(6));
float sx = bp.X + D(4), sy = bp.Y + D(4);
foreach (uint col in bars[i])
{
if (sx + sq > bp.X + bw - D(2)) { sx = bp.X + D(4); sy += sq + sgap; }
dl.AddRectFilled(new Vector2(sx, sy), new Vector2(sx + sq, sy + sq), Kinds2Abgr(col), D(2));
sx += sq + sgap;
}
}
}
/// <summary>A preview row's kind chips (no x). Returns the height; draws only when <paramref name="draw"/>.</summary>
private float PreviewChips(ImDrawListPtr dl, LayoutRow row, Vector2 p, float w, bool draw)
{
ImFontPtr f = Font(RynthUiFont.Ui10);
float h = D(26), gap = D(6), x = p.X, y = p.Y;
foreach (ChipModel c in row.Chips)
{
float cw = D(9) + D(8) + D(6) + Measure(f, c.Label).X + D(9);
if (x > p.X && x + cw > p.X + w) { x = p.X; y += h + gap; }
if (draw)
{
Vector2 cp = new(x, y);
dl.AddRectFilled(cp, cp + new Vector2(cw, h), Card2, h * 0.5f);
dl.AddRect(cp, cp + new Vector2(cw, h), Line2, h * 0.5f);
dl.AddCircleFilled(new Vector2(cp.X + D(9) + D(4), cp.Y + h * 0.5f), D(4), Kinds2Abgr(c.Dot), 12);
Text(dl, f, new Vector2(cp.X + D(9) + D(8) + D(6), cp.Y + (h - Fs(f)) * 0.5f), Ink, c.Label);
}
x += cw + gap;
}
return y + h - p.Y;
}
// ── Settings ─────────────────────────────────────────────────────────
// What the sliders and boxes show while the sheet is open (copied from the model when it opens).
private int _dSettle, _dHold, _dGap;
private bool _dCombat, _dOrder, _dKind, _dHandy;
private string _handyText = string.Empty;
private const string HandyKindsId = "##rs_handykinds";
/// <summary>
/// The handy list under its switch: its kinds and names as chips (the x takes one off), "+ Add a
/// kind..." and a box for a part of a name. Returns the y under it.
/// </summary>
private float HandyList(ImDrawListPtr dl, float x, float y, float w, bool enabled)
{
ImFontPtr f = Font(RynthUiFont.Ui10);
float h = D(26), gap = D(6), cx = x;
y += D(10);
ImGui.PushID("handy");
try
{
if (!enabled) ImGui.BeginDisabled();
ChipModel[] chips = _m.Settings.HandyChips;
for (int i = 0; i < chips.Length; i++)
{
ChipModel c = chips[i];
float cw = ChipWidth(f, c);
if (cx > x && cx + cw > x + w) { cx = x; y += h + gap; }
if (HandyChip(dl, c, new Vector2(cx, y), new Vector2(cw, h), i))
{
if (c.IsName) _act.HandyName(c.Name, false);
else _act.HandyKind(c.Cls, false);
}
cx += cw + gap;
}
float aw = Measure(f, AddKindLabel).X + D(20);
if (cx > x && cx + aw > x + w) { cx = x; y += h + gap; }
Vector2 ap = new(cx, y), asz = new(aw, h);
ImGui.SetCursorScreenPos(ap);
bool open = ImGui.InvisibleButton("##handyadd", asz);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip("Pick a kind of item to keep at the front of the main pack.");
if (hot) dl.AddRectFilled(ap, ap + asz, A(Teal, 0.08f), h * 0.5f);
Dashed(dl, ap, ap + asz, hot ? Teal : Line2, D(4));
Text(dl, f, new Vector2(ap.X + D(10), ap.Y + (h - Fs(f)) * 0.5f), Teal, AddKindLabel);
if (open) ImGui.OpenPopup(HandyKindsId);
HandyKindsPopup(new Vector2(ap.X, ap.Y + h + D(4)));
y += h + D(10);
// A part of a name ("Potion"): items with it in their name count whatever their kind.
float bw = ButtonWidth("Add name", false), fh = ImGui.GetFrameHeight();
ImGui.SetCursorScreenPos(new Vector2(x, y));
ImGui.SetNextItemWidth(Math.Max(D(80), w - bw - D(8)));
bool enter = ImGui.InputTextWithHint("##handyname", "Part of a name, like Potion", ref _handyText, 64, ImGuiInputTextFlags.EnterReturnsTrue);
bool add = Button("##handyaddname", "Add name", null, new Vector2(x + w - bw, y + (fh - D(30)) * 0.5f), D(30), Look.Normal, _handyText.Trim().Length > 0,
"Items with this in their name count as handy, whatever their kind.", out _);
if ((enter || add) && _handyText.Trim().Length > 0)
{
_act.HandyName(_handyText.Trim(), true);
_handyText = string.Empty;
}
y += Math.Max(fh, D(30)) + D(12);
if (!enabled) ImGui.EndDisabled();
}
finally { ImGui.PopID(); }
dl.AddLine(new Vector2(x, y), new Vector2(x + w, y), Line);
return y;
}
/// <summary>A handy-list chip (a kind with its dot, or a name dashed) and its x. True when the x was clicked.</summary>
private bool HandyChip(ImDrawListPtr dl, ChipModel c, Vector2 p, Vector2 s, int index)
{
ImGui.PushID(index);
try
{
ImFontPtr f = Font(RynthUiFont.Ui10);
dl.AddRectFilled(p, p + s, Card2, s.Y * 0.5f);
if (c.IsName) Dashed(dl, p, p + s, Line2, D(3));
else dl.AddRect(p, p + s, Line2, s.Y * 0.5f);
float tx = p.X + D(9);
if (!c.IsName)
{
dl.AddCircleFilled(new Vector2(tx + D(4), p.Y + s.Y * 0.5f), D(4), Kinds2Abgr(c.Dot), 12);
tx += D(8) + D(6);
}
Text(dl, f, new Vector2(tx, p.Y + (s.Y - Fs(f)) * 0.5f), Ink, c.Label);
Vector2 xs = new(D(18), D(18));
Vector2 xp = new(p.X + s.X - D(6) - xs.X, p.Y + (s.Y - xs.Y) * 0.5f);
ImGui.SetCursorScreenPos(p);
ImGui.InvisibleButton("##hc", new Vector2(Math.Max(1, xp.X - p.X), s.Y));
SafeImGui.SetItemTooltip(c.Tip);
ImGui.SetCursorScreenPos(xp);
bool x = ImGui.InvisibleButton("##hx", xs);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip("Take it off the handy list");
if (hot) dl.AddCircleFilled(xp + xs * 0.5f, xs.X * 0.5f, Argb(0xFF24344A), 16);
DrawIcon(dl, RynthIcons.X, xp, xs, D(11), hot ? Ink : Ink3);
return x;
}
finally { ImGui.PopID(); }
}
/// <summary>The handy list's kind picker (a popup over the settings sheet).</summary>
private void HandyKindsPopup(Vector2 anchor)
{
if (!ImGui.IsPopupOpen(HandyKindsId)) return;
ImGui.SetNextWindowPos(anchor, ImGuiCond.Appearing);
ImGui.SetNextWindowSizeConstraints(new Vector2(D(220), 0), new Vector2(D(320), D(340)));
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(D(8), D(8)));
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, D(10));
bool open = ImGui.BeginPopup(HandyKindsId);
ImGui.PopStyleVar(2);
if (!open) return;
try
{
ImFontPtr f = Font(RynthUiFont.Ui11);
float rowH = Fs(f) + D(10);
SafeImGui.TextDisabled("Keep at the front of the main pack");
KindChoice[] kinds = _m.Settings.HandyChoices;
for (int i = 0; i < kinds.Length; i++)
{
KindChoice k = kinds[i];
ImGui.PushID(i);
Vector2 p = ImGui.GetCursorScreenPos();
bool picked = ImGui.Selectable("##hk", false, ImGuiSelectableFlags.None, new Vector2(0, rowH));
ImGui.PopID();
ImDrawListPtr pdl = ImGui.GetWindowDrawList();
pdl.AddCircleFilled(new Vector2(p.X + D(8), p.Y + rowH * 0.5f), D(4), Kinds2Abgr(k.Dot), 12);
Text(pdl, f, new Vector2(p.X + D(20), p.Y + (rowH - Fs(f)) * 0.5f), Ink, k.Label);
if (picked) _act.HandyKind(k.Cls, true);
}
}
finally { ImGui.EndPopup(); }
}
private void CopySettings()
{
SettingsModel s = _m.Settings;
_dHandy = s.HandyOn;
_dSettle = s.SettleSec;
_dHold = s.HoldMin;
_dGap = s.GapMs;
_dCombat = s.SortInCombat;
_dOrder = s.OrderInPacks;
_dKind = s.KindFirst;
}
private static readonly string[] SecondsText = Units(0, 30, " s"), MinutesText = Units(0, 30, " min");
private static string[] Units(int from, int to, string unit)
{
var a = new string[to - from + 1];
for (int i = from; i <= to; i++) a[i - from] = i.ToString(System.Globalization.CultureInfo.InvariantCulture) + unit;
return a;
}
private int _gapFor = -1;
private string _gapText = string.Empty;
private float SettingsSheet(ImDrawListPtr dl, float x, float y, float w)
{
y = SliderRow(dl, x, y, w, "Wait before new loot moves", SecondsText[Math.Clamp(_dSettle, 0, 30)], "##settle", ref _dSettle, 0, 30,
"So you can look at a new item before it goes to its pack.", out bool changed);
if (changed) _act.SetSettle(_dSettle);
y = SliderRow(dl, x, y, w, "Leave items I use alone for", _dHold == 0 ? "off" : MinutesText[Math.Clamp(_dHold, 0, 30)], "##hold", ref _dHold, 0, 30,
"An item you select, drag, move, take off or pick up stays where you put it. 0 turns this off.", out changed);
if (changed) _act.SetHold(_dHold);
if (_dGap != _gapFor) { _gapFor = _dGap; _gapText = _dGap.ToString(System.Globalization.CultureInfo.InvariantCulture) + " ms"; }
y = SliderRow(dl, x, y, w, "Pause between moves", _gapText, "##gap", ref _dGap, 100, 3000,
"Auto-sort's pause between two moves, to leave the bot room. Sort now, Clean and Empty don't wait.", out changed);
if (changed) _act.SetGap(_dGap);
y = CheckRow(dl, x, y, w, "Sort during fights", "##combat", ref _dCombat, true, "Off: moves wait until the fight is over.", out changed);
if (changed) _act.SetCombat(_dCombat);
bool can = _m.Settings.CanOrder;
y = CheckRow(dl, x, y, w, "Put items in order inside packs", "##order", ref _dOrder, can,
can ? "Like items side by side, A-Z by name." : "This RynthCore can't read the order inside packs (it needs plugin API 80): items go to their packs but aren't put in order.",
out changed);
if (changed) _act.SetOrder(_dOrder);
y = CheckRow(dl, x, y, w, "Group by kind first", "##kind", ref _dKind, can, "Order by kind, then A-Z by name, instead of A-Z by name only.", out changed);
if (changed) _act.SetKindFirst(_dKind);
y = CheckRow(dl, x, y, w, "Keep handy items at the front of the main pack", "##handy", ref _dHandy, can,
can ? "The things you reach for sit in the main pack's first slots. Items you are using stay where you put them. A kind a pack's rule names goes to that pack instead."
: "This RynthCore can't move an item to a slot (it needs plugin API 80), so the main pack's order is left as it is.",
out changed);
if (changed) _act.SetHandy(_dHandy);
y = HandyList(dl, x, y, w, can);
// Empty side packs.
ImFontPtr lf = Font(RynthUiFont.Ui11), small = Font(RynthUiFont.Ui10);
float bw = ButtonWidth("Empty all", false);
y += D(12);
Text(dl, lf, new Vector2(x, y + (D(34) - Fs(lf)) * 0.5f), Ink, "Empty side packs");
if (Button("##rs_unpack", "Empty all", null, new Vector2(x + w - bw, y), D(34), Look.Normal, true,
"Also: /rsort unpack", out _))
{
_act.EmptySidePacks();
_closeSheet = true;
}
y += D(34) + D(6);
y = Wrapped(dl, small, new Vector2(x, y), w, Ink3, "Everything goes to the main pack, and auto-sort turns off so nothing moves back.") + D(18);
dl.AddLine(new Vector2(x, y), new Vector2(x + w, y), Line);
y += D(12);
return Wrapped(dl, small, new Vector2(x, y), w, Ink3,
"Drag the header to move this window; Ctrl+wheel over it makes it bigger or smaller. Chat: /rsort on | off | now | clean | back | unpack [pack] | add <pack> | status");
}
private float SliderRow(ImDrawListPtr dl, float x, float y, float w, string label, string value, string id, ref int v, int min, int max, string help, out bool changed)
{
ImFontPtr lf = Font(RynthUiFont.Ui11), vf = Font(RynthUiFont.Dash10), small = Font(RynthUiFont.Ui10);
y += D(12);
Text(dl, lf, new Vector2(x, y), Ink, label);
Text(dl, vf, new Vector2(x + w - Measure(vf, value).X, y + (Fs(lf) - Fs(vf)) * 0.5f), Sky, value);
y += Fs(lf) + D(8);
ImGui.SetCursorScreenPos(new Vector2(x, y));
ImGui.SetNextItemWidth(w);
int before = v;
ImGui.SliderInt(id, ref v, min, max, "");
changed = v != before;
y += ImGui.GetFrameHeight() + D(6);
y = Wrapped(dl, small, new Vector2(x, y), w, Ink3, help) + D(12);
dl.AddLine(new Vector2(x, y), new Vector2(x + w, y), Line);
return y;
}
private float CheckRow(ImDrawListPtr dl, float x, float y, float w, string label, string id, ref bool v, bool enabled, string help, out bool changed)
{
ImFontPtr lf = Font(RynthUiFont.Ui11), small = Font(RynthUiFont.Ui10);
y += D(12);
float fh = ImGui.GetFrameHeight();
Text(dl, lf, new Vector2(x, y + (fh - Fs(lf)) * 0.5f), enabled ? Ink : Ink3, label);
ImGui.SetCursorScreenPos(new Vector2(x + w - fh, y));
if (!enabled) ImGui.BeginDisabled();
bool before = v;
ImGui.Checkbox(id, ref v);
if (!enabled) ImGui.EndDisabled();
changed = v != before;
y += fh + D(6);
y = Wrapped(dl, small, new Vector2(x, y), w, Ink3, help) + D(12);
dl.AddLine(new Vector2(x, y), new Vector2(x + w, y), Line);
return y;
}
// ── The kind picker ──────────────────────────────────────────────────
private void KindsPopup()
{
if (!ImGui.IsPopupOpen(KindsId)) return;
ImGui.SetNextWindowPos(_kindsAnchor, ImGuiCond.Appearing);
ImGui.SetNextWindowSizeConstraints(new Vector2(D(330), 0), new Vector2(D(440), D(380))); // room for Overflow and the pack's name
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(D(8), D(8)));
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, D(10));
bool open = ImGui.BeginPopup(KindsId);
ImGui.PopStyleVar(2);
if (!open) return;
try
{
PackModel? pk = _m.Pack(_kindsPack);
if (pk == null) { ImGui.CloseCurrentPopup(); return; }
ImFontPtr f = Font(RynthUiFont.Ui11), small = Font(RynthUiFont.Ui10);
float rowH = Fs(f) + D(10);
SafeImGui.TextDisabled(_kindsTitle);
// 0.6.1: a name typed in, no item needed ("Pyreal" sends every item with Pyreal in its name).
SafeImGui.Text("Items whose name has:");
float addW = ImGui.CalcTextSize("Add").X + ImGui.GetStyle().FramePadding.X * 2;
ImGui.SetNextItemWidth(Math.Max(D(120), ImGui.GetContentRegionAvail().X - addW - ImGui.GetStyle().ItemSpacing.X));
if (ImGui.IsWindowAppearing()) ImGui.SetKeyboardFocusHere();
bool enter = ImGui.InputTextWithHint("##kname", "Part of a name, like Pyreal or Scarab", ref _kindsText, (uint)Sorting.SortRule.MaxNameLength, ImGuiInputTextFlags.EnterReturnsTrue);
ImGui.SameLine();
bool typed = _kindsText.Trim().Length > 0;
if (!typed) ImGui.BeginDisabled();
bool add = ImGui.Button("Add##kname");
if (!typed) ImGui.EndDisabled();
SafeImGui.SetItemTooltip("Any item with this in its name goes here, whatever its kind (a name beats a kind). It leaves any other pack's rules.");
if ((enter || add) && typed)
{
_act.SendNameText(pk.Number, _kindsText.Trim());
_kindsText = string.Empty;
ImGui.CloseCurrentPopup();
return;
}
ImGui.Separator();
if (_m.CanAddSelected)
{
if (ImGui.Selectable("The item selected in the game (by name)", false, ImGuiSelectableFlags.None, new Vector2(0, rowH)))
_act.AddSelected(pk.Number);
SafeImGui.SetItemTooltip(_kindsAddTip);
ImGui.Separator();
}
SafeImGui.Text("Or every item of a kind:");
float width = Math.Max(D(240), ImGui.GetContentRegionAvail().X);
for (int i = 0; i < _m.KindChoices.Length; i++)
{
KindChoice k = _m.KindChoices[i];
if (k.InPack == pk.Number) continue;
ImGui.PushID(i);
Vector2 p = ImGui.GetCursorScreenPos();
if (k.InPack > 0) ImGui.SetNextItemAllowOverlap();
bool picked = ImGui.Selectable("##k", false, ImGuiSelectableFlags.None, new Vector2(0, rowH));
if (k.InPack != 0)
SafeImGui.SetItemTooltip(k.InPack > 0 ? "Its pack now; picking it here moves the kind to this pack (Undo puts it back)." : "Its rule names a pack you don't carry; picking it here sends the kind to this pack.");
ImDrawListPtr dl = ImGui.GetWindowDrawList();
dl.AddCircleFilled(new Vector2(p.X + D(8), p.Y + rowH * 0.5f), D(4), Kinds2Abgr(k.Dot), 12);
Text(dl, f, new Vector2(p.X + D(20), p.Y + (rowH - Fs(f)) * 0.5f), Ink, k.Label);
bool overflow = false;
if (k.InPack != 0)
{
string where = k.InPack > 0 ? _m.PackName(k.InPack) : "not carried";
float ww = Measure(small, where).X;
float wx = p.X + width - ww - D(4);
Text(dl, small, new Vector2(wx, p.Y + (rowH - Fs(small)) * 0.5f), Ink3, where);
if (k.InPack > 0)
{
// Keep the kind in its pack; this one takes them when that one is full.
float bw = ButtonWidth("Overflow", false) - D(10);
overflow = SmallButton("##of", "Overflow", new Vector2(wx - bw - D(8), p.Y + (rowH - D(22)) * 0.5f), new Vector2(bw, D(22)),
$"Keep {k.Label.ToLowerInvariant()} in {where}; this pack takes them when {where} is full.");
}
}
ImGui.PopID();
if (overflow) { _act.AddOverflow(pk.Number, k.Cls); ImGui.CloseCurrentPopup(); }
else if (picked) _act.SendKind(pk.Number, k.Cls);
}
}
finally { ImGui.EndPopup(); }
}
}

View file

@ -0,0 +1,829 @@
// ============================================================================
// RynthSort - Window/SortWindow.cs
// The RynthSort window drawn by the plugin with ImGui (2026-11-26, the approved
// web design for #rynth-issues "The bag sort feature is lacking in UX"), in
// RynthCore's frameless plugin window (plugin API v90: the manifest's
// "chrome": "none", "scale": "draw"), the way RynthDefective's shortcut bar and
// RynthAi's dashboard draw theirs.
//
// header the RynthSort mark, whose packs; the Auto-sort switch, the status
// line and its pill; Sort now, Clean, Put back; Find an item;
// Layouts and Settings; pop-out and close. Drag the header to move
// the window; Ctrl+wheel over it: bigger or smaller (the engine's
// PanelScale); the corner resizes it.
// body three columns when wide (main pack, side packs, the plan), two
// (the plan under them), then one. The main pack and each side pack
// as a slot grid of the items' real pictures; rule chips, "+ Add a
// rule" (typed name or kind), a fold chevron; Next moves, Left alone, Activity.
// popups one at a time over the window: an item's detail, the drop choices
// (an item dragged onto a pack card), the layouts, the settings;
// and the rule picker under a pack's "+ Add a rule" (a typed name, or a kind).
// toast the last change, with Undo, in a strip at the bottom.
//
// AC's render thread. It only reads the ScreenModel the plugin tick published
// and queues every action for the tick (ISortWindowActions); what it keeps of
// its own is the search text, which popup is open, drag and animation state.
// Strings it draws come from the model or are made once (when a popup opens);
// nothing per frame allocates in the steady state.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthSort.Window;
/// <summary>What the window asks of the plugin (called on the render thread: each one only queues for the tick).</summary>
internal interface ISortWindowActions
{
void SetAuto(bool on);
void SortNow();
void Clean();
void PutBack();
/// <summary>"All &lt;kind&gt;" to side pack <paramref name="pack"/> (1-based).</summary>
void SendKind(int pack, int cls);
/// <summary>"Only &lt;name&gt;": item <paramref name="itemId"/>'s name to side pack <paramref name="pack"/>.</summary>
void SendName(int pack, uint itemId);
/// <summary>"Just move it" / "Send to": the item to <paramref name="pack"/> (0 = main pack), then left alone.</summary>
void MoveOnce(uint itemId, int pack);
void Hold(uint itemId);
void Release(uint itemId);
/// <summary>No longer left alone, without a toast: an item dropped on a pack with "All <kind>" or "Only <name>" (dragging it held it).</summary>
void Unhold(uint itemId);
void RemoveChip(int ruleUid, bool isName, int cls, string name);
void TurnOn(int ruleUid);
/// <summary>The item selected in the game into side pack <paramref name="pack"/>'s rules (by name).</summary>
void AddSelected(int pack);
void UseLayout(string key);
void Undo();
void DismissToast();
void SetSettle(int seconds);
void SetHold(int minutes);
void SetGap(int ms);
void SetCombat(bool on);
void SetOrder(bool on);
void SetKindFirst(bool on);
/// <summary>"Keep handy items at the front of the main pack".</summary>
void SetHandy(bool on);
/// <summary>"Overflow": side pack <paramref name="pack"/> takes class <paramref name="cls"/> when the pack that has it is full.</summary>
void AddOverflow(int pack, int cls);
/// <summary>Side pack <paramref name="pack"/>'s job (Sorting.JobKind as a number; 0 = none) and, for a mule, its name.</summary>
void SetJob(int pack, int kind, string mule);
/// <summary>A kind on or off the handy list.</summary>
void HandyKind(int cls, bool add);
/// <summary>A part of a name on or off the handy list.</summary>
void HandyName(string name, bool add);
void EmptySidePacks();
void SelectInGame(uint objectId);
/// <summary>The layouts popup opened or closed (the model carries the layouts only while it is open).</summary>
void WantLayouts(bool open);
/// <summary>"Name has...": items whose name has <paramref name="text"/> in it go to side pack <paramref name="pack"/>.</summary>
void SendNameText(int pack, string text);
/// <summary>A side pack's card folded down to its header and rules, or opened (by the pack's object id).</summary>
void SetCollapsed(uint packId, bool collapsed);
/// <summary>The main pack's card folded or opened.</summary>
void SetMainCollapsed(bool collapsed);
/// <summary>Every side pack carried folded or opened.</summary>
void SetAllCollapsed(bool collapsed);
}
internal sealed unsafe partial class SortWindow
{
public const string Title = "RynthSort";
private const string PayloadType = "RSORT_ITEM";
private readonly RynthCoreHost _host;
private readonly ISortWindowActions _act;
private ScreenModel _m = ScreenModel.Empty;
private float _k = 1f, _r = 1f;
private double _now;
private bool _popped;
public SortWindow(RynthCoreHost host, ISortWindowActions actions)
{
_host = host;
_act = actions;
}
// ── Look: the design's palette (rynthsort-packs.html :root), ABGR ────
private static readonly uint Ink = Argb(0xFFE9EEF2), Ink2 = Argb(0xFFB4C1CB), Ink3 = Argb(0xFF7F909D),
AppTop = Argb(0xFF0D141B), AppBottom = Argb(0xFF0A1015), Card = Argb(0xFF111921), Card2 = Argb(0xFF16212B),
CardHot = Argb(0xFF1C2A36), Well = Argb(0xFF0A1016), Line = Argb(0xFF1F2E3B), Line2 = Argb(0xFF2B4053),
Teal = Argb(0xFF35D0B4), TealHot = Argb(0xFF4FE0C6), TealInk = Argb(0xFF062B25), Brass = Argb(0xFFD2A85A),
Sky = Argb(0xFF78B8F0), Amber = Argb(0xFFF0BD5C), Mark = Argb(0xFFF4E6C8), DropBg = Argb(0xFF0F1F22),
DoneInk = Argb(0xFF9FE9D9), HeldInk = Argb(0xFFE9CF96), ToastBg = Argb(0xFF10212A), ToastLine = Argb(0xFF1F4A48),
ToastInk = Argb(0xFFC5F1E7), ToastBtn = Argb(0xFF2A5E5A), SheetBg = Argb(0xFF0F171F), BagTop = Argb(0xFF7A5530),
BagBottom = Argb(0xFF4A321B), BagInk = Argb(0xFFF6E3C2), SwitchOff = Argb(0xFF1A2632), KnobOff = Argb(0xFF9FB0BD),
PillOff = Argb(0xFF18222C), FeedDot = Argb(0xFF1F3A46), White = Argb(0xFFFFFFFF), Black = Argb(0xFF000000),
Red = Argb(0xFFE5675B), NoFitInk = Argb(0xFFF4C2BC);
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
private static uint Soft(uint c, float alpha) => A(c, alpha);
// ── Scale (the engine's PanelScale, Ctrl+wheel: 30-250 %, as the shortcut bar) ──
/// <summary>The layout's scale and the text's against the baked font: the window's own size or, unset, the text size the engine baked.</summary>
private void Scale()
{
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
int pct = _host.PanelScale(Title);
_k = pct > 0 ? pct / 100f : fontK;
_r = _k / fontK;
}
/// <summary>A length in the design's pixels, in the window's (the design at 85 %: a 40 px tile is 34, a 32 px item picture and its frame).</summary>
private float D(float v) => v * 0.85f * _k;
/// <summary>A font's size at this scale.</summary>
private float Fs(ImFontPtr f) => f.FontSize * _r;
private static Vector2 Round(Vector2 p) => new(MathF.Round(p.X), MathF.Round(p.Y));
// ── The frame ────────────────────────────────────────────────────────
/// <summary>Draws the window into the host's frameless window; returns the height it drew. Render thread.</summary>
public float Draw(ScreenModel model, bool popped)
{
_m = model;
_popped = popped;
_now = ImGui.GetTime();
Scale();
NewModel();
Vector2 origin = Round(ImGui.GetCursorScreenPos());
Vector2 size = ImGui.GetContentRegionAvail();
size = new Vector2(MathF.Floor(size.X), MathF.Floor(size.Y));
if (size.X < 60 || size.Y < 40) return size.Y;
_winMin = origin;
_winSize = size;
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float round = D(14);
Background(dl, origin, size, popped ? 0f : round);
ImGui.PushID("rsort");
int colors = PushColors();
int vars = PushVars();
ImGui.PushFont(Font(RynthUiFont.Ui11));
// A popup closed this frame by a click outside it: that click goes through to what is under it
// in ImGui, so for this one frame the window's own controls take no clicks.
bool popupNow = ImGui.IsPopupOpen(SheetId) || ImGui.IsPopupOpen(KindsId);
bool swallow = _popupLastFrame && !popupNow && ImGui.IsMouseClicked(ImGuiMouseButton.Left);
_popupLastFrame = popupNow;
if (swallow) ImGui.BeginDisabled();
try
{
float y = Header(dl, origin, size.X);
y = WarningsStrip(dl, origin.X, y, size.X);
float toastH = ToastHeight();
Vector2 bodyMin = new(origin.X, y);
Vector2 bodySize = new(size.X, Math.Max(D(40), origin.Y + size.Y - y - toastH));
Body(bodyMin, bodySize);
if (toastH > 0) Toast(dl, new Vector2(origin.X, origin.Y + size.Y - toastH), size.X, toastH);
if (swallow) { ImGui.EndDisabled(); swallow = false; }
Sheets();
if (SheetShowing) dl.AddRectFilled(origin, origin + size, A(Argb(0xFF020508), 0.62f), round);
}
finally
{
if (swallow) ImGui.EndDisabled();
ImGui.PopFont();
ImGui.PopStyleVar(vars);
ImGui.PopStyleColor(colors);
ImGui.PopID();
}
dl.AddRect(origin, origin + size, Line, round);
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(size);
return size.Y;
}
private Vector2 _winMin, _winSize;
private bool _popupLastFrame;
/// <summary>
/// The window's background (.app): a dark gradient, top to bottom, in a rounded frame (docked, the
/// game shows at the corners; popped out, <paramref name="r"/> is 0 and it fills its own window).
/// </summary>
private static void Background(ImDrawListPtr dl, Vector2 min, Vector2 size, float r)
{
Vector2 max = min + size;
dl.AddRectFilled(min, max, AppBottom, r);
dl.AddRectFilled(min, new Vector2(max.X, min.Y + r + 1), AppTop, r, ImDrawFlags.RoundCornersTop);
dl.AddRectFilledMultiColor(new Vector2(min.X, min.Y + r), new Vector2(max.X, min.Y + Math.Max(r + 1, size.Y * 0.5f)),
AppTop, AppTop, AppBottom, AppBottom);
}
private int PushColors()
{
ImGui.PushStyleColor(ImGuiCol.Text, Ink);
ImGui.PushStyleColor(ImGuiCol.TextDisabled, Ink3);
ImGui.PushStyleColor(ImGuiCol.FrameBg, Well);
ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, Card2);
ImGui.PushStyleColor(ImGuiCol.FrameBgActive, Card2);
ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal);
ImGui.PushStyleColor(ImGuiCol.SliderGrabActive, TealHot);
ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal);
ImGui.PushStyleColor(ImGuiCol.PopupBg, SheetBg);
ImGui.PushStyleColor(ImGuiCol.Border, Line2);
ImGui.PushStyleColor(ImGuiCol.ScrollbarBg, 0u);
ImGui.PushStyleColor(ImGuiCol.ScrollbarGrab, Line2);
ImGui.PushStyleColor(ImGuiCol.ScrollbarGrabHovered, Argb(0xFF3C5970));
ImGui.PushStyleColor(ImGuiCol.ScrollbarGrabActive, Argb(0xFF3C5970));
ImGui.PushStyleColor(ImGuiCol.Header, A(Teal, 0.14f));
ImGui.PushStyleColor(ImGuiCol.HeaderHovered, Card2);
ImGui.PushStyleColor(ImGuiCol.HeaderActive, A(Teal, 0.22f));
ImGui.PushStyleColor(ImGuiCol.TextSelectedBg, A(Teal, 0.35f));
return 18;
}
private int PushVars()
{
ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, D(8));
ImGui.PushStyleVar(ImGuiStyleVar.GrabRounding, D(8));
ImGui.PushStyleVar(ImGuiStyleVar.GrabMinSize, D(14));
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(D(8), D(5)));
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(D(8), D(6)));
ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, D(10));
ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarRounding, D(6));
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, D(14));
ImGui.PushStyleVar(ImGuiStyleVar.PopupBorderSize, 1f);
return 9;
}
// ── Header ───────────────────────────────────────────────────────────
private string _query = string.Empty;
private string _queryShown = string.Empty;
private int _queryVersion = -1;
private readonly HashSet<uint> _hits = new();
private float _knob;
/// <summary>The header row(s): mark, status, actions, search, Layouts, Settings, and the window's own buttons. Returns the y under it.</summary>
private float Header(ImDrawListPtr dl, Vector2 o, float w)
{
float pad = D(16), gap = D(14), rowH = D(36);
ImFontPtr markF = Font(RynthUiFont.NarrowBold13), whoF = Font(RynthUiFont.Ui10);
float markW = TrackedWidth(markF, Fs(markF) * 1.25f, "RYNTHSORT", 0.12f * Fs(markF)) + D(10) + Measure(whoF, _m.Who).X;
float winBtns = 2 * D(28) + D(4);
bool narrow = w < D(740);
// What goes where: the first row has the mark and the window's buttons, then each block in turn.
float statusMin = narrow ? w - 2 * pad : D(320);
float actionsW = ActionsWidth();
float rightW = LayoutsWidth() + D(8) + D(36);
float searchW = narrow ? Math.Max(D(120), w - 2 * pad - rightW - gap) : D(220);
float x0 = o.X + pad, xMax = o.X + w - pad;
// Rows: [mark][status][actions][search][layouts+settings] flowing; status grows to fill its row.
Span<float> widths = stackalloc float[5] { markW, statusMin, actionsW, _m.Ready ? searchW : 0, _m.Ready ? rightW : 0 };
Span<int> rowOf = stackalloc int[5];
int row = 0;
float x = x0, firstRowRight = xMax - winBtns - D(8);
for (int i = 0; i < 5; i++)
{
if (widths[i] <= 0) { rowOf[i] = -1; continue; }
float limit = row == 0 ? firstRowRight : xMax;
if (x > x0 && x + widths[i] > limit) { row++; x = x0; }
rowOf[i] = row;
x += widths[i] + gap;
}
int rows = row + 1;
float height = pad + rows * rowH + (rows - 1) * D(12) + pad - D(2);
// The brass glow along the top (rounded with the window's corners), and the line under the header.
float corner = _popped ? 0f : D(14);
dl.AddRectFilled(o, o + new Vector2(w, corner + 1), A(Brass, 0.06f), corner, ImDrawFlags.RoundCornersTop);
dl.AddRectFilledMultiColor(new Vector2(o.X, o.Y + corner + 1), o + new Vector2(w, height), A(Brass, 0.06f), A(Brass, 0.06f), 0u, 0u);
dl.AddLine(new Vector2(o.X, o.Y + height), new Vector2(o.X + w, o.Y + height), Line);
// The drag handle under everything (later items take the mouse where they are).
ImGui.SetCursorScreenPos(o);
ImGui.SetNextItemAllowOverlap();
ImGui.InvisibleButton("##rs_drag", new Vector2(w, height));
bool dragHot = ImGui.IsItemHovered();
_host.PanelDragWithLastItem();
// Status grows into its row's free room.
float statusW = statusMin;
if (rowOf[1] >= 0)
{
float used = 0;
int n = 0;
for (int i = 0; i < 5; i++) if (rowOf[i] == rowOf[1]) { used += widths[i]; n++; }
float limit = rowOf[1] == 0 ? firstRowRight : xMax;
statusW = Math.Max(statusMin, limit - x0 - used - (n - 1) * gap + statusMin);
}
Span<float> rowX = stackalloc float[8];
for (int i = 0; i < rowX.Length; i++) rowX[i] = x0;
float RowY(int r) => o.Y + pad + r * (rowH + D(12));
for (int i = 0; i < 5; i++)
{
int r = rowOf[i];
if (r < 0) continue;
float bx = rowX[r], by = RowY(r);
float bw = i == 1 ? statusW : widths[i];
switch (i)
{
case 0: MarkBlock(dl, new Vector2(bx, by), rowH, markF, whoF, dragHot); break;
case 1: StatusBlock(dl, new Vector2(bx, by), new Vector2(bw, rowH)); break;
case 2: ActionsBlock(new Vector2(bx, by), rowH); break;
case 3: SearchBlock(dl, new Vector2(bx, by), new Vector2(bw, rowH)); break;
case 4: RightBlock(new Vector2(bx, by), rowH); break;
}
rowX[r] = bx + bw + gap;
}
WindowButtons(new Vector2(xMax - winBtns, RowY(0) + (rowH - D(28)) * 0.5f));
return o.Y + height + 1;
}
private void MarkBlock(ImDrawListPtr dl, Vector2 p, float h, ImFontPtr markF, ImFontPtr whoF, bool dragHot)
{
float size = Fs(markF) * 1.25f;
float x = Tracked(dl, markF, size, new Vector2(p.X, MathF.Round(p.Y + (h - size) * 0.5f)), Mark, "RYNTHSORT", 0.12f * Fs(markF));
if (_m.Who.Length > 0)
Text(dl, whoF, new Vector2(x + D(10), p.Y + (h - Fs(whoF)) * 0.5f + D(1)), Ink3, _m.Who);
if (dragHot && ImGui.IsMouseHoveringRect(p, p + new Vector2(x - p.X, h)))
ImGui.SetTooltip("Drag the header to move the window. Ctrl+wheel over it: bigger or smaller. The corner resizes it.");
}
private void StatusBlock(ImDrawListPtr dl, Vector2 p, Vector2 s)
{
dl.AddRectFilled(p, p + s, Card, D(12));
dl.AddRect(p, p + s, Line, D(12));
if (!_m.Ready)
{
Text(dl, Font(RynthUiFont.Ui10), new Vector2(p.X + D(12), p.Y + (s.Y - Fs(Font(RynthUiFont.Ui10))) * 0.5f), Ink2, _m.NotReady);
return;
}
Vector2 sw = new(p.X + D(6), p.Y + (s.Y - D(26)) * 0.5f);
if (Switch("##rs_auto", sw, _m.Auto)) _act.SetAuto(!_m.Auto);
SafeImGui.SetItemTooltip(_m.Auto ? "Auto-sort is on: click to turn it off (/rsort off)." : "Auto-sort is off: click to turn it on (/rsort on).");
// The pill on the right, then the two lines between.
ImFontPtr pf = Font(RynthUiFont.NarrowBold11);
float pSize = Fs(pf) * 0.92f, track = 0.1f * pSize;
string pill = PillText(_m.Status);
float pw = TrackedWidth(pf, pSize, pill, track) + D(18), ph = pSize + D(11);
Vector2 pp = new(p.X + s.X - D(8) - pw, p.Y + (s.Y - ph) * 0.5f);
(uint fg, uint bg) = _m.Status.Tone switch
{
PillTone.Tidy => (Teal, A(Teal, 0.14f)),
PillTone.Moving => (Sky, A(Sky, 0.14f)),
PillTone.Waiting => (Amber, A(Amber, 0.12f)),
_ => (Ink3, PillOff),
};
dl.AddRectFilled(pp, pp + new Vector2(pw, ph), bg, ph * 0.5f);
Tracked(dl, pf, pSize, new Vector2(pp.X + D(9), MathF.Round(pp.Y + (ph - pSize) * 0.5f)), fg, pill, track);
float tx = sw.X + D(46) + D(12), tw = Math.Max(10, pp.X - D(8) - tx);
ImFontPtr bold = Font(RynthUiFont.UiBold11), small = Font(RynthUiFont.Ui10);
float lines = Fs(bold) + D(2) + Fs(small);
float ty = p.Y + (s.Y - lines) * 0.5f;
Text(dl, bold, new Vector2(tx, ty), Ink, "Auto-sort");
TextFit(dl, small, new Vector2(tx, ty + Fs(bold) + D(2)), Ink2, _m.Status.Line, tw);
if (ImGui.IsMouseHoveringRect(new Vector2(tx, p.Y), new Vector2(tx + tw, p.Y + s.Y)) && ImGui.IsWindowHovered())
SafeImGui.SetTooltip(_m.Status.Tip);
}
// The pill's words in capitals, made once per word.
private readonly Dictionary<string, string> _caps = new();
private string PillText(StatusModel s)
{
if (!_caps.TryGetValue(s.Pill, out string? up)) _caps[s.Pill] = up = s.Pill.ToUpperInvariant();
return up;
}
private float ActionsWidth()
{
if (!_m.Ready) return 0;
float w = ButtonWidth("Sort now", true) + D(8) + ButtonWidth("Clean", false);
if (ShowPutBack) w += D(8) + ButtonWidth("Put back", true);
return w;
}
private bool ShowPutBack => _m.Ready && _m.PutBack > 0 && !_m.Busy;
private void ActionsBlock(Vector2 p, float h)
{
float bh = D(34), y = p.Y + (h - bh) * 0.5f, x = p.X;
if (Button("##rs_sortnow", "Sort now", RynthIcons.SortAscending, new Vector2(x, y), bh, Look.Primary, !_m.Busy,
"Sort every pack once, now: items go to their packs, stacks are joined and packs put in order. "
+ "It doesn't wait for new items to settle; items you used lately are still left alone. Also: /rsort now", out float w))
_act.SortNow();
x += w + D(8);
if (Button("##rs_clean", "Clean", null, new Vector2(x, y), bh, Look.Normal, !_m.Busy,
"Sort now, and side-pack items no rule wants go back to the main pack. Also: /rsort clean", out w))
_act.Clean();
x += w + D(8);
if (ShowPutBack && Button("##rs_back", "Put back", RynthIcons.ArrowCounterClockwise, new Vector2(x, y), bh, Look.Quiet, true, _m.PutBackTip, out _))
_act.PutBack();
}
private void SearchBlock(ImDrawListPtr dl, Vector2 p, Vector2 s)
{
dl.AddRectFilled(p, p + s, Well, D(10));
dl.AddRect(p, p + s, ImGui.IsMouseHoveringRect(p, p + s) ? Argb(0xFF3C5970) : Line2, D(10));
DrawIcon(dl, RynthIcons.MagnifyingGlass, new Vector2(p.X + D(8), p.Y), new Vector2(D(16), s.Y), D(15), Ink3);
float fh = ImGui.GetFontSize();
ImGui.PushStyleColor(ImGuiCol.FrameBg, 0u);
ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, 0u);
ImGui.PushStyleColor(ImGuiCol.FrameBgActive, 0u);
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(D(2), Math.Max(0, (s.Y - fh) * 0.5f - 1)));
ImGui.SetCursorScreenPos(new Vector2(p.X + D(28), p.Y));
ImGui.SetNextItemWidth(Math.Max(20, s.X - D(28) - D(6)));
ImGui.InputTextWithHint("##rs_q", "Find an item", ref _query, 64);
ImGui.PopStyleVar();
ImGui.PopStyleColor(3);
SafeImGui.SetItemTooltip("Type part of an item's name: matching items light up, the rest dim.");
}
private float LayoutsWidth() => ButtonWidth("Layouts", true);
private void RightBlock(Vector2 p, float h)
{
float bh = D(34), y = p.Y + (h - bh) * 0.5f;
if (Button("##rs_layouts", "Layouts", RynthIcons.SquaresFour, new Vector2(p.X, y), bh, Look.Normal, true,
"Starter layouts: a kind of item for each pack, fitted to the packs you carry. You see what would move first.", out float w))
OpenLayouts(null);
if (IconButton("##rs_settings", RynthIcons.SlidersHorizontal, new Vector2(p.X + w + D(8), y), new Vector2(D(36), bh), "Settings"))
OpenSheet(Sheet.Settings);
}
private void WindowButtons(Vector2 p)
{
Vector2 s = new(D(28), D(28));
if (IconButton("##rs_pop", _popped ? RynthIcons.ArrowSquareIn : RynthIcons.ArrowSquareOut, p, s,
_popped ? "Dock it back into the game window" : "Pop out into its own window", quiet: true))
_host.SetPanelPopOut(Title, RynthPanelPopOut.Toggle);
if (IconButton("##rs_close", RynthIcons.X, p + new Vector2(D(32), 0), s, "Close (/rsort, or the Sort button on the Inventory, opens it again)", quiet: true))
_host.SetPanelOpen(Title, RynthPanelOpen.Close);
}
/// <summary>Amber lines under the header (wrapped); returns the y under them.</summary>
private float WarningsStrip(ImDrawListPtr dl, float x, float y, float w)
{
if (!_m.Ready) return y;
y = Strip(dl, x, y, w, _m.NoFit, Red, NoFitInk, RynthIcons.Warning);
return Strip(dl, x, y, w, _m.Warnings, Amber, HeldInk, RynthIcons.Warning);
}
/// <summary>A strip of wrapped lines under the header in <paramref name="tone"/> (red: what didn't fit; amber: warnings). Returns the y under it.</summary>
private float Strip(ImDrawListPtr dl, float x, float y, float w, string[] lines, uint tone, uint ink, string icon)
{
if (lines.Length == 0) return y;
ImFontPtr f = Font(RynthUiFont.Ui10);
float pad = D(16), wrap = w - 2 * pad - D(24);
float h = D(8);
foreach (string line in lines) h += f.CalcTextSizeA(Fs(f), float.MaxValue, wrap, line).Y + D(4);
h += D(4);
dl.AddRectFilled(new Vector2(x, y), new Vector2(x + w, y + h), A(tone, 0.10f));
dl.AddLine(new Vector2(x, y + h), new Vector2(x + w, y + h), A(tone, 0.30f));
float cy = y + D(8);
foreach (string line in lines)
{
DrawIcon(dl, icon, new Vector2(x + pad, cy), new Vector2(D(16), Fs(f)), D(13), tone);
dl.AddText(f, Fs(f), Round(new Vector2(x + pad + D(22), cy)), ink, line, wrap);
cy += f.CalcTextSizeA(Fs(f), float.MaxValue, wrap, line).Y + D(4);
}
return y + h + 1;
}
// ── Toast ────────────────────────────────────────────────────────────
private int _toastGone = -1;
private bool ToastShowing => _m.Toast is ToastModel t && t.Seq != _toastGone && Environment.TickCount64 < t.UntilMs;
private float ToastHeight() => ToastShowing ? D(52) : 0f;
private void Toast(ImDrawListPtr dl, Vector2 p, float w, float h)
{
ToastModel t = _m.Toast!;
ImFontPtr f = Font(RynthUiFont.Ui11), bf = Font(RynthUiFont.UiBold11);
float undoW = t.CanUndo ? Measure(bf, "Undo").X + D(20) : 0;
float closeW = D(22);
float maxText = w - D(32) - undoW - closeW - D(40);
float textW = Math.Min(Measure(f, t.Text).X, maxText);
float bw = textW + D(28) + (undoW > 0 ? undoW + D(12) : 0) + closeW + D(6);
float bh = h - D(12);
Vector2 bp = Round(new Vector2(p.X + (w - bw) * 0.5f, p.Y + D(4)));
dl.AddRectFilled(bp, bp + new Vector2(bw, bh), ToastBg, D(12));
dl.AddRect(bp, bp + new Vector2(bw, bh), ToastLine, D(12));
TextFit(dl, f, new Vector2(bp.X + D(14), bp.Y + (bh - Fs(f)) * 0.5f), ToastInk, t.Text, textW + 1);
float x = bp.X + D(14) + textW + D(12);
if (t.CanUndo)
{
Vector2 up = new(x, bp.Y + (bh - D(26)) * 0.5f), us = new(undoW, D(26));
ImGui.SetCursorScreenPos(up);
bool clicked = ImGui.InvisibleButton("##rs_undo", us);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip("Put the rules back as they were before this change. Nothing moves.");
dl.AddRectFilled(up, up + us, hot ? A(ToastBtn, 0.6f) : 0u, D(8));
dl.AddRect(up, up + us, ToastBtn, D(8));
Text(dl, bf, new Vector2(up.X + (us.X - Measure(bf, "Undo").X) * 0.5f, up.Y + (us.Y - Fs(bf)) * 0.5f), ToastInk, "Undo");
if (clicked) { _act.Undo(); _toastGone = t.Seq; }
x += undoW + D(6);
}
if (IconButton("##rs_toastx", RynthIcons.X, new Vector2(x, bp.Y + (bh - closeW) * 0.5f), new Vector2(closeW, closeW), "Hide this", quiet: true))
{
_toastGone = t.Seq;
_act.DismissToast();
}
}
// ── A new model: search hits, arrivals, caches ───────────────────────
private readonly Arrivals _arrivals = new();
private int _modelVersion = -1;
private string _modelWho = string.Empty;
private void NewModel()
{
bool changed = _m.Version != _modelVersion;
if (changed)
{
_modelVersion = _m.Version;
if (_m.Who != _modelWho)
{
// Another character (or logged out): its search, popups and animations go.
_modelWho = _m.Who;
_query = _queryShown = string.Empty;
_sheet = Sheet.None;
_pendingSheet = Sheet.None;
_arrivals.Clear();
_layoutsOffered = false;
}
_arrivals.Update(_m, _now);
if (_fit.Count > 1024) _fit.Clear();
}
if (changed || !ReferenceEquals(_query, _queryShown) || _queryVersion != _m.Version)
{
_queryShown = _query;
_queryVersion = _m.Version;
_hits.Clear();
string q = _query.Trim();
if (q.Length > 0)
foreach (KeyValuePair<uint, TileModel> kv in _m.TilesById)
if (ScreenText.Matches(kv.Value, q)) _hits.Add(kv.Key);
_searching = q.Length > 0;
}
// A new character with no rules: the layouts, once, with Everyday picked (the design's first run).
if (_m.Ready && _m.NoRules && _m.Packs.Length > 0 && !_layoutsOffered && _sheet == Sheet.None)
{
_layoutsOffered = true;
OpenLayouts("everyday");
}
}
private bool _searching;
private bool _layoutsOffered;
// ── Widgets ──────────────────────────────────────────────────────────
private enum Look { Normal, Primary, Quiet }
private float ButtonWidth(string label, bool icon)
{
ImFontPtr f = Font(RynthUiFont.UiBold11);
return MathF.Ceiling(Measure(f, label).X + (icon ? D(16) + D(7) : 0) + 2 * D(13));
}
/// <summary>The design's button (.btn, .btn.primary, .btn.quiet) at <paramref name="pos"/>; true when clicked.</summary>
private bool Button(string id, string label, string? icon, Vector2 pos, float h, Look look, bool enabled, string? tip, out float width)
{
ImFontPtr f = Font(RynthUiFont.UiBold11);
float w = ButtonWidth(label, icon != null);
width = w;
Vector2 size = new(w, h);
ImGui.SetCursorScreenPos(pos);
bool clicked = ImGui.InvisibleButton(id, size) && enabled;
bool hot = enabled && ImGui.IsItemHovered();
bool held = enabled && ImGui.IsItemActive();
if (tip != null) SafeImGui.SetItemTooltip(tip);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
uint fill, border, ink;
switch (look)
{
case Look.Primary:
fill = hot ? TealHot : Teal;
border = Teal;
ink = TealInk;
break;
case Look.Quiet:
fill = hot ? CardHot : 0u;
border = Line2;
ink = Ink;
break;
default:
fill = hot ? CardHot : Card2;
border = Line2;
ink = Ink;
break;
}
if (held) fill = Darken(fill == 0 ? CardHot : fill);
float alpha = enabled ? 1f : 0.45f;
if (fill != 0) dl.AddRectFilled(pos, pos + size, A(fill, alpha * ((fill >> 24) / 255f)), D(10));
dl.AddRect(pos, pos + size, A(border, alpha), D(10));
float x = pos.X + D(13);
if (icon != null)
{
DrawIcon(dl, icon, new Vector2(x, pos.Y), new Vector2(D(16), h), D(16), A(ink, alpha));
x += D(16) + D(7);
}
Text(dl, f, new Vector2(x, pos.Y + (h - Fs(f)) * 0.5f), A(ink, alpha), label);
return clicked;
}
/// <summary>The design's icon button (.icon-btn); <paramref name="quiet"/>: no fill until the mouse is over it.</summary>
private bool IconButton(string id, string icon, Vector2 pos, Vector2 size, string tip, bool quiet = false, bool enabled = true)
{
ImGui.SetCursorScreenPos(pos);
bool clicked = ImGui.InvisibleButton(id, size) && enabled;
bool hot = enabled && ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(tip);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float r = Math.Min(D(10), size.Y * 0.4f);
if (!quiet || hot) dl.AddRectFilled(pos, pos + size, hot ? CardHot : Card2, r);
if (!quiet) dl.AddRect(pos, pos + size, Line2, r);
DrawIcon(dl, icon, pos, size, Math.Min(D(16), size.Y * 0.62f), A(hot ? Ink : Ink2, enabled ? 1f : 0.45f));
return clicked;
}
/// <summary>The Auto-sort switch (.switch): its knob slides. True when clicked.</summary>
private bool Switch(string id, Vector2 p, bool on)
{
Vector2 size = new(D(46), D(26));
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton(id, size);
bool hot = ImGui.IsItemHovered();
float target = on ? 1f : 0f;
_knob += (target - _knob) * Math.Clamp(ImGui.GetIO().DeltaTime * 14f, 0f, 1f);
if (MathF.Abs(_knob - target) < 0.01f) _knob = target;
ImDrawListPtr dl = ImGui.GetWindowDrawList();
uint track = on ? Teal : hot ? Card2 : SwitchOff;
dl.AddRectFilled(p, p + size, track, size.Y * 0.5f);
dl.AddRect(p, p + size, on ? Teal : Line2, size.Y * 0.5f);
float kr = D(9);
Vector2 c = new(p.X + D(3) + kr + _knob * (size.X - 2 * D(3) - 2 * kr), p.Y + size.Y * 0.5f);
dl.AddCircleFilled(c, kr, on ? White : KnobOff, 20);
return clicked;
}
/// <summary>A meter (.meter): <paramref name="fill"/> of the width, teal, amber when nearly full, red when full.</summary>
private void Meter(ImDrawListPtr dl, Vector2 p, float w, float fill, bool amber, bool full = false)
{
float h = D(6);
dl.AddRectFilled(p, p + new Vector2(w, h), Well, h * 0.5f);
float fw = Math.Max(h, w * Math.Clamp(fill, 0.02f, 1f));
dl.AddRectFilled(p, p + new Vector2(fw, h), full ? Red : amber ? Amber : Teal, h * 0.5f);
}
/// <summary>The brass bag badge with the pack's number (.bag).</summary>
private void Bag(ImDrawListPtr dl, Vector2 p, float s, string number)
{
float r = s * 0.26f;
dl.AddRectFilled(p, p + new Vector2(s, s), BagBottom, r);
dl.AddRectFilled(p, p + new Vector2(s, s * 0.55f), BagTop, r, ImDrawFlags.RoundCornersTop);
dl.AddLine(new Vector2(p.X + r, p.Y + 1), new Vector2(p.X + s - r, p.Y + 1), A(White, 0.18f));
dl.AddRect(p, p + new Vector2(s, s), A(Black, 0.5f), r);
ImFontPtr f = Font(RynthUiFont.NarrowBold13);
float size = Math.Min(Fs(f), s * 0.5f);
Vector2 ts = f.CalcTextSizeA(size, float.MaxValue, 0, number);
dl.AddText(f, size, Round(p + (new Vector2(s, s) - ts) * 0.5f), BagInk, number);
}
/// <summary>A dashed rounded-ish box (straight dashes on each side), for name chips, ghosts and "+ Add a kind...".</summary>
private static void Dashed(ImDrawListPtr dl, Vector2 min, Vector2 max, uint col, float dash, float thick = 1f)
{
void Side(Vector2 a, Vector2 b)
{
Vector2 d = b - a;
float len = d.Length();
if (len <= 0) return;
Vector2 u = d / len;
for (float t = 0; t < len; t += dash * 2)
dl.AddLine(a + u * t, a + u * Math.Min(len, t + dash), col, thick);
}
float inset = dash * 0.8f;
Side(new Vector2(min.X + inset, min.Y), new Vector2(max.X - inset, min.Y));
Side(new Vector2(max.X, min.Y + inset), new Vector2(max.X, max.Y - inset));
Side(new Vector2(max.X - inset, max.Y), new Vector2(min.X + inset, max.Y));
Side(new Vector2(min.X, max.Y - inset), new Vector2(min.X, min.Y + inset));
}
// ── Text ─────────────────────────────────────────────────────────────
private Vector2 Measure(ImFontPtr f, string s) => f.CalcTextSizeA(Fs(f), float.MaxValue, 0f, s);
private void Text(ImDrawListPtr dl, ImFontPtr f, Vector2 p, uint c, string s) => dl.AddText(f, Fs(f), Round(p), c, s);
// Text cut to a width with "...", made once per text and width.
private readonly Dictionary<(string, int, int), string> _fit = new();
/// <summary>Draws <paramref name="s"/> cut to <paramref name="maxW"/> with an ellipsis when it doesn't fit.</summary>
private void TextFit(ImDrawListPtr dl, ImFontPtr f, Vector2 p, uint c, string s, float maxW)
{
if (maxW <= 4) return;
Text(dl, f, p, c, Fit(f, s, maxW));
}
private string Fit(ImFontPtr f, string s, float maxW)
{
float size = Fs(f);
if (f.CalcTextSizeA(size, float.MaxValue, 0f, s).X <= maxW) return s;
var key = (s, (int)maxW, (int)(size * 10));
if (_fit.TryGetValue(key, out string? cut)) return cut;
int lo = 0, hi = s.Length;
while (lo < hi)
{
int mid = (lo + hi + 1) / 2;
if (f.CalcTextSizeA(size, float.MaxValue, 0f, string.Concat(s.AsSpan(0, mid).TrimEnd(), "…")).X <= maxW) lo = mid;
else hi = mid - 1;
}
cut = lo == 0 ? "…" : string.Concat(s.AsSpan(0, lo).TrimEnd(), "…");
_fit[key] = cut;
return cut;
}
private static readonly string[] Chars = BuildChars();
private static string[] BuildChars()
{
var a = new string[128];
for (int i = 32; i < 127; i++) a[i] = ((char)i).ToString();
return a;
}
/// <summary>Text with <paramref name="spacing"/> pixels between its letters (the shortcut bar's). Returns the x after it.</summary>
private static float Tracked(ImDrawListPtr dl, ImFontPtr font, float size, Vector2 pos, uint color, string text, float spacing)
{
if (font.NativePtr == null || text.Length == 0) return pos.X;
float scale = size / font.FontSize;
float x = pos.X;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
string s = c < 128 && Chars[c] != null ? Chars[c] : c.ToString();
dl.AddText(font, size, new Vector2(MathF.Round(x), pos.Y), color, s);
x += font.GetCharAdvance(c) * scale;
if (i < text.Length - 1) x += spacing;
}
return x;
}
private static float TrackedWidth(ImFontPtr font, float size, string text, float spacing)
{
if (font.NativePtr == null || text.Length == 0) return 0;
float scale = size / font.FontSize, w = 0;
for (int i = 0; i < text.Length; i++) w += font.GetCharAdvance(text[i]) * scale;
return w + spacing * (text.Length - 1);
}
/// <summary>A section's eyebrow (.eyebrow): small tracked capitals, then a count in the number font. Returns the y under it.</summary>
private float Eyebrow(ImDrawListPtr dl, Vector2 p, string caps, string count)
{
ImFontPtr f = Font(RynthUiFont.Narrow10), n = Font(RynthUiFont.Dash10);
float size = Fs(f);
float x = Tracked(dl, f, size, p, Ink3, caps, 0.12f * size);
if (count.Length > 0) Text(dl, n, new Vector2(x + D(8), p.Y + (size - Fs(n)) * 0.5f), Ink2, count);
return p.Y + size + D(10);
}
/// <summary>A Phosphor glyph centred in the box, <paramref name="px"/> across its em (the shortcut bar's DrawIcon, from Ui18's bake).</summary>
private static void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color)
{
if (string.IsNullOrEmpty(glyph)) return;
ImFontPtr font = Font(RynthUiFont.Ui18);
if (font.NativePtr == null) return;
byte* g = (byte*)ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]);
if (g == null) return;
float advance = *(float*)(g + 4);
if (advance <= 0) return;
float* box = (float*)(g + 8);
float scale = px / advance;
Vector2 centre = new((box[0] + box[2]) * 0.5f * scale, (box[1] + box[3]) * 0.5f * scale);
Vector2 at = min + size * 0.5f - centre;
dl.AddText(font, font.FontSize * scale, new Vector2(MathF.Round(at.X), MathF.Round(at.Y)), color, glyph);
}
// Small numbers as text, made once.
private static readonly string[] Numbers = BuildNumbers();
private static string[] BuildNumbers()
{
var a = new string[1000];
for (int i = 0; i < a.Length; i++) a[i] = i.ToString(System.Globalization.CultureInfo.InvariantCulture);
return a;
}
private static string Num(int n) => n >= 0 && n < Numbers.Length ? Numbers[n] : n.ToString(System.Globalization.CultureInfo.InvariantCulture);
}