Snapshot for release 2026.10.13.1 (internal 90a2f4a)

This commit is contained in:
Tom Bohar 2026-10-13 14:25:48 -04:00
commit 1d86acdf27
218 changed files with 24019 additions and 1517 deletions

View file

@ -23,6 +23,7 @@ using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.D3D9;
using RynthCore.Engine.Plugins;
using RynthCore.Install;
namespace RynthCore.Engine.ImGuiBackend;
@ -48,6 +49,9 @@ internal static class EngineFrameController
private static bool _imguiInitFailed;
private static bool _coreResolved;
private static bool _pluginsInitialized;
// Pump frames plugin init has waited for the ImGui context (PumpPluginFrame; ~16 ms each).
private static int _pluginInitContextWaits;
private const int PluginInitContextMaxWaits = 300;
private static IntPtr _context;
private static IntPtr _gameHwnd;
@ -61,6 +65,26 @@ internal static class EngineFrameController
/// </summary>
internal static volatile IntPtr CachedDevice;
private static int _pluginPumpInFrame; // re-entrancy guard for the pump
private static int _pumpFrameFaults; // PumpPluginFrame throws caught (pump thread only)
// ImGui pipeline diagnostics (render thread only): one-time lines plus a 30 s heartbeat so a
// log shows whether frames start, which branch runs and whether draw data is submitted.
private const long HeartbeatIntervalMs = 30_000;
private static long _engineErrorCount;
private static long _nextEngineErrorLogAt;
private static bool _loggedFirstSubmit;
private static int _loggedBranch = -1;
private static string _initFailStep = "unknown";
private static long _drawSubmits;
private static long _nextHeartbeatAt;
// Device for this frame's built ImGui draw data, submitted by RenderDeferredImGui after the
// Avalonia blit. Render thread only; Zero = nothing pending. The draw data stays valid until
// the next NewFrame on the main context.
private static IntPtr _deferredSubmitDevice;
// Build + pop-out time of the frame waiting in _deferredSubmitDevice (UiFrameStats adds the submit).
private static long _deferredUiTicks;
private static long _lastFrameTicks;
private static int _frameCount;
@ -103,7 +127,10 @@ internal static class EngineFrameController
return true;
if (!EnsureCore(pDevice))
{
_initFailStep = "EnsureCore (game window not found)";
return false;
}
// Before any context exists: the loaded cimgui.dll must be the exact
// build ImGui.NET wraps, or every struct read below is at wrong offsets.
@ -131,7 +158,7 @@ internal static class EngineFrameController
System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir);
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
RynthLog.Render($"EngineFrameController: imgui.ini pinned to {iniPath}");
RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}");
}
catch (Exception ex)
{
@ -155,10 +182,16 @@ internal static class EngineFrameController
ImGuiFonts.Build(io, _uiScale);
if (!Win32Backend.Init(_gameHwnd))
{
_initFailStep = "Win32Backend.Init";
return false;
}
if (!DX9Backend.InitImGui(pDevice))
{
_initFailStep = "DX9Backend.InitImGui";
return false;
}
_lastFrameTicks = Stopwatch.GetTimestamp();
_imguiInitialized = true;
@ -229,6 +262,8 @@ internal static class EngineFrameController
// EngineSettings.EnableImGuiBackend, so world→screen capture, nav-
// marker rendering, and plugin lifecycle stay alive when the ImGui
// surface is disabled.
// A frame that throws before its build must not resubmit last frame's draw data.
_deferredSubmitDevice = IntPtr.Zero;
try
{
// Resolve game HWND and seed EntryPoint.GameHwnd. Required even
@ -344,10 +379,10 @@ internal static class EngineFrameController
// calls it at all.
// ── ImGui-gated work ─────────────────────────────────────────
// The frame is BUILT here and SUBMITTED after the Nav3D fallback and
// the vital HUD, so ImGui windows sit above both. The Avalonia quad
// (EndSceneHook, after this returns) stays topmost while both stacks
// run, matching input order: Avalonia gets the first hit test.
// The frame is BUILT here and SUBMITTED by RenderDeferredImGui, which
// EndSceneHook calls after the Avalonia quad, so ImGui windows sit above
// the Nav3D fallback, the vital HUD and the Avalonia panels. Input order
// matches: Win32Backend gives ImGui the mouse while it wants it.
bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend;
bool imguiBuilt = false;
long uiTicks = 0;
@ -370,17 +405,33 @@ internal static class EngineFrameController
if (imguiEnabled)
{
long t0 = Stopwatch.GetTimestamp();
if (imguiBuilt)
SubmitImGuiFrame(pDevice);
// Popped-out panels: their own contexts, windows and render targets.
if (_imguiInitialized)
ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive);
UiFrameStats.Record(uiTicks + (Stopwatch.GetTimestamp() - t0));
long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0);
if (imguiBuilt)
{
_deferredUiTicks = ticks;
_deferredSubmitDevice = pDevice;
}
else
{
UiFrameStats.Record(ticks);
}
}
}
catch (Exception ex)
{
RynthLog.Info($"EngineFrameController: frame {_frameCount} engine error: {ex.GetType().Name}: {ex.Message}");
// An exception here skips everything after it this frame (including RunImGuiFrame), so
// the first one gets a stack trace; repeats are summarised every 30 s instead of per frame.
_engineErrorCount++;
long errNow = Environment.TickCount64;
if (_engineErrorCount == 1)
RynthLog.Error($"EngineFrameController: engine frame error (rest of this frame skipped): {ex}");
else if (errNow >= _nextEngineErrorLogAt)
RynthLog.Error($"EngineFrameController: engine frame errors so far={_engineErrorCount}, latest {ex.GetType().Name}: {ex.Message}");
if (errNow >= _nextEngineErrorLogAt)
_nextEngineErrorLogAt = errNow + HeartbeatIntervalMs;
}
finally
{
@ -442,14 +493,26 @@ internal static class EngineFrameController
return; // never re-enter PluginManager from two stacks
try
{
// Plugins only get the ImGui context when they may draw with it
// (EnableImGuiShell, FORCE-gated). The engine's own ImGui panels
// don't need plugins to see it, and handing it over switched
// RynthAi into its legacy-ImGui setup (first ImGui-on test,
// 2026-09-28) - plugins must behave exactly as in Avalonia-only mode.
IntPtr pluginContext = Plugins.EngineSettings.EnableImGuiShell ? _context : IntPtr.Zero;
// Plugins only get the ImGui context when they may draw with it: the
// ImGui shell (EnableImGuiShell, FORCE-gated) or their own overlay
// windows (EnablePluginOverlayWindows: RynthAi's ILT Hub, HUDs, Item
// Info; RynthPluginRenderOverlay). RynthAi only reads the context for
// those windows, so this does not switch it into a legacy-ImGui setup.
bool pluginsDraw = Plugins.EngineSettings.EnableImGuiShell
|| (Plugins.EngineSettings.EnablePluginOverlayWindows && Plugins.EngineSettings.EnableImGuiBackend);
// _context is written by the render thread (Init); this is the pump thread.
IntPtr pluginContext = pluginsDraw ? System.Threading.Volatile.Read(ref _context) : IntPtr.Zero;
if (!_pluginsInitialized)
{
// The plugin host copies the context once at init, so wait for the
// render path's ImGui init (first ImGui frame) rather than hand over
// zero for the whole session. Bounded: a failed or stalled ImGui init
// must not hold plugins (and the bot) back.
if (pluginsDraw && pluginContext == IntPtr.Zero && !_imguiInitFailed
&& ++_pluginInitContextWaits <= PluginInitContextMaxWaits)
return;
if (pluginsDraw && pluginContext == IntPtr.Zero)
RynthLog.Warn($"EngineFrameController: plugins initialised without an ImGui context (imguiInitFailed={_imguiInitFailed}, waits={_pluginInitContextWaits}) - plugin overlay windows will not draw this session.");
_pluginsInitialized = true;
PluginManager.InitPlugins(pluginContext, device, _gameHwnd);
}
@ -471,7 +534,13 @@ internal static class EngineFrameController
}
catch (Exception ex)
{
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message}");
// The first one with its stack, then counted (a step throwing every frame
// would otherwise write a line per pump tick).
int n = ++_pumpFrameFaults;
if (n == 1)
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message} (caught; repeats are counted){Environment.NewLine}{ex}");
else if (n % StepFaultLog.RepeatEvery == 0)
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message} - {n} times so far, still caught.");
}
finally
{
@ -501,9 +570,16 @@ internal static class EngineFrameController
if (!PanelsLive) return false;
ImGuiPanelHost.RestoreOnce();
return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame
|| D3D9.VideoPatch.WantsBanner;
|| D3D9.VideoPatch.WantsBanner || PluginOverlayWindowsLive;
}
/// <summary>
/// In the world, with the shell off, and some loaded plugin exports
/// RynthPluginRenderOverlay: its windows need a frame every frame.
/// </summary>
private static bool PluginOverlayWindowsLive =>
PanelsLive && Plugins.EngineSettings.EnablePluginOverlayWindows && PluginManager.HasOverlayPlugins;
/// <summary>
/// Panel faces show only in the world, like the Avalonia overlay (hidden
/// between characters, not closed). Also off as soon as AC leaves the world screen
@ -544,7 +620,8 @@ internal static class EngineFrameController
}
private static bool HasImGuiContentNoRestore() =>
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner));
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner))
|| PluginOverlayWindowsLive;
// Keyboard owner between the stacks (plan §3.2 d): whichever side started
// text entry most recently keeps the keyboard.
@ -573,6 +650,7 @@ internal static class EngineFrameController
if (!Init(pDevice))
{
_imguiInitFailed = true;
RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session.");
return false;
}
}
@ -596,7 +674,6 @@ internal static class EngineFrameController
ImGuiNET.ImGui.SetCurrentContext(_context);
bool frameStarted = false;
bool frameEnded = false;
try
{
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
@ -644,6 +721,9 @@ internal static class EngineFrameController
ImGuiNET.ImGui.NewFrame();
frameStarted = true;
// Before any window: a drag from a popped-out Inventory or AC's inventory becomes
// a payload the client's drop targets (Mini Remote slots) see this frame.
ItemDragBridge.SubmitMainFrame(io);
ImGuiTextFocus.BeginFrame();
if (_dropImGuiTextFocus)
{
@ -653,11 +733,29 @@ internal static class EngineFrameController
}
// EnableImGuiShell gates the old diagnostic shell and plugin-drawn
// ImGui windows (plugin code on AC's thread: FORCE-gated, stays off).
int branch;
if (Plugins.EngineSettings.EnableImGuiShell)
{
branch = 1;
RynthCoreShell.Render(_frameCount);
PluginManager.RenderAll();
}
else if (PluginOverlayWindowsLive)
{
branch = 2;
// Only the opt-in extra windows (RynthPluginRenderOverlay), never the
// plugins' full ImGui UIs.
PluginManager.RenderOverlayAll();
}
else
{
branch = 0;
}
if (branch != _loggedBranch)
{
_loggedBranch = branch;
RynthLog.Info($"EngineFrameController: ImGui plugin branch = {(branch == 1 ? "shell (RenderAll)" : branch == 2 ? "overlay windows (RenderOverlayAll)" : "none")}.");
}
if (PanelsLive)
{
// World overlays: built into UnderUiLayer's list, drawn next frame at
@ -744,6 +842,24 @@ internal static class EngineFrameController
_prevAvaloniaText = avaloniaText;
}
/// <summary>
/// Submits this frame's ImGui draw data. EndSceneHook calls it after
/// OverlayTextureRenderer.Render so ImGui windows draw on top of the Avalonia layer.
/// Runs whether or not the Avalonia blit ran (character select, Avalonia off), and is
/// a no-op when <see cref="OnEndScene"/> built nothing this frame. Never throws.
/// </summary>
public static void RenderDeferredImGui()
{
IntPtr device = _deferredSubmitDevice;
if (device == IntPtr.Zero)
return;
_deferredSubmitDevice = IntPtr.Zero; // one submission per frame, even if it throws
long t0 = Stopwatch.GetTimestamp();
SubmitImGuiFrame(device);
UiFrameStats.Record(_deferredUiTicks + (Stopwatch.GetTimestamp() - t0));
}
/// <summary>Draws the frame <see cref="BuildImGuiFrame"/> produced.</summary>
private static void SubmitImGuiFrame(IntPtr pDevice)
{
@ -751,7 +867,15 @@ internal static class EngineFrameController
ImGuiNET.ImGui.SetCurrentContext(_context);
try
{
DX9Backend.RenderDrawData(ImGuiNET.ImGui.GetDrawData(), pDevice);
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
DX9Backend.RenderDrawData(drawData, pDevice);
_drawSubmits++;
if (!_loggedFirstSubmit)
{
_loggedFirstSubmit = true;
RynthLog.Info("EngineFrameController: first ImGui draw submitted.");
}
LogHeartbeatIfDue(drawData);
}
catch (Exception ex)
{
@ -763,6 +887,29 @@ internal static class EngineFrameController
}
}
/// <summary>
/// Every 30 s: built ImGui frames, submits, draw list / vertex counts of the
/// latest frame and the overlay-window stats from PluginManager. Zero draw lists means no
/// ImGui window was drawn that frame. One string per interval; no per-frame allocation.
/// </summary>
private static void LogHeartbeatIfDue(ImDrawDataPtr drawData)
{
long now = Environment.TickCount64;
if (now < _nextHeartbeatAt) return;
bool first = _nextHeartbeatAt == 0;
_nextHeartbeatAt = now + HeartbeatIntervalMs;
if (first) return; // first interval starts now; the first-frame line already covers t=0
int lists = 0, vertices = 0;
unsafe
{
// ImDrawData: +4 CmdListsCount, +8 TotalIdxCount, +12 TotalVtxCount (see CLAUDE.md offsets).
byte* p = (byte*)drawData.NativePtr;
if (p != null) { lists = *(int*)(p + 4); vertices = *(int*)(p + 12); }
}
RynthLog.Info($"EngineFrameController: ImGui heartbeat frames={_framesBuilt} submits={_drawSubmits} lastFrame drawLists={lists} vertices={vertices} {PluginManager.DescribeOverlayState()}.");
}
internal static IntPtr FindGameWindow()
{
uint pid = GetCurrentProcessId();

View file

@ -57,12 +57,14 @@ internal static class ImGuiBar
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
private static readonly string[] ImGuiOnlyBarPanels =
{ Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title };
{ Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title,
Panels.CharactersFace.Title };
// The ILT section: the RynthILT plugin's ImGui-only panels. They never get buttons of their
// own; one ILT button stands for them, shown only on Infinite Leaftide (IltInfo.IsIlt) and
// only for the ones registered (EntryPoint registers them when RynthILT is installed).
private static readonly string[] IltPanels = { Panels.BountiesFace.Title };
// The ILT section: ImGui-only Infinite Leaftide panels (Bounties from RynthILT, Guardian from
// RynthAi). They never get buttons of their own; one ILT button stands for them, shown only
// on Infinite Leaftide (IltInfo.IsIlt) and only for the ones registered (EntryPoint registers
// each when its plugin is installed).
private static readonly string[] IltPanels = { Panels.BountiesFace.Title, Panels.GuardianFace.Title };
// Known panels' icons (DrakBot's where the same window exists); others show their first letter.
private static readonly Dictionary<string, string> PanelIcons = new(StringComparer.OrdinalIgnoreCase)
@ -88,6 +90,7 @@ internal static class ImGuiBar
["Log"] = PhosphorIcons.TerminalWindow,
["Item Count"] = PhosphorIcons.Bag,
["Mini Remote"] = PhosphorIcons.SquaresFour,
["Characters"] = PhosphorIcons.UsersThree,
// Plugin windows with a bar button of their own (script windows, by title).
["RynthSort"] = PhosphorIcons.SortAscending,
["Oracle"] = PhosphorIcons.Sparkle,
@ -261,6 +264,8 @@ internal static class ImGuiBar
public static void Draw(float s)
{
// The bar draws every frame the ImGui shell is up: keep RynthAi's server menu current.
RynthCore.Engine.UI.ServerMenus.Tick();
EnsureButtons();
int step = ChromeStep(out float factor);
s *= factor;
@ -389,8 +394,8 @@ internal static class ImGuiBar
FacePopup(b.PopupId, b.Title, ImGuiPanelHost.HasFace(b.Title));
}
// The ILT section: one button, only on Infinite Leaftide with RynthILT's panels
// registered. With one panel it toggles that panel; with more it opens a menu.
// The ILT section: one button, only on Infinite Leaftide with ILT panels registered
// (Bounties, Guardian). With one panel it toggles that panel; with more it opens a menu.
int iltCount = IltPanelCount();
if (iltCount > 0)
{
@ -418,7 +423,11 @@ internal static class ImGuiBar
ImGuiNET.ImGui.SameLine(0, 6 * s);
if (IconButton("##reload", iconFont, PhosphorIcons.ArrowsClockwise, square, RynthTheme.ReloadLabel))
{
// By hand: not held while a plugin objects (combat, looting); the player chose the moment.
EntryPoint.NoteManualReload();
ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null);
}
ImGuiNET.ImGui.SetItemTooltip("Engine reload (RL) — shut down, FreeLibrary, reload from disk, re-init.");
if (ResolveFace() == PanelFace.ImGui)

View file

@ -67,6 +67,10 @@ internal sealed record PanelSpec(
// Where the panel first opens (logical units) when nothing is saved for its
// key; null = the cascade. (Script windows: a FirstUseEver position.)
Vector2? DefaultPos = null,
// With nothing saved and no DefaultPos: open centred in the game view rather
// than in the top-left cascade, where popped-out panels (separate windows
// above the game frame) usually sit and would hide it.
bool OpenCentered = false,
// No resize grip, docked or popped out: the face sizes itself (the RynthNav arrow
// fits its height to what it shows). Chromeless and GripInBody panels only.
bool NoResize = false);
@ -651,6 +655,10 @@ internal static class ImGuiPanelHost
{
pos = defaultPos; // the face's own first spot (a script window's FirstUseEver position)
}
else if (entry.Spec.OpenCentered && CenteredLogicalPos(size, placeScale) is Vector2 centered)
{
pos = centered;
}
else
{
int shown = 0;
@ -670,6 +678,104 @@ internal static class ImGuiPanelHost
entry.NeedsPlacement = true;
entry.DesiredPos = entry.Pos != pos * placeScale ? pos * placeScale : null;
entry.DesiredForDisplay = ImGuiNET.ImGui.GetIO().DisplaySize;
// Popped-out windows sit above the game frame, so a docked panel opening under
// one would be invisible. The new spot is saved by the open's Persist, so the
// panel comes back where it could be seen.
if (ClearOfPopOuts(entry.Pos, entry.Size) is Vector2 clear)
{
RynthLog.UI($"ImGuiPanelHost: {entry.Title} would open under a popped-out window; " +
$"moved from ({entry.Pos.X:0},{entry.Pos.Y:0}) to ({clear.X:0},{clear.Y:0}).");
entry.Pos = clear;
entry.PersistedPos = clear;
entry.DesiredPos = null; // don't pull it back under the pop-out as the display grows
}
}
/// <summary>Above this share of a docked panel hidden by popped-out windows, it opens elsewhere.</summary>
private const float MaxCoveredFraction = 0.5f;
/// <summary>Candidate spots per axis when looking for a clear place (a grid over the game view).</summary>
private const int ClearSpotSteps = 8;
/// <summary>
/// A spot (client px) for a docked window of <paramref name="size"/> at <paramref name="pos"/>
/// that popped-out windows hide less, nearest the original among the least-covered; null when
/// at most half of it is covered or no spot is better.
/// </summary>
private static Vector2? ClearOfPopOuts(Vector2 pos, Vector2 size)
{
float area = size.X * size.Y;
if (area <= 0) return null;
List<(Vector2 Min, Vector2 Max)> covers = PopOutRectsInClient();
if (covers.Count == 0) return null;
float covered = CoveredArea(pos, size, covers);
if (covered <= area * MaxCoveredFraction) return null;
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
if (display.X <= 1 || display.Y <= 1) return null;
Vector2 room = Vector2.Max(Vector2.Zero, display - size);
// Pass 1: the least coverage any grid spot reaches. Pass 2: the nearest spot within
// 2% of the panel's area of that, so a nearly-as-clear nearby spot beats a far one.
float least = float.MaxValue;
for (int i = 0; i <= ClearSpotSteps; i++)
for (int j = 0; j <= ClearSpotSteps; j++)
least = Math.Min(least, CoveredArea(GridSpot(room, i, j), size, covers));
if (least >= covered) return null;
float tolerance = least + area * 0.02f;
Vector2? best = null;
float bestDist = float.MaxValue;
for (int i = 0; i <= ClearSpotSteps; i++)
for (int j = 0; j <= ClearSpotSteps; j++)
{
Vector2 spot = GridSpot(room, i, j);
if (CoveredArea(spot, size, covers) > tolerance) continue;
float dist = Vector2.DistanceSquared(spot, pos);
if (dist < bestDist) { bestDist = dist; best = spot; }
}
return best;
}
private static Vector2 GridSpot(Vector2 room, int i, int j) =>
new(MathF.Round(room.X * i / ClearSpotSteps), MathF.Round(room.Y * j / ClearSpotSteps));
/// <summary>Visible popped-out windows' rects in the game window's client px (ImGui coordinates).</summary>
private static List<(Vector2 Min, Vector2 Max)> PopOutRectsInClient()
{
Vector2 origin = ImGuiPopOuts.ClientOriginOnScreen();
var rects = new List<(Vector2, Vector2)>();
foreach (var (left, top, width, height) in UI.LayeredWindow.VisibleContentRects())
{
var min = new Vector2(left, top) - origin;
rects.Add((min, min + new Vector2(width, height)));
}
return rects;
}
/// <summary>Area of the window hidden by <paramref name="covers"/> (overlaps between covers count twice).</summary>
private static float CoveredArea(Vector2 pos, Vector2 size, List<(Vector2 Min, Vector2 Max)> covers)
{
Vector2 max = pos + size;
float total = 0;
foreach (var (cMin, cMax) in covers)
{
float w = MathF.Min(max.X, cMax.X) - MathF.Max(pos.X, cMin.X);
float h = MathF.Min(max.Y, cMax.Y) - MathF.Max(pos.Y, cMin.Y);
if (w > 0 && h > 0) total += w * h;
}
return total;
}
/// <summary>
/// Top-left (logical units) that centres a window of logical <paramref name="size"/> in the
/// game view; null while the display size isn't known yet.
/// </summary>
private static Vector2? CenteredLogicalPos(Vector2 size, float placeScale)
{
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
if (display.X <= 1 || display.Y <= 1 || placeScale <= 0) return null;
return Vector2.Max(Vector2.Zero, (display / placeScale - size) * 0.5f);
}
private static Vector2 ClampToDisplay(Vector2 pos, Vector2 size)
@ -1093,43 +1199,7 @@ internal static class ImGuiPanelHost
if (!ImGuiNET.ImGui.BeginPopup(TextSizePopupId)) return;
try
{
int step = PanelTextScale.Get(title);
int max = PanelTextScale.SizeNames.Length - 1;
int all = PanelTextScale.GetAll();
float btn = 20f * s;
ImGuiNET.ImGui.TextUnformatted("Text size");
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
ImGuiNET.ImGui.BeginDisabled(step <= 0);
if (HeaderIconButton("##ts_smaller", PhosphorIcons.Minus, btn))
PanelTextScale.SetForWindow(title, step - 1);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip("Smaller");
ImGuiNET.ImGui.SameLine(0, 4 * s);
ImGuiNET.ImGui.BeginDisabled(step >= max);
if (HeaderIconButton("##ts_bigger", PhosphorIcons.Plus, btn))
PanelTextScale.SetForWindow(title, step + 1);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip("Bigger");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.SameLine(0, 8 * s);
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted(PanelTextScale.Describe(step));
int pick = step;
ImGuiNET.ImGui.SetNextItemWidth(btn * 2 + 4 * s + 8 * s + 110 * s);
if (ImGuiNET.ImGui.SliderInt("##ts_step", ref pick, 0, max, "%d", ImGuiSliderFlags.AlwaysClamp) && pick != step)
PanelTextScale.SetForWindow(title, pick);
ImGuiNET.ImGui.BeginDisabled(step == all);
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + " Reset"))
PanelTextScale.ResetWindow(title);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip(all == 0 ? "Back to normal size" : "Back to the All Panels size (Settings > Display)");
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button("Use for all windows"))
PanelTextScale.UseForAll(step);
ImGuiNET.ImGui.SetItemTooltip("Every in-game window at this size (Settings > Display > All Panels)");
TextSizeRows(title, s);
}
finally
{
@ -1137,6 +1207,53 @@ internal static class ImGuiPanelHost
}
}
/// <summary>
/// The text size popup's rows for <paramref name="title"/> at the cursor: smaller / bigger and the
/// size, a slider over the steps, reset, use for all windows. The title bar's popup, and a chromeless
/// panel's own popup (the RynthAi dashboard's title row). <paramref name="s"/> scales the buttons.
/// AC thread, inside a popup.
/// </summary>
public static void TextSizeRows(string title, float s, string heading = "Text size")
{
int step = PanelTextScale.Get(title);
int max = PanelTextScale.SizeNames.Length - 1;
int all = PanelTextScale.GetAll();
float btn = 20f * s;
ImGuiNET.ImGui.TextUnformatted(heading);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
ImGuiNET.ImGui.BeginDisabled(step <= 0);
if (HeaderIconButton("##ts_smaller", PhosphorIcons.Minus, btn))
PanelTextScale.SetForWindow(title, step - 1);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip("Smaller");
ImGuiNET.ImGui.SameLine(0, 4 * s);
ImGuiNET.ImGui.BeginDisabled(step >= max);
if (HeaderIconButton("##ts_bigger", PhosphorIcons.Plus, btn))
PanelTextScale.SetForWindow(title, step + 1);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip("Bigger");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.SameLine(0, 8 * s);
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted(PanelTextScale.Describe(step));
int pick = step;
ImGuiNET.ImGui.SetNextItemWidth(btn * 2 + 4 * s + 8 * s + 110 * s);
if (ImGuiNET.ImGui.SliderInt("##ts_step", ref pick, 0, max, "%d", ImGuiSliderFlags.AlwaysClamp) && pick != step)
PanelTextScale.SetForWindow(title, pick);
ImGuiNET.ImGui.BeginDisabled(step == all);
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + " Reset"))
PanelTextScale.ResetWindow(title);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip(all == 0 ? "Back to normal size" : "Back to the All Panels size (Settings > Display)");
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button("Use for all windows"))
PanelTextScale.UseForAll(step);
ImGuiNET.ImGui.SetItemTooltip("Every in-game window at this size (Settings > Display > All Panels)");
}
private const string DragLabel = PhosphorIcons.DotsSixVertical + "DRAG";
/// <summary>A header button (the theme's button look) with an icon centred on it.</summary>

View file

@ -0,0 +1,251 @@
// ============================================================================
// RynthCore.Engine - ImGui/ItemDragBridge.cs
// Carries an item drag into the MAIN ImGui context when it didn't start there,
// so drop targets in the client (RynthAi's Mini Remote slots) can take it:
//
// • A popped-out Inventory: the pop-out has its own ImGui context and holds
// mouse capture for the whole drag, so the main context never sees it.
// The pop-out face reports the dragged item (NotePopOutDrag); the main
// frame republishes it as an extern payload. The main context sees no
// button press, so the payload uses PayloadAutoExpire: it is delivered to
// the hovered target on the first frame it is no longer submitted.
// • AC's own inventory: a press that began on the game belongs to the game,
// and ImGui ignores hovering for it. DragDropHooks reports the item AC
// starts dragging (OnNativeDragStart); a carried one is republished the
// same way, under PayloadType, and delivered when ImGui sees the button go
// up. AC does not select the dragged item, so without that hook the bridge
// can only guess from the selection: the guess goes out under
// NativePayloadType, which targets treat as unreliable.
//
// A native drag released over an ImGui window would otherwise complete in AC
// as a drop on the 3D view (the item lands on the ground). TryRedirectNativeDrop
// moves that button-up back to where the drag began, which AC treats as
// putting the item back.
//
// Threads: AC's main thread only (game WndProc, EndScene, pop-out frames).
// ============================================================================
using System;
using System.Diagnostics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ItemDragBridge
{
/// <summary>Payload type for one item (uint object id). Must match RynthAi's MiniRemoteHud.ItemPayloadType.</summary>
public const string PayloadType = "RYNTH_INV_ITEM";
/// <summary>
/// Payload type for a game drag whose item was guessed from the selection (DragDropHooks not
/// installed). Any game left-drag with a carried item selected looks like this (moving an AC
/// panel too), so targets should take it only where a wrong item does no harm (RynthAi: empty
/// slots). Must match MiniRemoteHud.GameItemPayloadType.
/// </summary>
public const string NativePayloadType = "RYNTH_GAME_ITEM";
private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202;
private const int MK_LBUTTON = 0x0001, MK_OTHER = 0x0002 | 0x0010 | 0x0020 | 0x0040;
/// <summary>Movement (px, squared) before a game press counts as a drag.</summary>
private const int DragThresholdSq = 5 * 5;
/// <summary>AC may select the pressed item a few messages after the press: keep re-reading it this long.</summary>
private static readonly long SelectionSettleTicks = Stopwatch.Frequency / 2;
/// <summary>A pop-out drag with no report for this long is over (the pop-out closed mid-drag).</summary>
private static readonly long PopOutStaleTicks = Stopwatch.Frequency;
// Popped-out Inventory drag.
private static uint _popOutItem;
private static long _popOutSeenAt;
// Native (AC inventory) drag.
private static bool _pressPending;
private static IntPtr _pressLParam;
private static int _pressX, _pressY;
private static long _pressAt;
private static uint _nativeItem;
/// <summary>_nativeItem came from AC's drag start (DragDropHooks), not from the selection.</summary>
private static bool _nativeFromHook;
/// <summary>The left button is down on a press that belongs to the game.</summary>
private static bool _gamePressHeld;
private static bool _nativeReleased;
/// <summary>The cursor was over an ImGui window in the last main frame (only tracked during a native drag).</summary>
private static bool _overImGui;
// ── Popped-out Inventory ────────────────────────────────────────────────
/// <summary>A popped-out Inventory is dragging <paramref name="itemId"/> (call every pop-out frame of the drag).</summary>
public static void NotePopOutDrag(uint itemId)
{
if (itemId == 0) return;
if (_popOutItem != itemId)
RynthLog.UI($"ItemDragBridge: pop-out drag 0x{itemId:X8} published to the client.");
_popOutItem = itemId;
_popOutSeenAt = Stopwatch.GetTimestamp();
}
/// <summary>The popped-out Inventory's drag ended (dropped or cancelled).</summary>
public static void EndPopOutDrag() => _popOutItem = 0;
// ── Native drag (game WndProc) ──────────────────────────────────────────
/// <summary>
/// Every game-window mouse message, after the backend decided who owns the held buttons.
/// <paramref name="gameOwned"/>: the current press began on the game, not on ImGui.
/// </summary>
public static void OnGameMouse(uint msg, IntPtr wParam, IntPtr lParam, bool gameOwned)
{
int keys = (int)((long)wParam & 0xFFFF);
switch (msg)
{
case WM_LBUTTONDOWN:
// Only a plain left press that belongs to the game can be an inventory drag.
_pressPending = gameOwned && (keys & MK_OTHER) == 0;
_pressLParam = lParam;
_pressX = LoWord(lParam);
_pressY = HiWord(lParam);
_pressAt = Stopwatch.GetTimestamp();
_gamePressHeld = _pressPending;
if (_pressPending) { _nativeItem = 0; _nativeFromHook = false; _nativeReleased = false; }
break;
case WM_MOUSEMOVE:
if ((keys & MK_LBUTTON) == 0)
{
// A release we never saw (outside the window): finish the drag.
_pressPending = false;
_gamePressHeld = false;
if (_nativeItem != 0) _nativeReleased = true;
break;
}
if (_pressPending)
{
int dx = LoWord(lParam) - _pressX, dy = HiWord(lParam) - _pressY;
if (dx * dx + dy * dy >= DragThresholdSq)
{
_pressPending = false;
// With the drag-start hook the real item arrives through OnNativeDragStart.
if (_nativeItem == 0 && !DragDropHooks.IsInstalled)
{
_nativeItem = CarriedSelection();
if (_nativeItem != 0)
RynthLog.UI($"ItemDragBridge: native inventory drag 0x{_nativeItem:X8} (from the selection) published to ImGui.");
}
}
}
else if (_nativeItem != 0 && !_nativeFromHook && !_nativeReleased && Stopwatch.GetTimestamp() - _pressAt < SelectionSettleTicks)
{
// The selection can trail the press by a few messages: follow it while it settles.
uint sel = CarriedSelection();
if (sel != 0) _nativeItem = sel;
}
break;
case WM_LBUTTONUP:
_pressPending = false;
_gamePressHeld = false;
if (_nativeItem != 0) _nativeReleased = true;
break;
}
}
/// <summary>
/// AC started dragging <paramref name="itemId"/> (DragDropHooks, AC's main thread). Taken while
/// a game-owned left press is held and only for items the player carries.
/// </summary>
public static void OnNativeDragStart(uint itemId)
{
if (!_gamePressHeld || itemId == 0 || !IsCarried(itemId)) return;
_pressPending = false;
_nativeItem = itemId;
_nativeFromHook = true;
_nativeReleased = false;
RynthLog.UI($"ItemDragBridge: native inventory drag 0x{itemId:X8} published to ImGui.");
}
/// <summary>
/// A native item drag is being released over an ImGui window: returns the press position
/// to send AC instead, so AC puts the item back rather than dropping it on the ground.
/// </summary>
public static bool TryRedirectNativeDrop(uint msg, out IntPtr pressLParam)
{
pressLParam = _pressLParam;
if (msg != WM_LBUTTONUP || _nativeItem == 0 || !_overImGui) return false;
RynthLog.UI($"ItemDragBridge: native drag 0x{_nativeItem:X8} released over an ImGui window; AC gets the drop back at its start ({_pressX},{_pressY}).");
return true;
}
// ── Main frame (after ImGui.NewFrame, before any window) ────────────────
/// <summary>Republishes a pop-out or native drag in the main context for this frame.</summary>
public static void SubmitMainFrame(ImGuiIOPtr io)
{
uint id = 0;
string type = PayloadType;
if (_popOutItem != 0)
{
if (Stopwatch.GetTimestamp() - _popOutSeenAt > PopOutStaleTicks) _popOutItem = 0;
else id = _popOutItem;
}
if (id == 0 && _nativeItem != 0)
{
type = _nativeFromHook ? PayloadType : NativePayloadType;
// After the button-up, stop once ImGui itself sees the button up: that frame
// delivers the drop (the payload outlives its last submission by one frame).
if (_nativeReleased && !io.MouseDown[0])
{
_nativeItem = 0;
_nativeFromHook = false;
_nativeReleased = false;
_overImGui = false;
return;
}
id = _nativeItem;
_overImGui = ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem);
}
if (id == 0) return;
const ImGuiDragDropFlags flags = ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip
| ImGuiDragDropFlags.PayloadAutoExpire;
if (ImGuiNET.ImGui.BeginDragDropSource(flags))
{
ImGuiNET.ImGui.SetDragDropPayload(type, (IntPtr)(&id), sizeof(uint));
ImGuiNET.ImGui.EndDragDropSource();
}
}
/// <summary>Forget every drag (focus lost, logout, engine shutdown).</summary>
public static void Reset()
{
_popOutItem = 0;
_pressPending = false;
_gamePressHeld = false;
_nativeItem = 0;
_nativeFromHook = false;
_nativeReleased = false;
_overImGui = false;
}
/// <summary>The game's selected object when the player carries it, else 0.</summary>
private static uint CarriedSelection()
{
uint id = ClientHelperHooks.GetSelectedItemId();
return IsCarried(id) ? id : 0;
}
/// <summary><paramref name="id"/> is in the player's pack, a side pack, or worn.</summary>
private static bool IsCarried(uint id)
{
if (id == 0 || !ClientHelperHooks.HasGetPlayerId) return false;
uint player = ClientHelperHooks.GetPlayerId();
if (player == 0 || id == player) return false;
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _)) return false;
if (wielder == player || container == player) return true;
// Side pack in the main pack.
return container != 0 && ClientObjectHooks.TryGetObjectOwnershipInfo(container, out uint outer, out _, out _) && outer == player;
}
private static int LoWord(IntPtr l) => unchecked((short)((long)l & 0xFFFF));
private static int HiWord(IntPtr l) => unchecked((short)(((long)l >> 16) & 0xFFFF));
}

View file

@ -0,0 +1,76 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/CleaveHealth.cs
// Health for monsters the player hits but the server doesn't stream health
// for (2026-10-12, Drakkon with a Tetsubo: "the HUD health for monsters only
// changes if they are targeted. It doesn't change for AoE monsters").
//
// ACE pushes UpdateHealth (0x01C0) only for the object a player has selected
// or queried (RynthAi queries its combat target), so the second and third mob
// a cleave hits kept their old bar. Every hit does send an AttackerNotification
// (0x01B1) naming the monster - no id - with the damage and its share of the
// monster's max health (damage / max: 204 on an Olthoi Slasher's 2300 reads
// 0.089). This turns that share into a bar estimate on the plate it belongs
// to. Pure: no engine state; MonsterHud passes the candidates in.
//
// Rules, for the plates carrying the hit's name:
// * one whose real (server) health dropped by this share around the hit
// already got it from 0x01C0: nothing to do;
// * a plate with a live server feed (a real update in the last
// LiveFeedSec) is left to the server;
// * otherwise the nearest one takes the share off its last ratio (full when
// never seen), never below MinRatio - a kill comes from the kill message
// and the object's deletion, not from an estimate.
// ============================================================================
using System;
namespace RynthCore.Engine.ImGuiBackend.Hud;
internal static class CleaveHealth
{
/// <summary>A real update this close to the hit (s) with the same drop is the same hit.</summary>
public const double SameHitSec = 0.6;
/// <summary>Drop-vs-share tolerance for "the same hit".</summary>
public const float MatchTolerance = 0.006f; // both sides are the server's exact numbers; a different hit is rarely this close
/// <summary>A real update this recent (s) means the server is feeding this plate.</summary>
public const double LiveFeedSec = 1.5;
/// <summary>An estimate never takes a bar lower than this.</summary>
public const float MinRatio = 0.01f;
/// <summary>One plate with the hit's name. <paramref name="ObsAgeSec"/>: seconds between its
/// last health observation and the hit (negative = the observation came after it).</summary>
public readonly record struct Candidate(uint Id, float Distance, bool HasObs, float Ratio, float Prev, bool Estimated, double ObsAgeSec);
/// <summary>
/// The plate a hit of <paramref name="share"/> (damage / max health) belongs to and its new
/// ratio, or 0 when no plate should change.
/// </summary>
public static uint Pick(ReadOnlySpan<Candidate> candidates, float share, out float newRatio)
{
newRatio = 0f;
if (candidates.Length == 0 || !(share > 0f) || share > 1.5f) return 0;
foreach (Candidate c in candidates)
{
if (!c.HasObs || c.Estimated || c.Prev < 0f) continue;
if (Math.Abs(c.ObsAgeSec) <= SameHitSec && Math.Abs((c.Prev - c.Ratio) - share) <= MatchTolerance)
return 0; // the server reported this hit itself
}
uint best = 0;
float bestD = float.MaxValue, bestRatio = 1f;
foreach (Candidate c in candidates)
{
if (c.HasObs && !c.Estimated && c.ObsAgeSec >= -SameHitSec && c.ObsAgeSec <= LiveFeedSec) continue; // server-fed
if (c.Distance < bestD)
{
best = c.Id;
bestD = c.Distance;
bestRatio = c.HasObs ? c.Ratio : 1f;
}
}
if (best == 0) return 0;
newRatio = Math.Max(MinRatio, bestRatio - share);
return best;
}
}

View file

@ -102,10 +102,16 @@ internal static class HudFeed
catch (Exception ex) { Log("delete", ex); }
}
public static void OnDamageEvent(bool attacker, string? name, uint damage, bool crit)
/// <summary><paramref name="share"/>: the hit's damage / the monster's max health (AttackerNotification), 0 = unknown.</summary>
public static void OnDamageEvent(bool attacker, string? name, uint damage, bool crit, double share = 0)
{
if (!On) return;
try { CombatText.OnDamageEvent(attacker, name, damage, crit); }
try
{
CombatText.OnDamageEvent(attacker, name, damage, crit);
if (attacker && share > 0 && MonsterHudSettings.Enabled && !string.IsNullOrEmpty(name))
MonsterHud.NoteDealtHit(name, damage, share);
}
catch (Exception ex) { Log("damage", ex); }
}

View file

@ -298,6 +298,7 @@ internal static class MonsterHud
CombatText.PollGains(_playerId);
if (track) Snapshot(now, trackMonsters);
}
if (monsters) ApplyDealtHits(now);
_hasContent = Plates.Count > 0 || MonsterHudSettings.SelfPlate || CombatText.HasContent;
}
@ -1564,6 +1565,66 @@ internal static class MonsterHud
/// The plate whose monster has <paramref name="name"/>: the selected one first,
/// then the one the player hit most recently, then the nearest. 0 if none.
/// </summary>
// ── Hits on monsters with no health feed (CleaveHealth) ─────────────
private readonly record struct DealtHit(string Name, float Share, long Ticks);
private static readonly object HitSync = new();
private static readonly List<DealtHit> PendingHits = new();
private static readonly List<DealtHit> HitWork = new();
private static string? _lastHitName;
private static uint _lastHitDamage;
private static long _lastHitTicks;
private const int MaxPendingHits = 64;
/// <summary>A hit waits this long (s) so the server's own UpdateHealth for it (the queried
/// target's) is in before the plates are matched.</summary>
private const double HitSettleSec = 0.25;
/// <summary>AttackerNotification: the player hit <paramref name="name"/> for
/// <paramref name="share"/> of its max health. AC's main thread (SmartBoxHooks, two paths per
/// event - the same hit inside 50 ms counts once).</summary>
internal static void NoteDealtHit(string name, uint damage, double share)
{
long now = Stopwatch.GetTimestamp();
lock (HitSync)
{
if (damage == _lastHitDamage && name == _lastHitName && now - _lastHitTicks < Stopwatch.Frequency / 20) return;
_lastHitName = name; _lastHitDamage = damage; _lastHitTicks = now;
if (PendingHits.Count >= MaxPendingHits) PendingHits.RemoveAt(0);
PendingHits.Add(new DealtHit(name, (float)share, now));
}
}
private static readonly List<CleaveHealth.Candidate> HitCandidates = new();
/// <summary>Settled hits onto the plates of monsters the server isn't feeding health for.</summary>
private static void ApplyDealtHits(long now)
{
HitWork.Clear();
lock (HitSync)
{
if (PendingHits.Count == 0) return;
long settle = (long)(HitSettleSec * Stopwatch.Frequency);
int n = 0;
while (n < PendingHits.Count && now - PendingHits[n].Ticks >= settle) n++;
if (n == 0) return;
HitWork.AddRange(PendingHits.GetRange(0, n));
PendingHits.RemoveRange(0, n);
}
double freq = Stopwatch.Frequency;
foreach (DealtHit hit in HitWork)
{
HitCandidates.Clear();
foreach (Plate p in Plates.Values)
{
if (p.Gone || p.IsLabel || !p.Name.Equals(hit.Name, StringComparison.Ordinal)) continue;
bool has = MonsterHudData.TryGetHealth(p.Id, out HealthObservation h);
HitCandidates.Add(new CleaveHealth.Candidate(p.Id, p.Distance, has, has ? h.Ratio : 1f, has ? h.Prev : -1f,
has && h.Estimated, has ? (hit.Ticks - h.Ticks) / freq : 0));
}
uint id = CleaveHealth.Pick(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(HitCandidates), hit.Share, out float ratio);
if (id != 0) MonsterHudData.RecordHealth(id, ratio, 0, 0, estimated: true);
}
}
internal static uint FindPlateByName(string name)
{
uint target = ClientHelperHooks.GetSelectedItemId();

View file

@ -22,8 +22,9 @@ using System.Diagnostics;
namespace RynthCore.Engine.ImGuiBackend.Hud;
/// <summary>Last health observation for one object.</summary>
internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks);
/// <summary>Last health observation for one object. <paramref name="Prev"/>: the ratio before it
/// (-1 = first). <paramref name="Estimated"/>: worked out from a hit (CleaveHealth), not sent by the server.</summary>
internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks, float Prev = -1f, bool Estimated = false);
internal static class MonsterHudData
{
@ -36,17 +37,20 @@ internal static class MonsterHudData
/// <summary>
/// A health update for <paramref name="id"/>. A max of 0 (ratio-only update)
/// keeps the last known max. Any thread; never blocks for long.
/// <paramref name="estimated"/>: from a hit's share of max health (CleaveHealth), not the server.
/// </summary>
public static void RecordHealth(uint id, float ratio, uint current, uint max)
public static void RecordHealth(uint id, float ratio, uint current, uint max, bool estimated = false)
{
if (id == 0 || float.IsNaN(ratio)) return;
ratio = Math.Clamp(ratio, 0f, 1f);
long now = Stopwatch.GetTimestamp();
float before = -1f;
bool prevWasEstimate = false;
lock (Sync)
{
bool had = Health.TryGetValue(id, out HealthObservation prev);
if (had) before = prev.Ratio;
prevWasEstimate = had && prev.Estimated;
if (max == 0 && had && prev.Max > 0)
{
max = prev.Max;
@ -54,10 +58,13 @@ internal static class MonsterHudData
}
if (Health.Count >= MaxHealthEntries && !Health.ContainsKey(id))
Health.Clear();
Health[id] = new HealthObservation(ratio, current, max, now);
Health[id] = new HealthObservation(ratio, current, max, now, before, estimated);
}
// An estimate never kills (CleaveHealth keeps it above 0) and the server correcting one
// isn't a heal: the combat text sees an estimate's successor as a first observation.
if (estimated) return;
// Kills and heals for the combat text; a death also drops the monster's debuffs.
HudFeed.OnHealth(id, before, ratio, max);
HudFeed.OnHealth(id, prevWasEstimate ? -1f : before, ratio, max);
}
public static bool TryGetHealth(uint id, out HealthObservation h)

View file

@ -0,0 +1,401 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/CharactersFace.cs
// The Characters panel: your other characters (the other RynthCore clients on
// this PC, through the RynthNet plugin), like UtilityBelt's networked
// character window. Engine only, ImGui only.
//
// top how many, or why none (RynthNet missing / offline); "all
// follow me"; the help mark
// rows this client first (dimmed), then the others alphabetically (a
// stable order: characters standing together would reshuffle
// several times a second if sorted by distance). Each row:
// line 1 direction arrow (relative to where you face), name
// (+ server when it isn't yours), state (botting / idle /
// dead / portal space / combat stance), a stale marker,
// distance and compass point
// line 2 health / stamina / mana bars with current/max, and
// where they are (map coordinates or dungeon name)
// click selects the character in game when this client can see it;
// right follow me / stop following / start or stop the macro on that
// client (sent as /rn tell; its RynthNet command policy decides)
//
// Data: UiSources.Characters (UI/Data/CharactersData.cs, 2 Hz while open).
// Follows the panel text size (PanelTextScale): layout scales with the font.
// AC's render thread; no AC calls, no per-frame allocation except a hovered
// row's tooltip and the popup's labels.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class CharactersFace : IImGuiPanel
{
public const string Title = "Characters";
public static void Register()
{
ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(420, 260), new Vector2(280, 140), EdgeToEdge: true, GripInBody: true),
() => new CharactersFace());
}
// ── Palette (the RynthAi dashboard's vitals colours) ─────────────────
private static uint C(uint argb) => RynthTheme.Argb(argb);
private static readonly uint HpCol = C(0xFFD93333), StCol = C(0xFF40D973), MpCol = C(0xFF268CF2),
BarBg = C(0xFF0D161F), Purple = C(0xFFBF4DFF), White = C(0xFFFFFFFF);
private const string HelpText =
"Your other characters: every RynthCore client on this PC running the RynthNet plugin.\n\n" +
"Each row shows health, stamina and mana, what the character is doing, and where it is. " +
"The distance and direction show when you are both outdoors (or in surface buildings), or in the same dungeon; " +
"otherwise the row says elsewhere and names the dungeon or gives map coordinates. Characters on another server " +
"only show their server.\n\n" +
"Rows stay in alphabetical order. A row that stops updating says so (its client may be frozen).\n\n" +
"Click a row to select that character in game (when this client can see it). Right-click for commands: " +
"follow me, stop following, start or stop the macro. They go through RynthNet, so the other client's " +
"remote command setting (/rn remote) decides whether they run.\n\n" +
"/rc characters opens and closes this panel.";
private float _k = 1f;
private float Px(float v) => v * _k;
// The right-clicked row (copied: the snapshot can change while the popup is open).
private string _menuName = "";
private uint _menuId;
private bool _menuInView, _menuOtherWorld, _menuSelf, _menuLoggedOut;
private bool _openMenu;
public int PopOutIdleHz => 10; // the arrows turn with you
public void OnShown()
{
UiSources.Characters.Subscribe();
UiSources.Characters.RequestRefresh();
}
public void OnHidden() => UiSources.Characters.Unsubscribe();
public void Draw()
{
_k = PanelTextScale.Factor(ImGuiFonts.CurrentStep);
float w = Begin(out Vector2 origin, out Vector2 size);
CharactersView view = UiSources.Characters.Current?.Value ?? CharactersView.Empty;
DrawTop(view, w);
float bodyH = Math.Max(Px(30), Remaining(origin, size) - GripOverlap());
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
ImGuiNET.ImGui.BeginChild("##chars_rows", new Vector2(w, bodyH));
DrawRows(view);
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
End(origin, size);
DrawMenu(view);
}
// ── Top line ────────────────────────────────────────────────────────
private void DrawTop(CharactersView view, float w)
{
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
float h = Px(20), iconW = Px(22);
float fontH = ImGuiNET.ImGui.GetFontSize();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float textW = Math.Max(10, w - 2 * iconW - Px(8));
dl.PushClipRect(start, start + new Vector2(textW, h), true);
dl.AddText(new Vector2(start.X, start.Y + (h - fontH) * 0.5f), view.NetLoaded ? Mute : Amber,
view.Status.Length > 0 ? view.Status : "Waiting for RynthNet...");
dl.PopClipRect();
float bx = start.X + w - 2 * iconW - Px(4);
bool canFollow = view.NetLoaded && view.MyName.Length > 0;
if (IconButton("##chars_followall", PhosphorIcons.Footprints, new Vector2(bx, start.Y), new Vector2(iconW, h), Text, BtnFill,
enabled: canFollow, font: UiFont.Ui11))
CharactersCommands.FollowMeAll();
ImGuiNET.ImGui.SetItemTooltip("Everyone follow me (/rn followme): every other client runs /ra follow <you>.");
IconButton("##chars_help", PhosphorIcons.Info, new Vector2(bx + iconW + Px(4), start.Y), new Vector2(iconW, h), Mute, BtnFill,
font: UiFont.Ui11);
if (ImGuiNET.ImGui.IsItemHovered())
{
ImGuiNET.ImGui.BeginTooltip();
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetFontSize() * 30);
ImGuiNET.ImGui.TextUnformatted(HelpText);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.EndTooltip();
}
NextLine(start, h + Px(4));
}
// ── Rows ────────────────────────────────────────────────────────────
private float RowH => Px(38);
private void DrawRows(CharactersView view)
{
CharacterRow[] rows = view.Rows;
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
if (rows.Length == 0)
{
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(Px(6), Px(6));
dl.AddText(at, Faded(Mute), view.NetLoaded ? "Not in the world." : "");
return;
}
uint selected = ClientHelperHooks.GetSelectedItemId();
float heading = PlayerHeading(out bool haveHeading);
float rowH = RowH;
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
int hovered = -1;
for (int i = 0; i < rows.Length; i++)
{
CharacterRow r = rows[i];
var p = new Vector2(start.X, start.Y + i * rowH);
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.PushID(i);
bool clicked = ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(bw, rowH),
ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
bool hot = ImGuiNET.ImGui.IsItemHovered();
bool right = clicked && ImGuiNET.ImGui.IsMouseReleased(ImGuiMouseButton.Right);
ImGuiNET.ImGui.PopID();
if (hot) hovered = i;
if (clicked && !right && r.InView && r.Id != 0 && !r.IsSelf)
AcMainThreadQueue.EnqueueOverlaySelect(r.Id);
if (right) OpenMenu(r);
DrawRow(dl, r, p, bw, rowH, i, hot, r.Id != 0 && r.Id == selected, heading, haveHeading);
}
ImGuiNET.ImGui.SetCursorScreenPos(start);
ImGuiNET.ImGui.Dummy(new Vector2(bw, rows.Length * rowH));
if (hovered >= 0 && rows[hovered].Tooltip.Length > 0 && !ImGuiNET.ImGui.IsPopupOpen("##chars_menu"))
{
ImGuiNET.ImGui.BeginTooltip();
ImGuiNET.ImGui.TextUnformatted(rows[hovered].Tooltip);
ImGuiNET.ImGui.EndTooltip();
}
}
private void DrawRow(ImDrawListPtr dl, CharacterRow r, Vector2 p, float bw, float rowH, int index, bool hot, bool isSel,
float heading, bool haveHeading)
{
uint bg = isSel ? Selected : hot ? Lighten(PanelBg) : (index & 1) == 1 ? RowAlt : 0;
if (bg != 0) dl.AddRectFilled(p, p + new Vector2(bw, rowH), bg);
if (isSel) dl.AddRect(p, p + new Vector2(bw, rowH), Teal);
// This client's row is dimmed: it's here for comparison.
float dim = r.IsSelf || r.LoggedOut ? 0.55f : 1f;
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), f10 = ImGuiFonts.Get(UiFont.Ui10);
float arrowW = Px(20), pad = Px(4);
float line1 = p.Y + Px(3);
float x = p.X + arrowW;
float right = p.X + bw - pad;
// Arrow / dot / ring.
var mid = new Vector2(p.X + arrowW * 0.5f, line1 + bold.FontSize * 0.5f + Px(1));
uint arrowCol = Fade(StateColor(r), dim);
if (!r.IsSelf && r.Measured && haveHeading && !float.IsNaN(r.Bearing))
DrawArrow(dl, mid, r.Bearing - heading, arrowCol, _k);
else if (r.IsSelf || r.Measured)
dl.AddCircleFilled(mid, Px(2.5f), arrowCol);
else
dl.AddCircle(mid, Px(3.5f), Faded(Mute), 12, Px(1.2f));
// Right side of line 1: distance + compass (or "elsewhere").
string dist = r.IsSelf ? "" : r.Measured ? r.DistanceText + (r.Compass.Length > 0 ? " " + r.Compass : "") : r.DistanceText;
float distW = dist.Length > 0 ? ImGuiNET.ImGui.CalcTextSize(dist).X : 0;
if (dist.Length > 0)
dl.AddText(new Vector2(right - distW, line1 + (bold.FontSize - ImGuiNET.ImGui.GetFontSize()) * 0.5f),
Fade(r.Measured ? Text : Faded(Mute), dim), dist);
float limit = right - distW - (distW > 0 ? Px(8) : 0);
// Name (+ server), then state and the stale marker.
float nameW = Math.Min(CalcW(bold, r.Name), Math.Max(Px(40), (limit - x) * 0.55f));
Clip(dl, bold, r.Name, x, line1, nameW, Fade(r.IsSelf ? Mute : Text, dim));
float sx = x + nameW + Px(6);
if (r.OtherWorld.Length > 0)
{
string wtext = "[" + r.OtherWorld + "]";
float ww = Math.Min(CalcW(f10, wtext), Math.Max(0, limit - sx));
Clip(dl, f10, wtext, sx, line1 + Px(1), ww, Fade(Amber, dim));
sx += ww + Px(6);
}
if (r.StateText.Length > 0 && sx < limit)
{
float tw = Math.Min(CalcW(f10, r.StateText), limit - sx);
Clip(dl, f10, r.StateText, sx, line1 + Px(1), tw, Fade(StateColor(r), dim));
sx += tw + Px(6);
}
if (r.Stale && sx < limit)
{
string st = PhosphorIcons.Warning + " " + r.StaleText;
Clip(dl, f10, st, sx, line1 + Px(1), limit - sx, Amber);
}
// Line 2: bars, then the location.
float line2 = line1 + bold.FontSize + Px(4);
float barH = Px(13);
float locW = r.Location.Length > 0 ? Math.Min(CalcW(f10, r.Location), Math.Max(Px(70), bw * 0.32f)) : 0;
float barsW = right - x - (locW > 0 ? locW + Px(8) : 0);
if (barsW < Px(150)) { barsW = right - x; locW = 0; } // narrow: bars first, the tooltip has the place
if (r.HasVitals)
{
float gap = Px(3);
float one = (barsW - 2 * gap) / 3f;
Bar(dl, x, line2, one, barH, r.Hp, HpCol, f10, dim);
Bar(dl, x + one + gap, line2, one, barH, r.St, StCol, f10, dim);
Bar(dl, x + 2 * (one + gap), line2, one, barH, r.Mp, MpCol, f10, dim);
}
else if (!r.LoggedOut)
{
Clip(dl, f10, "no vitals yet", x, line2, barsW, Faded(Mute));
}
if (locW > 0)
Clip(dl, f10, r.Location, right - locW, line2 + (barH - f10.FontSize) * 0.5f, locW, Fade(Mute, dim));
}
private void Bar(ImDrawListPtr dl, float x, float y, float w, float h, CharVital v, uint color, ImFontPtr font, float dim)
{
if (w <= 2) return;
var a = new Vector2(x, y);
var b = new Vector2(x + w, y + h);
float round = Px(3);
dl.AddRectFilled(a, b, BarBg, round);
if (v.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * v.Fraction, b.Y), Fade(color, dim), round);
float tw = CalcW(font, v.Text);
float tx = x + Math.Max(Px(3), (w - tw) * 0.5f);
dl.PushClipRect(a, b, true);
dl.AddText(font, font.FontSize, new Vector2(tx, y + (h - font.FontSize) * 0.5f), Fade(White, dim), v.Text);
dl.PopClipRect();
}
private static uint StateColor(CharacterRow r) => r.StateKind switch
{
_ when r.IsSelf => Mute,
CharStateKind.Dead => Red,
CharStateKind.Fighting => Amber,
CharStateKind.Botting => Green,
CharStateKind.Portal => Purple,
CharStateKind.CombatMode => Teal,
CharStateKind.NoStatus or CharStateKind.LoggedOut => Faded(Mute),
_ => Mute,
};
private static float CalcW(ImFontPtr font, string text) =>
text.Length == 0 ? 0 : font.CalcTextSizeA(font.FontSize, float.MaxValue, 0f, text).X;
private static void Clip(ImDrawListPtr dl, ImFontPtr font, string text, float x, float y, float width, uint color)
{
if (text.Length == 0 || width <= 0) return;
dl.PushClipRect(new Vector2(x, y - 2), new Vector2(x + width, y + font.FontSize + 4), true);
dl.AddText(font, font.FontSize, new Vector2(x, y), color, text);
dl.PopClipRect();
}
private static uint Fade(uint abgr, float k)
{
if (k >= 1f) return abgr;
uint a = (uint)Math.Clamp((int)(((abgr >> 24) & 0xFF) * k), 0, 255);
return (abgr & 0x00FFFFFF) | (a << 24);
}
/// <summary>An arrow pointing <paramref name="degrees"/> clockwise from straight up (up = the way you face).</summary>
private static void DrawArrow(ImDrawListPtr dl, Vector2 c, float degrees, uint color, float k)
{
float rad = degrees * (MathF.PI / 180f);
float s = MathF.Sin(rad), co = MathF.Cos(rad);
Vector2 tip = Rot(c, 0, -6.5f * k, s, co), left = Rot(c, -4.5f * k, 5f * k, s, co),
notch = Rot(c, 0, 2.5f * k, s, co), rgt = Rot(c, 4.5f * k, 5f * k, s, co);
dl.AddTriangleFilled(tip, left, notch, color);
dl.AddTriangleFilled(tip, notch, rgt, color);
}
private static Vector2 Rot(Vector2 c, float x, float y, float s, float co) =>
new(c.X + x * co - y * s, c.Y + x * s + y * co);
/// <summary>Your heading this frame (compass degrees) from the pose snapshot; no AC call (SenseFace's way).</summary>
private static float PlayerHeading(out bool ok)
{
ok = PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out _, out _, out _, out _, out float qw, out float qz,
out bool headingValid, out float heading);
if (!ok) return 0;
if (headingValid) return heading;
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
return (float)((-yaw % 360.0 + 720.0) % 360.0);
}
// ── Right-click menu ────────────────────────────────────────────────
private void OpenMenu(CharacterRow r)
{
_menuName = r.Name;
_menuId = r.Id;
_menuInView = r.InView;
_menuOtherWorld = r.OtherWorld.Length > 0;
_menuSelf = r.IsSelf;
_menuLoggedOut = r.LoggedOut;
_openMenu = true;
}
private void DrawMenu(CharactersView view)
{
if (_openMenu)
{
_openMenu = false;
ImGuiNET.ImGui.OpenPopup("##chars_menu");
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(6)));
bool open = ImGuiNET.ImGui.BeginPopup("##chars_menu");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(3);
if (!open) return;
try
{
string me = view.MyName;
bool canFollow = me.Length > 0;
if (!_menuSelf && !_menuLoggedOut)
{
ImGuiNET.ImGui.TextDisabled(_menuName);
if (ImGuiNET.ImGui.MenuItem("Select", "", false, _menuInView && _menuId != 0))
AcMainThreadQueue.EnqueueOverlaySelect(_menuId);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Follow me", "", false, canFollow && !_menuOtherWorld))
CharactersCommands.Tell(_menuName, "/ra follow " + me);
ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow {me}");
if (ImGuiNET.ImGui.MenuItem("Stop following"))
CharactersCommands.Tell(_menuName, "/ra follow off");
ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow off");
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Start macro"))
CharactersCommands.Tell(_menuName, "/ra start");
ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra start");
if (ImGuiNET.ImGui.MenuItem("Stop macro"))
CharactersCommands.Tell(_menuName, "/ra stop");
ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra stop");
ImGuiNET.ImGui.Separator();
}
if (ImGuiNET.ImGui.MenuItem("Everyone: follow me", "", false, canFollow))
CharactersCommands.FollowMeAll();
ImGuiNET.ImGui.SetItemTooltip("/rn followme");
ImGuiNET.ImGui.TextDisabled("The other client's /rn remote setting decides.");
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
}

View file

@ -138,6 +138,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
Label("No rules yet. Click \"Add rule\", or right-click a line in the chat", Mute);
Label("and pick \"Move them to\", \"Hide them\" or \"Colour them\".", Mute);
}
DrawStandardFilters(rowW);
ImGuiNET.ImGui.PopStyleColor(2);
ImGuiNET.ImGui.EndChild();
@ -181,6 +182,58 @@ internal sealed class ChatFiltersFace : IImGuiPanel
edit?.Invoke(); // after drawing: the rows above drew from the old list
}
// ── Standard filters (RynthChatPresets) ──────────────────────────────
/// <summary>
/// The canned filters, by group: tick to hide, or pick a tab to move the lines there.
/// The router checks them after the rules, for lines no rule moved or hid.
/// </summary>
private void DrawStandardFilters(float rowW)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
if (!ImGuiNET.ImGui.CollapsingHeader("Standard filters##std")) return;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
Label("Checked after the rules above, only for lines no rule moved or hid.", Mute);
Label("Tick to hide the lines; pick a tab to move them there instead.", Mute);
ImGuiNET.ImGui.PopFont();
foreach (string group in UI.Panels.RynthChatPresets.Groups)
{
int on = 0, total = 0;
foreach (var p in UI.Panels.RynthChatPresets.All)
if (p.Group == group) { total++; if (p.Enabled) on++; }
if (!ImGuiNET.ImGui.TreeNode($"{group} ({on}/{total})###grp_{group}")) continue;
foreach (var p in UI.Panels.RynthChatPresets.All)
{
if (p.Group != group) continue;
ImGuiNET.ImGui.PushID(p.Id);
bool enabled = p.Enabled;
if (ImGuiNET.ImGui.Checkbox(p.Label, ref enabled)) { p.Enabled = enabled; ChatModel.FiltersChanged(); }
ImGuiNET.ImGui.SetItemTooltip(p.Description + "\nExample: " + p.Example);
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, rowW * 0.6f));
string tabText = (p.Tab.Length == 0 ? "hide" : "to " + p.Tab) + Caret;
if (ImGuiNET.ImGui.SmallButton(tabText))
OpenPresetTabPicker(p, new Vector2(ImGuiNET.ImGui.GetItemRectMin().X, ImGuiNET.ImGui.GetItemRectMax().Y + 2));
ImGuiNET.ImGui.SetItemTooltip("Where its lines go: hidden, or moved to a tab");
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.TreePop();
}
}
private void OpenPresetTabPicker(UI.Panels.RynthChatPresets.Preset preset, Vector2 below)
{
string[] tabs = ChatModel.TargetTabs();
var items = new string[tabs.Length + 1];
items[0] = "Hide";
Array.Copy(tabs, 0, items, 1, tabs.Length);
int selected = preset.Tab.Length == 0 ? 0 : Math.Max(0, Array.FindIndex(tabs, t => string.Equals(t, preset.Tab, StringComparison.OrdinalIgnoreCase)) + 1);
_picker.Open(below, items, selected, k =>
{
preset.Tab = k <= 0 ? "" : items[k];
ChatModel.FiltersChanged();
}, 160);
}
private void Flash(string message)
{
_flash = message;
@ -548,7 +601,12 @@ internal sealed class ChatFiltersFace : IImGuiPanel
var trace = new List<ChatRouter.Step>();
ChatRoute route = ChatModel.TestRouter().Evaluate(text, channel, type, trace);
foreach (ChatRouter.Step step in trace)
_testResult.Add(((step.Rule < 0 ? "Your name" : $"Rule {step.Rule + 1}") + ": " + step.What, Text));
_testResult.Add((step.Rule switch
{
ChatRouter.StandardFilterStep => "Standard",
< 0 => "Your name",
_ => $"Rule {step.Rule + 1}",
} + ": " + step.What, Text));
if (trace.Count == 0) _testResult.Add(("No rule matches.", Faded(Mute)));
string where;

View file

@ -10,8 +10,8 @@
//
// The mechanics live here (tabs, slide, side, placement, the one window);
// each drawer only draws its panel (DashboardDrawer.DrawPanel) and says how
// big it is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files and
// Patrol (RynthAiFace.Drawers.cs).
// big it is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files,
// Patrol and Mini Remote (RynthAiFace.Drawers.cs).
//
// A top-level ImGui window of its own, begun from inside the dashboard's Draw
// and placed against the dashboard's window every frame, so it follows the

View file

@ -23,6 +23,28 @@
// Settings are the engine's (dungeon_map_settings.txt beside radar_settings.txt),
// not RynthAi's per-character Map* fields. Zoom, pan and floor picks last for the
// session, as they did.
//
// RynthAi's nav route (2026-10-12; UiSources.Nav, subscribed only while the map is
// open and its Route box is on): legs between the points (closed for Circular,
// dashed after a Recall / Portal step, which jumps), points as dots and the other
// step types as icon badges, the next waypoint ringed, numbers when zoomed in, a
// tooltip on hover. A point's floor is the layer nearest its Z (nav Z * 240); points
// on floors the map isn't showing are hidden, on shown other floors dimmed, like the
// walls. Points outside this dungeon's floor area aren't drawn.
//
// "Edit route" (off by default; needs RynthAi with MapEdit >= 1):
// - click (no drag) on a floor: add a point there (after the selected point, else
// at the end; Z from that floor: the player's floor first, then the other shown
// floors nearest it). Off every shown floor: refused with a status line;
// - click a point: select / deselect it; Esc deselects;
// - drag a point: move it (it follows the cursor; one move on release; Esc or
// right-click cancels; a drop off every floor leaves it where it was);
// - drag empty space: pans as always; the wheel zooms;
// - right-click a point: Delete / Insert after / Set as next target.
// Every edit is a RynthAi nav command (addPointAt, movePointTo, deletePoint,
// setActive); the route file stays RynthAi's and the map shows the next poll.
// Coordinates: DungeonMapMath (screen <-> world through pan and rotation, world <->
// nav).
// ============================================================================
using System;
@ -44,7 +66,7 @@ internal sealed class DungeonMapFace : IImGuiPanel
{
DungeonMapSettingsStore.Load(); // engine init thread: the file read stays off AC's thread
ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true),
new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true, OpenCentered: true),
() => new DungeonMapFace());
}
@ -57,6 +79,10 @@ internal sealed class DungeonMapFace : IImGuiPanel
CreatureLabel = C(0xFFFFE6E6), Hint = C(0xFF8FA3B8), ButtonBg = C(0xC0141F29), ButtonBorder = C(0xFF34587A),
FloorOn = C(0xFF2673B3), FloorHere = C(0xFF1AA64D);
private const uint FillFlat = 0x662E8C38, FillUp = 0x668C1F14, FillDown = 0x661A8026, FillVisited = 0xB84D6B94;
// Route (ARGB, alpha scaled per floor).
private const uint RouteLegArgb = 0xD9FFA733, RoutePointArgb = 0xFFFFC266, RouteActiveArgb = 0xFFFFF04D,
RouteSelectedArgb = 0xFFFFFFFF, RouteBadgeBgArgb = 0xE00A121F, RouteNumberArgb = 0xFFFFE6B3,
RouteBadArgb = 0xFFFF4D4D, StatusArgb = 0xFFFFD27A;
private static uint C(uint argb) => RynthTheme.Argb(argb);
/// <summary>ARGB colour with its alpha scaled, as an ImGui colour.</summary>
@ -76,6 +102,37 @@ internal sealed class DungeonMapFace : IImGuiPanel
private uint _landblock;
private int[] _drawOrder = Array.Empty<int>();
// ── Route state (per open) ───────────────────────────────────────────
private const float NumberZoom = 6f; // point numbers from this zoom up
private const float PickRadius = 8f; // px: a press this close to a point grabs it
private const long StatusMs = 4000;
private bool _navSubscribed;
private bool _editRoute;
private int _selected = -1; // route index the next added point goes after
private int _hoverPt = -1;
private readonly List<(int Idx, Vector2 At)> _drawn = new(); // this frame's drawn points, for picking
private Vector2[] _ptScreen = Array.Empty<Vector2>();
private float[] _ptAlpha = Array.Empty<float>();
private int[] _ptLayer = Array.Empty<int>();
private bool _pressing; // left button went down on the canvas
private int _pressPt = -1; // the point under that press (Edit route)
private bool _pressMoved; // the press turned into a drag
private int _dragPt = -1; // the point being dragged
private Vector2 _dragWorld;
private bool _dragOnFloor;
private int _pendingMoveIdx = -1; // a sent move, drawn there until the route updates
private Vector2 _pendingMoveWorld;
private object? _pendingMoveFrom;
private long _pendingMoveUntil;
private bool _openPtMenu;
private int _menuPt = -1;
private string _status = string.Empty;
private long _statusUntil;
private object? _boundsFor;
private bool _haveBounds;
private Vector4 _bounds;
private int[] _layerOrder = new int[16];
public int PopOutIdleHz => 20; // markers move
public bool HiddenWhileDocked
@ -94,22 +151,42 @@ internal sealed class DungeonMapFace : IImGuiPanel
UiSources.Radar.RequestRefresh();
}
public void OnHidden() => UiSources.Radar.Unsubscribe();
public void OnHidden()
{
UiSources.Radar.Unsubscribe();
SyncNavSubscription(false);
CancelPress();
}
/// <summary>The route source is polled only while the map is open with Route on.</summary>
private void SyncNavSubscription(bool want)
{
if (want == _navSubscribed) return;
_navSubscribed = want;
if (want)
{
UiSources.Nav.Subscribe();
UiSources.Nav.RequestRefresh();
}
else UiSources.Nav.Unsubscribe();
}
public void Draw()
{
SyncNavSubscription(DungeonMapSettingsStore.ShowRoute);
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
if (size.X < 16 || size.Y < 16) return;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
RadarView? view = UiSources.Radar.Current?.Value;
NavPayload? nav = DungeonMapSettingsStore.ShowRoute ? UiSources.Nav.Current?.Value : null;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
try
{
if (view == null) { Message(dl, origin, size, "Waiting for map data from RynthAi..."); return; }
if (view == null) { CancelPress(); Message(dl, origin, size, "Waiting for map data from RynthAi..."); return; }
RadarSnapshot live = view.Live;
if (!live.IsIndoor) { Message(dl, origin, size, "Outdoors: the map shows while you're in a dungeon."); return; }
if (!live.IsIndoor) { CancelPress(); Message(dl, origin, size, "Outdoors: the map shows while you're in a dungeon."); return; }
int layers = live.LayerZs.Count;
TrackLayers(view, live.Player.Landblock, layers);
@ -132,6 +209,9 @@ internal sealed class DungeonMapFace : IImGuiPanel
if (_follow) _pan = Vector2.Zero;
Vector2 centre = (canvasMin + canvasMax) * 0.5f + _pan;
DungeonMapProjection? proj = null;
bool routeDrawn = false;
_drawn.Clear();
if (layers == 0)
DrawCentredText(dl, (canvasMin + canvasMax) * 0.5f, Hint,
$"Loading dungeon geometry for {live.Player.Landblock:X4}...");
@ -140,11 +220,15 @@ internal sealed class DungeonMapFace : IImGuiPanel
ImDrawListFlags saved = dl.Flags;
dl.Flags = saved & ~(ImDrawListFlags.AntiAliasedLines | ImDrawListFlags.AntiAliasedLinesUseTex | ImDrawListFlags.AntiAliasedFill);
dl.PushClipRect(canvasMin, canvasMax, true);
var proj = new Projection(centre, live.Player, DungeonMapSettingsStore.RotateWithPlayer, _zoom);
DrawFloors(dl, view, proj, canvasMin, canvasMax);
var p = new DungeonMapProjection(centre, live.Player.WorldX, live.Player.WorldY, live.Player.Heading,
DungeonMapSettingsStore.RotateWithPlayer, _zoom);
proj = p;
DrawFloors(dl, view, p, canvasMin, canvasMax);
dl.Flags = saved;
DrawMarkers(dl, live, proj, canvasMin, canvasMax);
DrawPlayer(dl, centre, proj);
if (nav != null) routeDrawn = DrawRoute(dl, view, nav, p, canvasMin, canvasMax);
DrawMarkers(dl, live, p, canvasMin, canvasMax);
DrawPlayer(dl, centre, p);
DrawRouteStatus(dl, canvasMin, canvasMax, nav, routeDrawn);
dl.PopClipRect();
}
@ -159,7 +243,8 @@ internal sealed class DungeonMapFace : IImGuiPanel
ImGuiNET.ImGui.SetItemTooltip("Show the map settings");
}
CanvasInput(canvasMin, canvasMax);
CanvasInput(canvasMin, canvasMax, view, nav, proj);
DrawPointMenu(nav);
}
finally
{
@ -195,7 +280,7 @@ internal sealed class DungeonMapFace : IImGuiPanel
if (_autoLayer < layers - 1) _visible.Add(_autoLayer + 1);
}
private void DrawFloors(ImDrawListPtr dl, RadarView view, in Projection proj, Vector2 clipMin, Vector2 clipMax)
private void DrawFloors(ImDrawListPtr dl, RadarView view, in DungeonMapProjection proj, Vector2 clipMin, Vector2 clipMax)
{
int layers = view.Live.LayerZs.Count;
int cur = view.CurrentLayer;
@ -248,7 +333,7 @@ internal sealed class DungeonMapFace : IImGuiPanel
}
}
private static void FillRect(ImDrawListPtr dl, in Projection proj, float x0, float y0, float x1, float y1,
private static void FillRect(ImDrawListPtr dl, in DungeonMapProjection proj, float x0, float y0, float x1, float y1,
uint col, Vector2 clipMin, Vector2 clipMax)
{
Vector2 p00 = proj.P(x0, y0), p11 = proj.P(x1, y1);
@ -273,14 +358,15 @@ internal sealed class DungeonMapFace : IImGuiPanel
// ── Markers and player ────────────────────────────────────────────────
private static void DrawMarkers(ImDrawListPtr dl, RadarSnapshot live, in Projection proj, Vector2 clipMin, Vector2 clipMax)
private static void DrawMarkers(ImDrawListPtr dl, RadarSnapshot live, in DungeonMapProjection proj, Vector2 clipMin, Vector2 clipMax)
{
const float Margin = 20f;
bool doors = DungeonMapSettingsStore.ShowDoors, creatures = DungeonMapSettingsStore.ShowCreatures;
bool doors = DungeonMapSettingsStore.ShowDoors, creatures = DungeonMapSettingsStore.ShowCreatures,
corpses = DungeonMapSettingsStore.ShowCorpses;
RadarMarkerStyle.FillColors(KindCols);
foreach (RadarMarker m in live.Markers)
{
if (!ShowOnMap(m.Kind, doors, creatures)) continue;
if (!ShowOnMap(m.Kind, doors, creatures, corpses)) continue;
Vector2 p = proj.P(m.X, m.Y);
if (p.X < clipMin.X - Margin || p.X > clipMax.X + Margin || p.Y < clipMin.Y - Margin || p.Y > clipMax.Y + Margin) continue;
switch (m.Kind)
@ -322,15 +408,17 @@ internal sealed class DungeonMapFace : IImGuiPanel
/// Portals always; doors with the map's Doors box; monsters and NPCs with its Creatures box.
/// The kinds added 2026-10-04 also follow the radar's show box for that kind (so items on the
/// ground stay off unless turned on there): players, fellows, pets and vendors with Creatures,
/// corpses, lifestones and ground items on the radar's box alone. Unknown kinds: hidden.
/// corpses (both kinds) with the map's Corpses box too (2026-10-12: off hides them here whatever
/// the radar says), lifestones and ground items on the radar's box alone. Unknown kinds: hidden.
/// </summary>
private static bool ShowOnMap(byte kind, bool doors, bool creatures) => kind switch
private static bool ShowOnMap(byte kind, bool doors, bool creatures, bool corpses) => kind switch
{
RadarKind.Portal => true,
RadarKind.Door => doors,
RadarKind.Monster or RadarKind.Npc => creatures,
RadarKind.Player or RadarKind.Fellow or RadarKind.Pet or RadarKind.Vendor =>
creatures && UI.Panels.RadarSettingsStore.ShowKind(kind),
RadarKind.Corpse or RadarKind.OwnCorpse => corpses && UI.Panels.RadarSettingsStore.ShowKind(kind),
_ => UI.Panels.RadarSettingsStore.ShowKind(kind),
};
@ -341,7 +429,7 @@ internal sealed class DungeonMapFace : IImGuiPanel
dl.AddText(pos, col, text);
}
private static void DrawPlayer(ImDrawListPtr dl, Vector2 at, in Projection proj)
private static void DrawPlayer(ImDrawListPtr dl, Vector2 at, in DungeonMapProjection proj)
{
dl.AddCircleFilled(at, 4f, PlayerCol, 10);
// Rotating: facing is always up. North-up: AC heading 0 = east, 90 = north.
@ -349,57 +437,473 @@ internal sealed class DungeonMapFace : IImGuiPanel
dl.AddLine(at, tip, PlayerCol, 1.5f);
}
/// <summary>World (AC x east, y north) to screen around the player, north-up or rotated so facing is up.</summary>
private readonly struct Projection
// ── Route ─────────────────────────────────────────────────────────────
/// <summary>
/// Draws the route's legs and points over the floors. Fills <see cref="_drawn"/> with the
/// points drawn (for hover and clicks). Returns true when at least one point was drawn.
/// </summary>
private bool DrawRoute(ImDrawListPtr dl, RadarView view, NavPayload nav, in DungeonMapProjection proj, Vector2 clipMin, Vector2 clipMax)
{
private readonly float _cx, _cy, _pwx, _pwy, _sin, _cos, _zoom;
public readonly bool Rotated;
public Projection(Vector2 playerAt, RadarPlayer p, bool rotate, float zoom)
List<NavPoint> pts = nav.Points;
int n = pts.Count;
if (n == 0) return false;
if (_ptScreen.Length < n)
{
_cx = playerAt.X; _cy = playerAt.Y; _pwx = p.WorldX; _pwy = p.WorldY;
float h = p.Heading * MathF.PI / 180f;
_sin = MathF.Sin(h); _cos = MathF.Cos(h);
Rotated = rotate; _zoom = zoom;
int cap = Math.Max(n, _ptScreen.Length * 2);
_ptScreen = new Vector2[cap];
_ptAlpha = new float[cap];
_ptLayer = new int[cap];
}
UpdateBounds(view);
List<float> layerZs = view.Live.LayerZs;
int cur = view.CurrentLayer;
bool pending = _pendingMoveIdx >= 0 && ReferenceEquals(nav, _pendingMoveFrom) && Environment.TickCount64 < _pendingMoveUntil;
if (!pending) _pendingMoveIdx = -1;
const float BoundsMargin = 24f;
public float Sin => _sin;
public float Cos => _cos;
public Vector2 P(float wx, float wy)
// Where each point is and how strongly it's drawn (0 = not at all).
for (int i = 0; i < n; i++)
{
float dx = wx - _pwx, dy = wy - _pwy;
if (Rotated)
NavPoint p = pts[i];
Vector2 w;
bool dragged = i == _dragPt && _pressMoved;
if (dragged) w = _dragWorld;
else if (pending && i == _pendingMoveIdx) w = _pendingMoveWorld;
else w = DungeonMapMath.NavToWorld(p.NS, p.EW);
_ptScreen[i] = proj.P(w.X, w.Y);
float a = 0f;
int layer = -1;
bool inside = _haveBounds && w.X >= _bounds.X - BoundsMargin && w.X <= _bounds.Z + BoundsMargin
&& w.Y >= _bounds.Y - BoundsMargin && w.Y <= _bounds.W + BoundsMargin;
if (inside)
{
float right = _sin * dx - _cos * dy;
float forward = _cos * dx + _sin * dy;
return new Vector2(_cx + right * _zoom, _cy - forward * _zoom);
layer = DungeonMapMath.NearestLayer(layerZs, DungeonMapMath.NavZToWorld(p.Z));
if (layer >= 0 && _visible.Contains(layer)) a = layer == cur ? 1f : DimOtherFloors;
}
return new Vector2(_cx + dx * _zoom, _cy - dy * _zoom);
if (dragged) a = 1f;
_ptAlpha[i] = a;
_ptLayer[i] = layer;
}
// Legs: point to point, back to the start on a Circular route.
bool closed = nav.RouteType == 1 && n > 2;
int legs = closed ? n : n - 1;
for (int k = 0; k < legs; k++)
{
int ia = k, ib = (k + 1) % n;
float a = MathF.Min(_ptAlpha[ia], _ptAlpha[ib]);
if (a <= 0f) continue;
Vector2 pa = _ptScreen[ia], pb = _ptScreen[ib];
if (MathF.Max(pa.X, pb.X) < clipMin.X || MathF.Min(pa.X, pb.X) > clipMax.X ||
MathF.Max(pa.Y, pb.Y) < clipMin.Y || MathF.Min(pa.Y, pb.Y) > clipMax.Y) continue;
uint col = MulAlpha(RouteLegArgb, a);
float thick = ib == nav.ActiveNavIndex ? 2.5f : 1.5f;
if (IsJumpStep(pts[ia].Type)) DashedLine(dl, pa, pb, col, thick); // a recall / portal: no walk
else dl.AddLine(pa, pb, col, thick);
LegArrow(dl, pa, pb, col);
}
// Points, the dragged one last (on top).
ImFontPtr font = ImGuiNET.ImGui.GetFont();
bool numbers = _zoom >= NumberZoom;
int drawnCount = 0;
for (int pass = 0; pass < 2; pass++)
{
for (int i = 0; i < n; i++)
{
bool top = i == _dragPt && _pressMoved;
if ((pass == 1) != top) continue;
float a = _ptAlpha[i];
if (a <= 0f) continue;
Vector2 at = _ptScreen[i];
if (at.X < clipMin.X - 12 || at.X > clipMax.X + 12 || at.Y < clipMin.Y - 12 || at.Y > clipMax.Y + 12) continue;
DrawRoutePoint(dl, font, pts[i].Type, at, a, i == nav.ActiveNavIndex, i == _selected, i == _hoverPt);
if (top && !_dragOnFloor) dl.AddCircle(at, 9f, RynthTheme.Argb(RouteBadArgb), 16, 2f);
if (numbers) dl.AddText(at + new Vector2(7, -15), MulAlpha(RouteNumberArgb, a), NumberLabel(i));
_drawn.Add((i, at));
drawnCount++;
}
}
return drawnCount > 0;
}
/// <summary>A Recall or Portal step: the leg after it is a jump, not a walk (drawn dashed).</summary>
private static bool IsJumpStep(string type) => type is "Recall" or "PortalNPC";
private static void DrawRoutePoint(ImDrawListPtr dl, ImFontPtr font, string type, Vector2 at, float a,
bool active, bool selected, bool hovered)
{
if (active) dl.AddCircle(at, 9.5f, MulAlpha(RouteActiveArgb, a), 18, 2f);
if (selected) dl.AddCircle(at, 12.5f, MulAlpha(RouteSelectedArgb, a), 20, 1.5f);
string? glyph = TypeGlyph(type);
if (glyph == null)
{
// Point / Checkpoint (walked to).
dl.AddCircleFilled(at, hovered ? 4.5f : 3.5f, MulAlpha(RoutePointArgb, a), 10);
if (type == "Checkpoint") dl.AddCircle(at, 6f, MulAlpha(RoutePointArgb, a), 12, 1.2f);
return;
}
const float r = 7f;
uint col = MulAlpha(TypeColour(type), a);
dl.AddCircleFilled(at, hovered ? r + 1 : r, MulAlpha(RouteBadgeBgArgb, a), 14);
dl.AddCircle(at, hovered ? r + 1 : r, col, 14, 1.3f);
PhosphorIcons.DrawCentered(dl, font, 10f, glyph, at - new Vector2(r, r), new Vector2(2 * r, 2 * r), col);
}
/// <summary>The badge icon for a step type that isn't simply walked to (RynthAi's NavPointType names).</summary>
private static string? TypeGlyph(string type) => type switch
{
"Point" or "Checkpoint" or "" => null,
"Recall" => PhosphorIcons.ArrowCounterClockwise,
"Pause" => PhosphorIcons.HourglassMedium,
"Chat" => PhosphorIcons.ChatCircleText,
"PortalNPC" => PhosphorIcons.Spiral,
"Npc" => PhosphorIcons.User,
"OpenVendor" => PhosphorIcons.Storefront,
"Jump" => PhosphorIcons.ArrowCircleUp,
_ => PhosphorIcons.Info,
};
private static uint TypeColour(string type) => type switch
{
"Recall" => 0xFF8CB3FF,
"Pause" => 0xFFE6E6E6,
"Chat" => 0xFF8CFFB3,
"PortalNPC" => 0xFFE673FF,
"Npc" => 0xFFFFD933,
"OpenVendor" => 0xFFFFB366,
"Jump" => 0xFF66E6FF,
_ => 0xFFB0B0B0,
};
/// <summary>"Portal" for PortalNPC and so on, for the tooltip.</summary>
private static string TypeName(string type) => type switch
{
"PortalNPC" => "Portal",
"Npc" => "NPC",
"OpenVendor" => "Vendor",
"" => "Point",
_ => type,
};
private static void DashedLine(ImDrawListPtr dl, Vector2 a, Vector2 b, uint col, float thick)
{
float len = Vector2.Distance(a, b);
if (len < 1f) return;
if (len > 4000f) { dl.AddLine(a, b, col, thick); return; }
Vector2 d = (b - a) / len;
const float On = 5f, Off = 4f;
for (float t = 0; t < len; t += On + Off)
dl.AddLine(a + d * t, a + d * MathF.Min(t + On, len), col, thick);
}
/// <summary>A small arrowhead at the middle of a leg that's long enough, pointing the way the route goes.</summary>
private static void LegArrow(ImDrawListPtr dl, Vector2 a, Vector2 b, uint col)
{
float len = Vector2.Distance(a, b);
if (len < 48f || len > 8000f) return;
Vector2 d = (b - a) / len, nrm = new(-d.Y, d.X);
Vector2 tip = (a + b) * 0.5f + d * 4f;
dl.AddTriangleFilled(tip, tip - d * 7f + nrm * 4f, tip - d * 7f - nrm * 4f, col);
}
private static readonly List<string> NumberLabels = new();
private static string NumberLabel(int i)
{
while (NumberLabels.Count <= i) NumberLabels.Add(NumberLabels.Count.ToString(CultureInfo.InvariantCulture));
return NumberLabels[i];
}
/// <summary>The floors' bounding box (cached per geometry): route points outside it aren't in this dungeon.</summary>
private void UpdateBounds(RadarView view)
{
if (ReferenceEquals(_boundsFor, view.Fills)) return;
_boundsFor = view.Fills;
_haveBounds = DungeonMapMath.FillBounds(view.FillsByLayer, out _bounds);
}
/// <summary>The floor (layer index) under a world spot, among the floors shown: the player's first.</summary>
private int FloorUnder(RadarView view, Vector2 world)
{
int layers = view.Live.LayerZs.Count;
if (_layerOrder.Length < layers) _layerOrder = new int[layers];
int n = DungeonMapMath.LayerOrder(view.CurrentLayer, _visible, layers, _layerOrder);
return DungeonMapMath.FloorAt(world.X, world.Y, view.FillsByLayer, _layerOrder.AsSpan(0, n));
}
/// <summary>Status line (bottom left of the canvas): the last edit's result, and in Edit route the controls.</summary>
private void DrawRouteStatus(ImDrawListPtr dl, Vector2 canvasMin, Vector2 canvasMax, NavPayload? nav, bool routeDrawn)
{
float y = canvasMax.Y - 18f;
float x = canvasMin.X + 6f;
if (_editRoute)
{
string hint = _selected >= 0
? $"Edit route: click a floor to add after {_selected} | drag a point to move | right-click a point | Esc deselects"
: "Edit route: click a floor to add at the end | click a point to select | drag to move | right-click a point";
dl.AddText(new Vector2(x, y), Hint, hint);
y -= 16f;
}
else if (DungeonMapSettingsStore.ShowRoute && nav != null && nav.Points.Count > 0 && !routeDrawn)
{
dl.AddText(new Vector2(x, y), Hint, $"Route ({nav.Points.Count} points): none on the floors shown");
y -= 16f;
}
if (_status.Length > 0 && Environment.TickCount64 < _statusUntil)
dl.AddText(new Vector2(x, y), RynthTheme.Argb(StatusArgb), _status);
}
private void SetStatus(string text)
{
_status = text;
_statusUntil = Environment.TickCount64 + StatusMs;
}
/// <summary>Edit route can be turned on: RynthAi has the map commands (or hasn't answered yet).</summary>
private bool TryStartEditing()
{
NavPayload? nav = UiSources.Nav.Current?.Value;
if (nav != null && nav.MapEdit < 1)
{
SetStatus("Editing the route on the map needs a newer RynthAi.");
return false;
}
_editRoute = true;
return true;
}
private void StopEditing()
{
_editRoute = false;
_selected = -1;
CancelPress();
}
private void CancelPress()
{
_pressing = false;
_pressPt = -1;
_pressMoved = false;
_dragPt = -1;
}
// ── Canvas input ──────────────────────────────────────────────────────
private void CanvasInput(Vector2 canvasMin, Vector2 canvasMax)
/// <summary>
/// Drag pans (and turns Follow off), the wheel zooms. Edit route: a press on a point and a drag
/// moves it; a click on a point selects it; a click on a floor adds a point; a drag from empty
/// space still pans; right-click a point for its menu.
/// </summary>
private void CanvasInput(Vector2 canvasMin, Vector2 canvasMax, RadarView view, NavPayload? nav, DungeonMapProjection? proj)
{
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
ImGuiNET.ImGui.SetCursorScreenPos(canvasMin);
ImGuiNET.ImGui.InvisibleButton("##dmap_canvas", Vector2.Max(canvasMax - canvasMin, new Vector2(1, 1)));
if (ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left))
ImGuiNET.ImGui.InvisibleButton("##dmap_canvas", Vector2.Max(canvasMax - canvasMin, new Vector2(1, 1)),
ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
bool hovered = ImGuiNET.ImGui.IsItemHovered();
Vector2 mouse = io.MousePos;
bool canEdit = _editRoute && nav != null && nav.MapEdit >= 1 && proj.HasValue;
int count = nav?.Points.Count ?? 0;
if (_selected >= count) _selected = -1;
_hoverPt = (hovered || _pressing) && _drawn.Count > 0 ? DungeonMapMath.Pick(mouse, _drawn, PickRadius) : -1;
// Press.
if (hovered && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
Vector2 delta = ImGuiNET.ImGui.GetIO().MouseDelta;
if (float.IsFinite(delta.X) && float.IsFinite(delta.Y) && delta != Vector2.Zero)
_pressing = true;
_pressMoved = false;
_pressPt = canEdit ? _hoverPt : -1;
_dragPt = -1;
}
// Drag: a point (Edit route, press on a point) or the map.
if (_pressing && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left))
{
_pressMoved = true;
if (_pressPt >= 0)
{
_follow = false;
_pan += delta;
if (canEdit && _pressPt < count)
{
_dragPt = _pressPt;
_dragWorld = proj!.Value.World(mouse);
_dragOnFloor = FloorUnder(view, _dragWorld) >= 0;
}
}
else
{
Vector2 delta = io.MouseDelta;
if (float.IsFinite(delta.X) && float.IsFinite(delta.Y) && delta != Vector2.Zero)
{
_follow = false;
_pan += delta;
}
}
}
if (ImGuiNET.ImGui.IsItemHovered())
// Cancel a point drag: Esc or the right button. Esc with nothing dragged deselects.
bool rightClicked = hovered && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right);
bool esc = ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape, false);
if (_pressing && _pressPt >= 0 && (esc || rightClicked))
{
float wheel = ImGuiNET.ImGui.GetIO().MouseWheel;
if (_dragPt >= 0) SetStatus("Move cancelled.");
CancelPress();
rightClicked = false;
}
else if (esc && canEdit && _selected >= 0 && ImGuiNET.ImGui.IsWindowFocused(ImGuiFocusedFlags.RootAndChildWindows))
_selected = -1;
// Release.
if (_pressing && ImGuiNET.ImGui.IsMouseReleased(ImGuiMouseButton.Left))
{
if (canEdit)
{
if (_pressMoved)
{
if (_dragPt >= 0) CommitMove(view, nav!, _dragPt, _dragWorld);
}
else if (_pressPt >= 0) _selected = _selected == _pressPt ? -1 : _pressPt;
else if (hovered) AddPointAt(view, nav!, proj!.Value.World(mouse));
}
else if (_editRoute && !_pressMoved && hovered)
SetStatus(nav == null ? "Waiting for the route from RynthAi..." : "Editing the route on the map needs a newer RynthAi.");
CancelPress();
}
if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && _pressing) CancelPress(); // released elsewhere
// Right-click a point: its menu.
if (rightClicked && canEdit && _hoverPt >= 0)
{
_menuPt = _hoverPt;
_openPtMenu = true;
}
if (hovered)
{
float wheel = io.MouseWheel;
if (float.IsFinite(wheel) && wheel != 0f)
_zoom = Math.Clamp(_zoom + wheel * 0.5f, MinZoom, MaxZoom);
}
if (hovered && _hoverPt >= 0 && _dragPt < 0 && nav != null && _hoverPt < count && !ImGuiNET.ImGui.IsPopupOpen("##dmap_ptmenu"))
PointTooltip(nav, _hoverPt, view);
}
private void AddPointAt(RadarView view, NavPayload nav, Vector2 world)
{
int layer = FloorUnder(view, world);
if (layer < 0)
{
SetStatus("Not on a floor: click inside a room or corridor (on a floor that's shown).");
return;
}
float z = view.Live.LayerZs[layer];
int after = _selected;
NavCommands.Send(new NavCmd
{
Cmd = "addPointAt",
NS = DungeonMapMath.WorldToNav(world.Y),
EW = DungeonMapMath.WorldToNav(world.X),
Z = DungeonMapMath.WorldZToNav(z),
AddMode = after >= 0 ? 2 : 0,
InsertAt = after,
});
if (after >= 0)
{
SetStatus($"Added point {after + 1} after {after} ({FloorName(layer)}).");
_selected = after + 1; // the next click goes after the new one
}
else SetStatus($"Added point {nav.Points.Count} at the end ({FloorName(layer)}).");
}
private void CommitMove(RadarView view, NavPayload nav, int idx, Vector2 world)
{
if (idx < 0 || idx >= nav.Points.Count) return;
int layer = FloorUnder(view, world);
if (layer < 0)
{
SetStatus($"Dropped off the floor: point {idx} not moved.");
return;
}
NavCommands.Send(new NavCmd
{
Cmd = "movePointTo",
Index = idx,
NS = DungeonMapMath.WorldToNav(world.Y),
EW = DungeonMapMath.WorldToNav(world.X),
Z = DungeonMapMath.WorldZToNav(view.Live.LayerZs[layer]),
});
// Keep it where it was dropped until the route comes back (or 3 s, if RynthAi refused).
_pendingMoveIdx = idx;
_pendingMoveWorld = world;
_pendingMoveFrom = nav;
_pendingMoveUntil = Environment.TickCount64 + 3000;
SetStatus($"Moved point {idx} ({FloorName(layer)}).");
}
private static string FloorName(int layer) => "F" + (layer + 1).ToString(CultureInfo.InvariantCulture);
private void PointTooltip(NavPayload nav, int i, RadarView view)
{
NavPoint p = nav.Points[i];
int layer = i < _ptLayer.Length ? _ptLayer[i] : -1;
ImGuiNET.ImGui.BeginTooltip();
ImGuiNET.ImGui.TextUnformatted($"{i} {TypeName(p.Type)}{(i == nav.ActiveNavIndex ? " (next waypoint)" : "")}");
if (!string.IsNullOrEmpty(p.Desc) && TypeGlyph(p.Type) != null) ImGuiNET.ImGui.TextUnformatted(p.Desc); // a Point's is just its coordinates
ImGuiNET.ImGui.TextUnformatted(string.Format(CultureInfo.InvariantCulture, "{0:0.000}{1} {2:0.000}{3} Z {4:0.0}{5}",
Math.Abs(p.NS), p.NS >= 0 ? "N" : "S", Math.Abs(p.EW), p.EW >= 0 ? "E" : "W",
DungeonMapMath.NavZToWorld(p.Z), layer >= 0 ? " " + FloorName(layer) : ""));
if (_editRoute)
ImGuiNET.ImGui.TextDisabled("Drag to move; click to select; right-click for more");
ImGuiNET.ImGui.EndTooltip();
}
/// <summary>Right-click menu on a route point (Edit route): Delete / Insert after / Set as next target.</summary>
private void DrawPointMenu(NavPayload? nav)
{
if (_openPtMenu)
{
_openPtMenu = false;
ImGuiNET.ImGui.OpenPopup("##dmap_ptmenu");
}
if (!ImGuiNET.ImGui.BeginPopup("##dmap_ptmenu")) return;
try
{
if (nav == null || _menuPt < 0 || _menuPt >= nav.Points.Count || !_editRoute)
{
ImGuiNET.ImGui.CloseCurrentPopup();
return;
}
int i = _menuPt;
ImGuiNET.ImGui.TextDisabled($"Point {i} {TypeName(nav.Points[i].Type)}");
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Delete"))
{
NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i });
if (_selected == i) _selected = -1;
else if (_selected > i) _selected--;
SetStatus($"Deleted point {i}.");
}
if (ImGuiNET.ImGui.MenuItem("Insert after"))
{
_selected = i;
SetStatus($"Click a floor to add a point after {i}.");
}
if (ImGuiNET.ImGui.MenuItem("Set as next target", null, i == nav.ActiveNavIndex))
{
NavCommands.Send(new NavCmd { Cmd = "setActive", Index = i });
SetStatus($"Next waypoint: {i}.");
}
if (_selected >= 0 && ImGuiNET.ImGui.MenuItem("Clear selection"))
_selected = -1;
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
// ── Toolbar ───────────────────────────────────────────────────────────
@ -490,12 +994,34 @@ internal sealed class DungeonMapFace : IImGuiPanel
SetOneUpOneDown(layers);
}
// Doors / Creatures.
SameLineIfFits(160, limit, 12);
// Doors / Creatures / Corpses.
SameLineIfFits(230, limit, 12);
changed |= ImGuiNET.ImGui.Checkbox("Doors##dmap_doors", ref DungeonMapSettingsStore.ShowDoors);
ImGuiNET.ImGui.SameLine();
changed |= ImGuiNET.ImGui.Checkbox("Creatures##dmap_creatures", ref DungeonMapSettingsStore.ShowCreatures);
ImGuiNET.ImGui.SetItemTooltip("Monsters, NPCs, players, fellows, your pet and vendors. Players, fellows, pets, vendors, corpses, lifestones and ground items also follow their box in the Radar's settings.");
ImGuiNET.ImGui.SetItemTooltip("Monsters, NPCs, players, fellows, your pet and vendors. Players, fellows, pets and vendors also follow their box in the Radar's settings; lifestones and items on the ground follow the Radar's settings alone.");
ImGuiNET.ImGui.SameLine();
changed |= ImGuiNET.ImGui.Checkbox("Corpses##dmap_corpses", ref DungeonMapSettingsStore.ShowCorpses);
ImGuiNET.ImGui.SetItemTooltip("Corpses on the map. Off hides them here whatever the Radar shows; on, they also follow the Radar's corpse boxes.");
// Route / Edit route.
SameLineIfFits(160, limit, 12);
if (ImGuiNET.ImGui.Checkbox("Route##dmap_route", ref DungeonMapSettingsStore.ShowRoute))
{
changed = true;
if (!DungeonMapSettingsStore.ShowRoute) StopEditing();
}
ImGuiNET.ImGui.SetItemTooltip("RynthAi's nav route: legs (dashed after a recall or portal), points (numbered when zoomed in), the next waypoint ringed. Hover a point for its details.");
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.BeginDisabled(!DungeonMapSettingsStore.ShowRoute);
bool edit = _editRoute;
if (ImGuiNET.ImGui.Checkbox("Edit route##dmap_editroute", ref edit))
{
if (edit) TryStartEditing();
else StopEditing();
}
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip("Click a floor to add a point (after the selected point, else at the end). Click a point to select it; drag a point to move it (Esc cancels); right-click a point to delete it, insert after it or make it the next waypoint. Dragging empty space still pans.");
// Opacity (of the map's background).
SameLineIfFits(130, limit, 12);
@ -573,7 +1099,8 @@ internal sealed class DungeonMapFace : IImGuiPanel
/// <summary>
/// The Dungeon Map's settings (the plugin map's MapShowDoors / MapShowCreatures /
/// MapShowToolbar / MapBgOpacity / MapRotateWithPlayer, same defaults). Engine-wide,
/// MapShowToolbar / MapBgOpacity / MapRotateWithPlayer, same defaults; showCorpses and
/// showRoute added 2026-10-12, both on by default). Engine-wide,
/// in %LOCALAPPDATA%\RynthCore\dungeon_map_settings.txt, like radar_settings.txt.
/// </summary>
internal static class DungeonMapSettingsStore
@ -583,6 +1110,8 @@ internal static class DungeonMapSettingsStore
public static bool ShowDoors = true;
public static bool ShowCreatures = true;
public static bool ShowCorpses = true;
public static bool ShowRoute = true;
public static bool ShowToolbar = true;
public static float BgOpacity = 1.0f;
public static bool RotateWithPlayer;
@ -618,6 +1147,8 @@ internal static class DungeonMapSettingsStore
{
case "showDoors": ShowDoors = val == "1"; break;
case "showCreatures": ShowCreatures = val == "1"; break;
case "showCorpses": ShowCorpses = val == "1"; break;
case "showRoute": ShowRoute = val == "1"; break;
case "showToolbar": ShowToolbar = val == "1"; break;
case "rotate": RotateWithPlayer = val == "1"; break;
case "opacity":
@ -638,6 +1169,8 @@ internal static class DungeonMapSettingsStore
string text = "# RynthCore dungeon map settings - auto-generated, hand-edits OK.\n"
+ $"showDoors={(ShowDoors ? "1" : "0")}\n"
+ $"showCreatures={(ShowCreatures ? "1" : "0")}\n"
+ $"showCorpses={(ShowCorpses ? "1" : "0")}\n"
+ $"showRoute={(ShowRoute ? "1" : "0")}\n"
+ $"showToolbar={(ShowToolbar ? "1" : "0")}\n"
+ $"rotate={(RotateWithPlayer ? "1" : "0")}\n"
+ FormattableString.Invariant($"opacity={BgOpacity:0.##}\n");

View file

@ -0,0 +1,78 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/GuardianFace.cs
// Temple of Enlightenment guardians (riddle answers, Give, the phrasebook),
// drawn by RynthAi through RynthPluginRenderEmbed ("guardian"). Part of the
// ILT section: registered when RynthAi is installed, opened from the bar's ILT
// button or "/rc guardian" on Infinite Leaftide only. ImGui-only.
//
// The panel is user-sized: the plugin fills the body it is given. Until
// RynthAi can draw it (not logged in, too old for the surface, or its embed
// failed) the body says why.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Plugins;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class GuardianFace : IImGuiPanel
{
public const string Title = "Guardian";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(540, 520), new Vector2(320, 220), EdgeToEdge: true, GripInBody: true),
() => new GuardianFace());
/// <summary>The RynthAi surface for this panel (NUL-terminated for the export).</summary>
private static ReadOnlySpan<byte> Surface => "guardian\0"u8;
// Its export failed this session: say so instead of calling it every frame.
private bool _embedOff;
public void OnShown() { }
public void OnHidden() { }
public void Draw()
{
float w = Begin(out Vector2 origin, out Vector2 size);
float h = Math.Max(60f, Remaining(origin, size) - GripOverlap());
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
int result = PluginManager.EmbedFailed;
if (!_embedOff)
{
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(6, 4));
bool open = ImGuiNET.ImGui.BeginChild("##guardian_rynthai", new Vector2(w, h), ImGuiChildFlags.AlwaysUseWindowPadding,
ImGuiWindowFlags.NoBackground);
ImGuiNET.ImGui.PopStyleVar();
try
{
if (open)
{
// The plugin's widgets use the default UI font, as in its own windows.
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
try { result = PluginManager.RenderEmbed("RynthAi", Surface, ImGuiNET.ImGui.GetContentRegionAvail(), out _); }
finally { ImGuiNET.ImGui.PopFont(); }
}
else result = PluginManager.EmbedDrawn; // clipped: nothing to draw, nothing wrong
}
finally { ImGuiNET.ImGui.EndChild(); }
if (result == PluginManager.EmbedFailed) _embedOff = true;
}
if (result != PluginManager.EmbedDrawn)
{
ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(0, 4));
Label(result switch
{
PluginManager.EmbedNoPlugin => "The Guardian tools come with RynthAi; it isn't loaded.",
PluginManager.EmbedFailed => "RynthAi couldn't draw the Guardian tools (this build may be too old). See the log.",
_ => "Waiting for RynthAi (log in; ILT features turn on once the server reports them).",
}, Mute);
}
End(origin, size);
}
}

View file

@ -0,0 +1,452 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/HotkeysSettingsUi.cs
// Settings > Hotkeys: the user hotkeys editor (Hotkeys/HotkeyService.cs).
//
// A master switch, the list of bindings (key, what it does, on/off; edit,
// remove, move up/down), Add hotkey, and an editor under the list: Key is
// captured ("press a key... Esc cancels": the next combo pressed, which never
// reaches AC), Action is a dropdown of the built-ins or "Chat command" with a
// text box. The VTank-style actions follow the built-ins under their own header;
// "Meta: set state..." asks for the state (the loaded meta's states are offered,
// from UiSources.Meta while the editor shows that action). Duplicate keys and
// keys AC uses are warned about, never refused.
// Drawn by SettingsFace for the Hotkeys tab's one row, in its look.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Hotkeys;
using RynthCore.Engine.UI.Data;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class HotkeysSettingsUi
{
public const string TabName = "Hotkeys";
private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Mute = C(0xFFB8C8D8),
TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), PanelBg = C(0xFF141F29), BtnFill = C(0xFF16283A),
BtnBord = C(0xFF34587A), ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455), TabActive = C(0xFF1A2E42),
Warn = C(0xFFFFB347);
private static uint C(uint argb) => RynthTheme.Argb(argb);
private const string ChatCommandItem = "Chat command...";
// The editor: open while adding (EditIndex -1) or editing a binding.
private bool _editorOpen;
private int _editIndex = -1;
private KeyCombo _editCombo;
private string _editAction = "macro";
private string _editCommand = string.Empty;
private string _editParam = string.Empty; // an action's parameter (the meta state)
private bool _editEnabled = true;
private bool _waitingForKey;
private bool _metaSubscribed; // UiSources.Meta, for the meta state list
/// <summary>The section is no longer shown (Settings closed, another tab): a key capture stops.</summary>
public void Leave()
{
if (_waitingForKey) HotkeyService.CancelCapture();
_waitingForKey = false;
WatchMetaStates(false);
}
/// <summary>Subscribes to the meta snapshot while "Meta: set state..." is being edited (its state list).</summary>
private void WatchMetaStates(bool on)
{
if (on == _metaSubscribed) return;
_metaSubscribed = on;
if (on) { UiSources.Meta.Subscribe(); UiSources.Meta.RequestRefresh(); }
else UiSources.Meta.Unsubscribe();
}
/// <summary>Draws the section. True while a text box here has the keyboard.</summary>
public bool Draw(float w)
{
bool typing = false;
HotkeyFile file = HotkeyService.Current;
IReadOnlyList<HotkeyBinding> list = file.Bindings;
PollCapture();
MasterSwitch(file.Enabled, w);
Note("A hotkey works in game while you aren't typing (AC's chat or any text box). The key goes to the hotkey, " +
"not to AC. Saved for this PC: every client uses the same hotkeys. Also: /rc hotkey.", w);
Section("Your Hotkeys", w);
if (list.Count == 0)
Note("(No hotkeys yet. Add hotkey picks a key and what it does.)", w);
List<int> shadowed = HotkeyConflicts.Shadowed(list);
for (int i = 0; i < list.Count; i++)
{
ImGuiNET.ImGui.PushID(i);
BindingRow(list, i, shadowed.Contains(i), w);
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
if (!_editorOpen)
{
if (ImGuiNET.ImGui.Button(PhosphorIcons.Plus + " Add hotkey"))
OpenEditor(-1, null);
ImGuiNET.ImGui.SetItemTooltip("Bind a key to a built-in action or a chat command.");
}
else
{
typing = Editor(list, w);
}
return typing;
}
// ── Rows ───────────────────────────────────────────────────────────────
private static void MasterSwitch(bool on, float w)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const string label = "Hotkeys On";
float labelW = ImGuiNET.ImGui.CalcTextSize(label).X;
if (ImGuiNET.ImGui.InvisibleButton("##hk_master", new Vector2(Math.Min(w, 18 + labelW), 16)))
HotkeyService.SetMasterEnabled(!on);
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
ImGuiNET.ImGui.SetItemTooltip("Off: no hotkey fires (they're kept). Also: /rc hotkey on|off.");
dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2);
dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
// [dot] Ctrl+F1 [^][v][edit][x]
// Toggle Combat
private void BindingRow(IReadOnlyList<HotkeyBinding> list, int i, bool shadowed, float w)
{
HotkeyBinding b = list[i];
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), small = ImGuiFonts.Get(UiFont.Ui10);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
bool editingThis = _editorOpen && _editIndex == i;
float rowH = bold.FontSize + small.FontSize + 6;
if (editingThis) dl.AddRectFilled(p - new Vector2(2, 1), p + new Vector2(w, rowH), TabActive);
// Enabled dot: click to switch this hotkey on or off.
ImGuiNET.ImGui.SetCursorScreenPos(p);
if (ImGuiNET.ImGui.InvisibleButton("##on", new Vector2(14, 16)))
HotkeyService.Replace(i, b with { Enabled = !b.Enabled });
ImGuiNET.ImGui.SetItemTooltip(b.Enabled ? "On. Click to switch this hotkey off." : "Off. Click to switch this hotkey on.");
dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), b.Enabled ? ToggleOn : ToggleOff, 2);
dl.AddText(bold, bold.FontSize, p + new Vector2(18, 1), b.Enabled ? Amber : Mute, b.Combo.ToString());
string what = HotkeyActions.Describe(b);
float textRight = p.X + w - 4 * 20 - 4;
dl.PushClipRect(p + new Vector2(18, 0), new Vector2(textRight, p.Y + rowH), true);
dl.AddText(small, small.FontSize, p + new Vector2(18, bold.FontSize + 3), b.Enabled ? TextDim : Mute, what);
dl.PopClipRect();
// The full text on hover (a long chat command is clipped).
ImGuiNET.ImGui.SetCursorScreenPos(p + new Vector2(18, 0));
ImGuiNET.ImGui.InvisibleButton("##what", new Vector2(Math.Max(1, textRight - p.X - 18), rowH));
ImGuiNET.ImGui.SetItemTooltip(b.Combo + ": " + what + (b.Enabled ? "" : " (off)"));
float x = p.X + w - 4 * 20;
if (IconButton("##up", new Vector2(x, p.Y), PhosphorIcons.CaretUp, i > 0))
HotkeyService.Move(i, -1);
ImGuiNET.ImGui.SetItemTooltip("Move up. Of two hotkeys on the same key, the higher one fires.");
if (IconButton("##down", new Vector2(x + 20, p.Y), PhosphorIcons.CaretDown, i < list.Count - 1))
HotkeyService.Move(i, +1);
ImGuiNET.ImGui.SetItemTooltip("Move down.");
if (IconButton("##edit", new Vector2(x + 40, p.Y), PhosphorIcons.PencilSimple, true))
OpenEditor(i, b);
ImGuiNET.ImGui.SetItemTooltip("Edit: change the key or what it does.");
if (IconButton("##del", new Vector2(x + 60, p.Y), PhosphorIcons.Trash, true))
{
HotkeyService.RemoveAt(i);
if (_editorOpen && _editIndex == i) CloseEditor();
else if (_editorOpen && _editIndex > i) _editIndex--;
}
ImGuiNET.ImGui.SetItemTooltip("Remove this hotkey.");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + rowH));
if (shadowed && b.Enabled)
Warning($"Never fires: a hotkey higher in the list has {b.Combo}.", w);
else if (b.IsCommand && b.Command.Trim().Length == 0)
Warning("No chat command: edit it to add one.", w);
else if (HotkeyActions.Find(b.Action) is { HasParam: true } pa && b.Command.Trim().Length == 0)
Warning($"No {pa.Param!.ToLowerInvariant()}: edit it to pick one.", w);
else if (!b.IsCommand && HotkeyActions.Find(b.Action) == null)
Warning($"This engine doesn't know the action '{b.Action}'.", w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
// ── Editor ─────────────────────────────────────────────────────────────
private void OpenEditor(int index, HotkeyBinding? b)
{
if (_waitingForKey) HotkeyService.CancelCapture();
_editorOpen = true;
_editIndex = index;
_editCombo = b?.Combo ?? default;
_editAction = b?.Action ?? "macro";
bool hasParam = b != null && HotkeyActions.Find(b.Action)?.HasParam == true;
_editCommand = b != null && !hasParam ? b.Command : string.Empty;
_editParam = hasParam ? b!.Command : string.Empty;
_editEnabled = b?.Enabled ?? true;
_waitingForKey = b == null; // a new hotkey starts by asking for its key
if (_waitingForKey) HotkeyService.BeginCapture();
}
private void CloseEditor()
{
if (_waitingForKey) HotkeyService.CancelCapture();
_waitingForKey = false;
_editorOpen = false;
_editIndex = -1;
WatchMetaStates(false);
}
private void PollCapture()
{
if (!_waitingForKey) return;
if (HotkeyService.TryTakeCapture(out KeyCombo? combo))
{
_waitingForKey = false;
if (combo is { } c) _editCombo = c;
}
}
private bool Editor(IReadOnlyList<HotkeyBinding> list, float w)
{
bool typing = false;
Section(_editIndex < 0 ? "New Hotkey" : "Edit Hotkey", w);
// Key: [Ctrl+F1] (click, then press the combo).
Label("Key", "Click, then press the key with any of Ctrl, Alt and Shift. Esc cancels.");
ImGuiNET.ImGui.SameLine(70);
string keyText = _waitingForKey ? "Press a key... (Esc cancels)" : _editCombo.IsEmpty ? "Click to set" : _editCombo.ToString();
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, _waitingForKey ? Teal : Amber);
if (ImGuiNET.ImGui.Button(keyText + "##key", new Vector2(Math.Max(80, w - 74), 0)))
{
if (_waitingForKey) { HotkeyService.CancelCapture(); _waitingForKey = false; }
else { HotkeyService.BeginCapture(); _waitingForKey = true; }
}
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.SetItemTooltip(_waitingForKey ? "Waiting for a key. Click again or press Esc to stop." : "Click, then press the key combination.");
if (_waitingForKey && HotkeyService.CaptureNote.Length > 0)
Warning(HotkeyService.CaptureNote, w);
// Action: dropdown of the built-ins and "Chat command...".
ImGuiNET.ImGui.Dummy(new Vector2(0, 3));
Label("Action", "What the key does: a built-in, or any chat command (e.g. /ra start, /rn bc /ra stop).");
ImGuiNET.ImGui.SameLine(70);
bool isCommand = string.Equals(_editAction, HotkeyActions.Command, StringComparison.OrdinalIgnoreCase);
HotkeyAction? picked = isCommand ? null : HotkeyActions.Find(_editAction);
string current = isCommand ? ChatCommandItem
: picked == null ? _editAction
: picked.Group.Length > 0 ? $"{picked.Name} ({picked.Group})" : picked.Name;
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 74));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
bool open = ImGuiNET.ImGui.BeginCombo("##action", current, ImGuiComboFlags.HeightLarge);
ImGuiNET.ImGui.PopStyleColor(3);
if (!open && picked is { Tip.Length: > 0 }) ImGuiNET.ImGui.SetItemTooltip(picked.Tip);
if (open)
{
if (ImGuiNET.ImGui.Selectable(ChatCommandItem, isCommand)) _editAction = HotkeyActions.Command;
ImGuiNET.ImGui.SetItemTooltip("Run a chat command, as if typed: /ra ..., /rc ..., /lua ..., /rn bc ...");
string group = string.Empty;
foreach (HotkeyAction a in HotkeyActions.BuiltIns)
{
if (a.Group != group || group.Length == 0 && a == HotkeyActions.BuiltIns[0])
{
ImGuiNET.ImGui.Separator();
if (a.Group.Length > 0)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.TextUnformatted(a.Group);
ImGuiNET.ImGui.PopStyleColor();
if (a.Group == HotkeyActions.VTankGroup)
ImGuiNET.ImGui.SetItemTooltip("VirindiTank's hotkey actions, by VTank's names.");
}
group = a.Group;
}
if (ImGuiNET.ImGui.Selectable((a.Group.Length > 0 ? " " : "") + a.Name + "##" + a.Id,
string.Equals(a.Id, _editAction, StringComparison.OrdinalIgnoreCase)))
_editAction = a.Id;
if (a.Tip.Length > 0) ImGuiNET.ImGui.SetItemTooltip(a.Tip);
}
ImGuiNET.ImGui.EndCombo();
}
bool hasParam = picked is { HasParam: true };
WatchMetaStates(hasParam && string.Equals(picked!.Id, HotkeyActions.MetaStateId, StringComparison.OrdinalIgnoreCase));
if (hasParam)
typing |= ParamRow(picked!, w);
if (isCommand)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 3));
Label("Command", "The chat line to run, starting with /.");
ImGuiNET.ImGui.SameLine(70);
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 74));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.InputTextWithHint("##cmd", "/ra start", ref _editCommand, 400u);
typing = ImGuiNET.ImGui.IsItemActive();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(3);
ImGuiNET.ImGui.SetItemTooltip("Any chat command: /ra start, /rc reload, /lua myscript go, /rn bc /ra stop.");
}
// Warnings for this key (allowed anyway).
foreach (string warning in HotkeyConflicts.Warnings(list, _editCombo, _editIndex))
Warning(warning, w);
string cmd = _editCommand.Trim();
string param = _editParam.Trim();
bool commandOk = !isCommand || cmd.StartsWith('/');
bool paramOk = !hasParam || param.Length > 0;
bool canSave = !_editCombo.IsEmpty && !_waitingForKey && commandOk && paramOk;
if (isCommand && cmd.Length > 0 && !cmd.StartsWith('/'))
Warning("A chat command starts with / (e.g. /ra start).", w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
ImGuiNET.ImGui.BeginDisabled(!canSave);
if (ImGuiNET.ImGui.Button(PhosphorIcons.FloppyDisk + " Save"))
{
var b = new HotkeyBinding(_editCombo, isCommand ? HotkeyActions.Command : _editAction,
isCommand ? cmd : hasParam ? param : string.Empty, _editEnabled);
if (_editIndex < 0 || !HotkeyService.Replace(_editIndex, b))
HotkeyService.Add(b);
CloseEditor();
}
ImGuiNET.ImGui.EndDisabled();
if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGuiNET.ImGui.SetTooltip(!canSave
? (_editCombo.IsEmpty || _waitingForKey ? "Pick a key first."
: !paramOk ? $"Pick the {picked?.Param?.ToLowerInvariant() ?? "value"} first."
: "Type the chat command (starting with /).")
: "Save this hotkey (it works right away, in every client on this PC).");
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button("Cancel"))
CloseEditor();
ImGuiNET.ImGui.SetItemTooltip("Close without saving.");
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
return typing;
}
/// <summary>
/// The parameter row (the meta state): a text box, and a list of the loaded meta's states when
/// they are known. True while the text box has the keyboard.
/// </summary>
private bool ParamRow(HotkeyAction a, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 3));
bool meta = string.Equals(a.Id, HotkeyActions.MetaStateId, StringComparison.OrdinalIgnoreCase);
Label(a.Param!, meta ? "The meta state to switch to. Pick one of the loaded meta's states, or type a name." : a.Tip);
ImGuiNET.ImGui.SameLine(70);
List<string> states = meta ? UiSources.Meta.Current?.Value.States ?? new List<string>() : new List<string>();
float listW = states.Count > 0 ? 26 : 0;
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 74 - listW));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.InputTextWithHint("##param", meta ? "state name" : a.Param!.ToLowerInvariant(), ref _editParam, 200u);
bool typing = ImGuiNET.ImGui.IsItemActive();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(3);
ImGuiNET.ImGui.SetItemTooltip(meta ? "The state's name, as in the meta (the case doesn't matter)." : a.Tip);
if (states.Count > 0)
{
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
ImGuiNET.ImGui.SetNextItemWidth(22);
bool open = ImGuiNET.ImGui.BeginCombo("##states", string.Empty, ImGuiComboFlags.NoPreview | ImGuiComboFlags.HeightLarge);
ImGuiNET.ImGui.PopStyleColor(3);
if (open)
{
foreach (string st in states)
if (ImGuiNET.ImGui.Selectable(st + "##st", string.Equals(st, _editParam.Trim(), StringComparison.OrdinalIgnoreCase)))
_editParam = st;
ImGuiNET.ImGui.EndCombo();
}
ImGuiNET.ImGui.SetItemTooltip("The loaded meta's states.");
}
else if (meta)
Note("(No meta loaded, or RynthAi isn't running: type the state's name.)", w);
if (meta && states.Count > 0 && _editParam.Trim().Length > 0
&& !states.Exists(st => string.Equals(st, _editParam.Trim(), StringComparison.OrdinalIgnoreCase)))
Warning($"The loaded meta has no state '{_editParam.Trim()}' (it may be in another meta).", w);
return typing;
}
// ── Pieces in Settings' look ───────────────────────────────────────────
private static void Label(string text, string tip)
{
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.SetItemTooltip(tip);
}
private static void Section(string text, float w)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
float h = bold.FontSize + 4;
dl.AddRectFilled(p, p + new Vector2(w, h), TabActive);
dl.AddText(bold, bold.FontSize, p + new Vector2(4, 2), Amber, text);
ImGuiNET.ImGui.Dummy(new Vector2(w, h));
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
private static void Note(string text, float w) => Wrapped(text, w, Mute);
private static void Warning(string text, float w) => Wrapped(PhosphorIcons.Warning + " " + text, w, Warn);
private static void Wrapped(string text, float w, uint color)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color);
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.PopFont();
}
private static bool IconButton(string id, Vector2 pos, string glyph, bool enabled)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, new Vector2(18, 18)) && enabled;
bool hot = enabled && ImGuiNET.ImGui.IsItemHovered();
dl.AddRectFilled(pos, pos + new Vector2(18, 18), hot ? Lighten(BtnFill) : BtnFill);
dl.AddRect(pos, pos + new Vector2(18, 18), BtnBord);
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, new Vector2(18, 18), enabled ? TextDim : ToggleOff);
return clicked;
}
private static uint Lighten(uint abgr)
{
uint a = abgr & 0xFF000000;
uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * 1.25f) + 12);
uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * 1.25f) + 12);
uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * 1.25f) + 12);
return a | (b << 16) | (g << 8) | r;
}
}

View file

@ -0,0 +1,403 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/InventoryFace.AttrFilter.cs
// The Inventory panel's attribute filter: the funnel-list button in the tools
// row, its rule editor popup, and the per-item check in the filtered list.
// Rules and matching: Compatibility/InventoryAttributeFilter.cs; values:
// Compatibility/InventoryFilterFacts.cs.
//
// Rules on appraised attributes (armor level, ratings, spells...) can't judge
// an item the server hasn't identified yet: those items are hidden and
// counted, and "Identify N" queues them (InventoryModel.QueueIdentify, a few a
// second on AC's main thread). While such a rule is on, the list is rebuilt
// once a second so new identifies show up.
//
// Classic: the filter applies only while the tools row is open (closing the
// row turns it off, like the search), so nothing hides items unseen.
// Threads: the panel's (render) thread only.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Text;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed partial class InventoryFace
{
private const string AttrPopupId = "##inv_attrfilter";
private static readonly long AttrRefreshTicks = Stopwatch.Frequency; // rebuild while appraisal rules are on
private InventoryAttributeFilter _attr = new();
private bool _attrLoaded;
private readonly InventoryFilterFacts _facts = new();
// Items the last rebuild hid because they need an identify.
private readonly List<uint> _unidentified = new();
private int _builtAttrKey = int.MinValue;
private long _attrRefreshAt;
private bool _attrPass;
private bool _openAttr, _attrPopupOpen, _attrSavePending;
private string _attrSummary = string.Empty;
private int _attrSummaryVersion = -1;
// The text rules' edit buffers, by rule.
private readonly Dictionary<InventoryFilterRule, byte[]> _attrText = new();
/// <summary>The attribute filter hides items now (on, has rules and, in Classic, the tools row is open).</summary>
private bool AttrOn => _attr.Active && (!InventorySettingsStore.Classic || InventorySettingsStore.ShowTools);
private void LoadAttrFilter()
{
if (_attrLoaded) return;
_attrLoaded = true;
_attr = InventoryAttributeFilter.Parse(InventorySettingsStore.AttrFilter);
}
/// <summary>An appraisal rule is on and a second has passed: rebuild to pick up new identifies.</summary>
private bool AttrRefreshDue(bool attrOn) =>
attrOn && _attr.NeedsIdentify && Stopwatch.GetTimestamp() >= _attrRefreshAt;
/// <summary>Start of a list rebuild.</summary>
private void BeginAttrPass(bool attrOn)
{
_attrPass = attrOn;
_unidentified.Clear();
_attrRefreshAt = Stopwatch.GetTimestamp() + AttrRefreshTicks;
}
/// <summary>Does the attribute filter keep <paramref name="item"/>? An unknown one is hidden and counted.</summary>
private bool AttrKeeps(InventoryItem item)
{
_facts.Bind(item);
switch (_attr.Evaluate(_facts))
{
case FilterVerdict.Match:
return true;
case FilterVerdict.Unknown:
_unidentified.Add(item.Id);
return false;
default:
return false;
}
}
/// <summary>Records an edit: the list rebuilds now; the rules are saved when the editor closes.</summary>
private void AttrChanged()
{
_attr.Touch();
_attrSavePending = true;
}
private void SetAttrEnabled(bool on)
{
if (_attr.Enabled == on) return;
_attr.Enabled = on;
_attr.Touch();
InventorySettingsStore.SetAttrFilter(_attr.Serialize());
}
private void SaveAttrIfPending()
{
if (!_attrSavePending) return;
_attrSavePending = false;
InventorySettingsStore.SetAttrFilter(_attr.Serialize());
}
// ── The tools-row button ────────────────────────────────────────────
private void AttrFilterButton(Vector2 pos)
{
bool on = AttrOn;
if (IconButton("##inv_attr", PhosphorIcons.ListChecks, pos, new Vector2(22, 22), on ? Teal : Mute,
on ? Selected : BtnFill, border: on ? Teal : 0u, font: UiFont.Ui11))
_openAttr = true;
if (!ImGuiNET.ImGui.IsItemHovered()) return;
if (_attrSummaryVersion != _attr.Version)
{
_attrSummaryVersion = _attr.Version;
_attrSummary = _attr.Rules.Count == 0 ? string.Empty : _attr.Summary();
}
string tip = on ? "Attribute filter on: " + _attrSummary
: _attr.Rules.Count > 0 ? "Attribute filter off (" + _attrSummary + ")"
: "Filter by item attributes (armor level, ratings, spells, slot...)";
if (on && _unidentified.Count > 0)
tip += "\n" + _unidentified.Count.ToString(CultureInfo.InvariantCulture) + " hidden until identified.";
ImGuiNET.ImGui.SetTooltip(tip);
}
// ── The editor popup ────────────────────────────────────────────────
/// <summary>Once per frame, outside any child.</summary>
private void AttrFilterDialog()
{
if (_openAttr)
{
_openAttr = false;
_attrPopupOpen = true;
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos(), ImGuiCond.Always);
ImGuiNET.ImGui.OpenPopup(AttrPopupId);
}
if (!_attrPopupOpen) return;
PushAttrStyle();
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
bool visible = ImGuiNET.ImGui.BeginPopup(AttrPopupId, ImGuiWindowFlags.AlwaysAutoResize);
ImGuiNET.ImGui.PopStyleVar();
if (!visible)
{
PopAttrStyle();
_attrPopupOpen = false; // clicked outside, or Esc
SaveAttrIfPending();
return;
}
try
{
if (AttrBody())
{
ImGuiNET.ImGui.CloseCurrentPopup();
_attrPopupOpen = false;
SaveAttrIfPending();
}
}
finally
{
ImGuiNET.ImGui.EndPopup();
PopAttrStyle();
}
}
/// <summary>The popup's contents; true when it should close.</summary>
private bool AttrBody()
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.TextUnformatted(PhosphorIcons.ListChecks + " Filter by attributes");
ImGuiNET.ImGui.PopStyleColor();
bool on = _attr.Enabled;
if (ImGuiNET.ImGui.Checkbox("Filter on", ref on))
{
_attr.Enabled = on;
AttrChanged();
}
ImGuiNET.ImGui.SameLine(0, 16);
ImGuiNET.ImGui.TextUnformatted("Keep items matching");
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.RadioButton("all rules", !_attr.MatchAny)) { _attr.MatchAny = false; AttrChanged(); }
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.RadioButton("any rule", _attr.MatchAny)) { _attr.MatchAny = true; AttrChanged(); }
ImGuiNET.ImGui.Separator();
int remove = -1;
for (int i = 0; i < _attr.Rules.Count; i++)
{
ImGuiNET.ImGui.PushID(i);
if (RuleRow(_attr.Rules[i])) remove = i;
ImGuiNET.ImGui.PopID();
}
if (remove >= 0)
{
_attrText.Remove(_attr.Rules[remove]);
_attr.Rules.RemoveAt(remove);
AttrChanged();
}
if (_attr.Rules.Count == 0)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
ImGuiNET.ImGui.TextUnformatted("No rules yet. Add one, e.g. Armor level >= 300.");
ImGuiNET.ImGui.PopStyleColor();
}
if (_attr.Rules.Count < InventoryAttributeFilter.MaxRules
&& ImGuiNET.ImGui.Button(PhosphorIcons.Plus + " Add rule"))
{
_attr.Rules.Add(InventoryAttributeFilter.NewRule(FilterAttr.ArmorLevel));
if (_attr.Rules.Count == 1) _attr.Enabled = true; // the first rule turns the filter on
AttrChanged();
}
IdentifySection();
ImGuiNET.ImGui.Separator();
bool close = false;
if (ImGuiNET.ImGui.Button("Clear rules") && _attr.Rules.Count > 0)
{
_attr.Rules.Clear();
_attrText.Clear();
AttrChanged();
}
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button("Close")) close = true;
return close;
}
/// <summary>One rule: attribute, operator, value, remove. True when its remove button was pressed.</summary>
private bool RuleRow(InventoryFilterRule rule)
{
FilterAttrInfo info = InventoryAttributeFilter.Info(rule.Attr);
ImGuiNET.ImGui.SetNextItemWidth(180);
if (ImGuiNET.ImGui.BeginCombo("##attr", AttrLabel(info)))
{
bool first = true;
foreach (FilterAttrInfo a in InventoryAttributeFilter.Attributes)
{
if (a.NeedsId && first)
{
first = false;
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
ImGuiNET.ImGui.TextUnformatted("Needs an identify (*)");
ImGuiNET.ImGui.PopStyleColor();
}
if (ImGuiNET.ImGui.Selectable(AttrLabel(a), a.Id == rule.Attr) && a.Id != rule.Attr)
{
InventoryAttributeFilter.SetAttr(rule, a.Id);
AttrChanged();
}
ImGuiNET.ImGui.SetItemTooltip(a.Tip);
}
ImGuiNET.ImGui.EndCombo();
}
ImGuiNET.ImGui.SetItemTooltip(info.Tip);
info = InventoryAttributeFilter.Info(rule.Attr);
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.SetNextItemWidth(info.Kind == FilterAttrKind.Text ? 120 : 60);
if (ImGuiNET.ImGui.BeginCombo("##op", InventoryAttributeFilter.OpLabel(rule.Op)))
{
foreach (FilterOp op in InventoryAttributeFilter.OpsFor(info.Kind))
{
if (ImGuiNET.ImGui.Selectable(InventoryAttributeFilter.OpLabel(op), op == rule.Op) && op != rule.Op)
{
rule.Op = op;
AttrChanged();
}
}
ImGuiNET.ImGui.EndCombo();
}
ImGuiNET.ImGui.SameLine();
switch (info.Kind)
{
case FilterAttrKind.Number:
{
ImGuiNET.ImGui.SetNextItemWidth(90);
double v = rule.Number;
if (ImGuiNET.ImGui.InputDouble("##num", ref v, 0, 0, "%g") && double.IsFinite(v) && v != rule.Number)
{
rule.Number = v;
AttrChanged();
}
break;
}
case FilterAttrKind.Text:
{
if (!_attrText.TryGetValue(rule, out byte[]? buf))
{
buf = new byte[64];
byte[] src = Encoding.UTF8.GetBytes(rule.Text);
Array.Copy(src, buf, Math.Min(src.Length, buf.Length - 1)); // the last byte stays the terminator
_attrText[rule] = buf;
}
ImGuiNET.ImGui.SetNextItemWidth(150);
if (ImGuiNET.ImGui.InputText("##text", buf, (uint)buf.Length))
{
rule.Text = Utf8(buf).Trim();
AttrChanged();
}
break;
}
case FilterAttrKind.Choice:
{
ImGuiNET.ImGui.SetNextItemWidth(150);
int c = Math.Clamp(rule.Choice, 0, InventoryAttributeFilter.SlotNames.Length - 1);
if (ImGuiNET.ImGui.BeginCombo("##choice", InventoryAttributeFilter.SlotNames[c]))
{
for (int k = 0; k < InventoryAttributeFilter.SlotNames.Length; k++)
{
if (ImGuiNET.ImGui.Selectable(InventoryAttributeFilter.SlotNames[k], k == c) && k != rule.Choice)
{
rule.Choice = k;
AttrChanged();
}
}
ImGuiNET.ImGui.EndCombo();
}
break;
}
default:
ImGuiNET.ImGui.Dummy(new Vector2(150, 0)); // a flag has no value; keeps the remove buttons lined up
break;
}
ImGuiNET.ImGui.SameLine();
bool removeIt = ImGuiNET.ImGui.SmallButton(PhosphorIcons.X);
ImGuiNET.ImGui.SetItemTooltip("Remove this rule");
return removeIt;
}
private static string AttrLabel(FilterAttrInfo a) => a.NeedsId ? a.Label + " *" : a.Label;
/// <summary>How many items wait for an identify, and the button that asks for them.</summary>
private void IdentifySection()
{
if (!_attr.NeedsIdentify) return;
ImGuiNET.ImGui.Separator();
int queued = InventoryModel.IdentifyQueueCount;
if (!AttrOn)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
ImGuiNET.ImGui.TextUnformatted(InventorySettingsStore.Classic && !InventorySettingsStore.ShowTools
? "Open the tools row to use the filter." : "Turn the filter on to see which items need an identify.");
ImGuiNET.ImGui.PopStyleColor();
}
else if (_unidentified.Count == 0)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Green);
ImGuiNET.ImGui.TextUnformatted("Every item the rules need is identified.");
ImGuiNET.ImGui.PopStyleColor();
}
else
{
string n = _unidentified.Count.ToString(CultureInfo.InvariantCulture);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.TextUnformatted(n + (_unidentified.Count == 1 ? " item is" : " items are") + " hidden until identified.");
ImGuiNET.ImGui.PopStyleColor();
if (ImGuiNET.ImGui.Button("Identify " + n)) InventoryModel.QueueIdentify(_unidentified);
ImGuiNET.ImGui.SetItemTooltip("Asks the server about them, 4 a second while this panel is open.");
}
if (queued > 0)
{
if (AttrOn && _unidentified.Count > 0) ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.TextUnformatted(queued.ToString(CultureInfo.InvariantCulture) + " waiting");
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Stop")) InventoryModel.ClearIdentifyQueue();
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
ImGuiNET.ImGui.TextUnformatted("* needs an identify. Hovering an item also identifies it.");
ImGuiNET.ImGui.PopStyleColor();
}
private static void PushAttrStyle()
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, Lighten(BtnFill));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Separator, BtnBord);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, Lighten(BtnFill));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
}
private static void PopAttrStyle()
{
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(9);
}
}

View file

@ -160,7 +160,7 @@ internal sealed partial class InventoryFace
// The open pack: a real pack (Classic has no "All" or "Worn" entry; the paperdoll is Worn).
if (_pack == AllPacks || _pack == WornPacks || view.PackOf(_pack) == null)
_pack = view.Packs.Length > 0 ? view.Packs[0].Id : AllPacks;
bool filtered = _category != 0 || _searchText.Length > 0;
bool filtered = FiltersOn;
RebuildIfNeeded(view, filtered ? AllPacks : _pack);
Backdrop(dl, o, w, bottom - o.Y, s);
@ -774,12 +774,13 @@ internal sealed partial class InventoryFace
dl.AddLine(p, p + new Vector2(w, 0), Faded(Gold));
InventoryTarget? target = InventoryModel.Target;
InventoryItem? sel = SelectedItem(view);
RefreshSelectionLabels(target);
float zh = h - 4, giveW = Math.Min(128 * s, w * 0.42f), dropW = 62 * s;
var give = new Vector2(p.X + w - giveW - 2, p.Y + 2);
var drop = new Vector2(give.X - dropW - 3, p.Y + 2);
Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, "Drop", drop, new Vector2(dropW, zh), 0, "",
InventoryModel.DropAvailable, sel, "Drop on the ground: drag an item here, or click to drop the selected item.");
Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, target?.ZoneLabel ?? "Give", give, new Vector2(giveW, zh),
Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, _dropLabel, drop, new Vector2(dropW, zh), 0, "",
InventoryModel.DropAvailable, sel, DropTip);
Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, _giveLabel, give, new Vector2(giveW, zh),
target?.Id ?? 0, target?.Name ?? "", InventoryModel.GiveAvailable && target != null, sel,
target?.ZoneTip ?? "Select a creature, NPC or player in the game to give to.");
StatusLine(new Vector2(p.X + 3, p.Y), Math.Max(10, drop.X - p.X - 6), h, view);
@ -803,7 +804,7 @@ internal sealed partial class InventoryFace
dl.AddText(tp, StackCol, it.StackText);
}
if (it.Id == pendingId) Overlay(dl, Art.Waiting, min, cell, Amber);
if (it.Id == _selected) Overlay(dl, Art.Selected, min, cell, SelYellow);
if (IsPicked(it)) Overlay(dl, Art.Selected, min, cell, SelYellow);
}
/// <summary>Hover, click (select, and a press that may become a drag), double-click (use), right-click (menu).</summary>
@ -813,7 +814,7 @@ internal sealed partial class InventoryFace
_hover = it;
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
_selected = it.Id;
ClickItem(it);
_pressItem = it;
_pressAt = ImGuiNET.ImGui.GetMousePos();
}
@ -823,11 +824,7 @@ internal sealed partial class InventoryFace
Act(InventoryActionKind.Use, it, 0, "", 0);
}
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right))
{
_selected = it.Id;
_ctxItem = it;
_openCtx = true;
}
RightClickItem(it);
}
/// <summary>
@ -967,8 +964,9 @@ internal sealed partial class InventoryFace
}
/// <summary>
/// The Inventory panel's remembered choices: Classic or Modern look, and whether the
/// Classic view shows its tools row. %LOCALAPPDATA%\RynthCore\inventory_settings.txt,
/// The Inventory panel's remembered choices: Classic or Modern look, whether the
/// Classic view shows its tools row, its size, and the attribute filter's rules.
/// %LOCALAPPDATA%\RynthCore\inventory_settings.txt,
/// read once when the panel opens, written in the background when a choice changes.
/// </summary>
internal static class InventorySettingsStore
@ -983,6 +981,8 @@ internal static class InventorySettingsStore
/// <summary>The panel's size in percent of the UI scale (50-150, steps of 5); text follows it.</summary>
public static int SizePct { get; private set; } = 80;
public static float SizeFactor => SizePct / 100f;
/// <summary>The attribute filter's rules (InventoryAttributeFilter.Serialize); "" = none.</summary>
public static string AttrFilter { get; private set; } = string.Empty;
private static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "inventory_settings.txt");
@ -1006,6 +1006,7 @@ internal static class InventorySettingsStore
if (key == "classic") Classic = val == "1";
else if (key == "tools") ShowTools = val == "1";
else if (key == "size" && int.TryParse(val, out int pct)) SizePct = Math.Clamp(pct, 50, 150);
else if (key == "attrfilter") AttrFilter = val;
}
}
catch { /* defaults stay */ }
@ -1034,13 +1035,22 @@ internal static class InventorySettingsStore
Save();
}
public static void SetAttrFilter(string line)
{
line ??= string.Empty;
if (AttrFilter == line) return;
AttrFilter = line;
Save();
}
/// <summary>Writes the settings in the background (the caller is AC's render thread).</summary>
private static void Save()
{
string text = "# RynthCore inventory panel settings - auto-generated, hand-edits OK.\n"
+ "classic=" + (Classic ? "1" : "0") + "\n"
+ "tools=" + (ShowTools ? "1" : "0") + "\n"
+ "size=" + SizePct + "\n";
+ "size=" + SizePct + "\n"
+ "attrfilter=" + AttrFilter + "\n";
UiBackgroundWriter.Enqueue("inventory settings", () =>
{
lock (Sync)

View file

@ -0,0 +1,373 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/InventoryFace.MultiSelect.cs
// Several items at once, in both looks:
// pick click = one item; Ctrl+click adds / removes one; Shift+click
// the run from the last clicked item (Ctrl+Shift adds the run);
// right-click menu: Select all shown
// act with more than one picked, Drop, Give and a drop on a pack act
// on all of them (drag any picked item, or click the zone); the
// right-click menu has Drop / Give / Move to for the group
// confirm Drop and Give of several ask first (given items don't come
// back); Move doesn't
// run InventoryModel.RequestBatch sends them one at a time; the status
// row shows "Giving 3 of 12 to Bob" with a Stop button
// Worn items, and items that can't go where they're sent, are left out (and
// counted in the confirm / refusal text).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed partial class InventoryFace
{
private const int ConfirmNameLines = 10;
private static readonly Func<InventoryItem, uint> IdOfItem = static it => it.Id;
private readonly InventorySelection _multi = new();
// A plain press on an item that is part of the group: the group stays for a drag;
// released without dragging, the selection narrows to that item (Explorer's rule).
private bool _pressNarrow;
// Drop / Give confirmation (opened at the end of Draw, like the split dialog).
private bool _openConfirm;
private InventoryRequest[] _confirmItems = Array.Empty<InventoryRequest>();
private string _confirmTitle = string.Empty, _confirmOk = string.Empty, _confirmNote = string.Empty;
private string[] _confirmNames = Array.Empty<string>();
// Labels that carry the selection's size, rebuilt only when it or the give target changes.
private int _labelsFor = -1;
private InventoryTarget? _labelsTarget;
private string _dropLabel = "Drop", _giveLabel = "Give", _countBadge = string.Empty, _selHint = string.Empty;
private string _menuCount = string.Empty, _menuDrop = string.Empty, _menuGive = string.Empty, _menuMove = string.Empty;
private string _selectAllLabel = "Select all shown";
// Status row cache for a running batch.
private InventoryBatchStatus? _batchShown;
/// <summary>A left click on an item: one item, or Ctrl / Shift to pick several.</summary>
private void ClickItem(InventoryItem it)
{
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
_pressNarrow = false;
if (io.KeyShift)
{
_multi.Range(_shown, IdOfItem, it.Id, additive: io.KeyCtrl);
SelectItem(it);
return;
}
if (io.KeyCtrl)
{
// Ctrl+click right after a right-click selection keeps that item too.
if (_multi.Count == 0 && _selected != 0 && _selected != it.Id) _multi.Single(_selected);
if (_multi.Toggle(it.Id)) SelectItem(it);
else _selected = _multi.Count > 0 ? _multi.Ids[_multi.Count - 1] : 0;
return;
}
if (_multi.IsMulti && _multi.Contains(it.Id)) _pressNarrow = true;
else _multi.Single(it.Id);
SelectItem(it);
}
/// <summary>A right click: on a picked item the menu acts on the group, else on that one item.</summary>
private void RightClickItem(InventoryItem it)
{
if (!_multi.Contains(it.Id)) _multi.Single(it.Id);
_selected = it.Id;
_ctxItem = it;
_openCtx = true;
}
/// <summary>True when <paramref name="it"/> is drawn as selected (the one clicked, or part of the group).</summary>
private bool IsPicked(InventoryItem it) => it.Id == _selected || _multi.Contains(it.Id);
/// <summary>True when an action on <paramref name="it"/> means the whole group.</summary>
private bool IsGroup(InventoryItem? it) => _multi.IsMulti && (it == null || _multi.Contains(it.Id));
/// <summary>
/// A zone click or a drop: on the group (Drop, Give, or a pack) when several are picked
/// and <paramref name="item"/> is one of them; otherwise the single-item action.
/// <paramref name="slot"/> is the pack cell a single item was dropped on (-1: none);
/// a group goes to the end of the pack.
/// </summary>
private void DropOnSelection(DropKind kind, uint targetId, string targetName, InventoryItem? item, int slot = -1)
{
if (IsGroup(item) && kind is DropKind.Drop or DropKind.Give or DropKind.Pack)
{
GroupAction(kind, targetId, targetName);
return;
}
if (item != null) DropOn(kind, targetId, targetName, item, slot);
}
/// <summary>Builds the group's requests; Drop and Give ask first, Move starts at once.</summary>
private void GroupAction(DropKind kind, uint targetId, string targetName)
{
InventoryView view = InventoryModel.Current;
InventoryActionKind action = kind switch
{
DropKind.Drop => InventoryActionKind.Drop,
DropKind.Give => InventoryActionKind.Give,
_ => InventoryActionKind.Move,
};
if (action == InventoryActionKind.Give && targetId == 0) { Refuse("Select someone in the game to give to."); return; }
var list = new List<InventoryRequest>(_multi.Count);
int worn = 0, gone = 0, cant = 0;
foreach (uint id in _multi.Ids)
{
InventoryItem? it = FindAny(view, id);
if (it == null) { gone++; continue; }
if (it.Wielder != 0) { worn++; continue; }
if (action == InventoryActionKind.Move)
{
// Already there (or the pack itself): skipped quietly, like a single item's drop.
if (it.Id == targetId || it.Container == targetId) continue;
// Foci and packs go only in the main pack (a side pack has no pack slots).
if ((it.RequiresPackSlot || it.IsPack) && targetId != view.PlayerId) { cant++; continue; }
}
list.Add(new InventoryRequest
{
Kind = action, ItemId = it.Id, TargetId = action == InventoryActionKind.Drop ? 0 : targetId,
TargetName = action == InventoryActionKind.Drop ? string.Empty : targetName, ItemName = it.Name,
});
}
if (list.Count > InventoryModel.MaxBatch)
{
Refuse($"{list.Count} items: at most {InventoryModel.MaxBatch} at once.");
return;
}
string note = LeftOutText(worn, gone, cant);
if (list.Count == 0)
{
// All already in that pack: nothing to do, nothing to say.
if (action == InventoryActionKind.Move && note.Length == 0) return;
Refuse(note.Length > 0 ? "Nothing to send: " + note : "Nothing to send.");
return;
}
if (action == InventoryActionKind.Move)
{
StartBatch(list);
if (note.Length > 0 && _refusal.Length == 0) Refuse("Left out: " + note);
return;
}
OpenConfirm(action, list, targetName, note);
}
/// <summary>"2 worn, 1 gone" for the items a group action leaves out ("" when none).</summary>
private static string LeftOutText(int worn, int gone, int cant)
{
var parts = new List<string>(3);
if (worn > 0) parts.Add($"{worn} worn");
if (cant > 0) parts.Add($"{cant} can only go in the main pack");
if (gone > 0) parts.Add($"{gone} gone");
return string.Join(", ", parts);
}
private void StartBatch(IReadOnlyList<InventoryRequest> list)
{
if (!InventoryModel.RequestBatch(list, out string why)) Refuse(why);
else _refusal = string.Empty;
}
// ── Confirmation ────────────────────────────────────────────────────
private void OpenConfirm(InventoryActionKind action, List<InventoryRequest> list, string targetName, string note)
{
string n = list.Count.ToString(CultureInfo.InvariantCulture);
_confirmItems = list.ToArray();
_confirmTitle = action == InventoryActionKind.Give
? $"Give {n} item{(list.Count == 1 ? "" : "s")} to {targetName}?"
: $"Drop {n} item{(list.Count == 1 ? "" : "s")} on the ground?";
_confirmOk = (action == InventoryActionKind.Give ? PhosphorIcons.Gift + " Give " : PhosphorIcons.ArrowFatDown + " Drop ") + n;
_confirmNote = note.Length > 0 ? "Left out: " + note + "." : string.Empty;
_confirmNames = ConfirmNames(list);
_openConfirm = true;
}
/// <summary>The items by name ("Pyreal x3"), in picked order, at most ConfirmNameLines lines.</summary>
private static string[] ConfirmNames(List<InventoryRequest> list)
{
var order = new List<string>();
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (InventoryRequest r in list)
{
if (counts.TryGetValue(r.ItemName, out int c)) counts[r.ItemName] = c + 1;
else { counts[r.ItemName] = 1; order.Add(r.ItemName); }
}
var lines = new List<string>(Math.Min(order.Count, ConfirmNameLines) + 1);
for (int i = 0; i < order.Count && i < ConfirmNameLines; i++)
lines.Add(counts[order[i]] > 1 ? $"{order[i]} x{counts[order[i]]}" : order[i]);
if (order.Count > ConfirmNameLines)
lines.Add($"...and {order.Count - ConfirmNameLines} more kind{(order.Count - ConfirmNameLines == 1 ? "" : "s")}");
return lines.ToArray();
}
private void ConfirmDialog()
{
if (_openConfirm)
{
_openConfirm = false;
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos(), ImGuiCond.Always);
ImGuiNET.ImGui.OpenPopup("##inv_batch_confirm");
}
PushMenuStyle();
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
bool open = ImGuiNET.ImGui.BeginPopup("##inv_batch_confirm");
ImGuiNET.ImGui.PopStyleVar();
if (!open) { PopMenuStyle(); return; }
try
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.TextUnformatted(_confirmTitle);
ImGuiNET.ImGui.PopStyleColor();
foreach (string line in _confirmNames) ImGuiNET.ImGui.BulletText(line);
if (_confirmNote.Length > 0) ImGuiNET.ImGui.TextDisabled(_confirmNote);
if (_confirmItems.Length > 0 && _confirmItems[0].Kind == InventoryActionKind.Give)
ImGuiNET.ImGui.TextDisabled("Given items can't be taken back.");
bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning;
Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4);
if (Button("##bc_ok", _confirmOk, bp, new Vector2(110, 24), Teal, BtnFill, enabled: idle && _confirmItems.Length > 0))
{
StartBatch(_confirmItems);
_confirmItems = Array.Empty<InventoryRequest>();
ImGuiNET.ImGui.CloseCurrentPopup();
}
if (!idle) ImGuiNET.ImGui.SetItemTooltip("An item action is still waiting.");
if (Button("##bc_cancel", "Cancel", bp + new Vector2(116, 0), new Vector2(80, 24), Text, BtnFill))
{
_confirmItems = Array.Empty<InventoryRequest>();
ImGuiNET.ImGui.CloseCurrentPopup();
}
ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28));
ImGuiNET.ImGui.Dummy(new Vector2(200, 0));
}
finally
{
ImGuiNET.ImGui.EndPopup();
PopMenuStyle();
}
}
// ── Labels ──────────────────────────────────────────────────────────
/// <summary>Zone labels, menu entries and hints that show the group's size. Rebuilt only on change.</summary>
private void RefreshSelectionLabels(InventoryTarget? target)
{
int n = _multi.IsMulti ? _multi.Count : 0;
if (n == _labelsFor && ReferenceEquals(target, _labelsTarget)) return;
_labelsFor = n;
_labelsTarget = target;
string count = n.ToString(CultureInfo.InvariantCulture);
_dropLabel = n > 0 ? "Drop " + count : "Drop";
_giveLabel = target == null ? "Give" : n > 0 ? "Give " + count + ": " + target.Name : target.ZoneLabel;
_countBadge = n > 0 ? count : string.Empty;
_selHint = n > 0
? count + " selected: Drop, Give, drag to a pack, or right-click. Ctrl+click adds or removes; Shift+click picks a run."
: string.Empty;
_menuCount = count + " items selected";
_menuDrop = "Drop " + count + " items";
_menuGive = target == null ? string.Empty : "Give " + count + " items to " + target.Name;
_menuMove = "Move " + count + " items to";
}
// ── Group menu ──────────────────────────────────────────────────────
/// <summary>The right-click menu when the clicked item is part of a group.</summary>
private void GroupMenu(InventoryView view, InventoryItem clicked)
{
bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning;
InventoryTarget? target = InventoryModel.Target;
RefreshSelectionLabels(target);
ImGuiNET.ImGui.TextDisabled(_menuCount);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem(_menuDrop, "", false, idle && InventoryModel.DropAvailable))
GroupAction(DropKind.Drop, 0, string.Empty);
if (target != null && ImGuiNET.ImGui.MenuItem(_menuGive, "", false, idle && InventoryModel.GiveAvailable))
GroupAction(DropKind.Give, target.Id, target.Name);
if (ImGuiNET.ImGui.BeginMenu(_menuMove, idle))
{
foreach (InventoryPack p in view.Packs)
if (ImGuiNET.ImGui.MenuItem(p.Name, p.FillText, false, true))
GroupAction(DropKind.Pack, p.Id, p.Name);
ImGuiNET.ImGui.EndMenu();
}
ImGuiNET.ImGui.Separator();
SelectionMenuItems(clicked);
if (!idle) ImGuiNET.ImGui.TextDisabled("(an item action is waiting)");
}
/// <summary>Select all shown / select only this one (both menus).</summary>
private void SelectionMenuItems(InventoryItem clicked)
{
if (ImGuiNET.ImGui.MenuItem(_selectAllLabel, "", false, _shown.Count > 1))
_multi.SelectAll(_shown, IdOfItem);
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("Pick every item the grid shows (this pack, or the search's matches). Ctrl+click and Shift+click also pick several.");
if (_multi.IsMulti && ImGuiNET.ImGui.MenuItem("Select only this item"))
{
_multi.Single(clicked.Id);
_selected = clicked.Id;
}
}
// ── Status and pieces ───────────────────────────────────────────────
/// <summary>
/// A running batch in the status row: progress and a Stop button at the row's right end.
/// False when no batch is running.
/// </summary>
private bool BatchStatus(ImDrawListPtr dl, Vector2 p, float w, float statusH, float ty)
{
InventoryBatchStatus? batch = InventoryModel.Batch;
if (batch == null || !batch.Running) { _batchShown = null; return false; }
_batchShown = batch;
float stop = Math.Min(statusH - 2, 20);
var stopPos = new Vector2(p.X + w - stop - 1, p.Y + (statusH - stop) * 0.5f);
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.HourglassMedium, p, new Vector2(16, statusH), Amber);
dl.PushClipRect(p, new Vector2(stopPos.X - 2, p.Y + statusH), true);
dl.AddText(new Vector2(p.X + 18, ty), Amber, batch.Text);
dl.PopClipRect();
if (IconButton("##inv_batch_stop", PhosphorIcons.Stop, stopPos, new Vector2(stop, stop), Red, BtnFill,
enabled: !batch.Stopping, font: UiFont.Ui11))
InventoryModel.CancelBatch();
ImGuiNET.ImGui.SetItemTooltip("Stop: no more items are sent (the one in flight still finishes).");
return true;
}
/// <summary>The group's size on the drag ghost.</summary>
private void DragBadge(ImDrawListPtr fg, Vector2 ghostMin)
{
if (!IsGroup(_dragItem) || _countBadge.Length == 0) return;
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_countBadge);
var tp = ghostMin + new Vector2(Icon - ts.X + 4, Icon - ts.Y + 4);
fg.AddRectFilled(tp - new Vector2(3, 1), tp + ts + new Vector2(3, 1), Faded(Black), 4);
fg.AddText(tp, Amber, _countBadge);
}
/// <summary>Forgets picked items that left the inventory (given, dropped, merged). On a new view only.</summary>
private void PruneSelection(InventoryView view)
{
if (_multi.Count == 0) return;
_multi.Prune(id => FindAny(view, id) != null);
}
/// <summary>An item in the packs or worn, by id.</summary>
private static InventoryItem? FindAny(InventoryView view, uint id)
{
foreach (InventoryPack p in view.Packs)
foreach (InventoryItem it in p.Items)
if (it.Id == id) return it;
foreach (InventoryItem it in view.Worn)
if (it.Id == id) return it;
return null;
}
}

View file

@ -7,20 +7,24 @@
// Modern the Phase 1 layout, below
//
// header burden (percent of capacity) and pyreals; item count
// tools search box, sort picker; category chips
// tools search box, attribute filter (InventoryFace.AttrFilter.cs), sort
// picker; category chips
// packs All, Main pack, each side pack (its icon and fill), Worn
// grid the chosen pack's items as icons with stack counts; hover for a
// tooltip (asks the server to identify an unknown item, throttled);
// double-click uses; right-click for Use / Equip / Split / Move to /
// Drop / Give; drag onto a pack to move, onto Equip / Drop / Give
// zones Equip, Drop, Give-to-<selected creature>: drop targets for a drag,
// or buttons for the selected item
// or buttons for the selected item(s)
// status the one action waiting for the server (with a timer), or how the
// last one ended
// last one ended; a several-item run's progress and Stop
// several Ctrl+click / Shift+click / Select all pick several items for Drop,
// Give or Move (InventoryFace.MultiSelect.cs)
//
// Data: InventoryModel (Compatibility), captured and acted on on AC's main
// thread. This face only reads its published objects and posts requests; one
// item action at a time (a click while one waits is refused, never queued).
// Several items go as a batch the model sends one after another.
// Per frame: no allocation except the tooltip of a newly hovered item and the
// filtered list when the view, pack, filter, search or sort change.
// ============================================================================
@ -122,6 +126,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
public void OnShown()
{
InventorySettingsStore.Load();
LoadAttrFilter();
InventoryModel.Subscribe();
}
@ -130,6 +135,8 @@ internal sealed partial class InventoryFace : IImGuiPanel
InventoryModel.Hover(0);
InventoryModel.Unsubscribe();
_dragItem = _pressItem = null;
_pressNarrow = false;
ItemDragBridge.EndPopOutDrag();
UiDropTargets.EngineDragObject = 0;
_lootAdd.Cancel();
}
@ -168,6 +175,8 @@ internal sealed partial class InventoryFace : IImGuiPanel
DrawDragGhost();
ContextMenu(view);
SplitDialog(view);
ConfirmDialog();
AttrFilterDialog();
_lootAdd.Draw();
_picker.Draw();
}
@ -254,7 +263,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float sortW = 118;
float boxW = Math.Max(80, w - sortW - 26 - 8);
float boxW = Math.Max(80, w - sortW - 26 - 26 - 8);
if (TextBox("##inv_search", _search, p, boxW, PhosphorIcons.MagnifyingGlass + " Search names", out _))
_searchText = Utf8(_search).Trim().ToLowerInvariant();
if (IconButton("##inv_clear", PhosphorIcons.X, new Vector2(p.X + boxW + 2, p.Y), new Vector2(22, 22), Mute, BtnFill,
@ -264,6 +273,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
_searchText = string.Empty;
}
ImGuiNET.ImGui.SetItemTooltip("Clear the search");
AttrFilterButton(new Vector2(p.X + boxW + 26, p.Y));
Vector2 sp = new(p.X + w - sortW, p.Y);
if (Button("##inv_sortbtn", SortLabels[_sort], sp, new Vector2(sortW, 22), Text, BtnFill,
leftAlign: true))
@ -316,12 +326,17 @@ internal sealed partial class InventoryFace : IImGuiPanel
private void RebuildIfNeeded(InventoryView view, uint pack)
{
bool classic = InventorySettingsStore.Classic;
bool attrOn = AttrOn;
int attrKey = attrOn ? _attr.Version : -1;
if (ReferenceEquals(view, _builtFor) && _builtPack == pack && _builtSort == _sort
&& _builtCategory == _category && ReferenceEquals(_builtSearch, _searchText) && _builtClassic == classic
&& _builtOrderVersion == Net.InventoryOrder.Version)
&& _builtOrderVersion == Net.InventoryOrder.Version && _builtAttrKey == attrKey && !AttrRefreshDue(attrOn))
return;
if (_builtPack != pack || !ReferenceEquals(_builtSearch, _searchText) || _builtCategory != _category)
if (_builtPack != pack || !ReferenceEquals(_builtSearch, _searchText) || _builtCategory != _category || _builtAttrKey != attrKey)
_gridFirstRow = 0; // another pack or filter: back to the top (Classic grid)
_builtAttrKey = attrKey;
BeginAttrPass(attrOn);
if (!ReferenceEquals(view, _builtFor)) PruneSelection(view);
_builtFor = view;
_builtPack = pack;
_builtSort = _sort;
@ -356,6 +371,9 @@ internal sealed partial class InventoryFace : IImGuiPanel
_countText = _shown.Count == total
? total.ToString(CultureInfo.InvariantCulture) + " items"
: _shown.Count.ToString(CultureInfo.InvariantCulture) + " of " + total.ToString(CultureInfo.InvariantCulture);
if (_unidentified.Count > 0)
_countText += ", " + _unidentified.Count.ToString(CultureInfo.InvariantCulture) + " not ID'd";
_selectAllLabel = "Select all shown (" + _shown.Count.ToString(CultureInfo.InvariantCulture) + ")";
// The Classic grid's caption, retail's "Contents of <pack>".
_captionText = pack == WornPacks ? "Worn"
: one == null ? (_shown.Count == total ? "All packs" : "Matches in all packs: " + _countText)
@ -388,7 +406,10 @@ internal sealed partial class InventoryFace : IImGuiPanel
/// <summary>A grid cell is a slot only while the list is the server's, whole and in pack order, and the item is an ordinary one.</summary>
private bool CellsAreSlots(InventoryItem item) =>
_orderKnown && _sort == 0 && _category == 0 && _searchText.Length == 0 && !item.RequiresPackSlot && !item.IsPack;
_orderKnown && _sort == 0 && !FiltersOn && !item.RequiresPackSlot && !item.IsPack;
/// <summary>Some filter hides items: a category, search text or the attribute filter.</summary>
private bool FiltersOn => _category != 0 || _searchText.Length > 0 || AttrOn;
/// <summary>The slot an item holds now among its pack's ordinary items, or -1 when unknown.</summary>
private static int SlotOf(InventoryItem item)
@ -411,6 +432,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
if (_skipSlotItems && it.RequiresPackSlot) continue;
if (_category != 0 && it.Category != cat) continue;
if (_searchText.Length > 0 && !it.SearchName.Contains(_searchText, StringComparison.Ordinal)) continue;
if (_attrPass && !AttrKeeps(it)) continue;
_shown.Add(it);
}
}
@ -513,7 +535,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
if (_shown.Count == 0)
{
dl.AddText(o + new Vector2(4, 4), Mute, _searchText.Length > 0 || _category != 0 ? "Nothing matches." : "Empty.");
dl.AddText(o + new Vector2(4, 4), Mute, FiltersOn ? "Nothing matches." : "Empty.");
ImGuiNET.ImGui.Dummy(new Vector2(avail, 20));
}
else
@ -538,7 +560,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
_selected = hot.Id;
ClickItem(hot);
_pressItem = hot;
_pressAt = mouse;
}
@ -548,11 +570,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
Act(InventoryActionKind.Use, hot, 0, "", 0);
}
if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right))
{
_selected = hot.Id;
_ctxItem = hot;
_openCtx = true;
}
RightClickItem(hot);
if (_pressItem != null && _dragItem == null && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)
&& Vector2.DistanceSquared(mouse, _pressAt) > 25)
_dragItem = _pressItem;
@ -571,7 +589,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
InventoryItem it = _shown[i];
var cmin = new Vector2(o.X + c * Cell, o.Y + r * Cell);
var cmax = cmin + new Vector2(Cell - 2, Cell - 2);
bool sel = it.Id == _selected;
bool sel = IsPicked(it);
dl.AddRectFilled(cmin, cmax, i == hoverIdx ? CellHot : CellBg, 3);
DrawItemIcon(dl, it.Id, cmin + new Vector2(2, 2), Icon, ReferenceEquals(it, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu);
if (it.StackText.Length > 0)
@ -612,21 +630,24 @@ internal sealed partial class InventoryFace : IImGuiPanel
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
InventoryTarget? target = InventoryModel.Target;
InventoryItem? sel = SelectedItem(view);
RefreshSelectionLabels(target);
float zw = (w - 8) / 3f;
var sz = new Vector2(zw, ZoneH);
Zone("##z_equip", DropKind.Equip, PhosphorIcons.Shield, "Equip", new Vector2(p.X, p.Y), sz, 0, "",
InventoryModel.WieldAvailable, sel,
"Equip: drag an item here, or click to equip the selected item.");
Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, "Drop", new Vector2(p.X + zw + 4, p.Y), sz, 0, "",
InventoryModel.DropAvailable, sel,
"Drop on the ground: drag an item here, or click to drop the selected item.");
Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, target?.ZoneLabel ?? "Give", new Vector2(p.X + 2 * (zw + 4), p.Y), sz,
Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, _dropLabel, new Vector2(p.X + zw + 4, p.Y), sz, 0, "",
InventoryModel.DropAvailable, sel, DropTip);
Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, _giveLabel, new Vector2(p.X + 2 * (zw + 4), p.Y), sz,
target?.Id ?? 0, target?.Name ?? "", InventoryModel.GiveAvailable && target != null, sel,
target?.ZoneTip ?? "Select a creature, NPC or player in the game to give to.");
NextLine(p, ZoneH + 4);
}
private const string DropTip = "Drop on the ground: drag an item here, or click to drop the selected item(s).\n"
+ "Ctrl+click or Shift+click items to drop several.";
private void Zone(string id, DropKind kind, string glyph, string label, Vector2 pos, Vector2 size, uint targetId,
string targetName, bool enabled, InventoryItem? selected, string tip)
{
@ -646,20 +667,14 @@ internal sealed partial class InventoryFace : IImGuiPanel
dl.PopClipRect();
if (enabled)
_targets.Add(new Target { Min = pos, Max = pos + size, Kind = kind, Id = targetId, Name = targetName });
if (clicked && enabled && selected != null)
DropOn(kind, targetId, targetName, selected); // refused with a message while one waits
// Refused with a message while one waits. Equip is always the one selected item.
if (clicked && enabled && kind != DropKind.Equip && _multi.IsMulti)
DropOnSelection(kind, targetId, targetName, null);
else if (clicked && enabled && selected != null)
DropOn(kind, targetId, targetName, selected);
}
private InventoryItem? SelectedItem(InventoryView view)
{
if (_selected == 0) return null;
foreach (InventoryPack p in view.Packs)
foreach (InventoryItem it in p.Items)
if (it.Id == _selected) return it;
foreach (InventoryItem it in view.Worn)
if (it.Id == _selected) return it;
return null;
}
private InventoryItem? SelectedItem(InventoryView view) => _selected == 0 ? null : FindAny(view, _selected);
// ── Status row ──────────────────────────────────────────────────────
@ -681,6 +696,8 @@ internal sealed partial class InventoryFace : IImGuiPanel
InventoryPending? pending = InventoryModel.Pending;
InventoryResult? result = InventoryModel.LastResult;
float ty = p.Y + (statusH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
// A several-item run: its progress and Stop (a button, so outside the clip below).
if (BatchStatus(dl, p, w, statusH, ty)) return;
dl.PushClipRect(p, p + new Vector2(w, statusH), true);
if (pending != null)
{
@ -710,6 +727,11 @@ internal sealed partial class InventoryFace : IImGuiPanel
p, new Vector2(16, statusH), result.Ok ? Green : Red);
dl.AddText(new Vector2(p.X + 18, ty), result.Ok ? Green : Red, result.Text);
}
else if (_selHint.Length > 0)
{
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CheckSquare, p, new Vector2(16, statusH), Teal);
dl.AddText(new Vector2(p.X + 18, ty), Text, _selHint);
}
else if (idleView != null)
{
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Coins, p, new Vector2(16, statusH), Amber);
@ -750,7 +772,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
case DropKind.Pack:
if (slot == -2)
{
Refuse(_sort != 0 || _category != 0 || _searchText.Length > 0
Refuse(_sort != 0 || FiltersOn
? "To reorder, set Sort to Pack order and clear the search and filter."
: "The pack's order isn't known yet: log in again so the panel can learn it.");
return;
@ -802,12 +824,13 @@ internal sealed partial class InventoryFace : IImGuiPanel
}
}
/// <summary>Back to everything: no search text, no category.</summary>
/// <summary>Back to everything: no search text, no category, the attribute filter off (its rules kept).</summary>
private void ClearFilters()
{
Array.Clear(_search);
_searchText = string.Empty;
_category = 0;
SetAttrEnabled(false);
}
private void Refuse(string why)
@ -834,15 +857,23 @@ internal sealed partial class InventoryFace : IImGuiPanel
{
if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left))
{
InventoryItem? item = _dragItem;
InventoryItem? item = _dragItem, pressed = _pressItem;
bool narrow = _pressNarrow;
_dragItem = null;
_pressItem = null;
if (item == null) return;
_pressNarrow = false;
if (item == null)
{
// A plain click on one of a group, not dragged: just that item now.
if (narrow && pressed != null) _multi.Single(pressed.Id);
return;
}
ItemDragBridge.EndPopOutDrag();
Vector2 m = ImGuiNET.ImGui.GetMousePos();
foreach (Target t in _targets)
{
if (m.X < t.Min.X || m.Y < t.Min.Y || m.X >= t.Max.X || m.Y >= t.Max.Y) continue;
DropOn(t.Kind, t.Id, t.Name, item, t.Slot);
DropOnSelection(t.Kind, t.Id, t.Name, item, t.Slot);
return;
}
// Let go outside this panel: another engine panel that takes items (Item Count,
@ -852,13 +883,51 @@ internal sealed partial class InventoryFace : IImGuiPanel
}
}
private void DrawDragGhost()
/// <summary>
/// ImGui drag-and-drop payload type for one item (uint object id), published while an item is
/// dragged so other ImGui windows (RynthAi's Mini Remote slots) can accept the drop. Must
/// match MiniRemoteHud.ItemPayloadType in RynthAi.
/// </summary>
public const string ItemPayloadType = "RYNTH_INV_ITEM";
/// <summary>
/// Selects <paramref name="it"/> here and in the game, like a click in the retail inventory, so
/// "selected item" features (Mini Remote slots, item info, loot rules) see it too.
/// </summary>
private void SelectItem(InventoryItem it)
{
_selected = it.Id;
// Queued, not called inline: Draw runs inside EndScene, and AC's SetSelectedObject rebuilds
// UI elements, so it runs at the main-thread queue's drain point instead.
if (ClientHelperHooks.GetSelectedItemId() != it.Id)
AcMainThreadQueue.EnqueueSetSelectedObject(it.Id);
}
private unsafe void DrawDragGhost()
{
if (_dragItem == null) return;
var fg = ImGuiNET.ImGui.GetForegroundDrawList();
Vector2 m = ImGuiNET.ImGui.GetMousePos() - new Vector2(Icon * 0.5f, Icon * 0.5f);
DrawItemIcon(fg, _dragItem.Id, m, Icon, 0xD0FFFFFF);
DragBadge(fg, m);
ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
// A popped-out Inventory draws in its own ImGui context: the client's drop targets
// only see the drag through the bridge, which republishes it in the main context.
if (ImGuiPopOuts.InPopOutFrame)
{
ItemDragBridge.NotePopOutDrag(_dragItem.Id);
return;
}
// Re-submitted every frame of the drag (an extern source expires when it isn't); the
// ghost above is the preview, so no ImGui tooltip.
if (ImGuiNET.ImGui.BeginDragDropSource(ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip))
{
uint id = _dragItem.Id;
ImGuiNET.ImGui.SetDragDropPayload(ItemPayloadType, (IntPtr)(&id), sizeof(uint));
ImGuiNET.ImGui.EndDragDropSource();
}
}
// ── Tooltip ─────────────────────────────────────────────────────────
@ -948,7 +1017,8 @@ internal sealed partial class InventoryFace : IImGuiPanel
{
InventoryItem? it = _ctxItem;
if (it == null) { ImGuiNET.ImGui.CloseCurrentPopup(); return; }
bool idle = InventoryModel.Pending == null;
if (IsGroup(it)) { GroupMenu(view, it); return; }
bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning;
ImGuiNET.ImGui.TextDisabled(it.Name);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Use", "double-click", false, idle))
@ -985,6 +1055,13 @@ internal sealed partial class InventoryFace : IImGuiPanel
_lootAdd.Open(it.Id, it.Name, toOpenProfile: false);
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("Make a RynthAi loot rule for this item (preview first)");
if (!it.IsPack && ImGuiNET.ImGui.MenuItem("Add to item count HUD"))
UI.Data.RynthAiCommands.ApplyRemoteCommand("itemhudadd", it.Name);
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("Track how many of these you carry on RynthAi's floating item count HUD (/ra itemhud add)");
if (!it.IsPack) MiniRemoteMenu(it);
ImGuiNET.ImGui.Separator();
SelectionMenuItems(it);
if (!idle)
ImGuiNET.ImGui.TextDisabled("(an item action is waiting)");
}
@ -995,6 +1072,36 @@ internal sealed partial class InventoryFace : IImGuiPanel
}
}
/// <summary>RynthAi Mini Remote quick-use grid size (HudState.MiniRemoteSlotCount, 6 rows of 5).</summary>
private const int MiniRemoteSlots = 30, MiniRemoteColumns = 5;
/// <summary>
/// "Add to Mini Remote" submenu: first empty slot, or a numbered grid laid out like the
/// remote's own slots. RynthAi validates the item and reports the result in chat.
/// </summary>
private static void MiniRemoteMenu(InventoryItem it)
{
if (!ImGuiNET.ImGui.BeginMenu("Add to Mini Remote")) return;
if (ImGuiNET.ImGui.MenuItem("First empty slot"))
UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot", "first " + it.Id.ToString(CultureInfo.InvariantCulture));
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.TextDisabled("Or pick a slot (replaces what's there):");
for (int i = 0; i < MiniRemoteSlots; i++)
{
if (i % MiniRemoteColumns != 0) ImGuiNET.ImGui.SameLine();
string label = (i + 1).ToString("00", CultureInfo.InvariantCulture);
if (ImGuiNET.ImGui.Button(label, new Vector2(28, 0)))
{
UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot",
(i + 1).ToString(CultureInfo.InvariantCulture) + " " + it.Id.ToString(CultureInfo.InvariantCulture));
ImGuiNET.ImGui.CloseCurrentPopup();
}
}
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.TextDisabled("Tip: you can also drag the item onto a slot.");
ImGuiNET.ImGui.EndMenu();
}
// ── Split dialog ────────────────────────────────────────────────────
private void SplitDialog(InventoryView view)

View file

@ -0,0 +1,129 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/InventorySelection.cs
// The Inventory panel's multi-selection: which items are picked for a
// Drop / Give / Move of several at once. Windows-style: click picks one,
// Ctrl+click adds or removes one, Shift+click picks the run from the last
// clicked item (the anchor) in the order the grid shows them, Ctrl+Shift+click
// adds that run.
//
// Ids only (object ids), no engine state, so tools/InventorySelectionTests can
// run it. AC's render thread only (the panel's Draw); not thread-safe.
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class InventorySelection
{
private readonly HashSet<uint> _set = new();
// Picked order: a batch acts on the items in the order the player picked them.
private readonly List<uint> _order = new();
/// <summary>Where a Shift+click run starts: the last item clicked or Ctrl+clicked (0 = none).</summary>
public uint Anchor { get; private set; }
public int Count => _order.Count;
/// <summary>The picked ids, in picked order.</summary>
public IReadOnlyList<uint> Ids => _order;
/// <summary>More than one item picked: the zones and the menu act on all of them.</summary>
public bool IsMulti => _order.Count > 1;
public bool Contains(uint id) => _set.Contains(id);
public void Clear()
{
_set.Clear();
_order.Clear();
Anchor = 0;
}
/// <summary>A plain click: just <paramref name="id"/>.</summary>
public void Single(uint id)
{
Clear();
if (id == 0) return;
Add(id);
Anchor = id;
}
/// <summary>Ctrl+click: adds <paramref name="id"/>, or removes it if picked. Returns true when it is now picked.</summary>
public bool Toggle(uint id)
{
if (id == 0) return false;
Anchor = id;
if (_set.Remove(id))
{
_order.Remove(id);
return false;
}
Add(id);
return true;
}
/// <summary>
/// Shift+click: the items from the anchor to <paramref name="id"/>, both included, in the
/// order of <paramref name="shown"/>. <paramref name="additive"/> (Ctrl+Shift) keeps what is
/// already picked. With no anchor on show (another pack, a new search) it picks just
/// <paramref name="id"/>. The anchor stays where it was, so the run can be changed.
/// </summary>
public void Range<T>(IReadOnlyList<T> shown, Func<T, uint> idOf, uint id, bool additive)
{
int to = IndexOf(shown, idOf, id);
int from = Anchor == 0 ? -1 : IndexOf(shown, idOf, Anchor);
if (to < 0 || from < 0)
{
if (additive) { Add(id); Anchor = id; }
else Single(id);
return;
}
uint anchor = Anchor;
if (!additive)
{
_set.Clear();
_order.Clear();
}
int step = to >= from ? 1 : -1;
for (int i = from; ; i += step)
{
Add(idOf(shown[i]));
if (i == to) break;
}
Anchor = anchor;
}
/// <summary>Everything in <paramref name="shown"/> (the grid's current list), in its order.</summary>
public void SelectAll<T>(IReadOnlyList<T> shown, Func<T, uint> idOf)
{
Clear();
for (int i = 0; i < shown.Count; i++) Add(idOf(shown[i]));
if (_order.Count > 0) Anchor = _order[0];
}
/// <summary>Drops ids that <paramref name="exists"/> no longer finds (given, dropped, merged). True if any went.</summary>
public bool Prune(Func<uint, bool> exists)
{
int before = _order.Count;
_order.RemoveAll(id => !exists(id));
if (_order.Count == before) return false;
_set.Clear();
foreach (uint id in _order) _set.Add(id);
if (Anchor != 0 && !_set.Contains(Anchor)) Anchor = 0;
return true;
}
private void Add(uint id)
{
if (id != 0 && _set.Add(id)) _order.Add(id);
}
private static int IndexOf<T>(IReadOnlyList<T> shown, Func<T, uint> idOf, uint id)
{
for (int i = 0; i < shown.Count; i++)
if (idOf(shown[i]) == id) return i;
return -1;
}
}

View file

@ -54,6 +54,13 @@ internal sealed class ItemsFace : IImGuiPanel
ImGuiNET.ImGui.BeginChild("##items_body", new Vector2(w, Math.Max(60, Remaining(origin, size))));
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
// Above the lists, which can run long: drops entries for items sold, dropped, used up or traded.
AddSelected("##clean_missing", PhosphorIcons.Eraser + " Remove Missing", "(weapons and consumables no longer in your inventory)", ItemsCommands.CleanMissing,
"Removes listed weapons and consumables that are no longer in your inventory.\n" +
"An entry whose item is gone but with an unlisted item of the same name in your pack\n" +
"(a new stack of kits, a replacement weapon) is pointed at that item instead.\n" +
"Does nothing while your inventory is still loading. Also: /ra items clean.");
// Weapons
Section("Weapons", bw);
if (_data.Weapons.Count == 0) Empty("No weapons configured", bw);
@ -242,11 +249,12 @@ internal sealed class ItemsFace : IImGuiPanel
return result;
}
private static void AddSelected(string id, string label, string hint, Action onClick)
private static void AddSelected(string id, string label, string hint, Action onClick, string? tooltip = null)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 4);
float bw = ButtonWidth(label) + 4;
if (Button(id, label, p, new Vector2(bw, 24), Teal, BtnFill)) onClick();
if (tooltip != null) ImGuiNET.ImGui.SetItemTooltip(tooltip);
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
ImGuiNET.ImGui.GetWindowDrawList().AddText(f9, f9.FontSize, new Vector2(p.X + bw + 8, p.Y + (24 - f9.FontSize) * 0.5f), Mute, hint);
NextLine(new Vector2(p.X - 4, p.Y - 4), 32);

View file

@ -1,14 +1,28 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/MiniRemoteFace.cs
// The Mini Remote: a small grid of slots the player fills with items; a click
// uses that item. Engine only, ImGui only. (An idea from Silentkelpie's rynth
// PR #1, done as an engine face.)
// The Mini Remote: one window for the quick-use item slots, whoever draws them.
//
// With RynthAi loaded it hosts RynthAi's Mini Remote (session rates, target,
// summon, item slots, toggles, bank, rebuff, Translate, Guardian and its
// Options menu, plus on ILT worlds the tabs Character, Quests, Pets, Banking,
// Gear and Games that were the ILT Hub), drawn by the plugin through
// RynthPluginRenderEmbed ("miniremote-window"). The window fits itself to what
// the plugin asks for whenever that changes (another tab, a section shown or
// hidden, bigger or smaller boxes);
// a resize by hand holds until then. While this window shows it, RynthAi keeps
// its own floating copy hidden, so there is one Mini Remote, not two.
//
// Without RynthAi (not loaded, too old for the surface, not logged in yet,
// popped out with a RynthAi older than 0.5.38, which can't draw in a pop-out's
// context, or its embed failed) it is the engine's own grid (an idea from Silentkelpie's
// rynth PR #1, done as an engine face):
// slots the item's icon and carried count; an empty slot shows +
// click uses the slot's item (the same object if still carried, else a
// stack with its name); on an empty slot, puts the selected
// inventory item there
// right Set to the selected item, Clear, More / Fewer slots
// right Set to the selected item, Clear, More / Fewer slots,
// Bigger / Smaller boxes
// ctrl+wheel over the slots: bigger / smaller boxes
// drop drag an item from the game's inventory (or the Inventory panel)
// onto a slot to put it there (UiDropTargets, one target a slot)
// status the use waiting for the server, or how the last one ended
@ -16,7 +30,8 @@
// A click never calls AC from the render thread: it posts an InventoryModel
// Use request, which AC's main thread sends at its next tick behind the
// client's own item gate (one item action at a time; a click while one waits
// is refused, not queued). Slots are saved per character (ItemHudStore).
// is refused, not queued). Slots and box size are saved per character
// (ItemHudStore).
// ============================================================================
using System;
@ -24,6 +39,7 @@ using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Plugins;
using RynthCore.Engine.UI.Data;
using RynthCore.Engine.UI.ScriptWindows;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
@ -42,7 +58,12 @@ internal sealed class MiniRemoteFace : IImGuiPanel
ItemHudStore.EnsureLoadQueued();
}
private const float Slot = 36f, Gap = 4f, IconSize = 32f, StatusH = 18f;
/// <summary>The RynthAi surface for this window (NUL-terminated for the export).</summary>
private static ReadOnlySpan<byte> Surface => "miniremote-window\0"u8;
private const float Gap = 4f, StatusH = 18f;
/// <summary>Pixels a Ctrl+wheel notch or a Bigger / Smaller menu click changes the box edge by.</summary>
private const int SlotSizeStep = 4;
private const string MenuId = "##miniremote_menu";
private static readonly string[] DropKeys = BuildDropKeys();
@ -66,34 +87,144 @@ internal sealed class MiniRemoteFace : IImGuiPanel
private uint[] _slotItem = Array.Empty<uint>();
private string[] _slotCount = Array.Empty<string>();
// RynthAi hosting: it drew last frame; its export failed this session; the size it last asked for.
private bool _hosted;
private bool _embedOff;
private Vector2 _lastWant;
// The engine grid: the box size it last fitted the window to (0 = fit on the next frame).
private int _fittedSlotSize;
// The window size last requested (logical units), so the same request isn't repeated.
private Vector2 _requested;
public void OnShown()
{
ItemHudStore.EnsureLoadQueued();
InventoryModel.Subscribe();
_lastWant = Vector2.Zero;
_fittedSlotSize = 0;
_requested = Vector2.Zero;
}
public void OnHidden()
{
InventoryModel.Unsubscribe();
_menuSlot = -1;
_hosted = false;
}
public void Draw()
{
float w = Begin(out Vector2 origin, out Vector2 size);
if (DrawRynthAi(w, origin, size))
{
End(origin, size);
return;
}
InventoryView view = InventoryModel.Current;
HudItem[] items = _items.Get(view);
ItemHudCharacter data = ItemHudStore.Current;
bool ready = ItemHudStore.Loaded && ItemHudStore.HasCharacter && view.PlayerId != 0;
Resolve(data, items);
float gridH = Math.Max(Slot, Remaining(origin, size) - StatusH - GripOverlap());
float haveH = Remaining(origin, size);
float gridH = Math.Max(data.SlotSize, haveH - StatusH - GripOverlap());
DrawGrid(data, items, w, gridH, ready);
DrawStatus(ready);
FitGrid(data, w, haveH);
End(origin, size);
DrawMenu(data, items);
}
// ── RynthAi's Mini Remote ───────────────────────────────────────────
/// <summary>
/// Lets RynthAi draw its Mini Remote here. True when it did (or is mid-layout after
/// drawing last frame); false means the engine grid draws instead. The plugin draws
/// nothing when it declines, and the auto-height child it would have filled stays
/// empty, so the grid can take the space the same frame.
/// </summary>
private bool DrawRynthAi(float w, Vector2 origin, Vector2 size)
{
if (_embedOff) return false;
float haveH = Remaining(origin, size);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
bool open = ImGuiNET.ImGui.BeginChild("##mr_rynthai", new Vector2(w, 0), ImGuiChildFlags.AutoResizeY,
ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoScrollbar);
ImGuiNET.ImGui.PopStyleVar();
int result = PluginManager.EmbedNotReady;
Vector2 want = Vector2.Zero;
try
{
if (open)
{
// The plugin's widgets use the default UI font, as in its floating Mini Remote.
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
try { result = PluginManager.RenderEmbed("RynthAi", Surface, new Vector2(w, Math.Max(1f, haveH)), out want); }
finally { ImGuiNET.ImGui.PopFont(); }
}
}
finally { ImGuiNET.ImGui.EndChild(); }
if (result == PluginManager.EmbedFailed) _embedOff = true;
// A clipped child (open == false) draws nothing; keep the last frame's answer so the
// window doesn't flick to the engine grid for that frame.
_hosted = open ? result == PluginManager.EmbedDrawn : _hosted && !_embedOff;
if (!_hosted) { _lastWant = Vector2.Zero; return false; }
if (result == PluginManager.EmbedDrawn && want.X > 0 && want.Y > 0
&& Vector2.DistanceSquared(want, _lastWant) > 1f)
{
_lastWant = want;
// + the grip's reach, so the plugin's last row isn't under the resize grip.
FitWindow(new Vector2(want.X, want.Y + GripOverlap()), w, haveH);
}
return true;
}
// ── Window fit ──────────────────────────────────────────────────────
/// <summary>
/// Sizes the window so the body area (<paramref name="haveW"/> × <paramref name="haveH"/>
/// now) becomes <paramref name="wantPx"/>; never taller than the screen. Docked only:
/// popped out the OS window keeps its size, as other faces do (RynthNavArrowFace).
/// </summary>
private void FitWindow(Vector2 wantPx, float haveW, float haveH)
{
if (ImGuiPopOuts.InPopOutFrame) return;
float place = ImGuiPanelHost.PlacementScale();
float extraW = ImGuiNET.ImGui.GetWindowWidth() - haveW; // anything around the body
float extraH = ImGuiNET.ImGui.GetWindowHeight() - haveH;
var want = new Vector2(MathF.Ceiling((wantPx.X + extraW) / place), MathF.Ceiling((wantPx.Y + extraH) / place));
float screenH = ImGuiNET.ImGui.GetIO().DisplaySize.Y / place;
if (screenH > 1) want.Y = MathF.Min(want.Y, screenH - 8);
if (Vector2.DistanceSquared(want, _requested) < 1f) return;
_requested = want;
ImGuiPanelHost.RequestSize(Title, want);
}
/// <summary>
/// The engine grid: after the box size changes (and on the first frame shown), fits the
/// window to the slots at the same number of columns, plus the status line.
/// </summary>
private void FitGrid(ItemHudCharacter data, float w, float haveH)
{
if (_fittedSlotSize == data.SlotSize || !ItemHudStore.Loaded) return;
bool first = _fittedSlotSize == 0;
int oldSlot = first ? data.SlotSize : _fittedSlotSize;
_fittedSlotSize = data.SlotSize;
// First show: keep the window the player left (only a box-size change refits it).
if (first) return;
int cols = Math.Max(1, (int)((w + Gap) / (oldSlot + Gap)));
int rows = (data.Slots.Length + cols - 1) / cols;
float slot = data.SlotSize;
var body = new Vector2(cols * (slot + Gap) - Gap, rows * (slot + Gap) - Gap + StatusH + GripOverlap());
FitWindow(body, w, haveH);
}
// ── Engine grid ─────────────────────────────────────────────────────
private void Resolve(ItemHudCharacter data, HudItem[] items)
{
if (ReferenceEquals(data, _resolvedFor) && _resolvedItemsVersion == _items.Version) return;
@ -112,20 +243,20 @@ internal sealed class MiniRemoteFace : IImGuiPanel
}
}
// ── Grid ────────────────────────────────────────────────────────────
private void DrawGrid(ItemHudCharacter data, HudItem[] items, float w, float h, bool ready)
{
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
int cols = Math.Max(1, (int)((w + Gap) / (Slot + Gap)));
float slot = data.SlotSize;
float iconSize = slot - 4f;
int cols = Math.Max(1, (int)((w + Gap) / (slot + Gap)));
bool dragging = ready && UiDropTargets.AnyDragInProgress;
int clicked = -1;
for (int i = 0; i < data.Slots.Length; i++)
{
var p = new Vector2(start.X + (i % cols) * (Slot + Gap), start.Y + (i / cols) * (Slot + Gap));
var max = p + new Vector2(Slot, Slot);
var p = new Vector2(start.X + (i % cols) * (slot + Gap), start.Y + (i / cols) * (slot + Gap));
var max = p + new Vector2(slot, slot);
RemoteSlot? s = data.Slots[i];
// One drop target a slot, so the item lands where it was let go.
@ -135,7 +266,7 @@ internal sealed class MiniRemoteFace : IImGuiPanel
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.PushID(i);
if (ImGuiNET.ImGui.InvisibleButton("##slot", new Vector2(Slot, Slot))) clicked = i;
if (ImGuiNET.ImGui.InvisibleButton("##slot", new Vector2(slot, slot))) clicked = i;
bool hot = ImGuiNET.ImGui.IsItemHovered();
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _menuSlot = i; _openMenu = true; }
ImGuiNET.ImGui.PopID();
@ -145,20 +276,20 @@ internal sealed class MiniRemoteFace : IImGuiPanel
dl.AddRect(p, max, dropHot || dragging ? Teal : BtnBord, 3);
uint id = s != null && i < _slotItem.Length ? _slotItem[i] : 0;
Vector2 ip = p + new Vector2((Slot - IconSize) * 0.5f, (Slot - IconSize) * 0.5f);
Vector2 ip = p + new Vector2((slot - iconSize) * 0.5f, (slot - iconSize) * 0.5f);
if (s == null)
{
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Plus, p, new Vector2(Slot, Slot), Faded(Mute));
if (hot) ImGuiNET.ImGui.SetItemTooltip("Empty slot: click to put the selected inventory item here, or drag an item onto it.");
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Plus, p, new Vector2(slot, slot), Faded(Mute));
if (hot) ImGuiNET.ImGui.SetItemTooltip("Empty slot: click to put the selected inventory item here, or drag an item onto it.\nCtrl+wheel: bigger / smaller boxes.");
continue;
}
if (id != 0 && ScriptIcons.TryGet(ScriptIconKind.Object, id, out IntPtr tex))
dl.AddImage(tex, ip, ip + new Vector2(IconSize, IconSize));
dl.AddImage(tex, ip, ip + new Vector2(iconSize, iconSize));
else
{
string initial = s.Name.Length > 0 ? s.Name[..1].ToUpperInvariant() : "?";
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(initial);
dl.AddText(p + (new Vector2(Slot, Slot) - ts) * 0.5f, Faded(Text), initial);
dl.AddText(p + (new Vector2(slot, slot) - ts) * 0.5f, Faded(Text), initial);
}
string count = _slotCount[i];
if (count.Length > 0)
@ -174,13 +305,30 @@ internal sealed class MiniRemoteFace : IImGuiPanel
: $"{s.Name} ({count switch { "" => "1", _ => count }} carried)\nClick to use. Right-click for options.");
}
int rows = (data.Slots.Length + cols - 1) / cols;
float shownH = Math.Min(h, rows * (slot + Gap));
ImGuiNET.ImGui.SetCursorScreenPos(start);
ImGuiNET.ImGui.Dummy(new Vector2(w, Math.Min(h, rows * (Slot + Gap))));
ImGuiNET.ImGui.Dummy(new Vector2(w, shownH));
// Ctrl+wheel over the slots: bigger / smaller boxes (saved per character).
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
if (ready && io.KeyCtrl && io.MouseWheel != 0
&& ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows)
&& ImGuiNET.ImGui.IsMouseHoveringRect(start, start + new Vector2(w, shownH)))
ResizeSlots(io.MouseWheel > 0 ? SlotSizeStep : -SlotSizeStep);
if (clicked >= 0 && ready) Click(data, items, clicked);
else if (clicked >= 0) ShowMessage(ItemHudStore.Loaded ? "Waiting for your character..." : "Loading...", Amber);
}
/// <summary>Grows (+) or shrinks (-) the boxes by <paramref name="delta"/> pixels, within the saved range.</summary>
private void ResizeSlots(int delta)
{
if (!ItemHudStore.Update(d => d.WithSlotSize(d.SlotSize + delta), out string why))
ShowMessage(why, Amber);
else
ShowMessage($"Box size {ItemHudStore.Current.SlotSize} px.", Mute);
}
private void Click(ItemHudCharacter data, HudItem[] items, int i)
{
RemoteSlot? s = data.Slots[i];
@ -228,7 +376,7 @@ internal sealed class MiniRemoteFace : IImGuiPanel
else if (pending != null) { text = pending.WaitingForGame ? "Waiting for the game: " + pending.Label : pending.Label + "..."; color = Teal; }
else if (last != null && nowTicks - last.AtTicks < System.Diagnostics.Stopwatch.Frequency * 4) { text = last.Text; color = last.Ok ? Green : Amber; }
else if (!ready) { text = ItemHudStore.Loaded ? "Waiting for your character..." : "Loading..."; color = Mute; }
else { text = "Click: use. Right-click: options."; color = Faded(Mute); }
else { text = "Click: use. Right-click: options. Ctrl+wheel: box size."; color = Faded(Mute); }
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float w = ImGuiNET.ImGui.GetContentRegionAvail().X - BodyGripRoom();
@ -273,6 +421,14 @@ internal sealed class MiniRemoteFace : IImGuiPanel
ItemHudStore.Update(d => d.WithSlotCount(d.Slots.Length + 4), out _);
if (ImGuiNET.ImGui.MenuItem("Fewer slots (drops the last 4)", "", false, n > ItemHudCharacter.MinSlots))
ItemHudStore.Update(d => d.WithSlotCount(d.Slots.Length - 4), out _);
ImGuiNET.ImGui.Separator();
int px = data.SlotSize;
if (ImGuiNET.ImGui.MenuItem($"Bigger boxes ({px} px now)", "Ctrl+wheel up", false, px < ItemHudCharacter.MaxSlotSize))
ResizeSlots(SlotSizeStep);
if (ImGuiNET.ImGui.MenuItem("Smaller boxes", "Ctrl+wheel down", false, px > ItemHudCharacter.MinSlotSize))
ResizeSlots(-SlotSizeStep);
if (ImGuiNET.ImGui.MenuItem("Default box size", "", false, px != ItemHudCharacter.DefaultSlotSize))
ResizeSlots(ItemHudCharacter.DefaultSlotSize - px);
ImGuiNET.ImGui.EndPopup();
}
}

View file

@ -1,21 +1,28 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/NavFace.cs
// ImGui face of the Nav panel (UI/Panels/NavPanel.cs): active nav + status,
// Start/Stop, route type and insert mode, Add Waypoint / Portal (not yet) /
// Recall / Clear / Save / Dungeon Patrol, a chat waypoint, Save As, the nav
// file picker, the nav point reach (RynthAi's FollowNavMin, the same row as
// Settings > Navigation), and the waypoint list (click selects the insert
// point, X deletes, => marks the active one).
// Start/Stop, route type and insert mode, the Breadcrumbs and Route overlay
// toggles, Add Waypoint / Portal (selected object) /
// Recall / Clear / Save / Dungeon Patrol, the route editor (move / duplicate /
// delete / set active / move here on the selection; nearest, reverse, snap to
// path, point at selection, pause, simplify; recording and trail -> route),
// a chat waypoint, Save As, the nav file picker, the nav point reach
// (RynthAi's FollowNavMin, the same row as Settings > Navigation), and the
// waypoint list (click selects, Ctrl/Shift-click multi-selects, double-click
// sets active, right-click edits, X or Delete deletes, => marks the active one).
//
// Data: UiSources.Nav (hub) and NavCommands. Button actions change a private
// copy at once; the plugin applies commands immediately, so the next
// snapshot (requested right after) replaces the copy. The reach row reads
// UiSources.Settings and saves through SettingsCommands, like the Settings face.
// snapshot (requested right after) replaces the copy. Edits send indices into
// the route this face shows, so the selection is remapped locally as the copy
// changes. The reach row reads UiSources.Settings and saves through
// SettingsCommands, like the Settings face.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
@ -28,7 +35,7 @@ internal sealed class NavFace : IImGuiPanel
public const string Title = "Nav";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(400, 560), new Vector2(360, 380), EdgeToEdge: true),
new PanelSpec(new Vector2(400, 680), new Vector2(360, 440), EdgeToEdge: true),
() => new NavFace());
private static readonly string[] Actions =
@ -38,12 +45,30 @@ internal sealed class NavFace : IImGuiPanel
};
private const string StartNav = PhosphorIcons.Play + " Start Navigation", StopNav = PhosphorIcons.Stop + " Stop Navigation";
private const string AddChat = PhosphorIcons.Plus + " Add Chat", SaveAs = PhosphorIcons.FloppyDisk + " Save As";
private static readonly bool[] ActionsEnabled = { true, false, true, true, true, true };
// Route editor rows. Edit acts on the selected waypoints; Tools on the route.
private static readonly string[] EditActions =
{
PhosphorIcons.ArrowUp + " Up", PhosphorIcons.ArrowDown + " Down", PhosphorIcons.Copy + " Duplicate",
PhosphorIcons.Trash + " Delete", PhosphorIcons.Target + " Set Active", PhosphorIcons.Crosshair + " Move Here",
};
private static readonly string[] ToolActions =
{
PhosphorIcons.NavigationArrow + " Nearest", PhosphorIcons.ArrowsClockwise + " Reverse", PhosphorIcons.Path + " Snap to Path",
PhosphorIcons.MapPin + " Point at Selected", PhosphorIcons.Hourglass + " Add Pause", PhosphorIcons.Scissors + " Simplify",
};
private static readonly string[] RowMenu =
{ "Set Active", "Move Here", "Move Up", "Move Down", "Duplicate", "Delete" };
private const string FromTrail = PhosphorIcons.Footprints + " Route from Trail...";
private readonly bool[] _editEnabled = new bool[6];
private NavPayload _data = new();
private long _seenVersion = -1;
private readonly List<string> _pointText = new();
private int _selected = -1, _addMode;
// _selected is the focus row (insert point, chat editing); _multi is every selected row,
// always containing _selected when it is set. _anchor starts Shift-click ranges.
private int _selected = -1, _anchor = -1, _addMode;
private readonly HashSet<int> _multi = new();
private bool _typing;
private string _routeLabel = "Route: Once", _insertLabel = "Insert: End", _activeLabel = "Active Nav: None (Unsaved)";
private string _fileLabel = "Select nav file...";
@ -130,13 +155,32 @@ internal sealed class NavFace : IImGuiPanel
});
NextLine(p, 26);
// Breadcrumbs | Route overlay (RynthAi's NavOverlaySettings; saved per character)
p = ImGuiNET.ImGui.GetCursorScreenPos();
if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half,
"Record the trail you walk and draw it on the ground (/ra navtrail on|off).\nTurning it off hides the trail; /ra navtrail clear wipes it."))
{
bool on = !_data.TrackBreadcrumbs;
NavCommands.Send(new NavCmd { Cmd = "setBreadcrumbs", On = on });
_data.TrackBreadcrumbs = on;
}
if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half,
"Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\nto the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate."))
{
bool on = !_data.ShowRouteOverlay;
NavCommands.Send(new NavCmd { Cmd = "setRouteOverlay", On = on });
_data.ShowRouteOverlay = on;
}
NextLine(p, 26);
typing |= ReachRow(w);
// Actions
int action = WrapButtons("nav_act", Actions, w, 24, ActionsEnabled);
int action = WrapButtons("nav_act", Actions, w, 24);
switch (action)
{
case 0: NavCommands.Send(new NavCmd { Cmd = "addWaypoint", AddMode = _addMode, InsertAt = _selected }); break;
case 1: NavCommands.Send(new NavCmd { Cmd = "addPortal", AddMode = _addMode, InsertAt = _selected }); break;
case 2:
_picker.Open(ImGuiNET.ImGui.GetIO().MousePos, NavCommands.RecallLabels, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "addRecall", SpellId = NavCommands.RecallIds[i], AddMode = _addMode, InsertAt = _selected }));
@ -144,13 +188,15 @@ internal sealed class NavFace : IImGuiPanel
case 3:
NavCommands.Send(new NavCmd { Cmd = "clearRoute" });
_data.Points.Clear();
_selected = -1;
ClearSelection();
RebuildPointText();
break;
case 4: NavCommands.Send(new NavCmd { Cmd = "saveRoute" }); break;
case 5: NavCommands.Send(new NavCmd { Cmd = "dunPatrol" }); break;
}
RouteEditor(w);
// Chat waypoint: sent as if typed when the route reaches it. Selecting an
// existing chat waypoint loads its command here; Update saves the edit.
bool chatSelected = _selected >= 0 && _selected < _data.Points.Count
@ -230,6 +276,9 @@ internal sealed class NavFace : IImGuiPanel
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1));
ImGuiNET.ImGui.BeginChild("##nav_points", new Vector2(w, listH));
Waypoints(ImGuiNET.ImGui.GetContentRegionAvail().X);
if (!typing && _multi.Count > 0 && ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Delete, false)
&& (ImGuiNET.ImGui.IsWindowHovered() || ImGuiNET.ImGui.IsWindowFocused()))
DeleteSelected();
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
@ -239,6 +288,18 @@ internal sealed class NavFace : IImGuiPanel
_picker.Draw();
}
/// <summary>
/// A checkbox-style toggle button: ticked box and teal text when on, empty box and muted
/// text when off. Returns true when clicked (the caller flips the value).
/// </summary>
private static bool OverlayToggle(string id, string label, bool on, Vector2 pos, float width, string tooltip)
{
string text = (on ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " " + label;
bool clicked = Button(id, text, pos, new Vector2(width, 22), on ? Teal : Mute, BtnFill, leftAlign: true);
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tooltip);
return clicked;
}
/// <summary>
/// Nav point reach (yd): how close nav gets to each nav point before moving on. Label,
/// [-] value [+]; the typed value commits on Enter or when the box loses focus. Saves the
@ -303,20 +364,24 @@ internal sealed class NavFace : IImGuiPanel
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const float h = 22;
if (p.Y + h < clipMin.Y || p.Y > clipMax.Y) { ImGuiNET.ImGui.Dummy(new Vector2(w, h)); continue; }
bool active = i == _data.ActiveNavIndex, selected = i == _selected;
bool active = i == _data.ActiveNavIndex, selected = _multi.Contains(i);
ImGuiNET.ImGui.PushID(i);
// Row click selects (drawn first so the X button on top wins).
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.SetNextItemAllowOverlap(); // the X button on top gets its clicks
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) _selected = i;
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) ClickRow(i);
if (ImGuiNET.ImGui.IsItemHovered() && ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
SetActive(i);
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
if (!selected) SelectOnly(i);
_picker.Open(ImGuiNET.ImGui.GetIO().MousePos, RowMenu, -1, RowMenuPick, width: 140);
}
dl.AddRectFilled(p, p + new Vector2(w, h), selected ? Selected : i % 2 == 0 ? PanelBg : RowAlt);
if (IconButton("##del", PhosphorIcons.X, new Vector2(p.X + 2, p.Y + 2), new Vector2(18, 18), Text, DeleteBg, font: UiFont.Ui11))
{
NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i });
if (_selected == i) _selected = -1;
else if (_selected > i) _selected--;
_data.Points.RemoveAt(i);
RebuildPointText();
RemoveLocal(new HashSet<int> { i });
ImGuiNET.ImGui.PopID();
return;
}
@ -331,6 +396,216 @@ internal sealed class NavFace : IImGuiPanel
}
}
/// <summary>
/// Route editor: Edit row (on the selection), Tools row (on the route), the Record toggle
/// with "Route from Trail...", and the last edit's result. Picker-backed buttons (pause,
/// simplify, trail) double as the confirmation for edits that can't be undone.
/// </summary>
private void RouteEditor(float w)
{
int n = _multi.Count, count = _data.Points.Count;
bool one = n == 1 && _selected >= 0;
_editEnabled[0] = n > 0 && _multi.Min() > 0;
_editEnabled[1] = n > 0 && _multi.Max() < count - 1;
_editEnabled[2] = _editEnabled[3] = n > 0;
_editEnabled[4] = _editEnabled[5] = one;
Label(n > 1 ? $"Edit ({n} selected)" : "Edit", Mute);
switch (WrapButtons("nav_edit", EditActions, w, 22, _editEnabled))
{
case 0: MoveSelected(-1); break;
case 1: MoveSelected(+1); break;
case 2: DuplicateSelected(); break;
case 3: DeleteSelected(); break;
case 4: SetActive(_selected); break;
case 5: NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break;
}
Vector2 at = ImGuiNET.ImGui.GetIO().MousePos;
switch (WrapButtons("nav_tools", ToolActions, w, 22))
{
case 0: NavCommands.Send(new NavCmd { Cmd = "nearestActive" }); break;
case 1:
if (count < 2) break;
NavCommands.Send(new NavCmd { Cmd = "reverseRoute" });
ReverseLocal();
break;
case 2: NavCommands.Send(new NavCmd { Cmd = "snapToPath" }); break;
case 3: NavCommands.Send(new NavCmd { Cmd = "addPointAtSelected", AddMode = _addMode, InsertAt = _selected }); break;
case 4:
_picker.Open(at, NavCommands.PauseLabels, -1, i => NavCommands.Send(new NavCmd
{ Cmd = "addPause", Seconds = NavCommands.PauseSeconds[i], AddMode = _addMode, InsertAt = _selected }), width: 140);
break;
case 5:
_picker.Open(at, NavCommands.SimplifyLabels, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "simplifyRoute", Yards = NavCommands.SimplifyYards[i] }), width: 300);
break;
}
// Record | Route from Trail...
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float half = (w - 4) / 2;
if (OverlayToggle("##record", "Record route", _data.IsRecording, p, half,
"Add a point every few yards as you walk, and portal steps as you use portals\n(/ra navrec on|off). Points go into the current route."))
{
bool on = !_data.IsRecording;
NavCommands.Send(new NavCmd { Cmd = "setRecording", On = on });
_data.IsRecording = on;
}
Vector2 tp = new(p.X + half + 4, p.Y);
if (Button("##fromtrail", FromTrail, tp, new Vector2(half, 22), Text, BtnFill, enabled: _data.TrailPoints >= 2))
_picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300);
if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGuiNET.ImGui.SetTooltip(_data.TrailPoints >= 2
? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed."
: "Turn on Breadcrumbs and walk a while to build a trail.");
NextLine(p, 26);
if (_data.EditStatus.Length > 0) Label(_data.EditStatus, Amber);
}
/// <summary>Plain click selects one row, Ctrl toggles a row, Shift selects from the anchor.</summary>
private void ClickRow(int i)
{
var io = ImGuiNET.ImGui.GetIO();
if (io.KeyShift && _anchor >= 0)
{
if (!io.KeyCtrl) _multi.Clear();
for (int k = Math.Min(_anchor, i); k <= Math.Max(_anchor, i); k++) _multi.Add(k);
_selected = i;
}
else if (io.KeyCtrl)
{
if (!_multi.Remove(i)) { _multi.Add(i); _selected = i; }
else if (_selected == i) _selected = _multi.Count > 0 ? _multi.Min() : -1;
_anchor = i;
}
else SelectOnly(i);
}
private void SelectOnly(int i)
{
_multi.Clear();
_multi.Add(i);
_selected = _anchor = i;
}
private void ClearSelection()
{
_multi.Clear();
_selected = _anchor = -1;
}
private List<int> SelectedIndices()
{
var list = new List<int>(_multi);
list.Sort();
return list;
}
private void RowMenuPick(int item)
{
switch (item)
{
case 0: if (_selected >= 0) SetActive(_selected); break;
case 1: if (_selected >= 0) NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break;
case 2: MoveSelected(-1); break;
case 3: MoveSelected(+1); break;
case 4: DuplicateSelected(); break;
case 5: DeleteSelected(); break;
}
}
private void SetActive(int i)
{
if (i < 0 || i >= _data.Points.Count) return;
NavCommands.Send(new NavCmd { Cmd = "setActive", Index = i });
_data.ActiveNavIndex = i;
}
/// <summary>Moves the selected rows one slot, the way the plugin does (NavRouteEditing.Move).</summary>
private void MoveSelected(int delta)
{
if (_multi.Count == 0) return;
NavCommands.Send(new NavCmd { Cmd = "movePoints", Indices = SelectedIndices(), Delta = delta });
var pts = _data.Points;
var sel = new HashSet<NavPoint>();
foreach (int i in _multi) sel.Add(pts[i]);
NavPoint? focus = _selected >= 0 ? pts[_selected] : null, anchor = _anchor >= 0 && _anchor < pts.Count ? pts[_anchor] : null;
if (delta < 0)
{
for (int i = 1; i < pts.Count; i++)
if (sel.Contains(pts[i]) && !sel.Contains(pts[i - 1])) (pts[i - 1], pts[i]) = (pts[i], pts[i - 1]);
}
else
{
for (int i = pts.Count - 2; i >= 0; i--)
if (sel.Contains(pts[i]) && !sel.Contains(pts[i + 1])) (pts[i + 1], pts[i]) = (pts[i], pts[i + 1]);
}
_multi.Clear();
for (int i = 0; i < pts.Count; i++) if (sel.Contains(pts[i])) _multi.Add(i);
_selected = focus != null ? pts.IndexOf(focus) : -1;
_anchor = anchor != null ? pts.IndexOf(anchor) : _selected;
RebuildPointText();
}
/// <summary>Each selected row gets a copy right after it (as the plugin does); the copies end up selected.</summary>
private void DuplicateSelected()
{
if (_multi.Count == 0) return;
NavCommands.Send(new NavCmd { Cmd = "duplicatePoints", Indices = SelectedIndices() });
var result = new List<NavPoint>(_data.Points.Count + _multi.Count);
var copies = new HashSet<int>();
for (int i = 0; i < _data.Points.Count; i++)
{
NavPoint pt = _data.Points[i];
result.Add(pt);
if (!_multi.Contains(i)) continue;
copies.Add(result.Count);
result.Add(new NavPoint { Type = pt.Type, Desc = pt.Desc, Text = pt.Text, NS = pt.NS, EW = pt.EW, Z = pt.Z });
}
_data.Points = result;
_multi.Clear();
_multi.UnionWith(copies);
_selected = _anchor = _multi.Count > 0 ? _multi.Min() : -1;
RebuildPointText();
}
private void DeleteSelected()
{
if (_multi.Count == 0) return;
NavCommands.Send(new NavCmd { Cmd = "deletePoints", Indices = SelectedIndices() });
RemoveLocal(new HashSet<int>(_multi));
}
/// <summary>Drops rows from the local copy and shifts the selection past them.</summary>
private void RemoveLocal(HashSet<int> removed)
{
int Shift(int i) { int s = 0; foreach (int r in removed) if (r < i) s++; return i - s; }
var keep = new List<int>();
foreach (int i in _multi) if (!removed.Contains(i)) keep.Add(Shift(i));
_selected = _selected >= 0 && !removed.Contains(_selected) ? Shift(_selected) : -1;
_anchor = _anchor >= 0 && !removed.Contains(_anchor) ? Shift(_anchor) : _selected;
_multi.Clear();
_multi.UnionWith(keep);
if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min();
for (int i = _data.Points.Count - 1; i >= 0; i--) if (removed.Contains(i)) _data.Points.RemoveAt(i);
RebuildPointText();
}
private void ReverseLocal()
{
int last = _data.Points.Count - 1;
_data.Points.Reverse();
var flipped = new List<int>();
foreach (int i in _multi) flipped.Add(last - i);
_multi.Clear();
_multi.UnionWith(flipped);
if (_selected >= 0) _selected = last - _selected;
if (_anchor >= 0) _anchor = last - _anchor;
RebuildPointText();
}
private void TakeSnapshot()
{
var snap = UiSources.Nav.Current;
@ -338,7 +613,11 @@ internal sealed class NavFace : IImGuiPanel
_seenVersion = snap.Version;
_data = snap.Value.Clone();
_navFiles = _data.NavFiles.ToArray();
if (_selected >= _data.Points.Count) _selected = -1;
int count = _data.Points.Count;
_multi.RemoveWhere(i => i >= count);
if (_selected >= count) _selected = -1;
if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min();
if (_anchor >= count) _anchor = _selected;
RebuildPointText();
UpdateLabels();
}

View file

@ -210,7 +210,7 @@ internal sealed unsafe class LogFace : IImGuiPanel
}
}
/// <summary>Tracker: nine session-stat rows over an adjustable-opacity background.</summary>
/// <summary>Tracker: the session-stat rows (TrackerSource) over an adjustable-opacity background.</summary>
internal sealed class TrackerFace : IImGuiPanel
{
private static readonly Vector4 TitleColor = RynthTheme.Vec(0xFFE6B450);
@ -275,6 +275,10 @@ internal sealed class TrackerFace : IImGuiPanel
float rowRight = ImGuiNET.ImGui.GetCursorPosX() + ImGuiNET.ImGui.GetContentRegionAvail().X;
if (ImGuiNET.ImGui.GetCursorScreenPos().Y + rowH > gripTop) rowRight -= grip;
ImGuiNET.ImGui.TextColored(LabelColor, labels[i]);
if (labels[i].StartsWith("Pass", StringComparison.Ordinal))
ImGuiNET.ImGui.SetItemTooltip("Luminance that reached your bank without a \"You've banked\" line: your vassals' pass-up.\nFellowship and Zone Share splits arrive the same silent way and are included.");
else if (labels[i] == "Lum/5m")
ImGuiNET.ImGui.SetItemTooltip("Luminance earned in the last five minutes.");
string value = values != null && i < values.Length ? values[i] : "—";
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono9));
float w = ImGuiNET.ImGui.CalcTextSize(value).X;

View file

@ -460,11 +460,10 @@ internal sealed class RadarFace : IImGuiPanel
_tipLabel = m.Label;
_tipDistance = d;
_tipPct = pct;
// A label is the object's name; the kinds a name alone doesn't tell apart say what they are.
// A label is the object's name; the kind always follows it, so a dot says which show box
// in the settings hides it (a fellow is not a "Player", your kill's corpse not a "Corpse").
string name = string.IsNullOrEmpty(m.Label) ? RadarKind.Name(m.Kind)
: m.Kind is RadarKind.Fellow or RadarKind.Pet or RadarKind.Vendor or RadarKind.OwnCorpse or RadarKind.Player
? m.Label + " (" + RadarKind.Name(m.Kind) + ")"
: m.Label!;
: m.Label + " (" + RadarKind.Name(m.Kind) + ")";
var inv = System.Globalization.CultureInfo.InvariantCulture;
_tipText = name + "\n" + d.ToString(inv) + " yd"
+ (pct >= 0 ? " " + pct.ToString(inv) + "%" : "");
@ -572,6 +571,9 @@ internal sealed class RadarFace : IImGuiPanel
AvaloniaOverlay.RadarCtrlGatedClickThrough = RadarSettingsStore.CtrlGatedClickThrough;
RadarSettingsStore.Save();
}
// The gear toggles this window too; Close is the obvious way out (changes are already saved).
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.Button("Close")) _settingsOpen = false;
ImGuiNET.ImGui.PopFont();
}
ImGuiNET.ImGui.End();
@ -590,16 +592,16 @@ internal sealed class RadarFace : IImGuiPanel
private static readonly string[] KindTips =
{
"Creatures you can attack.",
"Creatures you can't attack (townsfolk, quest givers).",
"Creatures you can attack.\nHover a dot on the radar: its tooltip names the box that shows it.",
"Creatures you can't attack (townsfolk, quest givers).\nShopkeepers have their own box (Vendors).",
"Portals, with their destination.",
"Doors, gates and hatches.",
"Other players.",
"Other players, outside your fellowship.\nPlayers in your fellowship have their own box (Fellows).",
"Players in your fellowship.",
"Your own combat pet.",
"Shopkeepers.",
"Corpses you can't loot (or not identified yet: selecting one tells).",
"Corpses you may loot: your kills, your fellows' kills and your own corpse. Known once the corpse has been identified (looting or selecting it does that).",
"Corpses. Off hides every corpse, the ones you may loot too.\nOn: corpses you can't loot (or not identified yet: selecting one tells) show in this colour.",
"Corpses you may loot: your kills, your fellows' kills and your own corpse, in their own colour. Known once the corpse has been identified (looting or selecting it does that).\nOnly while Corpses is on.",
"Lifestones.",
"Items lying on the ground. Off by default: there can be a lot of them.",
};
@ -623,14 +625,21 @@ internal sealed class RadarFace : IImGuiPanel
foreach (var (kind, label) in KindRowsOrder)
{
ImGuiNET.ImGui.PushID(kind);
// "Your corpses" sits under Corpses: Corpses off hides them too (RadarSettingsStore.ShowKind).
bool sub = kind == RadarKind.OwnCorpse;
if (sub) { ImGuiNET.ImGui.Indent(14 * scale); ImGuiNET.ImGui.BeginDisabled(!RadarSettingsStore.ShowCorpses); }
changed |= ImGuiNET.ImGui.Checkbox("##show", ref RadarSettingsStore.ShowFlag(kind));
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]);
ImGuiNET.ImGui.SameLine();
// The marker exactly as the radar draws it.
// The marker exactly as the radar draws it; faded while the kind is hidden, so the
// legend doesn't look like the box did nothing.
float box = ImGuiNET.ImGui.GetFrameHeight();
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.Dummy(new Vector2(box, box));
RadarMarkerStyle.Draw(dl, kind, at + new Vector2(box, box) * 0.5f, KindCols[kind], 1.3f * scale);
uint glyph = KindCols[kind];
if (!RadarSettingsStore.ShowKind(kind))
glyph = (glyph & 0x00FFFFFFu) | ((uint)((glyph >> 24) * 0.3f) << 24);
RadarMarkerStyle.Draw(dl, kind, at + new Vector2(box, box) * 0.5f, glyph, 1.3f * scale);
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted(label);
@ -642,6 +651,7 @@ internal sealed class RadarFace : IImGuiPanel
RadarSettingsStore.KindColors[kind] = ToArgb(v);
_colorDirty = true;
}
if (sub) { ImGuiNET.ImGui.EndDisabled(); ImGuiNET.ImGui.Unindent(14 * scale); }
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.PopStyleVar();

View file

@ -12,12 +12,19 @@
// recorded hazards and the saved routes. Was the Patrol
// launcher's right-click popup; right-click now opens this
// drawer (popped out: still the popup).
// Mini Remote RynthAi's Mini Remote (session rates, target, summon,
// item slots, toggles, bank, rebuff, Translate, Guardian)
// with its Options menu. The plugin draws it here through
// RynthPluginRenderEmbed("miniremote") and says how big it
// wants the panel; the Hub launcher's right-click opens it
// (popped out: the floating Mini Remote instead).
// AC thread only (inside the dashboard's Draw).
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Plugins;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
@ -25,7 +32,7 @@ namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed partial class RynthAiFace
{
/// <summary>Meta state, bot activity and the four file pickers.</summary>
/// <summary>Meta state, bot activity and the five file pickers.</summary>
private sealed class FilesDrawer : DashboardDrawer
{
private readonly RynthAiFace _face;
@ -40,17 +47,20 @@ internal sealed partial class RynthAiFace
public override string TabTooltip(bool right)
{
RynthAiView? v = _face._view;
return "Loaded files: the Profile, Nav, Loot and Meta pickers, meta state and bot activity.\n" +
return "Loaded files: the Profile, Nav, Loot, Meta and Buffs pickers, meta state and bot activity.\n" +
"Profile: " + (v?.ProfileText ?? "Default") + "\nNav: " + (v?.NavText ?? "None") +
"\nLoot: " + (v?.LootText ?? "None") + "\nMeta: " + (v?.MetaText ?? "None") +
"\nBuffs: " + (v?.BuffText ?? "Built-in") +
(right ? "\n\nClick to slide them out (to the right: there's no room on the left)." : "\n\nClick to slide them out.");
}
// The picker rows are the dashboard's own (Selector), so they take its size factor (_k);
// the frame and the info lines take the drawers' k.
private const float LineH = 15, SelRow = 16, SelGap = 3;
public override float Width(float k) => 230 * k;
public override float Height(float k) =>
(Pad + TitleH + 4 + 2 * LineH + 6) * k + 4 * SelRow + 3 * SelGap + Pad * k;
(Pad + TitleH + 4 + 2 * LineH + 6) * k + (5 * SelRow + 4 * SelGap) * _k + Pad * k;
public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k)
{
@ -70,12 +80,14 @@ internal sealed partial class RynthAiFace
y += lh + 6 * k;
_face.Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, x, y, w, null);
y += SelRow + SelGap;
y += (SelRow + SelGap) * _k;
_face.Selector(1, "Nav:", view?.NavText ?? "None", raw.NavProfiles, raw.SelectedNavIdx, 0, x, y, w, null);
y += SelRow + SelGap;
y += (SelRow + SelGap) * _k;
_face.Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, x, y, w, raw);
y += SelRow + SelGap;
y += (SelRow + SelGap) * _k;
_face.Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, x, y, w, null);
y += (SelRow + SelGap) * _k;
_face.Selector(4, "Buffs:", view?.BuffText ?? "Built-in", raw.BuffProfiles, raw.SelectedBuffIdx, 4, x, y, w, null, spellsButton: true);
}
private static void InfoLine(ImDrawListPtr dl, ImFontPtr f, float x, float y, float w, float lh, float labelW, string label, string value)
@ -136,4 +148,81 @@ internal sealed partial class RynthAiFace
finally { ImGuiNET.ImGui.EndChild(); }
}
}
/// <summary>RynthAi's Mini Remote, drawn by the plugin into this drawer (the Hub launcher's right-click).</summary>
private sealed class RemoteDrawer : DashboardDrawer
{
/// <summary>The plugin surface name, NUL-terminated for the export.</summary>
private static ReadOnlySpan<byte> Surface => "miniremote\0"u8;
// Content bounds in unscaled pixels; the plugin's wish is clamped to them.
private const float MinW = 200, MaxW = 760, MinH = 60, DefaultH = 120;
/// <summary>The content size the plugin last asked for (pixels); zero until it has drawn here.</summary>
private Vector2 _want;
public override string Key => "remote";
public override string Icon => PhosphorIcons.SquaresFour;
public override string Name => "Mini Remote drawer";
public override bool SavedOpen => RynthAiDashboardState.RemoteOpen;
public override void SaveOpen(bool open) => RynthAiDashboardState.SetRemoteOpen(open);
public override string TabTooltip(bool right) =>
"Mini Remote: session rates, attack target, summon, item slots, toggles, bank, rebuff, Translate.\n" +
"Its Options button picks the sections (also: right-click Hub). The ILT tabs are in the Mini Remote window.\n" +
(right ? "Click to slide it out (to the right: there's no room on the left)." : "Click to slide it out.");
public override float Width(float k) =>
Math.Clamp(_want.X > 0 ? _want.X : MinW * k, MinW * k, MaxW * k) + 2 * Pad * k;
public override float Height(float k)
{
float frame = (Pad + TitleH + 4 + Pad) * k;
// Never taller than the screen: the body scrolls instead.
float screen = ImGuiNET.ImGui.GetIO().DisplaySize.Y;
float maxBody = screen > 1 ? MathF.Max(MinH * k, screen - frame - 8 * k) : 900 * k;
return frame + Math.Clamp(_want.Y > 0 ? _want.Y : DefaultH * k, MinH * k, maxBody);
}
public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k)
{
float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.SquaresFour, "MINI REMOTE", null, "Hide the Mini Remote drawer");
float x = origin.X + Pad * k;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y));
Vector2 size = new(panelW - 2 * Pad * k, MathF.Max(1, origin.Y + panelH - Pad * k - y));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
bool open = ImGuiNET.ImGui.BeginChild("##remote_body", size, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground);
ImGuiNET.ImGui.PopStyleVar();
try
{
if (!open) return;
// The plugin's widgets use the default UI font, as in its floating Mini Remote.
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
try
{
int result = PluginManager.RenderEmbed("RynthAi", Surface, size, out Vector2 want);
if (result == PluginManager.EmbedDrawn)
{
if (want.X > 0 && want.Y > 0) _want = want;
}
else
{
_want = Vector2.Zero;
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, DMute);
ImGuiNET.ImGui.TextWrapped(result switch
{
PluginManager.EmbedNoPlugin =>
"This RynthAi can't draw its Mini Remote here (it needs RynthAi 0.5.27 or later). Left-click Hub for the floating Mini Remote.",
PluginManager.EmbedFailed =>
"The Mini Remote failed to draw here (see the log). Left-click Hub for the floating Mini Remote.",
_ => "The Mini Remote shows here once RynthAi is ready: in the world, with plugin windows on (engine.json EnablePluginOverlayWindows).",
});
ImGuiNET.ImGui.PopStyleColor();
}
}
finally { ImGuiNET.ImGui.PopFont(); }
}
finally { ImGuiNET.ImGui.EndChild(); }
}
}
}

View file

@ -18,7 +18,7 @@
// the buttons above it.
// drawers tabs on the left edge (DashboardDrawers.cs), one open at a
// time, a window of their own beside the dashboard: Ranges
// (RangesSlideOut.cs), Loaded files and Patrol
// (RangesSlideOut.cs), Loaded files, Patrol and Mini Remote
// (RynthAiFace.Drawers.cs). Everything that slides out goes
// left; only the bars stay at the bottom (Tom 2026-10-05).
// Minimized keeps the title row, the control row and the bars. The window's
@ -27,6 +27,17 @@
// string preformatted); clicks: RynthAiCommands.
//
// Chromeless (like the Avalonia face): the title row is the drag surface.
//
// Size: the dashboard's panel text size (PanelTextScale.Get(Title): its own
// row in Settings > Display, else All Panels). The host draws the face with
// the fonts baked for that step (ImGuiFonts.CurrentStep, the nearest baked
// one until a re-bake lands) and every box here is multiplied by that same
// step's factor (Px), so text, icons and boxes grow together; size 0 is the
// plain pixel layout. The title row has no host title bar, so it carries the
// control: Ctrl+wheel over it steps the size, right-click opens the size
// popup (ImGuiPanelHost.TextSizeRows). A size change scales the window's
// width with it and fits the height to the content (MeasureAndFit).
//
// AC thread only; no per-frame string building except the FPS/uptime footer,
// which is cached until its value changes.
// ============================================================================
@ -76,31 +87,54 @@ internal sealed partial class RynthAiFace : IImGuiPanel
// The drawers on the dashboard's left edge (their own window, placed against this one).
private readonly DashboardDrawers _drawers;
private readonly PatrolDrawer _patrol = new();
private readonly RemoteDrawer _remote = new();
// This frame's data, for the drawers.
private RynthAiView? _view;
private RynthAiSnapshot _raw = Empty;
// Picker toggle: ImGui closes a popup on the press outside it, so remember
// whether it was showing when the selector press began (a second click closes).
private readonly int[] _pickerShownFrame = { -10, -10, -10, -10 };
private readonly bool[] _pressedWhileOpen = new bool[4];
private readonly int[] _pickerShownFrame = { -10, -10, -10, -10, -10 };
private readonly bool[] _pressedWhileOpen = new bool[5];
// The content's height (logical units, body padding included), measured each
// frame: the window's minimum height. _fit: resize the window to it once.
private float _contentHeight;
private bool _fit;
// The host's resize grip, which keeps its own size (it is not the panel's text).
private const float GripRoom = 12;
// This frame's size factor (PanelTextScale.Factor of the step the fonts are drawn at); 1 at size 0.
// Static: the popups' and drawers' static helpers read it too. AC thread.
private static float _k = 1f;
/// <summary>A layout length (pixels at size 0) at the dashboard's size.</summary>
private static float Px(float v) => v * _k;
// The size factor the docked window was last fitted at and its width then (logical units):
// a size change scales the width from there (not from a width the new minimum already grew).
private float _fitK, _fitWidth;
private const string SizePopupId = "##dash_size";
/// <summary>The factor of the step the host draws this panel's fonts at (ImGuiPanelHost.DrawPanel sets the same step).</summary>
private static float SizeFactor() => PanelTextScale.Factor(ImGuiFonts.BakedStepNear(PanelTextScale.Get(Title)));
public RynthAiFace()
{
// Tab order top to bottom; the first one saved open wins at load.
_drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol);
_drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol, _remote);
}
public Vector2? MinSize => new Vector2(MinWidth, _contentHeight > 0 ? _contentHeight
: RynthAiDashboardState.Minimized ? 54 : 180);
public Vector2? MinSize
{
get
{
float k = SizeFactor();
return new Vector2(MinWidth * k, _contentHeight > 0 ? _contentHeight
: (RynthAiDashboardState.Minimized ? 54 : 180) * k);
}
}
public void OnShown()
{
UiSources.RynthAi.Subscribe();
UiSources.RynthSortWatch.Subscribe(); // the Sort toggle, while RynthSort is loaded
UiSources.RynthAi.RequestRefresh();
_fit = true; // drop the empty space a taller saved size leaves under the content
}
@ -108,6 +142,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
public void OnHidden()
{
UiSources.RynthAi.Unsubscribe();
UiSources.RynthSortWatch.Unsubscribe();
if (_patrolOpen) { UiSources.Patrol.Unsubscribe(); _patrolOpen = false; }
_drawers.Detach();
}
@ -121,31 +156,45 @@ internal sealed partial class RynthAiFace : IImGuiPanel
_view = view;
_raw = raw;
uint boxBg = (C(0xFF0A121A) & 0x00FFFFFF) | ((uint)(view?.PanelAlpha ?? 242) << 24);
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
float x0 = start.X;
float width = ImGuiNET.ImGui.GetContentRegionAvail().X;
TitleRow(raw, x0, width, minimized);
Gap(4);
// Popped out (no drawers there): the Profile/Nav/Loot/Meta pickers inline while expanded
// (the caret on the control row). Docked they are the Loaded files drawer.
if (popped && !minimized && RynthAiDashboardState.FilesOpen)
// The host set the step these fonts are drawn at; the boxes take the same step's factor.
_k = PanelTextScale.Factor(ImGuiFonts.CurrentStep);
// Enlarged: tooltips and menus opened from the dashboard at its size too. (At size 0 the
// default font already is Ui11: nothing is pushed, so nothing changes.)
bool pushFont = ImGuiFonts.CurrentStep > 0;
if (pushFont) ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
try
{
HeaderGrid(view, raw, x0, width);
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
float x0 = start.X;
float width = ImGuiNET.ImGui.GetContentRegionAvail().X;
TitleRow(raw, x0, width, minimized);
Gap(4);
// Popped out (no drawers there): the Profile/Nav/Loot/Meta pickers inline while expanded
// (the caret on the control row). Docked they are the Loaded files drawer.
if (popped && !minimized && RynthAiDashboardState.FilesOpen)
{
HeaderGrid(view, raw, x0, width);
Gap(4);
}
ControlRow(view, raw, x0, width, minimized, popped, boxBg);
if (!minimized)
{
Gap(4);
Launchers(x0, width);
Gap(6);
Footer(view, x0, width);
}
Bars(view, raw, x0, width, boxBg);
PatrolPopup();
CharMenu();
SizePopup();
MeasureAndFit(start.Y);
}
ControlRow(view, raw, x0, width, minimized, popped, boxBg);
if (!minimized)
finally
{
Gap(4);
Launchers(x0, width);
Gap(6);
Footer(view, x0, width);
if (pushFont) ImGuiNET.ImGui.PopFont();
}
Bars(view, raw, x0, width, boxBg);
PatrolPopup();
MeasureAndFit(start.Y);
// Last: a window of its own, placed against this one's rect (hidden popped out).
_drawers.Draw();
}
@ -153,6 +202,9 @@ internal sealed partial class RynthAiFace : IImGuiPanel
/// <summary>
/// Records the content height as the window's minimum (so the bars at the
/// bottom are never cut off) and, after a toggle, fits the window to it.
/// After a size change the width scales with the size (from the width it had
/// at the old size), never wider than the screen, and the window is kept on
/// the screen.
/// </summary>
private void MeasureAndFit(float startY)
{
@ -161,11 +213,30 @@ internal sealed partial class RynthAiFace : IImGuiPanel
float place = ImGuiPanelHost.PlacementScale();
// + room for the host's resize grip, which is painted over the body's bottom-right corner.
_contentHeight = MathF.Ceiling(px / place) + GripRoom;
if (_fit && !ImGuiPopOuts.InPopOutFrame)
// Popped out the window is the OS window's (sized by the player); a size change made
// meanwhile is fitted when it docks back (_fitK still holds the docked size).
if (ImGuiPopOuts.InPopOutFrame) return;
float width = ImGuiNET.ImGui.GetWindowWidth() / place;
if (_fitK > 0 && _k != _fitK)
{
_fit = false;
ImGuiPanelHost.RequestSize(Title, new Vector2(ImGuiNET.ImGui.GetWindowWidth() / place, _contentHeight));
width = _fitWidth * (_k / _fitK);
float screenW = ImGuiNET.ImGui.GetIO().DisplaySize.X / place;
if (screenW > 1) width = MathF.Min(width, screenW);
width = MathF.Max(width, MinWidth * _k);
ImGuiPanelHost.RequestSize(Title, new Vector2(width, _contentHeight));
// Applied after the size, clamped to the screen at it: a bigger dashboard near the right or
// bottom edge moves in rather than running off (saved with the new size, like the bar's clamp).
ImGuiPanelHost.RequestPos(Title, ImGuiNET.ImGui.GetWindowPos() / place);
}
else if (_fit)
{
_fit = false;
ImGuiPanelHost.RequestSize(Title, new Vector2(width, _contentHeight));
}
_fitK = _k;
_fitWidth = width;
}
// ── Title row: "R" + "YNTH" | chips (drag surface) ──────
@ -175,18 +246,19 @@ internal sealed partial class RynthAiFace : IImGuiPanel
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
const int chips = 7;
const float chipW = 18, chipH = 16, chipGap = 2;
float chipW = Px(18), chipH = Px(16), chipGap = Px(2), chipRound = Px(2);
float chipsW = chips * chipW + (chips - 1) * chipGap;
float rowH = 20;
float rowH = Px(20);
// Drag surface: everything left of the chips.
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y));
ImGuiNET.ImGui.InvisibleButton("##dash_drag", new Vector2(Math.Max(1, width - chipsW), rowH));
ImGuiPanelHost.DragWindowWithLastItem();
ImGuiNET.ImGui.SetItemTooltip(DragTip);
ImFontPtr title = ImGuiFonts.Get(UiFont.Dash14);
float ty = y + (rowH - title.FontSize) * 0.5f;
dl.PushClipRect(new Vector2(x0, y), new Vector2(x0 + Math.Max(1, width - chipsW - 4), y + rowH), true);
dl.PushClipRect(new Vector2(x0, y), new Vector2(x0 + Math.Max(1, width - chipsW - Px(4)), y + rowH), true);
dl.AddText(title, title.FontSize, new Vector2(x0, ty), Teal, "R");
float rw = CalcWidth(title, "R");
dl.AddText(title, title.FontSize, new Vector2(x0 + rw, ty), White, "YNTH");
@ -198,7 +270,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
const UiFont chipFont = UiFont.Dash11;
bool target = RynthAiDashboardState.ShowTargetBar;
if (IconButton("##chip_target", new Vector2(cx, cy), chip, PhosphorIcons.Crosshair, chipFont, BtnFill, target ? Teal : Mute, BtnBord, 2))
if (IconButton("##chip_target", new Vector2(cx, cy), chip, PhosphorIcons.Crosshair, chipFont, BtnFill, target ? Teal : Mute, BtnBord, chipRound))
{
RynthAiDashboardState.SetShowTargetBar(!target);
_fit = true;
@ -208,7 +280,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
: "Target bar off. Click to show the target's name and health at the bottom.");
cx += chipW + chipGap;
bool vitals = RynthAiDashboardState.ShowVitals;
if (IconButton("##chip_vitals", new Vector2(cx, cy), chip, PhosphorIcons.Heartbeat, chipFont, BtnFill, vitals ? Teal : Mute, BtnBord, 2))
if (IconButton("##chip_vitals", new Vector2(cx, cy), chip, PhosphorIcons.Heartbeat, chipFont, BtnFill, vitals ? Teal : Mute, BtnBord, chipRound))
{
RynthAiDashboardState.SetShowVitals(!vitals);
_fit = true;
@ -218,20 +290,20 @@ internal sealed partial class RynthAiFace : IImGuiPanel
: "Player vitals off. Click to show your health, stamina and mana at the bottom.");
cx += chipW + chipGap;
if (IconButton("##chip_lock", new Vector2(cx, cy), chip, raw.IsLocked ? PhosphorIcons.Lock : PhosphorIcons.LockOpen,
chipFont, BtnFill, raw.IsLocked ? Amber : Mute, BtnBord, 2))
chipFont, BtnFill, raw.IsLocked ? Amber : Mute, BtnBord, chipRound))
RynthAiCommands.TogglePanelLock();
ImGuiNET.ImGui.SetItemTooltip(raw.IsLocked ? "Locked. Click to unlock the dashboard." : "Click to lock the dashboard in place.");
cx += chipW + chipGap;
if (IconButton("##chip_minus", new Vector2(cx, cy), chip, PhosphorIcons.Minus, chipFont, BtnFill, Mute, BtnBord, 2))
if (IconButton("##chip_minus", new Vector2(cx, cy), chip, PhosphorIcons.Minus, chipFont, BtnFill, Mute, BtnBord, chipRound))
RynthAiCommands.AdjustOpacity(-0.1f);
ImGuiNET.ImGui.SetItemTooltip("More transparent");
cx += chipW + chipGap;
if (IconButton("##chip_plus", new Vector2(cx, cy), chip, PhosphorIcons.Plus, chipFont, BtnFill, Mute, BtnBord, 2))
if (IconButton("##chip_plus", new Vector2(cx, cy), chip, PhosphorIcons.Plus, chipFont, BtnFill, Mute, BtnBord, chipRound))
RynthAiCommands.AdjustOpacity(0.1f);
ImGuiNET.ImGui.SetItemTooltip("More opaque");
cx += chipW + chipGap;
if (IconButton("##chip_min", new Vector2(cx, cy), chip,
minimized ? PhosphorIcons.ArrowsOutLineVertical : PhosphorIcons.ArrowsInLineVertical, chipFont, BtnFill, Mute, BtnBord, 2))
minimized ? PhosphorIcons.ArrowsOutLineVertical : PhosphorIcons.ArrowsInLineVertical, chipFont, BtnFill, Mute, BtnBord, chipRound))
{
RynthAiDashboardState.SetMinimized(!minimized);
_fit = true; // the window fits the other mode's content next frame
@ -240,68 +312,122 @@ internal sealed partial class RynthAiFace : IImGuiPanel
cx += chipW + chipGap;
if (PanelRouter.CanPopOut)
{
if (IconButton("##chip_dock", new Vector2(cx, cy), chip, ImGuiPanelHost.PopOutGlyph, chipFont, BtnFill, Mute, BtnBord, 2))
if (IconButton("##chip_dock", new Vector2(cx, cy), chip, ImGuiPanelHost.PopOutGlyph, chipFont, BtnFill, Mute, BtnBord, chipRound))
ImGuiPanelHost.TogglePopOut(Title);
ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip);
}
// The size, from the title row (no host title bar here): Ctrl+wheel steps it, right-click
// opens the size popup. The whole row, chips included; the body below keeps its wheel.
if (ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem)
&& ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x0, y), new Vector2(x0 + width, y + rowH), false))
{
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
if (io.KeyCtrl && io.MouseWheel != 0f)
PanelTextScale.SetForWindow(Title, PanelTextScale.Get(Title) + (io.MouseWheel > 0f ? 1 : -1));
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right))
ImGuiNET.ImGui.OpenPopup(SizePopupId);
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + rowH));
}
// ── Header: macro + state (40%) | Profile/Nav/Loot/Meta pickers (60%) ──
private const string DragTip = "Drag to move the dashboard.\nRight-click: dashboard size. Ctrl+wheel here: bigger or smaller.";
/// <summary>
/// The title row's right-click popup: the dashboard's size (its panel text size, the same
/// setting as Settings > Display > RynthAi Dashboard, or All Panels until it is set on its own).
/// </summary>
private static void SizePopup()
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(8)));
bool open = ImGuiNET.ImGui.BeginPopup(SizePopupId);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return;
try
{
ImGuiPanelHost.TextSizeRows(Title, _k, "Dashboard size");
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
// ── Header: macro + state (40%) | Profile/Nav/Loot/Meta/Buffs pickers (60%) ──
private void HeaderGrid(RynthAiView? view, RynthAiSnapshot raw, float x0, float width)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float y0 = ImGuiNET.ImGui.GetCursorScreenPos().Y + 2;
float y0 = ImGuiNET.ImGui.GetCursorScreenPos().Y + Px(2);
float leftW = width * 0.4f;
// Left: Meta State / Bot Activity (the macro start/stop is the control row's first square).
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10);
float ly = y0;
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly), Mute, "Meta State:");
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.MetaStateText ?? "Default");
ly += 2 * (f10.FontSize + 1) + 4;
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + Px(1)), Amber, view?.MetaStateText ?? "Default");
ly += 2 * (f10.FontSize + Px(1)) + Px(4);
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly), Mute, "Bot Activity:");
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.BotActivityText ?? "Idle");
float leftBottom = ly + 2 * (f10.FontSize + 1);
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + Px(1)), Amber, view?.BotActivityText ?? "Idle");
float leftBottom = ly + 2 * (f10.FontSize + Px(1));
// Right: four selector rows (label 36 px, picker fills, spacing 3).
// Right: five selector rows (label 36 px, picker fills, spacing 3; x the size).
float rx = x0 + leftW, rw = width - leftW, ry = y0;
// The fold arrow sits at the end of the Profile row, where it always fits.
const float foldW = 18f;
Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, rx, ry, rw - foldW - 2, null);
if (IconButton("##files_fold", new Vector2(rx + rw - foldW, ry), new Vector2(foldW, 16), PhosphorIcons.CaretUp, UiFont.Dash11, BtnFill, Mute, BtnBord, 2))
float foldW = Px(18f), selH = Px(16), selStep = Px(16 + 3);
Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, rx, ry, rw - foldW - Px(2), null);
if (IconButton("##files_fold", new Vector2(rx + rw - foldW, ry), new Vector2(foldW, selH), PhosphorIcons.CaretUp, UiFont.Dash11, BtnFill, Mute, BtnBord, Px(2)))
RynthAiDashboardState.SetFilesOpen(false);
ImGuiNET.ImGui.SetItemTooltip("Fold the loaded files into one line");
ry += 16 + 3;
ry += selStep;
Selector(1, "Nav:", view?.NavText ?? "None", raw.NavProfiles, raw.SelectedNavIdx, 0, rx, ry, rw, null);
ry += 16 + 3;
ry += selStep;
Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, rx, ry, rw, raw);
ry += 16 + 3;
ry += selStep;
Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, rx, ry, rw, null);
ry += 16;
ry += selStep;
Selector(4, "Buffs:", view?.BuffText ?? "Built-in", raw.BuffProfiles, raw.SelectedBuffIdx, 4, rx, ry, rw, null, spellsButton: true);
ry += selH;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, Math.Max(leftBottom, ry) + 4));
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, Math.Max(leftBottom, ry) + Px(4)));
}
private static readonly string[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta" };
private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta" };
private static readonly string[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta", "##sel_buff" };
private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta", "##pick_buff" };
private static readonly string[] NoneItems = { "None" };
/// <summary>
/// One file picker row. <paramref name="kind"/> is RynthPluginSelectProfile's list (0 nav,
/// 1 loot, 2 meta, 3 settings profile, 4 buff profile). <paramref name="lootEdit"/> adds the
/// Loot Editor button, <paramref name="spellsButton"/> the RynthAi Spells window button.
/// </summary>
private void Selector(int slot, string label, string text, string[] items, int selected, int kind,
float x, float y, float w, RynthAiSnapshot? lootEdit)
float x, float y, float w, RynthAiSnapshot? lootEdit, bool spellsButton = false)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10), f9 = ImGuiFonts.Get(UiFont.Dash9);
dl.AddText(f10, f10.FontSize, new Vector2(x, y + (16 - f10.FontSize) * 0.5f), Mute, label);
float rowH = Px(16), round = Px(2);
dl.AddText(f10, f10.FontSize, new Vector2(x, y + (rowH - f10.FontSize) * 0.5f), Mute, label);
float editW = 0;
if (spellsButton)
{
editW = Px(18);
var ep = new Vector2(x + w - editW, y);
if (IconButton("##buff_spells", ep, new Vector2(editW, rowH), PhosphorIcons.Sparkle, UiFont.Dash11, SelectorBg, Mute, 0, round))
RynthAiCommands.ApplyRemoteCommand("spells", "toggle");
ImGuiNET.ImGui.SetItemTooltip("RynthAi Spells: browse the spell list and build buff profiles.");
editW += Px(3);
}
if (lootEdit != null)
{
editW = 18;
editW = Px(18);
var ep = new Vector2(x + w - editW, y);
if (IconButton("##loot_edit", ep, new Vector2(editW, 16), PhosphorIcons.TreasureChest, UiFont.Dash11, SelectorBg, Mute, 0, 2))
if (IconButton("##loot_edit", ep, new Vector2(editW, rowH), PhosphorIcons.TreasureChest, UiFont.Dash11, SelectorBg, Mute, 0, round))
{
string path = !string.IsNullOrEmpty(lootEdit.VendorProfilePath) ? lootEdit.VendorProfilePath : lootEdit.CurrentLootPath;
// The in-game Loot Editor panel. The external editor is one click away on the
@ -309,29 +435,29 @@ internal sealed partial class RynthAiFace : IImGuiPanel
LootEditorFace.ToggleFor(path);
}
ImGuiNET.ImGui.SetItemTooltip("Loot Editor: the loot profile in use, or the open vendor's AutoVendor profile.");
editW += 3;
editW += Px(3);
}
var pos = new Vector2(x + 36, y);
var size = new Vector2(Math.Max(20, w - 36 - editW), 16);
var pos = new Vector2(x + Px(36), y);
var size = new Vector2(Math.Max(Px(20), w - Px(36) - editW), rowH);
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(SelectorIds[slot], size);
bool hovered = ImGuiNET.ImGui.IsItemHovered();
if (ImGuiNET.ImGui.IsItemActivated())
_pressedWhileOpen[slot] = ImGuiNET.ImGui.GetFrameCount() - _pickerShownFrame[slot] <= 1;
bool open = ImGuiNET.ImGui.IsPopupOpen(PickerIds[slot]);
dl.AddRectFilled(pos, pos + size, hovered ? Lighten(SelectorBg) : SelectorBg, 2);
dl.AddRect(pos, pos + size, BtnBord, 2);
const float arrowW = 12;
dl.PushClipRect(pos, pos + size - new Vector2(arrowW + 4, 0), true);
dl.AddText(f9, f9.FontSize, pos + new Vector2(5, (16 - f9.FontSize) * 0.5f), White, text);
dl.AddRectFilled(pos, pos + size, hovered ? Lighten(SelectorBg) : SelectorBg, round);
dl.AddRect(pos, pos + size, BtnBord, round);
float arrowW = Px(12);
dl.PushClipRect(pos, pos + size - new Vector2(arrowW + Px(4), 0), true);
dl.AddText(f9, f9.FontSize, pos + new Vector2(Px(5), (rowH - f9.FontSize) * 0.5f), White, text);
dl.PopClipRect();
PhosphorIcons.DrawCentered(dl, f10, open ? PhosphorIcons.CaretUp : PhosphorIcons.CaretDown,
new Vector2(pos.X + size.X - arrowW - 3, y), new Vector2(arrowW, 16), Mute);
new Vector2(pos.X + size.X - arrowW - Px(3), y), new Vector2(arrowW, rowH), Mute);
if (clicked && !_pressedWhileOpen[slot] && !open)
{
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(pos.X, pos.Y + size.Y + 2));
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(pos.X, pos.Y + size.Y + Px(2)));
ImGuiNET.ImGui.OpenPopup(PickerIds[slot]);
}
Picker(slot, items.Length == 0 ? NoneItems : items, Math.Clamp(selected, 0, Math.Max(0, items.Length - 1)), kind, items.Length > 0);
@ -339,16 +465,16 @@ internal sealed partial class RynthAiFace : IImGuiPanel
private void Picker(int slot, string[] items, int selected, int kind, bool real)
{
// Same look as the Avalonia picker: 200 wide, teal border, radius 6.
float maxH = Math.Min(items.Length * 26 + 12, Math.Max(60,
ImGuiNET.ImGui.GetIO().DisplaySize.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - 20));
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(200, maxH));
// Same look as the Avalonia picker: 200 wide, teal border, radius 6 (x the size).
float maxH = Math.Min(items.Length * Px(26) + Px(12), Math.Max(Px(60),
ImGuiNET.ImGui.GetIO().DisplaySize.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - Px(20)));
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(Px(200), maxH));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 6f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(6f));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(2, 2));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(4), Px(4)));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(Px(2), Px(2)));
bool open = ImGuiNET.ImGui.BeginPopup(PickerIds[slot]);
ImGuiNET.ImGui.PopStyleVar(4);
ImGuiNET.ImGui.PopStyleColor(2);
@ -361,7 +487,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
ImGuiNET.ImGui.PushID(i);
bool isSel = i == selected;
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (ItemButton("##item", p, new Vector2(w, 24), items[i], isSel ? TealSoft : BtnFill, isSel ? Teal : White))
if (ItemButton("##item", p, new Vector2(w, Px(24)), items[i], isSel ? TealSoft : BtnFill, isSel ? Teal : White))
{
if (real) RynthAiCommands.SelectProfile(kind, i);
ImGuiNET.ImGui.CloseCurrentPopup();
@ -377,16 +503,16 @@ internal sealed partial class RynthAiFace : IImGuiPanel
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(bg) : bg;
dl.AddRectFilled(pos, pos + size, fill, 3);
dl.AddRect(pos, pos + size, BtnBord, 3);
dl.AddRectFilled(pos, pos + size, fill, Px(3));
dl.AddRect(pos, pos + size, BtnBord, Px(3));
ImFontPtr f = ImGuiFonts.Get(UiFont.Dash11);
dl.PushClipRect(pos, pos + size, true);
dl.AddText(f, f.FontSize, pos + new Vector2(8, (size.Y - f.FontSize) * 0.5f), fg, text);
dl.AddText(f, f.FontSize, pos + new Vector2(Px(8), (size.Y - f.FontSize) * 0.5f), fg, text);
dl.PopClipRect();
return clicked;
}
// ── Control row: (ON/OFF) combat, buffing, nav, looting, meta ... force rebuff ──
// ── Control row: (ON/OFF) combat, buffing, nav, looting, meta, [sort] ... force rebuff ──
private const float Square = 24, SquareStep = 27, RowPad = 3;
@ -394,66 +520,80 @@ internal sealed partial class RynthAiFace : IImGuiPanel
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float top = ImGuiNET.ImGui.GetCursorScreenPos().Y;
float bottom = top + Square + 2 * RowPad;
dl.AddRectFilled(new Vector2(x0, top), new Vector2(x0 + width, bottom), boxBg, 3);
dl.AddRect(new Vector2(x0, top), new Vector2(x0 + width, bottom), BtnBord, 3);
float sq = Px(Square), sqStep = Px(SquareStep), round = Px(3);
var square = new Vector2(sq, sq);
float bottom = top + sq + 2 * Px(RowPad);
dl.AddRectFilled(new Vector2(x0, top), new Vector2(x0 + width, bottom), boxBg, round);
dl.AddRect(new Vector2(x0, top), new Vector2(x0 + width, bottom), BtnBord, round);
float x = x0 + 5, y = top + RowPad;
float x = x0 + Px(5), y = top + Px(RowPad);
// Macro start/stop: a square like the toggles, green with a Stop glyph while running.
{
bool on = raw.MacroRunning;
if (IconButton("##macro", new Vector2(x, y), new Vector2(Square, Square), on ? PhosphorIcons.Stop : PhosphorIcons.Play,
UiFont.Dash14, on ? MacroRun : BarBg, on ? White : Mute, on ? Green : BtnBord, 3))
if (IconButton("##macro", new Vector2(x, y), square, on ? PhosphorIcons.Stop : PhosphorIcons.Play,
UiFont.Dash14, on ? MacroRun : BarBg, on ? White : Mute, on ? Green : BtnBord, round))
RynthAiCommands.ToggleMacro();
ImGuiNET.ImGui.SetItemTooltip(on ? "Macro running. Click to stop it." : "Macro stopped. Click to start it.");
x += SquareStep + 6;
x += sqStep + Px(6);
}
Toggle("##t_combat", PhosphorIcons.Sword, raw.CombatEnabled, 0, new Vector2(x, y), "Combat");
x += SquareStep;
x += sqStep;
Toggle("##t_buff", PhosphorIcons.Sparkle, raw.BuffingEnabled, 1, new Vector2(x, y), "Buffing");
x += SquareStep;
x += sqStep;
Toggle("##t_nav", PhosphorIcons.SneakerMove, raw.NavigationEnabled, 2, new Vector2(x, y), "Navigation");
x += SquareStep;
x += sqStep;
Toggle("##t_loot", PhosphorIcons.Bag, raw.LootingEnabled, 3, new Vector2(x, y), "Looting");
x += SquareStep;
x += sqStep;
Toggle("##t_meta", PhosphorIcons.Code, raw.MetaEnabled, 4, new Vector2(x, y), "Meta (the macro rules)");
x += SquareStep;
x += sqStep;
// RynthSort's auto-sort, when RynthSort is loaded and knows the character.
int sort = RynthSortWatch.State;
if (sort >= 0)
{
bool on = sort == 1;
if (IconButton("##t_sort", new Vector2(x, y), square, PhosphorIcons.SortAscending, UiFont.Dash14,
on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, round))
RynthSortCommands.SetAuto(!on);
ImGuiNET.ImGui.SetItemTooltip(on ? "Auto-sort (RynthSort) on. Click to turn it off." : "Auto-sort (RynthSort) off. Click to turn it on.");
x += sqStep;
}
// Popped out: the pickers fold out from a caret left of FR (expanded mode, while folded away).
// Docked they are the Loaded files drawer on the left edge.
const float caretW = 16f;
float caretW = Px(16f);
bool caret = popped && !minimized && !RynthAiDashboardState.FilesOpen;
float frX = x0 + width - 5 - Square;
float frX = x0 + width - Px(5) - sq;
if (caret)
{
if (IconButton("##files_open", new Vector2(frX - 4 - caretW, y), new Vector2(caretW, Square), PhosphorIcons.CaretDown,
UiFont.Dash11, BtnFill, Teal, BtnBord, 2))
if (IconButton("##files_open", new Vector2(frX - Px(4) - caretW, y), new Vector2(caretW, sq), PhosphorIcons.CaretDown,
UiFont.Dash11, BtnFill, Teal, BtnBord, Px(2)))
RynthAiDashboardState.SetFilesOpen(true);
ImGuiNET.ImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") +
"\nLoot: " + (view?.LootText ?? "None") + "\nMeta: " + (view?.MetaText ?? "None") +
"\n\nClick to show the Profile, Nav, Loot and Meta pickers.");
"\nBuffs: " + (view?.BuffText ?? "Built-in") +
"\n\nClick to show the Profile, Nav, Loot, Meta and Buffs pickers.");
}
// What the bot is doing, always in view (every mode, minimized too): between the toggles and FR.
{
ImFontPtr af = ImGuiFonts.Get(UiFont.Dash10);
float ax = x + 2, aRight = (caret ? frX - 4 - caretW : frX) - 6;
if (aRight - ax > 20)
float ax = x + Px(2), aRight = (caret ? frX - Px(4) - caretW : frX) - Px(6);
if (aRight - ax > Px(20))
{
string activity = view?.BotActivityText ?? "Idle";
float ay = y + (Square - af.FontSize) * 0.5f;
dl.PushClipRect(new Vector2(ax, y), new Vector2(aRight, y + Square), true);
float ay = y + (sq - af.FontSize) * 0.5f;
dl.PushClipRect(new Vector2(ax, y), new Vector2(aRight, y + sq), true);
dl.AddText(af, af.FontSize, new Vector2(ax, ay), Amber, activity);
dl.PopClipRect();
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(ax, y));
ImGuiNET.ImGui.InvisibleButton("##activity", new Vector2(aRight - ax, Square));
ImGuiNET.ImGui.InvisibleButton("##activity", new Vector2(aRight - ax, sq));
ImGuiNET.ImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + (view?.MetaStateText ?? "Default"));
}
}
// Force rebuff, set apart at the right (DrakBot's place for it).
if (IconButton("##fr", new Vector2(x0 + width - 5 - Square, y), new Vector2(Square, Square), PhosphorIcons.ArrowsClockwise,
UiFont.Dash14, FrFill, Amber, BtnBord, 3))
if (IconButton("##fr", new Vector2(frX, y), square, PhosphorIcons.ArrowsClockwise,
UiFont.Dash14, FrFill, Amber, BtnBord, round))
RynthAiCommands.ForceRebuff();
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
RynthAiCommands.CancelForceRebuff();
@ -465,7 +605,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
private void Toggle(string id, string icon, bool on, int subsystem, Vector2 pos, string name)
{
if (IconButton(id, pos, new Vector2(Square, Square), icon, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, 3))
if (IconButton(id, pos, new Vector2(Px(Square), Px(Square)), icon, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, Px(3)))
RynthAiCommands.SetSubsystemEnabled(subsystem, !on);
ImGuiNET.ImGui.SetItemTooltip(on ? name + " on. Click to turn it off." : name + " off. Click to turn it on.");
}
@ -477,30 +617,31 @@ internal sealed partial class RynthAiFace : IImGuiPanel
private void Launchers(float x0, float width)
{
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
const int buttons = 8;
float bw = MathF.Floor((width - buttons * LauncherGap) / buttons);
const int buttons = 10;
float gap = Px(LauncherGap);
float bw = MathF.Floor((width - buttons * gap) / buttons);
// Short labels only when every button has room for its icon and label.
bool labels = bw >= 68;
bool labels = bw >= Px(68);
float x = x0;
Launcher("##l_meta", PhosphorIcons.ListChecks, "Meta", "Meta: the macro rules", x, y, bw, labels, () => PanelRouter.Toggle("Meta"));
x += bw + LauncherGap;
x += bw + gap;
Launcher("##l_lua", PhosphorIcons.FileCode, "Lua", "Lua scripts", x, y, bw, labels, () => PanelRouter.Toggle("Lua"));
x += bw + LauncherGap;
x += bw + gap;
// Monsters opens the Damage panel (the basic Monsters panel and its
// Simple/Advanced chip were retired 2026-10-01).
Launcher("##l_mon", PhosphorIcons.Skull, "Monsters", "Monsters: weapons, spells and rules per monster (the Damage panel)",
x, y, bw, labels, PanelRouter.ToggleMonsters);
x += bw + LauncherGap;
x += bw + gap;
Launcher("##l_set", PhosphorIcons.Gear, "Settings", "Settings", x, y, bw, labels, () => PanelRouter.Toggle("Settings"));
x += bw + LauncherGap;
x += bw + gap;
Launcher("##l_nav", PhosphorIcons.MapTrifold, "Nav", "Nav: routes", x, y, bw, labels, () => PanelRouter.Toggle("Nav"));
x += bw + LauncherGap;
x += bw + gap;
Launcher("##l_map", PhosphorIcons.MapPin, "Map", "Dungeon Map (shows while you're in a dungeon)", x, y, bw, labels,
() => PanelRouter.Toggle(DungeonMapFace.Title));
x += bw + LauncherGap;
x += bw + gap;
Launcher("##l_items", PhosphorIcons.Backpack, "Items", "Items", x, y, bw, labels, () => PanelRouter.Toggle("Items"));
x += bw + LauncherGap;
x += bw + gap;
bool popped = ImGuiPopOuts.InPopOutFrame;
Launcher("##l_patrol", PhosphorIcons.Footprints, "Patrol",
popped ? "Patrol. Left-click: start dungeon patrol. Right-click: routes & recorded hazards."
@ -516,30 +657,57 @@ internal sealed partial class RynthAiFace : IImGuiPanel
}
else _drawers.Toggle(_patrol);
}
x += bw + gap;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + LauncherH));
// Char and Hub open the Mini Remote window (MiniRemoteFace, hosting RynthAi's remote): Char
// on its Character tab (an ILT tab; elsewhere the remote shows), Hub as it was left.
Launcher("##l_char", PhosphorIcons.User, "Char",
"Char. Left-click: the Mini Remote on its Character tab (ILT worlds). Right-click: Character windows (Spells, Quests, Pets, Skills, Inventory...), then Server: this server's plugin windows.",
x, y, bw, labels, () => ShowMiniRemoteTab("character"));
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1));
ImGuiNET.ImGui.OpenPopup("##charmenu");
}
x += bw + gap;
// Left-click is the Mini Remote window (MiniRemoteFace, which hosts RynthAi's remote, the
// same window as the bar button). Right-click is the Mini Remote drawer, as Patrol's is
// its drawer; popped out there are no drawers, so it opens the window. Inventory HUDs
// setup is in the Mini Remote's Options menu.
Launcher("##l_hub", PhosphorIcons.SquaresFour, "Hub",
popped ? "Hub. Left-click: the Mini Remote window (/rc miniremote). Right-click: open the Mini Remote window."
: "Hub. Left-click: the Mini Remote window (/rc miniremote). Right-click: the Mini Remote drawer (left), with its Options.",
x, y, bw, labels, () => PanelRouter.Toggle(MiniRemoteFace.Title));
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
if (popped) ImGuiPanelHost.Open(MiniRemoteFace.Title);
else _drawers.Toggle(_remote);
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + Px(LauncherH)));
}
private void Launcher(string id, string icon, string label, string tooltip, float x, float y, float w, bool showLabel, Action? onClick)
{
var pos = new Vector2(x, y);
var size = new Vector2(Math.Max(10, w), LauncherH);
float lh = Px(LauncherH);
var size = new Vector2(Math.Max(Px(10), w), lh);
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
ImGuiNET.ImGui.SetItemTooltip(tooltip);
uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill;
dl.AddRectFilled(pos, pos + size, fill, 3);
dl.AddRect(pos, pos + size, BtnBord, 3);
dl.AddRectFilled(pos, pos + size, fill, Px(3));
dl.AddRect(pos, pos + size, BtnBord, Px(3));
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Dash14);
if (showLabel)
{
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Dash9);
const float iconBox = 16;
PhosphorIcons.DrawCentered(dl, iconFont, icon, pos + new Vector2(4, 0), new Vector2(iconBox, LauncherH), Mute);
float iconBox = Px(16);
PhosphorIcons.DrawCentered(dl, iconFont, icon, pos + new Vector2(Px(4), 0), new Vector2(iconBox, lh), Mute);
dl.PushClipRect(pos, pos + size, true);
dl.AddText(f9, f9.FontSize, new Vector2(pos.X + 4 + iconBox + 4, pos.Y + (LauncherH - f9.FontSize) * 0.5f), Mute, label);
dl.AddText(f9, f9.FontSize, new Vector2(pos.X + Px(4) + iconBox + Px(4), pos.Y + (lh - f9.FontSize) * 0.5f), Mute, label);
dl.PopClipRect();
}
else
@ -606,24 +774,25 @@ internal sealed partial class RynthAiFace : IImGuiPanel
string version = view?.Version ?? string.Empty;
if (version.Length > 0)
{
float left = x0 + fpsW + 8, right = x0 + width - upW - 8;
float left = x0 + fpsW + Px(8), right = x0 + width - upW - Px(8);
if (right > left)
{
float vw = CalcWidth(f10, version);
float vx = x0 + (width - vw) * 0.5f;
if (vx < left || vx + vw > right) vx = left;
dl.PushClipRect(new Vector2(left, y), new Vector2(right, y + f10.FontSize + 2), true);
dl.PushClipRect(new Vector2(left, y), new Vector2(right, y + f10.FontSize + Px(2)), true);
dl.AddText(f10, f10.FontSize, new Vector2(vx, y), Mute, version);
dl.PopClipRect();
}
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + f10.FontSize + 2));
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + f10.FontSize + Px(2)));
ImGuiNET.ImGui.Dummy(new Vector2(width, 0));
}
// ── Bars (bottom): player vitals, then the target ──────────────────────
private const float VitalsH = 14 + 3 + 14 + 3 + 14;
// A vital bar's row and the gap under it; three rows.
private const float VitalH = 14, VitalGap = 3;
private void Bars(RynthAiView? view, RynthAiSnapshot raw, float x0, float width, uint boxBg)
{
@ -636,21 +805,23 @@ internal sealed partial class RynthAiFace : IImGuiPanel
// The target's stamina/mana rows are held while that option is on, so they
// don't grow the box (and the window) as targets come and go.
bool subRows = raw.ShowTargetStaminaMana;
float targetH = f11.FontSize + 2 + 3 + 12 + (subRows ? 2 * (13 + 3) - 3 : 0);
float targetH = f11.FontSize + Px(2) + Px(3) + Px(12) + (subRows ? 2 * (Px(13) + Px(3)) - Px(3) : 0);
float vh = Px(VitalH), vgap = Px(VitalGap);
float vitalsH = vh + vgap + vh + vgap + vh;
float top = ImGuiNET.ImGui.GetCursorScreenPos().Y;
float height = 5 + (vitals ? VitalsH : 0) + (vitals && target ? 6 : 0) + (target ? targetH : 0) + 4;
float height = Px(5) + (vitals ? vitalsH : 0) + (vitals && target ? Px(6) : 0) + (target ? targetH : 0) + Px(4);
var tl = new Vector2(x0, top);
var br = new Vector2(x0 + width, top + height);
dl.AddRectFilled(tl, br, boxBg, 3);
dl.AddRect(tl, br, BtnBord, 3);
dl.AddRectFilled(tl, br, boxBg, Px(3));
dl.AddRect(tl, br, BtnBord, Px(3));
float rx = x0 + 5, rw = width - 10, ry = top + 5;
float rx = x0 + Px(5), rw = width - Px(10), ry = top + Px(5);
if (vitals)
{
VitalRow(dl, rx, ry, rw, PhosphorIcons.Heart, view?.Health ?? default, Hp, f10); ry += 14 + 3;
VitalRow(dl, rx, ry, rw, PhosphorIcons.Lightning, view?.Stamina ?? default, Green, f10); ry += 14 + 3;
VitalRow(dl, rx, ry, rw, PhosphorIcons.Drop, view?.Mana ?? default, Mana, f10); ry += 14;
if (target) ry += 6;
VitalRow(dl, rx, ry, rw, PhosphorIcons.Heart, view?.Health ?? default, Hp, f10); ry += vh + vgap;
VitalRow(dl, rx, ry, rw, PhosphorIcons.Lightning, view?.Stamina ?? default, Green, f10); ry += vh + vgap;
VitalRow(dl, rx, ry, rw, PhosphorIcons.Drop, view?.Mana ?? default, Mana, f10); ry += vh;
if (target) ry += Px(6);
}
if (target)
{
@ -659,27 +830,28 @@ internal sealed partial class RynthAiFace : IImGuiPanel
float hpW = CalcWidth(f11, hpText);
float iconW = CalcWidth(f11, PhosphorIcons.Crosshair);
dl.AddText(f11, f11.FontSize, new Vector2(rx, ry), Mute, PhosphorIcons.Crosshair);
dl.PushClipRect(new Vector2(rx, ry), new Vector2(rx + rw - hpW - 4, ry + f11.FontSize + 2), true);
dl.AddText(f11, f11.FontSize, new Vector2(rx + iconW + 3, ry), TextDim, view?.TargetHeadline ?? "NO TARGET");
dl.PushClipRect(new Vector2(rx, ry), new Vector2(rx + rw - hpW - Px(4), ry + f11.FontSize + Px(2)), true);
dl.AddText(f11, f11.FontSize, new Vector2(rx + iconW + Px(3), ry), TextDim, view?.TargetHeadline ?? "NO TARGET");
dl.PopClipRect();
dl.AddText(f11, f11.FontSize, new Vector2(rx + rw - hpW, ry), White, hpText);
ry += f11.FontSize + 2 + 3;
ry += f11.FontSize + Px(2) + Px(3);
// 15-segment gradient bar, 10 high, 2 px between segments.
// 15-segment gradient bar, 10 high, 2 px between segments (x the size).
int lit = view?.TargetSegmentsLit ?? 0;
float segW = (rw - 2 * (RynthAiView.Segments - 1)) / RynthAiView.Segments;
float segGap = Px(2);
float segW = (rw - segGap * (RynthAiView.Segments - 1)) / RynthAiView.Segments;
for (int i = 0; i < RynthAiView.Segments; i++)
{
float sx = rx + i * (segW + 2);
dl.AddRectFilled(new Vector2(sx, ry + 1), new Vector2(sx + segW, ry + 11), i < lit ? SegmentColors[i] : BarBg, 1);
float sx = rx + i * (segW + segGap);
dl.AddRectFilled(new Vector2(sx, ry + Px(1)), new Vector2(sx + segW, ry + Px(11)), i < lit ? SegmentColors[i] : BarBg, Px(1));
}
ry += 12;
ry += Px(12);
if (subRows)
{
bool shown = view != null && view.ShowTargetSubBars;
ry += 3;
CompactBar(dl, rx, ry, rw, shown ? view!.TargetStamina : default, Green, f10); ry += 13 + 3;
ry += Px(3);
CompactBar(dl, rx, ry, rw, shown ? view!.TargetStamina : default, Green, f10); ry += Px(13) + Px(3);
CompactBar(dl, rx, ry, rw, shown ? view!.TargetMana : default, Mana, f10);
}
}
@ -690,22 +862,80 @@ internal sealed partial class RynthAiFace : IImGuiPanel
private static void CompactBar(ImDrawListPtr dl, float x, float y, float w, VitalView bar, uint color, ImFontPtr font)
{
var a = new Vector2(x, y + 1);
var b = new Vector2(x + w, y + 12);
dl.AddRectFilled(a, b, BarBg, 2);
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, 2);
dl.AddText(font, font.FontSize, new Vector2(x + 4, y + 1 + (11 - font.FontSize) * 0.5f), White, bar.Text ?? "");
var a = new Vector2(x, y + Px(1));
var b = new Vector2(x + w, y + Px(12));
dl.AddRectFilled(a, b, BarBg, Px(2));
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, Px(2));
dl.AddText(font, font.FontSize, new Vector2(x + Px(4), y + Px(1) + (Px(11) - font.FontSize) * 0.5f), White, bar.Text ?? "");
}
private static void VitalRow(ImDrawListPtr dl, float x, float y, float w, string icon, VitalView bar, uint color, ImFontPtr font)
{
var a = new Vector2(x, y + 1);
var b = new Vector2(x + w, y + 14);
dl.AddRectFilled(a, b, BarBg, 6);
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, 6);
float ty = y + 1 + (13 - font.FontSize) * 0.5f;
dl.AddText(font, font.FontSize, new Vector2(x + 4, ty), Mute, icon);
dl.AddText(font, font.FontSize, new Vector2(x + 4 + CalcWidth(font, icon) + 3, ty), White, bar.Text ?? "");
var a = new Vector2(x, y + Px(1));
var b = new Vector2(x + w, y + Px(14));
dl.AddRectFilled(a, b, BarBg, Px(6));
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, Px(6));
float ty = y + Px(1) + (Px(13) - font.FontSize) * 0.5f;
dl.AddText(font, font.FontSize, new Vector2(x + Px(4), ty), Mute, icon);
dl.AddText(font, font.FontSize, new Vector2(x + Px(4) + CalcWidth(font, icon) + Px(3), ty), White, bar.Text ?? "");
}
// ── Char menu (right-click Char) ───────────────────────────────────
// Top: "Character", the windows every server has. Bottom: the server section
// (UI.ServerMenus): the installed server plugins' windows for the world you're on.
/// <summary>
/// Opens the Mini Remote window on one of its tabs ("" = the remote). Quests and Pets show on
/// every server; RynthAi shows an ILT tab once the server reports that feature on, and until
/// then the window shows the remote.
/// </summary>
private static void ShowMiniRemoteTab(string section)
{
ImGuiPanelHost.Open(MiniRemoteFace.Title);
RynthAiCommands.ApplyRemoteCommand("hub", section.Length > 0 ? "tab " + section : "tab");
}
/// <summary>A Char menu item that toggles a registered ImGui panel (checked while open).</summary>
private static void PanelMenuItem(string title, string command)
{
if (!ImGuiPanelHost.HasFace(title)) return;
if (ImGuiNET.ImGui.MenuItem(title, command, ImGuiPanelHost.IsOpen(title)))
PanelRouter.Toggle(title);
}
private static void CharMenu()
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(8)));
bool open = ImGuiNET.ImGui.BeginPopup("##charmenu");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return;
try
{
ImGuiNET.ImGui.TextDisabled("Character");
if (ImGuiNET.ImGui.MenuItem("Mini Remote", "/rc miniremote", ImGuiPanelHost.IsOpen(MiniRemoteFace.Title)))
ShowMiniRemoteTab("");
if (ImGuiNET.ImGui.MenuItem("Spells", "/rc spells"))
RynthAiCommands.ApplyRemoteCommand("spells", "toggle");
ImGuiNET.ImGui.SetItemTooltip("RynthAi Spells: the spell catalog and buff profiles.");
// The Mini Remote's universal tabs (every server); its ILT tabs are in the server half.
if (ImGuiNET.ImGui.MenuItem("Quests", "/rc miniremote tab quests")) ShowMiniRemoteTab("quests");
ImGuiNET.ImGui.SetItemTooltip("The Mini Remote's Quests tab: /myquests timers and favorites (RynthAi).");
if (ImGuiNET.ImGui.MenuItem("Pets", "/rc miniremote tab pets")) ShowMiniRemoteTab("pets");
ImGuiNET.ImGui.SetItemTooltip("The Mini Remote's Pets tab: summoning essences, priorities and the healing pet (RynthAi).");
PanelMenuItem(SkillsFace.Title, "/rc skills");
PanelMenuItem(InventoryFace.Title, "/rc inventory");
PanelMenuItem(ItemCountFace.Title, "/rc itemcount");
PanelMenuItem(CharactersFace.Title, "/rc characters");
UI.ServerMenus.DrawImGuiMenu(separatorFirst: true);
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
// ── Patrol popup (right-click Patrol, popped out; docked it's the Patrol drawer) ──
@ -714,8 +944,8 @@ internal sealed partial class RynthAiFace : IImGuiPanel
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(260, 0), new Vector2(260, 376));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(8)));
ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(Px(260), 0), new Vector2(Px(260), Px(376)));
bool open = ImGuiNET.ImGui.BeginPopup("##patrol");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(2);
@ -801,7 +1031,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
private static void Section(string text)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
ImGuiNET.ImGui.Dummy(new Vector2(0, Px(4)));
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), text);
ImGuiNET.ImGui.PopFont();
@ -816,8 +1046,8 @@ internal sealed partial class RynthAiFace : IImGuiPanel
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 2f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(6, 1));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, Px(2f));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(Px(6), Px(1)));
bool clicked = ImGuiNET.ImGui.Button(label);
ImGuiNET.ImGui.PopStyleVar(3);
ImGuiNET.ImGui.PopStyleColor(5);
@ -880,7 +1110,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
return a | (b << 16) | (g << 8) | r;
}
private static void Gap(float h) => ImGuiNET.ImGui.Dummy(new Vector2(0, h));
private static void Gap(float h) => ImGuiNET.ImGui.Dummy(new Vector2(0, Px(h)));
private static uint[] BuildSegmentColors()
{

View file

@ -53,6 +53,16 @@ internal sealed class SettingsFace : IImGuiPanel
public bool Active; // the box had keyboard focus last frame
}
private readonly Dictionary<SettingRow, NumberEdit> _edits = new();
// Text rows being typed in (the saved value shows again once the box loses focus).
private readonly Dictionary<SettingRow, string> _textEdits = new();
// The Hotkeys tab (engine-side; not part of RynthAi's settings).
private readonly HotkeysSettingsUi _hotkeys = new();
// A tab asked for from outside (/rc hotkeys), taken on the next draw.
private static volatile string? _requestedTab;
/// <summary>Shows tab <paramref name="name"/> (a SettingsSchema tab name) the next time Settings draws. Any thread.</summary>
public static void RequestTab(string name) => _requestedTab = name;
public void OnShown()
{
@ -60,7 +70,11 @@ internal sealed class SettingsFace : IImGuiPanel
UiSources.Settings.RequestRefresh();
}
public void OnHidden() => UiSources.Settings.Unsubscribe();
public void OnHidden()
{
UiSources.Settings.Unsubscribe();
_hotkeys.Leave();
}
public void Draw()
{
@ -73,6 +87,13 @@ internal sealed class SettingsFace : IImGuiPanel
}
_editing = false;
if (_requestedTab is { } wanted)
{
_requestedTab = null;
int idx = Array.FindIndex(SettingsSchema.Tabs, t => t.Name.Equals(wanted, StringComparison.OrdinalIgnoreCase));
if (idx >= 0) _tab = idx;
}
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
@ -163,6 +184,7 @@ internal sealed class SettingsFace : IImGuiPanel
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
SettingRow[] rows = SettingsSchema.Tabs[_tab].Rows;
if (SettingsSchema.Tabs[_tab].Name != HotkeysSettingsUi.TabName) _hotkeys.Leave();
for (int i = 0; i < rows.Length; i++)
{
SettingRow row = rows[i];
@ -189,9 +211,133 @@ internal sealed class SettingsFace : IImGuiPanel
case SettingKind.Spacer: ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); break;
case SettingKind.Note: Note(row.Label, w); break;
case SettingKind.CraftingStatus: CraftingStatus(row); break;
case SettingKind.Button: ButtonRow(row, w); break;
case SettingKind.TraceCategories: TraceCategoriesRow(row, w); break;
case SettingKind.Text: TextRow(row, w); break;
case SettingKind.Status: StatusRow(row, w); break;
case SettingKind.Hotkeys: _editing |= _hotkeys.Draw(w); break;
}
}
// [All on] [All off] [ILT on], then a 3-column grid of square toggles, one per
// RynthAi trace category. Edits the copy's DiagCategories and saves like any other row.
private void TraceCategoriesRow(SettingRow row, float w)
{
var cats = TraceCategoryLevels.Parse(_data.DiagCategories);
if (cats.Count == 0)
{
Note("Waiting for RynthAi...", w);
return;
}
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
if (ImGuiNET.ImGui.Button("All on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true));
ImGuiNET.ImGui.SameLine(0, 6);
if (ImGuiNET.ImGui.Button("All off")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", false));
ImGuiNET.ImGui.SameLine(0, 6);
if (ImGuiNET.ImGui.Button("ILT on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true, "Ilt"));
Tooltip(row);
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float colW = Math.Max(80f, w / 3f);
int perRow = Math.Max(1, (int)(w / colW));
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
for (int i = 0; i < cats.Count; i++)
{
var (name, level) = cats[i];
bool on = level != TraceCategoryLevels.Off;
string label = TraceCategoryLevels.Label(name, level);
var p = start + new Vector2(i % perRow * colW, i / perRow * 18f);
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.PushID(name);
if (ImGuiNET.ImGui.InvisibleButton("##cat", new Vector2(colW - 4, 16)))
SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, name, !on));
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
ImGuiNET.ImGui.PopID();
dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2);
dl.PushClipRect(p, p + new Vector2(colW - 4, 16), true);
dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label);
dl.PopClipRect();
}
int rowsUsed = (cats.Count + perRow - 1) / perRow;
ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(0, rowsUsed * 18f));
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
}
private void SaveCategories(string levels)
{
_data.DiagCategories = levels;
SettingsCommands.Save(_data.Clone());
}
// Label, then a full-width box; the value commits on Enter or focus loss (like the number boxes).
private void TextRow(SettingRow row, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
ImGuiNET.ImGui.TextUnformatted(row.Label);
ImGuiNET.ImGui.PopStyleColor();
Tooltip(row);
string saved = row.GetText?.Invoke(_data) ?? string.Empty;
string text = _textEdits.TryGetValue(row, out string? typing) ? typing : saved;
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 4));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f);
bool enter = ImGuiNET.ImGui.InputTextWithHint("##text", row.Hint ?? string.Empty, ref text, 512u,
ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
bool committed = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(3);
Tooltip(row);
_editing |= active;
if (committed)
{
_textEdits.Remove(row);
if (!string.Equals(text, saved, StringComparison.Ordinal))
{
row.SetText?.Invoke(_data, text);
SettingsCommands.Save(_data.Clone());
}
}
else if (active) _textEdits[row] = text;
else _textEdits.Remove(row);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
// RynthAi's one-line status (teal), wrapped to the column.
private void StatusRow(SettingRow row, float w)
{
string text = row.GetText?.Invoke(_data) ?? string.Empty;
if (text.Length == 0) return;
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Teal);
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopStyleColor();
}
// Label | [caption]; Click posts its own work (never runs plugin code on AC's thread).
private static void ButtonRow(SettingRow row, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted(row.Label);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f));
if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label))
row.Click?.Invoke();
Tooltip(row);
}
private void Changed(SettingRow row, double value)
{
row.Set!(_data, value);
@ -420,6 +566,7 @@ internal sealed class SettingsFace : IImGuiPanel
{
["Display"] = PhosphorIcons.Monitor,
["UI"] = PhosphorIcons.AppWindow,
["Hotkeys"] = PhosphorIcons.Keyboard,
["Misc"] = PhosphorIcons.DotsThree,
["Recharge"] = PhosphorIcons.BatteryCharging,
["Melee Combat"] = PhosphorIcons.Sword,
@ -430,6 +577,7 @@ internal sealed class SettingsFace : IImGuiPanel
["Crafting"] = PhosphorIcons.Hammer,
["Looting"] = PhosphorIcons.Bag,
["Vendoring"] = PhosphorIcons.Storefront,
["Diagnostics"] = PhosphorIcons.Wrench,
};
private static readonly System.Collections.Generic.Dictionary<string, string> TabLabels = new();

View file

@ -0,0 +1,693 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/SkillsFace.Progression.cs
// The Skills panel's Progression tab, shown on ILT-like worlds only:
// - XP planner: exact XP for the next N raises of every attribute and vital,
// from the client's XP tables (raising stays on the Attributes & Vitals tab).
// - Attribute raiser: infinite attributes past the retail cap. RynthAi reads the
// server's costs ("/xp all") and raises with "/attr", by hand or on a timer from
// unassigned XP, in the order and mode set here. Laid out like UB's Leaftide XP
// tab: "+1 Level" / "+10 Levels" buttons labelled with their (projected) cost.
// - Augmentations: UB's Augs tab - Refresh current (/aug), Current / Target / Inc /
// Luminance / Coins with a totals row, Reset targets, Copy Discord / In-Game.
// - Augmentations / Enlightenment: RynthAi's ILT Hub planners. RynthAi owns the
// math and the saved inputs (UiSources.Progression snapshot); edits and
// actions go back as "prog ..." remote commands. /enl and arming
// auto-enlighten ask here first; the server still shows its own dialog.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed partial class SkillsFace
{
private const string ProgConfirmId = "##skills_prog_confirm";
private int _planLevels = 10; // XP planner: raises to price per row
private bool _progSubscribed;
// The confirm the Progression tab asked for; the command is sent only on its Yes button.
private string _progConfirmTitle = "", _progConfirmText = "", _progConfirmYes = "", _progConfirmCommand = "";
private bool _progConfirmOpenRequested;
// Set by ShowProgression (any panel, AC thread); the tab is selected once RynthAi's snapshot
// says it exists (the first poll lands a step after the panel opens).
private static bool _progressionRequested;
/// <summary>RynthAi reports an ILT-like world (its ILT Hub exists and the server has ILT features).</summary>
private static bool ProgressionTabVisible => UiSources.Progression.Current?.Value.Available == true;
/// <summary>Opens the Skills panel (if closed) on the Progression tab. AC thread.</summary>
public static void ShowProgression()
{
_progressionRequested = true;
if (!ImGuiPanelHost.IsOpen(Title)) PanelRouter.Toggle(Title);
}
/// <summary>Draw: applies a pending ShowProgression once the tab exists.</summary>
private void ApplyProgressionRequest()
{
if (!_progressionRequested || !ProgressionTabVisible) return;
_progressionRequested = false;
_tab = 2;
}
private void ProgressionShown()
{
if (_progSubscribed) return;
_progSubscribed = true;
UiSources.Progression.Subscribe();
UiSources.Progression.RequestRefresh();
}
private void ProgressionHidden()
{
_progressionRequested = false;
if (!_progSubscribed) return;
_progSubscribed = false;
UiSources.Progression.Unsubscribe();
}
/// <summary>Sends "prog &lt;value&gt;" to RynthAi; the snapshot re-polls after its next tick applies it.</summary>
private static void SendProg(string value)
{
RynthAiCommands.ApplyRemoteCommand("prog", value);
UiSources.Progression.RequestRefreshAfterPluginTick();
}
private void AskProgConfirm(string title, string text, string yes, string command)
{
_progConfirmTitle = title;
_progConfirmText = text;
_progConfirmYes = yes;
_progConfirmCommand = command;
_progConfirmOpenRequested = true;
}
// ── Body ────────────────────────────────────────────────────────────
private void DrawProgression(float w)
{
ProgressionInfo? info = UiSources.Progression.Current?.Value;
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4));
try
{
DrawXpPlanner(w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
if (info == null || !info.Available)
{
Message("Augmentations and Enlightenment need RynthAi's ILT features on an ILT world.", w);
return;
}
DrawAttrRaiser(info.Attr, w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
DrawAugPlanner(info.Aug, w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
DrawEnlPlanner(info.Enl, w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 8));
}
finally
{
ImGuiNET.ImGui.PopStyleVar();
}
}
private void DrawXpPlanner(float w)
{
Section("XP planner", w);
if (_snap == null || _dat == null || _attributes.Count == 0)
{
Message("Waiting for your character's data...", w);
return;
}
ImGuiNET.ImGui.Indent(8);
long have = _snap.UnassignedXp;
Label($"Unassigned XP: {have:N0}", have > 0 ? Teal : Mute);
ImGuiNET.ImGui.SetNextItemWidth(160);
ImGuiNET.ImGui.SliderInt("Raises to plan##prog_lv", ref _planLevels, 1, 100);
if (ImGuiNET.ImGui.BeginTable("##prog_xp", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Stat");
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 50);
ImGuiNET.ImGui.TableSetupColumn("Next raise", ImGuiTableColumnFlags.WidthFixed, 100);
ImGuiNET.ImGui.TableSetupColumn($"Next {_planLevels}", ImGuiTableColumnFlags.WidthFixed, 120);
ImGuiNET.ImGui.TableHeadersRow();
foreach (Row r in _attributes) PlannerRow(r, have);
foreach (Row r in _vitals) PlannerRow(r, have);
ImGuiNET.ImGui.EndTable();
}
Label("Exact costs from the client's XP tables. Raise on the Attributes & Vitals tab"
+ (ProgressionTabVisible ? ", or past the cap with the Attribute raiser below." : "."), Dim);
ImGuiNET.ImGui.Unindent(8);
}
private void PlannerRow(Row r, long have)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Name);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Base.ToString(CultureInfo.InvariantCulture));
uint[]? table = r.Table;
int left = table == null ? 0 : Math.Max(0, table.Length - 1 - (int)Math.Min(r.Ranks, (uint)int.MaxValue));
ImGuiNET.ImGui.TableNextColumn();
if (table == null || left == 0) { Label(table == null ? "-" : "max", Dim); ImGuiNET.ImGui.TableNextColumn(); Label("-", Dim); return; }
long one = SkillDat.CostOf(table, r.Ranks, r.Spent, 1);
Label(one >= 0 ? one.ToString("N0", CultureInfo.InvariantCulture) : "-", one >= 0 && one <= have ? Teal : Dim);
ImGuiNET.ImGui.TableNextColumn();
int n = Math.Min(_planLevels, left);
long many = SkillDat.CostOf(table, r.Ranks, r.Spent, n);
string text = many >= 0 ? many.ToString("N0", CultureInfo.InvariantCulture) : "-";
if (n < _planLevels) text += $" ({n} to max)";
Label(text, many >= 0 && many <= have ? Teal : Dim);
}
private static readonly string[] AttrModes =
{
"Priority - top of the order first",
"Round robin - one level each, in order",
"Cheapest next level first",
};
private string? _attrKeepEdit; // reserve box being typed in (null = show RynthAi's value)
private int? _attrEveryEdit; // interval box being typed in
private void DrawAttrRaiser(AttrRaiser? a, float w)
{
Section("Attribute raiser (infinite attributes)", w);
ImGuiNET.ImGui.Indent(8);
float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24;
ImGuiNET.ImGui.PushTextWrapPos(wrap);
try
{
if (a == null) { Label("Update RynthAi to use the attribute raiser.", Mute); return; }
if (a.Off) { Label(a.Reason, Mute); return; }
Label(a.XpHeader.Length > 0 ? a.XpHeader : a.Unassigned, Teal);
if (a.XpHeader.Length > 0 && a.Unassigned.Contains("spendable", StringComparison.Ordinal)) Label(a.Unassigned, Dim);
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (a.Running)
{
if (Button("##attr_stop", "Stop", p, new Vector2(90, 24), Text, StopBg)) SendProg("attrstop");
}
else if (Button("##attr_run", "Raise now", p, new Vector2(110, 24), Text, StartBg, border: Teal))
SendProg("attrrun");
if (Button("##attr_costs", "Refresh XP", new Vector2(p.X + 116, p.Y), new Vector2(100, 24), Text, BtnFill, enabled: !a.Running))
SendProg("attrcosts");
ImGuiNET.ImGui.SetItemTooltip("Re-reads every next-level cost with /xp all.");
if (a.Updated.Length > 0)
{
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 224, p.Y + 4));
Label("Last updated: " + a.Updated, Dim);
}
NextLine(p, 28);
if (a.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(a.Status);
if (a.LastRun.Length > 0) Label("Last run: " + a.LastRun, Dim);
ImGuiNET.ImGui.Separator();
bool auto = a.Auto;
if (ImGuiNET.ImGui.Checkbox("Auto-raise from unassigned XP##attr_auto", ref auto))
SendProg("attrauto " + (auto ? "on" : "off"));
ImGuiNET.ImGui.SameLine();
// Commit on Enter, the +/- buttons or focus loss (not on every keystroke: each send
// restarts the auto-raise timer).
int every = _attrEveryEdit ?? a.Every;
ImGuiNET.ImGui.SetNextItemWidth(90);
bool everyCommit = ImGuiNET.ImGui.InputInt("every (min)##attr_every", ref every, 1, 10, ImGuiInputTextFlags.EnterReturnsTrue);
bool everyActive = ImGuiNET.ImGui.IsItemActive();
if (everyCommit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_attrEveryEdit = null;
if (every != a.Every) SendProg("attrevery " + Math.Clamp(every, 1, 1440).ToString(CultureInfo.InvariantCulture));
}
else _attrEveryEdit = everyActive ? every : null;
if (a.Auto && a.Next.Length > 0) Label($"Next auto-raise: {a.Next}", Dim);
int mode = Math.Clamp(a.Mode, 0, AttrModes.Length - 1);
ImGuiNET.ImGui.SetNextItemWidth(260);
if (ImGuiNET.ImGui.Combo("Raise order##attr_mode", ref mode, AttrModes, AttrModes.Length))
SendProg("attrmode " + mode.ToString(CultureInfo.InvariantCulture));
// The box holds the exact reserve (KeepFull); it is sent only when the text changed, so an
// Enter on an untouched box can't round the reserve.
string shownKeep = a.KeepFull.Length > 0 ? a.KeepFull : a.Keep;
string keep = _attrKeepEdit ?? shownKeep;
ImGuiNET.ImGui.SetNextItemWidth(140);
bool enter = ImGuiNET.ImGui.InputTextWithHint("Keep in reserve (XP)##attr_keep", "0, 500m, 2b", ref keep, 32u,
ImGuiInputTextFlags.EnterReturnsTrue);
bool keepActive = ImGuiNET.ImGui.IsItemActive();
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_attrKeepEdit = null;
if (!string.Equals(keep.Trim(), shownKeep, StringComparison.Ordinal))
SendProg("attrkeep " + keep.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal));
}
else _attrKeepEdit = keepActive ? keep : null;
ImGuiNET.ImGui.SetItemTooltip("Unassigned XP the raiser never spends. Accepts k / m / b / t suffixes.");
DrawAttrTable(a, w);
Label("Auto: the stats Raise now / auto-raise may spend on; arrows set the order. "
+ "+1 / +10 raise by hand (red = not enough unassigned XP). "
+ "+10 is an estimate (7.7% dearer per level); the server charges the real cost. " + a.CostsAge + ".", Dim);
}
finally
{
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.Unindent(8);
}
}
/// <summary>
/// UB Leaftide XP tab layout: Auto tick, stat, base, then "+1 Level" / "+10 Levels" buttons
/// labelled with what they cost, then the priority arrows.
/// </summary>
private void DrawAttrTable(AttrRaiser a, float w)
{
if (!ImGuiNET.ImGui.BeginTable("##prog_attr", 6, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
return;
ImGuiNET.ImGui.TableSetupColumn("Auto", ImGuiTableColumnFlags.WidthFixed, 34);
ImGuiNET.ImGui.TableSetupColumn("Stat");
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 56);
ImGuiNET.ImGui.TableSetupColumn("+1 Level", ImGuiTableColumnFlags.WidthFixed, 84);
ImGuiNET.ImGui.TableSetupColumn("+10 Levels", ImGuiTableColumnFlags.WidthFixed, 84);
ImGuiNET.ImGui.TableSetupColumn("Order", ImGuiTableColumnFlags.WidthFixed, 48);
ImGuiNET.ImGui.TableHeadersRow();
for (int i = 0; i < a.Rows.Length; i++)
{
AttrRow r = a.Rows[i];
ImGuiNET.ImGui.PushID("attr_" + r.Key);
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn();
bool on = r.On;
if (ImGuiNET.ImGui.Checkbox("##on", ref on)) SendProg($"attron {r.Key} {(on ? "on" : "off")}");
ImGuiNET.ImGui.TableNextColumn();
Label($"{i + 1}. {r.Label}", r.On ? Text : Mute);
ImGuiNET.ImGui.TableNextColumn();
int clientBase = ClientBase(r);
Label(clientBase > 0 ? clientBase.ToString("N0", CultureInfo.InvariantCulture)
: r.Base >= 0 ? r.Base.ToString("N0", CultureInfo.InvariantCulture) : "-", Text);
// Older RynthAi sends no cost10 / afford1: plain buttons, the server decides.
bool rich = r.Cost10.Length > 0;
ImGuiNET.ImGui.TableNextColumn();
RaiseButton(a, r, 1, rich ? r.Cost : "+1", rich ? r.Afford1 : true, r.CostFull, rich);
ImGuiNET.ImGui.TableNextColumn();
RaiseButton(a, r, 10, rich ? r.Cost10 : "+10", rich ? r.Afford10 : true, r.Cost10Full, rich);
ImGuiNET.ImGui.TableNextColumn();
ImGuiNET.ImGui.BeginDisabled(i == 0);
if (ImGuiNET.ImGui.ArrowButton("##up", ImGuiDir.Up)) SendProg($"attrmove {r.Key} up");
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SameLine(0, 2);
ImGuiNET.ImGui.BeginDisabled(i == a.Rows.Length - 1);
if (ImGuiNET.ImGui.ArrowButton("##down", ImGuiDir.Down)) SendProg($"attrmove {r.Key} down");
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.EndTable();
}
/// <summary>
/// One by-hand raise button filling its cell. Unknown cost ("?") stays clickable (the server
/// checks); a known cost over the unassigned XP is red and disabled.
/// </summary>
private static void RaiseButton(AttrRaiser a, AttrRow r, int levels, string label, bool afford, string exact, bool rich)
{
bool known = rich && r.Known;
bool enabled = !a.Running && (!known || afford);
uint fg = !known ? Text : afford ? Teal : Red;
Vector2 pos = ImGuiNET.ImGui.GetCursorScreenPos();
float width = Math.Max(40f, ImGuiNET.ImGui.GetContentRegionAvail().X);
if (Button("##raise" + levels, label, pos, new Vector2(width, 20), fg, BtnFill, enabled, border: known && afford ? Teal : 0))
SendProg($"attrraise {r.Key} {levels}");
string what = $"{r.Label} +{levels} level{(levels > 1 ? "s" : "")}";
string tip = !known ? $"{what}: cost not read yet (Refresh XP)."
: levels > 1 ? $"{what}: about {exact} XP (estimate)."
: $"{what}: {exact} XP.";
if (known && !afford) tip += " Not enough unassigned XP.";
if (a.Running) tip += " Wait for the raise run to finish.";
ImGuiNET.ImGui.SetItemTooltip(tip);
}
/// <summary>The client's own base value for a raiser row (0 when the snapshot has none).</summary>
private int ClientBase(AttrRow r)
{
List<Row> rows = r.Vital ? _vitals : _attributes;
foreach (Row row in rows)
if (row.Name.Equals(r.Label, StringComparison.OrdinalIgnoreCase)) return row.Base;
return 0;
}
private void DrawAugPlanner(AugPlanner a, float w)
{
Section("Augmentations", w);
ImGuiNET.ImGui.Indent(8);
try
{
if (a.Off) { Label("/aug is not available on this server.", Mute); return; }
// UB Augs tab buttons: Refresh Current, Reset Target, Copy Discord, Copy In-Game.
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float x = p.X;
if (Button("##aug_refresh", "Refresh current", new Vector2(x, p.Y), new Vector2(120, 22), Text, StartBg, border: Teal))
SendProg("augload");
ImGuiNET.ImGui.SetItemTooltip("Reads your augmentation levels with /aug (also done once when this tab first opens).");
x += 124;
if (Button("##aug_reset", "Reset targets", new Vector2(x, p.Y), new Vector2(104, 22), Text, BtnFill))
SendProg("augreset");
ImGuiNET.ImGui.SetItemTooltip("Sets every target back to the current level.");
x += 108;
if (Button("##aug_discord", "Copy Discord", new Vector2(x, p.Y), new Vector2(100, 22), Text, BtnFill, enabled: a.CopyDiscord.Length > 0))
ImGuiNET.ImGui.SetClipboardText(a.CopyDiscord);
ImGuiNET.ImGui.SetItemTooltip("Copies the plan as a Discord code-block table.");
x += 104;
if (Button("##aug_ingame", "Copy in-game", new Vector2(x, p.Y), new Vector2(100, 22), Text, BtnFill, enabled: a.CopyIngame.Length > 0))
ImGuiNET.ImGui.SetClipboardText(a.CopyIngame);
ImGuiNET.ImGui.SetItemTooltip("Copies your current levels as one chat line.");
NextLine(p, 26);
Label("Status: " + a.Status, Dim);
if (ImGuiNET.ImGui.BeginTable("##prog_augs", 6, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Aug");
ImGuiNET.ImGui.TableSetupColumn("Current", ImGuiTableColumnFlags.WidthFixed, 56);
ImGuiNET.ImGui.TableSetupColumn("Target", ImGuiTableColumnFlags.WidthFixed, 124);
ImGuiNET.ImGui.TableSetupColumn("Inc", ImGuiTableColumnFlags.WidthFixed, 44);
ImGuiNET.ImGui.TableSetupColumn("Luminance", ImGuiTableColumnFlags.WidthFixed, 76);
ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 56);
ImGuiNET.ImGui.TableHeadersRow();
foreach (AugRow row in a.Rows)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Label);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Current.ToString("N0", CultureInfo.InvariantCulture));
ImGuiNET.ImGui.TableNextColumn();
DrawAugTarget(row);
int inc = row.Increase > 0 ? row.Increase : Math.Max(0, row.Target - row.Current);
ImGuiNET.ImGui.TableNextColumn(); Label(inc > 0 ? inc.ToString("N0", CultureInfo.InvariantCulture) : "-", inc > 0 ? Teal : Dim);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Lum);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Coins > 0 ? row.Coins.ToString("N0", CultureInfo.InvariantCulture) : "-");
}
if (a.TotalLum.Length > 0)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); Label("TOTALS", Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalCurrent.ToString("N0", CultureInfo.InvariantCulture), Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalTarget.ToString("N0", CultureInfo.InvariantCulture), Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalIncrease.ToString("N0", CultureInfo.InvariantCulture), Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalLum, Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalCoins.ToString("N0", CultureInfo.InvariantCulture), Amber);
}
ImGuiNET.ImGui.EndTable();
}
// Lum per coin commits on Enter / focus loss, not per keystroke.
string shownLpc = a.LumPerCoin.ToString(CultureInfo.InvariantCulture);
string lpc = _augLpcEdit ?? shownLpc;
ImGuiNET.ImGui.SetNextItemWidth(140);
bool lpcEnter = ImGuiNET.ImGui.InputTextWithHint("Lum per e-coin##prog_lpc", "0 = don't price coins", ref lpc, 24u,
ImGuiInputTextFlags.EnterReturnsTrue);
bool lpcActive = ImGuiNET.ImGui.IsItemActive();
if (lpcEnter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augLpcEdit = null;
string clean = lpc.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal);
if (!string.Equals(clean, shownLpc, StringComparison.Ordinal)) SendProg("lumpercoin " + clean);
}
else _augLpcEdit = lpcActive ? lpc : null;
ImGuiNET.ImGui.SetItemTooltip("Luminance one Enlightened Coin costs you. Accepts k / m / b / t suffixes.");
if (a.CoinsLine.Length > 0)
{
Label(a.CoinsLine, Text);
Label(a.LumToBuy, Text);
}
else
{
Label(a.Total, Amber);
if (a.Short.Length > 0) Label(a.Short, Text);
}
Label(a.Banked, Dim);
if (a.Config != null) DrawAugCostSettings(a.Config, w);
}
finally
{
ImGuiNET.ImGui.Unindent(8);
}
}
private static readonly string[] AugTierNames = { "Below S1", "From S1", "From S2", "From S3", "From S4" };
// Cost-settings boxes being typed in, by box id (committed on Enter / focus loss).
private readonly Dictionary<string, int> _augCfgIntEdit = new(StringComparer.Ordinal);
private readonly Dictionary<string, double> _augCfgDblEdit = new(StringComparer.Ordinal);
/// <summary>
/// Collapsible editor for this world's aug cost rules (RynthAi saves them per world). The
/// defaults are UB's InfiniteLeaftide model; Reset puts a changed world back on them.
/// </summary>
private void DrawAugCostSettings(AugCostConfig cfg, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
string head = $"Cost settings for {cfg.World}" + (cfg.Custom ? " (custom)" : " (InfiniteLeaftide defaults)");
if (!ImGuiNET.ImGui.CollapsingHeader(head + "##aug_cfg")) return;
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w - 24);
Label("Level i costs (Base + (i - 1) x Base x Growth% / 100) x the multiplier of its tier. "
+ "A tier starts at its S level (UB's InfiniteLeaftide model). Changes apply to this world only.", Dim);
ImGuiNET.ImGui.PopTextWrapPos();
// Tier multipliers, one box each.
Label("Tier multipliers", Text);
for (int t = 0; t < AugTierNames.Length && t < cfg.Multipliers.Length; t++)
{
if (t > 0) ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.BeginGroup();
Label(AugTierNames[t], Mute);
ImGuiNET.ImGui.SetNextItemWidth(62);
CfgDouble($"mult{t}", cfg.Multipliers[t], v => $"augmult {t} {v.ToString("R", CultureInfo.InvariantCulture)}");
ImGuiNET.ImGui.EndGroup();
}
// Per-aug rules.
if (ImGuiNET.ImGui.BeginTable("##aug_cfg_rows", 9, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Aug");
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 74);
ImGuiNET.ImGui.TableSetupColumn("Growth%", ImGuiTableColumnFlags.WidthFixed, 54);
ImGuiNET.ImGui.TableSetupColumn("S1", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("S2", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("S3", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("S4", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("Cap", ImGuiTableColumnFlags.WidthFixed, 50);
ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 42);
ImGuiNET.ImGui.TableHeadersRow();
foreach (AugCostRule r in cfg.Rows)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Label);
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.base", (int)Math.Min(r.Base, int.MaxValue), $"augcfg {r.Key} base");
ImGuiNET.ImGui.TableNextColumn(); CfgDouble($"{r.Key}.pct", r.Percent, v => $"augcfg {r.Key} pct {v.ToString("R", CultureInfo.InvariantCulture)}");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s1", r.S1, $"augcfg {r.Key} s1");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s2", r.S2, $"augcfg {r.Key} s2");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s3", r.S3, $"augcfg {r.Key} s3");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s4", r.S4, $"augcfg {r.Key} s4");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.cap", r.Cap, $"augcfg {r.Key} cap");
ImGuiNET.ImGui.SetItemTooltip("Highest target level; 0 = no limit.");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.coins", r.Coins, $"augcfg {r.Key} coins");
ImGuiNET.ImGui.SetItemTooltip("Enlightened Coins per level.");
}
ImGuiNET.ImGui.EndTable();
}
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (Button("##aug_cfg_reset", "Reset to InfiniteLeaftide defaults", p, new Vector2(230, 22), Text, BtnFill, enabled: cfg.Custom))
SendProg("augcfgreset");
ImGuiNET.ImGui.SetItemTooltip("Drops this world's changes; it goes back to UB's InfiniteLeaftide rules.");
NextLine(p, 26);
}
/// <summary>Integer box that sends "<paramref name="verb"/> value" on Enter or focus loss.</summary>
private void CfgInt(string id, int value, string verb)
{
int v = _augCfgIntEdit.TryGetValue(id, out int typing) ? typing : value;
ImGuiNET.ImGui.SetNextItemWidth(-1);
bool enter = ImGuiNET.ImGui.InputInt("##cfg_" + id, ref v, 0, 0, ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augCfgIntEdit.Remove(id);
if (v != value) SendProg($"{verb} {Math.Max(0, v).ToString(CultureInfo.InvariantCulture)}");
}
else if (active) _augCfgIntEdit[id] = v;
else _augCfgIntEdit.Remove(id);
}
/// <summary>Decimal box (the caller sets its width) that sends <paramref name="command"/>(value) on Enter or focus loss.</summary>
private void CfgDouble(string id, double value, Func<double, string> command)
{
double v = _augCfgDblEdit.TryGetValue(id, out double typing) ? typing : value;
if (!id.StartsWith("mult", StringComparison.Ordinal)) ImGuiNET.ImGui.SetNextItemWidth(-1);
bool enter = ImGuiNET.ImGui.InputDouble("##cfg_" + id, ref v, 0, 0, "%.6g", ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augCfgDblEdit.Remove(id);
if (Math.Abs(v - value) > 1e-9 && double.IsFinite(v)) SendProg(command(Math.Max(0, v)));
}
else if (active) _augCfgDblEdit[id] = v;
else _augCfgDblEdit.Remove(id);
}
private string? _augLpcEdit; // Lum per coin box being typed in
private readonly Dictionary<string, int> _augTargetEdit = new(StringComparer.Ordinal); // target boxes being typed in
/// <summary>
/// Target cell: -/+ step one level (Ctrl: 100), typing commits on Enter or focus loss so a
/// half-typed number never reaches RynthAi. RynthAi clamps to current..cap.
/// </summary>
private void DrawAugTarget(AugRow row)
{
int tgt = _augTargetEdit.TryGetValue(row.Key, out int typing) ? typing : row.Target;
ImGuiNET.ImGui.SetNextItemWidth(-1);
bool commit = ImGuiNET.ImGui.InputInt("##prog_tgt_" + row.Key, ref tgt, 1, 100, ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
if (commit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augTargetEdit.Remove(row.Key);
int clamped = Math.Clamp(tgt, row.Current, Math.Max(row.Cap, row.Current));
if (clamped != row.Target) SendProg($"augtarget {row.Key} {clamped.ToString(CultureInfo.InvariantCulture)}");
}
else if (active) _augTargetEdit[row.Key] = tgt;
else _augTargetEdit.Remove(row.Key);
ImGuiNET.ImGui.SetItemTooltip($"Target {row.Label} level (up to {row.Cap.ToString("N0", CultureInfo.InvariantCulture)}).");
}
private void DrawEnlPlanner(EnlPlanner e, float w)
{
Section("Enlightenment", w);
ImGuiNET.ImGui.Indent(8);
float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24; // window-local x
ImGuiNET.ImGui.PushTextWrapPos(wrap);
try
{
if (e.Off) { Label("/enl is not available on this server.", Mute); return; }
Label(e.Header, Text);
Label(e.Next, Teal);
int target = e.Target;
ImGuiNET.ImGui.SetNextItemWidth(100);
if (ImGuiNET.ImGui.InputInt("Plan to level##prog_enlt", ref target))
SendProg("enltarget " + Math.Max(e.Level + 1, target).ToString(CultureInfo.InvariantCulture));
foreach (string line in e.Plan) ImGuiNET.ImGui.BulletText(line);
int coinsPerToken = e.CoinsPerToken;
ImGuiNET.ImGui.SetNextItemWidth(100);
if (ImGuiNET.ImGui.InputInt("Coins per token (shop price)##prog_cpt", ref coinsPerToken))
SendProg("coinspertoken " + Math.Max(0, coinsPerToken).ToString(CultureInfo.InvariantCulture));
if (e.TokensShort.Length > 0) Label(e.TokensShort, Dim);
ImGuiNET.ImGui.Separator();
if (e.Blockers.Length == 0) Label("Client-side checks pass.", Green);
foreach (string b in e.Blockers) Label(b, Amber);
Label(e.ServerChecks, Dim);
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (Button("##prog_enl", "Enlighten now...", p, new Vector2(150, 24), Text, BtnFill, border: Teal))
AskProgConfirm("Enlighten",
"Send /enl now?\n\nEnlightening resets your level and wipes unassigned XP.\n"
+ "The server will show its own Yes/No dialog - you must click Yes there.",
"Send /enl", "enlighten");
NextLine(p, 28);
ImGuiNET.ImGui.Separator();
bool auto = e.Auto;
if (ImGuiNET.ImGui.Checkbox("Auto-enlighten when ready##prog_auto", ref auto))
{
if (auto)
AskProgConfirm("Arm auto-enlighten",
"Auto-enlighten will send /enl whenever the checks pass (peace mode, level, materials).\n"
+ "You still have to click Yes in the AC dialog each time.\n\nArm it for this session?",
"Arm", "autoenl on");
else
SendProg("autoenl off");
}
if (e.Auto && !e.Armed)
{
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Arm for this session...##prog_arm"))
AskProgConfirm("Arm auto-enlighten", "Arm auto-enlighten for this session?", "Arm", "autoenl arm");
}
bool spend = e.SpendFirst;
if (ImGuiNET.ImGui.Checkbox("Spend unassigned XP on attributes first##prog_spend", ref spend))
SendProg("spendfirst " + (spend ? "on" : "off"));
int every = e.CheckEvery;
ImGuiNET.ImGui.SetNextItemWidth(100);
if (ImGuiNET.ImGui.InputInt("Check every (s)##prog_every", ref every))
SendProg("checkevery " + Math.Max(10, every).ToString(CultureInfo.InvariantCulture));
Label(e.Armed ? "Armed." : "Disarmed.", e.Armed ? Amber : Dim);
if (e.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(e.Status);
}
finally
{
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.Unindent(8);
}
}
// ── Confirm ─────────────────────────────────────────────────────────
/// <summary>The Progression tab's Yes/No popup (outside the body child, like DrawConfirm).</summary>
private void DrawProgressionConfirm()
{
if (_progConfirmOpenRequested)
{
_progConfirmOpenRequested = false;
ImGuiNET.ImGui.OpenPopup(ProgConfirmId);
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
bool open = ImGuiNET.ImGui.BeginPopup(ProgConfirmId);
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return;
try
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
Label(_progConfirmTitle, Amber);
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 320);
Label(_progConfirmText, Text);
ImGuiNET.ImGui.PopTextWrapPos();
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4);
if (Button("##prog_yes", _progConfirmYes, p, new Vector2(120, 24), Text, StartBg))
{
SendProg(_progConfirmCommand);
ImGuiNET.ImGui.CloseCurrentPopup();
}
if (Button("##prog_no", "Cancel", new Vector2(p.X + 126, p.Y), new Vector2(90, 24), Text, BtnFill))
ImGuiNET.ImGui.CloseCurrentPopup();
NextLine(p, 28);
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
}

View file

@ -45,7 +45,7 @@ using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class SkillsFace : IImGuiPanel
internal sealed partial class SkillsFace : IImGuiPanel
{
public const string Title = "Skills";
@ -127,7 +127,7 @@ internal sealed class SkillsFace : IImGuiPanel
}
// ── State ───────────────────────────────────────────────────────────
private int _tab; // 0 skills, 1 attributes & vitals
private int _tab; // 0 skills, 1 attributes & vitals, 2 progression (ILT worlds)
private SortKey _sort = SortKey.Name;
private bool _descending;
private readonly bool[] _collapsed = { false, false, false, true };
@ -193,18 +193,23 @@ internal sealed class SkillsFace : IImGuiPanel
SkillDat.EnsureLoadQueued();
PortalSpellTable.EnsureLoadQueued();
MasteryFeed.PanelOpened(); // asks only on Aelrynth, and only if the last reply is stale
ProgressionShown();
}
public void OnHidden() => ProgressionHidden();
public void Draw()
{
PlayerProgressHooks.Want();
Refresh();
ApplyProgressionRequest();
if (_tab == 2 && !ProgressionTabVisible) _tab = 0;
float w = Begin(out Vector2 origin, out Vector2 size);
DrawSummary(w);
DrawTabs(w);
if (_tab == 0) DrawToolbar(w);
DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute");
if (_tab != 2) DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute");
float bodyH = Math.Max(60, Remaining(origin, size) - GripOverlap());
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
@ -212,7 +217,9 @@ internal sealed class SkillsFace : IImGuiPanel
ImGuiNET.ImGui.BeginChild("##skills_body", new Vector2(w, bodyH));
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
EnsureWidths();
if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead)
if (_tab == 2)
DrawProgression(bw);
else if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead)
Message("Waiting for your character's data...", bw);
else if (_dat == null)
Message("Loading skill names from the client's portal.dat: " + SkillDat.Status, bw);
@ -228,6 +235,7 @@ internal sealed class SkillsFace : IImGuiPanel
_picker.Draw();
DrawMulti();
DrawConfirm();
DrawProgressionConfirm();
}
// ── Data ────────────────────────────────────────────────────────────
@ -691,13 +699,18 @@ internal sealed class SkillsFace : IImGuiPanel
private void DrawTabs(float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float half = (w - 4) * 0.5f;
if (Button("##tab_skills", "Skills", p, new Vector2(half, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill,
// The Progression tab only exists on ILT-like worlds (RynthAi's snapshot says so).
int count = ProgressionTabVisible ? 3 : 2;
float tabW = (w - 4 * (count - 1)) / count;
if (Button("##tab_skills", "Skills", p, new Vector2(tabW, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill,
border: _tab == 0 ? Teal : 0))
_tab = 0;
if (Button("##tab_attrs", "Attributes & Vitals", new Vector2(p.X + half + 4, p.Y), new Vector2(half, 22),
if (Button("##tab_attrs", "Attributes & Vitals", new Vector2(p.X + tabW + 4, p.Y), new Vector2(tabW, 22),
_tab == 1 ? Teal : Text, _tab == 1 ? Selected : BtnFill, border: _tab == 1 ? Teal : 0))
_tab = 1;
if (count == 3 && Button("##tab_prog", "Progression", new Vector2(p.X + 2 * (tabW + 4), p.Y), new Vector2(tabW, 22),
_tab == 2 ? Teal : Text, _tab == 2 ? Selected : BtnFill, border: _tab == 2 ? Teal : 0))
_tab = 2;
NextLine(p, 26);
}

View file

@ -90,6 +90,7 @@ internal static unsafe class PhosphorIcons
public const string HourglassMedium = "\uE2B8";
public const string Hourglass = "\uE2B2";
public const string Info = "\uE2CE";
public const string Keyboard = "\uE2D8";
public const string Knife = "\uE636";
public const string Lightning = "\uE2DE";
public const string Leaf = "\uE2DA";
@ -168,7 +169,7 @@ internal static unsafe class PhosphorIcons
+ ArrowCircleUp + Barbell + Brain + GraduationCap + Hourglass + SortDescending + Package
+ Binoculars + Crown + Sun
+ CastleTurret + ClockCounterClockwise + GlobeHemisphereWest + Path + Star + Target + User
+ TextAa + Leaf;
+ TextAa + Leaf + Keyboard;
/// <summary>
/// Draws <paramref name="glyph"/> (one icon) centred in the box at

View file

@ -392,6 +392,14 @@ internal static unsafe class Win32Backend
RunOnGameThread<bool>(() => { action(); return true; });
}
/// <summary>
/// True once the game window is known AND its WndProc is subclassed, i.e.
/// <see cref="RunOnGameThread{T}"/> can actually deliver work to AC's main
/// thread. Knowing the HWND alone is not enough: without the subclass,
/// WM_RYNTH_RUN_ACTION reaches AC's own WndProc, which ignores it.
/// </summary>
public static bool CanRunOnGameThread => _initialized && _gameHwnd != IntPtr.Zero;
/// <summary>Deactivates chat capture. The game HWND retains focus throughout so no
/// Win32 focus transfer is needed.</summary>
public static void ReturnFocusToGame() => ChatCaptureActive = false;
@ -572,10 +580,11 @@ internal static unsafe class Win32Backend
if (!_initialized) return;
// Destroy floating panels while our hook can still run on the game
// thread. LayeredWindow.Dispose only POSTS its destroy, and the game
// thread usually hasn't reached that post by the time we unhook below —
// AC's own WndProc then drops it and the panel outlives this engine
// load, frozen and unclickable (duplicate RynthAi dashboard after RL).
// thread. LayeredWindow.Dispose posts its destroy to the panel itself
// (handled by the panel's own WndProc, which survives this unhook), but
// any panel never disposed would outlive this engine load, frozen and
// unclickable (duplicate RynthAi dashboard after RL) — this sweep is the
// synchronous backstop for those.
IntPtr swept = SendMessageTimeout(_gameHwnd, WM_RYNTH_SWEEP_PANELS, new IntPtr(1), IntPtr.Zero,
SMTO_NORMAL, 2000, out _);
if (swept == IntPtr.Zero)
@ -956,6 +965,17 @@ internal static unsafe class Win32Backend
// which used to be unusable whenever RynthChat was installed, even closed.
// !ImGuiTextInputActive: the same rule for an ImGui text box.
ExpireStaleCaptureFlags();
// ── User hotkeys (Settings > Hotkeys, Hotkeys/HotkeyService.cs) ──
// A bound combo's keystroke is eaten here, before AC, ImGui and the Enter-opens-chat
// branch below; every other key passes on. RynthChat's capture returned above, and
// the service holds hotkeys back while any text box (ours or AC's chat) is typed in.
if ((IsKeyMessage(msg) || IsExtraCharMessage(msg) || msg == WM_KILLFOCUS)
&& Hotkeys.HotkeyService.HandleKeyMessage(msg, wParam, lParam,
rynthTextFocus: ChatCaptureActive || AvaloniaTextInputActive || ImGuiTextInputActive
|| _wantCaptureKeyboard || ImGuiPopOuts.HasTextFocus))
return IntPtr.Zero;
if (msg == WM_KEYDOWN && (int)wParam == VK_RETURN && !IsExtendedKey(lParam) && !ChatCaptureActive && !AvaloniaTextInputActive
&& !ImGuiTextInputActive && !ImGuiPopOuts.HasTextFocus
&& RynthCore.Engine.Compatibility.ChatHooks.RynthChatOwnsChat)
@ -991,11 +1011,15 @@ internal static unsafe class Win32Backend
// HUD drag (keeps our SetCapture from fighting NewFrame's). No-op
// unless the HUD is drawn.
if (IsMouseMessage(msg))
{
TrackMouseButtons(msg, wParam);
ItemDragBridge.OnGameMouse(msg, wParam, lParam, _heldButtonsBelongToGame);
}
else if (msg == WM_KILLFOCUS)
{
_heldMouseButtons = 0;
_heldButtonsBelongToGame = false;
ItemDragBridge.Reset();
}
// ── Avalonia panel hit-test & input forwarding ────────────────
@ -1006,7 +1030,7 @@ internal static unsafe class Win32Backend
{
// fall through: AC gets the message
}
else if (IsMouseMessage(msg))
else if (IsMouseMessage(msg) && !ImGuiOwnsMouseOverAvalonia())
{
bool handled = TryForwardToAvalonia(msg, wParam, lParam);
if (handled)
@ -1097,6 +1121,14 @@ internal static unsafe class Win32Backend
}
}
// An AC inventory item dragged onto an ImGui window: AC must not drop it on the
// ground behind the window. It gets the release where the drag began instead.
if (ItemDragBridge.TryRedirectNativeDrop(msg, out IntPtr pressLParam))
{
CallWindowProcA(_originalWndProc, hWnd, WM_MOUSEMOVE, (IntPtr)MK_LBUTTON, pressLParam);
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, pressLParam);
}
// Pass through to original WndProc
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
}
@ -1107,6 +1139,17 @@ internal static unsafe class Win32Backend
}
}
/// <summary>
/// ImGui windows are drawn on top of the Avalonia layer, so when the cursor is over
/// an ImGui window (or an ImGui widget is active) mouse input must go to ImGui
/// instead of the Avalonia panel underneath. An Avalonia drag/resize that is already
/// in progress keeps its capture so the release is never lost.
/// </summary>
private static bool ImGuiOwnsMouseOverAvalonia()
{
return _wantCaptureMouse && !AvaloniaOverlay.HasPointerCapture;
}
/// <summary>
/// If the cursor is over the Avalonia shell panel, PostMessage the mouse event to
/// the off-screen Avalonia HWND and return true (caller should suppress game delivery).