RynthCore as of 2026-11-26 (internal 5e4b1f3): release 2026.11.26.1

This commit is contained in:
Tom Bohar 2026-11-26 22:32:30 -05:00
commit 2ff89683f4
75 changed files with 3838 additions and 173 deletions

View file

@ -0,0 +1,167 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AcCamera.cs
// Plugin API v99 (2026-11-24): AC's camera from a plugin, for the phone's Live
// view (RynthRemote's remote play): turn, tilt and zoom while held, and the
// views (the default one behind the character - "home" - and first person).
//
// It goes through AC's own camera key handler, CameraManager::OnAction(InputEvent
// const&) (0x00456060), with a made-up event: the action at +0x00, pressed at
// +0x20 - all that handler reads for its actions 0x33-0x3C. So a press does
// exactly what AC's camera key does, held until its release:
// 0x33 Closer CameraSet::Closer(1, 1.0f) / StopCloser
// 0x34 Farther CameraSet::Farther(1, 1.0f) / StopFarther
// 0x35/0x36 turn CameraSet::Rotate(a==0x35, 1, 1.0f, 1) / StopRotating
// 0x37 Raise CameraSet::Raise(1, 1.0f) / StopRaising
// 0x38 Lower CameraSet::Lower(1, 1.0f) / StopLowering
// 0x39 default CameraSet::SetDefaultOffsets(1) (on the press only)
// 0x3A first person CameraSet::SetInHead()
// The handler's this is the CameraManager's InputEventHandler part, the manager
// + 4 (it reads its CameraSet at [this + 0xB8] = manager + 0xBC). The manager is
// SmartBox + 0xA0 (CameraSet::CameraSet: [smartbox + 0xA0]); its CameraSet at
// + 0xBC points back at both (+0x08 the manager, +0x0C the SmartBox), which is
// checked before every call. Pattern only: a guessed address is never called.
// Queued from any thread, done on AC's game thread before its tick, like the
// shortcut slots. Nothing here throws across the boundary.
// ============================================================================
using System;
using System.Collections.Concurrent;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class AcCamera
{
/// <summary>The plugin API's camera actions (the SDK's RynthCameraAction).</summary>
public enum Action
{
Home = 0, // the default view behind the character (press only)
RotateLeft = 1, // held: the view turns left (the camera swings round to her right)
RotateRight = 2, // held: the view turns right
Raise = 3, // held: the camera swings up (it looks down at her)
Lower = 4, // held: the camera swings down (it looks up)
Closer = 5, // held: zoom in
Farther = 6, // held: zoom out
FirstPerson = 7, // press only
}
// AC's InputAction ids for them (CameraManager::OnAction's jump table, 0x33-0x3E).
private static int AcActionOf(Action a) => a switch
{
Action.Home => 0x39,
Action.RotateLeft => RotateLeftId,
Action.RotateRight => RotateRightId,
Action.Raise => 0x37,
Action.Lower => 0x38,
Action.Closer => 0x33,
Action.Farther => 0x34,
Action.FirstPerson => 0x3A,
_ => 0,
};
// 0x35 calls Rotate(1, ...), 0x36 Rotate(0, ...). On the test client (2026-11-24) an 80 ms 0x35 slid the houses
// ahead of her to the left of the picture - the view turned right - and 0x36 turned it left.
private const int RotateLeftId = 0x36, RotateRightId = 0x35;
private const int OnActionFallbackVa = 0x00456060;
// CameraManager::OnAction: esi = this, edi = the event; [edi] - 0x33 against 0x0B, the jump table, then the
// CameraSet at [esi + 0xB8].
private static readonly byte?[] OnActionPattern =
[
0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x8B, 0x17, 0x8D, 0x42, 0xCD, 0x83, 0xF8, 0x0B, 0x8B, 0xF1,
0x0F, 0x87, null, null, null, null, 0xFF, 0x24, 0x85, null, null, null, null,
0x8B, 0x8E, 0xB8, 0x00, 0x00, 0x00
];
private const int SmartBoxCameraManagerOffset = 0xA0;
private const int ManagerCameraSetOffset = 0xBC;
private const int ManagerHandlerOffset = 0x04;
private const int SetManagerOffset = 0x08, SetSmartBoxOffset = 0x0C;
private const int EventActionOffset = 0x00, EventPressedOffset = 0x20, EventSize = 0x40;
private static IntPtr _onAction;
private static bool _initialized;
private static string _status = "Not initialized.";
public static string Status => _status;
public static bool Available => _onAction != IntPtr.Zero;
private readonly record struct Request(Action Action, bool Pressed, long QueuedMs);
private static readonly ConcurrentQueue<Request> Queue = new();
private const int MaxQueued = 32;
private const long GiveUpMs = 2000;
public static void Initialize()
{
if (_initialized) return;
_initialized = true;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
_status = "acclient.exe not available.";
return;
}
var r = HookResolver.Resolve(text, "AcCamera.CameraManager::OnAction", OnActionPattern, OnActionFallbackVa);
_onAction = r.Success && r.Source == HookResolver.ResolveSource.PatternScan ? r.Address : IntPtr.Zero;
_status = _onAction != IntPtr.Zero ? $"CameraManager::OnAction at 0x{_onAction.ToInt64():X8}." : "CameraManager::OnAction not found.";
RynthLog.Compat("AcCamera: " + _status);
}
/// <summary>
/// Queues a camera key: <paramref name="pressed"/> true presses it (a held one goes on until its release),
/// false lets go. Home and FirstPerson act on the press. False when it can't be done here (not found, a
/// bad action, a full queue). Any thread.
/// </summary>
public static bool Enqueue(Action action, bool pressed)
{
Initialize();
if (!Available || AcActionOf(action) == 0) return false;
if (Queue.Count >= MaxQueued) return false;
Queue.Enqueue(new Request(action, pressed, Environment.TickCount64));
return true;
}
/// <summary>The CameraSet's manager, checked: its CameraSet points back at it and at the SmartBox.</summary>
private static IntPtr Manager()
{
if (!SmartBoxLocator.TryGetSmartBox(out IntPtr sb, out _, out _) || sb == IntPtr.Zero) return IntPtr.Zero;
if (!ClientObjectHooks.IsReadableSpan(sb + SmartBoxCameraManagerOffset, 4)) return IntPtr.Zero;
IntPtr mgr = *(IntPtr*)(sb + SmartBoxCameraManagerOffset);
if (mgr == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(mgr, ManagerCameraSetOffset + 4)) return IntPtr.Zero;
IntPtr set = *(IntPtr*)(mgr + ManagerCameraSetOffset);
if (set == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(set, SetSmartBoxOffset + 4)) return IntPtr.Zero;
if (*(IntPtr*)(set + SetManagerOffset) != mgr || *(IntPtr*)(set + SetSmartBoxOffset) != sb) return IntPtr.Zero;
return mgr;
}
/// <summary>Game thread, before AC's tick. Alloc-free when nothing is queued; never throws.</summary>
public static void Drain()
{
if (Queue.IsEmpty) return;
long now = Environment.TickCount64;
IntPtr mgr = IntPtr.Zero;
bool looked = false;
byte* ev = stackalloc byte[EventSize];
while (Queue.TryDequeue(out Request r))
{
// A press that waited too long is dropped; a release never is (it must not leave the camera turning).
if (r.Pressed && now - r.QueuedMs > GiveUpMs) continue;
if (!looked) { mgr = Manager(); looked = true; }
if (mgr == IntPtr.Zero) continue; // out of the world: there is no camera to move
try
{
new Span<byte>(ev, EventSize).Clear();
*(int*)(ev + EventActionOffset) = AcActionOf(r.Action);
ev[EventPressedOffset] = (byte)(r.Pressed ? 1 : 0);
((delegate* unmanaged[Thiscall]<IntPtr, byte*, byte>)_onAction)(mgr + ManagerHandlerOffset, ev);
}
catch (Exception ex)
{
RynthLog.Compat($"AcCamera: {r.Action} {(r.Pressed ? "press" : "release")} threw {ex.GetType().Name}: {ex.Message}");
}
}
}
/// <summary>Logout / relog: nothing queued for the old character.</summary>
public static void Reset()
{
while (Queue.TryDequeue(out _)) { }
}
}

View file

@ -623,7 +623,7 @@ internal static class AcMainThreadQueue
// Gesture-phase defer state for the action ring (mirrors the cast slot's
// 56e6946 guard; see DrainDeferTickCap note below for why we PROCEED
// rather than drop after the cap).
private static long _drainDeferSinceMs;
private static readonly GestureDeferRule _gestureDefer = new(DrainDeferMaxMs);
public static void Drain()
{
@ -726,13 +726,22 @@ internal static class AcMainThreadQueue
if (_ring.Count > 0)
{
// In milliseconds (was 250 Drain calls: 2 s to over 10 s depending on the frame rate).
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight)
// A head that stays the same motion past the cap is stuck, not playing, and is not
// waited on again until it changes (GestureDeferRule, R-20261123-152528-b02d).
if (PlayerPhysicsHooks.TryGetPendingMotionHead(out IntPtr motionHead))
{
long nowDefer = NowMs;
if (_drainDeferSinceMs == 0) _drainDeferSinceMs = nowDefer;
gestureSafeOnly = nowDefer - _drainDeferSinceMs <= DrainDeferMaxMs;
gestureSafeOnly = _gestureDefer.Defer(motionHead, nowDefer, out bool becameWedged);
if (becameWedged)
{
string line = $"AcMainThreadQueue: the character's motion queue has had the same motion first for {_gestureDefer.HeadAgeMs(nowDefer)} ms " +
$"(0x{motionHead.ToInt64():X}): taken as stuck, queued actions ({_ring.Count}) no longer wait for it until it changes.";
try { RynthLog.Compat(line); } catch { }
try { Net.FlightRecorder.Mark(Net.FlightMark.Note, text: line); } catch { }
}
}
if (!gestureSafeOnly) _drainDeferSinceMs = 0;
else
_gestureDefer.Unread();
}
long runAt = NowMs;
int epochNow = Volatile.Read(ref _loginEpoch);
@ -896,7 +905,7 @@ internal static class AcMainThreadQueue
}
}
// The gesture-safe entries emptied the ring: the next held entry gets its own full defer.
if (gestureSafeOnly && _ring.Count == 0) _drainDeferSinceMs = 0;
if (gestureSafeOnly && _ring.Count == 0) _gestureDefer.RingEmptied();
}
/// <summary>

View file

@ -86,4 +86,15 @@ internal static class AcMouseOverRules
/// the plates keep today's behaviour when AC's UI can't be read).
/// </summary>
public static bool UnderUiOverlayMayTakeClick(AcMouseTarget target) => target != AcMouseTarget.AcWindow;
/// <summary>
/// Should a panel drawn under AC's windows (PanelSpec.UnderUi) let the mouse through this frame?
/// Where an AC window covers the cursor, yes, unless the left button is held on a press that
/// began on the panel itself (its own drag carries on over the AC window). A press that began on
/// the game (an item dragged in AC's inventory) is AC's: the panel behind must not catch its
/// drop (problem report R-20261126-194457-f7d8: every inventory move snapped back while a
/// DreamWeave panel sat behind AC's inventory).
/// </summary>
public static bool UnderUiPanelClickThrough(AcMouseTarget target, bool leftDown, bool pressBelongsToGame) =>
target == AcMouseTarget.AcWindow && (!leftDown || pressBelongsToGame);
}

View file

@ -93,6 +93,27 @@ internal static class ChatCallbackHooks
private static IntPtr _lastOutgoingThis;
private static uint _lastOutgoingSource = 8;
// The client's one ClientCommunicationSystem (the 'this' every OnChatCommand gets: the
// chat bar fetches it with ClientCommunicationSystem::GetCommunicationSystem, which is just
// "mov eax, [s_pCommunicationSystem]; ret"). Read live, so the direct route works before the
// player has ever pressed Enter in AC's own chat bar. With RynthChat standing in for that
// bar (its "Hide retail chat"), nobody ever did, so every line the dispatcher hands to AC's
// parser (emotes, *wave*, /e, /a, /f, any other command) fell back to typing keystrokes into
// the hidden chat bar (2026-11-24: "I have to activate the old chat window to do emotes").
// Found by its code-xref only (never a guessed address): zero when the pattern isn't unique.
private static IntPtr _commSystemGlobal;
private static bool _commSystemLogged;
/// <summary>OnChatCommand's i_idCommandSource for the main chat window (ChatWindowId.Main).</summary>
private const uint MainChatWindowSource = 1;
// GetCommunicationSystem (0x0056F230): A1 <s_pCommunicationSystem> C3, its padding and the
// next function's first bytes (unique in the 4,841,472-byte client, checked 2026-11-26).
private static readonly byte?[] PatXrefCommunicationSystem =
[
0xA1, null, null, null, null, 0xC3, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90,
0x85, 0xC9, 0x74, 0x14, 0x8D, 0x41, 0x08, 0x8B, 0x0D
];
private const int CommunicationSystemFallbackVa = 0x008717FC;
public static bool IncomingInstalled { get; private set; }
public static bool OutgoingInstalled { get; private set; }
public static bool IsInstalled => (!EnableIncomingHook || IncomingInstalled) && (!EnableOutgoingHook || OutgoingInstalled);
@ -150,6 +171,7 @@ internal static class ChatCallbackHooks
MinHook.Enable(_outgoingAddress);
OutgoingInstalled = true;
outgoingStatus = $"0x{_outgoingAddress.ToInt32():X8} ({outgoingResolution})";
ResolveCommunicationSystem(textSection);
}
catch (Exception ex)
{
@ -758,17 +780,54 @@ internal static class ChatCallbackHooks
return opcode is 0xE9 or 0xE8 or 0xEB or 0x68 or 0xFF;
}
/// <summary>True once a chat-manager 'this' has been captured from a live submit.</summary>
/// <summary>True when a line can go straight to AC's chat parser: a 'this' captured from a live
/// submit, or the client's communication system read from its global.</summary>
public static bool CanDispatchDirect =>
OutgoingInstalled && _originalOutgoingChat != null && _lastOutgoingThis != IntPtr.Zero;
OutgoingInstalled && _originalOutgoingChat != null
&& (_lastOutgoingThis != IntPtr.Zero || ReadCommunicationSystem() != IntPtr.Zero);
/// <summary>Finds s_pCommunicationSystem by its code-xref. Once, with the outgoing hook.</summary>
private static void ResolveCommunicationSystem(AcClientTextSection textSection)
{
try
{
var r = HookResolver.ResolveData(textSection, "ChatCallback.CommunicationSystem",
PatXrefCommunicationSystem, 1, CommunicationSystemFallbackVa);
// A guessed address is never read: without the pattern the direct route needs a live submit, as before.
_commSystemGlobal = r.Source == HookResolver.ResolveSource.PatternScan ? r.Address : IntPtr.Zero;
RynthLog.Compat(_commSystemGlobal != IntPtr.Zero
? $"Compat: chat parser reachable without a chat-bar send (communication system @ 0x{_commSystemGlobal.ToInt32():X8})."
: "Compat: communication system not found: lines for AC's chat parser need one chat-bar send first, as before.");
}
catch (Exception ex)
{
_commSystemGlobal = IntPtr.Zero;
RynthLog.Compat($"Compat: communication system lookup failed - {ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>The client's ClientCommunicationSystem right now, or zero (not found, not in the world, unreadable).</summary>
private static IntPtr ReadCommunicationSystem()
{
IntPtr global = _commSystemGlobal;
if (global == IntPtr.Zero || !LoginLifecycleHooks.HasObservedLoginComplete) return IntPtr.Zero;
try
{
if (!MemoryProbe.IsAccessible(global)) return IntPtr.Zero;
IntPtr self = Marshal.ReadIntPtr(global);
return self != IntPtr.Zero && MemoryProbe.IsAccessible(self) ? self : IntPtr.Zero;
}
catch { return IntPtr.Zero; }
}
/// <summary>
/// Dispatches a chat line by calling AC's outgoing-chat function directly — the
/// same path AC takes when you press Enter on the native chat bar, but with no
/// keystroke simulation and no chat-bar state, so it is repeatable. Uses the
/// 'this' + command source captured by <see cref="OutgoingChatDetour"/> from a
/// prior real submit. Returns false if the hook isn't installed or no 'this' has
/// been captured yet — the caller then falls back to keystroke simulation, whose
/// prior real submit, else (2026-11-26) the client's communication system and the
/// main chat window as the source. Returns false if the hook isn't installed or
/// neither is there — the caller then falls back to keystroke simulation, whose
/// first successful send seeds the capture for all subsequent calls.
/// Plugin pre-dispatch / engine-command handling is the caller's responsibility
/// (already done in ChatCommandDispatcher.Dispatch), so this goes straight to AC.
@ -778,9 +837,24 @@ internal static class ChatCallbackHooks
if (!OutgoingInstalled || _originalOutgoingChat == null)
return false;
IntPtr self = _lastOutgoingThis;
if (self == IntPtr.Zero || string.IsNullOrWhiteSpace(text))
if (string.IsNullOrWhiteSpace(text))
return false;
IntPtr self = _lastOutgoingThis;
uint source = _lastOutgoingSource;
if (self == IntPtr.Zero)
{
// No chat-bar send seen (RynthChat owns the chat): the client's own communication
// system, as the main chat window's bar would use.
self = ReadCommunicationSystem();
if (self == IntPtr.Zero)
return false;
source = MainChatWindowSource;
if (!_commSystemLogged)
{
_commSystemLogged = true;
RynthLog.Compat("Compat: chat line sent to AC's parser through the communication system (no chat-bar send seen yet).");
}
}
string line = text!.TrimEnd('\r', '\n');
if (line.Length == 0)
@ -801,7 +875,7 @@ internal static class ChatCallbackHooks
{
// 'wide' is a stack local (unmanaged struct) — its address is stable
// for the synchronous call, so no 'fixed' pin is needed (or allowed).
_originalOutgoingChat(self, (IntPtr)(&wide), _lastOutgoingSource);
_originalOutgoingChat(self, (IntPtr)(&wide), source);
return true;
}
finally { wide.Dispose(); }

View file

@ -210,9 +210,11 @@ internal static unsafe class ChatCommandDispatcher
if (StartsWithCmd(trimmed, "/emote "))
return DispatchEmote(trimmed.Substring(7));
// /e message (soul emote — client-side)
if (StartsWithCmd(trimmed, "/me "))
return DispatchSoulEmote(trimmed.Substring(4));
// /me message: AC's @emote ("Name looks menacingly at the mob"). It sent a soul emote
// (the text half of an action emote) until 2026-11-26. "/me" alone: AC's own @emote
// answers with how to use it. (/e and /em are AC's own: they take the parser path below.)
if (ChatLineRoute.IsMeEmote(trimmed, out string meText))
return meText.Length > 0 ? DispatchEmote(meText) : DispatchRaw("@emote");
// /tell Name, message
if (StartsWithCmd(trimmed, "/tell "))
@ -233,10 +235,23 @@ internal static unsafe class ChatCommandDispatcher
if (ChatLineRoute.IsAcEmoteLine(trimmed))
return DispatchRaw(trimmed);
// Any other @command (@loc, @friends, @age, @myquests): AC's parser too, as its chat
// bar does, so the client's own commands work and the rest still reach the server.
if (ChatLineRoute.IsAtCommand(trimmed))
return DispatchAtCommand(trimmed);
// Bare text → say
if (!trimmed.StartsWith("/", StringComparison.Ordinal))
return DispatchSay(trimmed);
// Last of all: "/wave" alone (and AC's other standard emotes, ChatSlashEmote.cs) is AC's
// "*Wave*". Only here, after the engine's /rc, every plugin's commands (Lua's too), the
// routes above and AC's own command words (none is an emote name) had their turn, so a
// real command always wins. Through the Decal bridge too: DispatchRaw hands "*Wave*" to
// Decal's InvokeChatParser, the same route a typed "*wave*" already takes there.
if (ChatSlashEmote.TryMatch(trimmed, out string emoteLine))
return DispatchRaw(emoteLine);
// Everything else (arbitrary slash commands like /smite) → raw chat path
return DispatchRaw(trimmed);
}
@ -387,6 +402,20 @@ internal static unsafe class ChatCommandDispatcher
return SimulateChatInput(command);
}
/// <summary>
/// An @command for AC's parser. Only the direct routes: where AC's parser can't be reached
/// that way the line goes out as speech text, as every @command did before 2026-11-26 (the
/// server still runs its own commands), never as simulated keystrokes.
/// </summary>
private static bool DispatchAtCommand(string command)
{
if (DecalBridgeHost.Active)
return DecalBridgeHost.TryInvokeChatParser(command);
if (ChatCallbackHooks.TryDispatchDirect(command))
return true;
return DispatchSay(command);
}
/// <summary>
/// Simulates keyboard input to type and submit a chat command.
/// Used as fallback for commands without a direct Event_* function.

View file

@ -189,7 +189,8 @@ internal static class ChatCommandReplies
V("title", "Usage: /rc title <title id>", a => uint.TryParse(a.Trim(), out uint t) && t != 0),
V("hotkey", HotkeyUsage, null),
V("rl", "Usage: /rc rl (reloads RynthCore, as the bar's RL button)", NoArgs, "reload"),
V("inventory", "Usage: /rc inventory (opens or closes the Inventory panel)", NoArgs, "inv"),
V("inventory", "Usage: /rc inventory (opens or closes the Inventory panel) | /rc inventory ac (closes it and opens AC's own bags)",
a => a.Length == 0 || Words("ac", "retail", "game")(a), "inv"),
V("sense", RynthCore.Engine.UI.Data.SenseLayout.Usage, RynthCore.Engine.UI.Data.SenseLayout.IsValidArgs),
V("characters", "Usage: /rc characters (opens or closes RynthNet's Characters window)", NoArgs, "chars"),
V("itemcount", "Usage: /rc itemcount (opens or closes the Item Count panel)", NoArgs, "itemhud"),
@ -198,7 +199,7 @@ internal static class ChatCommandReplies
V("actionstate", "Usage: /rc actionstate (the client's item-action gates)", NoArgs, "actions"),
V("unlockactions", "Usage: /rc unlockactions (opens the client's item-action gates now)", NoArgs, "unlock"),
V("vitals", "Usage: /rc vitals (the old vitals HUD is gone: /rv plates self)", NoArgs, "hud"),
V("layout", "Usage: /rc layout [status] | default | reset [confirm]", LayoutArgs),
V("layout", "Usage: /rc layout [status] | default | reset [confirm] | here", LayoutArgs),
// The extra chat windows (ImGui/Panels/ChatWindowFace); its handler checks the arguments
// (UI/Data/ChatWindows.Parse, whose Usage is this same line).
V("chatwindow", "Usage: /rc chatwindow [list] | open [tab] | close <2-7|all> | tab <2-7> <tab>", null, "chatwin", "chatwindows"),
@ -210,10 +211,10 @@ internal static class ChatCommandReplies
public const string UiCostUsage =
"Usage: /rc uicost [on|off|<ms>|now|status] (alone: now; <ms> = the slow-frame threshold, 5-2000)";
/// <summary>"/rc layout": nothing or status, default, reset, reset confirm (any spacing).</summary>
/// <summary>"/rc layout": nothing or status, default, reset, reset confirm, here (any spacing).</summary>
private static bool LayoutArgs(string a) =>
string.Join(' ', a.Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant()
is "" or "status" or "default" or "reset" or "reset confirm";
is "" or "status" or "default" or "reset" or "reset confirm" or "here";
/// <summary>The verb <paramref name="word"/> names (its name or another spelling), or null.</summary>
public static ChatVerb? Find(string word)

View file

@ -39,4 +39,29 @@ internal static class ChatLineRoute
}
return false;
}
/// <summary>
/// "/me text", the text emote other games have (2026-11-24 request: "/me looks menacingly at
/// the mob"). AC has no /me; it is AC's "@emote text" ("Name looks menacingly at the mob").
/// <paramref name="text"/> is what follows, trimmed; "" for "/me" alone.
/// </summary>
public static bool IsMeEmote(string trimmed, out string text)
{
text = "";
if (string.IsNullOrEmpty(trimmed) || !trimmed.StartsWith("/me", StringComparison.OrdinalIgnoreCase)) return false;
if (trimmed.Length == 3) return true;
if (!char.IsWhiteSpace(trimmed[3])) return false; // "/meet", "/menu" are not /me
text = trimmed[3..].Trim();
return true;
}
/// <summary>
/// True for an AC chat command written with '@' ("@loc", "@friends", "@age", "@myquests"):
/// '@' then a letter. AC's chat bar takes '@' and '/' alike; it runs its own commands
/// itself and passes the rest to the server, as it does for '/' lines. (They used to go out
/// as speech text, which the server runs as a command but AC never sees: "@loc" and the
/// other client commands did nothing from the RynthChat window.)
/// </summary>
public static bool IsAtCommand(string trimmed) =>
trimmed is { Length: >= 2 } && trimmed[0] == '@' && char.IsAsciiLetter(trimmed[1]);
}

View file

@ -0,0 +1,68 @@
using System;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// "/wave" as a shortcut for AC's "*Wave*" (2026-11-26 request). AC has no /wave: its help text
/// says the standard emotes are typed between asterisks, and these are its names for them
/// (acclient.exe). A line that is exactly "/" and one of them, in any case ("/WAVE", "/warmhands"
/// or "/warm hands"), becomes the asterisk form for AC's parser. Anything after the emote
/// ("/wave hello") is not an emote. None of these words is one of AC's own client commands
/// (its command table in acclient.exe, checked 2026-11-26), and the dispatcher asks this only
/// last, after the engine's /rc, every plugin's commands (Lua's too) and its own routes have
/// had the line, so a real command always wins. Pure: no AC, no engine state.
/// </summary>
internal static class ChatSlashEmote
{
/// <summary>AC's standard emotes, as its help text writes them.</summary>
public static readonly string[] Names =
[
"ShakeFist", "Beckon", "BeSeeingYou", "BlowKiss", "BowDeep", "ClapHands", "Cry", "Laugh", "Nod",
"Point", "Shrug", "Wave", "Akimbo", "HeartyLaugh", "Salute", "TapFoot", "WaveHigh", "WaveLow",
"Yawn", "Stretch", "Cringe", "Kneel", "Plead", "Shiver", "Shoo", "Slouch", "Spit", "Surrender",
"Woah", "Winded", "YMCA", "Eat", "Drink", "Teapot", "Pray", "Mock", "Cheer", "Helper",
"Warm Hands", "Scratch Head", "Shake Head",
];
/// <summary>
/// True when <paramref name="trimmed"/> (a trimmed line) is "/" and one emote name, nothing
/// else; <paramref name="acLine"/> is then AC's form, "*Wave*" or "*Warm Hands*". A two-word
/// name matches with its words run together or apart ("/warmhands", "/warm hands").
/// </summary>
public static bool TryMatch(string? trimmed, out string acLine)
{
acLine = "";
if (trimmed is not { Length: >= 2 } || trimmed[0] != '/') return false;
ReadOnlySpan<char> word = trimmed.AsSpan(1);
if (char.IsWhiteSpace(word[0])) return false; // "/ wave" is not a command word
foreach (string name in Names)
{
if (!SameName(word, name)) continue;
acLine = "*" + name + "*";
return true;
}
return false;
}
/// <summary>
/// <paramref name="word"/> is <paramref name="name"/>, ignoring case; where the name has a
/// space the word may have one or more spaces or none.
/// </summary>
private static bool SameName(ReadOnlySpan<char> word, string name)
{
int w = 0;
for (int n = 0; n < name.Length; n++)
{
char c = name[n];
if (c == ' ')
{
while (w < word.Length && char.IsWhiteSpace(word[w])) w++;
continue;
}
if (w >= word.Length || char.ToUpperInvariant(word[w]) != char.ToUpperInvariant(c)) return false;
w++;
}
return w == word.Length;
}
}

View file

@ -599,6 +599,7 @@ internal static class ClientHelperHooks
if (IsFullOwnedContainer(targetContainerId))
return false;
SplitGlobals keep = SplitGlobals.Read();
try
{
// P0 (2026-06-24): defensively restore the whole-move split globals to
@ -627,6 +628,63 @@ internal static class ClientHelperHooks
{
return false;
}
finally
{
// 2026-11-26: the two globals are also the retail toolbar's quantity (the number a
// player types to buy or split several, which AC's vendor and pack drags read). They are
// read inside the call only, so AC's own values go back afterwards: Autocram, RynthSort
// or the Inventory panel moving an item no longer turns the player's number into 1.
keep.Restore();
}
}
/// <summary>
/// AC's split_amount / total_stack as they were before one of our moves, put back after it.
/// Main thread (the callers run there). An unreadable pair is left alone.
/// </summary>
private readonly struct SplitGlobals
{
private readonly int _split, _total;
private readonly bool _ok;
private SplitGlobals(int split, int total) { _split = split; _total = total; _ok = true; }
public static SplitGlobals Read()
{
try
{
return new SplitGlobals(Marshal.ReadInt32(new IntPtr(_splitAmountAddr)), Marshal.ReadInt32(new IntPtr(_totalStackAddr)));
}
catch
{
return default;
}
}
public void Restore()
{
if (!_ok) return;
try { Marshal.WriteInt32(new IntPtr(_splitAmountAddr), _split); } catch { }
try { Marshal.WriteInt32(new IntPtr(_totalStackAddr), _total); } catch { }
}
}
/// <summary>
/// AC's split_amount: the retail toolbar's quantity (how many of the selected stack or vendor item
/// a drag takes). False when it can't be read. Main thread.
/// </summary>
public static bool TryReadSplitAmount(out int amount)
{
amount = 0;
try
{
amount = Marshal.ReadInt32(new IntPtr(_splitAmountAddr));
return true;
}
catch
{
return false;
}
}
/// <summary>
@ -650,6 +708,7 @@ internal static class ClientHelperHooks
if (slot < 0) return false;
if (amount <= 0) return false;
SplitGlobals keep = SplitGlobals.Read();
try
{
// Force split_amount < total_stack so FUN_00588f70 takes the split
@ -673,8 +732,9 @@ internal static class ClientHelperHooks
// onto the 0x55 specific-slot path. DORMANT today (AutoStack uses
// MergeStackInternal) but fixed defensively. Writes are individually
// try/caught so a failed restore can't escape the finally.
try { Marshal.WriteInt32(new IntPtr(_splitAmountAddr), 1); } catch { }
try { Marshal.WriteInt32(new IntPtr(_totalStackAddr), 1); } catch { }
// 2026-11-26: AC's own values go back (the retail toolbar's quantity, see
// MoveItemInternal), and MoveItemInternal forces 1/1 for its own call anyway.
keep.Restore();
}
}

View file

@ -152,6 +152,9 @@ internal static class GameTickHooks
// keys reach the toolbar: before this tick. Alloc-free when nothing is queued.
try { AcShortcuts.Drain(); }
catch { }
// The camera's keys from a plugin (AcCamera, v99), the same moment AC's own camera keys arrive.
try { AcCamera.Drain(); }
catch { }
// Run AC's own game-logic + physics + animation pass.
int result;

View file

@ -0,0 +1,80 @@
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Whether the action ring waits for the motion in flight (AcMainThreadQueue.Drain's gesture defer).
///
/// The ring holds everything but the gesture-safe entries while the character's pending-motion list
/// is non-empty, for at most MaxMs, then runs them and starts a new wait. R-20261123-152528-b02d
/// ("He's doing tiny jumps and attacking air", a Thread on DreamWeave, just after a death and
/// respawn): the list read non-empty for seconds with nothing playing - RynthAi's pacer and the cast
/// gate both logged the animation queue "stuck" after 4 s - so the ring ran only in bursts every
/// 2.5 s. A movement start is dropped as stale at 1.5 s, so nearly every walk the bot sent was
/// dropped ("dropped SetAutoRun(on) 2515 ms"), the character moved 0.65 m in 5 s, nav's stuck
/// check jumped, and the next target's select and attack ran 1.8 s late or not at all.
///
/// A list whose head is the same motion for longer than MaxMs isn't playing it: that is a wedge,
/// and the ring no longer waits on it until the head changes or the list empties (what the cap
/// already did for one wait, now for as long as it lasts). A list that moves on - a bow's shots,
/// swing after swing - is a new motion at the head each time and keeps the old waits.
/// </summary>
internal sealed class GestureDeferRule
{
public GestureDeferRule(long maxMs) => MaxMs = maxMs;
/// <summary>The longest one wait lasts, and how long one motion may sit at the head before it counts as stuck.</summary>
public long MaxMs { get; }
private long _since; // when the current wait began (0: not waiting)
private nint _head; // the motion at the head of the list when last read (0: none)
private long _headSince; // since when it has been the head
/// <summary>The motion at the head has been there longer than MaxMs: the ring doesn't wait on it.</summary>
public bool Wedged { get; private set; }
/// <summary>How long the head has been the same motion.</summary>
public long HeadAgeMs(long now) => _head == 0 ? 0 : now - _headSince;
/// <summary>
/// One drain with entries queued: true when only gesture-safe entries run now.
/// <paramref name="head"/> is the first pending motion (0: the list is empty).
/// <paramref name="becameWedged"/> is true on the drain the head is first taken as stuck.
/// </summary>
public bool Defer(nint head, long now, out bool becameWedged)
{
becameWedged = false;
if (head == 0)
{
_head = 0;
_headSince = 0;
Wedged = false;
_since = 0;
return false;
}
if (head != _head)
{
_head = head;
_headSince = now;
Wedged = false;
}
else if (!Wedged && now - _headSince > MaxMs)
{
Wedged = true;
becameWedged = true;
}
if (Wedged)
{
_since = 0;
return false;
}
if (_since == 0) _since = now;
bool defer = now - _since <= MaxMs;
if (!defer) _since = 0;
return defer;
}
/// <summary>The list couldn't be read: no wait (as before).</summary>
public void Unread() => _since = 0;
/// <summary>The gesture-safe entries emptied the ring: the next held entry gets its own full wait.</summary>
public void RingEmptied() => _since = 0;
}

View file

@ -543,6 +543,30 @@ internal static class PlayerPhysicsHooks
}
}
/// <summary>
/// The first pending motion of CMotionInterp (0: none), for AcMainThreadQueue's gesture defer
/// (GestureDeferRule): the same pointer there for seconds is a motion that isn't playing.
/// Main thread only; the pointer value is read, never followed.
/// </summary>
public static bool TryGetPendingMotionHead(out IntPtr head)
{
head = IntPtr.Zero;
if (!MainThreadGuard.IsOnMainThread())
return false;
if (!TryGetCMotionInterp(out IntPtr cmi) || cmi == IntPtr.Zero)
return false;
try
{
head = Marshal.ReadIntPtr(cmi + CMotionPendingMotionsHeadOffset);
return true;
}
catch
{
head = IntPtr.Zero;
return false;
}
}
/// <summary>
/// AC's local cast gate. True when CMotionInterp has a sequenced/one-shot
/// motion queued — i.e. a spell-cast (or other action) gesture is currently

View file

@ -229,6 +229,15 @@ internal static class RynthCoreChatCommands
return;
}
// /rc inv ac: close RynthCore's Inventory window and open AC's own bags (2026-11-26). Alone,
// /rc inv opens or closes the window (the switch below).
if ((IsVerb(sub, "inv", out string invArgs) || IsVerb(sub, "inventory", out invArgs)) && invArgs.Length > 0)
{
var (ok, message) = ImGuiBackend.Panels.InventoryFace.UseAcBags();
if (ok) Reply(message); else Fail(message);
return;
}
// /rc vendor [list|info|status|buy <id|sel> [n]|sell <id|sel> [id ...]]: VendorTrade's own
// "[RC]" lines are the reply (to chat from the main-thread drain, and to the log).
if (IsVerb(sub, "vendor", out string vendorArgs))
@ -1284,9 +1293,10 @@ internal static class RynthCoreChatCommands
return;
}
// The list (2026-11-22): the selected object's name, and Virindi Sense's list brought over.
if (UI.Data.SenseLayout.IsAddSelected(args))
// An exact term (whole name) by default since 2026-11-26; "addselected contains" for a contains one.
if (UI.Data.SenseLayout.IsAddSelected(args, out bool exactName))
{
bool added = UI.Data.SenseStore.AddSelected(out string message);
bool added = UI.Data.SenseStore.AddSelected(out string message, exactName);
Answer(added, "Sense: " + message, "Sense: " + message);
return;
}
@ -1823,6 +1833,10 @@ internal static class RynthCoreChatCommands
Answer(problem == null, ask, problem ?? "");
return;
}
case UI.LayoutCommand.BringHere:
// Answered from the game thread once the windows have moved (ImGuiPopOuts.Gather).
ImGuiBackend.ImGuiPopOuts.RequestGather(LaterReply());
return;
case UI.LayoutCommand.MakeDefault:
case UI.LayoutCommand.ResetConfirm:
{

View file

@ -280,6 +280,7 @@ internal static unsafe class UiFlowHooks
try { RetailVitalsHooks.ResetCachedInstance(); } catch { }
try { RetailToolbarHooks.ResetCachedInstance(); } catch { }
try { AcShortcuts.Reset(); } catch { }
try { AcCamera.Reset(); } catch { }
try { AcKeymapLive.Reset(); } catch { }
try { AcPanels.Reset(); } catch { }
try { UiElementHooks.OnScreenLeaving(); } catch { }

View file

@ -0,0 +1,74 @@
// ============================================================================
// RynthCore.Engine - Compatibility/VendorBuyMath.cs
//
// The Inventory panel's "Buy how many?" box (2026-11-26, a player at a vendor
// couldn't buy in bulk with RynthCore's windows up): an item dragged out of an
// open vendor's list onto the panel asks how many, then buys through
// VendorTrade. These are its numbers:
//
// max the most one buy can ask for: what the vendor has (unlimited: the
// engine's 24-bit limit), and, when the money is known, what it pays
// for (the cost isn't linear: ACE prices each created stack with a
// floor of 1, so it is searched, not divided). Pack room and burden
// aren't counted here: VendorTrade checks them before it sends and
// says why it won't.
// prefill the box starts at the retail toolbar's number (AC's split_amount,
// what a drag of that item would take in AC's own windows) when it
// is 2 or more and can be bought, else at 1.
// clamp a typed number stays between 1 and max (1 when max is 0: the Buy
// button is then off and says why).
//
// Pure (no AC, no engine state): tools\VendorRateTests compiles it in.
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal static class VendorBuyMath
{
/// <summary>The most one request carries (an ItemProfile packs 24 bits; VendorTrade's MaxTradeAmount).</summary>
public const int MaxAmount = 0x7FFFFF;
/// <summary>
/// The most one buy of this item can ask for. <paramref name="stock"/>: what the vendor has (below 0:
/// unlimited). <paramref name="money"/>: what the player can pay with (below 0: unknown, not counted).
/// <paramref name="cost"/>: the price of n (rises with n). 0 when not even one can be bought.
/// </summary>
public static int MaxBuy(int stock, long money, Func<int, long> cost)
{
int cap = stock < 0 ? MaxAmount : Math.Min(stock, MaxAmount);
if (cap < 1) return 0;
if (money < 0) return cap;
if (Cost(cost, 1) > money) return 0;
if (Cost(cost, cap) <= money) return cap;
// The largest n in 1..cap with cost(n) <= money: cost(lo) fits, cost(hi) doesn't.
int lo = 1, hi = cap;
while (hi - lo > 1)
{
int mid = lo + (hi - lo) / 2;
if (Cost(cost, mid) <= money) lo = mid; else hi = mid;
}
return lo;
}
private static long Cost(Func<int, long> cost, int n)
{
long c = cost(n);
return c < 0 ? long.MaxValue : c;
}
/// <summary>Where the box starts: the retail toolbar's number when it is 2 or more and within <paramref name="max"/>, else 1.</summary>
public static int Prefill(int toolbarNumber, int max)
{
if (max < 1) return 1;
if (toolbarNumber >= 2) return Math.Min(toolbarNumber, max);
return 1;
}
/// <summary>A typed number kept between 1 and <paramref name="max"/> (1 when nothing can be bought).</summary>
public static int Clamp(int typed, int max) => max < 1 ? 1 : Math.Clamp(typed, 1, max);
/// <summary>Half of <paramref name="max"/>, at least 1.</summary>
public static int Half(int max) => Math.Max(1, max / 2);
}

View file

@ -1206,6 +1206,34 @@ internal static class VendorTrade
private static bool TradeAvailable(VendorSnapshot snap) =>
_resolved && _vtablesVerified && snap.LayoutVerified && snap.ProfileRead;
// ── The Inventory panel's "Buy how many?" box (2026-11-26) ─────────────────
/// <summary>The open vendor while buying from it is possible, else null (any thread).</summary>
public static VendorSnapshot? TradableSnapshot
{
get
{
VendorSnapshot? snap = _snapshot;
return snap != null && TradeAvailable(snap) ? snap : null;
}
}
/// <summary>Whether <paramref name="id"/> is on the open vendor's list (any thread; AC's drop detour asks).</summary>
public static bool IsVendorItem(uint id) => id != 0 && _snapshot?.Find(id) != null;
/// <summary>What the player pays this vendor with: pyreals, or the vendor's own currency; -1 unknown.</summary>
public static long MoneyFor(VendorSnapshot snap) => snap.AltCurrencyWcid != 0 ? _altHave : _playerCoins;
/// <summary>"pyreals", or the vendor's own currency's name.</summary>
public static string CurrencyName(VendorSnapshot snap) => Currency(snap);
/// <summary>The last request's state: 1 queued, 2 sent, 3 done (result 1 accepted, 2 refused in chat, 3 no answer), 4 refused.</summary>
public static (uint Seq, int State, int Result, string Message) LastStatus()
{
lock (_statusLock)
return (_stSeq, _stState, _stResult, _stMessage);
}
private static void SetStatus(Txn t, int state, int result, string message, long estimate = long.MinValue)
{
// Always the most recently UPDATED request; RequestId says which one. Plugins

View file

@ -297,7 +297,7 @@ internal static class ImGuiBar
ImGuiPopOuts.Open(PopOutTitle, (int)at.X, (int)at.Y, (int)(400 * s), (int)(28 * s), 0, 0, s,
draw: DrawPopped,
onMoved: static (x, y) => UiBackgroundWriter.Enqueue("persist bar", () => PanelStateStore.SetBarFloatingState(true, x, y)),
sizeToContent: true);
sizeToContent: true, fromSaved: saved.HasValue);
}
else if (!PoppedOut && have)
{

View file

@ -138,6 +138,12 @@ internal interface IImGuiPanel
/// </summary>
int PopOutIdleHz => 10;
/// <summary>
/// The face shows the chat line being typed (Win32Backend's chat capture, not an ImGui
/// text box): popped out, each chat key redraws it at once (ImGuiPopOuts.NoteChatKey).
/// </summary>
bool ShowsChatTyping => false;
/// <summary>
/// True while the face has nothing to show docked (the Dungeon Map outdoors): it
/// stays open and subscribed, but the host draws no window for it until this is
@ -456,6 +462,14 @@ internal static class ImGuiPanelHost
try { return Math.Clamp(entry?.Instance?.PopOutIdleHz ?? 10, 1, 30); } catch { return 10; }
}
/// <summary>IImGuiPanel.ShowsChatTyping for a face. AC thread.</summary>
public static bool ShowsChatTyping(string title)
{
Entry? entry;
lock (Sync) Entries.TryGetValue(title, out entry);
try { return entry?.Instance?.ShowsChatTyping ?? false; } catch { return false; }
}
/// <summary>For a face's own pop-out button: dock back (arrow in) while it is drawn in its own window, else pop out.</summary>
public static string PopOutGlyph => ImGuiPopOuts.InPopOutFrame ? PhosphorIcons.ArrowSquareIn : PhosphorIcons.ArrowSquareOut;
@ -608,6 +622,12 @@ internal static class ImGuiPanelHost
/// </summary>
public static bool UnderUiHovered { get; private set; }
/// <summary>
/// The last DrawAll: the title of the first panel found under the cursor (topmost not guaranteed
/// when panels overlap), or null. For logs only (ItemDragBridge). AC thread.
/// </summary>
public static string? HoveredTitle { get; private set; }
// ── Frame (AC thread) ──────────────────────────────────────────────
/// <summary>
@ -623,6 +643,7 @@ internal static class ImGuiPanelHost
_frameScale = uiScale;
WheelWanted = false;
UnderUiHovered = false;
HoveredTitle = null;
float placeScale = PlacementScale();
ApplyFaceChanges(placeScale); // plugin windows taking over (or giving back) engine panels
ApplyLayoutSwitch(placeScale); // another character's panel layout (UI/PanelLayout)
@ -959,16 +980,19 @@ internal static class ImGuiPanelHost
Vector2 size = entry.Size;
Vector2 origin = ImGuiPopOuts.ClientOriginOnScreen();
int left = (int)(origin.X + entry.Pos.X), top = (int)(origin.Y + entry.Pos.Y);
bool atSavedSpot = false;
if (PanelStateStore.TryGetPanel(entry.Title, out PanelStateStore.PanelEntry saved)
&& (saved.FloatingLeft != 0 || saved.FloatingTop != 0) && (fromSaved || saved.Floating))
{
left = (int)Math.Round(saved.FloatingLeft);
top = (int)Math.Round(saved.FloatingTop);
atSavedSpot = true; // follows the game window if it moved since (ImGuiPopOuts, UI/PopOutPlacement)
}
bool standard = entry.Spec.Chrome == PanelChrome.Standard;
int caption = standard ? (int)(RynthTheme.HeaderHeight * s) : 0;
int buttons = standard ? (int)HeaderButtonsWidth(entry, s, popped: true) : 0;
ImGuiPopOuts.Open(entry.Title, left, top, (int)size.X, (int)size.Y, caption, buttons, s, resizable: !entry.Spec.NoResize);
ImGuiPopOuts.Open(entry.Title, left, top, (int)size.X, (int)size.Y, caption, buttons, s, resizable: !entry.Spec.NoResize,
fromSaved: atSavedSpot);
entry.Popped = true;
PersistPopped(entry, open: true, left, top, (int)size.X, (int)size.Y, placeScale);
}
@ -1248,16 +1272,23 @@ internal static class ImGuiPanelHost
// Popped out, a panel is always interactive (like the Avalonia pop-out was).
if (!popped) try { clickThrough = entry.Instance?.ClickThrough ?? false; } catch { }
// Under AC's UI: where an AC window covers the cursor the click is AC's (unless a press that
// began on this panel is still held, so a drag over an AC window isn't dropped). In portal space
// AC's portal-space view covers the 3D view; AcMouseOver counts it as the world, not a window.
// began on this panel is still held, so a drag over an AC window isn't dropped). A press that
// began on the game (an item dragged in AC's inventory) stays AC's: the panel behind must not
// catch its drop (AcMouseOverRules.UnderUiPanelClickThrough). In portal space AC's
// portal-space view covers the 3D view; AcMouseOver counts it as the world, not a window.
bool underUi = spec.UnderUi && !popped;
if (underUi && !clickThrough && !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)
&& Compatibility.AcMouseOver.Current() == Compatibility.AcMouseTarget.AcWindow)
if (underUi && !clickThrough
&& Compatibility.AcMouseOverRules.UnderUiPanelClickThrough(Compatibility.AcMouseOver.Current(),
ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left), Win32Backend.HeldButtonsBelongToGame))
clickThrough = true;
if (clickThrough) flags |= ImGuiWindowFlags.NoInputs;
bool childOpen = false;
ImGuiNET.ImGui.Begin(entry.WindowId, flags);
// Which panel is under the cursor (ItemDragBridge names it when it keeps a drop from AC).
if (!clickThrough && HoveredTitle == null
&& ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem))
HoveredTitle = underUi ? entry.Title + " (under AC's UI)" : entry.Title;
if (underUi)
{
UnderUiLayer.AddWindowList(ImGuiNET.ImGui.GetWindowDrawList());

View file

@ -63,6 +63,9 @@ internal static unsafe class ImGuiPopOuts
[DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT p);
[DllImport("user32.dll")] private static extern IntPtr WindowFromPoint(POINT p);
[DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr hWnd, ref POINT p);
[StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; }
[DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr hWnd, out RECT r);
[DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")] private static extern short GetKeyState(int vk);
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
@ -88,6 +91,8 @@ internal static unsafe class ImGuiPopOuts
public Action<float, Vector2>? Draw;
public Action<int, int>? OnMoved;
public bool SizeToContent, ResizeGrip = true;
// Left/Top are the saved spot (not where a docked panel sat): it follows the game window (UI/PopOutPlacement).
public bool FromSaved;
public Vector2 ContentSize;
public int ShownWidth, ShownHeight; // the picture size last pushed
public long IdleInterval = Stopwatch.Frequency / 10;
@ -98,6 +103,11 @@ internal static unsafe class ImGuiPopOuts
public int MarginL, MarginT, MarginR, MarginB;
// Cost, for /rc imgui diag: frames built / pictures pushed, and the time spent.
public long Built, Pushed, BuildTicks, PushTicks;
// Typing: the first key not yet drawn (ticks), and key-to-screen times for the log.
public long PendingKeyAt;
public bool ShowsChatTyping; // the face's IImGuiPanel.ShowsChatTyping, refreshed each frame
public int Keys;
public long KeySumTicks, KeyMaxTicks, KeyLogAt;
}
private static readonly Dictionary<string, PopOut> Pops = new(StringComparer.OrdinalIgnoreCase);
@ -164,12 +174,30 @@ internal static unsafe class ImGuiPopOuts
return new Vector2(p.X, p.Y);
}
/// <summary>
/// The game window's client area on the screen; false while it is minimized or there is none
/// (a minimized window's client sits at -32000). Any thread.
/// </summary>
public static bool TryGetGameClientOnScreen(out ScreenRect client)
{
client = default;
IntPtr game = Win32Backend.GameHwnd;
if (game == IntPtr.Zero || IsIconic(game) || !GetClientRect(game, out RECT r)) return false;
var p = new POINT();
if (!ClientToScreen(game, ref p)) return false;
client = ScreenRect.FromSize(p.X, p.Y, r.Right - r.Left, r.Bottom - r.Top);
return !client.IsEmpty;
}
/// <summary>
/// Pops a panel out at the given screen geometry. Call with the main context
/// current (its font atlas is shared). AC thread.
/// current (its font atlas is shared). <paramref name="fromSaved"/>: the geometry is the
/// saved spot (panel_state.txt), which then follows the game window if it moved since
/// (UI/PopOutPlacement). AC thread.
/// </summary>
public static void Open(string title, int left, int top, int width, int height, int captionHeight, int captionRightInset, float uiScale,
Action<float, Vector2>? draw = null, Action<int, int>? onMoved = null, bool sizeToContent = false, bool resizable = true)
Action<float, Vector2>? draw = null, Action<int, int>? onMoved = null, bool sizeToContent = false, bool resizable = true,
bool fromSaved = false)
{
if (Pops.ContainsKey(title)) return;
IntPtr main = ImGuiNET.ImGui.GetCurrentContext();
@ -195,6 +223,7 @@ internal static unsafe class ImGuiPopOuts
Left = left, Top = top, Width = Math.Max(80, width), Height = Math.Max(40, height),
CaptionHeight = captionHeight, CaptionRightInset = captionRightInset,
Draw = draw, OnMoved = onMoved, SizeToContent = sizeToContent, ResizeGrip = resizable && !sizeToContent,
FromSaved = fromSaved,
};
Pops[title] = pop;
Order.Add(pop);
@ -208,6 +237,15 @@ internal static unsafe class ImGuiPopOuts
if (!Pops.TryGetValue(pop.Title, out PopOut? live) || live != pop || pop.Window != null) return;
try
{
int askedLeft = pop.Left, askedTop = pop.Top;
bool haveClient = TryGetGameClientOnScreen(out ScreenRect client);
// A saved spot over the game window stays on it when the game window opened somewhere else
// (the launcher, another client's layout, a window dragged since): 2026-11-24 report.
if (pop.FromSaved && haveClient
&& PanelStateStore.TryGetValue(PopOutPlacement.AnchorKey(pop.Title), out string anchorText)
&& PopOutPlacement.TryParseAnchor(anchorText, out ScreenRect savedClient)
&& PopOutPlacement.FollowGameWindow(ref pop.Left, ref pop.Top, pop.Width, pop.Height, savedClient, client))
RynthLog.UI($"ImGuiPopOuts: {pop.Title}: the game window moved from ({savedClient.Left},{savedClient.Top}) to ({client.Left},{client.Top}) since its spot was saved; moved with it to ({pop.Left},{pop.Top}).");
// A saved spot off the screen (a monitor since unplugged, a bad save) comes back on it.
if (LayeredWindow.ClampToWorkArea(ref pop.Left, ref pop.Top, pop.Width, pop.Height))
RynthLog.UI($"ImGuiPopOuts: {pop.Title}: saved spot was off the screen; moved to ({pop.Left},{pop.Top}).");
@ -220,11 +258,14 @@ internal static unsafe class ImGuiPopOuts
window.OnInput = (msg, wParam, lParam, _, _) => OnWindowInput(pop, msg, wParam, lParam);
window.OnResized = (_, _) => pop.HotFrames = Math.Max(pop.HotFrames, 2);
window.OnMoved = (x, y) => NotifyMoved(pop, window, x, y);
window.OnResizeEnd = (w, h) => ImGuiPanelHost.OnPopOutGeometry(pop.Title, window.ScreenLeft, window.ScreenTop, w, h);
window.OnResizeEnd = (w, h) => NotifyResized(pop, window, w, h);
LayeredWindow.ClaimTitle(pop.Title, window.Hwnd);
pop.Window = window;
pop.HotFrames = HotFramesAfterInput;
RynthLog.UI($"ImGuiPopOuts: {pop.Title} popped out at ({pop.Left},{pop.Top}) {pop.Width}x{pop.Height}.");
// The spot it opened at is the one saved, with the game window it goes with.
if (pop.Left != askedLeft || pop.Top != askedTop) NotifyMoved(pop, window, pop.Left, pop.Top);
else if (haveClient) SaveAnchor(pop.Title, client);
}
catch (Exception ex)
{
@ -237,6 +278,58 @@ internal static unsafe class ImGuiPopOuts
{
if (pop.OnMoved != null) pop.OnMoved(x, y);
else ImGuiPanelHost.OnPopOutGeometry(pop.Title, x, y, window.Width, window.Height);
if (TryGetGameClientOnScreen(out ScreenRect client)) SaveAnchor(pop.Title, client);
}
/// <summary>A pop-out's resize ended: its spot and size are saved (ImGuiPanelHost), with the game window. AC thread.</summary>
private static void NotifyResized(PopOut pop, LayeredWindow window, int width, int height)
{
ImGuiPanelHost.OnPopOutGeometry(pop.Title, window.ScreenLeft, window.ScreenTop, width, height);
if (TryGetGameClientOnScreen(out ScreenRect client)) SaveAnchor(pop.Title, client);
}
/// <summary>Saves the game window's client rectangle that a pop-out's saved spot goes with (UI/PopOutPlacement).</summary>
private static void SaveAnchor(string title, ScreenRect client)
{
string key = PopOutPlacement.AnchorKey(title), text = PopOutPlacement.FormatAnchor(client);
UiBackgroundWriter.Enqueue($"pop-out anchor {title}", () => PanelStateStore.SetValue(key, text));
}
/// <summary>
/// "Bring the windows back" (Settings > Interface, /rc layout here): every open pop-out (panels,
/// the popped-out bar) moves onto the game window, in a cascade from its top-left, and the spots
/// are saved. <paramref name="reply"/> gets the answer (text, ok). Any thread: the moves run on
/// the game thread.
/// </summary>
public static void RequestGather(Action<string, bool> reply)
{
if (!Win32Backend.PostToGameThread(() => Gather(reply)))
reply("No game window to bring the windows onto.", false);
}
private static void Gather(Action<string, bool> reply)
{
if (!TryGetGameClientOnScreen(out ScreenRect client))
{
reply("The game window is minimized: restore it, then bring the windows back.", false);
return;
}
int moved = 0, n = 0;
foreach (PopOut pop in Order.ToArray())
{
LayeredWindow? window = pop.Window;
if (window == null || window.Hwnd == IntPtr.Zero) continue;
var (x, y) = PopOutPlacement.GatherSpot(n++, window.Width, window.Height, client, EngineFrameController.FontScale);
LayeredWindow.ClampToWorkArea(ref x, ref y, window.Width, window.Height);
if (x != window.ScreenLeft || y != window.ScreenTop)
{
window.Move(x, y);
moved++;
}
NotifyMoved(pop, window, window.ScreenLeft, window.ScreenTop);
}
RynthLog.UI($"ImGuiPopOuts: brought {n} pop-out(s) onto the game window at ({client.Left},{client.Top}) {client.Width}x{client.Height}; {moved} moved.");
reply(PopOutPlacement.GatherReply(n, moved), true);
}
/// <summary>Closes a pop-out: its window, surfaces and context. AC thread.</summary>
@ -370,12 +463,30 @@ internal static unsafe class ImGuiPopOuts
if (sink == null || !sink.WantTextInput) return false;
sink.Input.Add(new InputMessage(msg, wParam, lParam));
sink.HotFrames = HotFramesAfterInput;
if (msg is WM_CHAR or WM_KEYDOWN && sink.PendingKeyAt == 0) sink.PendingKeyAt = Stopwatch.GetTimestamp();
return true;
}
}
return false;
}
/// <summary>
/// A key typed into the chat line (Win32Backend's chat capture: the keys never reach a
/// pop-out's own input). Every shown pop-out of a face that draws the line is redrawn on
/// the next frame, not at its idle 5 Hz (11-26: typing in a popped-out chat lagged). AC thread.
/// </summary>
public static void NoteChatKey()
{
if (Order.Count == 0) return;
long now = Stopwatch.GetTimestamp();
foreach (PopOut pop in Order)
{
if (!pop.Visible || !pop.ShowsChatTyping) continue;
pop.HotFrames = HotFramesAfterInput;
if (pop.PendingKeyAt == 0) pop.PendingKeyAt = now;
}
}
/// <param name="offsetX">Added to a message's client x to make it ImGui's (the window's origin in ImGui coordinates).</param>
private static void FeedInput(PopOut pop, ImGuiIOPtr io, int offsetX, int offsetY)
{
@ -466,6 +577,26 @@ internal static unsafe class ImGuiPopOuts
}
}
/// <summary>
/// Key-to-screen time for a pop-out's text box (the key reaching the game window to its
/// picture going to the layered window; the desktop's compositor adds up to a refresh
/// on top). Logged per 25 keys, or after 10 s of typing. AC thread.
/// </summary>
private static void NoteKeyShown(PopOut pop, long keyAt)
{
if (keyAt == 0) return;
long now = Stopwatch.GetTimestamp(), took = now - keyAt;
if (pop.Keys == 0) pop.KeyLogAt = now + 10 * Stopwatch.Frequency;
pop.Keys++;
pop.KeySumTicks += took;
if (took > pop.KeyMaxTicks) pop.KeyMaxTicks = took;
if (pop.Keys < 25 && now < pop.KeyLogAt) return;
double ms = 1000.0 / Stopwatch.Frequency;
RynthLog.Info($"ImGuiPopOuts: typing in {pop.Title}: {pop.Keys} key(s), key to screen avg {pop.KeySumTicks * ms / pop.Keys:0} ms, max {pop.KeyMaxTicks * ms:0} ms.");
pop.Keys = 0;
pop.KeySumTicks = pop.KeyMaxTicks = 0;
}
private static void RenderOne(IntPtr device, PopOut pop, float uiScale, long now)
{
LayeredWindow window = pop.Window!;
@ -547,14 +678,21 @@ internal static unsafe class ImGuiPopOuts
// Nothing changed since the last picture: skip the render, readback and
// window update (most panels are still most of the time).
ulong hash = HashDrawData(drawData, sw, sh) ^ Mix(sx, sy, w, h);
long keyAt = pop.PendingKeyAt;
if (hash == pop.LastHash && pop.Visible && pop.Surface.SnapshotPath == null)
{
// ImGui can take a key a frame later (its input queue trickles): keep the key's time
// for the picture it changes, unless nothing changed within a second (Shift alone).
if (keyAt != 0 && now - keyAt > Stopwatch.Frequency) pop.PendingKeyAt = 0;
pop.Surface.Flush(device, window);
}
else
{
pop.PendingKeyAt = 0;
pop.LastHash = hash;
if (pop.Surface.Render(device, drawData, sw, sh, new PopOutSurface.Placement(pop.MarginL, pop.MarginT, w, h), window))
// Typing (a text box had the keys last frame): this frame's own picture, not last frame's.
if (pop.Surface.Render(device, drawData, sw, sh, new PopOutSurface.Placement(pop.MarginL, pop.MarginT, w, h), window,
sameFrame: pop.WantTextInput || (pop.ShowsChatTyping && Win32Backend.ChatCaptureActive), keyAt: keyAt))
{
// Shown, or its picture changed size (the bar grows to its content):
// none of it may hang off the screen.
@ -571,12 +709,14 @@ internal static unsafe class ImGuiPopOuts
pop.Pushed++;
pop.PushTicks += Stopwatch.GetTimestamp() - built;
}
NoteKeyShown(pop, pop.Surface.TakePushedKeyAt());
// io.WantTextInput lags a frame behind the box (ImGui publishes it from the
// previous frame's widgets); a box that went active this frame counts too, so
// the keys typed right after the click already come here, not to AC.
pop.WantTextInput = ImGuiTextFocus.EndPopOutFrame(pop.Title, io.WantTextInput);
pop.IdleInterval = Stopwatch.Frequency / ImGuiPanelHost.PopOutIdleHz(pop.Title);
pop.ShowsChatTyping = pop.Draw == null && ImGuiPanelHost.ShowsChatTyping(pop.Title);
if (pop.WantTextInput) _keyboard = pop;
else if (_keyboard == pop) _keyboard = null;
if (pop.HotFrames > 0) pop.HotFrames--;

View file

@ -171,7 +171,7 @@ internal static unsafe class ItemDragBridge
{
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}).");
RynthLog.UI($"ItemDragBridge: native drag 0x{_nativeItem:X8} released over an ImGui window ({ImGuiPanelHost.HoveredTitle ?? "not a panel"}); AC gets the drop back at its start ({_pressX},{_pressY}).");
return true;
}

View file

@ -84,6 +84,7 @@ internal sealed class ChatFace : IImGuiPanel
/// <summary>New lines arrive a few times a second at most; popped out and idle, 5 Hz is plenty.</summary>
public int PopOutIdleHz => 5;
public bool ShowsChatTyping => true;
public void OnShown()
{
@ -312,7 +313,7 @@ internal sealed class ChatFace : IImGuiPanel
ImGuiNET.ImGui.SetCursorScreenPos(p);
if (ImGuiNET.ImGui.InvisibleButton("##chat_input", new Vector2(boxW, h)))
ChatModel.BeginTyping();
if (!typing && ChatHooks.RynthChatOwnsChat) ImGuiNET.ImGui.SetItemTooltip("Click or press Enter to chat (Ctrl+V pastes; /r replies, /rt retells)");
if (!typing && ChatHooks.RynthChatOwnsChat) ImGuiNET.ImGui.SetItemTooltip("Click or press Enter to chat (Ctrl+V pastes; /r replies, /rt retells;\n/me, /e, *wave* and /wave emote, @ and / commands work as in the game's chat)");
dl.AddRectFilled(p, p + new Vector2(boxW, h), InputBg, 3);
dl.AddRect(p, p + new Vector2(boxW, h), typing ? InputActive : InputBorder, 3);

View file

@ -16,12 +16,17 @@
// under itself. Lines keep the colour and highlights the rules gave them
// (ChatLine.Route, worked out on the pump - no regex runs here); a line with
// highlights is laid out by hand (LayoutSpans) so each run can take its own
// colour. Drag across lines to copy them (the keyboard stays with the game,
// so copy is mouse-driven). Right-click a line to copy it or to make a rule
// colour. Drag across text to select it, down to the character and across
// lines (2026-11-26; whole lines before): the mouse-up copies it, Ctrl+C
// copies it again (Win32Backend.OnChatSelectionCopy: the keyboard stays with
// the game, so the WndProc asks), and the line menu has Copy selection. Only
// the line under the mouse and the selection's two end lines are laid out by
// character (LineRows, cached), never the whole history. A RynthAi item info
// line offers "Copy item as one line". Right-click a line to copy it or to make a rule
// from it: move / copy lines like it to a tab, hide them, colour or highlight
// them (a "Highlight line" rule: a band behind the whole line). A line
// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go
// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them). The
// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to", "Route
// to" and "Go to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them). The
// coordinates are also drawn as underlined links: click points RynthNav's
// arrow there (its overlay opens), Ctrl+click walks there.
// Follows the newest line until you scroll up; the scroll for new lines is set
@ -119,12 +124,20 @@ internal sealed class ChatView
private const float ListScrollbarW = 10f;
private float _wrapFix;
// Selection: indices into _vis.
// Selection: lines as indices into _vis, and the character in each line's Text where it
// starts and ends (2026-11-26: it took whole lines only). Drag across text to select;
// the mouse-up copies it, Ctrl+C copies it again, and the right-click menu has Copy selection.
private int _selAnchor = -1, _selEnd = -1;
private int _selAnchorChar, _selEndChar;
private bool _selDragging, _selMoved;
private Vector2 _selDown;
private string? _flash;
private double _flashUntil;
// A copy made from Ctrl+C (the WndProc, outside any ImGui frame): flashed at the next draw.
private string? _pendingFlash;
/// <summary>The view whose selection Ctrl+C copies: the last one a selection was made in. AC thread.</summary>
private static ChatView? _selectionOwner;
// Unread lines per tab since it was last on screen (Id of the newest line seen there).
private readonly Dictionary<string, long> _seenId = new(StringComparer.OrdinalIgnoreCase);
@ -136,6 +149,9 @@ internal sealed class ChatView
private string? _ctxTab, _renameFrom;
private ChatLine? _ctxLine;
private string _ctxPattern = "";
// The right-clicked line's item (RynthAi's item info) as one line, or null: "Copy item as one line".
private string? _ctxItemOneLine;
private int _ctxItemLines;
// Map coordinates in the right-clicked line (ChatCoords, found when the menu opens):
// its menu offers "Arrow to" / "Go to" them, through RynthNav.
private List<ChatCoord> _ctxCoords = new();
@ -154,7 +170,11 @@ internal sealed class ChatView
_unreadLines = _unreadRoutes = -1; // a full recount
}
public void OnHidden() => OnScreen.Remove(_viewKey);
public void OnHidden()
{
OnScreen.Remove(_viewKey);
ClearSelection(); // Ctrl+C never copies from a closed window
}
/// <summary>Follow the newest line again (Auto-scroll turned on).</summary>
public void Restick() => _stick = true;
@ -561,7 +581,7 @@ internal sealed class ChatView
float viewH = ImGuiNET.ImGui.GetWindowHeight();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
int first = FirstAtOrBelow(scrollY, n);
int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd);
OrderedSelection(out int lo, out int loChar, out int hi, out int hiChar);
for (int i = first; i < n && _tops[i] < scrollY + viewH; i++)
{
Vector2 p = basePos + new Vector2(0, _tops[i]);
@ -574,7 +594,7 @@ internal sealed class ChatView
if (route.Mention)
dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), MentionBg);
if (lo >= 0 && i >= lo && i <= hi)
dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), SelBg);
DrawSelection(dl, font, i, p, tsW, textW, wrapW, i == lo ? loChar : 0, i == hi ? hiChar : line.Text.Length);
uint col = RynthTheme.Argb(ChatModel.LineArgb(line));
if (showTs) dl.AddText(font, font.FontSize, p + new Vector2(3, 0), TsColor, line.Timestamp);
Vector2 tp = p + new Vector2(3 + tsW, 0);
@ -594,11 +614,13 @@ internal sealed class ChatView
}
ImGuiNET.ImGui.Dummy(new Vector2(wrapW, Math.Max(1, total)));
HoverLink(basePos, tsW, n, out ChatCoord? hoveredLink);
HandleSelection(basePos, wrapW, scrollY, viewH, n, hoveredLink);
HandleSelection(font, basePos, tsW, textW, wrapW, scrollY, viewH, n, hoveredLink);
HandleLineMenu(basePos, wrapW, n);
_lastScrollY = scrollY;
if (_pendingFlash != null) { Flash(_pendingFlash, 1.5); _pendingFlash = null; }
// "Copied N lines" / "Rule added", top-right, for a moment.
if (_flash != null)
{
@ -733,6 +755,8 @@ internal sealed class ChatView
public required Seg[] Segs;
/// <summary>The line's map coordinates (ChatCoords), when any are drawn as links.</summary>
public ChatCoord[]? Links;
/// <summary>Each drawn row as [RowStarts[r], RowEnds[r]) of the line's Text (text selection).</summary>
public required int[] RowStarts, RowEnds;
}
/// <summary>Coordinate links in chat lines: soft teal, underlined (0xAARRGGBB, like ChatSpan.Argb).</summary>
@ -820,7 +844,14 @@ internal sealed class ChatView
}
if (c < b) segs.Add(new Seg(text[c..b], new Vector2(sx, y), 0));
}
return new SpanLayout { Height = Math.Max(1, rows.Count) * size, Segs = segs.ToArray(), Links = links?.ToArray() };
var rowStarts = new int[rows.Count];
var rowEnds = new int[rows.Count];
for (int r = 0; r < rows.Count; r++) { rowStarts[r] = rows[r].Start; rowEnds[r] = rows[r].End; }
return new SpanLayout
{
Height = Math.Max(1, rows.Count) * size, Segs = segs.ToArray(), Links = links?.ToArray(),
RowStarts = rowStarts, RowEnds = rowEnds,
};
}
/// <summary>Index of the line containing content y (clamped to the list).</summary>
@ -876,12 +907,14 @@ internal sealed class ChatView
}
else
{
ArrowTarget.NoteChat(c.Ns, c.Ew); // the arrow window says "Chat coords"
RynthNavCommands.Arrow(c.Text, c.Ns, c.Ew);
Flash("Arrow: " + c.Text, 1.5);
}
}
private void HandleSelection(Vector2 basePos, float wrapW, float scrollY, float viewH, int n, ChatCoord? hoveredLink = null)
private void HandleSelection(ImFontPtr font, Vector2 basePos, float tsW, float textW, float wrapW, float scrollY, float viewH, int n,
ChatCoord? hoveredLink = null)
{
if (n == 0) { ClearSelection(); return; }
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
@ -894,7 +927,8 @@ internal sealed class ChatView
return;
ClearSelection();
if (contentY < 0 || contentY >= _tops[n]) return;
_selAnchor = _selEnd = FirstAtOrBelow(contentY, n);
(_selAnchor, _selAnchorChar) = HitTest(font, mouse, basePos, tsW, textW, n);
(_selEnd, _selEndChar) = (_selAnchor, _selAnchorChar);
_selDragging = true;
_selMoved = false;
_selDown = mouse;
@ -903,7 +937,8 @@ internal sealed class ChatView
}
if (Math.Abs(mouse.X - _selDown.X) > 3 || Math.Abs(mouse.Y - _selDown.Y) > 3) _selMoved = true;
_selEnd = FirstAtOrBelow(Math.Clamp(contentY, 0, _tops[n] - 1), n);
// Only the line under the mouse is hit-tested (its rows are cached): nothing walks the history.
(_selEnd, _selEndChar) = HitTest(font, mouse, basePos, tsW, textW, n);
// Dragging past the edges scrolls.
Vector2 wp = ImGuiNET.ImGui.GetWindowPos();
@ -912,23 +947,237 @@ internal sealed class ChatView
if (ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) return;
_selDragging = false;
// A drag (even within one line) copies; a plain click just clears, or follows a
// A drag copies what it went across; a plain click just clears, or follows a
// coordinate link it was pressed on.
if (!_selMoved && _selEnd == _selAnchor)
if (!_selMoved || !HasSelection)
{
ChatCoord? link = _downLink;
ChatCoord? link = _selMoved ? null : _downLink;
ClearSelection();
if (link is { } c) ClickLink(c);
return;
}
int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd);
var parts = new List<string>(hi - lo + 1);
for (int i = lo; i <= hi && i < _vis.Count; i++) parts.Add(CopyText(_vis[i]));
Flash(ChatModel.CopyLines(parts), 1.5);
_selectionOwner = this;
Flash(CopySelectionText() ?? "Nothing selected", 1.5);
}
private static string CopyText(ChatLine line) => ChatModel.ShowTimestamps ? line.FormattedText : line.Text;
/// <summary>A selection that isn't empty and isn't being dragged.</summary>
private bool HasSelection =>
_selAnchor >= 0 && _selEnd >= 0 && _selAnchor < _vis.Count && _selEnd < _vis.Count
&& (_selAnchor != _selEnd || _selAnchorChar != _selEndChar);
/// <summary>The selection's ends in reading order; lo = -1 when there is none.</summary>
private void OrderedSelection(out int lo, out int loChar, out int hi, out int hiChar)
{
lo = _selAnchor; loChar = _selAnchorChar; hi = _selEnd; hiChar = _selEndChar;
if (lo < 0 || hi < 0) { lo = hi = -1; loChar = hiChar = 0; return; }
ChatTextSelection.Order(ref lo, ref loChar, ref hi, ref hiChar);
}
/// <summary>The selected text, one line per chat line (a line copied from its start keeps its timestamp).</summary>
private string? SelectedText(out int lines)
{
lines = 0;
if (!HasSelection) return null;
OrderedSelection(out int lo, out int loChar, out int hi, out int hiChar);
var sb = new System.Text.StringBuilder();
bool ts = ChatModel.ShowTimestamps;
for (int i = lo; i <= hi && i < _vis.Count; i++)
{
ChatLine line = _vis[i];
if (i > lo) sb.Append("\r\n");
sb.Append(ChatTextSelection.Part(line.Text, ts ? line.Timestamp : null, i == lo ? loChar : 0, i == hi ? hiChar : line.Text.Length));
lines++;
}
return sb.ToString();
}
/// <summary>Copies the selection; returns the message to show, or null when nothing is selected.</summary>
private string? CopySelectionText()
{
string? text = SelectedText(out int lines);
if (text == null) return null;
if (!ChatModel.SetClipboardText(text)) return "Clipboard busy — try again";
return lines > 1 ? $"Copied {lines} lines" : "Copied";
}
/// <summary>
/// Ctrl+C (Win32Backend.OnChatSelectionCopy, AC's thread, in the WndProc): copies the text
/// selected in the chat, if any. False when nothing is selected (the key goes on as before).
/// </summary>
internal static bool CopyActiveSelection()
{
ChatView? view = _selectionOwner;
if (view == null || view._selDragging || !view.HasSelection) return false;
view._pendingFlash = view.CopySelectionText(); // shown at its next draw, in its own ImGui context
return view._pendingFlash != null;
}
// ── Where the characters are (text selection) ───────────────────────
// The rows of a few lines, as ImGui wraps them: the lines a selection starts and ends on and
// the one under the mouse. Worked out once per line, width and font, never for the whole history.
private sealed class LineRows
{
public ChatLine? Line;
public float TextW, Font;
public SpanLayout? Lay;
public readonly List<int> Starts = new(4), Ends = new(4);
public long Used;
}
private readonly LineRows[] _rowCache = { new(), new(), new() };
private long _rowUse;
private byte[] _utf8 = new byte[256];
private int[] _byteOfChar = new int[257];
private ImFontPtr _advFont;
private string _advText = "";
private Func<int, float>? _advance;
/// <summary>The rows line <paramref name="i"/> is drawn in (chat font pushed).</summary>
private LineRows RowsOf(ImFontPtr font, int i, float textW)
{
ChatLine line = _vis[i];
SpanLayout? lay = _lay[i];
float size = font.FontSize;
LineRows? slot = null;
foreach (LineRows c in _rowCache)
if (ReferenceEquals(c.Line, line) && c.TextW == textW && c.Font == size && ReferenceEquals(c.Lay, lay)) { slot = c; break; }
if (slot == null)
{
slot = _rowCache[0];
foreach (LineRows c in _rowCache) if (c.Used < slot.Used) slot = c;
slot.Line = line; slot.TextW = textW; slot.Font = size; slot.Lay = lay;
slot.Starts.Clear(); slot.Ends.Clear();
if (lay != null)
for (int r = 0; r < lay.RowStarts.Length; r++) { slot.Starts.Add(lay.RowStarts[r]); slot.Ends.Add(lay.RowEnds[r]); }
else
WrapRows(font, line.Text, textW, slot.Starts, slot.Ends);
if (slot.Starts.Count == 0) { slot.Starts.Add(0); slot.Ends.Add(line.Text.Length); }
}
slot.Used = ++_rowUse;
return slot;
}
/// <summary>
/// The rows ImDrawList.AddText draws <paramref name="text"/> in, wrapped to <paramref name="wrapW"/>:
/// the same steps as ImFont::RenderText (ImGui 1.91), with its own word-wrap function, on the
/// same UTF-8 bytes; the rows go out as character ranges of the string.
/// </summary>
private unsafe void WrapRows(ImFontPtr font, string text, float wrapW, List<int> starts, List<int> ends)
{
int max = System.Text.Encoding.UTF8.GetMaxByteCount(text.Length);
if (_utf8.Length < max + 1) _utf8 = new byte[Math.Max(max + 1, _utf8.Length * 2)];
if (_byteOfChar.Length < text.Length + 1) _byteOfChar = new int[Math.Max(text.Length + 1, _byteOfChar.Length * 2)];
int nBytes = System.Text.Encoding.UTF8.GetBytes(text, _utf8);
// Where each character starts in the bytes (a surrogate pair is one 4-byte character).
for (int k = 0, b = 0; k <= text.Length; k++)
{
_byteOfChar[k] = b;
if (k == text.Length) break;
char c = text[k];
if (char.IsHighSurrogate(c) && k + 1 < text.Length && char.IsLowSurrogate(text[k + 1])) { _byteOfChar[++k] = b; b += 4; }
else b += c < 0x80 ? 1 : c < 0x800 ? 2 : 3;
}
fixed (byte* p = _utf8)
{
int s = 0, eol = -1, rowStart = 0;
while (s < nBytes)
{
if (eol < 0) eol = (int)(ImGuiNative.ImFont_CalcWordWrapPositionA(font.NativePtr, 1f, p + s, p + nBytes, wrapW) - p);
if (s >= eol)
{
AddRow(rowStart, s);
eol = -1;
// ImGui skips the blanks after a wrap, and one line break.
while (s < nBytes && (p[s] == ' ' || p[s] == '\t')) s++;
if (s < nBytes && p[s] == '\n') s++;
rowStart = s;
continue;
}
byte c = p[s];
if (c == '\n') { AddRow(rowStart, s); s++; rowStart = s; continue; }
s += c < 0x80 ? 1 : c < 0xE0 ? 2 : c < 0xF0 ? 3 : 4;
}
AddRow(rowStart, nBytes);
}
void AddRow(int b0, int b1) { starts.Add(CharAt(b0, text.Length)); ends.Add(CharAt(b1, text.Length)); }
}
/// <summary>The character starting at byte <paramref name="b"/> (WrapRows' table).</summary>
private int CharAt(int b, int length)
{
int lo = 0, hi = length; // first k with _byteOfChar[k] >= b
while (lo < hi)
{
int mid = (lo + hi) >> 1;
if (_byteOfChar[mid] < b) lo = mid + 1; else hi = mid;
}
return lo;
}
/// <summary>The drawn width of the character at an index of _advText (ImGui's advance, no kerning in 1.91).</summary>
private float AdvanceAt(int k)
{
char c = _advText[k];
if (char.IsHighSurrogate(c)) return _advFont.GetCharAdvance(0xFFFD); // beyond ImWchar16: drawn as the replacement glyph
if (c == '\r') return 0f;
return _advFont.GetCharAdvance(c);
}
/// <summary>The x of character <paramref name="k"/> in a row starting at <paramref name="start"/>.</summary>
private float XOf(ImFontPtr font, string text, int start, int k)
{
_advFont = font;
_advText = text;
float x = 0f;
for (int j = start; j < k && j < text.Length; j++) x += AdvanceAt(j);
return x;
}
/// <summary>The line and character under the mouse: above the lines the first one's start, below them the last one's end.</summary>
private (int Line, int Char) HitTest(ImFontPtr font, Vector2 mouse, Vector2 basePos, float tsW, float textW, int n)
{
float contentY = mouse.Y - basePos.Y;
if (contentY < 0) return (0, 0);
if (contentY >= _tops[n]) return (n - 1, _vis[n - 1].Text.Length);
int i = FirstAtOrBelow(contentY, n);
LineRows rows = RowsOf(font, i, textW);
int r = Math.Clamp((int)((contentY - _tops[i]) / font.FontSize), 0, rows.Starts.Count - 1);
string text = _vis[i].Text;
_advFont = font;
_advText = text;
_advance ??= AdvanceAt;
return (i, ChatTextSelection.CharAtX(text, rows.Starts[r], rows.Ends[r], mouse.X - (basePos.X + 3 + tsW), _advance));
}
/// <summary>The selection band behind line <paramref name="i"/>: all of it, or the characters [from, to) row by row.</summary>
private void DrawSelection(ImDrawListPtr dl, ImFontPtr font, int i, Vector2 p, float tsW, float textW, float wrapW, int from, int to)
{
ChatLine line = _vis[i];
if (from <= 0 && to >= line.Text.Length)
{
dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), SelBg);
return;
}
if (to <= from) return;
LineRows rows = RowsOf(font, i, textW);
float rowH = font.FontSize;
Vector2 tp = p + new Vector2(3 + tsW, 0);
for (int r = 0; r < rows.Starts.Count; r++)
{
int rs = rows.Starts[r], re = rows.Ends[r];
int a = Math.Max(from, rs), b = Math.Min(to, re);
if (b <= a) continue;
// From the line's start, the timestamp is copied too: the band covers it.
float x0 = a == 0 ? p.X - tp.X : XOf(font, line.Text, rs, a);
float x1 = XOf(font, line.Text, rs, b);
dl.AddRectFilled(tp + new Vector2(x0, r * rowH), tp + new Vector2(x1, (r + 1) * rowH), SelBg);
}
}
/// <summary>Right-click on a line: its menu (drawn in DrawPopups).</summary>
private void HandleLineMenu(Vector2 basePos, float wrapW, int n)
{
@ -937,17 +1186,39 @@ internal sealed class ChatView
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
float contentY = mouse.Y - basePos.Y;
if (mouse.X > basePos.X + wrapW + 6 || contentY < 0 || contentY >= _tops[n]) return;
_ctxLine = _vis[FirstAtOrBelow(contentY, n)];
int index = FirstAtOrBelow(contentY, n);
_ctxLine = _vis[index];
_ctxPattern = ChatModel.PatternFor(_ctxLine);
_ctxCoords = ImGuiPanelHost.HasFace(RynthNavFace.Title) ? ChatCoords.Find(_ctxLine.Text) : new List<ChatCoord>();
FindItemAround(index);
_openLineMenu = true;
}
/// <summary>
/// The right-clicked line is RynthAi item info: the item's lines (its name line and the ones
/// indented under it) as one line, for "Copy item as one line". On the right-click, never per frame.
/// </summary>
private void FindItemAround(int index)
{
_ctxItemOneLine = null;
_ctxItemLines = 0;
if (!ChatTextSelection.IsItemLine(_vis[index].Text)) return;
const int Reach = 12;
int from = Math.Max(0, index - Reach), to = Math.Min(_vis.Count - 1, index + Reach);
var texts = new List<string>(to - from + 1);
for (int k = from; k <= to; k++) texts.Add(_vis[k].Text);
if (!ChatTextSelection.ItemRun(texts, index - from, out int first, out int last)) return;
_ctxItemOneLine = ChatTextSelection.ItemOneLine(texts, first, last);
_ctxItemLines = last - first + 1;
}
private void ClearSelection()
{
_selAnchor = _selEnd = -1;
_selAnchorChar = _selEndChar = 0;
_selDragging = _selMoved = false;
_downLink = null;
if (_selectionOwner == this) _selectionOwner = null;
}
/// <summary>The coordinate link the left button went down on (acted on if it comes up without a drag).</summary>
@ -1145,13 +1416,35 @@ internal sealed class ChatView
ChatCoord c = _ctxCoords[i];
ImGuiNET.ImGui.PushID(i);
if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.NavigationArrow + " Arrow to " + c.Text))
{
ArrowTarget.NoteChat(c.Ns, c.Ew);
RynthNavCommands.Arrow(c.Text, c.Ns, c.Ew);
}
// Route here: RynthNav plans the trip (portals, recalls) and the arrow follows it.
if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Path + " Route to " + c.Text))
{
RynthNavCommands.Route(c.Text, c.Ns, c.Ew);
RynthNavArrowFace.Show();
}
if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Play + " Go to " + c.Text))
RynthNavCommands.Go(c.Text, c.Ns, c.Ew);
ImGuiNET.ImGui.PopID();
}
if (_ctxCoords.Count > 0) ImGuiNET.ImGui.Separator();
if (HasSelection)
{
if (ImGuiNET.ImGui.MenuItem("Copy selection", "Ctrl+C")) Flash(CopySelectionText() ?? "Nothing selected", 1.5);
ImGuiNET.ImGui.SetItemTooltip("Copy the text you dragged across (Ctrl+C does it too)");
}
if (ImGuiNET.ImGui.MenuItem("Copy line")) Flash(ChatModel.CopyLines(new[] { CopyText(line) }), 1.5);
if (_ctxItemOneLine != null)
{
if (ImGuiNET.ImGui.MenuItem("Copy item as one line"))
Flash(ChatModel.SetClipboardText(_ctxItemOneLine) ? "Copied the item" : "Clipboard busy — try again", 1.5);
ImGuiNET.ImGui.SetItemTooltip(_ctxItemLines > 1
? $"This item's {_ctxItemLines} info lines, joined into one line"
: "This item's info line, without the [RynthAi Item] tag\n(Item Info's one-line layout prints every item on one line)");
}
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 400);

View file

@ -77,6 +77,7 @@ internal sealed class ChatWindowFace : IImGuiPanel
public bool ClickThrough => ChatModel.CtrlGatedClickThrough && !ImGuiNET.ImGui.GetIO().KeyCtrl;
public int PopOutIdleHz => 5;
public bool ShowsChatTyping => true;
public void OnShown()
{

View file

@ -324,7 +324,7 @@ internal sealed partial class InventoryFace
if (TitleToggle("##inv_more", PhosphorIcons.DotsThree, At(lay.More), btn,
MiniRemoteOpen || RynthSortOpen || ItemCountOpen || GlobalInventoryOpen))
_openMore = true;
ImGuiNET.ImGui.SetItemTooltip("Mini Remote, RynthSort, Item Count, Global Inventory");
ImGuiNET.ImGui.SetItemTooltip("Use AC's own bags; Mini Remote, RynthSort, Item Count, Global Inventory");
break;
}
RelatedMenu();
@ -334,6 +334,8 @@ internal sealed partial class InventoryFace
ImGuiNET.ImGui.SetCursorScreenPos(o);
ImGuiNET.ImGui.InvisibleButton("##inv_titledrag", new Vector2(dragW, h));
ImGuiPanelHost.DragWindowWithLastItem();
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _openMore = true; // the menu, with Use AC's own bags
SafeImGui.SetItemTooltip(TitleMenuTip);
// The title: centred on the bar when it fits, else against the left edge and cut with "...".
float room = lay.TitleWidth - 4 * s;

View file

@ -0,0 +1,209 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/InventoryFace.VendorBuy.cs
// Buying from a vendor with the Inventory panel showing (2026-11-26: a player
// couldn't buy in bulk once RynthCore's windows were up).
//
// In AC's own windows an item dragged out of the vendor's list onto the pack
// takes the retail toolbar's number with it. Let go over this panel instead and
// AC used to drop it nowhere. Now the panel takes it (ImGui/UiDropTargets, only
// items on the open vendor's list; AC keeps the item where it was) and asks how
// many: a number box that starts at the toolbar's number (VendorBuyMath.Prefill),
// 1 / 10 / 100 / half / max, the cost and what you have, and Buy N, which goes
// through VendorTrade (the same checks as /rc vendor buy: money, pack room and
// burden before it sends). The box stays open with the answer, for the next buy.
//
// AC's main thread (the face draws in EndScene); VendorTrade's queue sends.
// ============================================================================
using System;
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 string VendorDropKey = "Inventory.VendorBuy";
private const string BuyPopupId = "##inv_vendorbuy";
private static readonly Predicate<uint> IsVendorItem = VendorTrade.IsVendorItem;
private uint _buyItem, _buyVendor, _buySeq;
private int _buyAmount = 1;
private bool _openBuy;
private string _buyAnswer = string.Empty;
private bool _buyAnswerOk;
/// <summary>
/// Every frame after the body: the panel takes items dragged out of an open vendor's list
/// (and shows that it does while one is dragged).
/// </summary>
private void AcceptVendorDrops(Vector2 origin, Vector2 size)
{
VendorSnapshot? snap = VendorTrade.TradableSnapshot;
UiDropTargets.Publish(VendorDropKey, Title, origin, origin + size, snap != null, IsVendorItem);
if (UiDropTargets.TryTake(VendorDropKey, out uint id) && snap?.Find(id) is { } dropped)
OpenBuy(snap, dropped);
if (snap == null) return;
uint dragging = UiElementHooks.CurrentDragObject;
if (dragging == 0 || snap.Find(dragging) == null) return;
bool over = UiDropTargets.IsCursorOver(VendorDropKey);
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRect(origin + new Vector2(1, 1), origin + size - new Vector2(1, 1), over ? Green : Teal, 4, ImDrawFlags.None, over ? 3f : 1.5f);
string hint = over ? "Let go: buy it (you pick how many)" : "Drop it here to buy (you pick how many)";
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(hint);
Vector2 at = new(origin.X + Math.Max(4, (size.X - ts.X) * 0.5f), origin.Y + size.Y * 0.5f - ts.Y * 0.5f);
dl.AddRectFilled(at - new Vector2(6, 3), at + ts + new Vector2(6, 3), ShellBg, 4);
dl.AddText(at, over ? Green : Teal, hint);
}
private void OpenBuy(VendorSnapshot snap, VendorItemInfo item)
{
_buyItem = item.ObjectId;
_buyVendor = snap.VendorId;
_buySeq = 0;
_buyAnswer = string.Empty;
int toolbar = ClientHelperHooks.TryReadSplitAmount(out int n) ? n : 0;
_buyAmount = VendorBuyMath.Prefill(toolbar, MaxBuy(snap, item));
_openBuy = true;
}
private static int MaxBuy(VendorSnapshot snap, VendorItemInfo item) =>
VendorBuyMath.MaxBuy(item.Unlimited ? -1 : item.Amount, VendorTrade.MoneyFor(snap), n => CostOf(snap, item, n));
private static long CostOf(VendorSnapshot snap, VendorItemInfo item, int n)
{
VendorTrade.EstimateBuy(item, n, snap.SellRate, out long cost, out _, out _, out _);
return cost;
}
private static string N(long v) => v.ToString("N0", CultureInfo.InvariantCulture);
/// <summary>The "Buy how many?" box. Draw with the other dialogs.</summary>
private void BuyDialog()
{
if (_openBuy)
{
_openBuy = false;
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos(), ImGuiCond.Always);
ImGuiNET.ImGui.OpenPopup(BuyPopupId);
}
PushMenuStyle();
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
bool open = ImGuiNET.ImGui.BeginPopup(BuyPopupId);
ImGuiNET.ImGui.PopStyleVar();
if (!open) { PopMenuStyle(); return; }
try
{
VendorSnapshot? snap = VendorTrade.TradableSnapshot;
VendorItemInfo? item = snap != null && snap.VendorId == _buyVendor ? snap.Find(_buyItem) : null;
if (snap == null || item == null)
{
ImGuiNET.ImGui.TextUnformatted(snap == null ? "The vendor closed." : "That item is no longer on the vendor's list.");
if (Button("##vb_close", "Close", ImGuiNET.ImGui.GetCursorScreenPos(), new Vector2(80, 22), Text, BtnFill))
ImGuiNET.ImGui.CloseCurrentPopup();
ImGuiNET.ImGui.Dummy(new Vector2(80, 24));
return;
}
string currency = VendorTrade.CurrencyName(snap);
long money = VendorTrade.MoneyFor(snap);
int max = MaxBuy(snap, item);
int unit = VendorTrade.UnitPrice(item, snap.SellRate);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.TextUnformatted(PhosphorIcons.Storefront + " " + item.Name);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.TextUnformatted($"{N(unit)} {currency} each" + (item.Unlimited ? "" : $", the vendor has {N(item.Amount)}"));
ImGuiNET.ImGui.TextUnformatted("How many?");
ImGuiNET.ImGui.SetNextItemWidth(200);
ImGuiNET.ImGui.InputInt("##vb_n", ref _buyAmount, 1, 10);
_buyAmount = VendorBuyMath.Clamp(_buyAmount, max);
SafeImGui.SetItemTooltip("Type how many to buy. It started at the game toolbar's number when that was set.");
// Quick numbers.
Vector2 cp = ImGuiNET.ImGui.GetCursorScreenPos();
float x = cp.X;
void Quick(string id, string label, int value, string tip)
{
float bw = ButtonWidth(label);
if (Button(id, label, new Vector2(x, cp.Y), new Vector2(bw, 20), Text, BtnFill, enabled: max >= 1))
_buyAmount = VendorBuyMath.Clamp(value, max);
SafeImGui.SetItemTooltip(tip);
x += bw + 3;
}
Quick("##vb_1", "1", 1, "One.");
Quick("##vb_10", "10", 10, "Ten.");
Quick("##vb_100", "100", 100, "A hundred.");
Quick("##vb_half", "half", VendorBuyMath.Half(max), $"Half of the most you can buy now ({N(VendorBuyMath.Half(max))}).");
Quick("##vb_max", "max", max, money >= 0
? $"The most you can buy now ({N(max)}): what the vendor has and what you can pay for. Pack room and burden are checked when you buy."
: $"What the vendor has ({N(max)}). Your {currency} couldn't be read; the buy checks them.");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(cp.X, cp.Y + 24));
long cost = CostOf(snap, item, _buyAmount);
bool cantPay = money >= 0 && cost > money;
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, cantPay ? Red : Text);
ImGuiNET.ImGui.TextUnformatted($"Cost {N(cost)} {currency}" + (money >= 0 ? $" (you have {N(money)})" : ""));
ImGuiNET.ImGui.PopStyleColor();
// The answer to the last Buy.
var (seq, state, result, message) = VendorTrade.LastStatus();
bool waiting = _buySeq != 0 && seq == _buySeq && state is 1 or 2;
if (_buySeq != 0 && seq == _buySeq && state is 3 or 4)
{
_buyAnswerOk = state == 3 && result == 1;
_buyAnswer = state == 4 ? "Not bought: " + message + "."
: result == 1 ? "Bought." : result == 2 ? "The vendor refused (see chat)." : "No answer from the vendor.";
_buySeq = 0;
}
bool can = max >= 1 && !waiting && !cantPay;
Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4);
string buyLabel = PhosphorIcons.Coins + " Buy " + N(_buyAmount);
float buyW = Math.Max(96, ButtonWidth(buyLabel));
if (Button("##vb_buy", buyLabel, bp, new Vector2(buyW, 24), Teal, BtnFill, enabled: can))
{
uint s = VendorTrade.RequestBuy(_buyVendor, [_buyItem], [_buyAmount]);
if (s != 0)
{
_buySeq = s;
_buyAnswer = string.Empty;
}
else
{
_buyAnswerOk = false;
_buyAnswer = "Not bought: " + VendorTrade.LastStatus().Message + ".";
}
}
SafeImGui.SetItemTooltip(max < 1 ? (money >= 0 ? $"You can't pay for one ({N(unit)} {currency})." : "The vendor has none left.")
: cantPay ? $"Costs {N(cost)} {currency}; you have {N(money)}."
: waiting ? "Waiting for the vendor."
: $"Buy {N(_buyAmount)} {item.Name} for {N(cost)} {currency}. The game checks your money, pack room and burden before it sends.");
if (Button("##vb_cancel", "Close", bp + new Vector2(buyW + 6, 0), new Vector2(80, 24), Text, BtnFill))
ImGuiNET.ImGui.CloseCurrentPopup();
ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28));
string line = waiting ? "Waiting for the vendor..." : _buyAnswer;
if (line.Length > 0)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, waiting ? Mute : _buyAnswerOk ? Green : Red);
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 260);
ImGuiNET.ImGui.TextUnformatted(line);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopStyleColor();
}
ImGuiNET.ImGui.Dummy(new Vector2(260, 0));
}
finally
{
ImGuiNET.ImGui.EndPopup();
PopMenuStyle();
}
}
}

View file

@ -177,12 +177,14 @@ internal sealed partial class InventoryFace : IImGuiPanel
InventoryModel.Hover(_dragItem == null ? _hover?.Id ?? 0 : 0);
FinishDrag();
UiDropTargets.EngineDragObject = _dragItem?.Id ?? 0;
AcceptVendorDrops(origin, size);
End(origin, size);
Tooltip();
DrawDragGhost();
ContextMenu(view);
SplitDialog(view);
BuyDialog();
ConfirmDialog();
AttrFilterDialog();
_lootAdd.Draw();
@ -269,6 +271,41 @@ internal sealed partial class InventoryFace : IImGuiPanel
/// <summary>Opens or closes RynthSort (same as /rsort).</summary>
private static void ToggleRynthSort() => ToggleScriptWindow(RynthSortKey, "/rsort");
// ── AC's own bags (2026-11-26) ──────────────────────────────────────
// This window never hides AC's inventory; it only looks like it in the Classic look. The way back
// to AC's: this menu (the ⋯ button, or right-click the title bar), /rc inv ac, or Settings >
// Inventory > AC's Own Bags. With "Hide retail toolbar" on, AC's backpack button and the number
// box for buying or splitting several are hidden too: the menu then offers to show the toolbar.
internal const string UseAcBagsTip =
"Close this window and open the game's own inventory (its backpack, as AC's backpack button or key does).\n" +
"RynthCore never hides AC's bags: this window is an extra one. Open it again from the RynthCore bar or /rc inv.";
private const string TitleMenuTip = "Drag to move. Right-click: Use AC's own bags, and the related windows.";
private const string ShowToolbarTip =
"Hide retail toolbar is on: the game's toolbar is hidden, with its backpack button and the number box\n" +
"where you type how many to buy or split. This shows it again (Settings > Interface > Hide The Game's Own).";
/// <summary>
/// Closes the Inventory panel and opens AC's own pack (queued for AC's game tick). Returns what was
/// done, or why not. Main thread (the panel's menu, the Settings button, /rc inv ac).
/// </summary>
internal static (bool Ok, string Message) UseAcBags()
{
bool wasOpen = ImGuiPanelHost.IsOpen(Title);
if (wasOpen) ImGuiPanelHost.Close(Title);
bool queued = AcPanels.Enqueue(7 /* RynthAcPanel.Inventory */, AcPanels.Op.Open);
string toolbar = RetailToolbarHooks.HideRetailToolbar
? " The game's toolbar (its backpack button and the buy/split number box) is hidden: /rc ui retailtoolbar off, or Settings > Interface > Hide retail toolbar, shows it."
: string.Empty;
if (!queued)
return (false, (wasOpen ? "Closed RynthCore's Inventory window, but c" : "C") +
"an't open AC's own inventory from here (" + AcPanels.Status + "): use the game's backpack button or key." + toolbar);
return (true, (wasOpen ? "Closed RynthCore's Inventory window and opened" : "Opened") +
" AC's own inventory. RynthCore's is on its bar button or /rc inv." + toolbar);
}
// The "more" menu both looks use when their bar is too short for the four buttons.
private bool _openMore;
@ -283,6 +320,18 @@ internal sealed partial class InventoryFace : IImGuiPanel
PushMenuStyle();
if (ImGuiNET.ImGui.BeginPopup("##inv_more_menu"))
{
// AC's own bags (2026-11-26: a player took this window for a replacement of AC's and
// couldn't find the way back).
if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Backpack + " Use AC's own bags", "/rc inv ac", false, AcPanels.CanToggle))
UseAcBags();
SafeImGui.SetItemTooltip(UseAcBagsTip);
if (RetailToolbarHooks.HideRetailToolbar)
{
if (ImGuiNET.ImGui.MenuItem("Show the game's toolbar", "/rc ui retailtoolbar off"))
RetailToolbarHooks.HideRetailToolbar = false;
SafeImGui.SetItemTooltip(ShowToolbarTip);
}
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Mini Remote", "/rc miniremote", MiniRemoteOpen, ImGuiPanelHost.HasFace(MiniRemoteFace.Title)))
ToggleMiniRemote();
SafeImGui.SetItemTooltip(MiniRemoteTip);
@ -366,7 +415,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
if (IconButton("##inv_more", PhosphorIcons.DotsThree, At(hl.More), btn22,
MiniRemoteOpen || RynthSortOpen || ItemCountOpen || GlobalInventoryOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11))
_openMore = true;
ImGuiNET.ImGui.SetItemTooltip("Mini Remote, RynthSort, Item Count, Global Inventory");
ImGuiNET.ImGui.SetItemTooltip("Use AC's own bags; Mini Remote, RynthSort, Item Count, Global Inventory");
}
RelatedMenu();
@ -393,6 +442,8 @@ internal sealed partial class InventoryFace : IImGuiPanel
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(dragFrom, p.Y));
ImGuiNET.ImGui.InvisibleButton("##inv_drag", new Vector2(dragTo - dragFrom, RowH));
ImGuiPanelHost.DragWindowWithLastItem();
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _openMore = true;
SafeImGui.SetItemTooltip(TitleMenuTip);
}
NextLine(p, RowH + 2);
}
@ -981,6 +1032,12 @@ internal sealed partial class InventoryFace : IImGuiPanel
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 (VendorTrade.TradableSnapshot != null)
{
// At a vendor: how to buy with this window up (InventoryFace.VendorBuy.cs).
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Storefront, p, new Vector2(16, statusH), Teal);
dl.AddText(new Vector2(p.X + 18, ty), Text, "Drag a vendor's item here to buy (any number)");
}
else if (idleView != null)
{
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Coins, p, new Vector2(16, statusH), Amber);

View file

@ -57,12 +57,50 @@ internal sealed class QuickSettingsDrawer : RynthAiDrawer
public override void Update(bool showing)
{
UpdateRulesFeed(showing);
if (showing == _sub) return;
_sub = showing;
if (showing) { UiSources.Settings.Subscribe(); UiSources.Settings.RequestRefresh(); }
else UiSources.Settings.Unsubscribe();
}
// A pinned Attack Spell Shapes row (Settings > Spell Combat) reads RynthAi's monster rules, and a pinned
// Navmesh View row (Settings > Navigation) RynthNav's status: polled while the drawer shows such a pin
// (checked once a second, not every frame).
private bool _rulesSub, _navSub;
private long _rulesCheckMs;
private void UpdateRulesFeed(bool showing)
{
bool want = _rulesSub, wantNav = _navSub;
if (!showing) want = wantNav = false;
else
{
long now = Environment.TickCount64;
if (now >= _rulesCheckMs)
{
_rulesCheckMs = now + 1000;
want = wantNav = false;
foreach (string key in QuickSettings.Pins)
{
string? label = QuickSettings.RowOf(key)?.Label;
want |= DefaultSpellShapes.IsShapeLabel(label);
wantNav |= NavmeshView.IsMeshLabel(label);
}
}
}
if (wantNav != _navSub)
{
_navSub = wantNav;
if (wantNav) { UiSources.RynthNav.Subscribe(); UiSources.RynthNav.RequestRefresh(); }
else UiSources.RynthNav.Unsubscribe();
}
if (want == _rulesSub) return;
_rulesSub = want;
if (want) { UiSources.MonsterRules.Subscribe(); UiSources.MonsterRules.RequestRefresh(); }
else UiSources.MonsterRules.Unsubscribe();
}
public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k)
{
float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.SlidersHorizontal, "MY SETTINGS", null, "Hide My settings");

View file

@ -9,10 +9,17 @@
// arrow turns with you every frame (the pose snapshot's heading); green
// within 30 yd, amber while it points at a portal on a route; a
// wand instead of the arrow when the next step is a recall.
// top line the one target and where it came from ("Chat coords 42.1N, 33.6E",
// "Route: Holtburg", "Arrow: Holtburg"; ArrowTarget), with an x that clears
// it (/rnav clear: the walk stops, the route goes, the arrow goes off).
// Popped out at a height saved before it had this line, the line folds
// into the name's place.
// text name, distance and compass point, the route step (n/m).
// row a box for coordinates or a place (Plan: route only; Enter or Go: RynthNav goes
// there), Plan, Go, Stop, and the caret: the route's steps open
// under it, current one green (the window fits its height).
// there; Route here for chat coords), Plan, Go, Stop, and the caret: the
// route's steps open under it, current one green (the window fits its
// height). Only a route to the arrow's own target opens there: an older
// route for somewhere else is not this window's target.
// corner small pop out and hide buttons. No resize grip: it sizes itself.
//
// The target comes from RynthNav's status (UiSources.RynthNav); RynthNav owns
@ -37,7 +44,7 @@ internal sealed class RynthNavArrowFace : IImGuiPanel
// Sized to its content (FitHeight): these are only the first-open size and the narrowest it goes.
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(232, 68), new Vector2(232, 60), PanelChrome.None, Background: 0, Rounding: 6, EdgeToEdge: true,
new PanelSpec(new Vector2(232, 82), new Vector2(232, 60), PanelChrome.None, Background: 0, Rounding: 6, EdgeToEdge: true,
NoResize: true),
() => new RynthNavArrowFace());
@ -65,6 +72,11 @@ internal sealed class RynthNavArrowFace : IImGuiPanel
private RynthNavRouteStep[]? _openWhenNot;
private int _scrolledTo = -1;
private float _requestedH = -1;
// The one target (ArrowTarget.Pick), rebuilt when the status or the chat note changes.
private ArrowTargetPick _pick = new(ArrowTargetSource.None, "No target", false);
private RynthNavStatus? _pickFor;
private int _pickChatV = -1;
private string _pickText = "No target";
public void OnShown()
{
@ -84,48 +96,50 @@ internal sealed class RynthNavArrowFace : IImGuiPanel
if (size.X < 40 || size.Y < 30) return;
RynthNavStatus? st = UiSources.RynthNav.Current?.Value;
_read.Update(st);
UpdatePick(st);
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), f10 = ImGuiFonts.Get(UiFont.Ui10), f9 = ImGuiFonts.Get(UiFont.Ui9);
const float pad = 5, gap = 3;
const float sb = 14; // the corner buttons: small, for a small panel
float b = MathF.Round(MathF.Max(20, f10.FontSize + 8)); // buttons and the input row
float d = MathF.Round(bold.FontSize + f10.FontSize + 14); // the arrow's ring
float rowY = origin.Y + pad + d + 4;
bool hasRoute = st != null && st.Route.Length > 0 && st.RouteLines.Length > 0;
bool hasRoute = st != null && st.Route.Length > 0 && st.RouteLines.Length > 0 && _pick.RouteBelongs;
if (_openWhenNot != null && hasRoute && !ReferenceEquals(st!.Route, _openWhenNot)) { _showRoute = true; _scrolledTo = -1; _openWhenNot = null; }
if (!hasRoute) _showRoute = false;
float lineH = f10.FontSize + 3;
int rows = hasRoute ? Math.Min(st!.Route.Length, MaxRouteRows) : 0;
float listH = _showRoute ? MathF.Round(bold.FontSize + 4 + rows * lineH + 6) : 0;
float wantH = pad + d + 4 + b + pad + (_showRoute ? 4 + listH : 0);
// The target's line on top. Popped out, the OS window keeps the size it had: one saved before
// this line was there is too short for it, so the line folds into the name's place.
float wantH = pad + sb + d + 4 + b + pad + (_showRoute ? 4 + listH : 0);
bool topLine = !ImGuiPopOuts.InPopOutFrame || size.Y + 0.5f >= wantH;
float lift = topLine ? sb : 0;
if (!topLine) wantH -= sb;
float rowY = origin.Y + pad + lift + d + 4;
FitHeight(wantH, size.Y);
dl.AddRectFilled(origin, origin + size, Glass, 6);
dl.AddRect(origin, origin + size, BtnBord, 6);
// The arrow, in a ring on the left.
Vector2 c = origin + new Vector2(pad + d * 0.5f, pad + d * 0.5f);
Vector2 c = origin + new Vector2(pad + d * 0.5f, pad + lift + d * 0.5f);
dl.AddCircleFilled(c, d * 0.5f, ShellBg, 32);
dl.AddCircle(c, d * 0.5f, Ring, 32, 1.5f);
_read.DrawPointer(dl, c, d * 0.5f - 5);
// Name, then distance and compass point (the route step on the right of it).
// Top-right corner: clear the target, pop out, hide (small and flat).
float tx = origin.X + pad + d + 8, right = origin.X + size.X - pad;
const float sb = 14; // the corner buttons: small, for a small panel
dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 2 * sb - 4, origin.Y + size.Y), true);
dl.AddText(bold, bold.FontSize, new Vector2(tx, origin.Y + pad + 2), Teal, _read.Line1);
dl.PopClipRect();
string step = _read.HasTarget && st?.Arrow is { Steps: > 1 } sa ? $"{sa.Step}/{sa.Steps}" : "";
float stepW = step.Length > 0 ? f9.CalcTextSizeA(f9.FontSize, float.MaxValue, 0, step).X + 4 : 0;
float line2Y = origin.Y + pad + 2 + bold.FontSize + 4;
dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - stepW, origin.Y + size.Y), true);
if (_read.HasTarget) dl.AddText(f10, f10.FontSize, new Vector2(tx, line2Y), Text, _read.Line2);
else dl.AddText(f9, f9.FontSize, new Vector2(tx, line2Y + 1), Mute, _read.Line3.Length > 0 ? "Type coordinates or a place below" : "");
dl.PopClipRect();
if (step.Length > 0) dl.AddText(f9, f9.FontSize, new Vector2(right - stepW + 4, line2Y + 1), Mute, step);
// Top-right corner: pop out, hide (small and flat).
var closePos = new Vector2(origin.X + size.X - 3 - sb, origin.Y + 3);
var popPos = closePos - new Vector2(sb + 2, 0);
var clearPos = (PanelRouter.CanPopOut ? popPos : closePos) - new Vector2(sb + 2, 0);
bool walking = st?.Goto == true;
bool canClear = _pick.Source != ArrowTargetSource.None || walking;
if (IconButton("##rna_clear", PhosphorIcons.XCircle, clearPos, new Vector2(sb, sb), canClear ? Text : Done, Glass, enabled: canClear, font: UiFont.Ui9)
&& canClear)
RynthNavCommands.ClearTarget(st);
SafeImGui.SetItemTooltip(!canClear ? "No target to clear"
: walking ? "Clear the target: stop walking, drop the route, turn the arrow off"
: "Clear the target: turn the arrow off and drop its route");
if (PanelRouter.CanPopOut)
{
if (IconButton("##rna_pop", ImGuiPanelHost.PopOutGlyph, popPos, new Vector2(sb, sb), Done, Glass, font: UiFont.Ui9))
@ -136,6 +150,31 @@ internal sealed class RynthNavArrowFace : IImGuiPanel
ImGuiPanelHost.Close(Title);
ImGuiNET.ImGui.SetItemTooltip("Hide the arrow (the RynthNav panel's Arrow tab shows it again)");
// The target's line: where it came from, beside the corner buttons.
if (topLine)
{
var labelPos = new Vector2(origin.X + pad + 2, origin.Y + 3 + (sb - f9.FontSize) * 0.5f);
dl.PushClipRect(new Vector2(origin.X + pad, origin.Y), new Vector2(clearPos.X - 3, origin.Y + 3 + sb), true);
dl.AddText(f9, f9.FontSize, labelPos, SourceColor(_pick.Source), _pickText);
dl.PopClipRect();
}
// Name, then distance and compass point (the route step on the right of it). Without the
// top line the target's line takes the name's place, beside the corner buttons.
float line1Y = origin.Y + pad + lift + 2;
dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(topLine ? right : clearPos.X - 3, origin.Y + size.Y), true);
if (topLine) dl.AddText(bold, bold.FontSize, new Vector2(tx, line1Y), Teal, _read.Line1);
else dl.AddText(bold, bold.FontSize, new Vector2(tx, line1Y), SourceColor(_pick.Source), _pick.Label);
dl.PopClipRect();
string step = _read.HasTarget && st?.Arrow is { Steps: > 1 } sa ? $"{sa.Step}/{sa.Steps}" : "";
float stepW = step.Length > 0 ? f9.CalcTextSizeA(f9.FontSize, float.MaxValue, 0, step).X + 4 : 0;
float line2Y = line1Y + bold.FontSize + 4;
dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - stepW, origin.Y + size.Y), true);
if (_read.HasTarget) dl.AddText(f10, f10.FontSize, new Vector2(tx, line2Y), Text, _read.Line2);
else dl.AddText(f9, f9.FontSize, new Vector2(tx, line2Y + 1), Mute, _read.Line3.Length > 0 ? "Type coordinates or a place below" : "");
dl.PopClipRect();
if (step.Length > 0) dl.AddText(f9, f9.FontSize, new Vector2(right - stepW + 4, line2Y + 1), Mute, step);
// Bottom row: where to go, Plan, Go, Pause, Stop, the route's steps.
var routePos = new Vector2(right - b, rowY);
var stopPos = routePos - new Vector2(b + gap, 0);
@ -154,6 +193,8 @@ internal sealed class RynthNavArrowFace : IImGuiPanel
}
SafeImGui.SetItemTooltip(typed.Length > 0
? "Plan a route to " + typed + " without walking it (the steps open below)"
: _pick.Source == ArrowTargetSource.Chat
? "Route here: plan a route to the chat coordinates without walking it (the steps open below)"
: "Plan a route to the arrow's target without walking it (the steps open below)");
bool go = IconButton("##rna_go", PhosphorIcons.Play, goPos, new Vector2(b, b), Green, BtnFill, enabled: canGo, font: UiFont.Ui11);
SafeImGui.SetItemTooltip(typed.Length > 0
@ -164,7 +205,7 @@ internal sealed class RynthNavArrowFace : IImGuiPanel
if (typed.Length > 0) RynthNavCommands.Command("go " + typed);
else if (st?.Arrow is RynthNavArrow ar) RynthNavCommands.Go(ar.Final, ar.FinalNs, ar.FinalEw);
}
bool walking = st?.Goto == true, paused = walking && st!.Paused;
bool paused = walking && st!.Paused;
if (IconButton("##rna_pause", paused ? PhosphorIcons.Play : PhosphorIcons.Pause, pausePos, new Vector2(b, b), paused ? Amber : Text,
paused ? Selected : BtnFill, enabled: walking, border: paused ? Amber : 0, font: UiFont.Ui11) && walking)
RynthNavCommands.Command(paused ? "resume" : "pause");
@ -179,7 +220,7 @@ internal sealed class RynthNavArrowFace : IImGuiPanel
_showRoute = !_showRoute;
_scrolledTo = -1;
}
SafeImGui.SetItemTooltip(hasRoute ? (_showRoute ? "Hide the route's steps" : "Show the route's steps") : "No route yet: Plan or Go makes one");
SafeImGui.SetItemTooltip(hasRoute ? (_showRoute ? "Hide the route's steps" : "Show the route's steps") : "No route to this target yet: Plan or Go makes one");
if (_showRoute && hasRoute)
RouteList(st!, new Vector2(origin.X + pad, rowY + b + 4), new Vector2(size.X - 2 * pad, listH), bold, lineH);
@ -189,10 +230,43 @@ internal sealed class RynthNavArrowFace : IImGuiPanel
ImGuiNET.ImGui.SetCursorScreenPos(origin);
ImGuiNET.ImGui.InvisibleButton("##rna_surface", new Vector2(size.X, rowY - origin.Y - 2));
ImGuiPanelHost.DragWindowWithLastItem();
if (ImGuiNET.ImGui.IsItemHovered() && _read.Tooltip.Length > 0)
SafeImGui.SetItemTooltip(_read.Tooltip + (_read.Line3.Length > 0 && _read.Kind == "portal" ? "\n" + _read.Line3 : ""));
if (ImGuiNET.ImGui.IsItemHovered())
{
// The top line: where the target came from. Below it: the arrow's own tooltip.
if (topLine && ImGuiNET.ImGui.GetMousePos().Y < origin.Y + 3 + sb)
SafeImGui.SetItemTooltip(_pick.Label + "\nOne target at a time: a new one (chat coordinates, Plan, Go) replaces it. The x clears it.");
else if (_read.Tooltip.Length > 0)
SafeImGui.SetItemTooltip(_read.Tooltip + (_read.Line3.Length > 0 && _read.Kind == "portal" ? "\n" + _read.Line3 : ""));
}
}
/// <summary>The one target, rebuilt when the status or the chat window's note changes (not per frame).</summary>
private void UpdatePick(RynthNavStatus? st)
{
if (ReferenceEquals(st, _pickFor) && ArrowTarget.ChatVersion == _pickChatV) return;
_pickFor = st;
_pickChatV = ArrowTarget.ChatVersion;
if (st == null) { _pick = new(ArrowTargetSource.None, "No target", false); _pickText = "No target"; return; }
ArrowTargetInput t = st.Target;
_pick = ArrowTarget.Pick(t, t.HasArrow && t.Steps <= 1 && ArrowTarget.FromChat(t.FinalNs, t.FinalEw));
string glyph = _pick.Source switch
{
ArrowTargetSource.Chat => PhosphorIcons.ChatCircleText,
ArrowTargetSource.Route => PhosphorIcons.Path,
ArrowTargetSource.Arrow => PhosphorIcons.NavigationArrow,
_ => "",
};
_pickText = glyph.Length > 0 ? glyph + " " + _pick.Label : _pick.Label;
}
private static uint SourceColor(ArrowTargetSource s) => s switch
{
ArrowTargetSource.Chat => Teal,
ArrowTargetSource.Route => Purple,
ArrowTargetSource.Arrow => Text,
_ => Mute,
};
/// <summary>The coordinates or place typed in the box, trimmed.</summary>
private string TypedTarget()
{

View file

@ -325,7 +325,7 @@ internal sealed class RynthNavFace : IImGuiPanel
if (Button("##go_stop", PhosphorIcons.Stop + " Stop", new Vector2(p.X + 3 * (bw + 4), p.Y), new Vector2(bw, 26),
walking ? Text : Red, walking ? StopBg : BtnFill, border: walking ? Red : 0))
RynthNavCommands.Move(5);
SafeImGui.SetItemTooltip(walking ? "Stop walking" : "Stop any movement");
SafeImGui.SetItemTooltip(walking ? "Stop walking (the trip's markers go too)" : "Stop any movement and take a planned trip's markers off the ground");
NextLine(p, 32);
// Switches
@ -721,7 +721,7 @@ internal sealed class RynthNavFace : IImGuiPanel
RynthNavCommands.Command(st.MarkersOn ? "markers off" : "markers on");
SafeImGui.SetItemTooltip("Show the planned trip on the ground, the way RynthAi shows its nav routes: rings at the\n"
+ "waypoints, lines between them, the portals, recalls and the goal in their own colours.\n"
+ "They go when the trip ends, you stop, or you land somewhere that isn't on it."
+ "They go when the trip ends, you stop, you reach a plan's goal, or you land somewhere that isn't on it."
+ (st.MarkerStatus.Length > 0 ? "\n\nNow: " + st.MarkerStatus : ""));
if (Toggle("##mk_labels", "Labels", st.MarkerLabels, new Vector2(p.X + w1 + 4, p.Y), w2))
RynthNavCommands.Command(st.MarkerLabels ? "markers labels off" : "markers labels on");
@ -730,6 +730,17 @@ internal sealed class RynthNavFace : IImGuiPanel
RynthNavCommands.Command(st.MarkerGuide ? "markers guide off" : "markers guide on");
ImGuiNET.ImGui.SetItemTooltip("A line from your feet to the next waypoint (to the nearest marker for a plan you're not walking).");
NextLine(p, 26);
// A trip on the ground now (a plan stays until you get there): take it off without the switch.
if (st.MarkersShown)
{
p = ImGuiNET.ImGui.GetCursorScreenPos();
const string ClearLabel = PhosphorIcons.Eraser + " Clear the trip's markers";
if (Button("##mk_clear", ClearLabel, p, new Vector2(w, 22), Text, BtnFill, leftAlign: true))
RynthNavCommands.Command("markers clear");
SafeImGui.SetItemTooltip("Take this trip's rings, lines and labels off the ground now (/rnav markers clear).\n"
+ "Path markers stays on: the next Route or Go shows its own.");
NextLine(p, 26);
}
}
// The navmesh drawn in the world (RynthNav 0.6.7+): green where nav can walk, red walls where
@ -741,7 +752,8 @@ internal sealed class RynthNavFace : IImGuiPanel
if (Toggle("##ms_on", "Show navmesh", st.MeshOn, p, w1))
RynthNavCommands.Command(st.MeshOn ? "mesh off" : "mesh on");
SafeImGui.SetItemTooltip("Draw the navigation mesh in the world: green where nav can walk, red walls where the mesh ends\n"
+ "(buildings, trees, rocks, cliffs, steep ground and the margin round them). Not drawn in dungeons."
+ "(buildings, trees, rocks, cliffs, steep ground and the margin round them). In a dungeon it draws the dungeon's\n"
+ "own mesh when RynthNav has one for it. It stays on (after a relog too) until you turn it off here (/rnav mesh off)."
+ (st.MeshOn ? $"\n\nNow: {st.MeshDrawn} triangles drawn." : ""));
if (Toggle("##ms_floor", "Green", st.MeshFloor, new Vector2(p.X + w1 + 4, p.Y), w2))
RynthNavCommands.Command(st.MeshFloor ? "mesh floor off" : "mesh floor on");

View file

@ -4,13 +4,17 @@
// the client knows about anywhere (not just in radar range) whose name
// matches shows up here. Engine only, ImGui only.
//
// add row a text box (Enter adds), Add, Add selected (the crosshair: the
// selected object's name), Import (the file icon: Virindi Sense's
// list, Documents\Decal Plugins\Virindi Sense\patterns.txt), the
// look buttons, the settings gear, the help mark (2026-11-22)
// terms one chip per term: click it to switch it on/off, X removes it;
// past four rows of chips they scroll in a box (an imported list
// can be a few hundred names). An empty list offers the import.
// add row a text box (Enter adds), Exact (2026-11-26: the typed name
// matches the whole name only), Add, Add selected (the crosshair:
// the selected object's name, as an exact term), Import (the file
// icon: Virindi Sense's list, Documents\Decal Plugins\Virindi
// Sense\patterns.txt), the look buttons, the settings gear, the
// help mark (2026-11-22)
// terms one chip per term: click it to switch it on/off, = switches
// Exact (lit = whole name only), X removes it; right-click for a
// menu with the Exact match checkbox; past four rows of chips they
// scroll in a box (an imported list can be a few hundred names).
// An empty list offers the import.
// status how many matches among how many known objects (or why none)
// rows direction arrow (relative to where you face), name, kind,
// distance, compass point, map coordinates; nearest first; a new
@ -80,11 +84,12 @@ internal sealed class SenseFace : IImGuiPanel
"around you (outdoors: your landblock and the ones around it, a few hundred yards, far past the radar), or the whole " +
"dungeon you are in. Nothing beyond that reaches the client, so no plugin can see it.\n\n" +
"Terms ignore case. Without * or ? a name only has to contain the term (drake finds Dragon's Isle Drake). " +
"With them the whole name must match: Drake* starts with Drake, ? is any one letter.\n\n" +
"With them the whole name must match: Drake* starts with Drake, ? is any one letter. " +
"Exact (the box by Add, or a name's = button): only that whole name matches, so Drake finds Drake but not Drake Hatchling.\n\n" +
"The distance shows when you and the object are both outdoors (or in surface buildings), or in the same dungeon. " +
"Otherwise the row says elsewhere and gives the landblock.\n\n" +
"Click a row to select it in game. Gear: a chat line or a beep when a new match appears.\n" +
"The crosshair adds the selected monster's or item's name. The file icon imports your Virindi Sense list " +
"The crosshair adds the selected monster's or item's exact name. The file icon imports your Virindi Sense list " +
"(Documents\\Decal Plugins\\Virindi Sense\\patterns.txt).\n" +
"The arrows-in button (or /rc sense compact on) shows just the matches, without the frame.\n" +
"/rc sense opens and closes this panel.";
@ -96,6 +101,10 @@ internal sealed class SenseFace : IImGuiPanel
private long _messageUntilMs;
private bool _openSettings;
private bool _flashing;
// The add row's Exact box (this session; off, so a typed name matches as before).
private bool _addExact;
// The term whose right-click menu is open (by text: the list can change under it).
private string _menuTerm = "";
private long _clearArmedUntilMs;
// Compact / collapsed: the mouse is over what the last frame drew (rows, the line, the
@ -162,17 +171,26 @@ internal sealed class SenseFace : IImGuiPanel
const float h = 22, iconW = 22;
string addLabel = PhosphorIcons.Plus + " Add";
float addW = ButtonWidth(addLabel);
float boxW = Math.Max(60, w - addW - iconW * 6 - 28);
// Exact (2026-11-26): the next typed name matches the whole name only. A checkbox of its own.
string exactLabel = (_addExact ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " Exact";
float exactW = ButtonWidth(exactLabel);
float boxW = Math.Max(60, w - addW - exactW - iconW * 6 - 32);
bool enter = TextBox("##sense_input", _input, start, boxW,
PhosphorIcons.MagnifyingGlass + " Name to watch for (* and ? wildcards)", out _,
ImGuiInputTextFlags.EnterReturnsTrue, h);
bool add = Button("##sense_add", addLabel, new Vector2(start.X + boxW + 4, start.Y), new Vector2(addW, h), Text, BtnFill,
float ex = start.X + boxW + 4;
if (Button("##sense_add_exact", exactLabel, new Vector2(ex, start.Y), new Vector2(exactW, h), _addExact ? Teal : Mute, BtnFill))
_addExact = !_addExact;
SafeImGui.SetItemTooltip(_addExact
? "Exact match is on: the name you add matches only that whole name, any case\n(\"Drake\" finds Drake, not Dragon's Isle Drake). Click for names containing it."
: "Exact match is off: the name you add matches every name containing it\n(\"Drake\" also finds Dragon's Isle Drake). Click so it matches the whole name only.\nEach name's = button switches it later.");
bool add = Button("##sense_add", addLabel, new Vector2(ex + exactW + 4, start.Y), new Vector2(addW, h), Text, BtnFill,
enabled: SenseStore.Loaded);
ImGuiNET.ImGui.SetItemTooltip("Add the name to the watch list (Enter in the box does the same)");
if (enter || add) AddTerm();
float gx = start.X + boxW + 4 + addW + 4;
float gx = ex + exactW + 4 + addW + 4;
// Add selected (2026-11-22): the selected monster's or item's name onto the list.
bool haveSel = SenseStore.Loaded && ClientHelperHooks.GetSelectedItemId() != 0;
if (IconButton("##sense_addsel", PhosphorIcons.Crosshair, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill,
@ -182,8 +200,8 @@ internal sealed class SenseFace : IImGuiPanel
ShowMessage(message, ok ? Mute : Amber);
}
SafeImGui.SetItemTooltip(haveSel
? "Add selected: watch for the selected object's name (/rc sense addselected)"
: "Add selected: select a monster or an item in game, then click here to watch for its name");
? "Add selected: watch for the selected object's exact name (/rc sense addselected;\n/rc sense addselected contains for names containing it)"
: "Add selected: select a monster or an item in game, then click here to watch for its exact name");
gx += iconW + 4;
// Import Virindi Sense's list (Documents\Decal Plugins\Virindi Sense\patterns.txt).
if (IconButton("##sense_import", PhosphorIcons.FilePlus, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill,
@ -221,7 +239,7 @@ internal sealed class SenseFace : IImGuiPanel
private void AddTerm()
{
string text = Utf8(_input);
bool ok = SenseStore.Add(text, out string message);
bool ok = SenseStore.Add(text, out string message, _addExact);
if (ok) WriteUtf8(_input, "");
ShowMessage(message, ok ? Mute : Amber);
}
@ -275,7 +293,7 @@ internal sealed class SenseFace : IImGuiPanel
return;
}
const float iconW = 18, xW = 16;
const float iconW = 18, xW = 16 + EqW; // the = (Exact) and X segments at the chip's end
float[] textWidths = ChipTextWidths(terms);
// A long list (an imported one can be a few hundred names) scrolls in a box of a few rows,
@ -293,7 +311,7 @@ internal sealed class SenseFace : IImGuiPanel
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Ui11);
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
float x = start.X, y = start.Y;
int toggle = -1, remove = -1;
int toggle = -1, remove = -1, exactFlip = -1, menu = -1;
for (int i = 0; i < terms.Length; i++)
{
SensePattern t = terms[i];
@ -307,12 +325,22 @@ internal sealed class SenseFace : IImGuiPanel
ImGuiNET.ImGui.SetCursorScreenPos(p);
if (ImGuiNET.ImGui.InvisibleButton("##t", new Vector2(chipW - xW, ChipH))) toggle = i;
bool hotT = ImGuiNET.ImGui.IsItemHovered();
if (hotT && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) menu = i;
if (hotT)
SafeImGui.SetItemTooltip(t.Enabled
? (t.IsGlob ? "On: the whole name must match (wildcards). Click to switch off." : "On: names containing this match. Click to switch off.")
: "Off. Click to switch on.");
SafeImGui.SetItemTooltip((t.Enabled
? (t.Exact ? "On: only this exact name matches (any case)." : t.IsGlob ? "On: the whole name must match (wildcards)." : "On: names containing this match.") + " Click to switch off."
: "Off. Click to switch on.") + "\nRight-click: Exact match and Remove.");
// Exact (2026-11-26): = lit when only the whole name matches; click to switch.
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x + chipW - xW, y));
if (ImGuiNET.ImGui.InvisibleButton("##x", new Vector2(xW, ChipH))) remove = i;
if (ImGuiNET.ImGui.InvisibleButton("##eq", new Vector2(EqW, ChipH))) exactFlip = i;
bool hotE = ImGuiNET.ImGui.IsItemHovered();
if (hotE && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) menu = i;
if (hotE)
SafeImGui.SetItemTooltip(t.Exact
? "Exact match: on. Only the whole name \"" + t.Text + "\" matches (any case).\nClick to match every name containing it."
: "Exact match: off. Every name containing \"" + t.Text + "\" matches" + (t.IsGlob ? " its wildcards" : "") + ".\nClick to match only this exact name.");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x + chipW - xW + EqW, y));
if (ImGuiNET.ImGui.InvisibleButton("##x", new Vector2(xW - EqW, ChipH))) remove = i;
bool hotX = ImGuiNET.ImGui.IsItemHovered();
if (hotX) ImGuiNET.ImGui.SetItemTooltip("Remove");
ImGuiNET.ImGui.PopID();
@ -326,11 +354,23 @@ internal sealed class SenseFace : IImGuiPanel
dl.PushClipRect(p, p + new Vector2(chipW - xW, ChipH), true);
dl.AddText(new Vector2(x + iconW, y + (ChipH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), fg, t.Text);
dl.PopClipRect();
PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.X, new Vector2(x + chipW - xW, y), new Vector2(xW, ChipH),
// The = mark: lit (teal) for an exact term, faint for the others.
Vector2 eqAt = new(x + chipW - xW, y);
if (hotE) dl.AddRectFilled(eqAt + new Vector2(1, 2), eqAt + new Vector2(EqW - 1, ChipH - 2), Lighten(bg), 2);
float eqTw = ImGuiNET.ImGui.CalcTextSize("=").X;
dl.AddText(new Vector2(eqAt.X + (EqW - eqTw) * 0.5f, y + (ChipH - ImGuiNET.ImGui.GetFontSize()) * 0.5f),
t.Exact ? Teal : hotE ? Mute : Faded(Faded(Mute)), "=");
PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.X, new Vector2(x + chipW - xW + EqW, y), new Vector2(xW - EqW, ChipH),
hotX ? Red : Faded(Mute));
x += chipW + 4;
}
NextLine(start, y - start.Y + ChipH + 4);
if (menu >= 0)
{
_menuTerm = terms[menu].Text;
ImGuiNET.ImGui.OpenPopup("##sense_term_menu");
}
DrawTermMenu(terms);
if (scroll)
{
ImGuiNET.ImGui.EndChild();
@ -338,6 +378,12 @@ internal sealed class SenseFace : IImGuiPanel
Label($"{terms.Length} names (scroll for more)", Faded(Mute));
}
if (exactFlip >= 0)
{
bool exact = !terms[exactFlip].Exact;
SenseStore.SetExact(exactFlip, exact);
ShowMessage(SenseFile.ExactReply(terms[exactFlip].Text, exact), Mute);
}
if (toggle >= 0) SenseStore.SetEnabled(toggle, !terms[toggle].Enabled);
if (remove >= 0)
{
@ -349,6 +395,54 @@ internal sealed class SenseFace : IImGuiPanel
/// <summary>Rows of term chips shown before the chips scroll.</summary>
private const int MaxChipRows = 4;
/// <summary>The = (Exact) segment of a chip, before its X.</summary>
private const float EqW = 14;
private const string ExactMenuTip =
"On: only a name that is exactly this matches, any case (Drake finds Drake, not Drake Hatchling).\n" +
"Off: every name containing it matches (or, with * or ?, the whole name matches them).\n" +
"The = on the chip switches it too.";
/// <summary>A chip's right-click menu: the Exact match checkbox, on/off, Remove.</summary>
private void DrawTermMenu(SensePattern[] terms)
{
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.CheckMark, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
bool open = ImGuiNET.ImGui.BeginPopup("##sense_term_menu");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(5);
if (!open) return;
try
{
int i = SenseFile.IndexOf(terms, _menuTerm);
if (i < 0) { ImGuiNET.ImGui.CloseCurrentPopup(); return; }
SensePattern t = terms[i];
ImGuiNET.ImGui.TextUnformatted(t.Text);
bool exact = t.Exact;
if (ImGuiNET.ImGui.Checkbox("Exact match (whole name, any case)", ref exact))
{
SenseStore.SetExact(i, exact);
ShowMessage(SenseFile.ExactReply(t.Text, exact), Mute);
}
SafeImGui.SetItemTooltip(ExactMenuTip);
bool on = t.Enabled;
if (ImGuiNET.ImGui.Checkbox("Watching", ref on)) SenseStore.SetEnabled(i, on);
SafeImGui.SetItemTooltip("Off: kept on the list, but not looked for (a click on the chip does the same).");
ImGuiNET.ImGui.Spacing();
if (ImGuiNET.ImGui.Button("Remove"))
{
ShowMessage($"Stopped watching for \"{t.Text}\".", Mute);
SenseStore.Remove(i);
ImGuiNET.ImGui.CloseCurrentPopup();
}
}
finally { ImGuiNET.ImGui.EndPopup(); }
}
// The chips' text widths, measured once per list (and text size), not every frame.
private SensePattern[]? _widthsFor;
private float _widthsFontSize;

View file

@ -63,6 +63,8 @@ internal sealed class SettingsFace : IImGuiPanel
{
UiSources.Settings.Unsubscribe();
SetDashboardFeed(false);
SetMonsterRulesFeed(false);
SetRynthNavFeed(false);
_rows.LeaveHotkeys();
}
@ -78,6 +80,36 @@ internal sealed class SettingsFace : IImGuiPanel
else UiSources.RynthAi.Unsubscribe();
}
private const string SpellCombatTab = "Spell Combat";
private bool _rulesFeed;
/// <summary>
/// Spell Combat's Attack Spell Shapes rows read RynthAi's monster rules (UI/Data/DefaultSpellShapes.cs):
/// subscribes (once) while that tab shows, even with the Damage panel closed.
/// </summary>
private void SetMonsterRulesFeed(bool on)
{
if (on == _rulesFeed) return;
_rulesFeed = on;
if (on) { UiSources.MonsterRules.Subscribe(); UiSources.MonsterRules.RequestRefresh(); }
else UiSources.MonsterRules.Unsubscribe();
}
private const string NavigationTab = "Navigation";
private bool _navFeed;
/// <summary>
/// Navigation's Navmesh View rows read RynthNav's status (UI/Data/NavmeshView.cs): subscribes (once)
/// while that tab shows, even with the RynthNav window closed.
/// </summary>
private void SetRynthNavFeed(bool on)
{
if (on == _navFeed) return;
_navFeed = on;
if (on) { UiSources.RynthNav.Subscribe(); UiSources.RynthNav.RequestRefresh(); }
else UiSources.RynthNav.Unsubscribe();
}
public void Draw()
{
// Take a newer fetch unless a value is being typed in.
@ -194,6 +226,8 @@ internal sealed class SettingsFace : IImGuiPanel
// Looting's Loot Profile row lists RynthAi's loot profiles from the dashboard snapshot: keep it
// polled while that tab shows, even with the dashboard closed.
SetDashboardFeed(SettingsSchema.Tabs[_tab].Name == LootingTab);
SetMonsterRulesFeed(SettingsSchema.Tabs[_tab].Name == SpellCombatTab);
SetRynthNavFeed(SettingsSchema.Tabs[_tab].Name == NavigationTab);
for (int i = 0; i < rows.Length; i++)
{
SettingRow row = rows[i];

View file

@ -177,7 +177,8 @@ internal static unsafe class PhosphorIcons
+ Pause + PersonSimpleRun
+ PushPin + SlidersHorizontal + Wrench
+ Scroll
+ Moon;
+ Moon
+ XCircle;
/// <summary>
/// Draws <paramref name="glyph"/> (one icon) centred in the box at

View file

@ -73,7 +73,8 @@ internal sealed unsafe class PopOutSurface : IDisposable
/// and pushes the latest finished frame to <paramref name="window"/>. False when
/// the device refused (logged, retried next frame).
/// </summary>
public bool Render(IntPtr device, ImDrawDataPtr drawData, int width, int height, Placement placement, LayeredWindow window)
public bool Render(IntPtr device, ImDrawDataPtr drawData, int width, int height, Placement placement, LayeredWindow window,
bool sameFrame = false, long keyAt = 0)
{
if (device == IntPtr.Zero || width <= 0 || height <= 0) return false;
if ((width != _width || height != _height || _targets[0] == IntPtr.Zero) && !Create(device, width, height))
@ -97,6 +98,7 @@ internal sealed unsafe class PopOutSurface : IDisposable
device, 0, IntPtr.Zero, D3DCLEAR_TARGET, 0x00000000, 1f, 0);
DX9Backend.RenderDrawData(drawData, device);
_placements[_current] = placement;
_keyAt[_current] = keyAt;
}
finally
{
@ -109,7 +111,9 @@ internal sealed unsafe class PopOutSurface : IDisposable
}
// Read back the target the GPU has finished: last frame's, or this one on the first frame.
int read = _previousValid ? 1 - _current : _current;
// While a text box is being typed in, this frame's own (sameFrame): the readback waits for
// the GPU, but a typed letter shows a frame sooner (11-26: typing in a popped-out chat lagged).
int read = _previousValid && !sameFrame ? 1 - _current : _current;
bool pushed = Push(device, vt, read, window);
_unpushed = read != _current; // this frame's picture is still to be shown
_previousValid = true;
@ -118,6 +122,17 @@ internal sealed unsafe class PopOutSurface : IDisposable
}
private bool _unpushed;
private readonly long[] _keyAt = new long[2];
private long _pushedKeyAt;
/// <summary>When the oldest key shown by the pushes since the last call was pressed (Stopwatch ticks), 0 if none. Read after Render/Flush.</summary>
public long TakePushedKeyAt()
{
long at = _pushedKeyAt;
_pushedKeyAt = 0;
return at;
}
/// <summary>
/// Shows the last rendered frame if it hasn't been shown yet (the readback
@ -135,6 +150,8 @@ internal sealed unsafe class PopOutSurface : IDisposable
{
IntPtr target = _targets[index];
Placement at = _placements[index];
if (_keyAt[index] != 0 && (_pushedKeyAt == 0 || _keyAt[index] < _pushedKeyAt)) _pushedKeyAt = _keyAt[index];
_keyAt[index] = 0;
if (((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, IntPtr, int>)vt[GetRenderTargetDataSlot])(device, target, _readback) < 0)
return Fail("GetRenderTargetData");
void** svt = *(void***)_readback;

View file

@ -32,6 +32,7 @@ internal static class UiDropTargets
public Vector2 Min, Max; // ImGui coordinates of the game window's client area (docked)
public long SeenMs;
public bool Accepting;
public Predicate<uint>? Accepts; // null: any item
public bool HasDrop;
public uint ItemId, SpellId;
}
@ -61,8 +62,9 @@ internal static class UiDropTargets
/// body in screen coordinates as ImGui sees them (FaceKit.Begin's origin and size).
/// <paramref name="accepting"/> false: drawn, but a drop now wouldn't be used (it then
/// goes to AC as usual). Popped-out faces hit-test against their own window.
/// <paramref name="accepts"/>: which items it takes (null: any); any other item goes to AC.
/// </summary>
public static void Publish(string key, string panelTitle, Vector2 min, Vector2 max, bool accepting)
public static void Publish(string key, string panelTitle, Vector2 min, Vector2 max, bool accepting, Predicate<uint>? accepts = null)
{
lock (Sync)
{
@ -72,6 +74,7 @@ internal static class UiDropTargets
t.Min = min;
t.Max = max;
t.Accepting = accepting;
t.Accepts = accepts;
t.SeenMs = Environment.TickCount64;
}
}
@ -92,6 +95,8 @@ internal static class UiDropTargets
{
if (!t.Accepting || now - t.SeenMs > StaleMs || !IsCursorOver(t))
continue;
if (t.Accepts != null && !SafeAccepts(t.Accepts, itemId))
continue; // not an item this target takes (it goes to AC as usual)
t.HasDrop = true;
t.ItemId = itemId;
t.SpellId = spellId;
@ -102,6 +107,12 @@ internal static class UiDropTargets
return false;
}
private static bool SafeAccepts(Predicate<uint> accepts, uint itemId)
{
try { return accepts(itemId); }
catch { return false; }
}
/// <summary>The face's draw: an item dropped on it since the last call.</summary>
public static bool TryTake(string key, out uint itemId)
{

View file

@ -443,6 +443,9 @@ internal static unsafe class Win32Backend
/// crosses an ImGui window keeps its moves and its RBUTTONUP.</summary>
private static bool _heldButtonsBelongToGame;
/// <summary>The mouse buttons held now were pressed on the game, not on an ImGui window (AC thread).</summary>
internal static bool HeldButtonsBelongToGame => _heldButtonsBelongToGame;
/// <summary>io.WantTextInput from the last ImGui frame: an ImGui text box is
/// being typed in. Vetoes chat Enter-capture the way AvaloniaTextInputActive
/// does for Avalonia TextBoxes.</summary>
@ -471,6 +474,8 @@ internal static unsafe class Win32Backend
/// trailing WM_CHAR ('\r') + WM_KEYUP of that same keystroke are eaten too and never
/// leak to the game (a lone '\r' can spuriously re-open AC's native chat bar).</summary>
private static bool _swallowEnterTail;
// A Ctrl+C that copied a chat selection: its WM_CHAR (0x03) is eaten too.
private static bool _swallowCopyChar;
// ── Chat input callbacks (set by RynthChatPanel) ─────────────────────
/// <summary>Fired when Enter in-game activates chat (UI thread dispatch optional).</summary>
@ -503,6 +508,13 @@ internal static unsafe class Win32Backend
public static Action? OnChatCopy;
/// <summary>Fired on Ctrl+X while capture is active.</summary>
public static Action? OnChatCut;
/// <summary>
/// Ctrl+C / Ctrl+Insert, typing in RynthChat or not: copies the text selected in a chat
/// window and returns true, or returns false when none is selected (then the key does what
/// it did before: copies the input line while typing, reaches the game otherwise). Not while
/// another text box has the keyboard. AC's main thread.
/// </summary>
public static Func<bool>? OnChatSelectionCopy;
private static int _lastPanelClientX; // last game-client pos over the panel (for wheel)
private static int _lastPanelClientY;
@ -897,6 +909,9 @@ internal static unsafe class Win32Backend
// updates to the panel on Avalonia's UI thread — no Avalonia focus needed.
if (ChatCaptureActive && (IsKeyMessage(msg) || IsExtraCharMessage(msg)))
{
// A popped-out chat draws the line: redraw it next frame (ImGuiPopOuts.NoteChatKey).
if (msg == WM_CHAR || msg == WM_KEYDOWN)
ImGuiPopOuts.NoteChatKey();
if (msg == WM_CHAR)
{
int ch = (int)wParam;
@ -910,7 +925,7 @@ internal static unsafe class Win32Backend
// control characters the branch above drops, so paste did nothing.
bool ctrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0, shift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
if ((ctrl && vk == 'V') || (shift && !ctrl && vk == VK_INSERT)) { OnChatPaste?.Invoke(); }
else if (ctrl && (vk == 'C' || vk == VK_INSERT)) { OnChatCopy?.Invoke(); }
else if (ctrl && (vk == 'C' || vk == VK_INSERT)) { if (OnChatSelectionCopy?.Invoke() != true) OnChatCopy?.Invoke(); }
else if (ctrl && vk == 'X') { OnChatCut?.Invoke(); }
else if (vk == VK_RETURN && !IsExtendedKey(lParam)) { ChatCaptureActive = false; _swallowEnterTail = true; PostMessage(_gameHwnd, WM_RYNTHCORE_CHAT, IntPtr.Zero, IntPtr.Zero); }
else if (vk == VK_ESCAPE) { ChatCaptureActive = false; _swallowEnterTail = true; OnChatCancel?.Invoke(); }
@ -1004,6 +1019,25 @@ internal static unsafe class Win32Backend
}
}
// ── Ctrl+C copies the text selected in a chat window ─────────
// The game keeps the keyboard, so the chat can't see the key itself. Only with text
// selected there; otherwise Ctrl+C goes on to AC (and ImGui) as before. Not while a
// text box of ours (or a pop-out's) has the keyboard: it copies its own text.
if (msg == WM_KEYDOWN && OnChatSelectionCopy != null && (int)wParam == 'C'
&& (GetKeyState(VK_CONTROL) & 0x8000) != 0 && (GetKeyState(VK_MENU) & 0x8000) == 0 && (GetKeyState(VK_SHIFT) & 0x8000) == 0
&& !AvaloniaTextInputActive && !ImGuiTextInputActive && !_wantCaptureKeyboard && !ImGuiPopOuts.HasTextFocus
&& OnChatSelectionCopy.Invoke())
{
_swallowCopyChar = true;
return IntPtr.Zero;
}
// The Ctrl+C's WM_CHAR (0x03) after a copy: AC never sees the key, so not its char either.
if (_swallowCopyChar)
{
if (msg == WM_CHAR && (int)wParam == 0x03) { _swallowCopyChar = false; return IntPtr.Zero; }
if (msg == WM_KEYDOWN || msg == WM_CHAR) _swallowCopyChar = false;
}
// ── Restore focus to game when Avalonia acquires it ───────────
if (msg == WM_RYNTH_RESTORE_FOCUS)
{

View file

@ -1091,6 +1091,15 @@ internal struct RynthCoreAPI
/// <summary>v94: <c>int WebPanelGetState(int handle, WebPanelStateNative* state)</c>: the WebPanelStatusCode
/// (a handle that is not the live one reads 6 Superseded), -1 bad args.</summary>
public IntPtr WebPanelGetStateFn;
// ── v99: AC's camera (Compatibility\AcCamera.cs) ──
/// <summary>v99: <c>int CameraAction(int action, int pressed)</c>: AC's own camera key for <c>action</c> (0 the
/// default view, 1 turn left, 2 turn right, 3 raise, 4 lower, 5 closer, 6 farther, 7 first person), pressed
/// (1) or let go (0); a held one goes on until it is let go, as the key does. Done on AC's game thread before its
/// tick. Returns 1 queued, 0 not available (AC's camera handler not found, a full queue), -1 bad action. Any
/// thread. Requires API v99+.</summary>
public IntPtr CameraActionFn;
}
/// <summary>v94 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs.</summary>
@ -2016,6 +2025,9 @@ internal delegate int WebPanelCloseCallbackDelegate(int handle);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int WebPanelGetStateCallbackDelegate(int handle, WebPanelStateNative* state);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int CameraActionCallbackDelegate(int action, int pressed);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate uint VendorBuyCallbackDelegate(uint vendorId, VendorTradeEntryNative* entries, int count);

View file

@ -79,5 +79,11 @@ internal static class PluginContractVersion
/// <summary>The API version whose PluginShared RynthCore.LootSdk has Keep # per day.</summary>
public const uint LootSdkPerDay = 98;
public const uint Current = 98;
// v99: CameraAction(action, pressed): AC's own camera keys from a plugin (Compatibility\AcCamera.cs) - turn,
// raise, lower, closer and farther held until let go, the default view ("home") and first person - for
// the phone's Live view (RynthRemote 0.11). The SDK's HasCameraAction / CameraAction / RynthCameraAction.
/// <summary>The API version with CameraAction.</summary>
public const uint Camera = 99;
public const uint Current = 99;
}

View file

@ -310,6 +310,18 @@ internal static partial class PluginManager
private static WebPanelCloseCallbackDelegate? _webPanelCloseCallback; // v94
private static WebPanelGetStateCallbackDelegate? _webPanelGetStateCallback; // v94
#endif
private static CameraActionCallbackDelegate? _cameraActionCallback; // v99
/// <summary>v99 CameraAction: 1 queued, 0 not available, -1 a bad action. Never throws.</summary>
private static int CameraAction(int action, int pressed)
{
try
{
if (action is < 0 or > 7) return -1;
return Compatibility.AcCamera.Enqueue((Compatibility.AcCamera.Action)action, pressed != 0) ? 1 : 0;
}
catch { return 0; }
}
private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback;
private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback;
private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback;
@ -1702,6 +1714,7 @@ internal static partial class PluginManager
Compatibility.RetailVitalsHooks.ResetCachedInstance();
Compatibility.RetailToolbarHooks.ResetCachedInstance();
Compatibility.AcShortcuts.Reset();
Compatibility.AcCamera.Reset();
Compatibility.AcKeymapLive.Reset();
Compatibility.AcPanels.Reset();
Compatibility.ChatCallbackHooks.ResetOutgoingTarget();
@ -3446,6 +3459,8 @@ internal static partial class PluginManager
_api.WebPanelCloseFn = Marshal.GetFunctionPointerForDelegate(_webPanelCloseCallback!);
_api.WebPanelGetStateFn = Marshal.GetFunctionPointerForDelegate(_webPanelGetStateCallback!);
#endif
_cameraActionCallback ??= CameraAction;
_api.CameraActionFn = Marshal.GetFunctionPointerForDelegate(_cameraActionCallback);
RouteApiThroughLoader();
}

View file

@ -190,7 +190,11 @@ internal static unsafe class ShortcutApi
/// <summary>
/// v90 GetIconTexture: kind 0 an icon (0x06) id, 1 an object (its icon with underlay and
/// overlay), 2 a spell. An ImGui texture id for ImGui.Image, or 0 while it is being made (ask
/// again next frame). AC's render thread, inside a docked window's draw.
/// again next frame). AC's render thread, inside a window's draw, docked or popped out.
/// Popped out (2026-11-26): a pop-out draws on the same D3D device with the same texture
/// ids, as the engine's own Inventory already does (ScriptIcons and RetailSprites in its
/// pop-out frames). Refused there before, every plugin window that drew items lost its
/// pictures once popped out: RynthSort's slots fell back to coloured squares with initials.
/// Kind 3 (2026-11-07, no API bump: older engines answer 0 for it): a retail UI picture, any 0x06
/// texture up to 512 x 512 at its own size (window backgrounds, banners, frame pieces), kept for
/// the session in RetailSprites, the cache the Inventory's Classic view draws from. For plugins
@ -203,7 +207,7 @@ internal static unsafe class ShortcutApi
{
try
{
if (kind is < 0 or > 4 || id == 0 || !MainThreadGuard.IsOnMainThread() || ImGuiPopOuts.InPopOutFrame) return IntPtr.Zero;
if (kind is < 0 or > 4 || id == 0 || !MainThreadGuard.IsOnMainThread()) return IntPtr.Zero;
if (kind == 3) return RetailSprites.TryGet(id, out IntPtr sprite) ? sprite : IntPtr.Zero;
if (kind == 4) return RetailSprites.TryGetFontSheet(id, out IntPtr sheet) ? sheet : IntPtr.Zero;
return ScriptIcons.TryGet((ScriptIconKind)kind, id, out IntPtr texture) ? texture : IntPtr.Zero;

View file

@ -14,6 +14,8 @@
// Tick): a client area that is not that size is resized to it at the restore, a saved
// size that differs is ignored (one log line), and a stretched window is never saved.
// Borderless windowed keeps the client area where it is (outer = client).
// Since 2026-11-26 a borderless game at (or above) its monitor's size fills that monitor
// exactly instead, taskbar included (BorderlessFill), and is kept there.
// While this is on, the launcher leaves the window's position to the engine.
// Original: SilentKelpie (RynthCore PR 6). Decisions live in AcWindowChromePolicy.
//
@ -60,7 +62,7 @@ internal static class AcWindowChrome
private static readonly object Sync = new();
private static readonly Action PostedWork = RunOnGameThread;
private static long _nextTickMs, _firstTickMs, _workPostedAtMs, _nextStyleActionMs;
private static long _nextTickMs, _firstTickMs, _workPostedAtMs, _nextStyleActionMs, _nextFillMs;
private static int _workPosted;
private static bool _loggedNoExecutor;
@ -96,7 +98,8 @@ internal static class AcWindowChrome
{
// AC's resolution, for the window's size (2026-11-21): the back buffer it draws into. Read
// here because the device belongs to the render thread; the game thread uses the copy.
if (EngineSettings.RememberAcWindowPosition)
// Borderless windowed uses it too (2026-11-26): a game at its monitor's size fills it.
if (EngineSettings.RememberAcWindowPosition || EngineSettings.BorderlessWindowed)
Interlocked.Exchange(ref _drawSize,
ImGuiBackend.DX9Backend.TryGetBackBufferSize(device, out int bw, out int bh) ? ((long)bw << 32) | (uint)bh : 0);
@ -116,6 +119,11 @@ internal static class AcWindowChrome
&& DecideBorderless(EngineSettings.BorderlessWindowed, ReadMarker(hwnd), style,
LooksExclusiveFullscreen(hwnd, style)).Action != ChromeAction.None;
// A window we made borderless that should fill its monitor and does not (AC resized it, or
// the restore moved it): put it back on the monitor, at most once per StyleRetryMs.
if (!work && now >= Interlocked.Read(ref _nextFillMs) && FillNeeded(hwnd, style) != null)
work = true;
// Posted every tick until the restore is decided: it waits for AC's size to settle.
if (EngineSettings.RememberAcWindowPosition && !PlacementDone(hwnd) && InWorld() && KeyReady(now, out _))
work = true;
@ -189,21 +197,86 @@ internal static class AcWindowChrome
{
case ChromeAction.Strip:
SetProp(hwnd, StyleProp, new IntPtr(d.NewMarker));
SetStyleKeepingClient(hwnd, d.NewStyle);
RynthLog.UI("AcWindowChrome: borderless windowed on.");
// A game at its monitor's size fills the monitor (2026-11-26); a smaller one keeps
// its client area where it is (2026-11-21). Decided from the framed window.
if (StripFill(hwnd) is Rect fill)
{
SetWindowLong(hwnd, GwlStyle, d.NewStyle);
FillMonitor(hwnd, fill);
RynthLog.UI(FormattableString.Invariant(
$"AcWindowChrome: borderless windowed on, full screen on the monitor at ({fill.Left},{fill.Top}) {fill.Width}x{fill.Height}."));
}
else
{
SetStyleKeepingClient(hwnd, d.NewStyle, pullOnScreen: false);
RynthLog.UI("AcWindowChrome: borderless windowed on.");
}
break;
case ChromeAction.Restore:
RemoveProp(hwnd, StyleProp);
SetStyleKeepingClient(hwnd, d.NewStyle);
// The frame grows around the client area; a full screen one would put the caption
// above the monitor, so the window is pulled onto the work area.
SetStyleKeepingClient(hwnd, d.NewStyle, pullOnScreen: true);
RynthLog.UI("AcWindowChrome: window borders restored.");
break;
case ChromeAction.ClearMarker:
RemoveProp(hwnd, StyleProp);
RynthLog.UI("AcWindowChrome: borderless marker cleared (" + d.Reason + ").");
break;
case ChromeAction.None:
if (Environment.TickCount64 >= Interlocked.Read(ref _nextFillMs) && FillNeeded(hwnd, style) is Rect again)
{
Interlocked.Exchange(ref _nextFillMs, Environment.TickCount64 + StyleRetryMs);
FillMonitor(hwnd, again);
RynthLog.UI(FormattableString.Invariant(
$"AcWindowChrome: borderless full screen put back on the monitor at ({again.Left},{again.Top}) {again.Width}x{again.Height}."));
}
break;
}
}
/// <summary>The window's rect and client size, and the full rect of the monitor it is (mostly) on.</summary>
private static bool TryReadWindow(IntPtr hwnd, out Rect outer, out Size client, out Rect monitor)
{
outer = default; client = default; monitor = default;
if (!GetWindowRect(hwnd, out RECT wr) || !GetClientRect(hwnd, out RECT cr)) return false;
IntPtr mon = MonitorFromWindow(hwnd, 2 /* MONITOR_DEFAULTTONEAREST */);
if (mon == IntPtr.Zero) return false;
var mi = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() };
if (!GetMonitorInfo(mon, ref mi)) return false;
outer = new Rect(wr.Left, wr.Top, wr.Right, wr.Bottom);
client = new Size(cr.Right - cr.Left, cr.Bottom - cr.Top);
monitor = new Rect(mi.rcMonitor.Left, mi.rcMonitor.Top, mi.rcMonitor.Right, mi.rcMonitor.Bottom);
return true;
}
/// <summary>At a strip (the window still framed): the monitor it must fill, else null.</summary>
private static Rect? StripFill(IntPtr hwnd)
{
if (IsIconic(hwnd) || IsZoomed(hwnd)) return null;
return TryReadWindow(hwnd, out Rect outer, out Size client, out Rect monitor)
? BorderlessFill(outer, client, DrawSize(), monitor)
: null;
}
/// <summary>
/// A window we made borderless (our marker, no caption, setting on) that should fill its monitor
/// and is not exactly on it: the monitor rect, else null. Reads only.
/// </summary>
private static Rect? FillNeeded(IntPtr hwnd, int style)
{
if (!EngineSettings.BorderlessWindowed || ReadMarker(hwnd) == 0 || (style & WsCaption) != 0) return null;
if (IsIconic(hwnd) || IsZoomed(hwnd)) return null;
return TryReadWindow(hwnd, out Rect outer, out Size client, out Rect monitor)
? BorderlessFillNeeded(outer, client, DrawSize(), monitor)
: null;
}
/// <summary>Borderless full screen: the window covers its monitor exactly (no topmost: Windows moves the taskbar aside).</summary>
private static void FillMonitor(IntPtr hwnd, Rect fill)
=> SetWindowPos(hwnd, IntPtr.Zero, fill.Left, fill.Top, fill.Width, fill.Height,
SwpNozorder | SwpNoactivate | SwpFramechanged);
// Style change only: same outer rect, non-client area rebuilt.
private static void Refresh(IntPtr hwnd)
=> SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0,
@ -215,8 +288,10 @@ internal static class AcWindowChrome
/// with the chrome back, the frame grows around it again. Keeping the outer rect instead, as
/// before, grew or shrank the client area by the frame, so AC stretched its picture by a few
/// pixels and the overlay was off by as much. Minimised or maximised: the style only.
/// <paramref name="pullOnScreen"/> (chrome back, 2026-11-26): the framed rect is pulled onto a
/// work area, so a caption grown above a full screen window's top edge stays reachable.
/// </summary>
private static void SetStyleKeepingClient(IntPtr hwnd, int newStyle)
private static void SetStyleKeepingClient(IntPtr hwnd, int newStyle, bool pullOnScreen)
{
RECT client = default;
bool keep = !IsIconic(hwnd) && !IsZoomed(hwnd) && GetClientRect(hwnd, out client);
@ -233,6 +308,12 @@ internal static class AcWindowChrome
if (AdjustWindowRectEx(ref outer, newStyle, false, GetWindowLong(hwnd, GwlExStyle)))
{
int outerW = outer.Right - outer.Left, outerH = outer.Bottom - outer.Top;
if (pullOnScreen)
{
var areas = new List<AcWindowPlacementRule.WorkArea>();
foreach (Rect a in WorkAreas()) areas.Add(new AcWindowPlacementRule.WorkArea(a.Left, a.Top, a.Right, a.Bottom));
(outer.Left, outer.Top) = AcWindowPlacementRule.ClampToWorkArea(outer.Left, outer.Top, outerW, outerH, areas);
}
SetWindowPos(hwnd, IntPtr.Zero, outer.Left, outer.Top, outerW, outerH,
SwpNozorder | SwpNoactivate | SwpFramechanged);
return;

View file

@ -9,6 +9,7 @@
// save follow the launcher's AcWindowPlacementRule (src\RynthCore.App, compiled in):
// position only, and a rect is saved only once it held for 30 s. Since 2026-11-21 the
// window's size comes from AC's resolution (the back buffer), never from a saved rect.
// - Borderless full screen (2026-11-26): which borderless window fills its monitor.
// AcWindowChrome does the Win32 work and asks these first.
// Idea and first version: SilentKelpie (RynthCore PR 6).
// ============================================================================
@ -85,6 +86,40 @@ internal static class AcWindowChromePolicy
return new ChromeDecision(ChromeAction.Restore, style | (marker & BorderChromeMask), 0, "restore");
}
// ── Borderless full screen (2026-11-26) ──────────────────────────────
//
// Discord 11-26: after 2026.11.23.1 borderless windowed at the monitor's resolution was no longer
// full screen: the taskbar showed, and there was a caption-high gap at the top. Since 2026-11-21
// the strip kept the CLIENT area where it was (AcWindowChrome.SetStyleKeepingClient), so a
// 1920x1080 game whose framed window sat at (0,0) kept its picture at (3,26), under where the
// caption had been, and a window that does not cover its monitor does not get the taskbar out of
// the way. Before, the strip kept the OUTER rect, which covered the monitor. So:
// - a borderless window whose game is at least its monitor's size (AC's resolution, else the
// client area), or whose window covers the whole monitor, fills that monitor exactly
// (rcMonitor, the taskbar's part included): borderless full screen;
// - any other borderless window keeps its client area where it is (2026-11-21), so a game
// smaller than the screen is not stretched.
/// <summary>
/// The monitor rect a borderless window must fill, or null when it is a smaller game that keeps its
/// client area. <paramref name="outer"/> is the window's rect (framed before a strip, = client after),
/// <paramref name="client"/> its client size, <paramref name="draw"/> AC's resolution (null: unknown)
/// and <paramref name="monitor"/> the full rect of the monitor the window is on.
/// </summary>
public static Rect? BorderlessFill(Rect outer, Size client, Size? draw, Rect monitor)
{
if (monitor.Width < MinWidth || monitor.Height < MinHeight) return null;
Size game = draw is Size d && d.IsUsable ? d : client;
bool gameFills = game.Width >= monitor.Width && game.Height >= monitor.Height;
bool covers = outer.Left <= monitor.Left && outer.Top <= monitor.Top
&& outer.Right >= monitor.Right && outer.Bottom >= monitor.Bottom;
return gameFills || covers ? monitor : null;
}
/// <summary>A borderless window that should fill its monitor and is not exactly on it: the monitor, else null.</summary>
public static Rect? BorderlessFillNeeded(Rect outer, Size client, Size? draw, Rect monitor)
=> BorderlessFill(outer, client, draw, monitor) is Rect m && m != outer ? m : null;
// ── Window position ──────────────────────────────────────────────────
public const int MinWidth = 160, MinHeight = 120, MaxExtent = 16384;

View file

@ -0,0 +1,100 @@
// ============================================================================
// RynthCore.Engine - UI/Data/ArrowTarget.cs
// What the RynthNav Arrow window shows as its one target, and where it came
// from (11-24, a player: "You'll notice the top and bottom have different
// targets": the arrow pointed at clicked chat coordinates while the route list
// under it was an older trip somewhere else).
//
// source Chat coords (a chat link clicked, noted here by the chat window),
// Route (the arrow follows a route, or the route shown goes where
// the arrow points), Arrow (a place set any other way), or none.
// route the steps list opens only when the route goes where the arrow
// points; an older route for somewhere else stays out of the window.
//
// RynthNav owns the target (one at a time, the newest wins: TargetSwitch); this
// is the window's side, so an older RynthNav that kept a stale route still shows
// one target. Pure: no engine types, so tools/ArrowTargetTests compiles it.
// ============================================================================
using System;
using System.Globalization;
namespace RynthCore.Engine.UI.Data;
internal enum ArrowTargetSource { None, Chat, Arrow, Route }
/// <summary>
/// RynthNav's arrow and route, as the window needs them. Final: where the arrow ends up (the place
/// itself on a chained route). Route goal: RynthNav's "gns"/"gew" when it sends them, else the
/// route's last step.
/// </summary>
internal readonly record struct ArrowTargetInput(
bool HasArrow, string Final, double FinalNs, double FinalEw, int Steps,
bool HasRoute, string RouteFor, bool RouteHasGoal, double RouteNs, double RouteEw,
bool RouteHasLast, double LastNs, double LastEw);
/// <summary>The one target: where it came from, the line that says so, and whether the route list belongs to it.</summary>
internal readonly record struct ArrowTargetPick(ArrowTargetSource Source, string Label, bool RouteBelongs);
internal static class ArrowTarget
{
/// <summary>Two spots this close (degrees, about 14 u) are the same place: chat coordinates have one decimal.</summary>
public const double SameDegrees = 0.06;
// The last coordinates a chat link pointed the arrow at (the chat window, AC's render thread).
private static bool _chat;
private static double _chatNs, _chatEw;
/// <summary>Bumped on every chat note, so the window rebuilds its label.</summary>
public static int ChatVersion { get; private set; }
/// <summary>The chat window pointed the arrow at these coordinates (a link clicked, or Arrow to / Route to).</summary>
public static void NoteChat(double ns, double ew)
{
_chat = true; _chatNs = ns; _chatEw = ew;
ChatVersion++;
}
public static void ForgetChat() { _chat = false; ChatVersion++; }
/// <summary>The arrow's place is where a chat link last pointed it (RynthNav's commands carry two decimals).</summary>
public static bool FromChat(double ns, double ew) =>
_chat && Math.Abs(ns - _chatNs) < 0.006 && Math.Abs(ew - _chatEw) < 0.006;
public static bool SamePlace(double nsA, double ewA, double nsB, double ewB) =>
!double.IsNaN(nsA) && !double.IsNaN(ewA) && !double.IsNaN(nsB) && !double.IsNaN(ewB)
&& Math.Abs(nsA - nsB) <= SameDegrees && Math.Abs(ewA - ewB) <= SameDegrees;
/// <summary>The route shown goes where the arrow points (or there is no arrow: the route is the target).</summary>
public static bool RouteBelongs(in ArrowTargetInput t)
{
if (!t.HasRoute) return false;
if (!t.HasArrow) return true;
// RynthNav says where its route goes: that decides (two places can share a name).
if (t.RouteHasGoal) return SamePlace(t.RouteNs, t.RouteEw, t.FinalNs, t.FinalEw);
if (t.RouteFor.Length > 0 && string.Equals(t.RouteFor, t.Final, StringComparison.OrdinalIgnoreCase)) return true;
return t.RouteHasLast && SamePlace(t.LastNs, t.LastEw, t.FinalNs, t.FinalEw);
}
/// <param name="chat">The arrow came from a chat link (<see cref="FromChat"/>).</param>
public static ArrowTargetPick Pick(in ArrowTargetInput t, bool chat)
{
bool belongs = RouteBelongs(t);
if (!t.HasArrow)
return belongs ? new(ArrowTargetSource.Route, "Route: " + Name(t.RouteFor, t.RouteNs, t.RouteEw, t.RouteHasGoal), true)
: new(ArrowTargetSource.None, "No target", false);
string final = Name(t.Final, t.FinalNs, t.FinalEw, true);
if (t.Steps > 1 || belongs) return new(ArrowTargetSource.Route, "Route: " + final, belongs);
if (chat) return new(ArrowTargetSource.Chat, "Chat coords " + Coord(t.FinalNs, t.FinalEw), false);
return new(ArrowTargetSource.Arrow, "Arrow: " + final, false);
}
private static string Name(string name, double ns, double ew, bool hasCoords) =>
name.Length > 0 ? name : hasCoords ? Coord(ns, ew) : "a place";
/// <summary>"12.3N, 45.6E" (RynthNavStatus.Coord's format).</summary>
public static string Coord(double ns, double ew) => Loc(ns, 'N', 'S') + ", " + Loc(ew, 'E', 'W');
private static string Loc(double v, char pos, char neg) =>
v.ToString("F1", CultureInfo.InvariantCulture).TrimStart('-') + (v >= 0 ? pos : neg);
}

View file

@ -1094,6 +1094,7 @@ internal static class ChatModel
SetInput(text, text.Length, null);
};
// The line has no selection: copy and cut take all of it, paste goes in at the caret.
// (Ctrl+C copies the chat's selected text instead when there is some.)
Win32Backend.OnChatPaste = () =>
{
InputState s = _input;
@ -1102,6 +1103,8 @@ internal static class ChatModel
_historyIndex = -1;
SetInput(text, cursor, null);
};
// Text selected in a chat window wins over the input line (ChatView.CopyActiveSelection).
Win32Backend.OnChatSelectionCopy = RynthCore.Engine.ImGuiBackend.Panels.ChatView.CopyActiveSelection;
Win32Backend.OnChatCopy = () =>
{
string text = _input.Text;

View file

@ -0,0 +1,141 @@
// ============================================================================
// RynthCore.Engine - UI/Data/ChatTextSelection.cs
// The pure half of selecting text in RynthChat's scrollback (2026-11-26 request:
// "mouse selection, ctrl + C to copy", "full item id on one text line"). The chat
// view (ImGui/Panels/ChatView.cs) finds which line and character the mouse is on;
// this file turns two such ends into the text that is copied, finds the character
// under an x position in one row, and joins an item's info lines into one line.
// No ImGui, no engine state: tools/ChatTellTests compiles it in.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Engine.UI.Data;
internal static class ChatTextSelection
{
/// <summary>Puts the two ends of a selection in reading order (a before b).</summary>
public static void Order(ref int aLine, ref int aChar, ref int bLine, ref int bChar)
{
if (aLine < bLine || (aLine == bLine && aChar <= bChar)) return;
(aLine, bLine) = (bLine, aLine);
(aChar, bChar) = (bChar, aChar);
}
/// <summary>
/// <paramref name="index"/> kept inside <paramref name="text"/> and never between the two
/// halves of a surrogate pair (it moves to the pair's start).
/// </summary>
public static int Clamp(string text, int index)
{
index = Math.Clamp(index, 0, text.Length);
if (index > 0 && index < text.Length && char.IsLowSurrogate(text[index]) && char.IsHighSurrogate(text[index - 1]))
index--;
return index;
}
/// <summary>
/// The selected part [from, to) of one line. A part that starts at the line's start takes
/// its timestamp too (<paramref name="timestamp"/>, null when timestamps are off), as a
/// whole copied line always has ("12:01:33 text").
/// </summary>
public static string Part(string text, string? timestamp, int from, int to)
{
from = Clamp(text, from);
to = Clamp(text, to);
if (to < from) (from, to) = (to, from);
string part = text.Substring(from, to - from);
return from == 0 && !string.IsNullOrEmpty(timestamp) ? timestamp + " " + part : part;
}
/// <summary>
/// The character boundary nearest <paramref name="x"/> in the row [start, end) of
/// <paramref name="text"/>, x measured from the row's left edge. <paramref name="advance"/>
/// is the drawn width of the character (or surrogate pair) at an index.
/// </summary>
public static int CharAtX(string text, int start, int end, float x, Func<int, float> advance)
{
end = Math.Min(end, text.Length);
if (x <= 0f || start >= end) return Math.Clamp(start, 0, text.Length);
float acc = 0f;
int k = start;
while (k < end)
{
int step = char.IsHighSurrogate(text[k]) && k + 1 < end && char.IsLowSurrogate(text[k + 1]) ? 2 : 1;
float w = advance(k);
if (x < acc + w * 0.5f) return k;
acc += w;
k += step;
}
return end;
}
// ── An item's info lines (RynthAi's item info, the Items tab) ───────────
/// <summary>RynthChat files the lines that start with this under Items (its ChatClassifier).</summary>
public const string ItemPrefix = "[RynthAi Item] ";
/// <summary>The longest run of one item's lines looked at (the pet layout writes up to 5).</summary>
private const int MaxItemLines = 12;
public static bool IsItemLine(string text) => text.StartsWith(ItemPrefix, StringComparison.Ordinal);
/// <summary>One of an item's later lines: indented under its first ("[RynthAi Item] ...").</summary>
public static bool IsItemDetail(string text) =>
IsItemLine(text) && text.Length > ItemPrefix.Length + 1
&& text[ItemPrefix.Length] == ' ' && text[ItemPrefix.Length + 1] == ' ';
/// <summary>
/// The lines of the item <paramref name="index"/> belongs to: its first line (the name) and
/// the indented lines under it. False when that line isn't item info.
/// </summary>
public static bool ItemRun(IReadOnlyList<string> texts, int index, out int first, out int last)
{
first = last = index;
if (index < 0 || index >= texts.Count || !IsItemLine(texts[index])) return false;
while (first > 0 && index - first < MaxItemLines && IsItemDetail(texts[first]) && IsItemLine(texts[first - 1]))
first--;
while (last + 1 < texts.Count && last - first < MaxItemLines && IsItemDetail(texts[last + 1]))
last++;
return true;
}
/// <summary>
/// An item's info lines as one line, without the "[RynthAi Item]" tags: the parts joined
/// with ", " (the two spaces the layout puts between parts of a line too).
/// </summary>
public static string ItemOneLine(IReadOnlyList<string> texts, int first, int last)
{
var sb = new StringBuilder(256);
for (int i = Math.Max(0, first); i <= last && i < texts.Count; i++)
{
string body = texts[i];
if (IsItemLine(body)) body = body.Substring(ItemPrefix.Length);
body = body.Trim();
if (body.Length == 0) continue;
if (sb.Length > 0) sb.Append(", ");
AppendCollapsingGaps(sb, body);
}
return sb.ToString();
}
// "+5% Melee D Wield 300" -> "+5% Melee D, Wield 300": a run of 2+ spaces is the layout's gap between parts.
private static void AppendCollapsingGaps(StringBuilder sb, string body)
{
int i = 0;
while (i < body.Length)
{
if (body[i] == ' ' && i + 1 < body.Length && body[i + 1] == ' ')
{
while (i < body.Length && body[i] == ' ') i++;
// A part that already ends in a comma keeps just the one.
if (sb.Length > 0 && sb[^1] == ',') sb.Append(' ');
else sb.Append(", ");
continue;
}
sb.Append(body[i++]);
}
}
}

View file

@ -0,0 +1,182 @@
// ============================================================================
// RynthCore.Engine - UI/Data/DefaultSpellShapes.cs
// Settings > Spell Combat > Attack Spell Shapes (2026-11-26): the DEFAULT
// monster line's war/void spell shapes (streak, arc, blast, bolt, ring,
// wall) as plain checkboxes, so "cast streaks instead of bolts" is found
// where the other attack-spell settings are. Until then it was only on the
// Damage panel's DEFAULT line (Monster Detail > Shapes), which a new player
// didn't find.
//
// The same flags as Monster Detail's Shapes row: these rows read the rules
// RynthAi sends (UiSources.MonsterRules) and edit the Default rule through
// DamageCommands.EditRule (the latest rules read fresh, on the pump thread),
// the path Monster Detail uses. No new plugin export.
//
// A monster with its own entry (an exact-name rule from the Damage panel, or
// a name rule) has its own copy of the shapes and keeps them; the status
// line under the checkboxes says how many do, and which cast something else.
//
// Pure except the "live" members at the bottom (Loaded, Get, Edit, SummaryNow),
// so tools\CombatSettingsTests can check the rules by reflection.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Text;
using Rule = RynthCore.Engine.UI.Panels.MonstersPanel.Rule;
namespace RynthCore.Engine.UI.Data;
internal static class DefaultSpellShapes
{
public const string SectionLabel = "Attack Spell Shapes (Default monster)";
public const string OpenMonstersLabel = "Per monster";
/// <summary>The checkboxes, in the order they're drawn: (rule field, label, tooltip).</summary>
public static readonly (string Field, string Label, string Tip)[] Rows =
{
("UseStreak", "Use streaks instead of bolts",
"Streak spells (Flame Streak, Frost Streak...): a fast projectile that is hard to dodge.\n" +
"On: streaks are cast instead of bolts. Arcs come first when Use arcs is on too."),
("UseArc", "Use arcs instead of bolts",
"Arc spells (Flame Arc, Frost Arc...): lobbed over low cover.\n" +
"On: arcs are cast first, before streaks, blasts and bolts."),
("UseBlast", "Use blasts instead of bolts",
"Blast spells (Flame Blast, Frost Blast...): a spread of projectiles, from level III.\n" +
"Used instead of a bolt when both are on (arcs and streaks come first). With Blast Range\n" +
"above 0 (below), a blast is cast only when enough monsters are in its fan."),
("UseBolt", "Use bolts",
"Bolt spells (Flame Bolt, Frost Bolt...): the default shape, cast when no shape above is on.\n" +
"Something is always on: turning the last shape off turns bolts back on."),
("UseRing", "Use rings when monsters crowd",
"Ring spells around you, instead of the shape above, when at least Min Ring Targets\n" +
"monsters are within Ring Range (Ring Spell Override below, and Ranges)."),
("UseWall", "Use walls when monsters line up",
"Wall spells (Slithering Flames, Os' Wall...): cast when Wall Range is above 0 and\n" +
"Min Wall Targets monsters stand in the wall's path (Wall Spell Override below)."),
};
public const string SectionTip =
"War and Void Magic shapes for every monster without an entry of its own.\n" +
"The same switches as the DEFAULT line's Shapes in the Damage panel (Monsters > DEFAULT).\n" +
"A monster with its own entry keeps its own shapes: Monsters, click its name.";
public const string OpenMonstersTip =
"Opens the Damage panel (the dashboard's Monsters button): click a monster's name for its own shapes,\n" +
"or DEFAULT for these.";
public static bool IsShapeField(string field) =>
field is "UseArc" or "UseBolt" or "UseRing" or "UseStreak" or "UseBlast" or "UseWall";
/// <summary>True for one of this section's checkbox labels.</summary>
public static bool IsShapeLabel(string? label)
{
if (label == null) return false;
foreach (var r in Rows) if (r.Label == label) return true;
return false;
}
public static bool IsDefault(Rule r) => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase);
/// <summary>The Default rule (null when there is none, or no rules).</summary>
public static Rule? DefaultRule(IReadOnlyList<Rule>? rules)
{
if (rules == null) return null;
foreach (Rule r in rules) if (IsDefault(r)) return r;
return null;
}
/// <summary>
/// Sets one shape on <paramref name="rule"/>. A rule is never left with no shape (RynthAi then
/// refuses to attack with magic): turning the last one off turns Bolt on, as Monster Detail does.
/// </summary>
public static void Set(Rule rule, string field, bool on)
{
if (!IsShapeField(field)) return;
rule.SetToggle(field, on);
if (!on && !HasAnyShape(rule)) rule.UseBolt = true;
}
public static bool HasAnyShape(Rule r) => r.UseArc || r.UseBolt || r.UseRing || r.UseStreak || r.UseBlast || r.UseWall;
/// <summary>The same six shapes on both.</summary>
public static bool SameShapes(Rule a, Rule b) =>
a.UseArc == b.UseArc && a.UseBolt == b.UseBolt && a.UseRing == b.UseRing
&& a.UseStreak == b.UseStreak && a.UseBlast == b.UseBlast && a.UseWall == b.UseWall;
/// <summary>"Streak", "Streak, Ring when enough are near", ... (RynthAi CombatManager.PickBaseShape's order).</summary>
public static string Casts(Rule r)
{
string b = DamageCommands.BaseShapeName(r);
if (b.Length == 0) return "nothing";
var sb = new StringBuilder(b);
if (r.UseRing) sb.Append(", Ring when enough are near");
if (r.UseWall) sb.Append(", Wall when they line up");
return sb.ToString();
}
/// <summary>Monster names shown in the line before "+N more".</summary>
public const int NamesShown = 3;
/// <summary>
/// The status line under the checkboxes: what the Default line casts, and the monsters with
/// their own entry ("3 monsters have their own setting: ..."). Empty when there's no Default rule.
/// </summary>
public static string Summary(IReadOnlyList<Rule>? rules)
{
Rule? def = DefaultRule(rules);
if (def == null || rules == null) return string.Empty;
var differ = new List<string>();
int own = 0;
foreach (Rule r in rules)
{
if (IsDefault(r) || string.IsNullOrWhiteSpace(r.Name)) continue;
own++;
if (!SameShapes(r, def)) differ.Add(r.Name.Trim());
}
var sb = new StringBuilder();
sb.Append(own == 0 ? "Every monster casts " : "Monsters without their own entry cast ").Append(Casts(def)).Append('.');
if (own == 0) return sb.ToString();
if (differ.Count > 0)
{
sb.Append(' ').Append(Count(differ.Count)).Append(differ.Count == 1 ? " has its own setting: " : " have their own setting: ");
for (int i = 0; i < Math.Min(NamesShown, differ.Count); i++)
{
if (i > 0) sb.Append(", ");
sb.Append(differ[i]);
}
if (differ.Count > NamesShown) sb.Append(" (+").Append(differ.Count - NamesShown).Append(" more)");
sb.Append('.');
}
int same = own - differ.Count;
if (same > 0)
{
sb.Append(' ');
if (differ.Count > 0) sb.Append(same.ToString(System.Globalization.CultureInfo.InvariantCulture)).Append(" more");
else sb.Append(Count(same));
sb.Append(same == 1 ? " has its own entry, set the same for now." : " have their own entry, set the same for now.");
}
sb.Append(own == 1 ? " It keeps its own shapes" : " Those keep their own shapes")
.Append(": change one in Monsters (click its name).");
return sb.ToString();
}
private static string Count(int n) => n == 1 ? "1 monster" : n.ToString(System.Globalization.CultureInfo.InvariantCulture) + " monsters";
// ── Live: the rules RynthAi sent (Settings is drawn on AC's thread) ──────────
private static IReadOnlyList<Rule>? CurrentRules => UiSources.MonsterRules.Current?.Value.Parsed.Rules;
/// <summary>RynthAi has sent its monster rules, Default among them (the rows show).</summary>
public static bool Loaded => DefaultRule(CurrentRules) != null;
/// <summary>The Default rule's <paramref name="field"/> as last sent.</summary>
public static bool Get(string field) => DefaultRule(CurrentRules)?.GetToggle(field) ?? false;
/// <summary>Sets the Default rule's <paramref name="field"/> (DamageCommands: the latest rules, pump thread).</summary>
public static void Edit(string field, bool on) => DamageCommands.EditRule("Default", r => Set(r, field, on));
public static string SummaryNow() => Summary(CurrentRules);
}

View file

@ -0,0 +1,110 @@
// ============================================================================
// RynthCore.Engine - UI/Data/NavmeshView.cs
// Settings > Navigation > Navmesh View (2026-11-26): RynthNav's navmesh
// drawing switches (Show navmesh, green floor, red walls, radius, detail)
// next to the other navigation display settings. Until then they were only
// a row on the RynthNav window's Go tab (ImGui/Panels/RynthNavFace.cs,
// MeshRows), which is easy to miss.
//
// These are RynthNav's settings (it saves them in rynthnav.json), not
// RynthAi's: the rows ignore the RynthAi settings object, read RynthNav's
// status (UiSources.RynthNav, the "mesh" block, RynthNav 0.6.7+) and send
// the Go tab's /rnav mesh commands (RynthNavCommands.Command). A save of
// the RynthAi copy after a click sends nothing (SettingsCommands.Save only
// sends changed fields), so nothing reaches RynthAi's payload or profile.
// Both places read the same status, so they stay in step.
//
// Pure except the "live" members at the bottom (Status, Get*, Set*), so
// tools\SettingsLayoutTests can check the rules by reflection.
// ============================================================================
using System;
using System.Globalization;
namespace RynthCore.Engine.UI.Data;
internal static class NavmeshView
{
public const string SectionLabel = "Navmesh View";
public const string ShowLabel = "Show Navmesh", FloorLabel = "Green Floor", WallsLabel = "Red Walls",
RadiusLabel = "Mesh Radius (m)", DetailLabel = "Mesh Detail (triangles)";
// The Go tab's steppers (RynthNavFace.MeshRows).
public const int RadiusMin = 10, RadiusMax = 150, RadiusStep = 10;
public const int DetailMin = 200, DetailMax = 7000, DetailStep = 500;
// The Go tab's tooltips (RynthNavFace.MeshRows).
public const string ShowTip =
"Draw the navigation mesh in the world: green where nav can walk, red walls where the mesh ends\n"
+ "(buildings, trees, rocks, cliffs, steep ground and the margin round them). In a dungeon it draws the dungeon's\n"
+ "own mesh when RynthNav has one for it. It stays on (after a relog too) until you turn it off here (/rnav mesh off).";
public const string FloorTip = "The walkable ground, in green.";
public const string WallsTip = "Upright red strips along every edge nav will not cross.";
public const string RadiusTip = "How far around you the mesh is drawn.";
public const string DetailTip =
"The most triangles the mesh may use. The game's 3D buffer holds 8192 for every plugin, so keep this under about 5000\n"
+ "when RynthVision's slope overlay is on. The nearest ground and walls are kept first.";
public const string SameAsGoTab = "\n\nRynthNav's setting (saved by RynthNav, not in the RynthAi profile); the same switch as the RynthNav window's Go tab.";
private static readonly string[] Labels = { ShowLabel, FloorLabel, WallsLabel, RadiusLabel, DetailLabel };
/// <summary>True for one of this section's row labels (the My settings drawer polls RynthNav for a pinned one).</summary>
public static bool IsMeshLabel(string? label) => label != null && Array.IndexOf(Labels, label) >= 0;
/// <summary>RynthNav has sent a status with the mesh block (0.6.7+): the rows show.</summary>
public static bool Available(RynthNavStatus? st) => st?.HasMesh == true;
/// <summary>Why the rows are hidden (empty while they show).</summary>
public static string Unavailable(RynthNavStatus? st) =>
st == null ? "Needs the RynthNav plugin. Once it is loaded, its navmesh switches show here."
: !st.HasMesh ? "This RynthNav can't draw the navmesh: it needs RynthNav 0.6.7 or newer."
: string.Empty;
/// <summary>"1840 triangles drawn now." while the mesh is on (empty otherwise).</summary>
public static string Drawn(RynthNavStatus? st) =>
st is { HasMesh: true, MeshOn: true } ? st.MeshDrawn.ToString(CultureInfo.InvariantCulture) + " triangles drawn now." : string.Empty;
/// <summary>The /rnav command (without /rnav) a switch sends.</summary>
public static string SwitchCommand(string label, bool on) => label switch
{
ShowLabel => on ? "mesh on" : "mesh off",
FloorLabel => on ? "mesh floor on" : "mesh floor off",
WallsLabel => on ? "mesh walls on" : "mesh walls off",
_ => throw new ArgumentException("not a navmesh switch: " + label, nameof(label)),
};
/// <summary>The /rnav command (without /rnav) a stepper sends, the value kept in its range.</summary>
public static string RadiusCommand(int metres) =>
"mesh radius " + Math.Clamp(metres, RadiusMin, RadiusMax).ToString(CultureInfo.InvariantCulture);
public static string DetailCommand(int triangles) =>
"mesh triangles " + Math.Clamp(triangles, DetailMin, DetailMax).ToString(CultureInfo.InvariantCulture);
public static bool GetSwitch(RynthNavStatus? st, string label) => st != null && label switch
{
ShowLabel => st.MeshOn,
FloorLabel => st.MeshFloor,
WallsLabel => st.MeshWalls,
_ => false,
};
// ── Live: RynthNav's last status (Settings is drawn on AC's thread) ──────────
public static RynthNavStatus? Status => UiSources.RynthNav.Current?.Value;
public static bool AvailableNow => Available(Status);
public static bool GetSwitchNow(string label) => GetSwitch(Status, label);
public static int RadiusNow => Status?.MeshRadius ?? 40;
public static int DetailNow => Status?.MeshTriangles ?? 3000;
public static void SetSwitch(string label, bool on) => RynthNavCommands.Command(SwitchCommand(label, on));
public static void SetRadius(int metres) => RynthNavCommands.Command(RadiusCommand(metres));
public static void SetDetail(int triangles) => RynthNavCommands.Command(DetailCommand(triangles));
}

View file

@ -85,7 +85,14 @@ internal sealed class RynthNavStatus
public double AvoidPortalM, AvoidWallM, CornerM;
public int OpenArrow;
public RynthNavArrow? Arrow;
/// <summary>RynthNav has /rnav clear (from 11-26: "clearCmd"): the arrow window's x sends it, else "arrow off".</summary>
public bool HasClear;
public string RouteFor = "", RouteSummary = "";
/// <summary>Where the route goes (RynthNav from 11-26: route "gns"/"gew"; RouteHasGoal false on older ones).</summary>
public bool RouteHasGoal;
public double RouteGoalNs, RouteGoalEw;
/// <summary>The arrow and route as the arrow window picks its one target from them (ArrowTarget).</summary>
public ArrowTargetInput Target;
/// <summary>How long the route takes, seconds (RynthNav from 11-19: route "secs"; -1 = not known, an older RynthNav).</summary>
public double RouteSecs = -1;
/// <summary>
@ -200,6 +207,7 @@ internal sealed class RynthNavStatus
s.AvoidWallM = Num(r, "avoidWallM");
s.CornerM = Num(r, "cornerM");
s.OpenArrow = Int(r, "openArrow");
s.HasClear = Int(r, "clearCmd") != 0;
if (r.TryGetProperty("arrow", out var a) && a.ValueKind == JsonValueKind.Object)
{
@ -220,6 +228,10 @@ internal sealed class RynthNavStatus
if (r.TryGetProperty("route", out var route) && route.ValueKind == JsonValueKind.Object)
{
s.RouteFor = Str(route, "for");
s.RouteHasGoal = route.TryGetProperty("gns", out var gns) && gns.ValueKind == JsonValueKind.Number
&& route.TryGetProperty("gew", out var gew) && gew.ValueKind == JsonValueKind.Number;
s.RouteGoalNs = Num(route, "gns");
s.RouteGoalEw = Num(route, "gew");
s.RouteActive = Int(route, "active") != 0;
s.RouteIdx = Int(route, "idx", -1);
var steps = new List<RynthNavRouteStep>();
@ -270,6 +282,14 @@ internal sealed class RynthNavStatus
}
s.Favorites = Places(r, "favs", recall: false);
s.Recent = Places(r, "recent", recall: false);
RynthNavArrow? ta = s.Arrow;
bool hasRoute = s.Route.Length > 0;
RynthNavRouteStep? last = hasRoute ? s.Route[^1] : null;
s.Target = new ArrowTargetInput(
ta != null, ta?.Final ?? "", ta?.FinalNs ?? 0, ta?.FinalEw ?? 0, ta?.Steps ?? 0,
hasRoute, s.RouteFor, s.RouteHasGoal, s.RouteGoalNs, s.RouteGoalEw,
last != null, last?.Ns ?? 0, last?.Ew ?? 0);
}
/// <summary>
@ -565,6 +585,18 @@ internal static unsafe class RynthNavCommands
public static void Arrow(string name, double ns, double ew) =>
Command("arrow " + RynthNavStatus.CommandCoord(ns, ew) + " " + name);
/// <summary>
/// The arrow window's x: no target at all. RynthNav from 11-26 has /rnav clear (stops a walk, drops
/// the route, arrow off); an older one gets Stop (while walking) and "arrow off".
/// </summary>
public static void ClearTarget(RynthNavStatus? st)
{
ArrowTarget.ForgetChat();
if (st?.HasClear == true) { Command("clear"); return; }
if (st?.Goto == true) Command("stop");
Command("arrow off");
}
public static void Go(string name, double ns, double ew) =>
Command("go " + RynthNavStatus.CommandCoord(ns, ew) + " " + name);

View file

@ -10,7 +10,8 @@
// format is SenseFile in SenseModel.cs).
// SensePattern (SenseModel.cs) one term, case-insensitive. Without wildcards
// the name only has to contain it ("drake" finds "Dragon's Isle
// Drake"); with * or ? the whole name must match ("Drake*").
// Drake"); with * or ? the whole name must match ("Drake*");
// Exact (2026-11-26): the whole name is the term ("Drake" only).
// SenseSource the scan: on the plugin pump thread at 2 Hz, reading only the
// engine's main-thread snapshots (LiveObjectIds, the identity,
// position, PWD and attackable snapshots, the player pose),
@ -133,10 +134,11 @@ internal static class SenseStore
}
/// <summary>
/// Adds a term (switched on). An existing term with the same text is switched
/// on instead. False when the text is empty, the list is full or not loaded yet.
/// Adds a term (switched on; <paramref name="exact"/>: whole name only). An existing term with
/// the same text is switched on instead, keeping how it matches. False when the text is empty,
/// the list is full or not loaded yet.
/// </summary>
public static bool Add(string text, out string message)
public static bool Add(string text, out string message, bool exact = false)
{
text = SenseFile.Clean(text);
if (!_loaded) { message = "The watch list is still loading."; return false; }
@ -148,25 +150,29 @@ internal static class SenseStore
if (at >= 0)
{
message = cur[at].Enabled ? $"\"{cur[at].Text}\" is already on the list." : $"\"{cur[at].Text}\" switched on.";
if (!cur[at].Enabled) Replace(at, new SensePattern(cur[at].Text, true));
if (cur[at].Exact != exact)
message += cur[at].Exact ? " It matches the exact name only (Exact is on)." : " It matches names containing it (Exact is off).";
if (!cur[at].Enabled) Replace(at, cur[at].WithEnabled(true));
return true;
}
if (cur.Length >= MaxTerms) { message = $"The list is full ({MaxTerms} terms)."; return false; }
var next = new SensePattern[cur.Length + 1];
Array.Copy(cur, next, cur.Length);
next[^1] = new SensePattern(text, true);
next[^1] = new SensePattern(text, true, exact);
Publish(next);
message = $"Watching for \"{text}\".";
message = exact ? $"Watching for \"{text}\" (exact name)." : $"Watching for \"{text}\".";
return true;
}
}
/// <summary>
/// The selected object's name onto the list (the panel's "Add selected" button and /rc sense
/// addselected): a monster, NPC, item, portal, anything the client has a name for. AC's thread
/// (reads the selection and the name snapshot only).
/// addselected): a monster, NPC, item, portal, anything the client has a name for. An exact
/// term since 2026-11-26 (the name was taken from the very object, so "Drake" doesn't also find
/// "Drake Hatchling"); <paramref name="exact"/> false ("/rc sense addselected contains") adds it
/// as a contains term. AC's thread (reads the selection and the name snapshot only).
/// </summary>
public static bool AddSelected(out string message)
public static bool AddSelected(out string message, bool exact = true)
{
uint id = ClientHelperHooks.GetSelectedItemId();
if (id == 0) { message = "Select something in game first (a monster, an item...), then Add selected."; return false; }
@ -175,7 +181,7 @@ internal static class SenseStore
message = "The selected object has no name the client knows yet; try again in a moment.";
return false;
}
return Add(name, out message);
return Add(name, out message, exact);
}
/// <summary>Where Virindi Sense keeps its list on this PC.</summary>
@ -229,7 +235,18 @@ internal static class SenseStore
{
SensePattern[] cur = _terms;
if ((uint)index >= (uint)cur.Length || cur[index].Enabled == enabled) return;
Replace(index, new SensePattern(cur[index].Text, enabled));
Replace(index, cur[index].WithEnabled(enabled));
}
}
/// <summary>Exact match on or off for one term (its chip's Exact box). Saved with the list.</summary>
public static void SetExact(int index, bool exact)
{
lock (Sync)
{
SensePattern[] cur = _terms;
if ((uint)index >= (uint)cur.Length || cur[index].Exact == exact) return;
Replace(index, cur[index].WithExact(exact));
}
}
@ -667,7 +684,7 @@ internal sealed class SenseSource : UiSource<SenseView>
if (coords.Length > 0) sb.Append(coords).Append(" ");
sb.Append("landblock ").Append((cell >> 16).ToString("X4", CultureInfo.InvariantCulture))
.Append(", cell 0x").Append(cell.ToString("X8", CultureInfo.InvariantCulture)).Append('\n');
sb.Append("Matches \"").Append(term.Text).Append("\"\n");
sb.Append("Matches \"").Append(term.Text).Append(term.Exact ? "\" (exact name)\n" : "\"\n");
sb.Append("Click to select it.");
return sb.ToString();
}

View file

@ -3,14 +3,16 @@
// The Sense panel's pure part (no AC, no ImGui, no files), so tools\SenseTests
// can compile it in:
//
// SensePattern one watch-list term (moved here from SenseData.cs).
// SensePattern one watch-list term (moved here from SenseData.cs): the name
// contains it, the whole name matches its * and ?, or (Exact,
// 2026-11-26) the whole name is it, any case.
// SenseLayoutMode how the panel looks: Full (the add row, term chips, status
// and the match rows), Compact (only the match rows, tighter,
// no frame or background, clicks pass through except on the
// rows; item-counter.lua's bare look) and Collapsed (one line,
// "Sense: N", that opens back to Compact on a click).
// SenseFile sense.txt read and written as text: the terms, the alerts
// and the look (view=full|compact|collapsed).
// SenseFile sense.txt read and written as text: the terms (and which
// are exact), the alerts and the look (view=full|compact|collapsed).
// SenseLayout the compact view's layout decisions (which columns fit,
// row height, which row the mouse is on) and /rc sense's
// look commands (compact on|off, collapse on|off, view ...)
@ -29,23 +31,40 @@ namespace RynthCore.Engine.UI.Data;
/// <summary>One watch-list term. Immutable.</summary>
internal sealed class SensePattern
{
public SensePattern(string text, bool enabled)
public SensePattern(string text, bool enabled, bool exact = false)
{
Text = (text ?? string.Empty).Trim();
Enabled = enabled;
IsGlob = Text.IndexOfAny(Wildcards) >= 0;
Exact = exact;
IsGlob = !exact && Text.IndexOfAny(Wildcards) >= 0;
}
private static readonly char[] Wildcards = { '*', '?' };
public string Text { get; }
public bool Enabled { get; }
/// <summary>True when the term has * or ?: the whole name must match it.</summary>
/// <summary>
/// Exact match (2026-11-26, asked for in #rynthsuite): the whole name is the term, any case and
/// nothing more ("Drake" finds "Drake", not "Dragon's Isle Drake"). * and ? are plain letters
/// then. Off for every term from before it, so they match as they did.
/// </summary>
public bool Exact { get; }
/// <summary>True when the term has * or ? (and isn't Exact): the whole name must match it.</summary>
public bool IsGlob { get; }
/// <summary>How the term matches, in a word: "exact", "wildcards", "contains".</summary>
public string MatchKind => Exact ? "exact" : IsGlob ? "wildcards" : "contains";
/// <summary>This term with <see cref="Enabled"/> set (Exact kept).</summary>
public SensePattern WithEnabled(bool enabled) => enabled == Enabled ? this : new SensePattern(Text, enabled, Exact);
/// <summary>This term with <see cref="Exact"/> set (on/off kept).</summary>
public SensePattern WithExact(bool exact) => exact == Exact ? this : new SensePattern(Text, Enabled, exact);
public bool Matches(string name)
{
if (Text.Length == 0 || string.IsNullOrEmpty(name)) return false;
if (Exact) return string.Equals(name.Trim(), Text, StringComparison.OrdinalIgnoreCase);
return IsGlob ? Glob(name, Text) : name.Contains(Text, StringComparison.OrdinalIgnoreCase);
}
@ -104,13 +123,16 @@ internal static class SenseFile
/// <summary>
/// Reads the lines of sense.txt: "alertChat=1", "alertBeep=0", "view=compact", "term=1|name"
/// (1 on, 0 off; a bare "term=name" is on). Comments (#), blank lines and unknown keys are
/// skipped; a duplicate term (any case), an empty one or one past <see cref="MaxTerms"/> is
/// dropped; an unknown view is Full.
/// (1 on, 0 off; a bare "term=name" is on) and "exact=name" (2026-11-26: that term matches the
/// whole name only; written on its own line after the term, so an engine from before it still
/// reads the term, as a contains term). An exact= line with no term= of that name adds the term,
/// on. Comments (#), blank lines and unknown keys are skipped; a duplicate term (any case), an
/// empty one or one past <see cref="MaxTerms"/> is dropped; an unknown view is Full.
/// </summary>
public static SenseFileData Parse(IEnumerable<string> lines)
{
var data = new SenseFileData();
var exact = new List<string>();
foreach (string raw in lines)
{
string line = (raw ?? string.Empty).Trim();
@ -141,8 +163,21 @@ internal static class SenseFile
data.Terms.Add(new SensePattern(text, on));
break;
}
case "exact":
{
string text = Clean(val);
if (text.Length > 0) exact.Add(text);
break;
}
}
}
// After every term= line, so the order of the two kinds of line doesn't matter.
foreach (string text in exact)
{
int at = IndexOf(data.Terms, text);
if (at >= 0) data.Terms[at] = data.Terms[at].WithExact(true);
else if (data.Terms.Count < MaxTerms) data.Terms.Add(new SensePattern(text, true, exact: true));
}
return data;
}
@ -152,15 +187,24 @@ internal static class SenseFile
var sb = new StringBuilder();
sb.AppendLine("# RynthCore Sense watch list - auto-generated, hand-edits OK. /rc sense in game.");
sb.AppendLine("# term=1|name (1 on, 0 off). No * or ?: the name contains it. With * or ?: the whole name matches.");
sb.AppendLine("# exact=name after a term: only that whole name, any case (the Exact box on its chip).");
sb.AppendLine("# view=full|compact|collapsed (/rc sense compact on|off, /rc sense collapse on|off).");
sb.AppendLine(alertChat ? "alertChat=1" : "alertChat=0");
sb.AppendLine(alertBeep ? "alertBeep=1" : "alertBeep=0");
sb.Append("view=").AppendLine(SenseLayout.LayoutName(layout));
foreach (SensePattern t in terms)
{
sb.Append("term=").Append(t.Enabled ? '1' : '0').Append('|').AppendLine(t.Text);
if (t.Exact) sb.Append("exact=").AppendLine(t.Text);
}
return sb.ToString();
}
/// <summary>The line after a term's Exact box is switched (the chip's = and its right-click menu).</summary>
public static string ExactReply(string text, bool exact) => exact
? $"\"{text}\": exact match, only that whole name."
: $"\"{text}\": names containing it match.";
/// <summary>One line, trimmed, at most <see cref="MaxTermLength"/> characters.</summary>
public static string Clean(string text)
{
@ -185,7 +229,8 @@ internal readonly record struct SenseMerge(SensePattern[] Terms, int Added, int
/// Documents\Decal Plugins\Virindi Sense\patterns.txt: the first line is how many names follow,
/// then one name per line, matched anywhere in an object's name, any case (as Sense's terms
/// without wildcards). The format is from a real file (CRLF, 163 names, repeats in it, no
/// wildcards or other marks); nothing else about Virindi Sense is used. Pure.
/// wildcards or other marks; no match-type field either, so imported names stay "contains", as
/// Virindi Sense matched them, 2026-11-26); nothing else about Virindi Sense is used. Pure.
/// </summary>
internal static class SenseImport
{
@ -289,13 +334,31 @@ internal static class SenseLayout
public const float CompactNameRoom = 110f;
public const string Usage =
"Usage: /rc sense [compact on|off | collapse on|off | view full|compact|collapsed | addselected | import [file]] (alone: opens or closes the Sense panel)";
"Usage: /rc sense [compact on|off | collapse on|off | view full|compact|collapsed | addselected [contains] | import [file]] (alone: opens or closes the Sense panel)";
/// <summary>"/rc sense addselected" (or "add selected"): the selected object's name onto the list.</summary>
public static bool IsAddSelected(string args)
public static bool IsAddSelected(string args) => IsAddSelected(args, out _);
/// <summary>
/// "/rc sense addselected [exact|contains]": the selected object's name onto the list, as an exact
/// term (the default since 2026-11-26) or, with "contains", one any name containing it matches.
/// </summary>
public static bool IsAddSelected(string args, out bool exact)
{
exact = true;
string a = string.Join(' ', (args ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant();
return a is "addselected" or "add selected" or "addsel";
foreach (string head in new[] { "add selected", "addselected", "addsel" })
{
if (a == head) return true;
if (!a.StartsWith(head + " ", StringComparison.Ordinal)) continue;
switch (a[(head.Length + 1)..])
{
case "exact": return true;
case "contains": case "contain": case "part": exact = false; return true;
default: return false;
}
}
return false;
}
/// <summary>"/rc sense import [file]": Virindi Sense's list (or the file given). <paramref name="file"/> is empty for the usual place.</summary>

View file

@ -74,6 +74,9 @@ internal sealed class RynthAiSettings
public int AutoVendorTries { get; set; } = 4;
public int AutoVendorTriesTime { get; set; } = 5000;
public bool LosDebugLog { get; set; }
// RynthAi's Show Line of Sight (2026-11-26, a testing aid, off by default). Null until RynthAi sends it;
// a save sends null back, which RynthAi leaves alone (an older RynthAi: the row is hidden).
public bool? ShowLosLine { get; set; }
public float CrossbowArcVelocity { get; set; } = 40f;
public float AtlatlArcVelocity { get; set; } = 22f;
// Arc spells' horizontal speed: ACE flies every player arc at 40 m/s across the ground.
@ -866,6 +869,22 @@ internal static class SettingsSchema
private static SettingRow Button(string label, string buttonText, Action click, string? tip = null) =>
new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click);
// "Use AC's bags" (Interface > Hide The Game's Own, Inventory > AC's Own Bags): the same as /rc inv ac.
// A refusal goes to chat (the Settings window has no line for a button's answer).
private const string UseAcBagsTip =
"Close RynthCore's Inventory window and open the game's own inventory, as AC's backpack button or key does.\n" +
"RynthCore never hides AC's bags; its Inventory window is an extra one (the RynthCore bar, or /rc inv).\n" +
"With Hide retail toolbar on, the game's backpack button and its buy / split number box are hidden too.\n" +
"Also: /rc inv ac, or right-click the Inventory window's title.";
private static void UseAcBagsClick()
{
var (ok, message) = ImGuiBackend.Panels.InventoryFace.UseAcBags();
if (!ok)
Compatibility.AcMainThreadQueue.EnqueueWriteToChat(Compatibility.ChatCommandReplies.ReplyPrefix + message,
Compatibility.ChatCommandReplies.FailChatType);
}
// A button that runs a RynthAi chat command as if typed (it answers in chat), through RynthAi's
// "sendchat" remote command: a one-shot action that has no setting of its own.
private static SettingRow ChatButton(string label, string buttonText, string command, string? tip = null) =>
@ -887,6 +906,26 @@ internal static class SettingsSchema
private static SettingRow Status(Func<RynthAiSettings, string> get) =>
new(SettingKind.Status, "", GetText: get, VisibleWhen: s => !string.IsNullOrEmpty(get(s)));
// Settings > Spell Combat > Attack Spell Shapes: the Default monster rule's shapes. They ignore the
// settings object (the rules come from UiSources.MonsterRules and go back through DamageCommands).
private static SettingRow[] DefaultShapeRows()
{
var rows = new SettingRow[DefaultSpellShapes.Rows.Length];
for (int i = 0; i < rows.Length; i++)
{
var (field, label, tip) = DefaultSpellShapes.Rows[i];
rows[i] = Bool(label, _ => DefaultSpellShapes.Get(field), (_, v) => DefaultSpellShapes.Edit(field, v),
tip + "\n\n" + DefaultSpellShapes.SectionTip, when: _ => DefaultSpellShapes.Loaded);
}
return rows;
}
// Settings > Navigation > Navmesh View: one of RynthNav's navmesh switches (UI/Data/NavmeshView.cs).
// Shown while RynthNav sends its mesh state; a click sends /rnav mesh ..., never a RynthAi setting.
private static SettingRow NavmeshSwitch(string label, string tip) =>
Bool(label, _ => NavmeshView.GetSwitchNow(label), (_, v) => NavmeshView.SetSwitch(label, v),
tip + NavmeshView.SameAsGoTab, when: _ => NavmeshView.AvailableNow);
private static SettingRow[] Tiers(Func<RynthAiSettings, int>[] get, Action<RynthAiSettings, int>[] set)
{
var rows = new SettingRow[get.Length];
@ -1036,7 +1075,11 @@ internal static class SettingsSchema
// Stored by the engine (RetailToolbarHooks, retail_ui.txt beside the vitals), not in the profile.
Bool("Hide retail toolbar", _ => Compatibility.RetailToolbarHooks.HideRetailToolbar,
(_, v) => Compatibility.RetailToolbarHooks.HideRetailToolbar = v,
"Hide the game's toolbar panel: the combat button, the panel buttons, the selection's health, examine, the backpack and the shortcut slots.\nThe shortcut keys keep working while it's hidden. Saved for this PC. Also: /rc ui retailtoolbar on|off."),
"Hide the game's toolbar panel: the combat button, the panel buttons, the selection's health, examine, the backpack and the shortcut slots,\n" +
"and the number box where you type how many to buy from a vendor or split off a stack (RynthDefective's Selection window has its own).\n" +
"The shortcut keys keep working while it's hidden. Saved for this PC. Also: /rc ui retailtoolbar on|off."),
// 2026-11-26: RynthCore's Inventory window never hides AC's; this is the way back to the game's own.
Button("AC's own bags", "Use AC's bags", UseAcBagsClick, UseAcBagsTip),
Spacer(),
Section("Your Vitals"),
Bool("Show Target Stamina / Mana", s => s.ShowTargetStaminaMana, (s, v) => s.ShowTargetStaminaMana = v,
@ -1101,6 +1144,11 @@ internal static class SettingsSchema
ConfirmButton("Reset This Character's Layout", "Reset...", () => PanelLayout.ResetConfirmText(), () => PanelLayout.ResetFromSettings(),
"Put this character's panel layout back to the default for new characters: open panels move to the default's places.\nAsks first. Also: /rc layout reset confirm.")
with { VisibleWhen = _ => Plugins.EngineSettings.PanelLayoutPerCharacter && PanelLayout.CanResetFromSettings },
// Pop-outs are their own windows on the desktop: lost behind another window or far from
// the game window, this lines them up on it again (2026-11-24 report). /rc layout here.
Button("Bring Windows Back", "Bring here", () => ImGuiBackend.ImGuiPopOuts.RequestGather(static (text, ok) =>
Compatibility.AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, ok ? 1 : 0x1A)),
"Move every popped-out window (panels, the popped-out bar) onto the game window, lined up from its\ntop-left corner, and save them there. For windows you lost off the game window or behind another one.\nAlso: /rc layout here."),
Button("Save Layout Now", "Save", () => AcWindowChrome.SaveLayoutNow(),
"Write the open panels, the game window position (when Remember Game Window Position is on),\nthe Vision HUD and the ImGui window positions to disk now."),
}, "RynthCore · this PC"),
@ -1431,6 +1479,12 @@ internal static class SettingsSchema
Spacer(HasWeaponSwaps),
Section("Line Of Sight"),
Bool("Enable Raycasting", s => s.EnableRaycasting, (s, v) => s.EnableRaycasting = v),
Bool("Show Line of Sight", s => s.ShowLosLine ?? false, (s, v) => s.ShowLosLine = v,
"A line from you to the combat target: green when RynthAi's line-of-sight raycast says clear,\n" +
"red when it says blocked, with a yellow marker where the raycast hit. Dashed green: clear without\n" +
"a geometry test (raycasting off or warming up, or no geometry near the path). Thin dim lines go\n" +
"to the other monsters in range. A testing aid; off by default. /ra losline [on|off].",
when: s => s.ShowLosLine.HasValue),
Bool("Use Arcs for Missile LoS", s => s.UseArcs, (s, v) => s.UseArcs = v,
"A missile target must pass both the straight line and the real arrow arc, ceilings included (dungeons too).\nWhen off, all missile LoS checks are linear (eye-to-eye).", gates: true),
Float("Bow", s => s.BowArcVelocity, (s, v) => s.BowArcVelocity = v, 10f, 60f, 0.5f,
@ -1504,6 +1558,18 @@ internal static class SettingsSchema
}),
new("Spell Combat", Concat(
// The DEFAULT monster line's shapes (2026-11-26: "cast streaks instead of bolts" was only on
// the Damage panel's DEFAULT line). UI/Data/DefaultSpellShapes.cs; shown once RynthAi has
// sent its monster rules.
Section(DefaultSpellShapes.SectionLabel, _ => DefaultSpellShapes.Loaded),
Note("For every monster without its own entry. Each monster in Monsters can still have its own.",
_ => DefaultSpellShapes.Loaded),
DefaultShapeRows(),
Status(_ => DefaultSpellShapes.Loaded ? DefaultSpellShapes.SummaryNow() : string.Empty),
Button(DefaultSpellShapes.OpenMonstersLabel, "Open Monsters",
() => ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.DamageFace.Title), DefaultSpellShapes.OpenMonstersTip)
with { VisibleWhen = _ => DefaultSpellShapes.Loaded },
Spacer(_ => DefaultSpellShapes.Loaded),
Section("Casting"),
Int("Attack Spell Delay (ms)", s => s.AttackSpellIntervalMs, (s, v) => s.AttackSpellIntervalMs = v, 0, 5000, 50,
"Least time between offensive (war/void) COMBAT casts at one target.\nThe next cast also waits until the last one is finished (the server's\nanswer and the casting animation), so 0 = cast again as soon as it is.\nDoes NOT affect buffing speed."),
@ -1577,6 +1643,22 @@ internal static class SettingsSchema
Bool("Guide Line", s => s.NavGuideLine, (s, v) => s.NavGuideLine = v,
"A line from your character to the waypoint nav is heading for."),
Spacer(),
// RynthNav's navmesh drawing (UI/Data/NavmeshView.cs): RynthNav's own settings, read from its
// status and sent as /rnav mesh commands; the RynthAi settings object is ignored.
Section(NavmeshView.SectionLabel),
Note(NavmeshView.Unavailable(null), _ => NavmeshView.Status == null),
Note(NavmeshView.Unavailable(new RynthNavStatus()), _ => NavmeshView.Status is { HasMesh: false }),
NavmeshSwitch(NavmeshView.ShowLabel, NavmeshView.ShowTip),
NavmeshSwitch(NavmeshView.FloorLabel, NavmeshView.FloorTip),
NavmeshSwitch(NavmeshView.WallsLabel, NavmeshView.WallsTip),
Int(NavmeshView.RadiusLabel, _ => NavmeshView.RadiusNow, (_, v) => NavmeshView.SetRadius(v),
NavmeshView.RadiusMin, NavmeshView.RadiusMax, NavmeshView.RadiusStep,
NavmeshView.RadiusTip + NavmeshView.SameAsGoTab, when: _ => NavmeshView.AvailableNow),
Int(NavmeshView.DetailLabel, _ => NavmeshView.DetailNow, (_, v) => NavmeshView.SetDetail(v),
NavmeshView.DetailMin, NavmeshView.DetailMax, NavmeshView.DetailStep,
NavmeshView.DetailTip + NavmeshView.SameAsGoTab, when: _ => NavmeshView.AvailableNow),
Status(_ => NavmeshView.Drawn(NavmeshView.Status)),
Spacer(),
Section("Doors"),
Bool("Open Doors While Navigating", s => s.OpenDoors, (s, v) => s.OpenDoors = v,
"Automatically open doors encountered during navigation.", gates: true),
@ -1800,6 +1882,9 @@ internal static class SettingsSchema
// New 2026-11-11: what happens to items once they are in your packs (from Looting, Misc and Display).
new("Inventory", new[]
{
Section("AC's Own Bags"),
Button("AC's own bags", "Use AC's bags", UseAcBagsClick, UseAcBagsTip),
Spacer(),
Section("Packs"),
Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v),
Bool("Enable Autocram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v,

View file

@ -1172,12 +1172,7 @@ internal sealed unsafe class LayeredWindow : IDisposable
var info = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() };
if (monitor == IntPtr.Zero || !GetMonitorInfoW(monitor, ref info)) return false;
RECT work = info.rcWork;
int x = Math.Clamp(left, work.Left, Math.Max(work.Left, work.Right - width));
int y = Math.Clamp(top, work.Top, Math.Max(work.Top, work.Bottom - height));
if (x == left && y == top) return false;
left = x;
top = y;
return true;
return PopOutPlacement.ClampInside(ref left, ref top, width, height, new ScreenRect(work.Left, work.Top, work.Right, work.Bottom));
}
/// <summary>The work area of the monitor nearest a rectangle (screen px). Any thread.</summary>

View file

@ -64,7 +64,7 @@ internal readonly record struct LayoutFiles(string PanelState, string ImGuiIni)
}
/// <summary>What /rc layout asks for.</summary>
internal enum LayoutCommand { Invalid, Status, MakeDefault, ResetAsk, ResetConfirm }
internal enum LayoutCommand { Invalid, Status, MakeDefault, ResetAsk, ResetConfirm, BringHere }
/// <summary>The kinds of windows the engine hosts (ImGuiPanelHost): its own panels, plugins' manifest windows, script windows.</summary>
internal enum WindowKind { EnginePanel, PluginWindow, ScriptWindow }
@ -211,7 +211,7 @@ internal static class PanelLayoutPolicy
// ── /rc layout ───────────────────────────────────────────────────────
public const string Usage = "Usage: /rc layout [status] | default | reset [confirm]";
public const string Usage = "Usage: /rc layout [status] | default | reset [confirm] | here";
/// <summary>"/rc layout" and its arguments (any case, any spacing).</summary>
public static LayoutCommand ParseCommand(string? args)
@ -223,6 +223,8 @@ internal static class PanelLayoutPolicy
"default" => LayoutCommand.MakeDefault,
"reset" => LayoutCommand.ResetAsk,
"reset confirm" => LayoutCommand.ResetConfirm,
// Every popped-out window back onto the game window (Settings > Interface "Bring Windows Back").
"here" => LayoutCommand.BringHere,
_ => LayoutCommand.Invalid,
};
}

View file

@ -0,0 +1,125 @@
// ============================================================================
// RynthCore.Engine - UI/PopOutPlacement.cs
// Where a popped-out window opens and where "bring the windows back" puts it.
// Pure (no Win32, no ImGui): ImGuiPopOuts and LayeredWindow feed it the game
// window's client rectangle and the monitor's work area; tools/PanelLayoutTests
// checks it.
//
// A pop-out's spot is saved in screen pixels (panel_state.txt). Saved alone, it
// stays where it was on the desktop when the game window doesn't: a client the
// launcher opens somewhere else, another client using the same layout, a game
// window dragged since. Players then lost them "outside the window" at launch
// and moved the game window around to find them (2026-11-24 report). So each
// saved spot carries the game window's client rectangle at that moment (a
// panel_state value, AnchorKey(title)): a pop-out that was over the game window
// then opens at the same place on it now; one put away from it (another monitor)
// keeps its screen spot. Either way it then comes onto the nearest monitor's
// work area: wholly when it fits, else its top-left corner, so the title bar is
// there to drag.
// ============================================================================
using System;
using System.Globalization;
namespace RynthCore.Engine.UI;
/// <summary>A rectangle in screen pixels: left/top inclusive, right/bottom exclusive.</summary>
internal readonly record struct ScreenRect(int Left, int Top, int Right, int Bottom)
{
public int Width => Right - Left;
public int Height => Bottom - Top;
public bool IsEmpty => Right <= Left || Bottom <= Top;
public static ScreenRect FromSize(int left, int top, int width, int height) => new(left, top, left + width, top + height);
public bool Intersects(ScreenRect o) => !IsEmpty && !o.IsEmpty && Left < o.Right && o.Left < Right && Top < o.Bottom && o.Top < Bottom;
}
internal static class PopOutPlacement
{
/// <summary>The panel_state value that holds a pop-out's game window rectangle: "popout.anchor.&lt;title&gt;".</summary>
public const string AnchorKeyPrefix = "popout.anchor.";
/// <summary>Cascade step between windows "bring the windows back" lines up (unscaled px).</summary>
public const int GatherStep = 30;
/// <summary>Where the first gathered window goes, from the game window's top-left (unscaled px).</summary>
public const int GatherInset = 40;
public static string AnchorKey(string title) => AnchorKeyPrefix + title;
/// <summary>"left,top,width,height" of the game window's client area on the screen.</summary>
public static string FormatAnchor(ScreenRect client) =>
string.Create(CultureInfo.InvariantCulture, $"{client.Left},{client.Top},{client.Width},{client.Height}");
/// <summary>Reads <see cref="FormatAnchor"/>'s text; false for anything else (or an empty rectangle).</summary>
public static bool TryParseAnchor(string? text, out ScreenRect client)
{
client = default;
if (string.IsNullOrWhiteSpace(text)) return false;
string[] p = text.Split(',');
if (p.Length != 4) return false;
var v = new int[4];
for (int i = 0; i < 4; i++)
if (!int.TryParse(p[i].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out v[i])) return false;
if (v[2] <= 0 || v[3] <= 0) return false;
client = ScreenRect.FromSize(v[0], v[1], v[2], v[3]);
return true;
}
/// <summary>
/// A saved pop-out spot for the game window as it is now: when the pop-out was over the game
/// window when it was saved (<paramref name="savedClient"/>), it moves as far as the game
/// window has moved since (<paramref name="clientNow"/>); otherwise, or when either rectangle
/// isn't known, the spot stays. True when it moved.
/// </summary>
public static bool FollowGameWindow(ref int left, ref int top, int width, int height, ScreenRect? savedClient, ScreenRect? clientNow)
{
if (savedClient is not { IsEmpty: false } was || clientNow is not { IsEmpty: false } now) return false;
if (!ScreenRect.FromSize(left, top, Math.Max(1, width), Math.Max(1, height)).Intersects(was)) return false;
int dx = now.Left - was.Left, dy = now.Top - was.Top;
if (dx == 0 && dy == 0) return false;
left += dx;
top += dy;
return true;
}
/// <summary>
/// Pulls a window inside <paramref name="work"/> (a monitor's work area): wholly when it fits,
/// else its top-left corner, so its title bar is on the screen. True when it had to move.
/// </summary>
public static bool ClampInside(ref int left, ref int top, int width, int height, ScreenRect work)
{
if (work.IsEmpty) return false;
int x = Math.Clamp(left, work.Left, Math.Max(work.Left, work.Right - width));
int y = Math.Clamp(top, work.Top, Math.Max(work.Top, work.Bottom - height));
if (x == left && y == top) return false;
left = x;
top = y;
return true;
}
/// <summary>"Bring the windows back"'s answer: <paramref name="count"/> open pop-outs, <paramref name="moved"/> of them moved.</summary>
public static string GatherReply(int count, int moved) => count <= 0
? "No popped-out windows are open. Docked panels always stay inside the game window."
: $"Brought {count} popped-out window{(count == 1 ? "" : "s")} onto the game window"
+ (moved < count ? $" ({count - moved} already there)." : ".");
/// <summary>
/// "Bring the windows back": where the <paramref name="index"/>th open pop-out goes on the game
/// window, a cascade from its top-left, starting over at the top when the next step would put
/// the window's corner past the client's middle. Kept inside the client when it fits.
/// </summary>
public static (int Left, int Top) GatherSpot(int index, int width, int height, ScreenRect client, float scale = 1f)
{
scale = float.IsFinite(scale) && scale > 0.25f ? scale : 1f;
int step = Math.Max(8, (int)(GatherStep * scale)), inset = Math.Max(0, (int)(GatherInset * scale));
int room = Math.Max(1, Math.Min(client.Width, client.Height) / 2 - inset);
int perColumn = Math.Max(1, room / step + 1);
int row = Math.Max(0, index) % perColumn, column = Math.Max(0, index) / perColumn;
int left = client.Left + inset + row * step + column * step * 2;
int top = client.Top + inset + row * step;
ClampInside(ref left, ref top, width, height, client);
return (left, top);
}
}

View file

@ -209,6 +209,8 @@ public struct RynthCoreApiNative
public IntPtr WebPanelNavigateFn; // int WebPanelNavigate(int handle, byte* url) -> 1 queued; -2 off-list; -6 stale
public IntPtr WebPanelCloseFn; // int WebPanelClose(int handle) -> 1 queued, 0 already closed, -6 stale
public IntPtr WebPanelGetStateFn; // int WebPanelGetState(int handle, WebPanelStateNative*) -> Status (non-live handle -> 6 Superseded), -1 bad args
// v99: AC's camera keys
public IntPtr CameraActionFn; // int CameraAction(int action, int pressed) -> 1 queued, 0 not available, -1 bad action
}
/// <summary>

View file

@ -1917,6 +1917,23 @@ public readonly unsafe struct RynthCoreHost
return true;
}
// ── v99: AC's camera ─────────────────────────────────────────────────────
/// <summary>v99: <see cref="CameraAction"/>. True only on an engine at API 99 or newer that fills it.</summary>
public bool HasCameraAction => _api.Version >= 99 && _api.CameraActionFn != IntPtr.Zero;
/// <summary>
/// v99: presses (<paramref name="pressed"/> true) or lets go of AC's own camera key for
/// <paramref name="action"/>, on AC's game thread before its tick. The turns, raise, lower, closer and
/// farther go on while pressed, as the keys do, until let go; Home (the default view behind the character)
/// and FirstPerson act on the press. True when queued. Any thread.
/// </summary>
public bool CameraAction(RynthCameraAction action, bool pressed)
{
if (!HasCameraAction) return false;
return ((delegate* unmanaged[Cdecl]<int, int, int>)_api.CameraActionFn)((int)action, pressed ? 1 : 0) == 1;
}
// ── v94: a web panel over the game window (number provisional) ───────────
/// <summary>

View file

@ -61,6 +61,25 @@ public enum RynthPanelPopOut
}
/// <summary>What RynthCoreHost.ShortcutAction does to an AC shortcut slot (v90).</summary>
/// <summary>v99: AC's camera keys (<see cref="RynthCoreHost.CameraAction"/>).</summary>
public enum RynthCameraAction
{
/// <summary>The default view, behind the character (on the press).</summary>
Home = 0,
RotateLeft = 1,
RotateRight = 2,
/// <summary>The camera swings up.</summary>
Raise = 3,
/// <summary>The camera swings down.</summary>
Lower = 4,
/// <summary>Zoom in.</summary>
Closer = 5,
/// <summary>Zoom out.</summary>
Farther = 6,
/// <summary>First person (on the press); Home goes back.</summary>
FirstPerson = 7,
}
public enum RynthShortcutOp
{
Use = 0, Set = 1, Clear = 2,

View file

@ -36,7 +36,7 @@
<PropertyGroup>
<!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. -->
<RynthCoreSdkApiVersion>98</RynthCoreSdkApiVersion>
<RynthCoreSdkApiVersion>99</RynthCoreSdkApiVersion>
<!-- The first engine API that loads managed plugins and gives them Runtime\PluginShared (2026.10.19.1). -->
<RynthCoreManagedPluginApi>88</RynthCoreManagedPluginApi>
<_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn>

View file

@ -23,6 +23,7 @@ internal static class Program
PortalSpaceViewIsTheWorld();
FailOpen();
NothingUnderTheMouse();
GameDragsGoThroughUnderUiPanels();
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
@ -120,6 +121,26 @@ internal static class Program
Console.WriteLine($"-- {name}");
}
private static void GameDragsGoThroughUnderUiPanels()
{
// Problem report R-20261126-194457-f7d8: a panel drawn under AC's UI (the DreamWeave Skills
// window) sat behind AC's inventory. While the button was down it stopped being click-through,
// so every item dragged inside AC's inventory was "released over an ImGui window" and snapped back.
Case("under-UI panel behind an AC window: click-through unless its own press is held");
Check(AcMouseOverRules.UnderUiPanelClickThrough(AcMouseTarget.AcWindow, leftDown: false, pressBelongsToGame: false),
"AC window, no button: click-through");
Check(AcMouseOverRules.UnderUiPanelClickThrough(AcMouseTarget.AcWindow, leftDown: true, pressBelongsToGame: true),
"AC window, a game press held (an AC inventory drag): click-through, the drop is AC's");
Check(!AcMouseOverRules.UnderUiPanelClickThrough(AcMouseTarget.AcWindow, leftDown: true, pressBelongsToGame: false),
"AC window, the panel's own press held: the panel keeps its drag");
Case("under-UI panel over the world (or AC can't tell): the panel takes the mouse");
foreach (AcMouseTarget t in new[] { AcMouseTarget.World, AcMouseTarget.Nothing, AcMouseTarget.Unknown })
foreach (bool down in new[] { false, true })
Check(!AcMouseOverRules.UnderUiPanelClickThrough(t, down, pressBelongsToGame: down),
$"{t}, leftDown={down}: not click-through");
}
private static void Check(bool ok, string what)
{
_checks++;

View file

@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the RynthNav Arrow window's one target (src\RynthCore.Engine\UI\Data\
ArrowTarget.cs, compiled in): where the target came from (chat coords, a route, the arrow),
its label, and whether the route list under the arrow belongs to it.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>ArrowTargetTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ArrowTarget.cs" Link="Engine\ArrowTarget.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,113 @@
using RynthCore.Engine.UI.Data;
namespace ArrowTargetTests;
/// <summary>
/// The RynthNav Arrow window's one target (ArrowTarget). 11-24, a player: clicked chat coordinates
/// went to the top of the window while the route list under them was for another place.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private const double HoltNs = 42.08, HoltEw = 33.60, FarNs = -12.3, FarEw = 45.6;
private static int Main()
{
Sources();
RouteBelongs();
ChatNote();
Labels();
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks})");
return _failed == 0 && _checks > 0 ? 0 : 1;
}
private static ArrowTargetInput Arrow(string final, double ns, double ew, int steps = 1) =>
new(true, final, ns, ew, steps, false, "", false, 0, 0, false, 0, 0);
private static ArrowTargetInput WithRoute(ArrowTargetInput a, string routeFor, double ns, double ew, bool goal = true) =>
a with { HasRoute = true, RouteFor = routeFor, RouteHasGoal = goal, RouteNs = goal ? ns : 0, RouteEw = goal ? ew : 0,
RouteHasLast = true, LastNs = ns, LastEw = ew };
private static readonly ArrowTargetInput Nothing = new(false, "", 0, 0, 0, false, "", false, 0, 0, false, 0, 0);
private static void Sources()
{
Check(ArrowTarget.Pick(Nothing, chat: false).Source == ArrowTargetSource.None, "nothing: no target");
Check(ArrowTarget.Pick(Arrow("Holtburg", HoltNs, HoltEw), chat: false).Source == ArrowTargetSource.Arrow, "a place: Arrow");
Check(ArrowTarget.Pick(Arrow("42.1N, 33.6E", 42.1, 33.6), chat: true).Source == ArrowTargetSource.Chat, "a chat link: Chat coords");
Check(ArrowTarget.Pick(Arrow("Holtburg", HoltNs, HoltEw, steps: 3), chat: false).Source == ArrowTargetSource.Route,
"an arrow along a route's portals: Route");
// A route to the arrow's own place makes it a route, even from chat ("Route here").
var routed = WithRoute(Arrow("42.1N, 33.6E", 42.1, 33.6), "42.1N, 33.6E", 42.1, 33.6);
Check(ArrowTarget.Pick(routed, chat: true).Source == ArrowTargetSource.Route, "chat coords, then Plan: Route");
// No arrow, a route shown (an older RynthNav after arrow off, or a trip): the route is the target.
var onlyRoute = WithRoute(Nothing, "Rithwic", 10, 59);
Check(ArrowTarget.Pick(onlyRoute, chat: false).Source == ArrowTargetSource.Route, "only a route: Route");
}
private static void RouteBelongs()
{
// The report: chat coords far away, the route list still for Holtburg.
var stale = WithRoute(Arrow("12.3S, 45.6E", FarNs, FarEw), "Holtburg", HoltNs, HoltEw);
ArrowTargetPick p = ArrowTarget.Pick(stale, chat: true);
Check(!p.RouteBelongs, "a route for another place stays out of the window");
Check(p.Source == ArrowTargetSource.Chat, "...and the target is the chat coords");
var same = WithRoute(Arrow("Holtburg", HoltNs, HoltEw), "Holtburg", HoltNs, HoltEw);
Check(ArrowTarget.RouteBelongs(same), "a route to the arrow's place belongs");
// Two places with one name: RynthNav's goal decides.
var namesake = WithRoute(Arrow("Lifestone", HoltNs, HoltEw), "Lifestone", FarNs, FarEw);
Check(!ArrowTarget.RouteBelongs(namesake), "same name, another place: not this target's route");
// An older RynthNav (no goal sent): the name, else the route's last step.
var byName = WithRoute(Arrow("Holtburg", HoltNs, HoltEw), "holtburg", FarNs, FarEw, goal: false);
Check(ArrowTarget.RouteBelongs(byName), "older RynthNav: the same name (any case) belongs");
var byLast = WithRoute(Arrow("42.1N, 33.6E", 42.1, 33.6), "Holtburg Lifestone", HoltNs, HoltEw, goal: false);
Check(ArrowTarget.RouteBelongs(byLast), "older RynthNav: a route ending at the arrow's spot belongs");
var neither = WithRoute(Arrow("Rithwic", 10, 59), "Holtburg", HoltNs, HoltEw, goal: false);
Check(!ArrowTarget.RouteBelongs(neither), "older RynthNav: another name ending elsewhere doesn't");
Check(!ArrowTarget.RouteBelongs(Arrow("Holtburg", HoltNs, HoltEw)), "no route: nothing belongs");
Check(ArrowTarget.SamePlace(42.1, 33.6, HoltNs, HoltEw), "chat coords' one decimal is the same place");
Check(!ArrowTarget.SamePlace(42.2, 33.6, HoltNs, HoltEw), "0.12 degrees off is not");
Check(!ArrowTarget.SamePlace(double.NaN, 33.6, HoltNs, HoltEw), "an unknown spot is never the same place");
}
private static void ChatNote()
{
ArrowTarget.ForgetChat();
Check(!ArrowTarget.FromChat(42.1, 33.6), "nothing noted: not from chat");
int v = ArrowTarget.ChatVersion;
ArrowTarget.NoteChat(42.1, 33.6);
Check(ArrowTarget.ChatVersion != v, "a note bumps the version (the window rebuilds its line)");
// RynthNav gets the coordinates with two decimals and sends them back as numbers.
Check(ArrowTarget.FromChat(42.10, 33.60), "the arrow at the noted spot came from chat");
Check(!ArrowTarget.FromChat(HoltNs, HoltEw), "Holtburg's own spot (0.02 off) did not: the Atlas set it");
ArrowTarget.NoteChat(-12.3, 45.6);
Check(!ArrowTarget.FromChat(42.1, 33.6), "a newer chat link replaces the note");
ArrowTarget.ForgetChat();
Check(!ArrowTarget.FromChat(-12.3, 45.6), "cleared: not from chat any more");
}
private static void Labels()
{
Check(ArrowTarget.Pick(Arrow("42.1N, 33.6E", 42.1, 33.6), chat: true).Label == "Chat coords 42.1N, 33.6E", "chat label");
Check(ArrowTarget.Pick(Arrow("12.3S, 45.6W", -12.3, -45.6), chat: true).Label == "Chat coords 12.3S, 45.6W", "south and west");
Check(ArrowTarget.Pick(Arrow("Holtburg", HoltNs, HoltEw, steps: 2), chat: false).Label == "Route: Holtburg", "route label");
Check(ArrowTarget.Pick(Arrow("Holtburg", HoltNs, HoltEw), chat: false).Label == "Arrow: Holtburg", "arrow label");
Check(ArrowTarget.Pick(Arrow("", HoltNs, HoltEw), chat: false).Label == "Arrow: 42.1N, 33.6E", "no name: the coordinates");
Check(ArrowTarget.Pick(WithRoute(Nothing, "Rithwic", 10, 59), chat: false).Label == "Route: Rithwic", "a route alone");
Check(ArrowTarget.Pick(Nothing, chat: false).Label == "No target", "nothing");
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine(" [FAIL] " + what);
}
}

View file

@ -214,6 +214,13 @@ internal static class Program
Check(ChatCommandReplies.Check("window save").Problem!.StartsWith("Unknown command '/rc window'", StringComparison.Ordinal),
"'/rc window save' (sent by /ub window save) is not an engine verb, and now says so");
Check(ChatCommandReplies.Check(" SKILLS Show ").Problem == null, "case and spaces as IsVerb takes them");
// /rc inv [ac] (2026-11-26): alone toggles RynthCore's Inventory; ac / retail / game open AC's own bags.
foreach (string ok in new[] { "inv", "inventory", "inv ac", "INV AC", "inventory retail", "inv game" })
Check(ChatCommandReplies.Check(ok).Problem == null, $"'/rc {ok}' runs");
ChatVerbCheck badInv = ChatCommandReplies.Check("inv bags");
Check(badInv.Problem != null && badInv.Problem.Contains("/rc inventory ac", StringComparison.Ordinal),
$"'/rc inv bags' answers with the usage, which names /rc inventory ac: {badInv.Problem}");
}
private static void ModuleLinesClassified()

View file

@ -5,7 +5,9 @@
src\RynthCore.Engine\Compatibility\TellMemory.cs - who to reply / retell to, read off the
chat lines, and the rewrite of "/r text" into "/tell Name, text";
src\RynthCore.Engine\UI\Data\ChatInputPaste.cs - clipboard text made into one input line;
src\RynthCore.Engine\Compatibility\ChatLineRoute.cs - which lines are AC emotes, not speech.
src\RynthCore.Engine\Compatibility\ChatLineRoute.cs - which lines are AC emotes, not speech;
src\RynthCore.Engine\Compatibility\ChatSlashEmote.cs - "/wave" as AC's "*Wave*";
src\RynthCore.Engine\UI\Data\ChatTextSelection.cs - the chat's selected text and item lines as one.
Nothing native: no AC, no engine state.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
@ -22,6 +24,8 @@
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\TellMemory.cs" Link="Engine\TellMemory.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatInputPaste.cs" Link="Engine\ChatInputPaste.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ChatLineRoute.cs" Link="Engine\ChatLineRoute.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ChatSlashEmote.cs" Link="Engine\ChatSlashEmote.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatTextSelection.cs" Link="Engine\ChatTextSelection.cs" />
</ItemGroup>
</Project>

View file

@ -25,6 +25,10 @@ internal static class Program
PasteClean();
PasteInsert();
EmoteLines();
MeAndAtCommands();
SlashEmotes();
SelectionText();
ItemInfoOneLine();
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
@ -196,6 +200,176 @@ internal static class Program
Check(!ChatLineRoute.IsAcEmoteLine(""), "empty");
}
// ── /me and @commands (ChatLineRoute.cs, 2026-11-26) ────────────────────
private static void MeAndAtCommands()
{
Case("/me is AC's @emote");
Check(ChatLineRoute.IsMeEmote("/me looks menacingly at the mob", out string t) && t == "looks menacingly at the mob", "/me text");
Check(ChatLineRoute.IsMeEmote("/ME waves ", out t) && t == "waves", "any case, trimmed");
Check(ChatLineRoute.IsMeEmote("/me", out t) && t.Length == 0, "/me alone");
Check(!ChatLineRoute.IsMeEmote("/meet you there", out _), "/meet is not /me");
Check(!ChatLineRoute.IsMeEmote("/menu", out _), "/menu is not /me");
Check(!ChatLineRoute.IsMeEmote("me too", out _), "plain words");
Check(!ChatLineRoute.IsMeEmote("", out _), "empty");
Case("@commands go to AC's parser");
Check(ChatLineRoute.IsAtCommand("@loc"), "@loc (a client command)");
Check(ChatLineRoute.IsAtCommand("@friends add Someone"), "@friends with arguments");
Check(ChatLineRoute.IsAtCommand("@myquests"), "@myquests (a server command: AC passes it on)");
Check(!ChatLineRoute.IsAtCommand("@"), "a lone @");
Check(!ChatLineRoute.IsAtCommand("@ everyone"), "@ then a space: speech");
Check(!ChatLineRoute.IsAtCommand("@@"), "@@");
Check(!ChatLineRoute.IsAtCommand("/loc"), "a / command is not an @ one (it takes the / path)");
Check(!ChatLineRoute.IsAtCommand("hello @Bob"), "an @ inside a line");
}
// ── /wave as *Wave* (ChatSlashEmote.cs, 2026-11-26) ─────────────────────
private static void SlashEmotes()
{
Case("/emote word is AC's *Emote*");
Check(ChatSlashEmote.TryMatch("/wave", out string a) && a == "*Wave*", "/wave");
Check(ChatSlashEmote.TryMatch("/WAVE", out a) && a == "*Wave*", "any case");
Check(ChatSlashEmote.TryMatch("/ymca", out a) && a == "*YMCA*", "/ymca, AC's capitals");
Check(ChatSlashEmote.TryMatch("/BeSeeingYou", out a) && a == "*BeSeeingYou*", "/BeSeeingYou");
Check(ChatSlashEmote.TryMatch("/wavehigh", out a) && a == "*WaveHigh*", "/wavehigh is WaveHigh, not Wave");
Check(ChatSlashEmote.TryMatch("/teapot", out a) && a == "*Teapot*", "/teapot");
int all = 0;
foreach (string name in ChatSlashEmote.Names)
if (ChatSlashEmote.TryMatch("/" + name.Replace(" ", ""), out a) && a == "*" + name + "*"
&& ChatLineRoute.IsAcEmoteLine(a))
all++;
Check(all == ChatSlashEmote.Names.Length && all == 41, $"every one of AC's 41 emotes, as an asterisk line AC's parser path takes ({all})");
Case("two-word emotes, run together or apart");
Check(ChatSlashEmote.TryMatch("/warmhands", out a) && a == "*Warm Hands*", "/warmhands");
Check(ChatSlashEmote.TryMatch("/warm hands", out a) && a == "*Warm Hands*", "/warm hands");
Check(ChatSlashEmote.TryMatch("/Warm Hands", out a) && a == "*Warm Hands*", "/Warm Hands, two spaces");
Check(ChatSlashEmote.TryMatch("/scratch head", out a) && a == "*Scratch Head*", "/scratch head");
Check(ChatSlashEmote.TryMatch("/SHAKEHEAD", out a) && a == "*Shake Head*", "/SHAKEHEAD");
Check(!ChatSlashEmote.TryMatch("/warm", out _), "/warm alone");
Check(!ChatSlashEmote.TryMatch("/shake", out _), "/shake alone");
Check(!ChatSlashEmote.TryMatch("/wave high", out _), "/wave high: WaveHigh is one word, so text after /wave");
Case("anything else is left as it is");
Check(!ChatSlashEmote.TryMatch("/wave hello", out a) && a.Length == 0, "/wave hello: text after the emote");
Check(!ChatSlashEmote.TryMatch("/warm hands now", out _), "/warm hands now");
Check(!ChatSlashEmote.TryMatch("/waves", out _), "/waves");
Check(!ChatSlashEmote.TryMatch("/wav", out _), "/wav");
Check(!ChatSlashEmote.TryMatch("/ wave", out _), "/ wave");
Check(!ChatSlashEmote.TryMatch("wave", out _), "no slash: speech");
Check(!ChatSlashEmote.TryMatch("*wave*", out _), "*wave* takes its own route");
Check(!ChatSlashEmote.TryMatch("@wave", out _), "@wave");
Check(!ChatSlashEmote.TryMatch("/", out _) && !ChatSlashEmote.TryMatch("", out _) && !ChatSlashEmote.TryMatch(null, out _), "/, empty, null");
Case("claimed commands win");
// AC's own client command words (its command table in acclient.exe, 2026-11-26): AC's
// parser runs them, so none may be an emote word.
string[] acCommands =
[
"abandon", "boot_all", "ma", "alleg_recall", "mansion_recall", "re", "recall", "rt", "clist", "index",
"log", "unfilter", "filter", "text", "lockui", "loadautoui", "saveautoui", "loadui", "saveui", "version",
"render", "pkl", "pklite", "loc", "framerate", "endurance", "day", "birth", "age", "status", "msg_types",
"msgtypes", "message_types", "messagetypes", "unsquelch", "squelch", "hoa", "hom", "hr", "hor", "hslist",
"hou", "friends_remove", "friends_add", "friends", "loadfile", "fillcomps", "emotes", "me", "emote", "em",
"e", "pla", "pklarena", "pka", "pkarena", "permit", "mp", "mar", "marketplace", "ls", "lif", "lifestone",
"die", "cor", "corpse", "consent", "death", "afk", "whisper", "send", "t", "tell", "say", "retell", "pr",
"mr", "rp", "notell", "chatting", "leave", "join", "vassal", "vassals", "patron", "monarch", "party", "g",
"group", "fellow", "fellows", "fellowship", "covassal", "covassals", "co-vassals", "channels", "speaker",
"ah", "alh", "ab", "allegiance", "allegiances", "commands", "help", "house", "lock", "motd", "ho",
"hometown", "title", "officer", "ban", "br", "broadcast", "ch", "chat", "info", "boot", "who", "olthoi",
"soc", "society", "crp", "roleplay", "clfg", "lfg", "ct", "trade", "cg", "general", "gu", "guild",
// and the routes and commands the dispatcher hands out before the emote
"a", "f", "r", "reply", "s", "rc", "ra", "vt", "ub", "mt", "lua", "rl",
];
int stolen = 0;
foreach (string cmd in acCommands)
if (ChatSlashEmote.TryMatch("/" + cmd, out _)) { stolen++; Console.WriteLine($" an emote name is a command: /{cmd}"); }
Check(stolen == 0, "no AC, engine or plugin command word is an emote");
Check(!ChatSlashEmote.TryMatch("/rc ui", out _) && !ChatSlashEmote.TryMatch("/ra start", out _), "/rc and /ra lines");
Check(!ChatSlashEmote.TryMatch("/e waves", out _) && !ChatSlashEmote.TryMatch("/a hi", out _)
&& !ChatSlashEmote.TryMatch("/f hi", out _) && !ChatSlashEmote.TryMatch("/r hi", out _), "/e /a /f /r lines");
Check(TellMemory.Parse("/wave", out _) == TellShortcut.None, "the /r rewrite (asked before the emote) leaves /wave alone");
}
// ── text selection (ChatTextSelection.cs) ───────────────────────────────
private static void SelectionText()
{
Case("ends in reading order");
int al = 5, ac = 3, bl = 2, bc = 9;
ChatTextSelection.Order(ref al, ref ac, ref bl, ref bc);
Check(al == 2 && ac == 9 && bl == 5 && bc == 3, "later line first: swapped");
al = 4; ac = 8; bl = 4; bc = 2;
ChatTextSelection.Order(ref al, ref ac, ref bl, ref bc);
Check(al == 4 && ac == 2 && bl == 4 && bc == 8, "same line, backwards drag: swapped");
al = 1; ac = 0; bl = 3; bc = 0;
ChatTextSelection.Order(ref al, ref ac, ref bl, ref bc);
Check(al == 1 && bl == 3, "already in order: kept");
Case("the part of a line that is copied");
const string line = "Bob says, \"meet at 42.1N, 33.6E\"";
Check(ChatTextSelection.Part(line, "12:01:33", 0, line.Length) == "12:01:33 " + line, "whole line keeps its timestamp");
Check(ChatTextSelection.Part(line, null, 0, line.Length) == line, "timestamps off: just the text");
Check(ChatTextSelection.Part(line, "12:01:33", 19, 31) == "42.1N, 33.6E", "the middle: no timestamp");
Check(ChatTextSelection.Part(line, "12:01:33", 0, 3) == "12:01:33 Bob", "from the start: timestamp too");
Check(ChatTextSelection.Part(line, null, 31, 19) == "42.1N, 33.6E", "ends the wrong way round");
Check(ChatTextSelection.Part(line, null, -4, 999) == line, "out of range: clamped");
Check(ChatTextSelection.Part("", "12:00:00", 0, 0) == "12:00:00 ", "an empty line");
Case("surrogate pairs are never split");
string smile = "a\U0001F600b"; // a, high, low, b
Check(ChatTextSelection.Clamp(smile, 2) == 1, "between the halves: to the pair's start");
Check(ChatTextSelection.Clamp(smile, 3) == 3, "after the pair: kept");
Check(ChatTextSelection.Part(smile, null, 0, 2) == "a", "a cut inside the pair drops the half");
Case("the character under the mouse");
Func<int, float> w = _ => 10f; // every character 10 wide
Check(ChatTextSelection.CharAtX("hello", 0, 5, -3f, w) == 0, "left of the row: its start");
Check(ChatTextSelection.CharAtX("hello", 0, 5, 4f, w) == 0, "left half of the first character");
Check(ChatTextSelection.CharAtX("hello", 0, 5, 6f, w) == 1, "right half: after it");
Check(ChatTextSelection.CharAtX("hello", 0, 5, 26f, w) == 3, "26 px: between l and l");
Check(ChatTextSelection.CharAtX("hello", 0, 5, 500f, w) == 5, "right of the row: its end");
Check(ChatTextSelection.CharAtX("hello world", 6, 11, 12f, w) == 7, "a later row starts at its own start");
Check(ChatTextSelection.CharAtX(smile, 0, smile.Length, 16f, w) == 3, "a pair is one character");
}
// ── an item's info lines as one (ChatTextSelection.cs) ──────────────────
private static void ItemInfoOneLine()
{
const string P = ChatTextSelection.ItemPrefix;
var lines = new List<string>
{
"You say, \"look at this\"",
P + "Ornate Long Sword, Gold, Craft 6, Value 4,200",
P + " Slash, 80-120, +5% Melee D",
P + " Damage Rating 3 Wield 300",
P + " Spells: Blood Drinker VI, Swift Killer VI",
P + "Pearl of Blood Drinking, Rare",
"Bob says, \"nice\"",
};
Case("which lines are one item's");
Check(ChatTextSelection.ItemRun(lines, 1, out int f, out int l) && f == 1 && l == 4, "from its name line: the 3 lines under it");
Check(ChatTextSelection.ItemRun(lines, 3, out f, out l) && f == 1 && l == 4, "from a line under it: back to its name");
Check(ChatTextSelection.ItemRun(lines, 5, out f, out l) && f == 5 && l == 5, "the next item: its own line only");
Check(!ChatTextSelection.ItemRun(lines, 0, out _, out _), "a say line is no item");
Check(!ChatTextSelection.ItemRun(lines, 99, out _, out _), "out of range");
Check(ChatTextSelection.IsItemDetail(lines[2]) && !ChatTextSelection.IsItemDetail(lines[1]), "detail = indented under the name");
Case("joined into one line");
ChatTextSelection.ItemRun(lines, 2, out f, out l);
Check(ChatTextSelection.ItemOneLine(lines, f, l)
== "Ornate Long Sword, Gold, Craft 6, Value 4,200, Slash, 80-120, +5% Melee D, Damage Rating 3, Wield 300, Spells: Blood Drinker VI, Swift Killer VI",
"tags gone, lines and two-space gaps joined with commas");
Check(ChatTextSelection.ItemOneLine(lines, 5, 5) == "Pearl of Blood Drinking, Rare", "one line: just without its tag");
var orphan = new List<string> { P + " Slash, 80-120", P + " Wield 300" };
Check(ChatTextSelection.ItemRun(orphan, 1, out f, out l) && f == 0 && l == 1, "name line scrolled away: the lines that are there");
}
private static void Case(string name)
{
_case = name;

View file

@ -35,6 +35,7 @@ namespace CombatSettingsTests
("KiteTagFirst", typeof(bool?), "true"),
("MeleeThroughWalls", typeof(bool?), "true"), // Combat > Targeting > Melee through walls (2026-11-15)
("DebuffAllBeforeAttacking", typeof(bool?), "false"), // Combat > Targeting > Debuff every monster in range before attacking (2026-11-22)
("ShowLosLine", typeof(bool?), "false"), // Combat > Line Of Sight > Show Line of Sight (2026-11-26)
};
private static int Main()
@ -103,11 +104,12 @@ namespace CombatSettingsTests
("Combat", "Magic Response", "Combo", 0, 0, 3), // beside Missile Response since 2026-11-11
("Combat", "Melee through walls", "Bool", 1, 0, 1), // on by default (2026-11-15)
("Combat", "Debuff every monster in range before attacking", "Bool", 0, 0, 1), // off by default (2026-11-22)
("Combat", "Show Line of Sight", "Bool", 0, 0, 1), // off by default (2026-11-26)
};
object older = Parse("{\"BoostNavPriority\":true}"); // what an older RynthAi sends
object newer = Parse("{\"VariablePowerMin\":50,\"VariablePowerMax\":100,\"MissileEnvironmentResponse\":0,\"MagicEnvironmentResponse\":0," +
"\"EnvironmentImpactLimit\":2,\"EnvironmentImpactWindowSec\":20,\"EnvironmentApproachMeters\":6,\"EnvironmentMinDistance\":3," +
"\"EnvironmentSkipSec\":30,\"KitePullMeters\":20,\"KiteTagFirst\":true,\"MeleeThroughWalls\":true,\"DebuffAllBeforeAttacking\":false}"); // the plugin's own defaults
"\"EnvironmentSkipSec\":30,\"KitePullMeters\":20,\"KiteTagFirst\":true,\"MeleeThroughWalls\":true,\"DebuffAllBeforeAttacking\":false,\"ShowLosLine\":false}"); // the plugin's own defaults
foreach (var (tab, label, kind, def, min, max) in rows)
{
object? row = Row(tab, label, kind);
@ -147,9 +149,12 @@ namespace CombatSettingsTests
Set(Row("Combat", "Magic Response", "Combo")!, edit, 1);
Set(Row("Combat", "Melee through walls", "Bool")!, edit, 0);
Set(Row("Combat", "Debuff every monster in range before attacking", "Bool")!, edit, 1);
Set(Row("Combat", "Show Line of Sight", "Bool")!, edit, 1);
string after = JsonSerializer.Serialize(edit, info);
Check(after.Contains("\"MeleeThroughWalls\":false"), "Melee through walls unticked saves false (RynthAi turns it off)");
Check(after.Contains("\"DebuffAllBeforeAttacking\":true"), "Debuff every monster ticked saves true (RynthAi turns it on)");
Check(after.Contains("\"ShowLosLine\":true"), "Show Line of Sight ticked saves true (RynthAi turns it on)");
Check(JsonSerializer.Serialize(Parse("{\"BoostNavPriority\":true}"), info).Contains("\"ShowLosLine\":null"), "an older RynthAi's Show Line of Sight is sent back absent (unchanged)");
Check(after.Contains("\"KitePullMeters\":55") && after.Contains("\"KiteTagFirst\":true") && after.Contains("\"MagicEnvironmentResponse\":1"), "the edits land on their own properties");
Check(after.Contains("\"BoostNavPriority\":true") && after.Contains("\"EnvironmentSkipSec\":60") && after.Contains("\"MissileEnvironmentResponse\":2"), "the other settings ride along unchanged");
@ -208,9 +213,91 @@ namespace CombatSettingsTests
foreach (string f in voidFields)
Check(ruleJson.Contains($"\"{f}\":true"), $"the panel sends \"{f}\":true");
// ── Settings > Spell Combat > Attack Spell Shapes (2026-11-26) ─────────────
DefaultShapes(engine, tabs, rule, Lst);
return Finish();
}
// The DEFAULT monster line's shapes as Settings rows (UI/Data/DefaultSpellShapes.cs): "use streaks
// instead of bolts" where the attack-spell settings are, and the monsters that keep their own.
private static void DefaultShapes(Assembly engine, Dictionary<string, List<object>> tabs, Type rule, Func<object[], IList> lst)
{
Type shapes = engine.GetType(Ns + "DefaultSpellShapes", throwOnError: true)!;
var defs = ((string Field, string Label, string Tip)[])shapes.GetField("Rows", All)!.GetValue(null)!;
static string Label(object r) => (string?)r.GetType().GetProperty("Label")!.GetValue(r) ?? "";
static string Kind(object r) => r.GetType().GetProperty("Kind")!.GetValue(r)!.ToString()!;
// The rows: the streak one first, every shape once, on Spell Combat, before Casting.
Check(defs.Length == 6 && defs[0].Field == "UseStreak" && defs[0].Label == "Use streaks instead of bolts", "the first row is Use streaks instead of bolts");
Check(defs.Select(d => d.Field).OrderBy(f => f).SequenceEqual(new[] { "UseArc", "UseBlast", "UseBolt", "UseRing", "UseStreak", "UseWall" }),
"every shape of a monster rule has a row (arc, blast, bolt, ring, streak, wall)");
List<object> spell = tabs["Spell Combat"];
int section = spell.FindIndex(r => Label(r) == (string)shapes.GetField("SectionLabel", All)!.GetValue(null)! && Kind(r) == "Section");
int casting = spell.FindIndex(r => Label(r) == "Casting" && Kind(r) == "Section");
Check(section == 0 && casting > section, "Attack Spell Shapes is the first section of Spell Combat, above Casting");
foreach (var d in defs)
{
object? row = spell.FirstOrDefault(r => Label(r) == d.Label && Kind(r) == "Bool");
Check(row != null, $"Spell Combat has the Bool row '{d.Label}'");
Check((bool)shapes.GetMethod("IsShapeLabel", All)!.Invoke(null, new object?[] { d.Label })!, $"'{d.Label}' is known as a shape row (the My settings drawer polls the rules for it)");
Check(d.Tip.Length > 20, $"'{d.Label}' has a tooltip");
}
Check(!(bool)shapes.GetMethod("IsShapeLabel", All)!.Invoke(null, new object?[] { "Min Ring Targets" })!, "other rows aren't shape rows");
Check(spell.Any(r => Label(r) == (string)shapes.GetField("OpenMonstersLabel", All)!.GetValue(null)! && Kind(r) == "Button"), "a button opens the per-monster place");
object Rule(string name, bool arc = false, bool bolt = true, bool ring = false, bool streak = false, bool blast = false, bool wall = false)
{
object r = Activator.CreateInstance(rule, nonPublic: true)!;
rule.GetProperty("Name")!.SetValue(r, name);
rule.GetProperty("UseArc")!.SetValue(r, arc);
rule.GetProperty("UseBolt")!.SetValue(r, bolt);
rule.GetProperty("UseRing")!.SetValue(r, ring);
rule.GetProperty("UseStreak")!.SetValue(r, streak);
rule.GetProperty("UseBlast")!.SetValue(r, blast);
rule.GetProperty("UseWall")!.SetValue(r, wall);
return r;
}
bool Flag(object r, string f) => (bool)rule.GetProperty(f)!.GetValue(r)!;
void Set(object r, string f, bool on) => shapes.GetMethod("Set", All)!.Invoke(null, new object[] { r, f, on });
string Casts(object r) => (string)shapes.GetMethod("Casts", All)!.Invoke(null, new[] { r })!;
string Summary(params object[] rules) => (string)shapes.GetMethod("Summary", All)!.Invoke(null, new object?[] { lst(rules) })!;
// Setting a shape.
object def = Rule("Default");
Set(def, "UseStreak", true);
Check(Flag(def, "UseStreak") && Flag(def, "UseBolt") && Casts(def) == "Streak", "Use streaks on: streaks are cast instead of bolts");
Set(def, "UseArc", true);
Check(Casts(def) == "Arc", "arcs come first (RynthAi's order: Arc, Streak, Blast, Bolt)");
Set(def, "UseArc", false);
Set(def, "UseRing", true);
Check(Casts(def) == "Streak, Ring when enough are near", "a ring is told as the override it is: " + Casts(def));
object only = Rule("Default", bolt: false, streak: true);
Set(only, "UseStreak", false);
Check(Flag(only, "UseBolt") && !Flag(only, "UseStreak"), "turning the last shape off turns bolts back on (never no shape: RynthAi wouldn't cast)");
object blastBolt = Rule("Default", blast: true);
Check(Casts(blastBolt) == "Blast", "a blast wins over the bolt");
Set(blastBolt, "Fester", true);
Check(!Flag(blastBolt, "Fester"), "Set only touches shapes");
// The line under the rows: what the Default line casts, and the monsters with their own entry.
object d1 = Rule("Default", streak: true);
string none = Summary(d1);
Check(none == "Every monster casts Streak.", "no monster has its own entry: " + none);
string three = Summary(d1, Rule("Drudge"), Rule("Mite Squire", arc: true), Rule("Tusker", bolt: false, streak: true, ring: true), Rule("Olthoi", streak: true));
Check(three.StartsWith("Monsters without their own entry cast Streak. 3 monsters have their own setting: Drudge, Mite Squire, Tusker.", StringComparison.Ordinal),
"three monsters with other shapes are counted and named: " + three);
Check(three.Contains(" 1 more has its own entry, set the same for now.", StringComparison.Ordinal), "one set the same is counted apart: " + three);
Check(three.EndsWith("Those keep their own shapes: change one in Monsters (click its name).", StringComparison.Ordinal), "and says where to change them: " + three);
string many = Summary(d1, Rule("A"), Rule("B"), Rule("C"), Rule("D"), Rule("E"));
Check(many.Contains("5 monsters have their own setting: A, B, C (+2 more).", StringComparison.Ordinal), "past three names: +N more: " + many);
string same = Summary(d1, Rule("Drudge", streak: true));
Check(same.Contains("1 monster has its own entry, set the same for now. It keeps its own shapes", StringComparison.Ordinal), "one the same, singular: " + same);
Check(Summary(Rule("Drudge")) == "", "no Default rule: no line (the rows are hidden)");
object lower = Rule("default", streak: true);
Check(Summary(lower, Rule("Drudge", streak: true)).StartsWith("Monsters without", StringComparison.Ordinal), "Default is found in any case");
}
private static int Finish()
{
Console.WriteLine(_fails == 0 ? $"All {_asserts} checks passed." : $"{_fails} of {_asserts} checks FAILED.");

View file

@ -46,6 +46,7 @@
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\WorldTransitionState.cs" Link="Engine\WorldTransitionState.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AddressSpace.cs" Link="Engine\AddressSpace.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ActionRing.cs" Link="Engine\ActionRing.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\GestureDeferRule.cs" Link="Engine\GestureDeferRule.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\CastStopRules.cs" Link="Engine\CastStopRules.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\MutatorGate.cs" Link="Engine\MutatorGate.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ReleasedObjectRetention.cs" Link="Engine\ReleasedObjectRetention.cs" />

View file

@ -11,6 +11,8 @@ internal static partial class Program
private static void RunRingAndGateTests()
{
RingTakesAStopWhenFullOfStarts();
GestureDeferWaitsForAPlayingMotion();
GestureDeferStopsWaitingOnAStuckMotion();
RingRefusesStartsDuringATransition();
RingStopRunsFirstAfterTheWindow();
CastStopFindsAnOutOfOrderStop();
@ -43,6 +45,43 @@ internal static partial class Program
private readonly record struct Act(string What, long At, bool Teardown);
// ---- the gesture defer (GestureDeferRule, R-20261123-152528-b02d) --------------------
private static void GestureDeferWaitsForAPlayingMotion()
{
_case = "gesture defer";
var r = new GestureDeferRule(2_500);
Check(!r.Defer(0, 1_000, out _), "an empty motion list: nothing waits");
Check(r.Defer(0x100, 1_000, out _), "a motion in flight: the ring waits");
Check(r.Defer(0x100, 3_400, out _), "2.4 s on it: still waiting");
// Swing after swing: a new motion at the head each time keeps the waits, capped as before.
Check(r.Defer(0x200, 3_450, out bool w1) && !w1, "the next swing: still waiting, not stuck");
Check(!r.Defer(0x300, 3_502, out bool w2) && !w2, "the wait is 2.5 s at most: then the ring runs (not stuck)");
Check(r.Defer(0x400, 3_503, out _), "and a new wait starts");
r.RingEmptied();
Check(r.Defer(0x500, 7_000, out _), "after the ring emptied, a full wait again");
}
private static void GestureDeferStopsWaitingOnAStuckMotion()
{
_case = "gesture defer stuck";
var r = new GestureDeferRule(2_500);
Check(r.Defer(0x100, 10_000, out _), "a motion at the head: the ring waits");
Check(r.Defer(0x100, 12_400, out bool w1) && !w1, "2.4 s on the same motion: still waiting");
Check(!r.Defer(0x100, 12_501, out bool w2) && w2 && r.Wedged, "the same motion there past 2.5 s: taken as stuck (logged once), the ring runs");
int waits = 0;
bool again = false;
for (long t = 12_600; t < 20_000; t += 33)
{
if (r.Defer(0x100, t, out bool w)) waits++;
again |= w;
}
Check(waits == 0 && !again, $"while it stays stuck the ring never waits on it (was a 2.5 s wait each time; {waits} waits)");
Check(r.Defer(0x200, 20_000, out _) && !r.Wedged, "a new motion at the head: waited on again");
Check(!r.Defer(0, 20_100, out _) && !r.Wedged, "an empty list clears it");
Check(r.Defer(0x200, 20_200, out _), "the same pointer coming back after an empty read is a new motion");
}
private static void RingTakesAStopWhenFullOfStarts()
{
_case = "ring reserve";

View file

@ -70,6 +70,7 @@ namespace EngineSettingsTests
Run(nameof(PlacementSaveNeedsAStableInWorldRect), PlacementSaveNeedsAStableInWorldRect);
Run(nameof(AcWindowChromeNeverResizes), AcWindowChromeNeverResizes);
Run(nameof(PlacementSizeIsAcsResolution), PlacementSizeIsAcsResolution);
Run(nameof(BorderlessFullScreenFillsMonitor), BorderlessFullScreenFillsMonitor);
Run(nameof(SavedSizeIgnoredLine), SavedSizeIgnoredLine);
Run(nameof(PlacementFilesArePerClient), PlacementFilesArePerClient);
Run(nameof(PlacementFileRoundTrips), PlacementFileRoundTrips);
@ -956,11 +957,14 @@ namespace EngineSettingsTests
bool keepsSize = call.Contains("SwpNosize");
bool forResolution = call.Contains("d.Width, d.Height");
bool keepsClient = call.Contains("outerW, outerH");
bool fillsMonitor = call.Contains("fill.Width, fill.Height"); // borderless full screen (2026-11-26)
if (!keepsSize) sized++;
Check(keepsSize || forResolution || keepsClient, "SetWindowPos keeps AC's size or sizes it for AC's resolution: " + call);
Check(keepsSize || forResolution || keepsClient || fillsMonitor, "SetWindowPos keeps AC's size or sizes it for AC's resolution: " + call);
Check(!Regex.IsMatch(call, @"\b(saved|sv|from|_saved|_reference|rf)\b"), "SetWindowPos never uses a saved rect: " + call);
}
Eq(sized, 2, "two calls size the window (the restore for AC's resolution, the borderless style change)");
Eq(sized, 3, "three calls size the window (the restore for AC's resolution, the borderless style change, borderless full screen)");
// The full screen rect is the monitor's, from BorderlessFill: never a saved rect.
Check(Regex.IsMatch(source, @"BorderlessFill(Needed)?\(outer, client, DrawSize\(\), monitor\)"), "the full screen rect comes from the monitor");
// The restore plan's size is AC's resolution plus the frame, never the saved size.
string policy = File.ReadAllText(FindUp(Path.Combine("src", "RynthCore.Engine", "UI", "AcWindowChromePolicy.cs")));
Check(policy.Contains("OuterForDrawSize(d, current, client)"), "the resize target comes from the back buffer's size");
@ -1047,6 +1051,54 @@ namespace EngineSettingsTests
Eq(SaveRefusedForSize(new Size(1600, 899), Draw1600), "its client area 1600x899 is not AC's resolution 1600x900", "one pixel off is still stretched");
}
// ── 2026-11-26: borderless full screen fills its monitor ────────────
// Discord 11-26: since 2026.11.23.1 a 1920x1080 game made borderless kept its picture at (3,26),
// under where the caption had been: a gap at the top and the taskbar showing.
private static readonly Rect Monitor1080 = new(0, 0, 1920, 1080);
private static readonly Rect Monitor2Right = new(1920, 0, 1920 + 2560, 1440); // a second monitor
private static readonly Size Draw1080 = new(1920, 1080);
private static void BorderlessFullScreenFillsMonitor()
{
// The report: AC at the monitor's resolution, its framed window at (0,0) (client at (3,26)).
var framed = new Rect(0, 0, 1926, 1109);
Eq(BorderlessFill(framed, Draw1080, Draw1080, Monitor1080), Monitor1080, "1920x1080 game on a 1920x1080 monitor: fills the monitor, taskbar included");
// The 11.23 result itself (borderless at the client's old spot) is put back on the monitor.
var gap = new Rect(3, 26, 3 + 1920, 26 + 1080);
Eq(BorderlessFillNeeded(gap, Draw1080, Draw1080, Monitor1080), Monitor1080, "borderless with the caption-high gap: moved back onto the monitor");
Eq(BorderlessFillNeeded(Monitor1080, Draw1080, Draw1080, Monitor1080), (Rect?)null, "already exactly on the monitor: nothing to do");
// Centred by AC, framed window hanging off every edge: still the monitor it is on.
Eq(BorderlessFill(new Rect(-3, -14, 1923, 1095), new Size(1920, 1080), Draw1080, Monitor1080), Monitor1080, "centred framed window: fills");
// Windows clamped the framed window, so the client is smaller than the game: the game's size decides.
Eq(BorderlessFill(new Rect(0, 0, 1926, 1092), new Size(1920, 1063), Draw1080, Monitor1080), Monitor1080, "clamped framed window: fills");
// Back buffer not read yet: the client area decides, and so does a window covering the monitor.
Eq(BorderlessFill(framed, Draw1080, null, Monitor1080), Monitor1080, "resolution unknown, client at the monitor's size: fills");
Eq(BorderlessFill(new Rect(-8, -31, 1928, 1088), new Size(1920, 1050), null, Monitor1080), Monitor1080, "resolution unknown, framed window covers the monitor: fills");
// An older borderless window a few pixels bigger than the monitor (the strip kept the outer rect): snapped exactly.
Eq(BorderlessFillNeeded(new Rect(0, 0, 1926, 1109), new Size(1926, 1109), Draw1080, Monitor1080), Monitor1080, "a borderless window past the monitor's edges: snapped onto it");
// A game bigger than the monitor: fills (the best a borderless window can do).
Eq(BorderlessFill(new Rect(0, 0, 1926, 1109), new Size(1920, 1080), new Size(2560, 1440), Monitor1080), Monitor1080, "game above the monitor's size: fills");
// The monitor the window is on, not the primary one.
var onSecond = new Rect(1920, 0, 1920 + 2566, 1469);
Eq(BorderlessFill(onSecond, new Size(2560, 1440), new Size(2560, 1440), Monitor2Right), Monitor2Right, "second monitor: fills that monitor");
// Normal borderless windowed (2026-11-21) is unchanged: a smaller game keeps its client area.
Eq(BorderlessFill(At1600, Client1600, Draw1600, Monitor1080), (Rect?)null, "1600x900 on 1920x1080: no fill, the client area stays");
Eq(BorderlessFillNeeded(new Rect(203, 129, 1803, 1029), Client1600, Draw1600, Monitor1080), (Rect?)null, "1600x900 borderless: never moved or resized");
Eq(BorderlessFill(new Rect(0, 0, 1926, 1109), Draw1080, Draw1080, new Rect(0, 0, 1920, 1200)), (Rect?)null, "1920x1080 on a 1920x1200 monitor: not full screen, no stretch");
Eq(BorderlessFill(new Rect(0, 0, 1926, 1109), new Size(1920, 1080), new Size(1920, 1080), new Rect(0, 0, 2560, 1440)), (Rect?)null, "1920x1080 on 2560x1440: no fill");
Eq(BorderlessFill(new Rect(0, 0, 1926, 1109), Draw1080, Draw1080, new Rect(0, 0, 0, 0)), (Rect?)null, "no monitor information: no fill");
// One dimension at the monitor's size is not full screen.
Eq(BorderlessFill(new Rect(0, 0, 1926, 909), new Size(1920, 880), new Size(1920, 880), Monitor1080), (Rect?)null, "full width, short: no fill");
// Once filled, the window is what LooksExclusiveFullscreen calls full screen, so the strip is not
// repeated and the restore / save stand down (the existing guards).
Eq(DecideBorderless(true, 0x00CF0000, 0x00CF0000 & ~BorderChromeMask, true).Action, ChromeAction.None, "filled and ours: no further strip");
Eq(DecideRestore(Saved1940, false, true, Monitor1080, Draw1080, Draw1080, S(30), S(30), Screen2560).Resize, false, "filled: the restore never resizes it");
}
// The launcher's shared line for the ignored size (AcWindowPlacementRule.SavedSizeIgnored).
private static void SavedSizeIgnoredLine()
{

View file

@ -27,6 +27,8 @@
<Compile Include="..\..\src\RynthCore.Engine\UI\BarLayout.cs" Link="Engine\BarLayout.cs" />
<!-- Where a docked window draws versus its home (the saved spot): 2026-11-12, panels moving on reload/login. -->
<Compile Include="..\..\src\RynthCore.Engine\UI\PanelPlacement.cs" Link="Engine\PanelPlacement.cs" />
<!-- Pop-outs follow the game window and stay on the screen; "bring windows back" (2026-11-24 report). -->
<Compile Include="..\..\src\RynthCore.Engine\UI\PopOutPlacement.cs" Link="Engine\PopOutPlacement.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettingsFile.cs" Link="Engine\EngineSettingsFile.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ChatCommandReplies.cs" Link="Engine\ChatCommandReplies.cs" />
<!-- ChatCommandReplies' /rc sense row names SenseLayout (the Sense views, feature/sense-compact). -->

View file

@ -69,6 +69,8 @@ namespace PanelLayoutTests
Run(PulledOnScreenNeverMovesTheSavedSpot);
Run(TheBarKeepsItsHome);
Run(HomeSurvivesAReloadThroughTheStore);
Run(PopOutsFollowTheGameWindowAndStayOnScreen);
Run(BringWindowsBack);
}
finally
{
@ -913,16 +915,17 @@ namespace PanelLayoutTests
Eq(PanelLayoutPolicy.ParseCommand("default"), LayoutCommand.MakeDefault, "default");
Eq(PanelLayoutPolicy.ParseCommand("reset"), LayoutCommand.ResetAsk, "reset alone asks");
Eq(PanelLayoutPolicy.ParseCommand("reset Confirm"), LayoutCommand.ResetConfirm, "reset confirm, any spacing and case");
Eq(PanelLayoutPolicy.ParseCommand(" HERE "), LayoutCommand.BringHere, "here: bring the popped-out windows back");
foreach (string bad in new[] { "frob", "default now", "reset now", "confirm", "reset confirm please" })
Eq(PanelLayoutPolicy.ParseCommand(bad), LayoutCommand.Invalid, $"'{bad}' is not a form");
Case("/rc layout: the check before it runs (ChatCommandReplies)");
foreach (string ok in new[] { "layout", "layout status", "layout default", "layout reset", "layout reset confirm", "LAYOUT Reset confirm" })
foreach (string ok in new[] { "layout", "layout status", "layout default", "layout reset", "layout reset confirm", "LAYOUT Reset confirm", "layout here" })
{
ChatVerbCheck c = ChatCommandReplies.Check(ok);
Check(c.Problem == null && c.Verb?.Name == "layout", $"'/rc {ok}' runs");
}
foreach (string bad in new[] { "layout frob", "layout default now", "layout reset please" })
foreach (string bad in new[] { "layout frob", "layout default now", "layout reset please", "layout here now" })
{
ChatVerbCheck c = ChatCommandReplies.Check(bad);
Check(c.Verb?.Name == "layout" && c.Problem == PanelLayoutPolicy.Usage, $"'/rc {bad}' answers with the usage");
@ -1007,6 +1010,99 @@ namespace PanelLayoutTests
Eq(PanelLayoutPolicy.ParseCommand("reset confirm"), LayoutCommand.ResetConfirm, "the button's command is reset confirm");
}
// ── pop-outs: following the game window, on the screen (2026-11-24 report) ──
private static void PopOutsFollowTheGameWindowAndStayOnScreen()
{
Case("pop-outs: the anchor text");
var client = ScreenRect.FromSize(100, 50, 1600, 900);
string text = PopOutPlacement.FormatAnchor(client);
Eq(text, "100,50,1600,900", "left,top,width,height");
Check(PopOutPlacement.TryParseAnchor(text, out ScreenRect back) && back == client, "reads back");
Check(PopOutPlacement.TryParseAnchor(" -1920 , 0 , 1920 , 1080 ", out ScreenRect left) && left == ScreenRect.FromSize(-1920, 0, 1920, 1080),
"a monitor left of the main one, any spacing");
foreach (string bad in new[] { "", " ", "1,2,3", "1,2,3,4,5", "a,b,c,d", "1,2,0,5", "1,2,5,-3" })
Check(!PopOutPlacement.TryParseAnchor(bad, out _), $"'{bad}' isn't an anchor");
Eq(PopOutPlacement.AnchorKey("RynthChat"), "popout.anchor.RynthChat", "the panel_state value's key");
Case("pop-outs: a saved spot over the game window moves with it");
var was = ScreenRect.FromSize(0, 0, 1600, 900);
var now = ScreenRect.FromSize(1920, 100, 1600, 900); // the launcher opened it on the second monitor
int l = 1200, t = 600;
Check(PopOutPlacement.FollowGameWindow(ref l, ref t, 300, 200, was, now), "it moves");
Eq((l, t), (3120, 700), "the same place on the game window");
l = 1500; t = 850; // only its corner was over the game window: still "on it"
Check(PopOutPlacement.FollowGameWindow(ref l, ref t, 300, 200, was, now) && (l, t) == (3420, 950), "a pop-out half over the edge follows too");
Case("pop-outs: a spot away from the game window stays where the player put it");
l = 2000; t = 100; // on the second monitor, beside the game window
Check(!PopOutPlacement.FollowGameWindow(ref l, ref t, 300, 200, was, now) && (l, t) == (2000, 100), "not over the game window: kept");
l = 1600; t = 0; // touching the right edge (right is exclusive): not over it
Check(!PopOutPlacement.FollowGameWindow(ref l, ref t, 300, 200, was, now) && (l, t) == (1600, 0), "touching the edge isn't over it");
Case("pop-outs: nothing known, nothing moved");
l = 1200; t = 600;
Check(!PopOutPlacement.FollowGameWindow(ref l, ref t, 300, 200, null, now), "no anchor saved (a spot from an older engine)");
Check(!PopOutPlacement.FollowGameWindow(ref l, ref t, 300, 200, was, null), "no game window now (minimized)");
Check(!PopOutPlacement.FollowGameWindow(ref l, ref t, 300, 200, was, was), "the game window didn't move");
Check(!PopOutPlacement.FollowGameWindow(ref l, ref t, 300, 200, default(ScreenRect), now), "an empty anchor");
Eq((l, t), (1200, 600), "...and the spot is as saved");
Case("pop-outs: onto the monitor's work area");
var work = new ScreenRect(0, 0, 1920, 1040); // a 1080p monitor above a 40 px taskbar
l = 100; t = 100;
Check(!PopOutPlacement.ClampInside(ref l, ref t, 400, 300, work) && (l, t) == (100, 100), "already on it: unchanged");
l = 1800; t = 950;
Check(PopOutPlacement.ClampInside(ref l, ref t, 400, 300, work) && (l, t) == (1520, 740), "hanging off the bottom-right: wholly on it");
l = -5000; t = -3000;
Check(PopOutPlacement.ClampInside(ref l, ref t, 400, 300, work) && (l, t) == (0, 0), "far off (a monitor since unplugged): its corner");
l = 3000; t = 2000;
Check(PopOutPlacement.ClampInside(ref l, ref t, 2400, 1200, work) && (l, t) == (0, 0),
"bigger than the screen: the top-left corner, so the title bar is there to drag");
l = 10; t = 10;
Check(!PopOutPlacement.ClampInside(ref l, ref t, 400, 300, default), "no work area known: unchanged");
Case("pop-outs: followed off the screen, then pulled back on");
var wide = ScreenRect.FromSize(0, 0, 3840, 1080);
var moved = ScreenRect.FromSize(-1700, 0, 1600, 900); // the game window now on a monitor left of it
l = 200; t = 200;
PopOutPlacement.FollowGameWindow(ref l, ref t, 400, 300, wide, moved);
Eq((l, t), (-1500, 200), "it followed to the left monitor");
var leftWork = new ScreenRect(-1920, 0, 0, 1040);
Check(!PopOutPlacement.ClampInside(ref l, ref t, 400, 300, leftWork), "and that monitor has it whole");
}
private static void BringWindowsBack()
{
Case("bring windows back: a cascade on the game window");
var client = ScreenRect.FromSize(100, 50, 1600, 900);
var first = PopOutPlacement.GatherSpot(0, 300, 200, client);
Eq(first, (100 + PopOutPlacement.GatherInset, 50 + PopOutPlacement.GatherInset), "the first one near the top-left");
var second = PopOutPlacement.GatherSpot(1, 300, 200, client);
Eq(second, (first.Left + PopOutPlacement.GatherStep, first.Top + PopOutPlacement.GatherStep), "the next one a step down and right");
var spots = new HashSet<(int, int)>();
for (int i = 0; i < 40; i++)
{
var (x, y) = PopOutPlacement.GatherSpot(i, 300, 200, client);
Check(x >= client.Left && y >= client.Top && x + 300 <= client.Right && y + 200 <= client.Bottom, $"window {i} is wholly on the game window");
spots.Add((x, y));
}
Eq(spots.Count, 40, "forty windows: forty spots (title bars don't stack)");
var scaled = PopOutPlacement.GatherSpot(1, 300, 200, client, 2f);
Eq(scaled, (100 + 2 * PopOutPlacement.GatherInset + 2 * PopOutPlacement.GatherStep, 50 + 2 * PopOutPlacement.GatherInset + 2 * PopOutPlacement.GatherStep),
"UI scale 2: twice the steps");
var tiny = ScreenRect.FromSize(0, 0, 640, 480);
var big = PopOutPlacement.GatherSpot(3, 900, 700, tiny);
Eq(big, (0, 0), "a window bigger than the game window: its corner on the game window's");
Eq(PopOutPlacement.GatherSpot(0, 300, 200, client, float.NaN), first, "a bad scale counts as 1");
Case("bring windows back: the answer");
Check(PopOutPlacement.GatherReply(0, 0).StartsWith("No popped-out windows", StringComparison.Ordinal), "none open says so");
Eq(PopOutPlacement.GatherReply(1, 1), "Brought 1 popped-out window onto the game window.", "one");
Eq(PopOutPlacement.GatherReply(3, 2), "Brought 3 popped-out windows onto the game window (1 already there).", "some already there");
Check(ChatCommandReplies.KindOfLine(PopOutPlacement.GatherReply(3, 3)) != ChatReplyKind.Fail, "a success isn't red");
}
// ── helpers ────────────────────────────────────────────────────────
private static void NoTempFiles(string dir)

View file

@ -60,6 +60,7 @@ internal static class Program
Run(nameof(TrainingStructsMirror), TrainingStructsMirror);
Run(nameof(ContainerOrderSlots), ContainerOrderSlots);
Run(nameof(WebPanelFieldsAppended), WebPanelFieldsAppended);
Run(nameof(CameraFieldAppended), CameraFieldAppended);
Run(nameof(WebPanelStructsMatch), WebPanelStructsMatch);
Run(nameof(WebPanelCodesMatch), WebPanelCodesMatch);
Run(nameof(HasWebPanel_FalseOnOldOrPartialTable), HasWebPanel_FalseOnOldOrPartialTable);
@ -608,8 +609,20 @@ internal static class Program
(int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>(prev) + IntPtr.Size, "SDK " + slot + " right after " + prev);
prev = slot;
}
Eq(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(4).Last(), "GetMonsterHealthFn", "engine table: GetMonsterHealthFn precedes the four");
Eq(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(4).Last(), "GetMonsterHealthFn", "SDK table: GetMonsterHealthFn precedes the four");
// v99's CameraActionFn follows the four (see CameraFieldAppended).
Eq(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(5).Last(), "GetMonsterHealthFn", "engine table: GetMonsterHealthFn precedes the four");
Eq(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(5).Last(), "GetMonsterHealthFn", "SDK table: GetMonsterHealthFn precedes the four");
}
// v99: CameraActionFn is appended right after v94's WebPanelGetStateFn and ends the table, on both sides.
private static void CameraFieldAppended()
{
Eq((int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("CameraActionFn"),
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("WebPanelGetStateFn") + IntPtr.Size, "engine CameraActionFn right after WebPanelGetStateFn");
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("CameraActionFn"),
(int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("WebPanelGetStateFn") + IntPtr.Size, "SDK CameraActionFn right after WebPanelGetStateFn");
Eq(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).Last(), "CameraActionFn", "engine table ends with CameraActionFn");
Eq(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).Last(), "CameraActionFn", "SDK table ends with CameraActionFn");
}
private static void StructMirror(Type engine, Type sdk, int size)
@ -758,11 +771,11 @@ internal static class Program
Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits");
Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits");
// The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v91 follow:
// eleven slots to v89, then v90's thirteen, v91's two, v93's one and v94's four).
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(31).TakeLast(6).ToArray();
// eleven slots to v89, then v90's thirteen, v91's two, v93's one, v94's four and v99's one).
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(32).TakeLast(6).ToArray();
Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }),
"v79, v80 then v81 slots last: " + string.Join(",", names));
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(31).TakeLast(6).ToArray();
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(32).TakeLast(6).ToArray();
Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order");
}
@ -773,7 +786,12 @@ internal static class Program
{
var all = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray();
var sdkAll = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray();
// v94: the web panel's four slots end the table; the checks after these are on the table before them.
// v99: CameraActionFn ends the table; the checks after it are on the table before it.
Check(all.Last() == "CameraActionFn", "v99 slot last: " + all.Last());
Check(sdkAll.Last() == "CameraActionFn", "SDK v99 slot last: " + sdkAll.Last());
all = all.SkipLast(1).ToArray();
sdkAll = sdkAll.SkipLast(1).ToArray();
// v94: the web panel's four slots come next; the checks after these are on the table before them.
string[] v94 = { "WebPanelOpenFn", "WebPanelNavigateFn", "WebPanelCloseFn", "WebPanelGetStateFn" };
Check(all.TakeLast(v94.Length).SequenceEqual(v94), "v94 slots last: " + string.Join(",", all.TakeLast(v94.Length)));
Check(sdkAll.TakeLast(v94.Length).SequenceEqual(v94), "SDK v94 slots last: " + string.Join(",", sdkAll.TakeLast(v94.Length)));

View file

@ -25,6 +25,9 @@ internal static class Program
Matching();
VirindiSenseList();
ListCommands();
ExactMatching();
ExactInTheFile();
ExactCommands();
Console.WriteLine($"{_checks} checks, {_failed} failed");
return _failed == 0 ? 0 : 1;
@ -302,4 +305,88 @@ internal static class Program
Check(!SenseLayout.IsLayoutCommand("import") && !SenseLayout.IsLayoutCommand("addselected"), "they aren't look commands");
Check(SenseLayout.Usage.Contains("addselected", StringComparison.Ordinal) && SenseLayout.Usage.Contains("import [file]", StringComparison.Ordinal), "the usage names them");
}
// ── Exact match (2026-11-26) ───────────────────────────────────────
private static void ExactMatching()
{
var drake = new SensePattern("Drake", true, exact: true);
Check(drake.Exact && !drake.IsGlob && drake.MatchKind == "exact", "an exact term says so");
Check(drake.Matches("Drake") && drake.Matches("drake") && drake.Matches("DRAKE"), "exact: the whole name, any case");
Check(!drake.Matches("Dragon's Isle Drake") && !drake.Matches("Drake Hatchling") && !drake.Matches("Drakes"), "exact: not a name that only contains it");
Check(drake.Matches(" Drake "), "exact: spaces around the name don't count");
Check(!drake.Matches("") && !new SensePattern("", true, exact: true).Matches("Drake"), "exact: empty never matches");
var literal = new SensePattern("Drake*", true, exact: true);
Check(!literal.IsGlob && literal.Matches("drake*") && !literal.Matches("Drake Hatchling"), "exact: * and ? are plain letters");
var plain = new SensePattern("Drake", true);
Check(!plain.Exact && plain.MatchKind == "contains" && plain.Matches("Dragon's Isle Drake"), "a term without Exact still contains (the old behaviour)");
Check(new SensePattern("Drake*", true).MatchKind == "wildcards", "wildcards say so");
SensePattern off = drake.WithEnabled(false);
Check(!off.Enabled && off.Exact && off.Text == "Drake", "switching a term off keeps Exact");
SensePattern loose = off.WithExact(false);
Check(!loose.Exact && !loose.Enabled && loose.Matches("Isle Drake") , "switching Exact off keeps on/off (off terms are skipped by the scan, not by Matches)");
Check(ReferenceEquals(drake.WithExact(true), drake) && ReferenceEquals(drake.WithEnabled(true), drake), "no change: the same term");
Check(loose.WithExact(true).IsGlob == false && new SensePattern("D?ake", true).WithExact(true).Matches("D?ake")
&& !new SensePattern("D?ake", true).WithExact(true).Matches("Drake"), "a wildcard term made exact takes its letters as they are");
Check(new SensePattern("D?ake", true, exact: true).WithExact(false).Matches("Drake"), "and back to wildcards");
Check(SenseFile.ExactReply("Drake", true).Contains("exact", StringComparison.Ordinal)
&& SenseFile.ExactReply("Drake", false).Contains("containing", StringComparison.Ordinal), "the line after the = is clicked");
}
private static void ExactInTheFile()
{
var terms = new List<SensePattern> { new("Drake", true, exact: true), new("Golem", true), new("Mattekar*", false), new("Olthoi", false, exact: true) };
string text = SenseFile.Format(terms, false, false, SenseLayoutMode.Full);
Check(text.Contains("term=1|Drake\nexact=Drake", StringComparison.Ordinal) || text.Contains("term=1|Drake\r\nexact=Drake", StringComparison.Ordinal),
"an exact term is written as its term line, then an exact line");
Check(!text.Contains("exact=Golem", StringComparison.Ordinal) && !text.Contains("exact=Mattekar", StringComparison.Ordinal), "only exact terms get one");
SenseFileData back = SenseFile.Parse(Lines(text));
Check(back.Terms.Count == 4, $"four terms come back ({back.Terms.Count})");
Check(back.Terms[0].Exact && back.Terms[0].Enabled && !back.Terms[1].Exact && !back.Terms[2].Exact && back.Terms[2].IsGlob
&& back.Terms[3].Exact && !back.Terms[3].Enabled, "Exact comes back on the right terms, with on/off and wildcards");
// A file from before Exact: every term matches as before.
SenseFileData old = SenseFile.Parse(new[] { "alertChat=0", "term=1|Drake", "term=0|Golem*" });
Check(old.Terms.TrueForAll(t => !t.Exact) && old.Terms[1].IsGlob, "an older file: no term is exact");
// An engine from before Exact skips the exact lines and still has every term (as contains): what it keeps.
var withoutExact = Lines(text).Where(l => !l.StartsWith("exact=", StringComparison.Ordinal));
SenseFileData olderEngine = SenseFile.Parse(withoutExact);
Check(olderEngine.Terms.Count == 4 && olderEngine.Terms[0].Text == "Drake" && !olderEngine.Terms[0].Exact,
"the term lines alone are the whole list (an older engine reads them as contains terms)");
// By hand: an exact line before its term, any case, or with no term at all.
SenseFileData hand = SenseFile.Parse(new[] { "exact=drake", "term=1|Drake", "exact= Banderling ", "exact=", "exact=Drake" });
Check(hand.Terms.Count == 2, $"an exact line for a term already there adds nothing ({hand.Terms.Count})");
Check(hand.Terms[0].Text == "Drake" && hand.Terms[0].Exact, "an exact line before its term, any case, still makes it exact");
Check(hand.Terms[1].Text == "Banderling" && hand.Terms[1].Exact && hand.Terms[1].Enabled, "an exact line alone adds an exact term, on, trimmed");
var many = new List<string>();
for (int i = 0; i < SenseFile.MaxTerms; i++) many.Add("term=1|name" + i);
many.Add("exact=one too many");
many.Add("exact=name7");
SenseFileData full = SenseFile.Parse(many);
Check(full.Terms.Count == SenseFile.MaxTerms && full.Terms[7].Exact, "a full list: an exact line still marks its term, and adds none past the cap");
// The Virindi Sense import: patterns.txt has no match-type field, so its names stay contains.
SenseMerge m = SenseImport.Merge(new List<SensePattern> { new("Drake", true, exact: true) }, new[] { "drake", "Sand Caves" });
Check(m.Terms[0].Exact && !m.Terms[1].Exact, "importing keeps an exact term exact and adds contains terms, as Virindi Sense matched");
}
private static void ExactCommands()
{
Check(SenseLayout.IsAddSelected("addselected", out bool e1) && e1, "addselected adds the exact name");
Check(SenseLayout.IsAddSelected("add selected exact", out bool e2) && e2, "addselected exact");
Check(SenseLayout.IsAddSelected("ADDSEL Contains", out bool e3) && !e3, "addselected contains: a contains term (any case)");
Check(SenseLayout.IsAddSelected("add selected contains", out bool e4) && !e4, "spacing");
Check(!SenseLayout.IsAddSelected("addselected maybe", out _) && !SenseLayout.IsAddSelected("addselectedcontains", out _), "only exact or contains after it");
foreach (string ok in new[] { "addselected contains", "addselected exact", "add selected contains" })
Check(SenseLayout.IsValidArgs(ok), $"'/rc sense {ok}' runs");
Check(!SenseLayout.IsValidArgs("addselected maybe"), "'/rc sense addselected maybe' gets the usage");
Check(SenseLayout.Usage.Contains("addselected [contains]", StringComparison.Ordinal), "the usage names contains");
}
}

View file

@ -7,7 +7,9 @@
the mouse and when clicks go to the game), the collapsed line, /rc sense's look commands
(compact on|off, collapse on|off, view ...: the look they lead to and their replies, and the
argument check), sense.txt read and written (terms, alerts and the look, a file from before
the look, bad values), and the term matching. No file I/O, no AC, no ImGui.
the look, bad values), and the term matching (contains, wildcards, and Exact: the whole name,
2026-11-26, with its exact= lines in sense.txt and /rc sense addselected [contains]).
No file I/O, no AC, no ImGui.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>

View file

@ -53,9 +53,87 @@ namespace SettingsLayoutTests
Moves();
HuntAndDirtyFighting();
LootProfileRow();
NavmeshViewRows();
return Finish();
}
// ── Settings > Navigation > Navmesh View: RynthNav's navmesh switches (2026-11-26) ─────────────
private static void NavmeshViewRows()
{
object? nav = Tabs.Cast<object>().FirstOrDefault(t => Name(t) == "Navigation");
Check(nav != null, "there is a Navigation tab");
if (nav == null) return;
List<object> rows = Rows(nav).Cast<object>().ToList();
int Index(string kind, string label) => rows.FindIndex(r => Kind(r) == kind && Label(r).Trim() == label);
// Right after Nav Marker Display (it ends with Guide Line), before Doors.
int guide = Index("Bool", "Guide Line"), section = Index("Section", "Navmesh View"), doors = Index("Section", "Doors");
Check(guide >= 0 && section > guide && doors > section, $"Navmesh View sits between Guide Line and Doors (Guide Line {guide}, Navmesh View {section}, Doors {doors})");
Check(section > guide && rows.Skip(guide + 1).Take(section - guide - 1).All(r => Kind(r) == "Spacer"), "...with only a spacer between Guide Line and it");
if (section < 0 || doors < 0) return;
List<object> mine = rows.Skip(section + 1).Take(doors - section - 1).ToList();
object? Mine(string kind, string label) => mine.FirstOrDefault(r => Kind(r) == kind && Label(r).Trim() == label);
double D(object row, string prop) => (double)row.GetType().GetProperty(prop)!.GetValue(row)!;
string? Tip(object row) => (string?)row.GetType().GetProperty("Tooltip")!.GetValue(row);
foreach (var (kind, label, min, max, step, tipStart) in new[]
{
("Bool", "Show Navmesh", 0.0, 0.0, 1.0, "Draw the navigation mesh in the world"),
("Bool", "Green Floor", 0, 0, 1, "The walkable ground, in green."),
("Bool", "Red Walls", 0, 0, 1, "Upright red strips along every edge nav will not cross."),
("Int", "Mesh Radius (m)", 10, 150, 10, "How far around you the mesh is drawn."),
("Int", "Mesh Detail (triangles)", 200, 7000, 500, "The most triangles the mesh may use."),
})
{
object? row = Mine(kind, label);
Check(row != null, $"Navmesh View has a {kind} row '{label}'");
if (row == null) continue;
if (kind == "Int") Check(D(row, "Min") == min && D(row, "Max") == max && D(row, "Step") == step, $"{label}: {min}..{max}, step {step} (the Go tab's)");
Check(Tip(row)?.StartsWith(tipStart, StringComparison.Ordinal) == true, $"{label}: the Go tab's tooltip");
Check(Tip(row)?.Contains("not in the RynthAi profile") == true, $"{label}: the tooltip says it is RynthNav's, not the profile's");
Check(KeyOf(row) == "Navigation/Navmesh View/" + label, $"{label} can be pinned under Navmesh View (got {KeyOf(row)})");
}
Check(mine.Count(r => Kind(r) is "Bool" or "Int") == 5, "five switches and steppers, no more");
// Without RynthNav (no status here): the rows hide and a note says why.
Type settings = _engine.GetType("RynthCore.Engine.UI.Data.RynthAiSettings", throwOnError: true)!;
object s = Activator.CreateInstance(settings, true)!;
bool Visible(object row) => (bool)row.GetType().GetMethod("IsVisible")!.Invoke(row, new[] { s })!;
Check(mine.Where(r => Kind(r) is "Bool" or "Int" or "Status").All(r => !Visible(r)), "no RynthNav: the switches, steppers and status line hide");
List<object> notes = mine.Where(r => Kind(r) == "Note" && Visible(r)).ToList();
Check(notes.Count == 1 && Label(notes[0]).Contains("RynthNav plugin"), $"...and one note says RynthNav is needed (got {string.Join(" | ", notes.Select(Label))})");
Check(Visible(rows[section]), "...under the Navmesh View heading, which stays");
double Get(object row) => (double)((Delegate)row.GetType().GetProperty("Get")!.GetValue(row)!).DynamicInvoke(s)!;
Check(Get(Mine("Bool", "Show Navmesh")!) == 0 && Get(Mine("Int", "Mesh Radius (m)")!) == 40 && Get(Mine("Int", "Mesh Detail (triangles)")!) == 3000,
"reading them with no RynthNav doesn't throw (off, RynthNav's defaults)");
// Not RynthAi settings: nothing about the mesh in the payload.
Type ctxType = _engine.GetType("RynthCore.Engine.UI.Data.RynthAiSettingsJsonContext", throwOnError: true)!;
object ctx = ctxType.GetProperty("Default", All)!.GetValue(null)!;
var info = (System.Text.Json.Serialization.Metadata.JsonTypeInfo)ctxType.GetProperty("RynthAiSettings", All)!.GetValue(ctx)!;
string json = System.Text.Json.JsonSerializer.Serialize(s, info);
Check(!json.Contains("Mesh", StringComparison.OrdinalIgnoreCase) && !json.Contains("Navmesh", StringComparison.OrdinalIgnoreCase),
"the RynthAi settings payload has no navmesh fields");
// The rules behind the rows (UI/Data/NavmeshView.cs).
Type view = _engine.GetType("RynthCore.Engine.UI.Data.NavmeshView", throwOnError: true)!;
Type statusType = _engine.GetType("RynthCore.Engine.UI.Data.RynthNavStatus", throwOnError: true)!;
object? Parse(string j) => statusType.GetMethod("Parse", All)!.Invoke(null, new object[] { j });
object? V(string name, params object?[] a) => view.GetMethod(name, All)!.Invoke(null, a);
object? older = Parse("{\"hasPose\":1}"), newer = Parse("{\"hasPose\":1,\"mesh\":{\"on\":1,\"floor\":0,\"walls\":1,\"radius\":70,\"triangles\":4200,\"drawn\":1840}}");
Check(older != null && newer != null, "RynthNav statuses parse");
Check(!(bool)V("Available", (object?)null)! && !(bool)V("Available", older)! && (bool)V("Available", newer)!, "the rows show only for a RynthNav that sends its mesh state (0.6.7+)");
Check(((string)V("Unavailable", older)!).Contains("0.6.7"), "an older RynthNav: the note says which version is needed");
Check((string)V("Unavailable", newer)! == "", "a new one: no note");
Check((bool)V("GetSwitch", newer, "Show Navmesh")! && !(bool)V("GetSwitch", newer, "Green Floor")! && (bool)V("GetSwitch", newer, "Red Walls")!, "the switches read RynthNav's on / floor / walls");
Check((string)V("Drawn", newer)! == "1840 triangles drawn now." && (string)V("Drawn", older)! == "", "the status line: triangles drawn while on");
Check((string)V("SwitchCommand", "Show Navmesh", true)! == "mesh on" && (string)V("SwitchCommand", "Show Navmesh", false)! == "mesh off", "Show Navmesh sends /rnav mesh on|off");
Check((string)V("SwitchCommand", "Green Floor", false)! == "mesh floor off" && (string)V("SwitchCommand", "Red Walls", true)! == "mesh walls on", "Green Floor / Red Walls send mesh floor|walls on|off");
Check((string)V("RadiusCommand", 70)! == "mesh radius 70" && (string)V("RadiusCommand", 999)! == "mesh radius 150" && (string)V("RadiusCommand", 0)! == "mesh radius 10", "Mesh Radius sends mesh radius N, 10..150");
Check((string)V("DetailCommand", 3700)! == "mesh triangles 3700" && (string)V("DetailCommand", 9000)! == "mesh triangles 7000" && (string)V("DetailCommand", 1)! == "mesh triangles 200", "Mesh Detail sends mesh triangles N, 200..7000");
Check((bool)V("IsMeshLabel", "Mesh Radius (m)")! && !(bool)V("IsMeshLabel", "Guide Line")! && !(bool)V("IsMeshLabel", (object?)null)!, "the drawer knows a pinned navmesh row");
}
// ── Settings > Looting's Loot Profile picker (2026-11-22) ──────────────────────────────
private static void LootProfileRow()
{
@ -273,6 +351,7 @@ namespace SettingsLayoutTests
("Targeting", "Combat/Targeting/Targeting"),
("Attempts Before Blacklist", "Combat/Targeting/Attempts Before Blacklist"),
("Enable Raycasting", "Combat/Line Of Sight/Enable Raycasting"),
("Show Line of Sight", "Combat/Line Of Sight/Show Line of Sight"), // 2026-11-26, next to Enable Raycasting
("Magic Response", "Combat/Hitting the Environment/Magic Response"),
("Enable Missile Crafting", "Combat/Missile Ammo Crafting/Enable Missile Crafting"),
("Enable Autostack", "Inventory/Packs/Enable Autostack"),

View file

@ -24,6 +24,8 @@ internal static class Program
Pricing();
WiringPinned();
BuyBox();
BuyBoxWiringPinned();
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks failed)");
return _failed == 0 ? 0 : 1;
@ -77,6 +79,100 @@ internal static class Program
Check(text.Contains(needle, StringComparison.Ordinal), "VendorTrade.cs contains: " + needle);
}
// The Inventory panel's "Buy how many?" box (VendorBuyMath, 2026-11-26).
private static void BuyBox()
{
static long Linear12(int n) => 12L * n;
const int Max = VendorBuyMath.MaxAmount;
// Stock and money.
Eq(VendorBuyMath.MaxBuy(-1, -1, Linear12), Max, "unlimited stock, money unknown: the engine's limit");
Eq(VendorBuyMath.MaxBuy(0, 1000, Linear12), 0, "the vendor has none");
Eq(VendorBuyMath.MaxBuy(50, -1, Linear12), 50, "50 in stock, money unknown: 50");
Eq(VendorBuyMath.MaxBuy(-1, 1000, Linear12), 83, "12 each, 1,000 to spend: 83");
Eq(VendorBuyMath.MaxBuy(-1, 11, Linear12), 0, "12 each, 11 to spend: none");
Eq(VendorBuyMath.MaxBuy(-1, 12, Linear12), 1, "12 each, 12 to spend: one");
Eq(VendorBuyMath.MaxBuy(100, 1200, Linear12), 100, "exactly enough for the whole stock");
Eq(VendorBuyMath.MaxBuy(100, 1_000_000, Linear12), 100, "rich: the stock");
Eq(VendorBuyMath.MaxBuy(Max + 5, -1, Linear12), Max, "a stock past the limit is capped");
Eq(VendorBuyMath.MaxBuy(-1, 0, _ => 0), Max, "a free vendor (cost 0): the engine's limit");
Eq(VendorBuyMath.MaxBuy(-1, 100, _ => -1), 0, "a cost that overflowed to negative counts as too much");
// ACE's per-stack pricing (each created stack rounds up, floor 1): searched, not divided.
foreach (float rate in new[] { 1.15f, 0.9f, 2.5f })
foreach (int maxStack in new[] { 1, 7, 100 })
{
long StackCost(int n)
{
long full = n / maxStack, rem = n % maxStack;
return full * VendorRatePolicy.PlayerPaysForStack(rate, Misc, 3L * maxStack)
+ (rem > 0 ? VendorRatePolicy.PlayerPaysForStack(rate, Misc, 3L * rem) : 0);
}
foreach (long money in new long[] { 0, 1, 3, 4, 100, 345, 1000, 9999 })
{
int got = VendorBuyMath.MaxBuy(5000, money, StackCost);
bool fits = got == 0 || StackCost(got) <= money;
bool most = got == 5000 || StackCost(got + 1) > money;
Check(fits && most, $"rate {rate}, stacks of {maxStack}, {money} to spend: {got} is the most that fits");
}
}
// Where the number starts and how a typed one is kept.
Eq(VendorBuyMath.Prefill(50, 200), 50, "the toolbar's 50, 200 buyable: 50");
Eq(VendorBuyMath.Prefill(500, 200), 200, "the toolbar's 500, 200 buyable: 200");
Eq(VendorBuyMath.Prefill(1, 200), 1, "the toolbar's 1: 1");
Eq(VendorBuyMath.Prefill(0, 200), 1, "no toolbar number: 1");
Eq(VendorBuyMath.Prefill(-7, 200), 1, "a junk toolbar number: 1");
Eq(VendorBuyMath.Prefill(50, 0), 1, "nothing buyable: 1 (Buy is off)");
Eq(VendorBuyMath.Clamp(0, 10), 1, "typed 0: 1");
Eq(VendorBuyMath.Clamp(-3, 10), 1, "typed -3: 1");
Eq(VendorBuyMath.Clamp(11, 10), 10, "typed 11 of 10: 10");
Eq(VendorBuyMath.Clamp(7, 10), 7, "typed 7 of 10: 7");
Eq(VendorBuyMath.Clamp(7, 0), 1, "nothing buyable: 1");
Eq(VendorBuyMath.Half(0), 1, "half of 0: 1");
Eq(VendorBuyMath.Half(1), 1, "half of 1: 1");
Eq(VendorBuyMath.Half(9), 4, "half of 9: 4");
}
// The box and the split-globals fix must use what is tested here.
private static void BuyBoxWiringPinned()
{
string? box = FindUp(Path.Combine("src", "RynthCore.Engine", "ImGui", "Panels", "InventoryFace.VendorBuy.cs"));
Check(box != null, "found InventoryFace.VendorBuy.cs");
if (box != null)
{
string text = File.ReadAllText(box);
foreach (string needle in new[]
{
"VendorBuyMath.Prefill(toolbar, MaxBuy(snap, item))",
"VendorBuyMath.MaxBuy(item.Unlimited ? -1 : item.Amount, VendorTrade.MoneyFor(snap)",
"VendorBuyMath.Clamp(_buyAmount, max)",
"UiDropTargets.Publish(VendorDropKey, Title, origin, origin + size, snap != null, IsVendorItem)",
"VendorTrade.RequestBuy(_buyVendor, [_buyItem], [_buyAmount])",
})
Check(text.Contains(needle, StringComparison.Ordinal), "InventoryFace.VendorBuy.cs contains: " + needle);
}
string? hooks = FindUp(Path.Combine("src", "RynthCore.Engine", "Compatibility", "ClientHelperHooks.cs"));
Check(hooks != null, "found ClientHelperHooks.cs");
if (hooks != null)
{
string text = File.ReadAllText(hooks);
int reads = CountOf(text, "SplitGlobals keep = SplitGlobals.Read();");
int restores = CountOf(text, "keep.Restore();");
Check(reads == 2 && restores == 2, $"MoveItemInternal and SplitStackInternal both keep AC's split globals (reads {reads}, restores {restores})");
Check(!text.Contains("try { Marshal.WriteInt32(new IntPtr(_splitAmountAddr), 1); } catch { }", StringComparison.Ordinal),
"SplitStackInternal no longer leaves split_amount at 1 after it");
}
}
private static int CountOf(string text, string needle)
{
int n = 0;
for (int i = text.IndexOf(needle, StringComparison.Ordinal); i >= 0; i = text.IndexOf(needle, i + needle.Length, StringComparison.Ordinal)) n++;
return n;
}
private static string? FindUp(string relative)
{
for (DirectoryInfo? d = new(AppContext.BaseDirectory); d != null; d = d.Parent)

View file

@ -19,6 +19,8 @@
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\VendorRatePolicy.cs" Link="Engine\VendorRatePolicy.cs" />
<!-- 2026-11-26: the Inventory panel's "Buy how many?" box (max, prefill, clamp). -->
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\VendorBuyMath.cs" Link="Engine\VendorBuyMath.cs" />
</ItemGroup>
</Project>