diff --git a/Changelog/2026-11-11-settings-regroup.md b/Changelog/2026-11-11-settings-regroup.md new file mode 100644 index 0000000..ddebac1 --- /dev/null +++ b/Changelog/2026-11-11-settings-regroup.md @@ -0,0 +1,58 @@ +# Settings panel regrouped: 14 tabs in three groups, 10 settings get rows + +Branch `feature/settings-regroup`, from `rc/2026.11.next` f219759. Not deployed. RynthSuite's chat text and tooltips that +name a tab are on `feature/settings-regroup-text` (from `rc/2026.11.next` a91104fe). The phone app's own copy of the +groups is on RynthRemote's `feature/settings-regroup`. No plugin API change; any RynthAi works with it. + +## What changed + +- The tabs, in three sidebar groups: + - **RynthCore · this PC:** Interface (Display + UI), Game Client (new), Hotkeys. + - **RynthAi · saved in the profile:** General (was Misc), Recharge, Combat (was Melee Combat), Spell Combat, Ranges, + Navigation, Buffing, Looting, Inventory (new), Vendoring. + - **Support:** Diagnostics. +- What moved where: + - **Interface:** the theme and the dashboard look (Look), text size, the RynthCore toolbar, the four "Hide retail" + switches, your vitals plate and Show Target Stamina / Mana, the RynthDefective windows in the retail toolbar's + place, and window layout. + - **Game Client:** Borderless Windowed and Remember Game Window Position (Game Window); the FPS limit, the video + patch and Background Identify (Performance); Close Client on Server Disconnect and the reload hold (Disconnects + And Updates); the server picker (Server, from Diagnostics). + - **Hotkeys:** Insert Key Releases the UI (from Display). + - **General:** login and VTank switches (Starting Up), Peace Mode When Idle and Weapons Back After Heals (Between + Fights), Escape Acid and Lava and the macro stops (Safety Stops, from Misc and Recharge), Recall On Death (from + Recharge), fellowship management (from Spell Combat), Vaulted Dungeons (Server Features, from Navigation). + - **Combat:** targeting (from Ranges) and the blacklist (from Misc) under Targeting; line of sight and the missile + arcs (from Misc); both environment responses together (Magic Response from Spell Combat); missile ammo crafting + (the old Crafting tab). + - **Buffing:** Buff Spell Interval (from Spell Combat), Use Buff Items (from Recharge). + - **Inventory:** packs (Autostack, Autocram, Tidy, Floating HUDs), aetheria, salvage and its timers (from Looting), + Give Interval (from Misc), Item Info (from Display). +- Follow-up (`feature/settings-hunt-df-rows`, on `rc/2026.11.next` 1d6345a): **Hunt On Login** under General > Starting + Up (one or the other with Patrol On Login: ticking one clears the other, as RynthAi keeps them), and the **Dirty + Fighting rotation** under Combat > Attack Power & Height with its **Effect order** and **Then attack** (RynthAi's + DfHeightRotation, DfHeightOrder, DfDefaultHeight; also its own Dirty Fighting window). Hidden until RynthAi sends them. +- Taken out: Misc's duplicate Auto Cram (Inventory > Packs > Enable Autocram is the same switch) and Recharge's three + "Helper Settings — NOT WIRED YET" sliders (they do nothing; their values stay in the payload). +- New rows for settings RynthAi already had and sends (each hidden until RynthAi sends the value, so an older RynthAi + shows nothing and a save leaves them alone): + - Combat > Targeting: **Cast Settle (ms)**. + - Combat > Weapon Swaps: **Weakness Swap Min Gain %**, **No Swap Under Target Health %**, **Wait After Target + Switch (ms)**, **Prefer Dual Wield**, **Off-hand Default** (Auto, Shield, Weapon, None). + - Buffing: **Idle Margin (minutes)** (with Rebuff When Idle on), **Skip buffs this character can't use**. + - Looting: **Loot Mode** (RynthAi's loot messages already pointed here), **Chest relock wait (s)** (also on the + Item Tool), and the **Loot By Name** section (Names, Radius; 399b519 rebuilt, never shipped before). +- Pins: My settings drawer pins are "Tab/Section/Label" keys. A pin saved under the old layout is found again by its + label on the tabs its old tab's rows went to, and the file is rewritten with the new keys when it loads + (`QuickSettings.MigrateKey`). Misc's Auto Cram pin goes to Enable Autocram. An engine older than this one won't + draw the rewritten pins (they stay in the file). +- `/rc settings ` and a plugin's link accept the old names too (`SettingsSchema.FindTab`: Display and UI open + Interface, Misc opens General, Melee Combat and Crafting open Combat). `/rc diagnostics` and `/rc serverpick` + open Game Client, where the server picker is now. +- Text that names a tab follows: chat replies, tooltips, the video patch banner and the comments. + +## Tests + +- `tools/SettingsLayoutTests` (new): the tab order and groups; every one of the 301 pin keys of the old layout + (`OldPinKeys.txt`, dumped from f219759) leads to its row; the old tab names; where the moved rows are. +- `tools/CombatSettingsTests` and `tools/VaultedSettingTests` follow the rows to Combat and General. diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs index f52a0fd..0d28ae2 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs @@ -181,7 +181,7 @@ internal static class ChatCommandReplies V("progression", "Usage: /rc progression (opens the Progress tab)", NoArgs, "progress"), V("spells", "Usage: /rc spells [show|hide|toggle]", PanelArgs), V("hotkeys", "Usage: /rc hotkeys (opens Settings > Hotkeys) | /rc hotkeys (as /rc hotkey)", null), - V("diagnostics", "Usage: /rc diagnostics (opens Settings > Diagnostics, the server picker)", NoArgs, "serverpick"), + V("diagnostics", "Usage: /rc diagnostics (opens Settings > Game Client, the server picker)", NoArgs, "serverpick"), V("settings", "Usage: /rc settings [tab]", null), V("shortcuts", "Usage: /rc shortcuts [use <1-18> | set <1-18> [id] | clear <1-18>]", ShortcutsArgs), V("keymap", "Usage: /rc keymap check|bind|unbind | dump, e.g. /rc keymap bind UseQuickSlot_10 F11", KeymapArgs), diff --git a/src/RynthCore.Engine/Compatibility/ConfirmationArmPolicy.cs b/src/RynthCore.Engine/Compatibility/ConfirmationArmPolicy.cs new file mode 100644 index 0000000..a901679 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ConfirmationArmPolicy.cs @@ -0,0 +1,166 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ConfirmationArmPolicy.cs +// +// The pure half of ConfirmationResponder (plugin API v85, v97): what the armed answers +// do with a server yes/no prompt, and the "N percent" the prompt's text carries. +// No client memory, no hooks, no clock of its own (the caller passes the time), so +// tools\ConfirmationResponderTests compiles it as it is. +// +// Two slots, one of each kind: +// +// ONE-SHOT (v85, unchanged): ArmConfirmation(type, minPercent 0-100, timeoutMs 1-120000). +// The next request of that type inside the timeout is answered Yes when the +// server's percent is at least the minimum (or the minimum is 0), else No, and +// the arm is spent. A new one-shot replaces the old one; timeoutMs <= 0 (without +// the flag) disarms it. A one-shot always goes first: a plugin's own automated +// step is answered by its own arm, whatever sticky arm is standing. +// +// STICKY, LEAVE BELOW (v97): the same call with ArmFlagLeaveBelow (0x100) OR'ed into +// minPercent, and a minimum of 1-100. A request at or above the minimum is answered +// Yes; one below it, or one whose text has no percent, is LEFT TO THE CLIENT (its +// dialog opens as if nothing were armed); it is never answered No. The arm stays +// armed for every later request until it times out, is disarmed (the flag with +// timeoutMs <= 0) or another sticky arm replaces it. A one-shot arm or disarm never +// touches it. The timeout is capped at 120 s as for one-shots, so an arm left +// behind by a plugin that went away lasts two minutes at most; a plugin that wants +// it longer re-arms before it runs out. +// +// An engine before v97 refuses the flag as bad arguments (-3: minPercent over 100), so +// a plugin built for v97 fails cleanly on an older engine instead of arming a one-shot +// that would answer No. (An old engine's disarm ignores the arguments and clears its +// only slot: a plugin disarms its sticky arm only on a v97 engine.) +// +// Every other bit of minPercent is refused (-3), so later flags can be added the same way. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +/// One armed answer (ConfirmationResponder keeps a one-shot and a sticky one, under its lock). +internal struct ConfirmationArm +{ + public bool Armed; + public uint Type; + public int MinPercent; + public long Until; +} + +internal static class ConfirmationArmPolicy +{ + /// v97: OR'ed into ArmConfirmation's minPercent: the sticky arm (leave below-minimum prompts to the client). + public const int ArmFlagLeaveBelow = 0x100; + + /// The longest timeout an arm takes (both kinds). + public const int MaxTimeoutMs = 120_000; + + // ABI results of ArmConfirmation. Never renumber. + public const int ArmOk = 1; + public const int ArmUnavailable = 0; + public const int ArmBadArgs = -3; + + /// What the responder does with one request. + public enum Verdict + { + /// Nothing armed for it, expired, another type, or below the sticky minimum: AC shows its dialog. + LeaveToClient, + /// The one-shot arm said Yes (and is spent). + Accept, + /// The one-shot arm said No (and is spent). + Decline, + /// The sticky arm said Yes (and stays). + AcceptSticky, + } + + /// True when an arm call (any timeout) is for the sticky slot. + public static bool IsSticky(int minPercentArg) => (minPercentArg & ArmFlagLeaveBelow) != 0; + + /// + /// Checks an arm call's arguments (timeoutMs > 0; a disarm never gets here). + /// with the minimum and the slot, or . + /// + public static int Validate(uint type, int minPercentArg, int timeoutMs, out int minPercent, out bool sticky) + { + sticky = IsSticky(minPercentArg); + minPercent = minPercentArg & ~ArmFlagLeaveBelow; + if (type == 0 || timeoutMs <= 0 || timeoutMs > MaxTimeoutMs) + return ArmBadArgs; + if (minPercentArg < 0 || minPercent < 0 || minPercent > 100) + return ArmBadArgs; // negative, an unknown flag bit, or over 100 + if (sticky && minPercent < 1) + return ArmBadArgs; // a sticky arm with no minimum would say Yes to every prompt + return ArmOk; + } + + /// A new arm from validated arguments. + public static ConfirmationArm Make(uint type, int minPercent, int timeoutMs, long nowMs) + => new() { Armed = true, Type = type, MinPercent = minPercent, Until = nowMs + timeoutMs }; + + /// + /// One ArmConfirmation call on the two slots: timeoutMs <= 0 disarms the call's slot (the flag + /// picks the sticky one), otherwise the arguments are checked and the call's slot is replaced. + /// false (no sender or no game-event hook) arms nothing. + /// Returns , or . + /// + public static int Apply(ref ConfirmationArm oneShot, ref ConfirmationArm sticky, uint type, int minPercentArg, + int timeoutMs, long nowMs, bool available) + { + bool toSticky = IsSticky(minPercentArg); + if (timeoutMs <= 0) + { + if (toSticky) sticky.Armed = false; + else oneShot.Armed = false; + return ArmOk; + } + int ok = Validate(type, minPercentArg, timeoutMs, out int min, out _); + if (ok != ArmOk) + return ok; + if (!available) + return ArmUnavailable; + if (toSticky) sticky = Make(type, min, timeoutMs, nowMs); + else oneShot = Make(type, min, timeoutMs, nowMs); + return ArmOk; + } + + /// + /// What to do with a request of whose text says + /// (-1 = no percent), at . The one-shot goes first and is spent when it + /// answers; otherwise the sticky arm answers Yes at its minimum and stays. Expired arms are dropped. + /// + public static Verdict Decide(ref ConfirmationArm oneShot, ref ConfirmationArm sticky, uint type, int percent, long nowMs) + { + if (oneShot.Armed && nowMs > oneShot.Until) + oneShot.Armed = false; + if (sticky.Armed && nowMs > sticky.Until) + sticky.Armed = false; + + if (oneShot.Armed && oneShot.Type == type) + { + oneShot.Armed = false; + return oneShot.MinPercent <= 0 || (percent >= 0 && percent >= oneShot.MinPercent) ? Verdict.Accept : Verdict.Decline; + } + if (sticky.Armed && sticky.Type == type && percent >= 0 && percent >= sticky.MinPercent) + return Verdict.AcceptSticky; + return Verdict.LeaveToClient; + } + + /// + /// "You determine that you have a 38 percent chance to succeed." -> 38 (cp1252 bytes, the + /// string16's body). -1 when there is no "N percent"; over 100 reads as 100. + /// + public static int ParsePercent(ReadOnlySpan text) + { + int at = text.IndexOf(" percent"u8); + if (at <= 0) + return -1; + int end = at, start = at; + while (start > 0 && text[start - 1] >= (byte)'0' && text[start - 1] <= (byte)'9') + start--; + if (start == end || end - start > 3) + return -1; + int value = 0; + for (int i = start; i < end; i++) + value = value * 10 + (text[i] - '0'); + return value > 100 ? 100 : value; + } +} diff --git a/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs b/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs index 037b155..4e64f3d 100644 --- a/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs +++ b/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs @@ -27,6 +27,12 @@ // (or the minimum is 0), else No, and the arm is spent. An unarmed or // expired request is left to the client, as before. The last request is // always recorded so the plugin can see what happened. +// v97 (ConfirmationArmPolicy.ArmFlagLeaveBelow in minPercent): a second, sticky +// slot. A request at its minimum is answered Yes, one below it is left to the +// client instead of answered No, and the arm stays armed for the next one until +// it times out (120 s at most) or is disarmed (the flag with timeoutMs <= 0). A +// one-shot arm goes first and its arm/disarm calls never touch the sticky one. +// The rules live in ConfirmationArmPolicy.cs (pure, tested). // // Threading: the detour runs on AC's main thread and only takes a short lock; // the sender is called there, outside the lock. Arm/Get run on any thread. @@ -48,6 +54,7 @@ internal static unsafe class ConfirmationResponder public const int OutcomeAccepted = 2; // answered Yes for the plugin public const int OutcomeDeclined = 3; // answered No: the server's percent was below the minimum public const int OutcomeSendFailed = 4; // armed, but the sender failed; the client showed it + public const int OutcomeAcceptedSticky = 5; // v97: answered Yes by the sticky (leave-below) arm private const int EventConfirmationResponseVa = 0x006A2030; @@ -58,11 +65,8 @@ internal static unsafe class ConfirmationResponder private static delegate* unmanaged[Cdecl] _eventConfirmationResponse; private static readonly object _lock = new(); - // The armed answer (one-shot). - private static bool _armed; - private static uint _armedType; - private static int _armedMinPercent; - private static long _armedUntil; + // The armed answers: the v85 one-shot and the v97 sticky (leave-below) arm. + private static ConfirmationArm _oneShot, _sticky; // The last request seen. private static int _seq; private static uint _lastType, _lastContext; @@ -86,28 +90,17 @@ internal static unsafe class ConfirmationResponder /// /// Arm one answer for the next request of within - /// . timeoutMs <= 0 disarms. 1 armed (or disarmed), - /// 0 the sender or the game-event hook isn't available, -3 bad arguments. + /// . timeoutMs <= 0 disarms. with + /// (v97) arms or disarms the sticky slot, + /// without it the one-shot slot. 1 armed (or disarmed), 0 the sender or the game-event hook + /// isn't available, -3 bad arguments. /// public static int Arm(uint type, int minPercent, int timeoutMs) { - if (timeoutMs <= 0) - { - lock (_lock) _armed = false; - return 1; - } - if (type == 0 || minPercent < 0 || minPercent > 100 || timeoutMs > 120_000) - return -3; - if (!HasSender || !SmartBoxHooks.IsGameEventHookInstalled) - return 0; + bool available = HasSender && SmartBoxHooks.IsGameEventHookInstalled; lock (_lock) - { - _armed = true; - _armedType = type; - _armedMinPercent = minPercent; - _armedUntil = Environment.TickCount64 + timeoutMs; - } - return 1; + return ConfirmationArmPolicy.Apply(ref _oneShot, ref _sticky, type, minPercent, timeoutMs, + Environment.TickCount64, available); } /// The last request: its sequence number (0 = none yet), type, context, the @@ -139,7 +132,7 @@ internal static unsafe class ConfirmationResponder uint context = unchecked((uint)Marshal.ReadInt32(data, 8)); int percent = ParsePercent(data, size); - bool answer = false, accept = false; + bool answer = false, accept = false, viaSticky = false; lock (_lock) { _seq++; @@ -148,12 +141,10 @@ internal static unsafe class ConfirmationResponder _lastPercent = percent; _lastAt = Environment.TickCount64; _lastOutcome = OutcomeShown; - if (_armed && _armedType == type && Environment.TickCount64 <= _armedUntil) - { - _armed = false; - answer = true; - accept = _armedMinPercent <= 0 || (percent >= 0 && percent >= _armedMinPercent); - } + ConfirmationArmPolicy.Verdict verdict = ConfirmationArmPolicy.Decide(ref _oneShot, ref _sticky, type, percent, _lastAt); + answer = verdict != ConfirmationArmPolicy.Verdict.LeaveToClient; + viaSticky = verdict == ConfirmationArmPolicy.Verdict.AcceptSticky; + accept = verdict == ConfirmationArmPolicy.Verdict.Accept || viaSticky; } if (!answer) return false; @@ -166,17 +157,16 @@ internal static unsafe class ConfirmationResponder catch { sent = false; } lock (_lock) - _lastOutcome = !sent ? OutcomeSendFailed : accept ? OutcomeAccepted : OutcomeDeclined; + _lastOutcome = !sent ? OutcomeSendFailed : viaSticky ? OutcomeAcceptedSticky : accept ? OutcomeAccepted : OutcomeDeclined; if (_logCount < 40) { _logCount++; - RynthLog.Compat($"Confirmation type={type} ctx=0x{context:X8} percent={percent} -> {(sent ? (accept ? "yes" : "no") : "send failed, shown")}"); + RynthLog.Compat($"Confirmation type={type} ctx=0x{context:X8} percent={percent} -> {(sent ? (accept ? (viaSticky ? "yes (sticky)" : "yes") : "no") : "send failed, shown")}"); } return sent; } - // "You determine that you have a 38 percent chance to succeed." -> 38. The text is a - // string16 (u16 length, cp1252 bytes) at +12. -1 when there is no "N percent". + // The text is a string16 (u16 length, cp1252 bytes) at +12. -1 when there is no "N percent". private static int ParsePercent(IntPtr data, uint size) { const int textOff = 12; @@ -185,19 +175,6 @@ internal static unsafe class ConfirmationResponder int len = (ushort)Marshal.ReadInt16(data, textOff); if (len <= 0 || len > 512 || textOff + 2 + len > size) return -1; - byte* p = (byte*)data + textOff + 2; - ReadOnlySpan text = new(p, len); - int at = text.IndexOf(" percent"u8); - if (at <= 0) - return -1; - int end = at, start = at; - while (start > 0 && text[start - 1] >= (byte)'0' && text[start - 1] <= (byte)'9') - start--; - if (start == end || end - start > 3) - return -1; - int value = 0; - for (int i = start; i < end; i++) - value = value * 10 + (text[i] - '0'); - return value > 100 ? 100 : value; + return ConfirmationArmPolicy.ParsePercent(new ReadOnlySpan((byte*)data + textOff + 2, len)); } } diff --git a/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs b/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs index c7b9419..8071dfb 100644 --- a/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs @@ -195,7 +195,7 @@ internal static class MessageBoxHooks if (!Read(text, wide).StartsWith("Failed to establish connection to the server", StringComparison.OrdinalIgnoreCase)) return false; RynthLog.Warn("MessageBoxHooks: the connection failed - answering AC's box (OK) unseen so the client exits " + - "and a launcher can relaunch it (Close on server disconnect, Settings > Misc)."); + "and a launcher can relaunch it (Close on server disconnect, Settings > Game Client)."); if (Interlocked.Exchange(ref _connectionFailureAnswered, 1) == 0) { var fallback = new Thread(() => diff --git a/src/RynthCore.Engine/Compatibility/RetailToolbarHooks.cs b/src/RynthCore.Engine/Compatibility/RetailToolbarHooks.cs index 55792b2..e04f984 100644 --- a/src/RynthCore.Engine/Compatibility/RetailToolbarHooks.cs +++ b/src/RynthCore.Engine/Compatibility/RetailToolbarHooks.cs @@ -138,7 +138,7 @@ internal static unsafe class RetailToolbarHooks /// /// The "Hide retail toolbar" option. Stored for the whole PC in /// %LOCALAPPDATA%\RynthCore\retail_ui.txt ("HideRetailToolbar=1"), beside "Hide retail - /// vitals". Set from Settings > UI or /rc ui retailtoolbar. Any thread: it only flips a flag + /// vitals". Set from Settings > Interface or /rc ui retailtoolbar. Any thread: it only flips a flag /// and writes the file; TickHide applies it on AC's main thread. /// public static bool HideRetailToolbar diff --git a/src/RynthCore.Engine/Compatibility/RetailVitalsHooks.cs b/src/RynthCore.Engine/Compatibility/RetailVitalsHooks.cs index d9f95e3..0fecbee 100644 --- a/src/RynthCore.Engine/Compatibility/RetailVitalsHooks.cs +++ b/src/RynthCore.Engine/Compatibility/RetailVitalsHooks.cs @@ -137,7 +137,7 @@ internal static unsafe class RetailVitalsHooks /// The "Hide retail vitals" option. Stored for the whole PC in /// %LOCALAPPDATA%\RynthCore\retail_ui.txt ("HideRetailVitals=1"), beside the /// engine's other in-client UI settings (panel_text_size.txt, - /// nameplate_settings.txt). Set from Settings > UI or /rc ui retailvitals. + /// nameplate_settings.txt). Set from Settings > Interface or /rc ui retailvitals. /// Any thread: it only flips a flag and writes the file; TickHide applies it /// on AC's main thread. /// diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 0e5dbc1..e0eed66 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -99,7 +99,7 @@ namespace RynthCore.Engine.Compatibility; /// /rc hotkeys - opens Settings > Hotkeys. /rc hotkey list | add <combo> <action or /// /command> | remove <combo> | enable|disable <combo> | actions | status | on|off - the user /// hotkeys (; saved for the PC in hotkeys.txt). -/// /rc diagnostics (or /rc serverpick) - opens Settings > Diagnostics, the server +/// /rc diagnostics (or /rc serverpick) - opens Settings > Game Client, the server /// picker: the one place a server is forced for this character (plugins' "Force a server" links). /// /rc layout [status] | default | reset [confirm] - the panel layout this client uses /// (: its character's own, or the PC-wide default and why) and its files; @@ -119,8 +119,11 @@ internal static class RynthCoreChatCommands /// RynthNet's Characters window (a plugin window: its title is its panel key). private const string CharactersWindowTitle = "Characters"; - /// The Settings tab with the server picker (UI/Data/SettingsData.cs "Diagnostics"). - private const string DiagnosticsTabName = "Diagnostics"; + /// + /// The Settings tab with the server picker (UI/Data/SettingsData.cs): Game Client since 2026-11-11, Diagnostics + /// before. /rc diagnostics still opens it, as plugins link there for the picker. + /// + private const string ServerPickTabName = "Game Client"; // The line being handled on this thread: who sent it, and whether it has answered yet. [ThreadStatic] private static ChatCommandOrigin _origin; @@ -409,7 +412,7 @@ internal static class RynthCoreChatCommands } // /rc dashboard [classic|modern|tab ] : the RynthAi dashboard's look (the title bar buttons and - // Settings > Display), and the Classic look's tab (main, monsters, gear, buffs, route, loot, meta, + // Settings > Interface), and the Classic look's tab (main, monsters, gear, buffs, route, loot, meta, // tuning); either opens the dashboard. No argument: says which look is on. if (IsVerb(sub, "dashboard", out string dashArgs)) { @@ -505,14 +508,15 @@ internal static class RynthCoreChatCommands OpenSettingsTab(ImGuiBackend.Panels.HotkeysSettingsUi.TabName); return; } - // /rc diagnostics : Settings > Diagnostics, where a server is forced for this character (the - // server picker). The one place to force a server since 2026.10.5.54, so plugins link here. + // /rc diagnostics, /rc serverpick : Settings > Game Client, where a server is forced for this character + // (the server picker; on Diagnostics until 2026-11-11, hence the name). The one place to force a server + // since 2026.10.5.54, so plugins link here. if ((IsVerb(sub, "diagnostics", out string diagArgs) || IsVerb(sub, "serverpick", out diagArgs)) && diagArgs.Length == 0) { if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SettingsFace.Title)) Fail("The Settings panel isn't available (the ImGui layer is off?). /rc server auto|on|off works here in chat."); else - OpenSettingsTab(DiagnosticsTabName); + OpenSettingsTab(ServerPickTabName); return; } // /rc settings [tab] : the Settings panel (toggled), or opened on a tab ("/rc settings buffing"). @@ -1317,7 +1321,8 @@ internal static class RynthCoreChatCommands TogglePanel(title, "Settings", "The Settings panel isn't available (the ImGui layer is off?)."); return; } - UI.Data.SettingsTab? tab = Array.Find(UI.Data.SettingsSchema.Tabs, t => t.Name.Equals(tabName, StringComparison.OrdinalIgnoreCase)); + // FindTab also takes the names from before the 2026-11-11 regroup ("/rc settings misc" opens General). + UI.Data.SettingsTab? tab = UI.Data.SettingsSchema.FindTab(tabName); if (tab != null) { OpenSettingsTab(tab.Name); diff --git a/src/RynthCore.Engine/Compatibility/ServerDisconnectClose.cs b/src/RynthCore.Engine/Compatibility/ServerDisconnectClose.cs index 3785944..cd8a561 100644 --- a/src/RynthCore.Engine/Compatibility/ServerDisconnectClose.cs +++ b/src/RynthCore.Engine/Compatibility/ServerDisconnectClose.cs @@ -22,7 +22,7 @@ // That runs the normal shutdown: Win32Backend stops the plugin pump and starts // EngineLifecycle.Shutdown, AC's UseTime returns 0 and the client exits with 0; // - still open 20 s later: posts WM_CLOSE once more; 60 s later: says so and stops. -// Off (engine.json CloseOnServerDisconnect false, Settings > Misc): only the log line. +// Off (engine.json CloseOnServerDisconnect false, Settings > Game Client): only the log line. // Polled rather than evented, so a hot reload on the screen still closes the client. // ============================================================================ using System; @@ -85,8 +85,8 @@ internal static class ServerDisconnectClose _fromMode = UiFlowHooks.PreviousMode; string who = DescribeSession(); string action = enabled - ? $"closing the client in {Policy.DelayMs / 1000}s so a launcher can relaunch it (Close on server disconnect, Settings > Misc)" - : "Close on server disconnect is off (Settings > Misc) - the client stays on this screen"; + ? $"closing the client in {Policy.DelayMs / 1000}s so a launcher can relaunch it (Close on server disconnect, Settings > Game Client)" + : "Close on server disconnect is off (Settings > Game Client) - the client stays on this screen"; RynthLog.Warn($"ServerDisconnect: AC lost the server and shows its 'server has disconnected' screen ({UiFlowHooks.ModeName(_fromMode)} -> Disconnected){who}; {action}."); try { Net.FlightRecorder.RequestAuto("server disconnect (the Disconnected screen)", "engine"); } catch { } diff --git a/src/RynthCore.Engine/Compatibility/TrainingCosts.cs b/src/RynthCore.Engine/Compatibility/TrainingCosts.cs index ea2fe8b..d8937fc 100644 --- a/src/RynthCore.Engine/Compatibility/TrainingCosts.cs +++ b/src/RynthCore.Engine/Compatibility/TrainingCosts.cs @@ -57,6 +57,17 @@ internal enum RaiseStatus SendFailed = -9, } +/// +/// What a Max raise buys (TrainingCosts.PlanMax): ranks for XP, +/// with ranks and XP left to the top before it, and +/// more unassigned XP needed to reach the top in one go (0 when it does). +/// +internal readonly record struct MaxRaisePlan(int Ranks, long Cost, int RanksLeft, long CostToTop, long Missing) +{ + /// The raise takes the stat all the way to the top rank. + public bool ReachesTop => Ranks > 0 && Ranks == RanksLeft; +} + internal static class TrainingCosts { /// Most ranks one API raise may buy (the retail window offers 1 and 10). @@ -151,6 +162,23 @@ internal static class TrainingCosts return lo; } + /// + /// The Skills panel's Max: the most ranks XP buys in one raise, what + /// that raise costs, and how far it is from the top. Worked out from the stat's numbers now, so a + /// skill that was untrained and trained again (rank 0, nothing spent, the refund in the unassigned + /// XP) is priced from rank 0 like any other. The XP sent never goes past the top + /// ( = table[top] - spent, which is ACE's ExperienceLeft). + /// + public static MaxRaisePlan PlanMax(uint[] table, uint ranks, uint spent, long available) + { + int left = RanksLeft(table, ranks); + long toTop = left > 0 ? CostOf(table, ranks, spent, left) : 0; + long have = Math.Max(0L, available); + int n = Affordable(table, ranks, spent, have); + long cost = n > 0 ? CostOf(table, ranks, spent, n) : 0; + return new MaxRaisePlan(n, cost, left, toTop, Math.Max(0L, toTop - have)); + } + // ── the checks before a raise is sent ────────────────────────────────── /// diff --git a/src/RynthCore.Engine/D3D9/VideoPatch.cs b/src/RynthCore.Engine/D3D9/VideoPatch.cs index faa62b5..cd39a23 100644 --- a/src/RynthCore.Engine/D3D9/VideoPatch.cs +++ b/src/RynthCore.Engine/D3D9/VideoPatch.cs @@ -356,7 +356,7 @@ internal static unsafe class VideoPatch { VideoPatchMode.World => "Video patch: WORLD - AC's 3D world isn't drawn; AC's UI and the panels are. /rc video off to restore.", VideoPatchMode.Unfocused => "Video patch: UNFOCUSED - the 3D world isn't drawn while another window has the focus; it draws again the moment you switch back.", - VideoPatchMode.All => "Video patch: ALL - nothing of AC's is drawn; the panels and a banner are. Type /rc video off (or Settings > Misc) to restore.", + VideoPatchMode.All => "Video patch: ALL - nothing of AC's is drawn; the panels and a banner are. Type /rc video off (or Settings > Game Client) to restore.", _ => "Video patch: off - normal drawing.", }; diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 5f8fca0..edf1151 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -379,7 +379,7 @@ internal static class EngineFrameController MainThreadHangWatchdog.Step = "EndScene: engine pipeline (layout, prefetches, queues)"; EnsureCore(pDevice); - // Settings > Display: borderless windowed + AC window placement. Throttled; reads only + // Settings > Game Client: borderless windowed + AC window placement. Throttled; reads only // here - the window itself is changed from the game WndProc (AcWindowChrome). try { UI.AcWindowChrome.Tick(_gameHwnd); } catch (Exception ex) { RynthLog.UI($"AcWindowChrome.Tick threw {ex.GetType().Name}: {ex.Message}"); } diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs index beab7f9..d0a0682 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiBar.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -25,7 +25,7 @@ // // The bar's size is its own text size step (PanelTextScale chrome row): the bar's // fonts come from that baked set and its metrics scale by the step's factor. Set it -// from the grip's right-click menu, Ctrl+wheel over the bar, Settings > Display or +// from the grip's right-click menu, Ctrl+wheel over the bar, Settings > Interface or // /rc ui barsize. // // Rows (BarLayout): the player picks how many rows the bar has (1-6) and the most @@ -182,18 +182,21 @@ internal static class ImGuiBar private static string[] _scriptKeys = Array.Empty(); private static string _tooltip = ""; private static bool _placed; - private static Vector2 _pos, _persistedPos; - // What may write a new position to the bar= row: the user dragging the grip, or the bar being - // pulled back on screen by a size change (a few frames: the window grows a frame late). A clamp - // from a smaller AC window leaves the saved position alone. - private static bool _userMoved; - private static int _lastStep, _sizeWatch; + private static Vector2 _pos; + // The bar's home (the bar= row, or where the player dragged it) and where that draws: pulled onto + // the screen for the bar's size and the display, worked out again from the home whenever either + // changes (UI/PanelPlacement). Only the player's drag writes the bar= row (2026-11-12: a pull from + // a size change - a text size step, new rows, icons added as plugins load, a font re-bake - stayed + // for the session and was saved, so the bar came back moved after a reload or login). + private static readonly HomePlace Place = new(); + private static Vector2 _savedHome; // the home the bar= row holds (logical units) + private static bool _userMoved, _pullLogged; // The bar's rows and icons-per-row limit (BarLayout). Read from panel_state once, then kept // here so a change shows at once (the file is written in the background); one reference, so // a reader on another thread never sees half a change. private sealed record RowSettings(int Rows, int MaxPerRow); - private static RowSettings? _rowSettings, _lastRowSettings; + private static RowSettings? _rowSettings; // Icons per row as last drawn: where the icons-per-row "-" starts from when there is no limit. private static int _shownPerRow = 1; @@ -385,17 +388,18 @@ internal static class ImGuiBar { var saved = PanelStateStore.BarPosition; Vector2 logical = saved.HasValue ? new Vector2((float)saved.Value.Left, (float)saved.Value.Top) : new Vector2(50, 5); - _pos = _persistedPos = logical * place; + _savedHome = logical; + // The size isn't known before its first frame: KeepOnScreen fits it once the window has one. + Place.Set(logical * place, Vector2.Zero, ImGuiNET.ImGui.GetIO().DisplaySize); + _pos = Place.Drawn; ImGuiNET.ImGui.SetNextWindowPos(_pos, ImGuiCond.Always); _placed = true; - _lastStep = step; // the size the bar loads at is the baseline, not a change - _lastRowSettings = RowLayout; + _userMoved = false; + _pullLogged = false; + RynthLog.UI("ImGuiBar: " + Place.Describe("the bar", saved.HasValue ? "its saved bar row" : "the default spot (no bar row)") + + $" Layout {PanelStateStore.CurrentPath}."); } - if (step != _lastStep) { _lastStep = step; _sizeWatch = 4; } - // New rows reshape the bar (wider or taller): the same pull back on screen as a new size. - RowSettings rowsNow = RowLayout; - if (!ReferenceEquals(rowsNow, _lastRowSettings)) { _lastRowSettings = rowsNow; _sizeWatch = 4; } PushBarWindowStyle(s); ImGuiNET.ImGui.Begin("##rc_bar", BarFlags); try @@ -414,29 +418,36 @@ internal static class ImGuiBar PopBarWindowStyle(); } - if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && _pos != _persistedPos) + // Only the player's drag moves the bar's home and writes the bar= row (once the mouse is up). + if (_userMoved && !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) { - _persistedPos = _pos; - if (_userMoved || _sizeWatch > 0) + _userMoved = false; + Vector2 logical = Place.Home / place; + if (logical != _savedHome) { - Vector2 logical = _pos / place; + _savedHome = logical; double left = logical.X, top = logical.Y; UiBackgroundWriter.Enqueue("persist bar", () => PanelStateStore.SetBarPosition(left, top)); AvaloniaOverlay.SyncDockedBarPosition(left, top); } - _userMoved = false; } - if (_sizeWatch > 0) _sizeWatch--; } - /// A bigger size or new rows can push the bar's right or bottom end off the screen: pull it back (not while it is being dragged). + /// + /// A bigger size, new rows, icons added as plugins load or a smaller display can push the bar's right or + /// bottom end off the screen: drawn from its home, pulled back only as far as needed, and back home once + /// it fits again (UI/PanelPlacement). Never saved. Not while it is being dragged. + /// private static void KeepOnScreen() { - Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; - if (display.X <= 1 || ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) return; - Vector2 pos = ImGuiNET.ImGui.GetWindowPos(); - Vector2 next = Vector2.Clamp(pos, Vector2.Zero, Vector2.Max(Vector2.Zero, display - ImGuiNET.ImGui.GetWindowSize())); - if (next != pos) ImGuiNET.ImGui.SetWindowPos(next); + if (ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && _userMoved) return; + if (!Place.Fit(ImGuiNET.ImGui.GetWindowSize(), ImGuiNET.ImGui.GetIO().DisplaySize)) return; + ImGuiNET.ImGui.SetWindowPos(Place.Drawn); + if (Place.Pulled && !_pullLogged) + { + _pullLogged = true; + RynthLog.UI("ImGuiBar: " + Place.DescribePull("the bar") + $" (bar row {HomePlace.Xy(_savedHome)})."); + } } private static void DrawContent(float s, bool popped) @@ -468,6 +479,7 @@ internal static class ImGuiBar if (display.X > 1) next = Vector2.Clamp(next, Vector2.Zero, Vector2.Max(Vector2.Zero, display - size)); ImGuiNET.ImGui.SetWindowPos(next); + Place.MoveTo(next, size, display); // the player's spot: the bar's home _userMoved = true; } SafeImGui.SetItemTooltip(_tooltip); diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index 2cd29f6..29c2120 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -170,12 +170,13 @@ internal static class ImGuiPanelHost public bool NeedsPlacement; public Vector2 Pos, Size; // client pixels, as last drawn public Vector2 PersistedPos, PersistedSize; - // The saved spot when the client was too small for it at placement (AC's 800x600 - // character select): re-applied as the display grows, dropped once it fits or the - // player moves the panel. Without this a panel saved near the right or bottom edge - // came back pulled inwards on every restart. - public Vector2? DesiredPos; - public Vector2 DesiredForDisplay; + // Docked: the panel's home (the saved spot, or where the player / a request put it) and + // where that draws, pulled onto the screen for its size and the display (UI/PanelPlacement). + // Worked out again whenever either changes, from the home, and the home is what is saved: + // a pull from a moment's smaller client (AC's 800x600 character select) or a taller first + // frame (a fit-height window at its saved height) is undone once it fits and never saved. + public readonly HomePlace Place = new(); + public bool PullLogged; // the first pull after this load's placement is logged public Vector2? RequestedSize; // logical units, applied next frame (under Sync) public Vector2? RequestedPos; // logical units, applied next frame (under Sync) public volatile bool HasRequest; // RequestedSize or RequestedPos is set @@ -514,7 +515,7 @@ internal static class ImGuiPanelHost foreach (Entry e in order) { if (!e.Shown && !IsOpen(e.Title)) continue; - lines.Add($"face {e.Title}: requested={IsOpen(e.Title)} shown={e.Shown} pos=({e.Pos.X:0},{e.Pos.Y:0}) size=({e.Size.X:0}x{e.Size.Y:0}) failures={e.Failures}{(e.Error != null ? " error=" + e.Error : "")}"); + lines.Add($"face {e.Title}: requested={IsOpen(e.Title)} shown={e.Shown} pos=({e.Pos.X:0},{e.Pos.Y:0}){(e.Place.Pulled ? $" home=({e.Place.Home.X:0},{e.Place.Home.Y:0})" : "")} size=({e.Size.X:0}x{e.Size.Y:0}) failures={e.Failures}{(e.Error != null ? " error=" + e.Error : "")}"); } if (lines.Count == 0) lines.Add("faces: none open"); return lines; @@ -734,7 +735,7 @@ internal static class ImGuiPanelHost { if (_restored) return; _restored = true; - // Settings > Display "Remember Open Windows and Positions" (default on). + // Settings > Interface "Remember Open Windows and Positions" (default on). if (!Plugins.EngineSettings.RememberWindowLayout) return; OpenSavedOpen(); } @@ -978,28 +979,34 @@ internal static class ImGuiPanelHost { Vector2 size = entry.Spec.DefaultSize; Vector2 pos; + string source; if (PanelStateStore.TryGetPanel(entry.Title, out PanelStateStore.PanelEntry saved) && (saved.Width > 0 || saved.Left != 0 || saved.Top != 0)) { pos = new Vector2((float)saved.Left, (float)saved.Top); if (saved.Width > 0 && saved.Height > 0) size = new Vector2((float)saved.Width, (float)saved.Height); + source = "its saved place"; } else if (entry.Spec.DefaultPos is Vector2 defaultPos) { pos = defaultPos; // the face's own first spot (a script window's FirstUseEver position) + source = "its first-open spot"; } else if (entry.Spec.OpenCorner != PanelCorner.None && CornerLogicalPos(entry.Spec.OpenCorner, size, placeScale) is Vector2 corner) { pos = corner; + source = "its first-open corner"; } else if (entry.Spec.OpenCentered && CenteredLogicalPos(size, placeScale) is Vector2 centered) { pos = centered; + source = "the centre"; } else { int shown = 0; lock (Sync) foreach (Entry e in DrawOrder) if (e.Shown) shown++; pos = new Vector2(100 + shown * 20, 100 + shown * 20); // Avalonia's cascade + source = "the cascade"; } size = Vector2.Max(size, entry.Spec.MinSize); @@ -1007,25 +1014,43 @@ internal static class ImGuiPanelHost if (PanelRouter.ResolveDockedFace(entry.Title) == PanelFace.Both) pos += new Vector2(24, 24); - entry.Pos = ClampToDisplay(pos * placeScale, size * placeScale); + // Its home is the saved spot; where it draws is that pulled onto the screen (HomePlace), and + // DrawPanel lets go of the pull once the panel fits (a bigger display, its real height). + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; entry.Size = size * placeScale; + entry.Place.Set(pos * placeScale, entry.Size, display); + entry.Pos = entry.Place.Drawn; entry.PersistedPos = entry.Pos; entry.PersistedSize = entry.Size; entry.NeedsPlacement = true; - entry.DesiredPos = entry.Pos != pos * placeScale ? pos * placeScale : null; - entry.DesiredForDisplay = ImGuiNET.ImGui.GetIO().DisplaySize; + entry.PullLogged = false; // Popped-out windows sit above the game frame, so a docked panel opening under - // one would be invisible. The new spot is saved by the open's Persist, so the - // panel comes back where it could be seen. + // one would be invisible. The new spot is its home now and is saved by the open's + // Persist, so the panel comes back where it could be seen. if (ClearOfPopOuts(entry.Pos, entry.Size) is Vector2 clear) { RynthLog.UI($"ImGuiPanelHost: {entry.Title} would open under a popped-out window; " + $"moved from ({entry.Pos.X:0},{entry.Pos.Y:0}) to ({clear.X:0},{clear.Y:0})."); + entry.Place.MoveTo(clear, entry.Size, display); entry.Pos = clear; entry.PersistedPos = clear; - entry.DesiredPos = null; // don't pull it back under the pop-out as the display grows + source = "a spot clear of popped-out windows"; } + LogPlacement(entry, source); + } + + // Titles whose placement this engine load has logged (AC's render thread). + private static readonly HashSet PlacementLogged = new(StringComparer.OrdinalIgnoreCase); + + /// + /// One line per panel per engine load (its first placement: the login's or the hot reload's), and every + /// placement that pulls it off its saved spot: where it draws, from what, and why. AC thread. + /// + private static void LogPlacement(Entry entry, string source) + { + if (!PlacementLogged.Add(entry.Title) && !entry.Place.Pulled) return; + RynthLog.UI("ImGuiPanelHost: " + entry.Place.Describe(entry.Title, source) + $" Layout {PanelStateStore.CurrentPath}."); } /// Above this share of a docked panel hidden by popped-out windows, it opens elsewhere. @@ -1176,28 +1201,28 @@ internal static class ImGuiPanelHost // A script's size request is its own, not the player's: not saved. if (entry.Dynamic) entry.PersistedSize = entry.Size; } - if (reqPos is Vector2 requestedPos) + // A face asking for the spot it is drawn at (PluginWindowFace / RynthAiFace after a text + // size change: "clamped to the screen at the new size") changes nothing here: the fit + // below pulls it onto the screen from its home. Any other spot is its new home. + if (reqPos is Vector2 requestedPos && !HomePlace.Near(requestedPos * placeScale, entry.Pos)) { - entry.Pos = ClampToDisplay(requestedPos * placeScale, entry.Size); - entry.PersistedPos = entry.Pos; // not a move by the player: nothing to save - entry.DesiredPos = null; + entry.Place.MoveTo(requestedPos * placeScale, entry.Size, ImGuiNET.ImGui.GetIO().DisplaySize); + entry.Pos = entry.Place.Drawn; + entry.PersistedPos = entry.Pos; // not a move by the player: nothing to save now entry.NeedsPlacement = true; } } - if (entry.DesiredPos is Vector2 want) + // Its size or the display changed: drawn from its home again, pulled onto the screen only + // as far as needed (UI/PanelPlacement). Not a move by the player: nothing is saved. + if (entry.Place.Fit(entry.Size, ImGuiNET.ImGui.GetIO().DisplaySize)) { - Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; - if (display != entry.DesiredForDisplay) + entry.Pos = entry.Place.Drawn; + entry.PersistedPos = entry.Pos; + entry.NeedsPlacement = true; + if (entry.Place.Pulled && !entry.PullLogged) { - entry.DesiredForDisplay = display; - Vector2 p = ClampToDisplay(want, entry.Size); - if (p != entry.Pos) - { - entry.Pos = p; - entry.PersistedPos = p; // not a move by the player: nothing to save - entry.NeedsPlacement = true; - } - if (p == want) entry.DesiredPos = null; // back where it was saved + entry.PullLogged = true; + RynthLog.UI("ImGuiPanelHost: " + entry.Place.DescribePull(entry.Title)); } } if (entry.NeedsPlacement) @@ -1251,7 +1276,7 @@ internal static class ImGuiPanelHost return; // closed, popped out or docked back this frame ImGuiNET.ImGui.SetCursorPos(new Vector2(0, header)); - // Per-panel text size (Settings > Display): the face's fonts come from the + // Per-panel text size (Settings > Interface): the face's fonts come from the // set baked at that size (ImGuiFonts.Get); the header above keeps its size. // (Until a size change has been re-baked, the nearest size that is.) ImGuiFonts.CurrentStep = ImGuiFonts.BakedStepNear(PanelTextScale.Get(entry.Title)); @@ -1294,6 +1319,8 @@ internal static class ImGuiPanelHost Vector2 maxSize = display.X > 1 ? display - outerPos : new Vector2(float.MaxValue, float.MaxValue); Vector2 next = Vector2.Clamp(_resizeStartSize + (mouse - _resizeStartMouse), minSize, Vector2.Max(minSize, maxSize)); if (next != outerSize) ImGuiNET.ImGui.SetWindowSize(next); + // Resized where it draws: that spot is the player's now (a pulled window doesn't jump back mid-drag). + entry.Place.MoveTo(outerPos, next, display); } gHot = over || resizing; if (gHot) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.ResizeNWSE); @@ -1366,7 +1393,9 @@ internal static class ImGuiPanelHost if (popped) _pendingDragDelta = Vector2.Zero; if (_pendingDragDelta != Vector2.Zero) { - ImGuiNET.ImGui.SetWindowPos(ClampToDisplay(ImGuiNET.ImGui.GetWindowPos() + _pendingDragDelta, ImGuiNET.ImGui.GetWindowSize())); + Vector2 next = ClampToDisplay(ImGuiNET.ImGui.GetWindowPos() + _pendingDragDelta, ImGuiNET.ImGui.GetWindowSize()); + ImGuiNET.ImGui.SetWindowPos(next); + entry.Place.MoveTo(next, ImGuiNET.ImGui.GetWindowSize(), ImGuiNET.ImGui.GetIO().DisplaySize); // the player's spot _pendingDragDelta = Vector2.Zero; } } @@ -1390,8 +1419,7 @@ internal static class ImGuiPanelHost { entry.PersistedPos = entry.Pos; entry.PersistedSize = entry.Size; - entry.DesiredPos = null; // the player placed it: that is the spot now - Persist(entry, open: true, placeScale); + Persist(entry, open: true, placeScale); // its home (a drag made that the new spot) } } @@ -1594,6 +1622,7 @@ internal static class ImGuiPanelHost { Vector2 next = ClampToDisplay(winPos + ImGuiNET.ImGui.GetIO().MouseDelta, ImGuiNET.ImGui.GetWindowSize()); ImGuiNET.ImGui.SetWindowPos(next); + entry.Place.MoveTo(next, ImGuiNET.ImGui.GetWindowSize(), ImGuiNET.ImGui.GetIO().DisplaySize); // the player's spot } // Grip dots + DRAG (teal, 9) + title (10), vertically centred. @@ -1641,7 +1670,7 @@ internal static class ImGuiPanelHost } } - // Text size (the same per-panel setting as Settings > Display). + // Text size (the same per-panel setting as Settings > Interface). float tsX = x - (canPopOut ? btn + 2 * s : 0) - 2 * s - btn; ImGuiNET.ImGui.SetCursorPos(new Vector2(tsX, y)); int step = PanelTextScale.Get(entry.Title); @@ -1755,11 +1784,11 @@ internal static class ImGuiPanelHost if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + " Reset")) PanelTextScale.ResetWindow(title); ImGuiNET.ImGui.EndDisabled(); - SafeImGui.SetItemTooltip(all == 0 ? "Back to normal size" : "Back to the All Panels size (Settings > Display)"); + SafeImGui.SetItemTooltip(all == 0 ? "Back to normal size" : "Back to the All Panels size (Settings > Interface)"); ImGuiNET.ImGui.SameLine(); if (ImGuiNET.ImGui.Button("Use for all windows")) PanelTextScale.UseForAll(step); - ImGuiNET.ImGui.SetItemTooltip("Every in-game window at this size (Settings > Display > All Panels)"); + ImGuiNET.ImGui.SetItemTooltip("Every in-game window at this size (Settings > Interface > All Panels)"); } private const string DragLabel = PhosphorIcons.DotsSixVertical + "DRAG"; @@ -1819,6 +1848,8 @@ internal static class ImGuiPanelHost Vector2 next = Vector2.Clamp(winSize + ImGuiNET.ImGui.GetIO().MouseDelta, minSize, Vector2.Max(minSize, maxSize)); if (windowName != null) ImGuiNET.ImGui.SetWindowSize(windowName, next); else ImGuiNET.ImGui.SetWindowSize(next); + // Resized where it draws: that spot is the player's now (a pulled window doesn't jump back mid-drag). + entry.Place.MoveTo(winPos, next, display); } return hot; } @@ -1848,7 +1879,7 @@ internal static class ImGuiPanelHost private static void PersistPopped(Entry entry, bool open, int left, int top, int width, int height, float placeScale, bool keepSize = false) { string title = entry.Title; - Vector2 docked = entry.Pos / placeScale; + Vector2 docked = DockedHome(entry) / placeScale; Vector2 size = new Vector2(width, height) / placeScale; UiBackgroundWriter.Enqueue($"persist {title}", () => { @@ -1860,10 +1891,16 @@ internal static class ImGuiPanelHost }); } + /// + /// The docked spot to save (client px): the panel's home (HomePlace), not where it draws: a pull onto + /// a smaller screen or for a taller moment is never written over the saved spot. + /// + private static Vector2 DockedHome(Entry entry) => entry.Place.IsSet ? entry.Place.Home : entry.Pos; + private static void Persist(Entry entry, bool open, float placeScale, bool floating = false) { string title = entry.Title; - Vector2 pos = entry.Pos / placeScale; + Vector2 pos = DockedHome(entry) / placeScale; Vector2 size = entry.Size / placeScale; if (PanelRouter.ResolveDockedFace(title) == PanelFace.Both) pos -= new Vector2(24, 24); // don't let the side-by-side offset drift the Avalonia face diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs index 27b2af2..ebdea3d 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs @@ -174,7 +174,7 @@ internal static class MonsterHudSettingsUi bool locked = MonsterHudSettings.SelfLocked; if (Toggle("Lock position", ref locked, "Locked, the plate can't be grabbed or clicked, so play never moves it. " + - "Untick it, then drag the plate (it shows a frame) and tick it again. Also in Settings > UI > Vitals. " + + "Untick it, then drag the plate (it shows a frame) and tick it again. Also in Settings > Interface > Your Vitals. " + "Chat: /rv plates self lock on|off.", indent: 32)) { MonsterHudSettings.SetSelfLocked(locked); diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs index 31527fa..0c717e3 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs @@ -300,7 +300,7 @@ internal static class PlayerPlate _wantsMouse = _hover || _dragging; } - private const string DragTip = "Drag to move your plate.\nLock it again in Settings > UI > Vitals or Vision > Nameplates > Your plate (or /rv plates self lock)."; + private const string DragTip = "Drag to move your plate.\nLock it again in Settings > Interface > Your Vitals or Vision > Nameplates > Your plate (or /rv plates self lock)."; /// Fades the plate in / out and steps the bars; false when nothing should be painted. private static bool Advance(ref MonsterHud.Frame f, bool show) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatView.cs b/src/RynthCore.Engine/ImGui/Panels/ChatView.cs index 651e67d..21d0704 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatView.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatView.cs @@ -636,7 +636,8 @@ internal sealed class ChatView private void MeasureLine(ImFontPtr font, int i, float textW) { ChatLine line = _vis[i]; - ChatSpan[]? spans = line.Route.Spans; + // The rules' match colours over the plugin's own colour runs (per-part item info). + ChatSpan[]? spans = ChatOwnColors.EffectiveSpans(line.OwnSpans, line.Route.Spans, line.Route.LineArgb != null); // Map coordinates ("82.3N, 34.2E") become links. Found here, when the line is measured, // never per frame; a line without any keeps the plain (or highlighted) path. List coords = ChatCoords.MayHaveCoords(line.Text) ? ChatCoords.Find(line.Text) : NoCoords; diff --git a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicDashboard.cs b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicDashboard.cs index c0439d1..9b573e4 100644 --- a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicDashboard.cs +++ b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicDashboard.cs @@ -10,7 +10,7 @@ // // RynthAiFace draws this instead of the dashboard while // RynthAiDashboardState.Classic is on; the title bar's Modern button and -// Settings > Display switch back. Minimized (the dashboard's shared flag) +// Settings > Interface switch back. Minimized (the dashboard's shared flag) // shows the title bar over a compact strip: the systems, Stop/Start and the // three vitals meters. // @@ -166,8 +166,8 @@ internal sealed class ClassicDashboard _fittedH = wantH; _fittedW = wantW; ImGuiPanelHost.RequestSize(RynthAiFace.Title, new Vector2(wantW / place, wantH / place)); - // Applied after the size, clamped to the screen at it (the dashboard's MeasureAndFit does the same): - // a taller tab near the bottom of the screen moves the window up instead of running off it. + // A taller tab near the bottom of the screen moves the window up instead of running off it: the host + // pulls it onto the screen from its home at the new size (UI/PanelPlacement), and back once it fits. ImGuiPanelHost.RequestPos(RynthAiFace.Title, ImGuiNET.ImGui.GetWindowPos() / place); } diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs index ed5f847..7578ff2 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs @@ -429,7 +429,7 @@ internal sealed class DamageDetailFace : IImGuiPanel ? "Pull-away for every monster without its own. Default = Off (fight in place).\n" : "Pull-away for the monsters it covers. Default = the DEFAULT line's.\n") + "Off = kill where it stands. PullAway = tag, run until it has been dragged\n" + - "Kite Pull Distance metres from its lock spot (Settings > Melee Combat), then kill."); + "Kite Pull Distance metres from its lock spot (Settings > Combat), then kill."); // The DEFAULT line's own choice is the Prefer chip in the Damage panel's top bar. if (!isDefault) diff --git a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs index ec45794..d116623 100644 --- a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs +++ b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs @@ -212,7 +212,8 @@ internal sealed unsafe class LogFace : IImGuiPanel /// /// Tracker: the session-stat rows (TrackerSource) over an adjustable-opacity background, or text only -/// (TrackerSettings.TextOnly: bare, the rows shadowed, clicks pass through except over them). +/// (TrackerSettings.TextOnly: bare, the Ledger, clicks pass through except over it, or everywhere with +/// TrackerSettings.ClickThrough unless Ctrl is held). Rows can be hidden (the gear menu, TrackerSettings.Stats). /// internal sealed class TrackerFace : IImGuiPanel { @@ -220,20 +221,60 @@ internal sealed class TrackerFace : IImGuiPanel private static readonly Vector4 LabelColor = RynthTheme.Vec(0xFF999999); private static readonly uint ResetBg = RynthTheme.Argb(0xFF1A2E40); private static uint ResetBorder => RynthTheme.AccentFill; - // Text only: no background behind it, so brighter than the framed look, each with a shadow. - private static readonly uint BareLabel = RynthTheme.Argb(0xFFCFCFCF); - private static readonly uint BareValue = RynthTheme.Argb(0xFFFFFFFF); - private static readonly uint BareShadow = RynthTheme.Argb(0xD0000000); + + // Text only, the Ledger (2026-11-12, the owner: "something similar to how our Lua script works for + // item tracking ... no windows or background. Just text"; picked "Ledger", tinted, from the + // artifact "Bare Tracker"). Each label right-aligned beside its number, the rates, a gap, then the + // totals; numbers of a thousand and up shortened (3.12M, 148k); the rates tinted by what they + // count, deaths green at 0 and red above; every letter in a dark halo so it reads on any ground. + private static readonly uint LedgerLabel = RynthTheme.Argb(0xFFD8D8D8); + private static readonly uint LedgerValue = RynthTheme.Argb(0xFFFFFFFF); + private static readonly uint LedgerDim = RynthTheme.Argb(0xFFBDBDBD); + private static readonly uint LedgerXp = RynthTheme.Argb(0xFFEFC054); + private static readonly uint LedgerLum = RynthTheme.Argb(0xFF7FB9F9); + private static readonly uint LedgerKill = RynthTheme.Argb(0xFFF98075); + private static readonly uint LedgerPass = RynthTheme.Argb(0xFFC5ABF4); + private static readonly uint LedgerRad = RynthTheme.Argb(0xFF62D5C8); + private static readonly uint LedgerOk = RynthTheme.Argb(0xFF73D885); + // The halo: the four sides firm, the corners soft. + private static readonly uint HaloNear = RynthTheme.Argb(0xE6000000); + private static readonly uint HaloFar = RynthTheme.Argb(0x8C000000); + private static readonly Vector2[] HaloSides = { new(1, 0), new(-1, 0), new(0, 1), new(0, -1) }; + private static readonly Vector2[] HaloCorners = { new(1, 1), new(-1, -1), new(1, -1), new(-1, 1) }; + private const float LedgerGap = 8f, LedgerGroupGap = 5f, ToolsGap = 10f; + + // The Ledger's rows, worked out when the snapshot or the hidden set changes (not per frame). + private TrackerSnapshot? _ledgerFor; + private bool _ledgerBuilt; + private int _ledgerHiddenVersion; + private string[] _ledgerLabels = Array.Empty(), _ledgerValues = Array.Empty(); + private uint[] _ledgerColors = Array.Empty(); + private int _ledgerTotalsAt = -1; // the first shown total's row (the gap goes above it) private int _opacity; + private const string StatsMenuId = "##tracker_stats"; + private static readonly string AllHiddenText = "All stats hidden (" + PhosphorIcons.Gear + ")"; // Text only: the mouse is over what the last frame drew, so the window takes input (to drag it, or - // for the frame button); elsewhere clicks reach the game. A press that began there keeps it. + // for the buttons); elsewhere clicks reach the game. A press that began while it took input keeps it. + // With full click-through (TrackerSettings.ClickThrough) it takes input only while Ctrl is held. private bool _hot, _pressHot; /// Text only is bare: docked, no frame, title, background or grip (popped out it is framed as usual). public bool Bare => TrackerSettings.TextOnly; - public bool ClickThrough => Bare && !_hot && !_pressHot; + public bool ClickThrough + { + get + { + if (!Bare) return false; + if (_pressHot) return false; // a press of ours: keep the mouse until the button is up + if (!TrackerSettings.ClickThrough) return !_hot; + // Full click-through (2026-11-12): only Ctrl over the Ledger takes the mouse, and not in the + // middle of a press the game already has (Ctrl pressed while holding a game click). + if (!_hot || !ImGuiNET.ImGui.GetIO().KeyCtrl) return true; + return ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && !ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left); + } + } public void OnShown() { @@ -256,9 +297,10 @@ internal sealed class TrackerFace : IImGuiPanel } /// - /// Text only: each row's label and value with a 1 px shadow, nothing behind them. The rows are a - /// drag handle; the button at the end of the first row (faint until the mouse is on the rows) - /// brings the frame back. + /// Text only, the Ledger: each row's label right-aligned beside its number, in a dark halo, nothing + /// behind them. The rows are a drag handle. While the mouse is on them four small buttons show at + /// the end of the first row, Reset, click-through, the stats menu and the frame; the rest of the time + /// it is only the text. With full click-through the rows and buttons need Ctrl held. /// private void DrawTextOnly() { @@ -266,65 +308,233 @@ internal sealed class TrackerFace : IImGuiPanel Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); float width = Math.Max(60, ImGuiNET.ImGui.GetContentRegionAvail().X); Vector2 mouse = ImGuiNET.ImGui.GetIO().MousePos; - bool wasHot = _hot; + bool locked = TrackerSettings.ClickThrough; + // Whether the host gave this window the mouse this frame (the same test it made before Begin). + bool takingInput = !ClickThrough; + bool showTools = locked ? takingInput : _hot || _pressHot; - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - float rowH = ImGuiNET.ImGui.GetTextLineHeight() + 1; - float buttonW = rowH + 4; TrackerSnapshot? snap = UiSources.Tracker.Current?.Value; - string[]? values = snap?.Values; - string[] labels = snap?.Labels ?? TrackerSnapshot.DefaultLabels; + BuildLedger(snap); + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Narrow10)); ImFontPtr labelFont = ImGuiNET.ImGui.GetFont(); float labelSize = ImGuiNET.ImGui.GetFontSize(); - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono9)); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono10)); ImFontPtr valueFont = ImGuiNET.ImGui.GetFont(); float valueSize = ImGuiNET.ImGui.GetFontSize(); - float y = origin.Y; - for (int i = 0; i < labels.Length; i++) + float rowH = Math.Max(labelSize, valueSize) + 1; + float labelDrop = MathF.Round((valueSize - labelSize) * 0.6f); // the labels sit on the numbers' baseline + + float labelW = 0, valueW = 0; + for (int i = 0; i < _ledgerLabels.Length; i++) { - // The first row stops short of the frame button. - float right = origin.X + width - (i == 0 ? buttonW + 2 : 0); - Shadowed(dl, labelFont, labelSize, new Vector2(origin.X, y), BareLabel, labels[i]); - string value = values != null && i < values.Length ? values[i] : "—"; - float w = ImGuiNET.ImGui.CalcTextSize(value).X; - Shadowed(dl, valueFont, valueSize, new Vector2(Math.Max(origin.X, right - w), y), BareValue, value); + labelW = Math.Max(labelW, labelFont.CalcTextSizeA(labelSize, float.MaxValue, 0f, _ledgerLabels[i]).X); + valueW = Math.Max(valueW, valueFont.CalcTextSizeA(valueSize, float.MaxValue, 0f, _ledgerValues[i]).X); + } + float valueX = origin.X + MathF.Ceiling(labelW) + LedgerGap; + float y = origin.Y; + for (int i = 0; i < _ledgerLabels.Length; i++) + { + if (i == _ledgerTotalsAt && i > 0) y += LedgerGroupGap; + float lw = labelFont.CalcTextSizeA(labelSize, float.MaxValue, 0f, _ledgerLabels[i]).X; + Haloed(dl, labelFont, labelSize, new Vector2(MathF.Round(origin.X + labelW - lw), y + labelDrop), LedgerLabel, _ledgerLabels[i]); + Haloed(dl, valueFont, valueSize, new Vector2(valueX, y), _ledgerColors[i], _ledgerValues[i]); y += rowH; } ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.PopFont(); + float blockW = Math.Max(1, valueX + valueW - origin.X); float height = Math.Max(rowH, y - origin.Y); // The rows: a drag handle (the window has no title bar to hold). ImGuiNET.ImGui.SetCursorScreenPos(origin); - ImGuiNET.ImGui.InvisibleButton("##tracker_textonly_drag", new Vector2(Math.Max(1, width - buttonW - 2), height)); + ImGuiNET.ImGui.InvisibleButton("##tracker_textonly_drag", new Vector2(blockW, height)); ImGuiPanelHost.DragWindowWithLastItem(); if (ImGuiNET.ImGui.IsItemHovered() && !ImGuiNET.ImGui.IsItemActive()) - ImGuiNET.ImGui.SetTooltip("Drag to move the Tracker."); + ImGuiNET.ImGui.SetTooltip(locked ? "Ctrl-drag to move the Tracker (click-through is on)." : "Drag to move the Tracker."); - // Frame button: faint until the mouse is on the rows. - Vector2 bp = new(origin.X + width - buttonW, origin.Y); - ImGuiNET.ImGui.SetCursorScreenPos(bp); - float alpha = wasHot ? 1f : 0.35f; - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.Alpha, alpha); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(1, 0)); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, ResetBg); - if (ImGuiNET.ImGui.Button(PhosphorIcons.SquaresFour + "##tracker_frame", new Vector2(buttonW, rowH))) - TrackerSettings.SetTextOnly(false); - ImGuiNET.ImGui.SetItemTooltip("Show the Tracker's frame and background again."); - ImGuiNET.ImGui.PopStyleColor(); - ImGuiNET.ImGui.PopStyleVar(2); - ImGuiNET.ImGui.PopFont(); + // Reset, click-through, the stats menu and the frame, only while the mouse is on the Tracker + // (with click-through, while Ctrl is held there): at the end of the first row (inside the + // window when it is narrower than that). + float buttonW = rowH + 4; + const int ToolCount = 4; + float toolsW = ToolCount * buttonW + (ToolCount - 1) * 2; + float toolsX = Math.Max(origin.X, Math.Min(origin.X + blockW + ToolsGap, origin.X + width - toolsW)); + if (showTools) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); // the icons' font, as the framed look's buttons + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(1, 0)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, ResetBg); + var size = new Vector2(buttonW, rowH); + float x = toolsX; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, origin.Y)); + if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + "##tracker_reset", size)) + UiSources.Tracker.RequestReset(); + ImGuiNET.ImGui.SetItemTooltip("Reset the session stats"); + x += buttonW + 2; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, origin.Y)); + if (locked) ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, RynthTheme.AccentFill); + bool lockClicked = ImGuiNET.ImGui.Button((locked ? PhosphorIcons.Lock : PhosphorIcons.LockOpen) + "##tracker_clickthrough", size); + if (locked) ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.SetItemTooltip(locked ? ClickThroughOnTip : ClickThroughOffTip); + if (lockClicked) TrackerSettings.SetClickThrough(!locked); + x += buttonW + 2; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, origin.Y)); + if (ImGuiNET.ImGui.Button(PhosphorIcons.Gear + "##tracker_statsbtn", size)) + ImGuiNET.ImGui.OpenPopup(StatsMenuId); + ImGuiNET.ImGui.SetItemTooltip("Choose which stats the Tracker shows"); + x += buttonW + 2; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, origin.Y)); + if (ImGuiNET.ImGui.Button(PhosphorIcons.SquaresFour + "##tracker_frame", size)) + TrackerSettings.SetTextOnly(false); + ImGuiNET.ImGui.SetItemTooltip("Show the Tracker's frame again (its background and opacity)."); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopFont(); + } + DrawStatsMenu(); - // Hot for the next frame: the mouse over the rows or the button. - bool over = mouse.X >= origin.X && mouse.X <= origin.X + width && mouse.Y >= origin.Y && mouse.Y <= origin.Y + height; + // Hot for the next frame: the mouse over the rows, or over the buttons while they show. + bool overRows = mouse.X >= origin.X && mouse.X <= origin.X + blockW && mouse.Y >= origin.Y && mouse.Y <= origin.Y + height; + bool overTools = showTools && mouse.X >= origin.X + blockW && mouse.X <= toolsX + toolsW && mouse.Y >= origin.Y && mouse.Y <= origin.Y + rowH; + bool over = overRows || overTools; _hot = over; bool down = ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left); if (!down) _pressHot = false; - else if (over && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) _pressHot = true; + // Only a press this window took (a game click over the text never grabs the mouse mid-press). + else if (over && takingInput && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) _pressHot = true; } - private static void Shadowed(ImDrawListPtr dl, ImFontPtr font, float size, Vector2 p, uint color, string text) + private const string ClickThroughOffTip = + "Click-through: every click reaches the game, even over the numbers.\nHold Ctrl to move it or reach these buttons."; + private const string ClickThroughOnTip = + "Click-through is on: every click reaches the game, even over the numbers.\nHold Ctrl to move it or reach these buttons. Click to turn it off."; + + /// + /// The stats menu (2026-11-12, the owner: "a small settings menu to show/hide some of the stats"): a + /// box per row the Tracker can show, Show all, and click-through. Opened by the gear in either look. + /// + private static void DrawStatsMenu() { - dl.AddText(font, size, p + new Vector2(1, 1), BareShadow, text); + if (!ImGuiNET.ImGui.BeginPopup(StatsMenuId)) return; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + ImGuiNET.ImGui.TextColored(TitleColor, "Show on the Tracker"); + foreach (TrackerStat s in TrackerSettings.Stats) + { + bool shown = !TrackerSettings.IsHidden(s.Id); + ImGuiNET.ImGui.PushID(s.Id); + if (ImGuiNET.ImGui.Checkbox(s.Name, ref shown)) + TrackerSettings.SetHidden(s.Id, !shown); + if (s.Note != null) + ImGuiNET.ImGui.SetItemTooltip(s.Note); + ImGuiNET.ImGui.PopID(); + } + if (ImGuiNET.ImGui.Button("Show all")) + TrackerSettings.ShowAll(); + ImGuiNET.ImGui.Separator(); + bool clickThrough = TrackerSettings.ClickThrough; + if (ImGuiNET.ImGui.Checkbox("Click-through (text only)", ref clickThrough)) + TrackerSettings.SetClickThrough(clickThrough); + ImGuiNET.ImGui.SetItemTooltip("Text only, every click reaches the game, even over the numbers.\nHold Ctrl to move it or reach its buttons."); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.EndPopup(); + } + + /// + /// The Ledger's labels, numbers and colours for without the hidden rows; + /// only when the snapshot or the hidden set changed. Every row hidden leaves one dim line saying so. + /// + private void BuildLedger(TrackerSnapshot? snap) + { + int hiddenVersion = TrackerSettings.HiddenVersion; + if (_ledgerBuilt && ReferenceEquals(snap, _ledgerFor) && hiddenVersion == _ledgerHiddenVersion) return; + _ledgerBuilt = true; + _ledgerFor = snap; + _ledgerHiddenVersion = hiddenVersion; + string[] labels = snap?.Labels ?? TrackerSnapshot.DefaultLabels; + string[]? values = snap?.Values; + var names = new List(labels.Length); + var shownValues = new List(labels.Length); + var colors = new List(labels.Length); + int totalsFrom = Array.IndexOf(labels, "XP"); // the rates come before XP, the totals from it + _ledgerTotalsAt = -1; + for (int i = 0; i < labels.Length; i++) + { + if (TrackerSettings.IsLabelHidden(labels[i])) continue; + string value = values != null && i < values.Length ? values[i] : "—"; + // The gap goes above the first total shown, and only with a rate shown above it. + if (_ledgerTotalsAt < 0 && totalsFrom >= 0 && i >= totalsFrom) _ledgerTotalsAt = names.Count; + names.Add(LedgerName(labels[i])); + shownValues.Add(Shorten(value)); + colors.Add(LedgerColor(labels[i], value)); + } + if (names.Count == 0) + { + names.Add("TRACKER"); + shownValues.Add("all stats hidden"); + colors.Add(LedgerDim); + } + _ledgerLabels = names.ToArray(); + _ledgerValues = shownValues.ToArray(); + _ledgerColors = colors.ToArray(); + } + + /// The Ledger's name for a row: in capitals, with the framed look's abbreviations spelled out. + internal static string LedgerName(string label) => label switch + { + "Kls/hr" => "KILLS/HR", + "XP/kl" => "XP/KILL", + _ => label.ToUpperInvariant(), + }; + + /// + /// A number of a thousand and up as three figures and a unit (1.23k, 12.3k, 148k, 3.12M, 1.05B); + /// anything else (the session clock, a rate with a decimal, "max level", "—") as it is. + /// + internal static string Shorten(string value) + { + if (value.IndexOf(',') < 0 || !long.TryParse(value.Replace(",", ""), System.Globalization.NumberStyles.AllowLeadingSign, + System.Globalization.CultureInfo.InvariantCulture, out long n)) + return value; + string[] units = { "", "k", "M", "B", "T" }; + double x = n; + int u = 0; + while (Math.Abs(x) >= 1000 && u < units.Length - 1) { x /= 1000; u++; } + string s = Three(x); + if (Math.Abs(double.Parse(s, System.Globalization.CultureInfo.InvariantCulture)) >= 1000 && u < units.Length - 1) + { + x /= 1000; // 999,999 rounds to 1000k: one unit up instead + u++; + s = Three(x); + } + return s + units[u]; + + static string Three(double v) + { + double a = Math.Abs(v); + string format = a < 10 ? "0.##" : a < 100 ? "0.#" : "0"; + return v.ToString(format, System.Globalization.CultureInfo.InvariantCulture); + } + } + + /// A row's colour: the rates by what they count, deaths green at 0 and red above, the clock dim, totals white. + private static uint LedgerColor(string label, string value) => label switch + { + "Session" => LedgerDim, + "XP/hr" => LedgerXp, + "Lum/hr" or "Lum/5m" => LedgerLum, + "Kls/hr" => LedgerKill, + "Pass/hr" => LedgerPass, + "Rad/hr" => LedgerRad, + "Deaths" => value == "0" ? LedgerOk : LedgerKill, + _ => LedgerValue, + }; + + /// Text in a dark halo: the four sides firm, the corners soft, then the text. + private static void Haloed(ImDrawListPtr dl, ImFontPtr font, float size, Vector2 p, uint color, string text) + { + foreach (Vector2 o in HaloCorners) dl.AddText(font, size, p + o, HaloFar, text); + foreach (Vector2 o in HaloSides) dl.AddText(font, size, p + o, HaloNear, text); dl.AddText(font, size, p, color, text); } @@ -340,12 +550,14 @@ internal sealed class TrackerFace : IImGuiPanel ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - // Title row: [Tracker] [===slider===] [text only] [reset] + // Title row: [Tracker] [===slider===] [text only] [stats menu] [reset] ImGuiNET.ImGui.TextColored(TitleColor, "Tracker"); ImGuiNET.ImGui.SameLine(); float resetW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.ArrowCounterClockwise).X + 8; float textOnlyW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.TextAa).X + 8; - ImGuiNET.ImGui.SetNextItemWidth(Math.Max(10, ImGuiNET.ImGui.GetContentRegionAvail().X - resetW - textOnlyW - 8)); + float gearW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.Gear).X + 8; + float spacing = ImGuiNET.ImGui.GetStyle().ItemSpacing.X; + ImGuiNET.ImGui.SetNextItemWidth(Math.Max(10, ImGuiNET.ImGui.GetContentRegionAvail().X - resetW - textOnlyW - gearW - 8 - spacing)); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(2, 0)); if (ImGuiNET.ImGui.SliderInt("##opacity", ref _opacity, 0, 100, "")) TrackerSettings.SetBgAlpha((byte)Math.Round(_opacity * 2.55), save: false); @@ -363,9 +575,15 @@ internal sealed class TrackerFace : IImGuiPanel TrackerSettings.SetTextOnly(true); ImGuiNET.ImGui.EndDisabled(); ImGuiNET.ImGui.SetItemTooltip(canBare - ? "Text only: hide the frame and background, just the numbers (clicks pass through to the game).\nThe button at the end of its first row brings the frame back." + ? (TrackerSettings.ClickThrough + ? "Text only: just the numbers, no frame or background. Click-through is on: every click reaches the game,\neven over the numbers; hold Ctrl over them to move it or for its buttons (Reset, click-through, stats, frame)." + : "Text only: just the numbers, no frame or background (clicks pass through to the game except over the numbers).\nHover them for Reset, click-through, the stats menu and the button that brings the frame back.") : "Text only works while the Tracker is docked (not popped out)."); ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.Button(PhosphorIcons.Gear + "##stats")) + ImGuiNET.ImGui.OpenPopup(StatsMenuId); + ImGuiNET.ImGui.SetItemTooltip("Choose which stats the Tracker shows, and click-through for text only"); + ImGuiNET.ImGui.SameLine(); if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + "##reset")) UiSources.Tracker.RequestReset(); ImGuiNET.ImGui.SetItemTooltip("Reset the session stats"); @@ -380,8 +598,11 @@ internal sealed class TrackerFace : IImGuiPanel float grip = ImGuiPanelHost.BodyGripReserve; float gripTop = grip > 0 ? ImGuiNET.ImGui.GetWindowPos().Y + ImGuiNET.ImGui.GetWindowHeight() - grip : float.MaxValue; float rowH = ImGuiNET.ImGui.GetTextLineHeight(); + int drawn = 0; for (int i = 0; i < labels.Length; i++) { + if (TrackerSettings.IsLabelHidden(labels[i])) continue; + drawn++; float rowRight = ImGuiNET.ImGui.GetCursorPosX() + ImGuiNET.ImGui.GetContentRegionAvail().X; if (ImGuiNET.ImGui.GetCursorScreenPos().Y + rowH > gripTop) rowRight -= grip; SafeImGui.TextColored(LabelColor, labels[i]); @@ -396,6 +617,8 @@ internal sealed class TrackerFace : IImGuiPanel ImGuiNET.ImGui.TextUnformatted(value); ImGuiNET.ImGui.PopFont(); } + if (drawn == 0) + ImGuiNET.ImGui.TextDisabled(AllHiddenText); ImGuiNET.ImGui.PopFont(); float bottom = ImGuiNET.ImGui.GetCursorScreenPos().Y; @@ -403,5 +626,6 @@ internal sealed class TrackerFace : IImGuiPanel uint bg = RynthTheme.Argb(((uint)TrackerSettings.BgAlpha << 24) | 0x0A121A); dl.AddRectFilled(top, new Vector2(top.X + width, bottom), bg); dl.ChannelsMerge(); + DrawStatsMenu(); } } diff --git a/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs b/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs index 9a17ca1..a96f1ac 100644 --- a/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs @@ -165,7 +165,8 @@ internal sealed class PluginWindowFace : IImGuiPanel float screenW = ImGuiNET.ImGui.GetIO().DisplaySize.X / place; if (screenW > 1f) width = MathF.Min(width, screenW); ImGuiPanelHost.RequestSize(_title, new Vector2(width, height)); - // Clamped to the screen at the new size: near the right or bottom edge it moves in. + // Near the right or bottom edge it moves in at the new size: the host pulls it onto the screen + // from its home (UI/PanelPlacement; this spot is where it draws, so it changes nothing there). ImGuiPanelHost.RequestPos(_title, ImGuiNET.ImGui.GetWindowPos() / place); } else if (mouseUp && MathF.Abs(shownHeight - height) > 0.5f) diff --git a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs index 45ad766..d5700ee 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs @@ -953,7 +953,7 @@ internal sealed class RadarFace : IImGuiPanel /// /// "Hide the retail radar": RynthAi's own SuppressRetailRadar setting (RynthAi pushes it to the engine every - /// tick), the same switch as Settings > UI > Hide retail radar. This reads it from RynthAi's settings payload + /// tick), the same switch as Settings > Interface > Hide retail radar. This reads it from RynthAi's settings payload /// and saves it back through the same command, so the two always agree whichever is changed; saved with the /// character's RynthAi settings. Greyed out until RynthAi has answered. The box shows the new value at once, /// until RynthAi's answer catches up. @@ -976,7 +976,7 @@ internal sealed class RadarFace : IImGuiPanel } ImGuiNET.ImGui.EndDisabled(); if (ImGuiNET.ImGui.IsItemHovered()) - ImGuiNET.ImGui.SetTooltip("Hides the game's built-in radar (bezel, compass, coordinates, blips).\nThe same switch as RynthAi's Settings > UI > Hide retail radar: change it in either place."); + ImGuiNET.ImGui.SetTooltip("Hides the game's built-in radar (bezel, compass, coordinates, blips).\nThe same switch as Settings > Interface > Hide retail radar: change it in either place."); if (ra == null) { ImGuiNET.ImGui.SameLine(); diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs index 1206914..5b350ac 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -38,7 +38,7 @@ // Chromeless (like the Avalonia face): the title row is the drag surface. // // Size: the dashboard's panel text size (PanelTextScale.Get(Title): its own -// row in Settings > Display, else All Panels). The host draws the face with +// row in Settings > Interface, else All Panels). The host draws the face with // the fonts baked for that step (ImGuiFonts.CurrentStep, the nearest baked // one until a re-bake lands) and every box here is multiplied by that same // step's factor (Px), so text, icons and boxes grow together; size 0 is the @@ -176,7 +176,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel /// /// Switches the dashboard between its Modern (compact) and Classic (retail) looks: the title bar - /// buttons of either look and Settings > Display. The window refits on the next frame. AC thread. + /// buttons of either look and Settings > Interface. The window refits on the next frame. AC thread. /// internal static void SwitchLook(bool classic) => RynthAiDashboardState.SetClassic(classic); @@ -289,8 +289,9 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (screenW > 1) width = MathF.Min(width, screenW); width = MathF.Max(width, MinWidth * _k); ImGuiPanelHost.RequestSize(Title, new Vector2(width, _contentHeight)); - // Applied after the size, clamped to the screen at it: a bigger dashboard near the right or - // bottom edge moves in rather than running off (saved with the new size, like the bar's clamp). + // A bigger dashboard near the right or bottom edge moves in rather than running off: the host + // pulls it onto the screen from its home at the new size (UI/PanelPlacement; the spot asked for + // here is where it draws, so it changes nothing), and the home stays the saved spot. ImGuiPanelHost.RequestPos(Title, ImGuiNET.ImGui.GetWindowPos() / place); } else if (_fit) @@ -422,7 +423,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel /// /// The title row's right-click popup: the dashboard's size (its panel text size, the same - /// setting as Settings > Display > RynthAi Dashboard, or All Panels until it is set on its own). + /// setting as Settings > Interface > RynthAi Dashboard, or All Panels until it is set on its own). /// private static void SizePopup() { diff --git a/src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs b/src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs index 334372e..98ad7ea 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs @@ -1,6 +1,6 @@ // ============================================================================ // RynthCore.Engine - ImGui/Panels/ServerPickSettingsUi.cs -// Settings > Diagnostics > Server: which server this character counts as. +// Settings > Game Client > Server: which server this character counts as. // // A picker (Auto, or one of the servers the engine knows: the built-in ones // and every server a loaded plugin declares), what is active and why, and the @@ -8,7 +8,7 @@ // the other plugins ask for that server's settings. Picking a server forces it // on and every other server off for this character (ServerSelectionStore); // the menus, the "servermenu" push and plugin API v85 follow on the next frame. -// Drawn by SettingsFace for the Diagnostics tab's ServerPick row, in its look. +// Drawn by SettingsFace for the Game Client tab's ServerPick row, in its look. // ============================================================================ using System; diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs index c117917..94d2f4a 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs @@ -73,7 +73,9 @@ internal sealed class SettingsFace : IImGuiPanel if (_requestedTab is { } wanted) { _requestedTab = null; - int idx = Array.FindIndex(SettingsSchema.Tabs, t => t.Name.Equals(wanted, StringComparison.OrdinalIgnoreCase)); + // FindTab also takes the names from before the 2026-11-11 regroup (Misc = General). + SettingsTab? found = SettingsSchema.FindTab(wanted); + int idx = found == null ? -1 : Array.IndexOf(SettingsSchema.Tabs, found); if (idx >= 0) _tab = idx; } @@ -107,6 +109,14 @@ internal sealed class SettingsFace : IImGuiPanel for (int i = 0; i < tabs.Length; i++) { string tabName = tabs[i].Name; + // A group's heading above its first tab (RynthCore · this PC, RynthAi · saved in the profile, Support). + if (tabs[i].Group is { } group) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, i == 0 ? 2 : 8)); + Vector2 gp = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddText(new Vector2(gp.X + 4, gp.Y), Mute, group); + ImGuiNET.ImGui.Dummy(new Vector2(0, ImGuiNET.ImGui.GetFontSize() + 1)); + } ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); ImGuiNET.ImGui.PushID(i); @@ -184,18 +194,18 @@ internal sealed class SettingsFace : IImGuiPanel // Tab icons by tab name (SettingsSchema); a tab not listed shows its name alone. private static readonly System.Collections.Generic.Dictionary TabIcons = new() { - ["Display"] = PhosphorIcons.Monitor, - ["UI"] = PhosphorIcons.AppWindow, + ["Interface"] = PhosphorIcons.AppWindow, + ["Game Client"] = PhosphorIcons.Monitor, ["Hotkeys"] = PhosphorIcons.Keyboard, - ["Misc"] = PhosphorIcons.DotsThree, + ["General"] = PhosphorIcons.SlidersHorizontal, ["Recharge"] = PhosphorIcons.BatteryCharging, - ["Melee Combat"] = PhosphorIcons.Sword, + ["Combat"] = PhosphorIcons.Sword, ["Spell Combat"] = PhosphorIcons.MagicWand, ["Ranges"] = PhosphorIcons.Ruler, ["Navigation"] = PhosphorIcons.SneakerMove, ["Buffing"] = PhosphorIcons.Sparkle, - ["Crafting"] = PhosphorIcons.Hammer, ["Looting"] = PhosphorIcons.Bag, + ["Inventory"] = PhosphorIcons.Backpack, ["Vendoring"] = PhosphorIcons.Storefront, ["Diagnostics"] = PhosphorIcons.Wrench, }; diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs index d2d23b0..98acf7c 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs @@ -14,9 +14,11 @@ // three vital maximums. // - Raise: "+1" raises one rank at once; the caret beside it drops down +10, // +100 and Max (each with its XP cost; Max asks first only when it spends -// over half the unassigned XP). PlayerTraining.Raise(defer) queues it for -// AC's main thread outside the ImGui frame; raise buttons stay locked until -// the new values arrive (or 5 s pass). Train (skill credits) always asks first. +// over half the unassigned XP, and says when it stops short of the top). +// PlayerTraining.Raise(defer) queues it for AC's main thread outside the +// ImGui frame; raise buttons stay locked until the new values arrive (or 5 s +// pass: then the panel says the server hasn't taken it). Train (skill +// credits) always asks first. // - Aelrynth only (ServerInfo.IsAelrynth): skill mastery from the SkillMastery // mod's /mastery-data reply (MasteryFeed). A crown badge with the mastery // points on trained rows that have any; the open row shows points, bonus, @@ -169,6 +171,11 @@ internal sealed partial class SkillsFace : IImGuiPanel private long _pendingUnassigned; private int _pendingCredits; private int _pendingVersion; + // The raise in flight (-1 key: a train), to tell the player when the server never took it. + private int _pendingKey = -1; + private uint _pendingRanks, _pendingSpent; + private long _pendingCost; + private string _pendingWhat = ""; private string _status = ""; private uint _statusColor; @@ -350,10 +357,19 @@ internal sealed partial class SkillsFace : IImGuiPanel Order(); } - if (_pending && (now > _pendingUntilMs - || (snap != null && snap.Version != _pendingVersion - && (snap.UnassignedXp != _pendingUnassigned || snap.SkillCredits != _pendingCredits)))) - _pending = false; + if (_pending) + { + if (snap != null && snap.Version != _pendingVersion + && (snap.UnassignedXp != _pendingUnassigned || snap.SkillCredits != _pendingCredits)) + _pending = false; + else if (now > _pendingUntilMs) + { + _pending = false; + // Only while the panel kept drawing (its numbers kept coming): not on a reopen much later. + if (now - _pendingUntilMs < 2000) NoteUnanswered(snap); + else _pendingKey = -1; + } + } // The open row's time-left text, once a second. if (second != _detailSecond && _byKey.TryGetValue(_expandedKey, out Row? open)) @@ -1278,14 +1294,17 @@ internal sealed partial class SkillsFace : IImGuiPanel } PlayerProgress s = _snap; long have = s.UnassignedXp; - int maxLeft = Math.Max(0, r.Table.Length - 1 - (int)Math.Min(r.Ranks, (uint)int.MaxValue)); - int affordable = SkillDat.Affordable(r.Table, r.Ranks, r.Spent, have); + MaxRaisePlan plan = TrainingCosts.PlanMax(r.Table, r.Ranks, r.Spent, have); + int maxLeft = plan.RanksLeft; + int affordable = plan.Ranks; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); float y = p.Y; MultiItem(r, s, "##m10", "+10", 10, maxLeft, have, p.X, ref y); MultiItem(r, s, "##m100", "+100", 100, maxLeft, have, p.X, ref y); - MultiItem(r, s, "##mmax", affordable > 0 ? $"Max (+{affordable})" : "Max", affordable, maxLeft, have, p.X, ref y); + // Max says when the XP doesn't reach the top ("+150 of 208"), and the tooltip how much more it needs. + string maxLabel = affordable <= 0 ? "Max" : plan.ReachesTop ? $"Max (+{affordable})" : $"Max (+{affordable} of {maxLeft})"; + MultiItem(r, s, "##mmax", maxLabel, affordable, maxLeft, have, p.X, ref y, plan); NextLine(p, y - p.Y); ImGuiNET.ImGui.PopFont(); } @@ -1296,7 +1315,8 @@ internal sealed partial class SkillsFace : IImGuiPanel } /// One drop-down line: label left, XP cost right; greyed with the reason when it can't act. - private void MultiItem(Row r, PlayerProgress s, string id, string label, int n, int maxLeft, long have, float x, ref float y) + private void MultiItem(Row r, PlayerProgress s, string id, string label, int n, int maxLeft, long have, float x, ref float y, + MaxRaisePlan plan = default) { const float h = 22; long cost = n > 0 && n <= maxLeft ? SkillDat.CostOf(r.Table!, r.Ranks, r.Spent, n) : -1; @@ -1319,7 +1339,10 @@ internal sealed partial class SkillsFace : IImGuiPanel right = Compact(cost) + " XP"; ok = !_pending && PlayerTraining.Available; why = $"Raise {r.Name} {r.Base} → {r.Base + n} for {cost:N0} XP" - + (isMax && cost * 2 > have ? " (asks first: over half your unassigned XP)" : ""); + + (isMax && cost * 2 > have ? " (asks first: over half your unassigned XP)" : "") + + (isMax && !plan.ReachesTop && plan.Missing > 0 + ? $"\nThe top rank is {maxLeft} ranks away and costs {plan.CostToTop:N0} XP: {plan.Missing:N0} more than you have." + : ""); } var pos = new Vector2(x, y); var size = new Vector2(MultiW - 6, h); @@ -1403,6 +1426,12 @@ internal sealed partial class SkillsFace : IImGuiPanel Label(cost >= 0 && cost <= have ? $"Unassigned: {have:N0} → {have - cost:N0}" : $"Unassigned: {have:N0} (not enough)", Mute); + if (n < maxLeft && cost >= 0) + { + long toTop = SkillDat.CostOf(table, r.Ranks, r.Spent, maxLeft); + int gap = maxLeft - n; + Label($"Stops {gap} rank{(gap == 1 ? "" : "s")} short of the top: that needs {Math.Max(0L, toTop - have):N0} more XP.", Amber); + } ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9); ImGuiNET.ImGui.PushFont(f9); Label("That is more than half of your unassigned XP. Spent XP can't be taken back.", Dim); @@ -1458,7 +1487,7 @@ internal sealed partial class SkillsFace : IImGuiPanel { if (PlayerTraining.TrainSkill(r.Stype, (uint)r.TrainCost, defer: true)) { - MarkPending(s); + MarkPending(s, null, 0); SetStatus($"Sent: train {r.Name} for {Credits(r.TrainCost)}.", Teal); } else @@ -1467,16 +1496,42 @@ internal sealed partial class SkillsFace : IImGuiPanel } } - private void MarkPending(PlayerProgress s) + /// Locks the buttons until the server answers; is the raise's row (null for a train). + private void MarkPending(PlayerProgress s, Row? raised, long cost) { _pending = true; _pendingUntilMs = Environment.TickCount64 + 5000; _pendingUnassigned = s.UnassignedXp; _pendingCredits = s.SkillCredits; _pendingVersion = s.Version; + _pendingKey = raised?.Key ?? -1; + _pendingRanks = raised?.Ranks ?? 0; + _pendingSpent = raised?.Spent ?? 0; + _pendingCost = cost; + _pendingWhat = raised?.Name ?? ""; PlayerProgressHooks.RefreshSoon(); } + /// + /// The 5 s lock ran out with nothing changed. ACE turns a raise down without a word (more XP + /// than it thinks is left to the top, or than you have), so say so here and log the numbers + /// the raise was worked out from. + /// + private void NoteUnanswered(PlayerProgress? snap) + { + int key = _pendingKey; + _pendingKey = -1; + if (key < 0 || snap == null || !_byKey.TryGetValue(key, out Row? r) || r.Table == null) return; + if (r.Ranks != _pendingRanks || r.Spent != _pendingSpent || snap.UnassignedXp != _pendingUnassigned) return; + SetStatus($"{_pendingWhat}: the server hasn't taken the raise ({_pendingCost:N0} XP) after 5 s; nothing was spent.", Red); + RynthLog.Compat($"Skills panel: {_pendingWhat} raise for {_pendingCost:N0} XP got no answer in 5 s " + + $"(rank {r.Ranks}, XP spent {r.Spent:N0}, unassigned {snap.UnassignedXp:N0}, class {RowClass(r, snap)}, " + + $"top rank {r.Table.Length - 1} at {r.Table[^1]:N0} XP)"); + } + + private static uint RowClass(Row r, PlayerProgress s) => + r.Kind == RowKind.Skill && r.Stype <= PlayerProgress.MaxSkill ? s.SkillClass[r.Stype] : 0; + /// /// Raises ranks at once: the XP is worked out from the current /// snapshot, checked against the unassigned XP and the top rank, then queued for AC's @@ -1500,7 +1555,9 @@ internal sealed partial class SkillsFace : IImGuiPanel uint stype = r.Kind == RowKind.Vital ? r.Stype * 2 - 1 : r.Stype; // vitals by their maximum if (PlayerTraining.Raise(kind, stype, (uint)cost, defer: true)) { - MarkPending(s); + RynthLog.Compat($"Skills panel: raise {r.Name} +{n} from rank {r.Ranks} (XP spent {r.Spent:N0}, " + + $"unassigned {s.UnassignedXp:N0}) for {cost:N0} XP"); + MarkPending(s, r, cost); SetStatus($"Sent: raise {r.Name} +{n} for {cost:N0} XP.", Teal); } else diff --git a/src/RynthCore.Engine/ImGui/RynthTheme.cs b/src/RynthCore.Engine/ImGui/RynthTheme.cs index 043a21f..66c6856 100644 --- a/src/RynthCore.Engine/ImGui/RynthTheme.cs +++ b/src/RynthCore.Engine/ImGui/RynthTheme.cs @@ -6,7 +6,7 @@ // (ImGui.GetColorU32 order) built from the Avalonia #AARRGGBB literals. // // Colour themes (Tom 2026-10-14): the structural colours come from a palette -// the player can change in Settings > Display: a preset (RynthCore, Ember, +// the player can change in Settings > Interface: a preset (RynthCore, Ember, // Verdant, Amethyst, Crimson, Slate, and since 2026-10-21 Brass, Volt and // Ivory, the instrument dashboard's three) or their own eight colours (accent, // highlight, background, title bars, buttons, borders, text, muted text). @@ -277,7 +277,7 @@ internal static class RynthTheme public static readonly uint RadarGripIdle = Argb(0x400A121A); public static readonly uint RadarGripHover = Argb(0xA00A121A); - // ── Choosing a theme (Settings > Display) ─────────────────────────── + // ── Choosing a theme (Settings > Interface) ─────────────────────────── // // Three kinds of theme (Tom 2026-10-22: a new preset must never cost a player the colours they // made, and players can keep their own schemes): diff --git a/src/RynthCore.Engine/ImGui/ThemeSchemes.cs b/src/RynthCore.Engine/ImGui/ThemeSchemes.cs index 9cccc84..4a59d72 100644 --- a/src/RynthCore.Engine/ImGui/ThemeSchemes.cs +++ b/src/RynthCore.Engine/ImGui/ThemeSchemes.cs @@ -4,7 +4,7 @@ // save their color schemes"): named sets of the theme's eight colours, one // file each in %AppData%\RynthCore\themes\ ("name=", then the eight colours // as theme.txt writes them), for the PC, so every client lists the same ones. -// RynthTheme puts them in Settings > Display's Theme picker between the +// RynthTheme puts them in Settings > Interface's Theme picker between the // presets and Custom; "Save colours as" adds one, Delete removes the one in // use. // diff --git a/src/RynthCore.Engine/ImGui/VideoPatchBanner.cs b/src/RynthCore.Engine/ImGui/VideoPatchBanner.cs index 828d176..6c3ca90 100644 --- a/src/RynthCore.Engine/ImGui/VideoPatchBanner.cs +++ b/src/RynthCore.Engine/ImGui/VideoPatchBanner.cs @@ -14,7 +14,7 @@ namespace RynthCore.Engine.ImGuiBackend; internal static class VideoPatchBanner { private const string Line1 = "Rendering paused (video patch: all)"; - private const string Line2 = "Type /rc video off, or Settings > Misc > Video patch"; + private const string Line2 = "Type /rc video off, or Settings > Game Client > Video patch"; private static readonly uint Back = RynthTheme.Argb(0xC0101820); private static uint Border => RynthTheme.Border; diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs index a3f2177..f29c555 100644 --- a/src/RynthCore.Engine/ImGui/Win32Backend.cs +++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs @@ -712,7 +712,7 @@ internal static unsafe class Win32Backend // GetAsyncKeyState reads the physical key whatever window has focus: without // the focus test, Insert (or Shift/Ctrl+Insert paste/copy) pressed in another // client or app flipped this client's capture off unseen. Not while typing in - // RynthChat: there Shift/Ctrl+Insert are paste/copy. Opt-in (Settings > Display, + // RynthChat: there Shift/Ctrl+Insert are paste/copy. Opt-in (Settings > Hotkeys, // EngineSettings.InsertReleasesUi): off, Insert does nothing. if (insertDown && !_insertWasDown && _hasFocus && !ChatCaptureActive && Plugins.EngineSettings.InsertReleasesUi) diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index f0d9f60..49b7bab 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -41,13 +41,13 @@ internal static class EngineSettings private static bool _serverMessageStream = true; private static bool _flightRecorder = true; private static bool _insertReleasesUi; - // Settings > Display: strip AC window chrome while windowed (default off). + // Settings > Game Client: strip AC window chrome while windowed (default off). private static bool _borderlessWindowed; - // Settings > Display: reopen Rynth panels where they were (default on: panels have always been remembered). + // Settings > Interface: reopen Rynth panels where they were (default on: panels have always been remembered). private static bool _rememberWindowLayout = true; - // Settings > Display: each character keeps its own panel layout (default on; off = the one shared layout). + // Settings > Interface: each character keeps its own panel layout (default on; off = the one shared layout). private static bool _panelLayoutPerCharacter = true; - // Settings > Display: save and restore the AC window's own position and size (default off, opt-in). + // Settings > Game Client: save and restore the AC window's own position and size (default off, opt-in). private static bool _rememberAcWindowPosition; // "LoadAllServerPlugins": hand-set only, written back only when true (PluginManifestGate). private static bool _loadAllServerPlugins; @@ -288,7 +288,7 @@ internal static class EngineSettings /// its "The server has disconnected" screen (UIFlow mode Disconnected, only a Quit Game /// button), the engine closes the client a few seconds later the way the window's close /// button does (Compatibility/ServerDisconnectClose.cs), so a launcher's auto-relaunch can - /// bring it back. Off: the client stays on that screen. Set in game in Settings > Misc. + /// bring it back. Off: the client stays on that screen. Set in game in Settings > Game Client. public static bool CloseOnServerDisconnect { get @@ -416,7 +416,7 @@ internal static class EngineSettings /// "InsertReleasesUi" in engine.json (default false, 2026-10-08): Insert hands the /// mouse to the game (the UI/GAME toggle, Win32Backend), for clicking through a Rynth window. /// Off, Insert does nothing: a stray press left every Rynth text box unable to keep the - /// keyboard, which read as "can't type in Rynth". Set in game in Settings > Display. + /// keyboard, which read as "can't type in Rynth". Set in game in Settings > Hotkeys. public static bool InsertReleasesUi { get @@ -436,7 +436,7 @@ internal static class EngineSettings /// "BorderlessWindowed" in engine.json (default false, 2026-10-18): strip the AC /// window caption and thick frame while staying windowed. Exclusive fullscreen is left alone, /// and chrome is only ever given back to a window this setting stripped (AcWindowChrome). - /// Set in game in Settings > Display. From SilentKelpie's PR 6. + /// Set in game in Settings > Game Client. From SilentKelpie's PR 6. public static bool BorderlessWindowed { get @@ -458,7 +458,7 @@ internal static class EngineSettings /// "RememberWindowLayout" in engine.json (default true: Rynth panels have always been /// remembered). Off: panel_state.txt is not overwritten and open panels are not reopened from /// the last session. Does not touch the AC window itself (RememberAcWindowPosition). - /// Set in game in Settings > Display. + /// Set in game in Settings > Interface. public static bool RememberWindowLayout { get @@ -498,7 +498,7 @@ internal static class EngineSettings /// "RememberAcWindowPosition" in engine.json (default false, opt-in): save the Asheron's /// Call window's position and size per character and put it back at the next login. - /// Set in game in Settings > Display. + /// Set in game in Settings > Game Client. public static bool RememberAcWindowPosition { get @@ -535,7 +535,7 @@ internal static class EngineSettings /// the player logs out / reaches character select instead of reloading mid-session, for at most /// . A reload asked for by hand (ERl, the bar RL button, /// /rc rl, the hotkey) is never held. A workaround for CoreCLR re-init crashes on stacked - /// mid-session reloads. Only a true is written to the file. Set in game in Settings > Misc. + /// mid-session reloads. Only a true is written to the file. Set in game in Settings > Game Client. public static bool HoldReloadInWorld { get diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index bb69de1..41c2253 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -934,13 +934,19 @@ internal struct RynthCoreAPI /// without the client opening its dialog: Yes when the server's "N percent" is at least /// minPercent (or minPercent is 0), else No. One-shot. timeoutMs <= 0 disarms. /// 1 armed/disarmed, 0 sender or game-event hook unavailable, -3 bad arguments - /// (type 0, minPercent outside 0-100, timeout over 120 s). Any thread. Requires API v85+. + /// (type 0, minPercent outside 0-100, timeout over 120 s). Any thread. Requires API v85+. + /// v97: minPercent | 0x100 (ConfirmationArmPolicy.ArmFlagLeaveBelow, minimum 1-100) arms a second, + /// sticky slot: a prompt below the minimum (or without a percent) is left to the client instead of + /// answered No, and the arm stays armed for later prompts until it times out or is disarmed (the + /// flag with timeoutMs <= 0). The one-shot slot goes first; its arm and disarm never touch the + /// sticky one. Older engines return -3 for the flag. public IntPtr ArmConfirmationFn; /// v85: int GetLastConfirmation(uint* type, uint* contextId, int* percent, int* outcome, int* ageMs): /// the last prompt the server sent: returns its sequence number (0 = none yet); percent -1 /// when the text has none; outcome 1 shown to the player, 2 answered Yes, 3 answered No, - /// 4 the send failed (shown). Any out pointer may be null. Any thread. Requires API v85+. + /// 4 the send failed (shown), 5 (v97) answered Yes by the sticky arm. Any out pointer may be null. + /// Any thread. Requires API v85+. public IntPtr GetLastConfirmationFn; /// v86: int GetServerStateJson(byte* buffer, int capacity): which server this is, @@ -1037,7 +1043,7 @@ internal struct RynthCoreAPI public IntPtr AcPanelFn; /// v90: int PanelScale(const char* key, int percent): how big a frameless window draws /// itself, 30-250% of normal (0 asks, -1 = follow the text size again); returns it, 0 = follows the - /// text size. Settings > UI > Toolbar sets it too. Any thread. Requires API v90+. + /// text size. Settings > Interface > In The Retail Toolbar's Place sets it too. Any thread. Requires API v90+. public IntPtr PanelScaleFn; /// v90: uint DropTarget(const char* window, float x0, float y0, float x1, float y1, int flags, /// int* dragging): the plugin window takes items dragged out of AC's UI and let go over that rect diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index d13120b..bbe7930 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -58,5 +58,18 @@ internal static class PluginContractVersion /// The API version that added the "barMenu" manifest key; a plugin declaring it pins its own copy against this. public const uint BarMenu = 95; - public const uint Current = 95; + // v96: RESERVED for another contributor's request slot (jump-loot resend); not used here. + // v97: no table change. ArmConfirmation takes ConfirmationArmPolicy.ArmFlagLeaveBelow (0x100) OR'ed into + // minPercent: a second, sticky slot. A prompt at or above its minimum is answered Yes, one below it (or + // without a percent) is left to the client's dialog instead of answered No, and the arm stays armed for + // the next prompt until it times out (120 s at most) or is disarmed (the flag with timeoutMs <= 0). The + // v85 one-shot slot goes first, and a one-shot arm or disarm never touches the sticky one. Outcome 5 + // (AcceptedSticky): the sticky arm said Yes (RynthAi's "Auto-confirm crafting", 2026-11-11). Engines + // before v97 refuse the flag as bad arguments (-3), so a plugin fails cleanly there. The SDK's + // HasConfirmationLeaveBelow / ArmConfirmationLeaveBelow / DisarmConfirmationLeaveBelow. PROVISIONAL like + // 94 and 95 (feature/auto-confirm-craft): whichever merges second renumbers (never onto 96). + /// The API version whose ArmConfirmation takes the leave-below (sticky) flag. + public const uint ConfirmationLeaveBelow = 97; + + public const uint Current = 97; } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 9bd837d..c3b92e3 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -4281,14 +4281,32 @@ internal static partial class PluginManager // RynthCore's chat draws this line in it; the chat type still decides where it goes. long now = Environment.TickCount64; uint? own = UI.Data.ChatOwnColors.TakeArmed(now); - if (own != null && !string.IsNullOrEmpty(text)) - UI.Data.ChatOwnColors.Lines.Expect(text, chatType, own.Value, now); + // And colour runs ("nextspans", 2026-11-11): every run must fit inside this text, or none is used. + UI.Data.ChatSpan[]? spans = UI.Data.ChatOwnColors.TakeArmedSpans(now); + if (spans != null && !string.IsNullOrEmpty(text)) + { + spans = UI.Data.ChatOwnColors.FitSpans(spans, UI.Data.ChatOwnColorQueue.Key(text).Length, out string? why); + if (why != null) LogChatSpansRefused($"WriteToChat: colour runs dropped, {why}"); + } + bool noted = (own != null || spans != null) && !string.IsNullOrEmpty(text); + if (noted) + UI.Data.ChatOwnColors.Lines.Expect(text!, chatType, own, spans, now); bool written = ClientHelperHooks.WriteToChat(text, chatType); - if (!written && own != null && !string.IsNullOrEmpty(text)) - UI.Data.ChatOwnColors.Lines.Forget(text, chatType); + if (!written && noted) + UI.Data.ChatOwnColors.Lines.Forget(text!, chatType); return ToAbiBool(written); } + private static int _chatSpansRefused; + + /// A plugin's bad colour runs: the first few, then one in a hundred (a plugin bug could send one per line). + private static void LogChatSpansRefused(string why) + { + int n = Interlocked.Increment(ref _chatSpansRefused); + if (n <= 5 || n % 100 == 0) + RynthLog.Warn($"RynthCore.Chat nextspans: {why} (#{n}; the line keeps its own colour)"); + } + private static int InvokeChatParser(IntPtr textUtf16) { string? text = textUtf16 != IntPtr.Zero ? Marshal.PtrToStringUni(textUtf16) : null; @@ -4934,7 +4952,10 @@ internal static partial class PluginManager { string? action = actionAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(actionAnsi) : null; string? value = valueAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(valueAnsi) : null; - return UI.Data.ChatOwnColors.HandlePluginCommand(action, value, Environment.TickCount64) ? 1 : 0; + bool ok = UI.Data.ChatOwnColors.HandlePluginCommand(action, value, Environment.TickCount64, out string? why); + if (!ok && why != null) + LogChatSpansRefused($"refused '{(value is { Length: > 120 } ? value[..120] + "..." : value)}': {why}"); + return ok ? 1 : 0; } IntPtr export = ResolvePluginExport(name, "RynthPluginApplyRemoteCommand"); diff --git a/src/RynthCore.Engine/ReloadInWorldGate.cs b/src/RynthCore.Engine/ReloadInWorldGate.cs index 94c5e78..b512a3b 100644 --- a/src/RynthCore.Engine/ReloadInWorldGate.cs +++ b/src/RynthCore.Engine/ReloadInWorldGate.cs @@ -9,7 +9,7 @@ // This gate waits with the old engine still mapped until the player is out of the world. // // Differences from the PR, all the owner's decisions: -// - OFF by default: engine.json "HoldReloadInWorld" (Settings > Misc, "Hold reloads while in +// - OFF by default: engine.json "HoldReloadInWorld" (Settings > Game Client, "Hold reloads while in // the world"). Off, nothing here runs and a reload behaves exactly as before. // - A reload asked for by hand (ERl, the bar RL button, /rc rl, the hotkey) is never held; // only automatic ones (the file watcher, an engine deploy) are. diff --git a/src/RynthCore.Engine/UI/AcWindowChrome.cs b/src/RynthCore.Engine/UI/AcWindowChrome.cs index 0ba24a6..350fd4d 100644 --- a/src/RynthCore.Engine/UI/AcWindowChrome.cs +++ b/src/RynthCore.Engine/UI/AcWindowChrome.cs @@ -1,6 +1,6 @@ // ============================================================================ // RynthCore.Engine - UI/AcWindowChrome.cs -// Settings > Display helpers for the Asheron's Call game HWND: +// Settings > Game Client helpers for the Asheron's Call game HWND: // - Borderless windowed: strip caption / thick frame while leaving the client // windowed (not exclusive fullscreen). Chrome is only given back to a window // WE stripped: that is recorded as an HWND property (SetProp) holding the @@ -99,7 +99,7 @@ internal static class AcWindowChrome } } - /// A Settings > Display toggle changed: apply it on the game thread soon (not inline). + /// A Settings > Game Client toggle changed: apply it on the game thread soon (not inline). public static void RequestApply() { try @@ -256,7 +256,7 @@ internal static class AcWindowChrome } } - /// Settings > Display "Save Layout Now". Runs on the render thread (a button in a + /// Settings > Interface "Save Layout Now". Runs on the render thread (a button in a /// frame): everything that touches a file is queued to the background writer. public static void SaveLayoutNow() { diff --git a/src/RynthCore.Engine/UI/AcWindowChromePolicy.cs b/src/RynthCore.Engine/UI/AcWindowChromePolicy.cs index 1cb786c..45a33e2 100644 --- a/src/RynthCore.Engine/UI/AcWindowChromePolicy.cs +++ b/src/RynthCore.Engine/UI/AcWindowChromePolicy.cs @@ -1,6 +1,6 @@ // ============================================================================ // RynthCore.Engine - UI/AcWindowChromePolicy.cs -// The decisions behind Settings > Display for the Asheron's Call window, as pure +// The decisions behind Settings > Game Client for the Asheron's Call window, as pure // functions (no HWND, no engine state) so tools\EngineSettingsTests can run them: // - Borderless windowed: what to do given the setting, the "we stripped it" marker // and the window's current style bits. diff --git a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs index 86e0c65..a2da693 100644 --- a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs +++ b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs @@ -1513,7 +1513,7 @@ internal class RynthOverlayWindow : Window { try { - // Settings > Display "Remember Open Windows and Positions" (default on). + // Settings > Interface "Remember Open Windows and Positions" (default on). // Off: leave panels closed so a hand-arranged layout is not forced back. if (!Plugins.EngineSettings.RememberWindowLayout) return; diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index a8fc7c3..69b7adf 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -165,12 +165,15 @@ internal sealed unsafe class ChatSource : UiSource if (dto.Seq <= _sinceSeq) continue; _sinceSeq = dto.Seq; string text = StripAcLinks(dto.Text ?? "", out string? linkedName); + // A plugin's own colour for it (ChatOwnColors), matched by the text as AC printed it, + // and its own colour runs (offsets into that text: kept only while it's unchanged). + uint? ownArgb = ChatOwnColors.Lines.Take(dto.Text, dto.Type, Environment.TickCount64, out ChatSpan[]? ownSpans); var line = new ChatLine(_nextId++, dto.Ts ?? "", dto.Chan ?? "Other", dto.Type, dto.Sender is { Length: > 0 } s ? StripAcLinks(s, out _) : linkedName, text) { Seq = dto.Seq, - // A plugin's own colour for it (ChatOwnColors), matched by the text as AC printed it. - OwnArgb = ChatOwnColors.Lines.Take(dto.Text, dto.Type, Environment.TickCount64), + OwnArgb = ownArgb, + OwnSpans = ChatOwnColors.ArrivedSpans(ownSpans, dto.Text, text), }; line.Route = router.Evaluate(line, null); if (line.Route.Mention) ChatModel.PumpMentionSound(); diff --git a/src/RynthCore.Engine/UI/Data/ChatOwnColors.cs b/src/RynthCore.Engine/UI/Data/ChatOwnColors.cs index 63d3e26..a2e4273 100644 --- a/src/RynthCore.Engine/UI/Data/ChatOwnColors.cs +++ b/src/RynthCore.Engine/UI/Data/ChatOwnColors.cs @@ -22,6 +22,24 @@ // (RynthChat not loaded, the chat face closed for a long time, AC refused the // line) are forgotten after LineTtlMs, and at most MaxLines are kept. // +// Colours per part of the line (2026-11-11, "nextspans"): a player asked for +// RynthAi's one-line item info with its name, armour, spells, value ... each +// in a colour of its own. The same one-shot way, on the same channel (no API +// change): +// SendPluginCommand("RynthCore.Chat", "nextspans", "start:length:RRGGBB;...") +// arms colour runs for the next WriteToChat on this thread. The payload is +// 1..MaxSpans entries "start:length:RRGGBB" joined by ';': start and length +// are plain decimal UTF-16 offsets into the text the plugin then writes +// (length >= 1), the colour six hex digits ('#' in front allowed); entries in +// increasing order and not overlapping. Anything else is refused (answers 0, +// nothing armed, a log line); "" / "none" disarms (answers 1, so a plugin can +// ask whether the engine has this). At WriteToChat a run that doesn't fit +// inside the text drops all of them (logged). Text outside every run keeps +// the line's colour (nextcolor's, else as usual), so a plugin sends nextcolor +// first as the fallback: an engine without nextspans answers 0 to it and the +// line still shows in that one colour. A rule's line colour wins over the +// runs, a rule's match colour over the run it overlaps (EffectiveSpans). +// // Pure (no engine state), so tools/ChatFilterTests compiles it in. // ============================================================================ @@ -41,7 +59,8 @@ internal sealed class ChatOwnColorQueue /// AC's longest incoming chat line (ChatCallbackHooks.MaxIncomingChatChars): a longer line arrives cut. public const int MaxArrivingChars = 1024; - private readonly record struct Entry(string Text, int ChatType, uint Argb, long AtMs); + // Argb 0 = no whole-line colour (only runs). + private readonly record struct Entry(string Text, int ChatType, uint Argb, ChatSpan[]? Spans, long AtMs); private readonly object _lock = new(); private readonly LinkedList _lines = new(); @@ -53,15 +72,21 @@ internal sealed class ChatOwnColorQueue public static string Key(string text) => text.TrimEnd('\r', '\n'); /// The plugin is about to write as , drawn in . - public void Expect(string text, int chatType, uint argb, long nowMs) + public void Expect(string text, int chatType, uint argb, long nowMs) => Expect(text, chatType, argb, null, nowMs); + + /// + /// As above, with an optional whole-line colour and optional colour runs (offsets into + /// , checked by ). Nothing to note when both are null. + /// + public void Expect(string text, int chatType, uint? argb, ChatSpan[]? spans, long nowMs) { string key = Key(text); - if (key.Length == 0) return; + if (key.Length == 0 || (argb == null && spans == null)) return; lock (_lock) { Expire(nowMs); while (_lines.Count >= MaxLines) _lines.RemoveFirst(); - _lines.AddLast(new Entry(key, chatType, argb | 0xFF000000, nowMs)); + _lines.AddLast(new Entry(key, chatType, argb is uint a ? a | 0xFF000000 : 0u, spans, nowMs)); Volatile.Write(ref _count, _lines.Count); } } @@ -86,8 +111,12 @@ internal sealed class ChatOwnColorQueue /// The colour for an arriving line, or null: the oldest waiting entry with this text and chat /// type is used up. -1 (RynthChat before 0.2.0) matches any type. /// - public uint? Take(string? text, int chatType, long nowMs) + public uint? Take(string? text, int chatType, long nowMs) => Take(text, chatType, nowMs, out _); + + /// As above; gets the entry's colour runs (null when none). + public uint? Take(string? text, int chatType, long nowMs, out ChatSpan[]? spans) { + spans = null; if (Count == 0 || string.IsNullOrEmpty(text)) return null; string key = Key(text); lock (_lock) @@ -102,7 +131,8 @@ internal sealed class ChatOwnColorQueue if (!same) continue; _lines.Remove(n); Volatile.Write(ref _count, _lines.Count); - return e.Argb; + spans = e.Spans; + return e.Argb != 0 ? e.Argb : null; } Volatile.Write(ref _count, _lines.Count); return null; @@ -127,13 +157,44 @@ internal static class ChatOwnColors public static readonly ChatOwnColorQueue Lines = new(); + /// "start:length:RRGGBB;...": colour runs for the next WriteToChat on this thread; "" / "none" disarms. + public const string NextSpansAction = "nextspans"; + /// At most this many runs in one "nextspans". + public const int MaxSpans = 32; + /// A longer "nextspans" payload is refused. + public const int MaxPayloadChars = 1024; + /// A run's start or length above this is refused (no line is that long; keeps the sums small). + public const int MaxOffset = 100_000; + [ThreadStatic] private static uint t_armed; // 0 = none (an armed colour is always opaque) [ThreadStatic] private static long t_armedAtMs; + [ThreadStatic] private static ChatSpan[]? t_armedSpans; + [ThreadStatic] private static long t_spansAtMs; /// The command. True when it was understood (the plugin then knows the engine has this). - public static bool HandlePluginCommand(string? action, string? value, long nowMs) + public static bool HandlePluginCommand(string? action, string? value, long nowMs) => + HandlePluginCommand(action, value, nowMs, out _); + + /// + /// As above; says why a "nextspans" payload was refused (the engine + /// logs it), null otherwise. + /// + public static bool HandlePluginCommand(string? action, string? value, long nowMs, out string? error) { - if (!string.Equals((action ?? "").Trim(), NextColorAction, StringComparison.OrdinalIgnoreCase)) return false; + error = null; + string act = (action ?? "").Trim(); + if (string.Equals(act, NextSpansAction, StringComparison.OrdinalIgnoreCase)) + { + string sv = (value ?? "").Trim(); + t_armedSpans = null; + if (sv.Length == 0 || sv.Equals("none", StringComparison.OrdinalIgnoreCase)) return true; + ChatSpan[]? spans = ParseSpans(sv, out error); + if (spans == null) return false; + t_armedSpans = spans; + t_spansAtMs = nowMs; + return true; + } + if (!string.Equals(act, NextColorAction, StringComparison.OrdinalIgnoreCase)) return false; string v = (value ?? "").Trim(); if (v.Length == 0 || v.Equals("none", StringComparison.OrdinalIgnoreCase)) { @@ -155,4 +216,141 @@ internal static class ChatOwnColors t_armed = 0; return nowMs - t_armedAtMs <= ArmWindowMs ? armed : null; } + + /// This thread's armed colour runs, used up (null when none, or armed too long ago). + public static ChatSpan[]? TakeArmedSpans(long nowMs) + { + ChatSpan[]? armed = t_armedSpans; + if (armed == null) return null; + t_armedSpans = null; + return nowMs - t_spansAtMs <= ArmWindowMs ? armed : null; + } + + /// + /// A "nextspans" payload as runs (sorted, not overlapping, opaque colours), or null with + /// saying why. Strict: see the file header. + /// + public static ChatSpan[]? ParseSpans(string? payload, out string? error) + { + error = null; + string p = (payload ?? "").Trim(); + if (p.Length == 0) { error = "empty"; return null; } + if (p.Length > MaxPayloadChars) { error = $"longer than {MaxPayloadChars} characters"; return null; } + string[] parts = p.Split(';'); + if (parts.Length > MaxSpans) { error = $"more than {MaxSpans} runs"; return null; } + var spans = new ChatSpan[parts.Length]; + int prevEnd = 0; + for (int i = 0; i < parts.Length; i++) + { + string[] f = parts[i].Trim().Split(':'); + if (f.Length != 3) { error = $"run {i + 1} '{parts[i]}' is not start:length:RRGGBB"; return null; } + if (!TryOffset(f[0], out int start) || !TryOffset(f[1], out int length) || length < 1) + { + error = $"run {i + 1} '{parts[i]}': start and length must be whole numbers (length at least 1)"; + return null; + } + if (!TryHex6(f[2], out uint rgb)) { error = $"run {i + 1} '{parts[i]}': the colour must be RRGGBB"; return null; } + if (start < prevEnd) { error = $"run {i + 1} '{parts[i]}' starts before the run in front of it ends"; return null; } + spans[i] = new ChatSpan(start, length, rgb | 0xFF000000); + prevEnd = start + length; + } + return spans; + } + + private static bool TryOffset(string s, out int v) + { + v = 0; + if (s.Length == 0 || s.Length > 6) return false; + foreach (char c in s) + { + if (c < '0' || c > '9') return false; + v = v * 10 + (c - '0'); + } + return v <= MaxOffset; + } + + private static bool TryHex6(string s, out uint rgb) + { + rgb = 0; + if (s.StartsWith('#')) s = s[1..]; + if (s.Length != 6) return false; + foreach (char c in s) + { + int d = c >= '0' && c <= '9' ? c - '0' + : c >= 'a' && c <= 'f' ? c - 'a' + 10 + : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; + if (d < 0) return false; + rgb = (rgb << 4) | (uint)d; + } + return true; + } + + /// + /// The runs, when every one fits inside a line characters long + /// (its text as noted, ); else null and why. + /// + public static ChatSpan[]? FitSpans(ChatSpan[]? spans, int textLength, out string? error) + { + error = null; + if (spans == null) return null; + foreach (ChatSpan s in spans) + if (s.Start < 0 || s.Length < 1 || s.Start + s.Length > textLength) + { + error = $"run {s.Start}:{s.Length} is outside the {textLength}-character line"; + return null; + } + return spans; + } + + /// + /// The runs for a line as RynthChat's copy arrived: as it came, + /// as the chat keeps it (AC's tell links taken out). Offsets only + /// hold when the two are the same text, so otherwise none; a line AC cut short keeps the + /// runs (or the parts of them) inside what arrived. + /// + public static ChatSpan[]? ArrivedSpans(ChatSpan[]? spans, string? arrivedText, string shownText) + { + if (spans == null) return null; + string shown = ChatOwnColorQueue.Key(shownText); + if (ChatOwnColorQueue.Key(arrivedText ?? "") != shown) return null; + List? cut = null; + for (int i = 0; i < spans.Length; i++) + { + ChatSpan s = spans[i]; + if (s.Start + s.Length <= shown.Length) { cut?.Add(s); continue; } + if (cut == null) { cut = new List(spans.Length); for (int k = 0; k < i; k++) cut.Add(spans[k]); } + if (s.Start < shown.Length) cut.Add(new ChatSpan(s.Start, shown.Length - s.Start, s.Argb)); + } + if (cut == null) return spans; + return cut.Count > 0 ? cut.ToArray() : null; + } + + /// + /// The runs a line is drawn with: the rules' match colours () over + /// the plugin's own (), cut around them. A rule's whole-line colour + /// () wins over the plugin's runs, as it does over its line + /// colour. Sorted, not overlapping (given sorted, non-overlapping inputs). Called when a line + /// is measured, never per frame. + /// + public static ChatSpan[]? EffectiveSpans(ChatSpan[]? ownSpans, ChatSpan[]? ruleSpans, bool ruleLineColour) + { + if (ownSpans == null || ownSpans.Length == 0 || ruleLineColour) return ruleSpans; + if (ruleSpans == null || ruleSpans.Length == 0) return ownSpans; + var result = new List(ownSpans.Length + ruleSpans.Length * 2); + foreach (ChatSpan s in ownSpans) + { + int a = s.Start, b = s.Start + s.Length; + foreach (ChatSpan r in ruleSpans) + { + int ra = r.Start, rb = r.Start + r.Length; + if (rb <= a || ra >= b) continue; + if (ra > a) result.Add(new ChatSpan(a, ra - a, s.Argb)); + a = Math.Max(a, rb); + } + if (b > a) result.Add(new ChatSpan(a, b - a, s.Argb)); + } + result.AddRange(ruleSpans); + result.Sort((x, y) => x.Start.CompareTo(y.Start)); + return result.ToArray(); + } } diff --git a/src/RynthCore.Engine/UI/Data/ChatRouting.cs b/src/RynthCore.Engine/UI/Data/ChatRouting.cs index 65b06ac..8decf42 100644 --- a/src/RynthCore.Engine/UI/Data/ChatRouting.cs +++ b/src/RynthCore.Engine/UI/Data/ChatRouting.cs @@ -56,6 +56,10 @@ internal sealed class ChatLine /// The colour the plugin that wrote the line asked for (RynthAi's Info text colour; /// ChatOwnColors), or null. Below a rule's line colour, above the kind / tab / retail ones. public uint? OwnArgb { get; init; } + /// Colour runs the plugin that wrote the line asked for (RynthAi's per-part item info + /// colours; ChatOwnColors "nextspans"): offsets into Text, sorted, not overlapping, or null. + /// The rest of the line keeps its colour; a rule's colours win (ChatOwnColors.EffectiveSpans). + public ChatSpan[]? OwnSpans { get; init; } /// "HH:mm:ss text": copy, log and the Avalonia face. public string FormattedText { get; } diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index e463bd2..f26680c 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -47,6 +47,9 @@ internal sealed class RynthAiSettings public bool? RearmAfterVitals { get; set; } public bool StartMacroOnLogin { get; set; } public bool PatrolOnLogin { get; set; } + // RynthAi's Hunt On Login (2026-11-11). Nullable: a RynthAi without it doesn't send it, and then the row is + // hidden and nothing is sent back. One or the other with Patrol On Login (RynthAi's LoginAutoStart). + public bool? HuntOnLogin { get; set; } // RynthAi's Resume Meta After Reload (2026-11-07). Nullable: an older RynthAi doesn't send it, // and then the row is hidden and nothing is sent back. public bool? ResumeMetaOnReload { get; set; } @@ -77,10 +80,18 @@ internal sealed class RynthAiSettings public float MagicArcVelocity { get; set; } = 40f; public int BlacklistAttempts { get; set; } = 3; public int BlacklistTimeoutSec { get; set; } = 30; - // Not shown in the panel, but carried so a save doesn't send them missing. + // Combat > Targeting > Cast Settle (ms) (a row since 2026-11-11) and Ranges > Disengage Range. public int BlacklistCastSettleMs { get; set; } = 1500; public int MonsterDisengageRange { get; set; } - // Ranges > Combat Targeting. Null until RynthAi sends them; an older RynthAi leaves them alone. + // Combat > Weapon Swaps (2026-11-11: RynthAi had them, the panel didn't). Null until RynthAi sends them; + // a save sends null back, which RynthAi leaves alone. OffhandDefault is RynthAi's spelling: Auto, Shield, + // Weapon or None. + public int? WeaponSwapSettleMs { get; set; } + public int? WeaponSwapMinHealthPct { get; set; } + public int? WeaponSwapMinGainPct { get; set; } + public bool? PreferDualWield { get; set; } + public string? OffhandDefault { get; set; } + // Combat > Targeting. Null until RynthAi sends them; an older RynthAi leaves them alone. public int? TargetSelection { get; set; } public bool? TargetLock { get; set; } // Fight the monster I select (RynthAi 2026-11-01). Null: a RynthAi without it; it leaves it alone. @@ -129,6 +140,12 @@ internal sealed class RynthAiSettings public int MeleeAttackHeight { get; set; } = 1; public int MissileAttackPower { get; set; } = -1; public int MissileAttackHeight { get; set; } = 1; + // RynthAi's Dirty Fighting rotation (2026-11-11; its Dirty Fighting window, /ra dfheight): on/off, the order + // the effects are put on ("HML" and the like) and the height once all three are on (0 Low, 1 Medium, 2 High, + // -1 the Attack Height setting). Null until RynthAi sends them; a save then sends null, which it leaves alone. + public bool? DfHeightRotation { get; set; } + public string? DfHeightOrder { get; set; } + public int? DfDefaultHeight { get; set; } public bool UseNativeAttack { get; set; } = true; public bool SummonPets { get; set; } public int PetMinMonsters { get; set; } = 1; @@ -245,6 +262,10 @@ internal sealed class RynthAiSettings // RynthAi's unticked prots and banes (buff base names). Null = never received from RynthAi: // sent back as null, which RynthAi reads as "unchanged". public System.Collections.Generic.List? DisabledBuffs { get; set; } + // Buffing's Idle Margin (minutes) and Skip buffs this character can't use (rows since 2026-11-11). + // Null until RynthAi sends them (0 is a real margin); a save sends null back, which RynthAi leaves alone. + public int? RebuffIdleMarginMinutes { get; set; } + public bool? SkipUnusableBuffs { get; set; } public int BuffMinSkillLevelTier1 { get; set; } = 35; public int BuffMinSkillLevelTier2 { get; set; } = 85; public int BuffMinSkillLevelTier3 { get; set; } = 135; @@ -265,6 +286,13 @@ internal sealed class RynthAiSettings public bool LootJumpEnabled { get; set; } public bool LootChestsMacroOff { get; set; } = true; // Pickup with macro off; a RynthAi that doesn't send it leaves it on public bool LootChestsMacroOffLeaveOpen { get; set; } // its "Leave the chest open", off by default + // Looting rows since 2026-11-11, null until RynthAi sends them (a save then sends null, which RynthAi + // leaves alone): Loot Mode (0 the loot profile, 1 rares and needed mana stones only), the Item Tool's + // chest relock wait (s), and Loot By Name (names separated by |, and the radius in yards). + public int? LootMode { get; set; } + public int? ChestRelockWaitSec { get; set; } + public string? LootByNames { get; set; } + public float? LootByNameRadius { get; set; } public int LootJumpHeight { get; set; } = 10; public int LootOwnership { get; set; } // Recover your own death corpse whole (default on), and travel back to it after a death @@ -575,7 +603,8 @@ internal sealed record SettingRow( public string[] CurrentItems => ItemsNow?.Invoke() ?? Items ?? Array.Empty(); } -internal sealed record SettingsTab(string Name, SettingRow[] Rows); +/// A Settings tab. : a heading the sidebar draws above this tab (the tabs below it, to the next one, are that group). +internal sealed record SettingsTab(string Name, SettingRow[] Rows, string? Group = null); internal static class SettingsSchema { @@ -629,6 +658,46 @@ internal static class SettingsSchema private static bool HasVariablePower(RynthAiSettings s) => s.VariablePowerMin.HasValue; private static bool HasEnvironmentThrottle(RynthAiSettings s) => s.EnvironmentImpactLimit.HasValue; private static bool HasKite(RynthAiSettings s) => s.KitePullMeters.HasValue; + private static bool HasWeaponSwaps(RynthAiSettings s) => s.WeaponSwapMinGainPct.HasValue; + private static bool HasDfRotation(RynthAiSettings s) => s.DfHeightRotation.HasValue; + // RynthAi's DirtyFightingHeights.OrderChoices, and the labels its Dirty Fighting window shows. + public static readonly string[] DfOrders = { "HML", "HLM", "MHL", "MLH", "LHM", "LMH" }; + private static readonly string[] DfOrderLabels = + { "High, Medium, Low", "High, Low, Medium", "Medium, High, Low", "Medium, Low, High", "Low, High, Medium", "Low, Medium, High" }; + // RynthAi's DfDefaultHeight -1..2, shown in this order (index = value + 1). + private static readonly string[] DfDefaultLabels = { "Attack Height setting", "Low", "Medium", "High" }; + private static int DfOrderIndex(string? order) + { + int i = Array.FindIndex(DfOrders, o => string.Equals(o, order, StringComparison.OrdinalIgnoreCase)); + return i < 0 ? 0 : i; + } + private static bool HasLootByName(RynthAiSettings s) => s.LootByNames != null; + // RynthAi's Loot.LootModes, in its order. + public static readonly string[] LootModeNames = { "Profile", "Rares and needed mana stones only" }; + // RynthAi's OffhandDefault values (OffhandRules.SettingValue), shown as they are. + public static readonly string[] OffhandDefaults = { "Auto", "Shield", "Weapon", "None" }; + private static int OffhandIndex(string? value) + { + int i = Array.FindIndex(OffhandDefaults, v => string.Equals(v, value, StringComparison.OrdinalIgnoreCase)); + return i < 0 ? 0 : i; + } + + // The tab names before the 2026-11-11 regroup, so "/rc settings misc" and a plugin's older link still land. + private static readonly Dictionary OldTabNames = new(StringComparer.OrdinalIgnoreCase) + { + ["Display"] = "Interface", ["UI"] = "Interface", ["Misc"] = "General", + ["Melee Combat"] = "Combat", ["Melee"] = "Combat", ["Crafting"] = "Combat", + }; + + /// The tab called (any case), or the tab an old name's rows went to; null if none. + public static SettingsTab? FindTab(string name) + { + name = name.Trim(); + SettingsTab? tab = Array.Find(Tabs, t => t.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + if (tab == null && OldTabNames.TryGetValue(name, out string? now)) + tab = Array.Find(Tabs, t => t.Name.Equals(now, StringComparison.OrdinalIgnoreCase)); + return tab; + } public static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" }; public static readonly string[] NavLabelModes = { "Off", "Numbers", "Numbers and names" }; public static readonly string[] DunPatrolCoverages = { "Whole dungeon", "Loops only", "Everything", "Sweep (by sight)" }; @@ -760,7 +829,7 @@ internal static class SettingsSchema private static SettingRow ChatButton(string label, string buttonText, string command, string? tip = null) => Button(label, buttonText, () => RynthAiCommands.ApplyRemoteCommand("sendchat", command), tip); - // A button that asks first (Settings > Display's layout reset): Click runs once the player confirms. + // A button that asks first (Settings > Interface's layout reset): Click runs once the player confirms. private static SettingRow ConfirmButton(string label, string buttonText, Func confirm, Action click, string? tip = null) => new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click, Confirm: confirm); @@ -839,54 +908,15 @@ internal static class SettingsSchema public static readonly SettingsTab[] Tabs = { - new("Display", new[] + // ── RynthCore · this PC: how Rynth looks and the game client (stored by the engine, mostly) ── + new("Interface", new[] { - Bool("Show Target Stamina / Mana", s => s.ShowTargetStaminaMana, (s, v) => s.ShowTargetStaminaMana = v, - "When enabled, displays stamina and mana bars for the selected target (requires appraisal data)."), + Section("Look"), // Stored with the dashboard's state (RynthAiDashboardState), not in the RynthAi profile. Combo("RynthAi Dashboard Look", DashboardLooks, _ => RynthAiDashboardState.Classic ? 1 : 0, (_, v) => ImGuiBackend.Panels.RynthAiFace.SwitchLook(v == 1), "Modern: the compact dashboard. Classic: a retail-style window with tabs (Main, Monsters, Gear, Buffs,\nRoute, Loot, Meta, Tuning), drawn with the game's own pictures. Also: the button on either look's title bar."), - // Stored in engine.json for every client (EngineSettings), not in the RynthAi profile. - Bool("Insert Key Releases the UI", _ => Plugins.EngineSettings.InsertReleasesUi, - (_, v) => { Plugins.EngineSettings.InsertReleasesUi = v; if (!v) ImGuiBackend.Win32Backend.ReclaimUi(); }, - "On: Insert switches between UI and GAME (shown on the RynthCore bar). In GAME, clicks pass through\nRynth windows to the game and Rynth text boxes can't be typed in. Press Insert again to get the UI back.\nOff (default): Insert does nothing. Applies to all your clients; others pick it up when they start."), - Bool("Borderless Windowed", _ => Plugins.EngineSettings.BorderlessWindowed, - (_, v) => - { - Plugins.EngineSettings.BorderlessWindowed = v; - AcWindowChrome.RequestApply(); // applied from the game thread, not inside this frame - }, - "On: hide the Asheron's Call window title bar and borders while staying windowed (exclusive fullscreen is left alone).\nOff (default): normal window chrome. Turning it off only gives back the chrome this setting removed.\nApplies to all your clients; others pick it up when they start."), - Spacer(), - Section("Window and HUD Layout"), - Bool("Remember Open Windows and Positions", _ => Plugins.EngineSettings.RememberWindowLayout, - (_, v) => Plugins.EngineSettings.RememberWindowLayout = v, - "On (default): reopen Rynth panels where you left them.\nOff: do not overwrite the saved panel layout or reopen panels from the last session. Applies to all your clients."), - // Stored in engine.json for every client (EngineSettings); the layouts themselves by UI/PanelLayout. - Bool("Panel Layout Per Character", _ => Plugins.EngineSettings.PanelLayoutPerCharacter, - (_, v) => Plugins.EngineSettings.PanelLayoutPerCharacter = v, - "On (default): each character keeps its own panel places (docked, popped out, the bar, plugin windows),\nso clients on this PC no longer move each other's panels. A new character starts from the default layout.\nOff: every client shares one layout, as before. /rc layout shows the files in use.\nThis client switches at once; your other clients when they start."), - // Whose layout is in use and its folder (/rc layout's first line, short). - Status(_ => PanelLayout.SettingsLine()), - Button("Layout for New Characters", "Use this character's", () => PanelLayout.MakeDefaultFromSettings(), - "Make this character's panel layout the default that new characters start from (/rc layout default).\nCharacters that already have a layout keep their own; the button below puts one back to the default.") - with { VisibleWhen = _ => Plugins.EngineSettings.PanelLayoutPerCharacter }, - 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 }, - Bool("Remember Game Window Position", _ => Plugins.EngineSettings.RememberAcWindowPosition, - (_, v) => - { - Plugins.EngineSettings.RememberAcWindowPosition = v; - AcWindowChrome.RequestApply(); - }, - "On: save the Asheron's Call window's position and size for each character and put it back after you log in.\nOff (default): the game window is never moved. A saved spot that is off-screen (a monitor that is gone) is ignored."), - 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."), - Spacer(), // The colour theme is stored by the engine (theme.txt, ImGuiBackend.RynthTheme), not in the RynthAi profile. - Section("Colour Theme"), // The picker's list changes while the game runs (saved schemes), so it is asked each draw. new SettingRow(SettingKind.Combo, "Theme", "The colours of every RynthCore window: RynthCore's own, a preset, a scheme you saved, or Custom (your own colours).\n" + @@ -915,15 +945,6 @@ internal static class SettingsSchema Section("Text Size (in-game panels)"), Combo("All Panels", PanelTextScale.SizeNames, _ => PanelTextScale.GetAll(), (_, v) => PanelTextScale.SetAll(v), "The size of every in-game panel: 100% = normal, 10% a step.\nOne panel on its own: Ctrl+wheel over it (it then keeps its own size)."), - Combo("Toolbar", PanelTextScale.SizeNames, _ => PanelTextScale.GetChrome(), (_, v) => PanelTextScale.SetChrome(v), - "Size of the RynthCore icon bar (its icons and tooltips), separate from the panels: 0 = normal, each step 10% bigger.\nAlso: right-click the bar's grip, Ctrl+wheel over the bar, or /rc ui barsize."), - // The bar's rows are stored by the engine (panel_state.txt, ImGuiBar), not in the RynthAi profile. - Combo("Toolbar Rows", BarLayout.RowNames, _ => ImGuiBackend.ImGuiBar.Rows - BarLayout.MinRows, - (_, v) => ImGuiBackend.ImGuiBar.SetRowLayout(v + BarLayout.MinRows, ImGuiBackend.ImGuiBar.MaxPerRow), - "How many rows the RynthCore icon bar spreads its icons over (Icons Per Row can add more).\nAlso: right-click the bar's grip, or /rc ui barrows."), - Combo("Toolbar Icons Per Row", BarLayout.MaxPerRowNames, _ => BarLayout.MaxPerRowToIndex(ImGuiBackend.ImGuiBar.MaxPerRow), - (_, v) => ImGuiBackend.ImGuiBar.SetRowLayout(ImGuiBackend.ImGuiBar.Rows, BarLayout.IndexToMaxPerRow(v)), - "The most icons one row of the bar holds; more icons start another row. No limit: the rows share them evenly.\nAlso: right-click the bar's grip, or /rc ui baricons."), Bool("Size Each Panel Separately", _ => PanelTextScale.PerPanel, (_, v) => PanelTextScale.PerPanel = v, "Off: every panel uses All Panels. On: set each panel's text size below.", gates: true), TextSize("RynthAi Dashboard", "RynthAi"), @@ -942,16 +963,18 @@ internal static class SettingsSchema TextSize("Log", "Log"), TextSize("Tracker", "Tracker"), Spacer(), - Section("Item Info"), - Bool("Describe Items When Selected", s => s.ItemInfoOnSelect, (s, v) => s.ItemInfoOnSelect = v, - "Print a Mag-style description of an item in chat when you select it, identifying it\nfirst when needed. Items the bot selects while looting are skipped.\nAlso: /ra iteminfo on|off."), - Button("Item Info Options", "Open...", () => RynthAiCommands.ApplyRemoteCommand("iteminfo", "window"), - "Which fields the description shows, which item types are described on select, and its chat\ntype and text colour (/ra iteminfo window)."), - }), - - new("UI", new[] - { - Section("Radar"), + Section("RynthCore Toolbar"), + Combo("Toolbar", PanelTextScale.SizeNames, _ => PanelTextScale.GetChrome(), (_, v) => PanelTextScale.SetChrome(v), + "Size of the RynthCore icon bar (its icons and tooltips), separate from the panels: 0 = normal, each step 10% bigger.\nAlso: right-click the bar's grip, Ctrl+wheel over the bar, or /rc ui barsize."), + // The bar's rows are stored by the engine (panel_state.txt, ImGuiBar), not in the RynthAi profile. + Combo("Toolbar Rows", BarLayout.RowNames, _ => ImGuiBackend.ImGuiBar.Rows - BarLayout.MinRows, + (_, v) => ImGuiBackend.ImGuiBar.SetRowLayout(v + BarLayout.MinRows, ImGuiBackend.ImGuiBar.MaxPerRow), + "How many rows the RynthCore icon bar spreads its icons over (Icons Per Row can add more).\nAlso: right-click the bar's grip, or /rc ui barrows."), + Combo("Toolbar Icons Per Row", BarLayout.MaxPerRowNames, _ => BarLayout.MaxPerRowToIndex(ImGuiBackend.ImGuiBar.MaxPerRow), + (_, v) => ImGuiBackend.ImGuiBar.SetRowLayout(ImGuiBackend.ImGuiBar.Rows, BarLayout.IndexToMaxPerRow(v)), + "The most icons one row of the bar holds; more icons start another row. No limit: the rows share them evenly.\nAlso: right-click the bar's grip, or /rc ui baricons."), + Spacer(), + Section("Hide The Game's Own"), Bool("Hide retail radar", s => s.SuppressRetailRadar, (s, v) => s.SuppressRetailRadar = v, "Suppress the game's built-in radar (bezel, compass, coords, blips)."), // "Show RynthRadar" / "Radar Click-Through" and "Show RynthChat" / "Chat Click-Through" @@ -961,17 +984,21 @@ internal static class SettingsSchema // gear menus. "Hide retail chat" lives in the Chat panel's gear menu // ("Hide retail chat"). The four fields stay in the payload so RynthAi and the // engine keep round-tripping them whichever is newer. - Spacer(), - Section("Power Bar"), Bool("Hide retail power bar", s => s.SuppressRetailPowerbar, (s, v) => s.SuppressRetailPowerbar = v, "Hide the vanilla attack/magic power bar that appears under the cursor while charging.\nThe bar's underlying combat state still works — only the on-screen widget is hidden."), - Spacer(), - Section("Vitals"), // Stored by the engine (RetailVitalsHooks, %LOCALAPPDATA%\RynthCore\retail_ui.txt), // not in the RynthAi profile, so the settings object is ignored here. Bool("Hide retail vitals bar", _ => Compatibility.RetailVitalsHooks.HideRetailVitals, (_, v) => Compatibility.RetailVitalsHooks.HideRetailVitals = v, "Hide the game's own health/stamina/mana bars; the RynthVision player plate and the RynthAi dashboard show them.\nSaved for this PC. Also: /rc ui retailvitals on|off."), + // 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."), + Spacer(), + Section("Your Vitals"), + Bool("Show Target Stamina / Mana", s => s.ShowTargetStaminaMana, (s, v) => s.ShowTargetStaminaMana = v, + "When enabled, displays stamina and mana bars for the selected target (requires appraisal data)."), // RynthVision's own plate (2026-10-27: players couldn't find how to move it). The same setting as // Vision > Nameplates > Your plate > Lock position, stored by the engine (nameplate_settings.txt). Bool("Lock your vitals plate", _ => SelfPlateLocked(), (_, v) => SetSelfPlateLocked(v), @@ -991,11 +1018,7 @@ internal static class SettingsSchema when: _ => ImGuiBackend.Hud.HudFeed.VisionInstalled && ImGuiBackend.Hud.MonsterHudSettings.Loaded && !ImGuiBackend.Hud.MonsterHudSettings.SelfPlate), Spacer(), - Section("Toolbar"), - // 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."), + Section("In The Retail Toolbar's Place"), // RynthDefective's windows in its place (plugin windows the engine hosts, API v90): shown or // not (the panel's open state, remembered with the layout) and their size (the window's own // text size, as Ctrl+wheel over it sets). Only while a plugin hosts them. @@ -1019,14 +1042,46 @@ internal static class SettingsSchema WindowSize("Shortcut bar 3 size", ExtraShortcutsWindow(3)), WindowShown("Shortcut bar 4", ExtraShortcutsWindow(4), ExtraShortcutsTip(4)), WindowSize("Shortcut bar 4 size", ExtraShortcutsWindow(4)), - }), + Spacer(), + Section("Window Layout"), + Bool("Remember Open Windows and Positions", _ => Plugins.EngineSettings.RememberWindowLayout, + (_, v) => Plugins.EngineSettings.RememberWindowLayout = v, + "On (default): reopen Rynth panels where you left them.\nOff: do not overwrite the saved panel layout or reopen panels from the last session. Applies to all your clients."), + // Stored in engine.json for every client (EngineSettings); the layouts themselves by UI/PanelLayout. + Bool("Panel Layout Per Character", _ => Plugins.EngineSettings.PanelLayoutPerCharacter, + (_, v) => Plugins.EngineSettings.PanelLayoutPerCharacter = v, + "On (default): each character keeps its own panel places (docked, popped out, the bar, plugin windows),\nso clients on this PC no longer move each other's panels. A new character starts from the default layout.\nOff: every client shares one layout, as before. /rc layout shows the files in use.\nThis client switches at once; your other clients when they start."), + // Whose layout is in use and its folder (/rc layout's first line, short). + Status(_ => PanelLayout.SettingsLine()), + Button("Layout for New Characters", "Use this character's", () => PanelLayout.MakeDefaultFromSettings(), + "Make this character's panel layout the default that new characters start from (/rc layout default).\nCharacters that already have a layout keep their own; the button below puts one back to the default.") + with { VisibleWhen = _ => Plugins.EngineSettings.PanelLayoutPerCharacter }, + 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 }, + 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"), - // The user hotkeys: stored by the engine for the PC (Hotkeys/HotkeyService.cs, hotkeys.txt), - // not in the RynthAi profile; the ImGui face draws the whole editor for this one row. - new("Hotkeys", new[] { new SettingRow(SettingKind.Hotkeys, "Hotkeys") }), - - new("Misc", new[] + new("Game Client", new[] { + Section("Game Window"), + Bool("Borderless Windowed", _ => Plugins.EngineSettings.BorderlessWindowed, + (_, v) => + { + Plugins.EngineSettings.BorderlessWindowed = v; + AcWindowChrome.RequestApply(); // applied from the game thread, not inside this frame + }, + "On: hide the Asheron's Call window title bar and borders while staying windowed (exclusive fullscreen is left alone).\nOff (default): normal window chrome. Turning it off only gives back the chrome this setting removed.\nApplies to all your clients; others pick it up when they start."), + Bool("Remember Game Window Position", _ => Plugins.EngineSettings.RememberAcWindowPosition, + (_, v) => + { + Plugins.EngineSettings.RememberAcWindowPosition = v; + AcWindowChrome.RequestApply(); + }, + "On: save the Asheron's Call window's position and size for each character and put it back after you log in.\nOff (default): the game window is never moved. A saved spot that is off-screen (a monitor that is gone) is ignored."), + Spacer(), + Section("Performance"), Bool("Enable FPS Limit", s => s.EnableFPSLimit, (s, v) => s.EnableFPSLimit = v, gates: true), Int("Focused FPS", s => s.TargetFPSFocused, (s, v) => s.TargetFPSFocused = v, 10, 240, 1, when: s => s.EnableFPSLimit), Int("Background FPS", s => s.TargetFPSBackground, (s, v) => s.TargetFPSBackground = v, 5, 60, 1, when: s => s.EnableFPSLimit), @@ -1043,12 +1098,6 @@ internal static class SettingsSchema "While the 3D world isn't drawn the client runs at most this many frames a second, so the\n" + "saved time is slept (0 = no extra cap). Saved for this PC. Also: /rc video fps .", when: _ => D3D9.VideoPatch.Mode != D3D9.VideoPatchMode.Off), - // Stored in engine.json for every client (EngineSettings), not in the RynthAi profile. - Bool("Close Client on Server Disconnect", _ => Plugins.EngineSettings.CloseOnServerDisconnect, - (_, v) => Plugins.EngineSettings.CloseOnServerDisconnect = v, - "On (default): when the game shows \"The server has disconnected\" (only a Quit Game button),\n" + - "the client closes itself 5 seconds later, so the launcher's auto-relaunch can start it again.\n" + - "A logout or a quit never shows that screen. Applies to all your clients; others pick it up when they start."), // Stored in engine.json for every client (EngineSettings.AutoIdMode, AutoIdPolicy). Combo("Background Identify", new[] { "All", "Limited", "Off" }, _ => (int)Plugins.EngineSettings.AutoIdMode, (_, v) => Plugins.EngineSettings.AutoIdMode = (Compatibility.AutoIdMode)Math.Clamp(v, 0, 2), @@ -1058,6 +1107,14 @@ internal static class SettingsSchema "items after 30 s, at most 5 a second. Unselected monsters' nameplates show no level.\n" + "Off: nothing in the background.\n" + "RynthAi's own identifies (loot, monster weaknesses) are never limited. Applies to all your clients. Also: /rc autoid."), + Spacer(), + Section("Disconnects And Updates"), + // Stored in engine.json for every client (EngineSettings), not in the RynthAi profile. + Bool("Close Client on Server Disconnect", _ => Plugins.EngineSettings.CloseOnServerDisconnect, + (_, v) => Plugins.EngineSettings.CloseOnServerDisconnect = v, + "On (default): when the game shows \"The server has disconnected\" (only a Quit Game button),\n" + + "the client closes itself 5 seconds later, so the launcher's auto-relaunch can start it again.\n" + + "A logout or a quit never shows that screen. Applies to all your clients; others pick it up when they start."), // Stored in engine.json for every client (EngineSettings.HoldReloadInWorld, ReloadInWorldGate); opt-in. Bool("Hold reloads while in the world", _ => Plugins.EngineSettings.HoldReloadInWorld, (_, v) => Plugins.EngineSettings.HoldReloadInWorld = v, @@ -1072,100 +1129,61 @@ internal static class SettingsSchema "How long a held reload waits for you to leave the world before it reloads anyway (default 10).", when: _ => Plugins.EngineSettings.HoldReloadInWorld), Spacer(), - Bool("Auto Cram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v, - "Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack.", - disabledWhen: s => s.AutoSortOn, disabledTip: CramOffForSortTip), - Bool("Peace Mode When Idle", s => s.PeaceModeWhenIdle, (s, v) => s.PeaceModeWhenIdle = v), - Bool("Weapons Back After Heals", s => s.RearmAfterVitals == true, (s, v) => s.RearmAfterVitals = v, - "After a heal, restam or remana spell with nothing to fight, put the last fight's weapons\n(main hand and off hand) back on instead of waiting for the next monster."), + Section("Server"), + new SettingRow(SettingKind.ServerPick, "Server", + "Which server this character counts as. Auto detects it (the connect host, the world name the server announces, RynthILT).\n" + + "Picking a server forces it on and every other server off, for this character; every plugin follows at once.\n" + + "Also: /rc server pick |auto, and /rc server for the list."), + Note("The list is every server the engine knows: the built-in ones and those declared by the loaded server plugins. \"Settings from\" is the plugin the others ask for that server's settings."), + }), + + // The user hotkeys: stored by the engine for the PC (Hotkeys/HotkeyService.cs, hotkeys.txt), + // not in the RynthAi profile; the ImGui face draws the whole editor for this one row. + new("Hotkeys", new[] + { + // Stored in engine.json for every client (EngineSettings), not in the RynthAi profile. + Bool("Insert Key Releases the UI", _ => Plugins.EngineSettings.InsertReleasesUi, + (_, v) => { Plugins.EngineSettings.InsertReleasesUi = v; if (!v) ImGuiBackend.Win32Backend.ReclaimUi(); }, + "On: Insert switches between UI and GAME (shown on the RynthCore bar). In GAME, clicks pass through\nRynth windows to the game and Rynth text boxes can't be typed in. Press Insert again to get the UI back.\nOff (default): Insert does nothing. Applies to all your clients; others pick it up when they start."), + Spacer(), + new SettingRow(SettingKind.Hotkeys, "Hotkeys"), + }), + + // ── RynthAi · saved in the character's profile ── + new("General", new[] + { + Section("Starting Up"), Bool("Start Macro On Login", s => s.StartMacroOnLogin, (s, v) => s.StartMacroOnLogin = v, "Automatically starts the macro when RynthAi loads."), - Bool("Patrol On Login", s => s.PatrolOnLogin, (s, v) => s.PatrolOnLogin = v, - "Automatically starts dungeon patrol when RynthAi loads."), + // Patrol On Login and Hunt On Login are one choice (RynthAi's LoginAutoStart.Exclusive): ticking one clears + // the other here too, so the panel shows what RynthAi will keep and the save sends both. + Bool("Patrol On Login", s => s.PatrolOnLogin, + (s, v) => { s.PatrolOnLogin = v; if (v && s.HuntOnLogin == true) s.HuntOnLogin = false; }, + "Automatically starts dungeon patrol when RynthAi loads.\nOne or the other: ticking it clears Hunt On Login.", + gates: true), + Bool("Hunt On Login", s => s.HuntOnLogin ?? false, + (s, v) => { s.HuntOnLogin = v; if (v) s.PatrolOnLogin = false; }, + "Starts the Outdoor Hunt from where you are once you're in the world (and the macro with it).\n" + + "In a dungeon, or without RynthNav: it doesn't start, and says why in chat.\n" + + "One or the other: ticking it clears Patrol On Login. Also: the Outdoor Hunt window, /ra hunt login on|off.", + when: s => s.HuntOnLogin.HasValue, gates: true), Bool("Resume Meta After Reload", s => s.ResumeMetaOnReload != false, (s, v) => s.ResumeMetaOnReload = v, "After a hot reload (RynthCore or RynthAi updated while you play), the meta carries on where it was:\n" + "the same state, its variables, the rules that had already fired, the call stack, the watchdog and\n" + "the route with its waypoint. Nothing in Default runs again, so a meta that recalls in Default doesn't recall.\n" + "A real login (or a changed meta file) still starts in Default. Off: every reload starts the meta in Default.", when: s => s.ResumeMetaOnReload != null), - Bool("Escape Acid and Lava", s => s.EscapeHazards, (s, v) => s.EscapeHazards = v, - "When acid or lava hurts you, stop everything (combat, buffs, healing, looting)\nand walk back out the way you came. The spot is remembered so the patrol avoids it.\nTurn off for a character that walks through acid on purpose."), Bool("Yield to VTank", s => s.YieldToVTank, (s, v) => s.YieldToVTank = v, "With Decal: when VTank's macro starts (/vt start), RynthAi's macro stops, and it won't start while VTank runs.\nOne bot per client. Without Decal this does nothing. Also: /ra vtankyield on|off."), - Bool("Enable Raycasting", s => s.EnableRaycasting, (s, v) => s.EnableRaycasting = v), - // The Server Features (ILT) rows went with the ILT Hub to RynthILT (2026-10-13): its world - // list and "Treat this world as ILT" are on the Mini Remote's Character tab (/ra hub servers). Spacer(), - Section("Missile Arc Velocities (m/s)"), - 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, - "Bow projectile speed (m/s). Lower = higher arc.", when: s => s.UseArcs), - Float("Crossbow", s => s.CrossbowArcVelocity, (s, v) => s.CrossbowArcVelocity = v, 10f, 80f, 0.5f, when: s => s.UseArcs), - Float("Atlatl", s => s.AtlatlArcVelocity, (s, v) => s.AtlatlArcVelocity = v, 10f, 60f, 0.5f, when: s => s.UseArcs), - Float("Magic Arc", s => s.MagicArcVelocity, (s, v) => s.MagicArcVelocity = v, 10f, 60f, 0.5f, - "Arc spells' horizontal speed (m/s). ACE: 40. Lower = higher arc.\nA monster rule with Arc on casts an arc only when this path reaches the target (walls, and ceilings in dungeons); otherwise its other shape (Streak, Blast) or a bolt. Needs Enable Raycasting. /ra lostest magic shows the arc to the selected mob."), - Float("Arc Clearance (m)", s => s.MissileArcClearance, (s, v) => s.MissileArcClearance = MathF.Max(0f, v), 0f, 3f, 0.1f, - "Extra headroom the arc must have at mid-flight. Raise it if arrows still hit ceilings; lower it if reachable mobs get skipped.", when: s => s.UseArcs), - Bool("LoS Debug Log", s => s.LosDebugLog, (s, v) => s.LosDebugLog = v, - "Log each blocked missile target and why (arc peak, where it hits) to the RynthCore log. /ra lostest bow tests the selected mob."), - Spacer(), - Section("Monster Blacklist"), - Int("Attempts Before Blacklist", s => s.BlacklistAttempts, (s, v) => s.BlacklistAttempts = v, 1, 20, 1, - "How many failed attack attempts on a mob before it gets blacklisted."), - Int("Blacklist Timeout (sec)", s => s.BlacklistTimeoutSec, (s, v) => s.BlacklistTimeoutSec = v, 5, 120, 5, - "How long a blacklisted mob is ignored before re-trying."), - Int("No Progress Timeout (sec)", s => s.TargetNoProgressTimeoutSec, (s, v) => s.TargetNoProgressTimeoutSec = v, 0, 300, 10, - "Blacklist a target after being engaged this many seconds without dealing damage.\n0 = disabled. Default 60s."), - Spacer(), - Section("Give Queue"), - Int("Give Interval (ms)", s => s.GiveQueueIntervalMs, (s, v) => s.GiveQueueIntervalMs = v, 50, 2000, 50, - "Minimum delay between each item sent by /ra givea commands."), - }), - - new("Recharge", new[] - { - Section("In Combat — target within Monster Range (%)"), - Int("Heal At", s => s.HealAt, (s, v) => s.HealAt = v, 0, 100, 1, - "While a target is within Monster Range, cast Heal Self when HP < this %."), - Int("Re-stam At", s => s.RestamAt, (s, v) => s.RestamAt = v, 0, 100, 1, - "While a target is within Monster Range, cast Revitalize Self when Stamina < this %."), - Int("Re-stam To", s => s.RestamTo, (s, v) => s.RestamTo = v, 0, 100, 1, - "Once a recharge starts under Re-stam At, keep recharging until Stamina reaches this %\n(one Revitalize often doesn't get far). 0 = one recharge, as before."), - Int("Get Mana At", s => s.GetManaAt, (s, v) => s.GetManaAt = v, 0, 100, 1, - "While a target is within Monster Range, cast Stamina to Mana Self when Mana < this % (needs stam > 15%)."), - Spacer(), - Section("Idle Top-Off — no targets in range (%)"), - Int("Top HP", s => s.TopOffHP, (s, v) => s.TopOffHP = v, 0, 100, 1, - "When no targets are within Monster Range, heal up to this HP %. Usually set higher than Heal At."), - Int("Top Stam", s => s.TopOffStam, (s, v) => s.TopOffStam = v, 0, 100, 1, - "When no targets are within Monster Range, re-stam up to this %."), - Int("Top Mana", s => s.TopOffMana, (s, v) => s.TopOffMana = v, 0, 100, 1, - "When no targets are within Monster Range, recharge mana up to this %."), - Spacer(), - Section("Kits & Potions"), - Bool("Use Potions", s => s.UsePotions, (s, v) => s.UsePotions = v, - "Drink health, mana and stamina potions from the Items panel when a vital is low\nand no spell can fix it (no spell, Life Magic untrained, out of components)."), - Bool("Use Buff Items", s => s.UseBuffItems, (s, v) => s.UseBuffItems = v, - "Use Asheron's Benediction, Asheron's Lesser Benediction and Blackmoor's Favor\nfrom your pack whenever their buff isn't on you (they're never used up)."), - Int("Make Field Rations Below", s => s.MakeRationsBelow, (s, v) => s.MakeRationsBelow = v, 0, 100, 1, - "Cook field rations (Cooking Pot on Dried Rations, 25 at a time) when you have fewer than this.\n0 = off. Rations restore stamina and are eaten like stamina potions."), - Bool("Use Kits In Magic Mode", s => s.UseKitsInMagicMode, (s, v) => s.UseKitsInMagicMode = v, - "Allow healing kits while in magic mode."), - Bool("Peace Mode For Kits", s => s.PeaceModeForKits, (s, v) => s.PeaceModeForKits = v, - "Switch to peace mode before using a healing kit."), - Int("Emergency Heal At", s => s.EmergencyHealAt, (s, v) => s.EmergencyHealAt = v, 0, 100, 1, - "At or under this health %, out of Magic mode a healing kit is used ahead of the\nnormal Heal At chain (kit, Heal Self, potion), and while a spell cast is pending a kit\nor potion is used. Stamina to Health has its own line below. 0 = off. Starts at 30."), - Int("Stamina To Health At", s => s.StaminaToHealthAt, (s, v) => s.StaminaToHealthAt = v, 0, 100, 1, - "At or under this health %, cast Stamina to Health Self ahead of the normal\nHeal At chain (out of Magic mode a kit is tried first). If it can't be cast,\nthe normal chain (kit, Heal Self, potion) runs. 0 = never cast it. Starts at 30."), - Int("Stamina To Health Min Stamina", s => s.StaminaToHealthMinStamina, (s, v) => s.StaminaToHealthMinStamina = v, 0, 100, 1, - "Cast Stamina to Health only while stamina is over this %, so it doesn't\ndrain you to nothing. Starts at 20."), - Int("Kit Min Success %", s => s.KitMinSuccessPct, (s, v) => s.KitMinSuccessPct = v, 0, 100, 1, - "Use a healing kit only when its chance to work is at least this %,\nworked out like the server does: Healing skill + the kit's bonus vs. what's missing.\nBelow it, the spell is cast instead. 0 = always use kits. Starts at 70."), - Int("Stamina Kit Min Success %", s => s.StaminaKitMinSuccessPct, (s, v) => s.StaminaKitMinSuccessPct = v, 0, 100, 1, - "The same for stamina kits: use one only when its chance to work is at least this %\n(Healing skill + the kit's bonus vs. the stamina missing). Below it Revitalize Self\nor a stamina potion goes instead. 0 = always use stamina kits. Starts at 70."), + Section("Between Fights"), + Bool("Peace Mode When Idle", s => s.PeaceModeWhenIdle, (s, v) => s.PeaceModeWhenIdle = v), + Bool("Weapons Back After Heals", s => s.RearmAfterVitals == true, (s, v) => s.RearmAfterVitals = v, + "After a heal, restam or remana spell with nothing to fight, put the last fight's weapons\n(main hand and off hand) back on instead of waiting for the next monster."), Spacer(), Section("Safety Stops"), + Bool("Escape Acid and Lava", s => s.EscapeHazards, (s, v) => s.EscapeHazards = v, + "When acid or lava hurts you, stop everything (combat, buffs, healing, looting)\nand walk back out the way you came. The spot is remembered so the patrol avoids it.\nTurn off for a character that walks through acid on purpose."), Bool("Stop Macro On Death", s => s.StopMacroOnDeath, (s, v) => s.StopMacroOnDeath = v, "Stop the macro when you die. Off by default: most metas run back on their own."), Bool("Stop Macro On No Components", s => s.StopMacroOnNoComponents, (s, v) => s.StopMacroOnNoComponents = v, @@ -1200,17 +1218,76 @@ internal static class SettingsSchema "Name of the item to use after a death, as it shows in your inventory. An exact match wins;\n" + "otherwise the first item whose name contains it.", hint: "item name, as in your inventory") with { VisibleWhen = s => s.DeathRecallMode == 2 }, + Spacer(when: s => s.AutoFellowMgmt.HasValue), + Section("Fellowship", when: s => s.AutoFellowMgmt.HasValue), + Bool("Auto Fellowship Management", s => s.AutoFellowMgmt ?? false, (s, v) => s.AutoFellowMgmt = v, + "VTank's Auto Fellow Mgmt., saved with the profile. Metas read it (AutoFellowMgmt).", + when: s => s.AutoFellowMgmt.HasValue, gates: true), + Bool(" Open fellowship on create", s => s.OpenFellowOnCreate ?? true, (s, v) => s.OpenFellowOnCreate = v, + "A fellowship RynthAi creates (/mt fellow create, or a meta's /fellowship create) is opened\n" + + "as soon as you lead it, so every member can recruit, not just the leader. AC makes a new\n" + + "fellowship closed.\nOnly right after RynthAi creates it: one you made or closed by hand is left alone.", + when: s => s.AutoFellowMgmt == true && s.OpenFellowOnCreate.HasValue), + Spacer(when: s => s.EnableVaultedDungeons.HasValue), + Section("Server Features", when: s => s.EnableVaultedDungeons.HasValue), + Bool(VaultedDungeonsLabel, s => s.EnableVaultedDungeons ?? false, (s, v) => s.EnableVaultedDungeons = v, + "Master switch of the Vaulted Dungeons keeper (Infinite Leaftide / ACECustom only). Off by default.\n" + + "While off the keeper does nothing: no recalls, no /rc quit, no Mini Remote tab, and a saved On or\n" + + "Auto Start is ignored. Turning it off while it runs stops it at once.\n" + + "On: the Mini Remote shows the \"Vaulted Dungeons\" tab on those worlds, where you pick a dungeon and a\n" + + "tied Portal Recall Gem and start it yourself (/ilt vaulted on); it never resumes by itself after a\n" + + "relog unless Auto Start On Arrival is ticked. Recalls wait while RynthAi is in combat or buffing.\n" + + "Kill Client (/rc quit after N minutes without a kill) restarts on luminance, your killing blows and\n" + + "pet captures; kills by pets or fellows that pay you no luminance do NOT.\n" + + "Needs RynthILT and a RynthAi that has this setting; the other settings are per character in RynthILT.", + when: s => s.EnableVaultedDungeons.HasValue), + }, "RynthAi · saved in the profile"), + + new("Recharge", new[] + { + Section("In Combat — target within Monster Range (%)"), + Int("Heal At", s => s.HealAt, (s, v) => s.HealAt = v, 0, 100, 1, + "While a target is within Monster Range, cast Heal Self when HP < this %."), + Int("Re-stam At", s => s.RestamAt, (s, v) => s.RestamAt = v, 0, 100, 1, + "While a target is within Monster Range, cast Revitalize Self when Stamina < this %."), + Int("Re-stam To", s => s.RestamTo, (s, v) => s.RestamTo = v, 0, 100, 1, + "Once a recharge starts under Re-stam At, keep recharging until Stamina reaches this %\n(one Revitalize often doesn't get far). 0 = one recharge, as before."), + Int("Get Mana At", s => s.GetManaAt, (s, v) => s.GetManaAt = v, 0, 100, 1, + "While a target is within Monster Range, cast Stamina to Mana Self when Mana < this % (needs stam > 15%)."), Spacer(), - Section("Helper Settings (%) — NOT WIRED YET"), - Int("Heal Others", s => s.HealOthersAt, (s, v) => s.HealOthersAt = v, 0, 100, 1, - "Intended: cast Heal Other on a fellow when their HP < this %. Not implemented yet — slider is inert."), - Int("Re-stam Others", s => s.RestamOthersAt, (s, v) => s.RestamOthersAt = v, 0, 100, 1, - "Intended: cast Revitalize Other on a fellow when their Stamina < this %. Not implemented yet — slider is inert."), - Int("Infuse Others", s => s.InfuseOthersAt, (s, v) => s.InfuseOthersAt = v, 0, 100, 1, - "Intended: cast Infuse Mana Other on a fellow when their Mana < this %. Not implemented yet — slider is inert."), + Section("Idle Top-Off — no targets in range (%)"), + Int("Top HP", s => s.TopOffHP, (s, v) => s.TopOffHP = v, 0, 100, 1, + "When no targets are within Monster Range, heal up to this HP %. Usually set higher than Heal At."), + Int("Top Stam", s => s.TopOffStam, (s, v) => s.TopOffStam = v, 0, 100, 1, + "When no targets are within Monster Range, re-stam up to this %."), + Int("Top Mana", s => s.TopOffMana, (s, v) => s.TopOffMana = v, 0, 100, 1, + "When no targets are within Monster Range, recharge mana up to this %."), + Spacer(), + Section("Kits & Potions"), + Bool("Use Potions", s => s.UsePotions, (s, v) => s.UsePotions = v, + "Drink health, mana and stamina potions from the Items panel when a vital is low\nand no spell can fix it (no spell, Life Magic untrained, out of components)."), + Int("Make Field Rations Below", s => s.MakeRationsBelow, (s, v) => s.MakeRationsBelow = v, 0, 100, 1, + "Cook field rations (Cooking Pot on Dried Rations, 25 at a time) when you have fewer than this.\n0 = off. Rations restore stamina and are eaten like stamina potions."), + Bool("Use Kits In Magic Mode", s => s.UseKitsInMagicMode, (s, v) => s.UseKitsInMagicMode = v, + "Allow healing kits while in magic mode."), + Bool("Peace Mode For Kits", s => s.PeaceModeForKits, (s, v) => s.PeaceModeForKits = v, + "Switch to peace mode before using a healing kit."), + Int("Emergency Heal At", s => s.EmergencyHealAt, (s, v) => s.EmergencyHealAt = v, 0, 100, 1, + "At or under this health %, out of Magic mode a healing kit is used ahead of the\nnormal Heal At chain (kit, Heal Self, potion), and while a spell cast is pending a kit\nor potion is used. Stamina to Health has its own line below. 0 = off. Starts at 30."), + Int("Stamina To Health At", s => s.StaminaToHealthAt, (s, v) => s.StaminaToHealthAt = v, 0, 100, 1, + "At or under this health %, cast Stamina to Health Self ahead of the normal\nHeal At chain (out of Magic mode a kit is tried first). If it can't be cast,\nthe normal chain (kit, Heal Self, potion) runs. 0 = never cast it. Starts at 30."), + Int("Stamina To Health Min Stamina", s => s.StaminaToHealthMinStamina, (s, v) => s.StaminaToHealthMinStamina = v, 0, 100, 1, + "Cast Stamina to Health only while stamina is over this %, so it doesn't\ndrain you to nothing. Starts at 20."), + Int("Kit Min Success %", s => s.KitMinSuccessPct, (s, v) => s.KitMinSuccessPct = v, 0, 100, 1, + "Use a healing kit only when its chance to work is at least this %,\nworked out like the server does: Healing skill + the kit's bonus vs. what's missing.\nBelow it, the spell is cast instead. 0 = always use kits. Starts at 70."), + Int("Stamina Kit Min Success %", s => s.StaminaKitMinSuccessPct, (s, v) => s.StaminaKitMinSuccessPct = v, 0, 100, 1, + "The same for stamina kits: use one only when its chance to work is at least this %\n(Healing skill + the kit's bonus vs. the stamina missing). Below it Revitalize Self\nor a stamina potion goes instead. 0 = always use stamina kits. Starts at 70."), + // The three Helper sliders (Heal / Re-stam / Infuse Others) are left out until RynthAi acts on them; their + // fields stay in the payload (HealOthersAt, RestamOthersAt, InfuseOthersAt). }), - new("Melee Combat", new[] + // Melee Combat until 2026-11-11 (it held the missile settings too): every weapon setting, targeting and pets. + new("Combat", new[] { Section("Attack Power & Height"), Bool("Use Recklessness", s => s.UseRecklessness, (s, v) => s.UseRecklessness = v, @@ -1223,6 +1300,22 @@ internal static class SettingsSchema Bool("Missile Auto Power", s => s.MissileAttackPower < 0, (s, v) => s.MissileAttackPower = v ? -1 : 100, gates: true), Int("Missile Power %", s => s.MissileAttackPower, (s, v) => s.MissileAttackPower = v, 0, 100, 5, when: s => s.MissileAttackPower >= 0), Combo("Missile Attack Height", AttackHeights, s => s.MissileAttackHeight, (s, v) => s.MissileAttackHeight = v), + Spacer(HasDfRotation), + Bool("Dirty Fighting rotation", s => s.DfHeightRotation ?? false, (s, v) => s.DfHeightRotation = v, + "With Dirty Fighting trained, melee and missile attacks aim at the height of the next Dirty Fighting effect\n" + + "the target doesn't have: High lowers its attack skills and the heals it gets, Medium makes it bleed, Low\n" + + "lowers its defense skills. Off, or untrained, the Melee and Missile Attack Height above apply.\n" + + "Also: RynthAi's Dirty Fighting window (/ra dfheight window).", + when: HasDfRotation, gates: true), + Combo(" Effect order", DfOrderLabels, s => DfOrderIndex(s.DfHeightOrder), + (s, v) => s.DfHeightOrder = DfOrders[Math.Clamp(v, 0, DfOrders.Length - 1)], + "The order the three effects are put on the target. Default High, Medium, Low.", + when: s => s.DfHeightRotation == true && s.DfHeightOrder != null), + Combo(" Then attack", DfDefaultLabels, s => Math.Clamp((s.DfDefaultHeight ?? -1) + 1, 0, DfDefaultLabels.Length - 1), + (s, v) => s.DfDefaultHeight = Math.Clamp(v, 0, DfDefaultLabels.Length - 1) - 1, + "Once all three are on, the height attacks use (Attack Height setting: the Melee or Missile Attack Height\n" + + "above). They go back to an effect about 5 seconds before it runs out; each lasts 20 seconds.", + when: s => s.DfHeightRotation == true && s.DfDefaultHeight.HasValue), Spacer(), Section("Variable Power (monster rules)", HasVariablePower), Int("Variable Min %", s => s.VariablePowerMin ?? 50, (s, v) => s.VariablePowerMin = v, 0, 100, 5, @@ -1234,6 +1327,69 @@ internal static class SettingsSchema Int("Variable Max %", s => s.VariablePowerMax ?? 100, (s, v) => s.VariablePowerMax = v, 0, 100, 5, when: HasVariablePower), Spacer(HasVariablePower), + Section("Targeting"), + Combo("Targeting", new[] { "Lowest health", "Closest", "Farthest", "Least turning" }, + s => Math.Clamp(s.TargetSelection ?? 0, 0, 3), (s, v) => s.TargetSelection = Math.Clamp(v, 0, 3), + "Which monster to attack, among those of the highest priority inside Monster Range.\n" + + "Least turning: the one needing the smallest turn to face. Unknown health counts as full."), + Bool("Target Lock", s => s.TargetLock ?? true, (s, v) => s.TargetLock = v, + "On: keeps the target it picked until it dies, leaves range (Disengage Range), or a higher-priority monster shows up.\n" + + "Off: switches whenever another monster is clearly better by the Targeting rule."), + Bool("Fight the monster I select", s => s.FightSelectedTarget ?? false, (s, v) => s.FightSelectedTarget = v, + "On: in a fight, a monster YOU select (click it, or pick it on the radar or in a Selection window)\n" + + "is fought first, ahead of Targeting and Priority, until it dies, can't be reached, or you select\n" + + "another monster or deselect. The bot's own selections never count. Ignored (Priority 0) and\n" + + "never-attack monsters are not followed (/ra targetlock still forces them). Out to Disengage Range.\n" + + "/ra fightselected [on|off]"), + Int("Attempts Before Blacklist", s => s.BlacklistAttempts, (s, v) => s.BlacklistAttempts = v, 1, 20, 1, + "How many failed attack attempts on a mob before it gets blacklisted."), + Int("Blacklist Timeout (sec)", s => s.BlacklistTimeoutSec, (s, v) => s.BlacklistTimeoutSec = v, 5, 120, 5, + "How long a blacklisted mob is ignored before re-trying."), + Int("No Progress Timeout (sec)", s => s.TargetNoProgressTimeoutSec, (s, v) => s.TargetNoProgressTimeoutSec = v, 0, 300, 10, + "Blacklist a target after being engaged this many seconds without dealing damage.\n0 = disabled. Default 60s."), + Int("Cast Settle (ms)", s => s.BlacklistCastSettleMs, (s, v) => s.BlacklistCastSettleMs = v, 500, 5000, 100, + "After an offensive spell, how long to wait for its damage before the cast counts as a miss toward\n" + + "Attempts Before Blacklist (so a slow damage message doesn't blacklist a monster you are hurting). Default 1500."), + Spacer(), + Section("Weapon Swaps", HasWeaponSwaps), + Int("Weakness Swap Min Gain %", s => s.WeaponSwapMinGainPct ?? 20, (s, v) => s.WeaponSwapMinGainPct = v, 0, 200, 5, + "A swap picked for the monster's weakness (Auto) happens only when the new weapon does at least this much\n" + + "more damage than the one in hand. A weapon picked on the Damage tab, a slayer or a Monsters rule always\n" + + "swaps. 0 = always swap. Default 20.", when: HasWeaponSwaps), + Int("No Swap Under Target Health %", s => s.WeaponSwapMinHealthPct ?? 25, (s, v) => s.WeaponSwapMinHealthPct = v, 0, 100, 5, + "No new swap onto a target at or under this much health: it is finished with the weapon in hand.\n0 = off. Default 25.", + when: HasWeaponSwaps), + Int("Wait After Target Switch (ms)", s => s.WeaponSwapSettleMs ?? 750, (s, v) => s.WeaponSwapSettleMs = v, 0, 3000, 50, + "When the bot switches from one live target to another, a weapon swap waits this long first, so a target that\n" + + "changes again doesn't cost a wasted swap. A new target after a kill swaps at once. 0 = never wait. Default 750.", + when: HasWeaponSwaps), + Bool("Prefer Dual Wield", s => s.PreferDualWield ?? false, (s, v) => s.PreferDualWield = v, + "With the off hand on Auto: dual wield a second listed one-handed melee weapon rather than a shield, when the\n" + + "Dual Wield skill is trained. Off by default (the shield).", + when: s => s.PreferDualWield.HasValue), + Combo("Off-hand Default", OffhandDefaults, s => OffhandIndex(s.OffhandDefault), (s, v) => s.OffhandDefault = OffhandDefaults[Math.Clamp(v, 0, OffhandDefaults.Length - 1)], + "The off hand (the shield slot) when a monster's rule doesn't pick one:\n" + + " Auto - a listed shield with a one-handed weapon (dual wield instead with Prefer Dual Wield)\n" + + " Shield - a listed shield, or nothing\n" + + " Weapon - dual wield a second listed one-handed weapon (needs Dual Wield), else a listed shield\n" + + " None - the off hand is never touched", + when: s => s.OffhandDefault != null), + Spacer(HasWeaponSwaps), + Section("Line Of Sight"), + Bool("Enable Raycasting", s => s.EnableRaycasting, (s, v) => s.EnableRaycasting = v), + 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, + "Bow projectile speed (m/s). Lower = higher arc.", when: s => s.UseArcs), + Float("Crossbow", s => s.CrossbowArcVelocity, (s, v) => s.CrossbowArcVelocity = v, 10f, 80f, 0.5f, when: s => s.UseArcs), + Float("Atlatl", s => s.AtlatlArcVelocity, (s, v) => s.AtlatlArcVelocity = v, 10f, 60f, 0.5f, when: s => s.UseArcs), + Float("Magic Arc", s => s.MagicArcVelocity, (s, v) => s.MagicArcVelocity = v, 10f, 60f, 0.5f, + "Arc spells' horizontal speed (m/s). ACE: 40. Lower = higher arc.\nA monster rule with Arc on casts an arc only when this path reaches the target (walls, and ceilings in dungeons); otherwise its other shape (Streak, Blast) or a bolt. Needs Enable Raycasting. /ra lostest magic shows the arc to the selected mob."), + Float("Arc Clearance (m)", s => s.MissileArcClearance, (s, v) => s.MissileArcClearance = MathF.Max(0f, v), 0f, 3f, 0.1f, + "Extra headroom the arc must have at mid-flight. Raise it if arrows still hit ceilings; lower it if reachable mobs get skipped.", when: s => s.UseArcs), + Bool("LoS Debug Log", s => s.LosDebugLog, (s, v) => s.LosDebugLog = v, + "Log each blocked missile target and why (arc peak, where it hits) to the RynthCore log. /ra lostest bow tests the selected mob."), + Spacer(), Section("Hitting the Environment", HasEnvironmentThrottle), Combo("Missile Response", EnvironmentResponses, s => s.MissileEnvironmentResponse ?? 0, (s, v) => s.MissileEnvironmentResponse = v, "When arrows or bolts keep hitting walls or objects instead of the target\n" + @@ -1241,7 +1397,16 @@ internal static class SettingsSchema " Move closer - run toward the target for a clearer shot\n" + " New target - skip this one for a while and fight another\n" + " Move closer, then new target - one approach, then switch\n" + - "The only monster in reach is never skipped. Off by default. Magic: Spell Combat tab.", + "The only monster in reach is never skipped. Off by default. Magic: Magic Response below.", + when: HasEnvironmentThrottle), + Combo("Magic Response", EnvironmentResponses, s => s.MagicEnvironmentResponse ?? 0, (s, v) => s.MagicEnvironmentResponse = v, + "When bolts, streaks, arcs or blasts keep stopping short of the target\n" + + "(a wall, a pillar, the ceiling) with no hit or resist, stop casting and:\n" + + " Move closer - run toward the target for a clearer line\n" + + " New target - skip this one for a while and fight another\n" + + " Move closer, then new target - one approach, then switch\n" + + "Rings and walls aren't judged. The only monster in reach is never skipped. Off by default.\n" + + "Hits to trip, the window, distances and the skip time: below.", when: HasEnvironmentThrottle), Int("Hits to trip", s => s.EnvironmentImpactLimit ?? 2, (s, v) => s.EnvironmentImpactLimit = v, 1, 10, 1, "Environment hits on one target, within the window, before combat reacts (missiles and magic).", @@ -1256,6 +1421,13 @@ internal static class SettingsSchema Int("Skip target (s)", s => s.EnvironmentSkipSec ?? 30, (s, v) => s.EnvironmentSkipSec = v, 5, 300, 5, when: HasEnvironmentThrottle), Spacer(HasEnvironmentThrottle), + Section("Missile Ammo Crafting"), + Bool("Enable Missile Crafting", s => s.EnableMissileCrafting, (s, v) => s.EnableMissileCrafting = v, + "Auto-manage missile ammo when the ammo slot is empty or low.", gates: true), + Note("(Disabled)", when: s => !s.EnableMissileCrafting), + Spacer(when: s => s.EnableMissileCrafting), + new SettingRow(SettingKind.CraftingStatus, "State:", VisibleWhen: s => s.EnableMissileCrafting && !string.IsNullOrEmpty(s.MissileCraftingState)), + Spacer(), Section("Pull Away (Kite)", HasKite), Int("Pull Distance (m)", s => s.KitePullMeters ?? 20, (s, v) => s.KitePullMeters = v, 3, 100, 1, "When a monster rule's Kite is PullAway (or Default follows the DEFAULT row set to PullAway),\n" + @@ -1266,9 +1438,9 @@ internal static class SettingsSchema "Land a hit before running so aggro sticks. Off = flee as soon as locked.", when: HasKite), Spacer(HasKite), + Section("Native Attack And Pets"), Bool("Use Native Attack", s => s.UseNativeAttack, (s, v) => s.UseNativeAttack = v, "Uses the client's combat pipeline for attacks.\nThe client handles turn-to-face naturally (no backwards arrows)."), - Spacer(), Bool("Summon Pets", s => s.SummonPets, (s, v) => s.SummonPets = v), Int("Pet Min Monsters", s => s.PetMinMonsters, (s, v) => s.PetMinMonsters = v, 1, 20, 1), new(SettingKind.Int, "Pet Range", @@ -1278,23 +1450,13 @@ internal static class SettingsSchema }), new("Spell Combat", Concat( - Section("War/Void Casting Settings"), - Int("Buff Spell Interval (ms)", s => s.SpellCastIntervalMs, (s, v) => s.SpellCastIntervalMs = v, 100, 1500, 50, - "Delay between BUFF / utility spell casts (not combat).\nLower = faster buff chains. 400ms is a good balance.\nBelow 200ms may cause fizzles or dropped casts on laggy servers."), + 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."), Bool("Cast Dispel Self", s => s.CastDispelSelf, (s, v) => s.CastDispelSelf = v), Bool("Use Dispel Items", s => s.UseDispelItems ?? false, (s, v) => s.UseDispelItems = v, "VTank's Use Dispel Items, saved with the profile. Metas read it (UseDispelItems).", when: s => s.UseDispelItems.HasValue), - Bool("Auto Fellowship Management", s => s.AutoFellowMgmt ?? false, (s, v) => s.AutoFellowMgmt = v, - "VTank's Auto Fellow Mgmt., saved with the profile. Metas read it (AutoFellowMgmt).", - when: s => s.AutoFellowMgmt.HasValue, gates: true), - Bool(" Open fellowship on create", s => s.OpenFellowOnCreate ?? true, (s, v) => s.OpenFellowOnCreate = v, - "A fellowship RynthAi creates (/mt fellow create, or a meta's /fellowship create) is opened\n" + - "as soon as you lead it, so every member can recruit, not just the leader. AC makes a new\n" + - "fellowship closed.\nOnly right after RynthAi creates it: one you made or closed by hand is left alone.", - when: s => s.AutoFellowMgmt == true && s.OpenFellowOnCreate.HasValue), Bool("M. Charges When Off", s => s.MChargesWhenOff ?? false, (s, v) => s.MChargesWhenOff = v, "VTank's option of this name, saved with the profile for VTank users. RynthAi doesn't act on it yet.", when: s => s.MChargesWhenOff.HasValue), @@ -1315,17 +1477,6 @@ internal static class SettingsSchema Int("Min Wall Targets", s => s.MinWallTargets, (s, v) => s.MinWallTargets = v, 1, 20, 1, "How many monsters (the target included) must be in the wall's path, within Wall Range."), Spacer(), - Section("Hitting the Environment", HasEnvironmentThrottle), - Combo("Magic Response", EnvironmentResponses, s => s.MagicEnvironmentResponse ?? 0, (s, v) => s.MagicEnvironmentResponse = v, - "When bolts, streaks, arcs or blasts keep stopping short of the target\n" + - "(a wall, a pillar, the ceiling) with no hit or resist, stop casting and:\n" + - " Move closer - run toward the target for a clearer line\n" + - " New target - skip this one for a while and fight another\n" + - " Move closer, then new target - one approach, then switch\n" + - "Rings and walls aren't judged. The only monster in reach is never skipped. Off by default.\n" + - "Hits to trip, the window, distances and the skip time: Melee Combat tab.", - when: HasEnvironmentThrottle), - Spacer(HasEnvironmentThrottle), Section("Spell Difficulty (Min Buffed Skill)"), Tiers( new Func[] { s => s.MinSkillLevelTier1, s => s.MinSkillLevelTier2, s => s.MinSkillLevelTier3, s => s.MinSkillLevelTier4, @@ -1342,21 +1493,6 @@ internal static class SettingsSchema Int("Disengage Range", s => s.MonsterDisengageRange, (s, v) => s.MonsterDisengageRange = v, 0, 200, 1, "Drop a locked target only once it is this far away (yards).\n0, or anything up to Monster Range, = automatic (Monster Range + 3)."), Spacer(), - Section("Combat Targeting"), - Combo("Targeting", new[] { "Lowest health", "Closest", "Farthest", "Least turning" }, - s => Math.Clamp(s.TargetSelection ?? 0, 0, 3), (s, v) => s.TargetSelection = Math.Clamp(v, 0, 3), - "Which monster to attack, among those of the highest priority inside Monster Range.\n" + - "Least turning: the one needing the smallest turn to face. Unknown health counts as full."), - Bool("Target Lock", s => s.TargetLock ?? true, (s, v) => s.TargetLock = v, - "On: keeps the target it picked until it dies, leaves range (Disengage Range), or a higher-priority monster shows up.\n" + - "Off: switches whenever another monster is clearly better by the Targeting rule."), - Bool("Fight the monster I select", s => s.FightSelectedTarget ?? false, (s, v) => s.FightSelectedTarget = v, - "On: in a fight, a monster YOU select (click it, or pick it on the radar or in a Selection window)\n" + - "is fought first, ahead of Targeting and Priority, until it dies, can't be reached, or you select\n" + - "another monster or deselect. The bot's own selections never count. Ignored (Priority 0) and\n" + - "never-attack monsters are not followed (/ra targetlock still forces them). Out to Disengage Range.\n" + - "/ra fightselected [on|off]"), - Spacer(), Section("Corpse Acquisition (Yards)"), Double("Corpse Max (yd)", s => s.CorpseApproachRangeMax, (s, v) => s.CorpseApproachRangeMax = v, 0.5, 50.0, 0.5, CorpseMaxTip), Double("Corpse Min (yd)", s => s.CorpseApproachRangeMin, (s, v) => s.CorpseApproachRangeMin = v, 0.5, 20.0, 0.5, @@ -1369,19 +1505,6 @@ internal static class SettingsSchema "While a nav route runs, only navigate: no hunting, no looting, no fighting back. With no route, at the end of a Once route or in Outdoor Hunt it hunts and loots as usual. Buffs and heals still run."), Float(NavPointReachLabel, s => s.FollowNavMin, (s, v) => s.FollowNavMin = v, 0.5f, 20f, 0.1f, NavPointReachTip), Spacer(), - Section("Infinite Leaftide"), - Bool(VaultedDungeonsLabel, s => s.EnableVaultedDungeons ?? false, (s, v) => s.EnableVaultedDungeons = v, - "Master switch of the Vaulted Dungeons keeper (Infinite Leaftide / ACECustom only). Off by default.\n" + - "While off the keeper does nothing: no recalls, no /rc quit, no Mini Remote tab, and a saved On or\n" + - "Auto Start is ignored. Turning it off while it runs stops it at once.\n" + - "On: the Mini Remote shows the \"Vaulted Dungeons\" tab on those worlds, where you pick a dungeon and a\n" + - "tied Portal Recall Gem and start it yourself (/ilt vaulted on); it never resumes by itself after a\n" + - "relog unless Auto Start On Arrival is ticked. Recalls wait while RynthAi is in combat or buffing.\n" + - "Kill Client (/rc quit after N minutes without a kill) restarts on luminance, your killing blows and\n" + - "pet captures; kills by pets or fellows that pay you no luminance do NOT.\n" + - "Needs RynthILT and a RynthAi that has this setting; the other settings are per character in RynthILT.", - when: s => s.EnableVaultedDungeons.HasValue), - Spacer(), Section("Nav Marker Display"), Bool("Breadcrumbs", s => s.TrackBreadcrumbs ?? true, (s, v) => s.TrackBreadcrumbs = v, BreadcrumbsTip + SameAsNavPanel, when: s => s.TrackBreadcrumbs.HasValue), @@ -1502,15 +1625,28 @@ internal static class SettingsSchema Bool("Enable Buffing", s => s.EnableBuffing, (s, v) => s.EnableBuffing = v), Button("Buff Profiles", "Spells...", () => RynthAiCommands.ApplyRemoteCommand("spells", "show"), "Open the RynthAi Spells window: browse the spell list by school, level and target,\nand build the buff profile buffing uses (pick it under Loaded Files > Buffs).\nAlso: /ra spells, /ra buffprofile |none."), - Bool("Rebuff When Idle", s => s.RebuffWhenIdle, (s, v) => s.RebuffWhenIdle = v), + Bool("Rebuff When Idle", s => s.RebuffWhenIdle, (s, v) => s.RebuffWhenIdle = v, gates: true), Int("Rebuff With (seconds left)", s => s.RebuffSecondsRemaining, (s, v) => s.RebuffSecondsRemaining = v, 30, 1800, 30, "Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly."), Int("Also Refresh Under (seconds left)", s => s.RebuffTopOffSecondsRemaining, (s, v) => s.RebuffTopOffSecondsRemaining = v, 30, 3600, 60, "When a buff is due, also recast every other buff with less than this much time left,\nso they land together. Buffs with more time are left alone. Default 1200 (20 minutes).\nAt or below 'Rebuff With', only the expiring buff is recast."), + Int("Idle Margin (minutes)", s => s.RebuffIdleMarginMinutes ?? 2, (s, v) => s.RebuffIdleMarginMinutes = v, 0, 60, 1, + "With Rebuff When Idle: while nothing is in range, a buff may be recast this many minutes earlier than\n" + + "Rebuff With says, so quiet moments are used. 0 = no earlier than Rebuff With. Default 2.", + when: s => s.RebuffIdleMarginMinutes.HasValue && s.RebuffWhenIdle), Bool("Cast buffs even when an item gives them", s => s.CastBuffsOverItemBuffs, (s, v) => s.CastBuffsOverItemBuffs = v, "Cast your own buff even when worn gear already gives that buff.\nFor servers with buff augments, where your own cast is stronger or lasts longer.\nOn by default: on retail it costs a few extra casts."), + Bool("Skip buffs this character can't use", s => s.SkipUnusableBuffs ?? true, (s, v) => s.SkipUnusableBuffs = v, + "Leave out the weapon enchantments this character has no use for: Blood Drinker, Heart Seeker and Swift Killer\n" + + "with no melee or missile weapon (listed or in hand), Spirit Drinker and Hermetic Link with no wand, Defender with\n" + + "neither. Buffs Left Out lists what was left out. On by default. A mastery for an untrained skill is never cast.", + when: s => s.SkipUnusableBuffs.HasValue), ChatButton("Buffs Left Out", "List in chat", "/ra buff skipped", "The buffs RynthAi leaves out because this character can't use them, listed in chat (/ra buff skipped)."), + Int("Buff Spell Interval (ms)", s => s.SpellCastIntervalMs, (s, v) => s.SpellCastIntervalMs = v, 100, 1500, 50, + "Delay between BUFF / utility spell casts (not combat).\nLower = faster buff chains. 400ms is a good balance.\nBelow 200ms may cause fizzles or dropped casts on laggy servers."), + Bool("Use Buff Items", s => s.UseBuffItems, (s, v) => s.UseBuffItems = v, + "Use Asheron's Benediction, Asheron's Lesser Benediction and Blackmoor's Favor\nfrom your pack whenever their buff isn't on you (they're never used up)."), Spacer(), Section("Protections (untick to skip)"), BuffToggles(ProtToggles), @@ -1525,20 +1661,16 @@ internal static class SettingsSchema new Action[] { (s, v) => s.BuffMinSkillLevelTier1 = v, (s, v) => s.BuffMinSkillLevelTier2 = v, (s, v) => s.BuffMinSkillLevelTier3 = v, (s, v) => s.BuffMinSkillLevelTier4 = v, (s, v) => s.BuffMinSkillLevelTier5 = v, (s, v) => s.BuffMinSkillLevelTier6 = v, (s, v) => s.BuffMinSkillLevelTier7 = v, (s, v) => s.BuffMinSkillLevelTier8 = v }))), - new("Crafting", new[] - { - Section("Missile Ammo Crafting"), - Bool("Enable Missile Crafting", s => s.EnableMissileCrafting, (s, v) => s.EnableMissileCrafting = v, - "Auto-manage missile ammo when the ammo slot is empty or low.", gates: true), - Note("(Disabled)", when: s => !s.EnableMissileCrafting), - Spacer(when: s => s.EnableMissileCrafting), - new SettingRow(SettingKind.CraftingStatus, "State:", VisibleWhen: s => s.EnableMissileCrafting && !string.IsNullOrEmpty(s.MissileCraftingState)), - }), - new("Looting", new[] { Bool("Enable Looting", s => s.EnableLooting, (s, v) => s.EnableLooting = v), Bool("Boost Loot Priority", s => s.BoostLootPriority, (s, v) => s.BoostLootPriority = v), + Combo("Loot Mode", LootModeNames, s => Math.Clamp(s.LootMode ?? 0, 0, LootModeNames.Length - 1), + (s, v) => s.LootMode = Math.Clamp(v, 0, LootModeNames.Length - 1), + "Profile (default): loot what the loaded loot profile keeps.\n" + + "Rares and needed mana stones only: the loot profile isn't used; rares are looted, and mana stones while\n" + + "you keep fewer than you want. Also: /ra loot mode, the dashboard's loot button, the meta setting LootMode.", + when: s => s.LootMode.HasValue), Bool("Loot Only Rare Corpses", s => s.LootOnlyRareCorpses, (s, v) => s.LootOnlyRareCorpses = v), Bool("Learn Unknown Spells", s => s.ReadUnknownScrolls, (s, v) => s.ReadUnknownScrolls = v, "Loots scrolls of spells you don't know and can learn (magic school trained or\nspecialized, skill high enough), and reads them when it's safe. Scrolls already\nin your pack are read too. Needs Enable Looting for corpses."), @@ -1548,12 +1680,25 @@ internal static class SettingsSchema "When the pickup is done the chest stays open and chat says what was taken, so you can check it\n" + "and take anything your profile missed. Untick it and RynthAi closes the chest when it's done\n" + "(some chests lock again on close).", when: s => s.LootChestsMacroOff), + Int("Chest relock wait (s)", s => s.ChestRelockWaitSec ?? 125, (s, v) => s.ChestRelockWaitSec = v, 5, 600, 5, + "The Item Tool's chest key looter: the next key goes into a chest this long after it was opened (sooner when the\n" + + "chest shows locked again). 125 covers ACE's usual chest reset (120 s); a chest that resets sooner can use less.\n" + + "The same value as the Item Tool's re-lock wait. Also: /ra itemtool relock.", + when: s => s.ChestRelockWaitSec.HasValue), Bool("Stop Looting When Pack Full", s => s.StopLootingWhenPackFull, (s, v) => s.StopLootingWhenPackFull = v, "Don't start on another corpse when no pack has a free slot (says so once in chat)."), Bool("Jump When Looting", s => s.LootJumpEnabled, (s, v) => s.LootJumpEnabled = v, gates: true), Int("Jump Height", s => s.LootJumpHeight, (s, v) => s.LootJumpHeight = v, 1, 100, 5, when: s => s.LootJumpEnabled), Bool("Loot Items On Ground", s => s.EnableGroundLoot, (s, v) => s.EnableGroundLoot = v, "Pick up loose items on the ground that match your loot profile, within Corpse Max range.\nCorpses always come first. Status and rescan: /ra groundloot."), + Spacer(HasLootByName), + Section("Loot By Name", HasLootByName), + Text("Names", s => s.LootByNames ?? string.Empty, (s, v) => s.LootByNames = v.Trim(), + "Anything lying in the world with one of these names, inside the radius below, is used while the bot runs\nwith Looting on: a chest or cache is opened (and looted by your loot profile), an item on the ground is\npicked up. Separate names with |. A name must match the whole name (any case); put * at the start and/or\nend to match part of one: *cache* matches Unearthed Cache. Also: /ra lootname add|remove|list.", + hint: "Unearthed Cache | *Doubloon*") with { VisibleWhen = HasLootByName }, + Float("Radius (yd)", s => s.LootByNameRadius ?? 30f, (s, v) => s.LootByNameRadius = v, 3, 200, 1, + "How far from the character to look for these names. Default 30.", + when: s => HasLootByName(s) && !string.IsNullOrWhiteSpace(s.LootByNames)), Spacer(), Section("Corpse Ownership"), Combo("Loot From", LootOwnershipModes, s => s.LootOwnership, (s, v) => s.LootOwnership = v), @@ -1568,30 +1713,6 @@ internal static class SettingsSchema ChatButton("Stop Going To My Corpse", "Stop", "/ra owncorpse stop", "Stop the walk back to your corpse (/ra owncorpse stop)."), Spacer(), - Section("Inventory Management"), - Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v), - Bool("Enable Autocram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v, - "Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack.", - disabledWhen: s => s.AutoSortOn, disabledTip: CramOffForSortTip), - Bool("Unbox Aetheria When Idle", s => s.UnboxAetheriaWhenIdle, (s, v) => s.UnboxAetheriaWhenIdle = v, - "With the macro on and nothing to fight or loot, uses an Aetheria Mana Stone on each Coalesced\n" + - "Aetheria in your pack, one at a time, to reveal its sigil. The server puts you in peace mode for\n" + - "the clap; combat takes its stance again for the next fight. The stone isn't used up.\n" + - "Says once in chat when coalesced aetheria are left and no stone is. Status: /ra aetheria."), - ChatButton("Unbox Aetheria Now", "Unbox", "/ra aetheria unbox", - "Unbox every Coalesced Aetheria in your pack now, one at a time, setting on or off\n" + - "(with the macro on it waits for a quiet moment) (/ra aetheria unbox)."), - Bool("Combine Salvage Bags", s => s.EnableCombineSalvage, (s, v) => s.EnableCombineSalvage = v, - "After the salvage queue empties, move same-name bags together so the server merges them."), - Bool("Combine Bags During Salvage", s => s.CombineBagsDuringSalvage, (s, v) => s.CombineBagsDuringSalvage = v, - "When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel."), - ChatButton("Tidy Packs Now", "Stack and cram", "/mt autopack", - "One pass now: stack what stacks and move items from the main pack into side packs (/mt autopack).\nAutostack and Autocram above do it on their own while they are on."), - Button("Floating HUDs", "Inventory HUDs...", () => RynthAiCommands.ApplyRemoteCommand("huds", "show"), - "Opens the floating pack item count HUD / Mini Remote setup (/ra huds).\nThe Item Count panel is separate (/rc itemcount; Inventory's Count button)."), - Bool("Salvage Without The Panel", s => s.SalvageWithoutPanel, (s, v) => s.SalvageWithoutPanel = v, - "Salvage (and combine bags) by sending the salvage request to the server directly:\nAC's salvage panel never opens. When a request changes nothing, that batch is tried once\nthrough the panel. Needs an engine with plugin API v82; otherwise the panel is used."), - Spacer(), Section("Loot Timers (ms)"), EditButton("Optimized defaults", "Use optimized defaults", LootTimerDefaults.Apply, "Set the six loot timers RynthAi's corpse looting reads (everything here except Inter-Item\n" + @@ -1612,6 +1733,38 @@ internal static class SettingsSchema "Wait before sending another open to a corpse that hasn't opened. Optimized default: 1500."), Int("Corpse Timeout", s => s.LootCorpseTimeoutMs, (s, v) => s.LootCorpseTimeoutMs = v, 0, 60000, 500, "Give up on a claimed corpse after this long. The clock stops during combat\nand buffing. Optimized default: 12000."), + }), + + // New 2026-11-11: what happens to items once they are in your packs (from Looting, Misc and Display). + new("Inventory", new[] + { + Section("Packs"), + Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v), + Bool("Enable Autocram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v, + "Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack.", + disabledWhen: s => s.AutoSortOn, disabledTip: CramOffForSortTip), + ChatButton("Tidy Packs Now", "Stack and cram", "/mt autopack", + "One pass now: stack what stacks and move items from the main pack into side packs (/mt autopack).\nAutostack and Autocram above do it on their own while they are on."), + Button("Floating HUDs", "Inventory HUDs...", () => RynthAiCommands.ApplyRemoteCommand("huds", "show"), + "Opens the floating pack item count HUD / Mini Remote setup (/ra huds).\nThe Item Count panel is separate (/rc itemcount; Inventory's Count button)."), + Spacer(), + Section("Aetheria"), + Bool("Unbox Aetheria When Idle", s => s.UnboxAetheriaWhenIdle, (s, v) => s.UnboxAetheriaWhenIdle = v, + "With the macro on and nothing to fight or loot, uses an Aetheria Mana Stone on each Coalesced\n" + + "Aetheria in your pack, one at a time, to reveal its sigil. The server puts you in peace mode for\n" + + "the clap; combat takes its stance again for the next fight. The stone isn't used up.\n" + + "Says once in chat when coalesced aetheria are left and no stone is. Status: /ra aetheria."), + ChatButton("Unbox Aetheria Now", "Unbox", "/ra aetheria unbox", + "Unbox every Coalesced Aetheria in your pack now, one at a time, setting on or off\n" + + "(with the macro on it waits for a quiet moment) (/ra aetheria unbox)."), + Spacer(), + Section("Salvage"), + Bool("Combine Salvage Bags", s => s.EnableCombineSalvage, (s, v) => s.EnableCombineSalvage = v, + "After the salvage queue empties, move same-name bags together so the server merges them."), + Bool("Combine Bags During Salvage", s => s.CombineBagsDuringSalvage, (s, v) => s.CombineBagsDuringSalvage = v, + "When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel."), + Bool("Salvage Without The Panel", s => s.SalvageWithoutPanel, (s, v) => s.SalvageWithoutPanel = v, + "Salvage (and combine bags) by sending the salvage request to the server directly:\nAC's salvage panel never opens. When a request changes nothing, that batch is tried once\nthrough the panel. Needs an engine with plugin API v82; otherwise the panel is used."), Spacer(), Section("Salvage Timers (ms) - First / Fast"), Int("Open (First)", s => s.SalvageOpenDelayFirstMs, (s, v) => s.SalvageOpenDelayFirstMs = v, 0, 5000, 50), @@ -1621,6 +1774,16 @@ internal static class SettingsSchema Int("Salvage Click", s => s.SalvageSalvageDelayMs, (s, v) => s.SalvageSalvageDelayMs = v, 0, 2000, 25), Int("Result (First)", s => s.SalvageResultDelayFirstMs, (s, v) => s.SalvageResultDelayFirstMs = v, 0, 5000, 50), Int("Result (Fast)", s => s.SalvageResultDelayFastMs, (s, v) => s.SalvageResultDelayFastMs = v, 0, 2000, 25), + Spacer(), + Section("Giving And Trading"), + Int("Give Interval (ms)", s => s.GiveQueueIntervalMs, (s, v) => s.GiveQueueIntervalMs = v, 50, 2000, 50, + "Minimum delay between each item sent by /ra givea commands."), + Spacer(), + Section("Item Info"), + Bool("Describe Items When Selected", s => s.ItemInfoOnSelect, (s, v) => s.ItemInfoOnSelect = v, + "Print a Mag-style description of an item in chat when you select it, identifying it\nfirst when needed. Items the bot selects while looting are skipped.\nAlso: /ra iteminfo on|off."), + Button("Item Info Options", "Open...", () => RynthAiCommands.ApplyRemoteCommand("iteminfo", "window"), + "Which fields the description shows, which item types are described on select, and its chat\ntype and text colour (/ra iteminfo window)."), }), new("Vendoring", new[] @@ -1645,6 +1808,7 @@ internal static class SettingsSchema Note("Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match."), }), + // ── Support ── new("Diagnostics", new[] { Section("Logging & Debugging"), @@ -1679,13 +1843,6 @@ internal static class SettingsSchema () => Compatibility.RynthCoreChatCommands.TryHandle("/rc uicost now", Compatibility.ChatCommandOrigin.Player), "Which parts of the UI frame took the time over the last few seconds, and the slowest frame part by part\n" + "(/rc uicost now)."), - Spacer(), - Section("Server"), - new SettingRow(SettingKind.ServerPick, "Server", - "Which server this character counts as. Auto detects it (the connect host, the world name the server announces, RynthILT).\n" - + "Picking a server forces it on and every other server off, for this character; every plugin follows at once.\n" - + "Also: /rc server pick |auto, and /rc server for the list."), - Note("The list is every server the engine knows: the built-in ones and those declared by the loaded server plugins. \"Settings from\" is the plugin the others ask for that server's settings."), - }), + }, "Support"), }; } diff --git a/src/RynthCore.Engine/UI/PanelDrawScale.cs b/src/RynthCore.Engine/UI/PanelDrawScale.cs index 04ee41e..d8be8e5 100644 --- a/src/RynthCore.Engine/UI/PanelDrawScale.cs +++ b/src/RynthCore.Engine/UI/PanelDrawScale.cs @@ -75,7 +75,7 @@ internal static class PanelDrawScale { string path = FilePath; Directory.CreateDirectory(Path.GetDirectoryName(path)!); - var lines = new List { "# RynthCore: how big each self-drawn window is (percent; Settings > UI > Toolbar)." }; + var lines = new List { "# RynthCore: how big each self-drawn window is (percent; Settings > Interface > In The Retail Toolbar's Place)." }; foreach (var kv in Scales) lines.Add($"{kv.Key}={kv.Value.ToString(CultureInfo.InvariantCulture)}"); File.WriteAllLines(path, lines); _fileTime = File.GetLastWriteTimeUtc(path); diff --git a/src/RynthCore.Engine/UI/PanelLayout.cs b/src/RynthCore.Engine/UI/PanelLayout.cs index 807c748..2673cf2 100644 --- a/src/RynthCore.Engine/UI/PanelLayout.cs +++ b/src/RynthCore.Engine/UI/PanelLayout.cs @@ -176,7 +176,7 @@ internal static class PanelLayout if (!Session.InFlight && Volatile.Read(ref _pendingOp) != null && Interlocked.Exchange(ref _pendingOp, null) is { } op) RunOp(op, imguiReady ? snapshotIni : null); - MarkDefaultReadOnly(EngineSettings.PanelLayoutPerCharacter); // the setting can change in Settings > Display + MarkDefaultReadOnly(EngineSettings.PanelLayoutPerCharacter); // the setting can change in Settings > Interface LayoutSwitch? sw = Session.Tick(Environment.TickCount64, EngineSettings.PanelLayoutPerCharacter, InWorld, LoginLifecycleHooks.LoginCompleteAtMs, SessionStateRegistry.LoginRecorded, Identity()); if (sw is { } s) @@ -353,7 +353,7 @@ internal static class PanelLayout private static string SaveBlockedReason() => PanelLayoutPolicy.DefaultReadOnlyText(InWorld); /// - /// Save Layout Now (Settings > Display): null when the window places go to the layout in use, else + /// Save Layout Now (Settings > Interface): null when the window places go to the layout in use, else /// why they don't (the PC-wide default with the setting on is only read). Any thread (racy read). /// public static string? SavePlacesProblem() @@ -386,12 +386,12 @@ internal static class PanelLayout return PanelLayoutPolicy.StatusLines(active, files, why, defaults, perCharacter); } - // Settings > Display's line, built again only when what it shows changed (it draws every frame). + // Settings > Interface's line, built again only when what it shows changed (it draws every frame). private static Loaded? _lineFor; private static int _lineFlags = -1; private static string _line = string.Empty; - /// Settings > Display: whose layout this client uses and where its files are. Render thread. + /// Settings > Interface: whose layout this client uses and where its files are. Render thread. public static string SettingsLine() { bool perCharacter = EngineSettings.PanelLayoutPerCharacter; @@ -415,13 +415,13 @@ internal static class PanelLayout return _line; } - /// Settings > Display's reset button: there is a character's own layout to reset. + /// Settings > Interface's reset button: there is a character's own layout to reset. public static bool CanResetFromSettings => _initialized && Active != null; - /// Settings > Display's reset confirmation text. + /// Settings > Interface's reset confirmation text. public static string ResetConfirmText() => PanelLayoutPolicy.ResetConfirmText(Active); - /// Settings > Display "Reset this character's layout" (confirmed): /rc layout reset confirm, answered in chat. + /// Settings > Interface "Reset this character's layout" (confirmed): /rc layout reset confirm, answered in chat. public static void ResetFromSettings() { static void Chat(string text, bool ok) => @@ -459,7 +459,7 @@ internal static class PanelLayout return null; } - /// Settings > Display "Layout for New Characters": /rc layout default, answered in chat. + /// Settings > Interface "Layout for New Characters": /rc layout default, answered in chat. public static void MakeDefaultFromSettings() { static void Chat(string text, bool ok) => diff --git a/src/RynthCore.Engine/UI/PanelLayoutPolicy.cs b/src/RynthCore.Engine/UI/PanelLayoutPolicy.cs index f5077dd..6396918 100644 --- a/src/RynthCore.Engine/UI/PanelLayoutPolicy.cs +++ b/src/RynthCore.Engine/UI/PanelLayoutPolicy.cs @@ -229,7 +229,7 @@ internal static class PanelLayoutPolicy public static string ReasonText(DefaultReason why) => why switch { - DefaultReason.SettingOff => "Panel layout per character is off (Settings > Display)", + DefaultReason.SettingOff => "Panel layout per character is off (Settings > Interface)", DefaultReason.NotInWorld => "no character is in the world", DefaultReason.NoCharacterName => "this client doesn't know its character's name yet, so window places aren't saved until it does", DefaultReason.WaitingForName => "still waiting for the character's name", @@ -255,7 +255,7 @@ internal static class PanelLayoutPolicy } /// - /// Settings > Display's line under "Panel Layout Per Character": whose layout is in use and the + /// Settings > Interface's line under "Panel Layout Per Character": whose layout is in use and the /// folder its files are in (a character's), or the PC-wide default and why. /// public static string SettingsLine(LayoutOwner? inUse, LayoutFiles files, DefaultReason why) @@ -267,7 +267,7 @@ internal static class PanelLayoutPolicy return $"In use: the PC-wide default ({ReasonText(why)}): {files.PanelState}."; } - /// Settings > Display's reset confirmation: what "Reset this character's layout" will do. + /// Settings > Interface's reset confirmation: what "Reset this character's layout" will do. public static string ResetConfirmText(LayoutOwner? who) => who is null ? "No character's own layout is in use, so there is nothing to reset." diff --git a/src/RynthCore.Engine/UI/PanelPlacement.cs b/src/RynthCore.Engine/UI/PanelPlacement.cs new file mode 100644 index 0000000..fe1a541 --- /dev/null +++ b/src/RynthCore.Engine/UI/PanelPlacement.cs @@ -0,0 +1,121 @@ +// ============================================================================ +// RynthCore.Engine - UI/PanelPlacement.cs +// Where a docked window is drawn versus where it belongs (2026-11-12, "a few +// of the panels still move around on reload and login (shortcuts, our own +// toolbar)"). +// +// A docked panel (ImGuiPanelHost) and the toolbar (ImGuiBar) each keep a home: +// the spot read from panel_state.txt, or the one the player dragged it to (or +// a script / face asked for). It is drawn at its home pulled onto the screen: +// [0, display - size] on each axis, the home itself while the display is not +// known. The pull is worked out again whenever the window's size or the +// display changes, always from the home, so it lets go as soon as the window +// fits again: a fit-height plugin window (the Shortcuts bar) that comes up one +// frame at its saved, taller height, or one whose content is a line long until +// the game's slots are read, or a client smaller than the place for a moment, +// only moves the window while it lasts. The home is what is saved: a pull on +// screen is never written over the saved spot. +// +// Before, the open's save wrote the pulled-in spot (ImGuiPanelHost.Apply -> +// Persist(entry.Pos)), a later size change was never undone (only a display +// change re-applied the saved spot), and the toolbar's pull on screen stayed +// for the session and was saved by the next size step (its _sizeWatch), so a +// window near the right or bottom edge came back further in after the next +// reload or login. +// +// Pure (no ImGui, no files): tools/PanelLayoutTests. One instance per window, +// AC's render thread. +// ============================================================================ + +using System; +using System.Globalization; +using System.Numerics; + +namespace RynthCore.Engine.UI; + +internal sealed class HomePlace +{ + private Vector2 _size, _display; + + /// The window's own spot (client px): saved, the player's, or asked for. Never a pull on screen. + public Vector2 Home { get; private set; } + + /// Where it is drawn (client px): the home, pulled onto the screen. + public Vector2 Drawn { get; private set; } + + /// A home has been set (a window never placed has none). + public bool IsSet { get; private set; } + + /// Drawn somewhere else than its home (pulled onto the screen). + public bool Pulled => IsSet && Drawn != Home; + + /// The home, and where that draws for on . + public void Set(Vector2 home, Vector2 size, Vector2 display) + { + Home = home; + IsSet = true; + _size = size; + _display = display; + Drawn = OnScreen(home, size, display); + } + + /// + /// The window's size or the display changed (or not): drawn from the home again. True when where it + /// draws changed. Cheap when neither changed. Without a home: nothing. + /// + public bool Fit(Vector2 size, Vector2 display) + { + if (!IsSet || (size == _size && display == _display)) return false; + _size = size; + _display = display; + Vector2 next = OnScreen(Home, size, display); + if (next == Drawn) return false; + Drawn = next; + return true; + } + + /// The player (or a script, a face) put the window at : that is its home now. + public void MoveTo(Vector2 pos, Vector2 size, Vector2 display) => Set(pos, size, display); + + /// + /// Client px: pulled into [0, display - size] on each axis (0 when the window is + /// bigger than the display); itself while the display is not known (1 px or less). + /// + public static Vector2 OnScreen(Vector2 pos, Vector2 size, Vector2 display) + { + if (display.X <= 1 || display.Y <= 1) return pos; + return new Vector2( + Math.Clamp(pos.X, 0, Math.Max(0, display.X - size.X)), + Math.Clamp(pos.Y, 0, Math.Max(0, display.Y - size.Y))); + } + + /// Within half a pixel on both axes (ImGui truncates window positions). + public static bool Near(Vector2 a, Vector2 b) => MathF.Abs(a.X - b.X) <= 0.5f && MathF.Abs(a.Y - b.Y) <= 0.5f; + + /// "(1301,811)" for the log. + public static string Xy(Vector2 v) => + "(" + v.X.ToString("0", CultureInfo.InvariantCulture) + "," + v.Y.ToString("0", CultureInfo.InvariantCulture) + ")"; + + /// "299x89" for the log. + public static string Wh(Vector2 v) => + v.X.ToString("0", CultureInfo.InvariantCulture) + "x" + v.Y.ToString("0", CultureInfo.InvariantCulture); + + /// + /// The load line (one per window per placement): where it draws and why. : where + /// the home came from ("the saved row", "its first-open corner", ...). + /// + public string Describe(string what, string source) + { + string size = _size.X > 0 && _size.Y > 0 ? " " + Wh(_size) : string.Empty; + string where = $"{what} placed at {Xy(Drawn)}{size} from {source} {Xy(Home)}"; + if (_display.X <= 1 || _display.Y <= 1) return where + "; the display size isn't known yet: drawn at its home."; + string display = Wh(_display); + return Pulled + ? where + $"; pulled onto the {display} display (its home is kept and saved; it goes back when it fits)." + : where + $" on the {display} display: as saved."; + } + + /// The line when a size or display change pulls the window off its home (once per window per load). + public string DescribePull(string what) => + $"{what} pulled onto the screen at {Xy(Drawn)}: its home {Xy(Home)} at {Wh(_size)} doesn't fit the {Wh(_display)} display. Not saved; it goes back when it fits."; +} diff --git a/src/RynthCore.Engine/UI/PanelStateStore.cs b/src/RynthCore.Engine/UI/PanelStateStore.cs index ec615f5..b843857 100644 --- a/src/RynthCore.Engine/UI/PanelStateStore.cs +++ b/src/RynthCore.Engine/UI/PanelStateStore.cs @@ -293,7 +293,7 @@ internal static class PanelStateStore } } - /// Rewrite panel_state.txt from the in-memory snapshot (Settings > Display "Save Layout + /// Rewrite panel_state.txt from the in-memory snapshot (Settings > Interface "Save Layout /// Now"). An explicit user action, so unlike the automatic saves it is NOT gated by /// RememberWindowLayout: it writes even when that is off. public static void Flush() @@ -391,7 +391,7 @@ internal static class PanelStateStore private static void Save(bool force = false) { - // Settings > Display "Remember Open Windows and Positions" (default on). Off: keep the last + // Settings > Interface "Remember Open Windows and Positions" (default on). Off: keep the last // file; do not overwrite it while the user is rearranging. if (!force && !EngineSettings.RememberWindowLayout) return; diff --git a/src/RynthCore.Engine/UI/PanelTextScale.cs b/src/RynthCore.Engine/UI/PanelTextScale.cs index 5d6372a..47ee1d6 100644 --- a/src/RynthCore.Engine/UI/PanelTextScale.cs +++ b/src/RynthCore.Engine/UI/PanelTextScale.cs @@ -3,11 +3,11 @@ // Per-panel text size for the in-client (ImGui) panels. Sizes 0-10; 0 is the // normal size, each step is 10% bigger, and the last one ("yourjokin") is // 2.5x. Stored for the whole PC in %LOCALAPPDATA%\RynthCore\panel_text_size.txt -// as "Title=size" lines; set from Settings > Display or from a window's own +// as "Title=size" lines; set from Settings > Interface or from a window's own // title bar (the text size button, Ctrl+wheel; ImGuiPanelHost). One size // ("All Panels") applies to every panel unless "Size each panel separately" // is on. The toolbar (the icon bar, ImGuiBar) has its own size, the "chrome" -// row (Settings > Display > Toolbar, the bar's right-click menu, Ctrl+wheel on +// row (Settings > Interface > Toolbar, the bar's right-click menu, Ctrl+wheel on // the bar, /rc ui barsize); it is independent of All Panels and per-panel sizes. // ============================================================================ diff --git a/src/RynthCore.Engine/UI/QuickSettings.cs b/src/RynthCore.Engine/UI/QuickSettings.cs index a09cbde..b94338e 100644 --- a/src/RynthCore.Engine/UI/QuickSettings.cs +++ b/src/RynthCore.Engine/UI/QuickSettings.cs @@ -8,7 +8,9 @@ // since labels repeat across tabs ("Level 1" in Buffing and Spell Combat). // Only rows that edit or do something can be pinned (Pinnable); a pin whose // row no longer exists (renamed in an update) is kept in the file but not -// drawn, so it comes back if the row does. +// drawn, so it comes back if the row does. A pin saved before a row moved to +// another tab or section (the 2026-11-11 regroup) is found again by its label +// (MigrateKey) and rewritten under the row's new key when the file loads. // // Persisted to %AppData%\RynthCore\rynthai_quick_settings.txt, one key per // line, written in the background (UiBackgroundWriter). The pins are the @@ -52,6 +54,66 @@ internal static class QuickSettings return _byKey!.TryGetValue(key, out SettingRow? row) ? row : null; } + // Where each tab's rows went in the 2026-11-11 regroup (UI/Data/SettingsData.cs). A pin of the old layout + // ("Misc//Video patch") is the row with the same label on one of these tabs (Game Client > Performance). + private static readonly Dictionary MovedTo = new(StringComparer.OrdinalIgnoreCase) + { + ["Display"] = new[] { "Interface", "Game Client", "Hotkeys", "Inventory" }, + ["UI"] = new[] { "Interface" }, + ["Misc"] = new[] { "Game Client", "General", "Combat", "Inventory" }, + ["Recharge"] = new[] { "Recharge", "General", "Buffing" }, + ["Melee Combat"] = new[] { "Combat" }, + ["Spell Combat"] = new[] { "Spell Combat", "General", "Buffing", "Combat" }, + ["Ranges"] = new[] { "Ranges", "Combat" }, + ["Navigation"] = new[] { "Navigation", "General" }, + ["Crafting"] = new[] { "Combat" }, + ["Looting"] = new[] { "Looting", "Inventory" }, + ["Diagnostics"] = new[] { "Diagnostics", "Game Client" }, + }; + + // A row taken out whose pin goes to the row left doing the same thing. + private static readonly Dictionary Replaced = new(StringComparer.OrdinalIgnoreCase) + { + ["Misc//Auto Cram"] = "Inventory/Packs/Enable Autocram", // Misc's copy of Looting's Enable Autocram + }; + + /// + /// The key stands for now: itself while its row exists, else the key of the row it + /// moved to (same label, on a tab the old one's rows went to; the same section first), else null. + /// + public static string? MigrateKey(string key) + { + EnsureIndex(); + if (_byKey!.TryGetValue(key, out SettingRow? row)) return _keyOf![row]; + if (Replaced.TryGetValue(key, out string? replaced)) return RowOf(replaced) != null ? replaced : null; + // Tab names have no '/', but sections and labels can ("War/Void Casting Settings", "Day/Night timer"), + // so the key is matched against each row's label rather than split. + int first = key.IndexOf('/'); + if (first <= 0) return null; + string tab = key[..first], rest = key[(first + 1)..]; // "Section/Label" + if (!MovedTo.TryGetValue(tab, out string[]? tabs)) tabs = new[] { tab }; + string? best = null; + int bestLength = -1; + bool bestSameSection = false; + foreach (KeyValuePair pair in _keyOf!) + { + string label = pair.Key.Label.Trim(), k = pair.Value; + if (label.Length == 0 || rest.Length <= label.Length || rest[^(label.Length + 1)] != '/' || !rest.EndsWith(label, StringComparison.Ordinal)) continue; + string newTab = k[..k.IndexOf('/')]; + if (Array.FindIndex(tabs, t => t.Equals(newTab, StringComparison.OrdinalIgnoreCase)) < 0) continue; + string section = rest[..(rest.Length - label.Length - 1)]; + bool sameSection = k[(newTab.Length + 1)..(k.Length - label.Length - 1)].Equals(section, StringComparison.OrdinalIgnoreCase); + // The longest label that fits wins ("Avoid Lava/Acid Floors" over a row called "Acid Floors"), then the same section. + if (label.Length > bestLength || (label.Length == bestLength && sameSection && !bestSameSection)) + { + best = k; + bestLength = label.Length; + bestSameSection = sameSection; + } + } + return best; + } + /// The pinned keys, in order (a copy). public static string[] Pins { @@ -136,6 +198,7 @@ internal static class QuickSettings private static void EnsureLoaded() { if (_loaded) return; + bool migrated = false; lock (Sync) { if (_loaded) return; @@ -145,12 +208,17 @@ internal static class QuickSettings foreach (string line in File.ReadAllLines(FilePath)) { string key = line.Trim(); - if (key.Length > 0 && !_pins.Contains(key)) _pins.Add(key); + if (key.Length == 0) continue; + // A pin of a row that moved is rewritten under its new key; one that leads nowhere is kept as it is. + string now = MigrateKey(key) ?? key; + migrated |= now != key; + if (!_pins.Contains(now)) _pins.Add(now); } } catch { /* unreadable: start with no pins */ } _loaded = true; } + if (migrated) UiBackgroundWriter.Enqueue("quick settings", Save); } private static void Save() diff --git a/src/RynthCore.Engine/UI/Sections/ServerSelection.cs b/src/RynthCore.Engine/UI/Sections/ServerSelection.cs index e6f6953..8362bfd 100644 --- a/src/RynthCore.Engine/UI/Sections/ServerSelection.cs +++ b/src/RynthCore.Engine/UI/Sections/ServerSelection.cs @@ -1,7 +1,7 @@ // ============================================================================ // RynthCore.Engine - UI/Sections/ServerSelection.cs // "Which server is this?" as one choice, on top of the per-server overrides -// (ServerForce): the Diagnostics page's server picker and "/rc server pick". +// (ServerForce): the Game Client page's server picker and "/rc server pick". // // pick that server forced On, every other server forced Off, so // exactly one server is active whatever detection says; diff --git a/src/RynthCore.Engine/UI/ServerMenus.cs b/src/RynthCore.Engine/UI/ServerMenus.cs index 33e87d0..7e0ec64 100644 --- a/src/RynthCore.Engine/UI/ServerMenus.cs +++ b/src/RynthCore.Engine/UI/ServerMenus.cs @@ -98,8 +98,12 @@ internal static class ServerMenus /// The command that opens section in the Mini Remote. public static string OpenSectionCommand(string sectionId) => "/rc miniremote section " + sectionId; - /// The command that forces on for this character. - public static string ForceCommand(string serverId) => "/rc server " + serverId + " on"; + /// + /// The command that makes this character's world count as : the + /// Settings picker's own "pick" (that server on, every other off), so the picker then shows it + /// instead of "Mixed". "/rc server <id> on" left the others on Auto. + /// + public static string ForceCommand(string serverId) => "/rc server pick " + serverId; /// Every server that has items (active or not), with them. Any thread. public static List Groups(SectionRegistry.Snapshot snap) @@ -262,7 +266,7 @@ internal static class ServerMenus { if (ImGuiNET.ImGui.MenuItem("Treat this world as " + g.Server.Name + "##srvforce_" + g.Server.Id)) Run(ForceCommand(g.Server.Id), showReply: true); - SafeImGui.SetItemTooltip("Saved for this character. Undo with /rc server " + g.Server.Id + " auto, or in the Mini Remote's Char section."); + SafeImGui.SetItemTooltip("Saved for this character. Undo: Settings > Game Client > Server > Auto (detect), or /rc server pick auto."); } return true; } diff --git a/src/RynthCore.Engine/UI/TrackerSettings.cs b/src/RynthCore.Engine/UI/TrackerSettings.cs index 3c8fbab..25b066d 100644 --- a/src/RynthCore.Engine/UI/TrackerSettings.cs +++ b/src/RynthCore.Engine/UI/TrackerSettings.cs @@ -1,22 +1,57 @@ // ============================================================================ // RynthCore.Engine - UI/TrackerSettings.cs -// The Tracker panel's background opacity and its text-only look, shared by its -// ImGui and Avalonia faces: %APPDATA%\RynthCore\rynthtracker_settings.json -// ({"bgAlpha":0-255,"textOnly":false}). +// The Tracker panel's background opacity, its text-only look, the Ledger's full click-through +// and the stat rows it hides, shared by its ImGui and Avalonia faces: +// %APPDATA%\RynthCore\rynthtracker_settings.json +// ({"bgAlpha":0-255,"textOnly":false,"clickThrough":false,"hidden":["lum5m",...]}). // Loaded on the engine init worker; saves go through UiBackgroundWriter so // the ImGui face never writes a file from AC's thread. // ============================================================================ using System; +using System.Collections.Generic; using System.IO; +using System.Text; using System.Text.Json; namespace RynthCore.Engine.UI; +/// A row the Tracker can show: a stable id (saved), the snapshot's label, and what it is. +internal sealed record TrackerStat(string Id, string Label, string Name, string? Note = null); + +/// What the settings file holds (TrackerSettings.Parse). +internal sealed record TrackerSettingsData(int BgAlpha, bool TextOnly, bool ClickThrough, string[] Hidden); + internal static class TrackerSettings { + /// + /// Every row TrackerSource can send, in its order. The id is what "hidden" saves; the label is the + /// snapshot's (UI/Data/PanelSources.cs TrackerSource.Poll). Pass and Rad rows only come on some servers. + /// + internal static readonly TrackerStat[] Stats = + { + new("session", "Session", "Session time"), + new("xpRate", "XP/hr", "XP per hour"), + new("lumRate", "Lum/hr", "Luminance per hour"), + new("lum5m", "Lum/5m", "Luminance, last 5 minutes"), + new("passRate", "Pass/hr", "Pass-up per hour", "Only where the bank is read (ACECustom)."), + new("radRate", "Rad/hr", "Radiance per hour", "Only on Aelrynth, once some is earned."), + new("killRate", "Kls/hr", "Kills per hour"), + new("xp", "XP", "XP total"), + new("lum", "Lum", "Luminance total"), + new("passUp", "Pass-up", "Pass-up total", "Only where the bank is read (ACECustom)."), + new("rad", "Rad", "Radiance total", "Only on Aelrynth, once some is earned."), + new("kills", "Kills", "Kills"), + new("xpPerKill", "XP/kl", "XP per kill"), + new("deaths", "Deaths", "Deaths"), + }; + private static volatile int _bgAlpha = 0xCC; // ~80% private static volatile bool _textOnly; + private static volatile bool _clickThrough; + // Replaced whole on a change (never edited), so the background save reads a settled set. + private static volatile HashSet _hidden = new(StringComparer.Ordinal); + private static volatile int _hiddenVersion; private static volatile bool _loaded; private static readonly object LoadSync = new(); @@ -49,6 +84,56 @@ internal static class TrackerSettings } } + /// + /// Full click-through (2026-11-12, the owner: "It needs to have click through capability"): text + /// only, the Ledger never takes the mouse, even over its numbers, unless Ctrl is held. + /// + public static bool ClickThrough + { + get + { + EnsureLoaded(); + return _clickThrough; + } + } + + /// Goes up each time the hidden set changes (the face rebuilds its rows). + public static int HiddenVersion + { + get + { + EnsureLoaded(); + return _hiddenVersion; + } + } + + /// The stat id for a snapshot label (a label not in is its own id). + public static string StatId(string label) + { + foreach (TrackerStat s in Stats) + if (s.Label == label) return s.Id; + return label; + } + + /// Whether the row with this snapshot label is hidden (2026-11-12: "show/hide some of the stats"). + public static bool IsLabelHidden(string label) => IsHidden(StatId(label)); + + public static bool IsHidden(string id) + { + EnsureLoaded(); + return _hidden.Contains(id); + } + + /// The hidden ids, in order. + public static string[] HiddenIds + { + get + { + EnsureLoaded(); + return Ordered(_hidden); + } + } + /// Sets the alpha now; writes the file in the background. public static void SetBgAlpha(byte alpha, bool save) { @@ -66,6 +151,36 @@ internal static class TrackerSettings UiBackgroundWriter.Enqueue("tracker settings", Save); } + /// Full click-through on or off, saved in the background. + public static void SetClickThrough(bool on) + { + EnsureLoaded(); + _clickThrough = on; + UiBackgroundWriter.Enqueue("tracker settings", Save); + } + + /// Hides or shows one stat (by id), saved in the background. + public static void SetHidden(string id, bool hidden) + { + EnsureLoaded(); + if (!IsKnownId(id) || _hidden.Contains(id) == hidden) return; + var next = new HashSet(_hidden, StringComparer.Ordinal); + if (hidden) next.Add(id); else next.Remove(id); + _hidden = next; + _hiddenVersion++; + UiBackgroundWriter.Enqueue("tracker settings", Save); + } + + /// Shows every stat again, saved in the background. + public static void ShowAll() + { + EnsureLoaded(); + if (_hidden.Count == 0) return; + _hidden = new HashSet(StringComparer.Ordinal); + _hiddenVersion++; + UiBackgroundWriter.Enqueue("tracker settings", Save); + } + public static void EnsureLoaded() { if (_loaded) return; @@ -77,11 +192,11 @@ internal static class TrackerSettings string path = SettingsPath; if (File.Exists(path)) { - using var doc = JsonDocument.Parse(File.ReadAllText(path)); - if (doc.RootElement.TryGetProperty("bgAlpha", out var v)) - _bgAlpha = Math.Clamp(v.GetInt32(), 0, 255); - if (doc.RootElement.TryGetProperty("textOnly", out var t) && t.ValueKind is JsonValueKind.True or JsonValueKind.False) - _textOnly = t.GetBoolean(); + TrackerSettingsData d = Parse(File.ReadAllText(path)); + _bgAlpha = d.BgAlpha; + _textOnly = d.TextOnly; + _clickThrough = d.ClickThrough; + _hidden = new HashSet(d.Hidden, StringComparer.Ordinal); } } catch { } @@ -89,9 +204,68 @@ internal static class TrackerSettings } } + private static bool IsKnownId(string id) + { + foreach (TrackerStat s in Stats) + if (s.Id == id) return true; + return false; + } + + private static string[] Ordered(IReadOnlyCollection ids) + { + var list = new List(); + foreach (TrackerStat s in Stats) + foreach (string id in ids) + if (id == s.Id) { list.Add(id); break; } + return list.ToArray(); + } + + /// + /// The file's settings; a missing key or a value of the wrong kind is the default (opacity ~80%, + /// framed, click-through off, every stat shown); unknown or repeated stat ids are dropped. + /// Throws only when the text is not JSON. + /// + internal static TrackerSettingsData Parse(string json) + { + int bgAlpha = 0xCC; + bool textOnly = false, clickThrough = false; + var hidden = new HashSet(StringComparer.Ordinal); + using var doc = JsonDocument.Parse(json); + JsonElement r = doc.RootElement; + if (r.ValueKind == JsonValueKind.Object) + { + if (r.TryGetProperty("bgAlpha", out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int a)) + bgAlpha = Math.Clamp(a, 0, 255); + if (r.TryGetProperty("textOnly", out var t) && t.ValueKind is JsonValueKind.True or JsonValueKind.False) + textOnly = t.GetBoolean(); + if (r.TryGetProperty("clickThrough", out var c) && c.ValueKind is JsonValueKind.True or JsonValueKind.False) + clickThrough = c.GetBoolean(); + if (r.TryGetProperty("hidden", out var h) && h.ValueKind == JsonValueKind.Array) + foreach (JsonElement e in h.EnumerateArray()) + if (e.ValueKind == JsonValueKind.String && e.GetString() is { } id && IsKnownId(id)) + hidden.Add(id); + } + return new TrackerSettingsData(bgAlpha, textOnly, clickThrough, Ordered(hidden)); + } + /// The settings file's text. - internal static string ToJson(int bgAlpha, bool textOnly) => - $"{{\"bgAlpha\":{bgAlpha},\"textOnly\":{(textOnly ? "true" : "false")}}}"; + internal static string ToJson(int bgAlpha, bool textOnly, bool clickThrough = false, IReadOnlyCollection? hidden = null) + { + var sb = new StringBuilder(); + sb.Append("{\"bgAlpha\":").Append(bgAlpha) + .Append(",\"textOnly\":").Append(textOnly ? "true" : "false") + .Append(",\"clickThrough\":").Append(clickThrough ? "true" : "false") + .Append(",\"hidden\":["); + bool first = true; + foreach (string id in Ordered(hidden ?? Array.Empty())) + { + if (!first) sb.Append(','); + first = false; + sb.Append('"').Append(id).Append('"'); // only known ids (Ordered): plain letters, nothing to escape + } + sb.Append("]}"); + return sb.ToString(); + } private static void Save() { @@ -99,7 +273,7 @@ internal static class TrackerSettings { string path = SettingsPath; Directory.CreateDirectory(Path.GetDirectoryName(path)!); - File.WriteAllText(path, ToJson(_bgAlpha, _textOnly)); + File.WriteAllText(path, ToJson(_bgAlpha, _textOnly, _clickThrough, _hidden)); } catch { } } diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 6d713ad..b86b37a 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -175,7 +175,7 @@ public struct RynthCoreApiNative // v84: every property of an object (/ub propertydump), one record (ObjectProperties.TryParse) public IntPtr GetObjectPropertiesFn; // int GetObjectProperties(uint id, byte* buf, int size) -> record size (copied if <= size), 0 unknown, -1 bad args // v85: answer the server's yes/no prompt (craft chance) without the client's dialog - public IntPtr ArmConfirmationFn; // int ArmConfirmation(uint type, int minPercent, int timeoutMs) -> 1 armed, 0 unavailable, -3 bad args + public IntPtr ArmConfirmationFn; // int ArmConfirmation(uint type, int minPercent, int timeoutMs) -> 1 armed, 0 unavailable, -3 bad args; v97: minPercent | 0x100 = the sticky slot (leave below to the client) public IntPtr GetLastConfirmationFn; // int GetLastConfirmation(uint* type, uint* ctx, int* percent, int* outcome, int* ageMs) -> seq // v86: which server this is, for every plugin (servers, verdicts, overrides, owning plugins) public IntPtr GetServerStateJsonFn; // int GetServerStateJson(byte* buffer, int capacity) -> UTF-8 byte length (>= capacity: too small) diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 5e5da89..20298bb 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -203,6 +203,8 @@ public readonly unsafe struct RynthCoreHost public bool HasGetMergeStackResult => _api.Version >= 81 && _api.GetMergeStackResultFn != IntPtr.Zero; /// v85: and . public bool HasConfirmationAnswers => _api.Version >= 85 && _api.ArmConfirmationFn != IntPtr.Zero && _api.GetLastConfirmationFn != IntPtr.Zero; + /// v97: (a sticky arm that leaves prompts below its minimum to the client). + public bool HasConfirmationLeaveBelow => HasConfirmationAnswers && _api.Version >= 97; public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero; public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero; public bool HasGetLastUseDone => _api.Version >= 70 && _api.GetLastUseDoneFn != IntPtr.Zero; @@ -652,6 +654,15 @@ public readonly unsafe struct RynthCoreHost public const uint YesNo = 7; } + /// Flags OR'ed into 's minPercent. + public static class ConfirmationArmFlags + { + /// v97: the sticky slot. A prompt below the minimum (or without a percent) is left to the client + /// instead of answered No, and the arm stays armed for later prompts until it times out or is disarmed. + /// Engines before v97 refuse it (-3). + public const int LeaveBelow = 0x100; + } + /// What happened to the last prompt (). public static class ConfirmationOutcome { @@ -660,6 +671,7 @@ public readonly unsafe struct RynthCoreHost public const int Accepted = 2; // answered Yes for the plugin public const int Declined = 3; // answered No: the server's percent was below the minimum public const int SendFailed = 4; // armed, but the send failed: the client showed it + public const int AcceptedSticky = 5; // v97: answered Yes by the sticky arm (ArmConfirmationLeaveBelow) } /// @@ -677,6 +689,34 @@ public readonly unsafe struct RynthCoreHost return ((delegate* unmanaged[Cdecl])_api.ArmConfirmationFn)(type, minPercent, timeoutMs); } + /// + /// v97: a sticky arm for prompts of : every one that arrives within + /// (1-120000) is answered Yes when the server's percent is at least + /// (1-100), with outcome ; + /// one below it, or without a percent, is left to the client's own dialog (never answered No). The arm + /// stays until it times out, , or another sticky arm replaces + /// it (one sticky slot per client, shared by every plugin). A one-shot + /// goes first, and its arm or disarm never touches the sticky arm. 1 armed, 0 unavailable, -3 bad + /// arguments, and -3 from an engine before v97 (check first). + /// + public int ArmConfirmationLeaveBelow(uint type, int minPercent, int timeoutMs) + { + if (minPercent < 1 || minPercent > 100 || timeoutMs <= 0) + return -3; + return ArmConfirmation(type, minPercent | ConfirmationArmFlags.LeaveBelow, timeoutMs); + } + + /// + /// v97: drops the sticky arm (); a one-shot arm stays. Does + /// nothing (0) before v97, where a disarm would clear the one-shot arm instead. + /// + public int DisarmConfirmationLeaveBelow(uint type) + { + if (!HasConfirmationLeaveBelow) + return 0; + return ArmConfirmation(type, ConfirmationArmFlags.LeaveBelow, 0); + } + /// /// v85: the last prompt the server sent. counts them (0 = none yet); /// is the server's context for it; is @@ -1582,7 +1622,7 @@ public readonly unsafe struct RynthCoreHost /// /// v90: how big the frameless window draws itself, in percent of normal - /// (30-250; Settings > UI > Toolbar sets it too): 0 asks, -1 goes back to + /// (30-250; Settings > Interface > In The Retail Toolbar's Place sets it too): 0 asks, -1 goes back to /// following the text size, 30-250 sets it. Returns it now: 0 = follow the text size (draw at the /// fonts' size), -1 on an older engine. Any thread; cheap to ask every frame. /// diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index 8434353..7eec6b7 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -36,7 +36,7 @@ - 95 + 97 88 <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 9b0f084..20cb2dd 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -68,6 +68,10 @@ internal static class Program OwnColorPrecedence(); OwnColorQueue(); OwnColorCommand(); + OwnSpansParse(); + OwnSpansCommand(); + OwnSpansQueue(); + OwnSpansOverRules(); SlowRulesNeedStrikes(); Console.WriteLine(); @@ -569,6 +573,109 @@ internal static class Program Check(other == null && ChatOwnColors.TakeArmed(700) == Orange, "armed per thread: another plugin thread's line isn't coloured"); } + // 2026-11-11: colour runs for parts of a line ("nextspans": RynthAi's per-part item info). + private static void OwnSpansParse() + { + Case("own runs: the nextspans payload is read strictly"); + ChatSpan[]? s = ChatOwnColors.ParseSpans("0:15:E6B450;15:15:FFFFFF;40:6:#3fbfff", out string? err); + Check(err == null && s is { Length: 3 }, "three runs"); + Check(s![0] == new ChatSpan(0, 15, 0xFFE6B450) && s[1] == new ChatSpan(15, 15, 0xFFFFFFFF) && s[2] == new ChatSpan(40, 6, 0xFF3FBFFF), + "offsets as given, colours opaque, '#' and lower case allowed"); + Check(ChatOwnColors.ParseSpans(" 2:3:112233 ", out _) is { Length: 1 }, "spaces around the payload are fine"); + + string[] bad = + { + "", "0:5", "0:5:FFFFFF:1", "a:5:FFFFFF", "0:b:FFFFFF", "-1:5:FFFFFF", "0:-5:FFFFFF", "0:0:FFFFFF", + "0:5:FFFFF", "0:5:FFFFFFF", "0:5:GGGGGG", "0:5:orange", "0:5:0xFFFFFF", "+1:5:FFFFFF", "1.5:2:FFFFFF", + "0:5:FFFFFF;", ";0:5:FFFFFF", "0:5:FFFFFF;;6:1:FFFFFF", "10:5:FFFFFF;0:5:FFFFFF", "0:10:FFFFFF;5:5:FFFFFF", + "100001:1:FFFFFF", "0:9999999:FFFFFF", "0:5:FF FFFF", + }; + foreach (string b in bad) + Check(ChatOwnColors.ParseSpans(b, out string? why) == null && why != null, $"refused with a reason: '{b}'"); + + var many = new System.Text.StringBuilder(); + for (int i = 0; i < ChatOwnColors.MaxSpans + 1; i++) many.Append(many.Length > 0 ? ";" : "").Append($"{i}:1:FFFFFF"); + Check(ChatOwnColors.ParseSpans(many.ToString(), out _) == null, $"more than {ChatOwnColors.MaxSpans} runs: refused"); + Check(ChatOwnColors.ParseSpans(new string(' ', 2) + new string('1', ChatOwnColors.MaxPayloadChars + 1), out _) == null, "an over-long payload: refused"); + Check(ChatOwnColors.ParseSpans("0:5:FFFFFF;5:5:000000", out _) is { Length: 2 }, "runs that touch are fine"); + + Check(ChatOwnColors.FitSpans(s, 46, out string? fit) == s && fit == null, "runs inside the line: kept"); + Check(ChatOwnColors.FitSpans(s, 45, out fit) == null && fit != null, "one run past the end: none kept, and why"); + Check(ChatOwnColors.FitSpans(null, 10, out fit) == null && fit == null, "no runs: nothing to say"); + } + + private static void OwnSpansCommand() + { + Case("own runs: SendPluginCommand(\"RynthCore.Chat\", \"nextspans\", ...) arms the next WriteToChat"); + Check(ChatOwnColors.NextSpansAction == "nextspans", "the name RynthAi sends"); + Check(ChatOwnColors.TakeArmedSpans(0) == null, "nothing armed: null"); + Check(ChatOwnColors.HandlePluginCommand("nextspans", "0:4:EE921E", 100, out string? err) && err == null, "understood"); + Check(ChatOwnColors.TakeArmed(100) == null, "it arms no whole-line colour"); + Check(ChatOwnColors.TakeArmedSpans(150) is [{ Start: 0, Length: 4, Argb: Orange }], "the next WriteToChat takes it"); + Check(ChatOwnColors.TakeArmedSpans(160) == null, "only the next one"); + Check(ChatOwnColors.HandlePluginCommand("NextSpans", "0:4:EE921E", 200) && ChatOwnColors.TakeArmedSpans(200 + ChatOwnColors.ArmWindowMs + 1) == null, + "any case; armed too long ago: dropped"); + Check(ChatOwnColors.HandlePluginCommand("nextspans", "0:4:EE921E", 300) && ChatOwnColors.HandlePluginCommand("nextspans", "none", 301) + && ChatOwnColors.TakeArmedSpans(302) == null, "\"none\" disarms (and answers yes: how a plugin asks)"); + Check(ChatOwnColors.HandlePluginCommand("nextspans", "", 303), "\"\" answers yes too"); + ChatOwnColors.HandlePluginCommand("nextspans", "0:4:EE921E", 400); + Check(!ChatOwnColors.HandlePluginCommand("nextspans", "0:4", 401, out err) && err != null && ChatOwnColors.TakeArmedSpans(402) == null, + "a bad payload: refused with a reason, and what was armed before is gone"); + Check(ChatOwnColors.HandlePluginCommand("nextcolor", "#EE921E", 500) && ChatOwnColors.HandlePluginCommand("nextspans", "0:4:FFFFFF", 501) + && ChatOwnColors.TakeArmed(502) == Orange && ChatOwnColors.TakeArmedSpans(502) is { Length: 1 }, "nextcolor then nextspans: both for the same line"); + ChatOwnColors.HandlePluginCommand("nextspans", "0:4:EE921E", 600); + ChatSpan[]? other = null; + var t = new Thread(() => other = ChatOwnColors.TakeArmedSpans(600)); + t.Start(); t.Join(); + Check(other == null && ChatOwnColors.TakeArmedSpans(600) != null, "armed per thread"); + } + + private static void OwnSpansQueue() + { + Case("own runs: noted with the line, handed over when it arrives"); + var q = new ChatOwnColorQueue(); + var runs = new[] { new ChatSpan(0, 15, 0xFFE6B450), new ChatSpan(15, 5, 0xFFFFFFFF) }; + q.Expect(ItemLine + "\n", 0x12, null, runs, 1000); + Check(q.Count == 1, "runs alone are noted"); + Check(q.Take(ItemLine, 0x12, 1100, out ChatSpan[]? got) == null && got == runs, "no whole-line colour; the runs come back"); + q.Expect(ItemLine, 0x12, Orange, runs, 2000); + Check(q.Take(ItemLine, 0x12, 2100, out got) == Orange && got == runs, "both together"); + q.Expect(ItemLine, 0x12, null, null, 3000); + Check(q.Count == 0, "neither: nothing noted"); + q.Expect(ItemLine, 0x12, Orange, 4000); + Check(q.Take(ItemLine, 0x12, 4100, out got) == Orange && got == null, "nextcolor alone: no runs (as before)"); + + Check(ChatOwnColors.ArrivedSpans(runs, ItemLine + "\r\n", ItemLine) == runs, "arrived as written: the runs as they are"); + Check(ChatOwnColors.ArrivedSpans(runs, "Bob<\\Tell> " + ItemLine, "Bob " + ItemLine) == null, + "AC's tell links taken out of it: the offsets don't hold, none"); + Check(ChatOwnColors.ArrivedSpans(null, ItemLine, ItemLine) == null, "none written: none"); + string cut = ItemLine[..18]; + Check(ChatOwnColors.ArrivedSpans(runs, cut, cut) is [{ Start: 0, Length: 15 }, { Start: 15, Length: 3 }], + "a line cut short: the runs inside it, the last one cut"); + Check(ChatOwnColors.ArrivedSpans(runs, ItemLine[..10], ItemLine[..10]) is [{ Start: 0, Length: 10 }], "runs past the cut are dropped"); + } + + private static void OwnSpansOverRules() + { + Case("own runs: drawn under the rules' colours"); + var own = new[] { new ChatSpan(0, 10, 0xFF111111), new ChatSpan(10, 10, 0xFF222222), new ChatSpan(25, 5, 0xFF333333) }; + Check(ChatOwnColors.EffectiveSpans(null, null, false) == null, "none: none"); + Check(ChatOwnColors.EffectiveSpans(own, null, false) == own, "no rule: the plugin's runs"); + var rule = new[] { new ChatSpan(5, 8, 0xFFAAAAAA) }; + Check(ChatOwnColors.EffectiveSpans(null, rule, false) == rule, "no runs of its own: the rule's, as before"); + Check(ChatOwnColors.EffectiveSpans(own, rule, true) == rule, "a rule's line colour wins over the runs (its match colours stay)"); + Check(ChatOwnColors.EffectiveSpans(own, null, true) == null, "...and with no match colours the line is the rule's colour"); + ChatSpan[] eff = ChatOwnColors.EffectiveSpans(own, rule, false)!; + Check(eff is [{ Start: 0, Length: 5, Argb: 0xFF111111 }, { Start: 5, Length: 8, Argb: 0xFFAAAAAA }, { Start: 13, Length: 7, Argb: 0xFF222222 }, + { Start: 25, Length: 5, Argb: 0xFF333333 }], + "a rule's match colour over the runs it overlaps, the runs cut around it"); + var inside = new[] { new ChatSpan(26, 2, 0xFFBBBBBB) }; + Check(ChatOwnColors.EffectiveSpans(own, inside, false) is [_, _, { Start: 25, Length: 1 }, { Start: 26, Length: 2, Argb: 0xFFBBBBBB }, { Start: 28, Length: 2 }], + "a match inside a run splits it"); + for (int i = 1; i < eff.Length; i++) + Check(eff[i].Start >= eff[i - 1].Start + eff[i - 1].Length, "sorted, not overlapping"); + } + private static void LineColorJson() { Case("line colours: lineColors in rynthchat_settings.json"); diff --git a/tools/CombatSettingsTests/Program.cs b/tools/CombatSettingsTests/Program.cs index ce55ce3..0ec04a0 100644 --- a/tools/CombatSettingsTests/Program.cs +++ b/tools/CombatSettingsTests/Program.cs @@ -75,8 +75,8 @@ namespace CombatSettingsTests string tabName = (string)t.GetType().GetProperty("Name")!.GetValue(t)!; tabs[tabName] = ((IEnumerable)t.GetType().GetProperty("Rows")!.GetValue(t)!).Cast().ToList(); } - Check(tabs.ContainsKey("Melee Combat") && tabs.ContainsKey("Spell Combat"), "the Melee Combat and Spell Combat tabs exist"); - if (!tabs.ContainsKey("Melee Combat") || !tabs.ContainsKey("Spell Combat")) return Finish(); + Check(tabs.ContainsKey("Combat") && tabs.ContainsKey("Spell Combat"), "the Combat and Spell Combat tabs exist (Combat was Melee Combat until 2026-11-11)"); + if (!tabs.ContainsKey("Combat") || !tabs.ContainsKey("Spell Combat")) return Finish(); static string Label(object r) => (string?)r.GetType().GetProperty("Label")!.GetValue(r) ?? ""; static string Kind(object r) => r.GetType().GetProperty("Kind")!.GetValue(r)!.ToString()!; @@ -88,17 +88,17 @@ namespace CombatSettingsTests // (tab, label, kind, default shown, min, max) var rows = new (string Tab, string Label, string Kind, double Default, double Min, double Max)[] { - ("Melee Combat", "Variable Min %", "Int", 50, 0, 100), - ("Melee Combat", "Variable Max %", "Int", 100, 0, 100), - ("Melee Combat", "Missile Response", "Combo", 0, 0, 3), - ("Melee Combat", "Hits to trip", "Int", 2, 1, 10), - ("Melee Combat", "Window (s)", "Int", 20, 5, 120), - ("Melee Combat", "Move closer by (m)", "Int", 6, 1, 30), - ("Melee Combat", "Closest (m)", "Int", 3, 1, 30), - ("Melee Combat", "Skip target (s)", "Int", 30, 5, 300), - ("Melee Combat", "Pull Distance (m)", "Int", 20, 3, 100), - ("Melee Combat", "Tag Before Fleeing", "Bool", 1, 0, 1), - ("Spell Combat", "Magic Response", "Combo", 0, 0, 3), + ("Combat", "Variable Min %", "Int", 50, 0, 100), + ("Combat", "Variable Max %", "Int", 100, 0, 100), + ("Combat", "Missile Response", "Combo", 0, 0, 3), + ("Combat", "Hits to trip", "Int", 2, 1, 10), + ("Combat", "Window (s)", "Int", 20, 5, 120), + ("Combat", "Move closer by (m)", "Int", 6, 1, 30), + ("Combat", "Closest (m)", "Int", 3, 1, 30), + ("Combat", "Skip target (s)", "Int", 30, 5, 300), + ("Combat", "Pull Distance (m)", "Int", 20, 3, 100), + ("Combat", "Tag Before Fleeing", "Bool", 1, 0, 1), + ("Combat", "Magic Response", "Combo", 0, 0, 3), // beside Missile Response since 2026-11-11 }; object older = Parse("{\"BoostNavPriority\":true}"); // what an older RynthAi sends object newer = Parse("{\"VariablePowerMin\":50,\"VariablePowerMax\":100,\"MissileEnvironmentResponse\":0,\"MagicEnvironmentResponse\":0," + @@ -119,32 +119,34 @@ namespace CombatSettingsTests // Section headers and spacers of these groups follow the same gate (no empty headers on an older RynthAi). foreach (string sec in new[] { "Variable Power (monster rules)", "Hitting the Environment", "Pull Away (Kite)" }) - foreach (string tab in new[] { "Melee Combat", "Spell Combat" }) + foreach (string tab in new[] { "Combat" }) { object? header = Row(tab, sec, "Section"); if (header == null) continue; Check(!Visible(header, older), $"{tab} / {sec}: the header is hidden for an older RynthAi"); Check(Visible(header, newer), $"{tab} / {sec}: the header shows for a newer one"); } - Check(Row("Melee Combat", "Pull Away (Kite)", "Section") != null && Row("Melee Combat", "Hitting the Environment", "Section") != null - && Row("Melee Combat", "Variable Power (monster rules)", "Section") != null && Row("Spell Combat", "Hitting the Environment", "Section") != null, "all four section headers exist"); + Check(Row("Combat", "Pull Away (Kite)", "Section") != null && Row("Combat", "Hitting the Environment", "Section") != null + && Row("Combat", "Variable Power (monster rules)", "Section") != null, "all three section headers exist"); + Check(Row("Spell Combat", "Hitting the Environment", "Section") == null && Row("Spell Combat", "Magic Response", "Combo") == null, + "Spell Combat no longer has its own Hitting the Environment (Magic Response is on Combat, with the rest)"); // The combos list RynthAi's EnvironmentResponse in its order. - object missile = Row("Melee Combat", "Missile Response", "Combo")!; + object missile = Row("Combat", "Missile Response", "Combo")!; var items = (string[])missile.GetType().GetProperty("Items")!.GetValue(missile)!; Check(items.SequenceEqual(new[] { "Off", "Move closer", "New target", "Move closer, then new target" }), "Missile Response: Off, Move closer, New target, Move closer then new target (RynthAi's order)"); // A row edits only its own property; the rest rides along. object edit = Parse("{\"BoostNavPriority\":true," + sent.TrimStart('{')); - Set(Row("Melee Combat", "Pull Distance (m)", "Int")!, edit, 55); - Set(Row("Melee Combat", "Tag Before Fleeing", "Bool")!, edit, 1); - Set(Row("Spell Combat", "Magic Response", "Combo")!, edit, 1); + Set(Row("Combat", "Pull Distance (m)", "Int")!, edit, 55); + Set(Row("Combat", "Tag Before Fleeing", "Bool")!, edit, 1); + Set(Row("Combat", "Magic Response", "Combo")!, edit, 1); string after = JsonSerializer.Serialize(edit, info); 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"); // The rows an older RynthAi lacks don't change what a plain save sends. - Set(Row("Melee Combat", "Pull Distance (m)", "Int")!, older, 30); // can't happen in the UI (hidden); must not throw + Set(Row("Combat", "Pull Distance (m)", "Int")!, older, 30); // can't happen in the UI (hidden); must not throw Check(true, "setting a hidden row doesn't throw"); // ── The monster rule: Power and Kite ──────────────────────────────────────── diff --git a/tools/ConfirmationResponderTests/ConfirmationResponderTests.csproj b/tools/ConfirmationResponderTests/ConfirmationResponderTests.csproj new file mode 100644 index 0000000..ffed54e --- /dev/null +++ b/tools/ConfirmationResponderTests/ConfirmationResponderTests.csproj @@ -0,0 +1,24 @@ + + + + + Exe + net10.0 + enable + enable + true + ConfirmationResponderTests + + + + + + + diff --git a/tools/ConfirmationResponderTests/Program.cs b/tools/ConfirmationResponderTests/Program.cs new file mode 100644 index 0000000..2915258 --- /dev/null +++ b/tools/ConfirmationResponderTests/Program.cs @@ -0,0 +1,273 @@ +using System.Text; +using RynthCore.Engine.Compatibility; +using P = RynthCore.Engine.Compatibility.ConfirmationArmPolicy; +using V = RynthCore.Engine.Compatibility.ConfirmationArmPolicy.Verdict; + +namespace ConfirmationResponderTests; + +/// +/// What the armed answers do with the server's yes/no prompts (ConfirmationArmPolicy.cs, the pure +/// half of ConfirmationResponder): the v85 one-shot arm, unchanged, and the v97 sticky arm +/// (minPercent | 0x100), which answers Yes at its minimum, leaves a prompt below it to the client's +/// own dialog, stays armed, and never fights a one-shot. CraftInteraction is type 5. +/// +internal static class Program +{ + private const uint Craft = 5, YesNo = 7; + private const int Flag = P.ArmFlagLeaveBelow; + private static int _checks, _failed; + private static string _case = ""; + + /// The responder's two slots, driven the way ConfirmationResponder drives them. + private sealed class Slots + { + public ConfirmationArm OneShot, Sticky; + public bool Available = true; + public int Arm(uint type, int minArg, int timeoutMs, long now) + => P.Apply(ref OneShot, ref Sticky, type, minArg, timeoutMs, now, Available); + public V Request(uint type, int percent, long now) + => P.Decide(ref OneShot, ref Sticky, type, percent, now); + } + + private static int Main() + { + Run(nameof(ArgumentsAreChecked), ArgumentsAreChecked); + Run(nameof(OneShotUnchanged), OneShotUnchanged); + Run(nameof(StickyYesAtTheMinimum), StickyYesAtTheMinimum); + Run(nameof(StickyBelowIsLeftAndStaysArmed), StickyBelowIsLeftAndStaysArmed); + Run(nameof(StickyExpiresAndReArms), StickyExpiresAndReArms); + Run(nameof(OtherTypesAreLeft), OtherTypesAreLeft); + Run(nameof(OneShotGoesFirstAndNeverFights), OneShotGoesFirstAndNeverFights); + Run(nameof(DisarmPicksTheSlot), DisarmPicksTheSlot); + Run(nameof(Unavailable), Unavailable); + Run(nameof(PercentParse), PercentParse); + + Console.WriteLine($"{_checks} check(s), {_failed} failed."); + return _failed == 0 ? 0 : 1; + } + + private static void Run(string name, Action body) + { + _case = name; + try { body(); } + catch (Exception ex) { _checks++; _failed++; Console.WriteLine($"[FAIL] {name}: threw {ex.GetType().Name}: {ex.Message}"); } + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"[FAIL] {_case}: {what}"); + } + + private static void Eq(T actual, T expected, string what) => + Check(EqualityComparer.Default.Equals(actual, expected), $"{what}: expected {expected}, got {actual}"); + + private static void ArgumentsAreChecked() + { + var s = new Slots(); + // v85's rules, as before. + Eq(s.Arm(0, 50, 1000, 0), P.ArmBadArgs, "type 0"); + Eq(s.Arm(Craft, -1, 1000, 0), P.ArmBadArgs, "minimum -1"); + Eq(s.Arm(Craft, 101, 1000, 0), P.ArmBadArgs, "minimum 101"); + Eq(s.Arm(Craft, 50, 120_001, 0), P.ArmBadArgs, "timeout over 120 s"); + Check(!s.OneShot.Armed && !s.Sticky.Armed, "bad arguments arm nothing"); + Eq(s.Arm(Craft, 0, 1000, 0), P.ArmOk, "one-shot, minimum 0"); + Eq(s.Arm(Craft, 100, 120_000, 0), P.ArmOk, "one-shot 100 for 120 s"); + Check(s.OneShot.Armed && s.OneShot.MinPercent == 100 && !s.Sticky.Armed, "a one-shot goes in the one-shot slot"); + + // v97's flag. + Eq(Flag, 0x100, "the flag's value (ABI)"); + s = new Slots(); + Eq(s.Arm(Craft, 100 | Flag, 60_000, 0), P.ArmOk, "sticky 100"); + Check(s.Sticky.Armed && s.Sticky.MinPercent == 100 && !s.OneShot.Armed, "a sticky arm goes in the sticky slot, minimum 100"); + Eq(s.Arm(Craft, 1 | Flag, 60_000, 0), P.ArmOk, "sticky 1"); + Eq(s.Arm(Craft, 0 | Flag, 60_000, 0), P.ArmBadArgs, "sticky with no minimum (would say Yes to everything)"); + Eq(s.Arm(Craft, 101 | Flag, 60_000, 0), P.ArmBadArgs, "sticky 101"); + Eq(s.Arm(Craft, 100 | Flag, 120_001, 0), P.ArmBadArgs, "sticky: the same 120 s cap"); + Eq(s.Arm(Craft, 100 | 0x200, 60_000, 0), P.ArmBadArgs, "an unknown flag bit"); + Eq(s.Arm(Craft, 100 | 0x300, 60_000, 0), P.ArmBadArgs, "the flag with an unknown bit"); + Eq(s.Arm(Craft, int.MinValue | 100, 60_000, 0), P.ArmBadArgs, "the sign bit"); + Eq(s.Sticky.MinPercent, 1, "a refused call leaves the arm before it (sticky 1)"); + // What an engine before v97 does with the flag: its check was minPercent > 100 -> -3. + Check((100 | Flag) > 100 && (1 | Flag) > 100, "the flag makes minPercent > 100, which a v85-v96 engine refuses as bad arguments"); + } + + private static void OneShotUnchanged() + { + long t = 1_000; + var s = new Slots(); + s.Arm(Craft, 80, 15_000, t); + Eq(s.Request(Craft, 90, t + 10), V.Accept, "90% with a minimum of 80: Yes"); + Check(!s.OneShot.Armed, "spent after one answer"); + Eq(s.Request(Craft, 100, t + 20), V.LeaveToClient, "the next prompt is the client's"); + + s.Arm(Craft, 80, 15_000, t); + Eq(s.Request(Craft, 38, t + 10), V.Decline, "38% with a minimum of 80: No (as v85 always did)"); + Check(!s.OneShot.Armed, "spent after a No too"); + + s.Arm(Craft, 80, 15_000, t); + Eq(s.Request(Craft, -1, t + 10), V.Decline, "no percent with a minimum: No"); + + s.Arm(Craft, 0, 15_000, t); + Eq(s.Request(Craft, -1, t + 10), V.Accept, "minimum 0: Yes even without a percent"); + + s.Arm(Craft, 80, 15_000, t); + Eq(s.Request(Craft, 100, t + 15_000), V.Accept, "at the timeout itself: still armed"); + s.Arm(Craft, 80, 15_000, t); + Eq(s.Request(Craft, 100, t + 15_001), V.LeaveToClient, "past the timeout: the client's"); + Check(!s.OneShot.Armed, "an expired arm is dropped"); + + s.Arm(Craft, 80, 15_000, t); + s.Arm(Craft, 50, 15_000, t + 1); + Eq(s.Request(Craft, 60, t + 2), V.Accept, "a new one-shot replaces the old (60% with 50: Yes)"); + Eq(s.Arm(Craft, 0, 0, t + 3), P.ArmOk, "disarm: 1"); + } + + private static void StickyYesAtTheMinimum() + { + long t = 5_000; + var s = new Slots(); + s.Arm(Craft, 100 | Flag, 60_000, t); + for (int i = 0; i < 5; i++) + { + Eq(s.Request(Craft, 100, t + 1_000 * (i + 1)), V.AcceptSticky, $"craft {i + 1} at 100%: Yes (sticky)"); + Check(s.Sticky.Armed, $"still armed after craft {i + 1}"); + } + s.Arm(Craft, 90 | Flag, 60_000, t); + Eq(s.Request(Craft, 90, t + 1), V.AcceptSticky, "90% with a minimum of 90: Yes"); + Eq(s.Request(Craft, 95, t + 2), V.AcceptSticky, "95%: Yes"); + Check(s.Sticky.Armed, "and still armed"); + } + + private static void StickyBelowIsLeftAndStaysArmed() + { + long t = 10_000; + var s = new Slots(); + s.Arm(Craft, 100 | Flag, 60_000, t); + Eq(s.Request(Craft, 99, t + 1), V.LeaveToClient, "99% with a minimum of 100: the client's dialog, never No"); + Check(s.Sticky.Armed, "still armed after a prompt it left"); + Eq(s.Request(Craft, 0, t + 2), V.LeaveToClient, "0%: the client's"); + Eq(s.Request(Craft, -1, t + 3), V.LeaveToClient, "no percent in the text: the client's"); + Check(s.Sticky.Armed, "still armed"); + Eq(s.Request(Craft, 100, t + 4), V.AcceptSticky, "then 100%: Yes"); + Check(s.Sticky.Armed, "still armed after that"); + for (int pct = -1; pct <= 100; pct++) + { + V v = s.Request(Craft, pct, t + 5); + Check(v != V.Decline, $"never No ({pct}%)"); + Eq(v, pct == 100 ? V.AcceptSticky : V.LeaveToClient, $"{pct}% with a minimum of 100"); + } + } + + private static void StickyExpiresAndReArms() + { + long t = 20_000; + var s = new Slots(); + s.Arm(Craft, 100 | Flag, 60_000, t); + Eq(s.Request(Craft, 100, t + 60_000), V.AcceptSticky, "at the timeout itself: Yes"); + Eq(s.Request(Craft, 100, t + 60_001), V.LeaveToClient, "past it: the client's"); + Check(!s.Sticky.Armed, "dropped"); + Eq(s.Request(Craft, 100, t + 60_002), V.LeaveToClient, "and stays dropped"); + + // Re-arming before it runs out keeps it going (what RynthAi does). + s.Arm(Craft, 100 | Flag, 60_000, t); + s.Arm(Craft, 100 | Flag, 60_000, t + 30_000); + Eq(s.Request(Craft, 100, t + 75_000), V.AcceptSticky, "re-armed at +30 s: still Yes at +75 s"); + // A new sticky arm replaces the old one (one sticky slot). + s.Arm(Craft, 90 | Flag, 60_000, t + 76_000); + Eq(s.Request(Craft, 92, t + 76_001), V.AcceptSticky, "re-armed at 90: 92% is Yes"); + } + + private static void OtherTypesAreLeft() + { + long t = 30_000; + var s = new Slots(); + s.Arm(Craft, 100 | Flag, 60_000, t); + Eq(s.Request(YesNo, 100, t + 1), V.LeaveToClient, "another type: the client's"); + Check(s.Sticky.Armed, "the craft arm is kept"); + s.Arm(Craft, 80, 15_000, t); + Eq(s.Request(YesNo, 100, t + 1), V.LeaveToClient, "one-shot, another type: the client's"); + Check(s.OneShot.Armed, "the one-shot is kept for its own type (as before)"); + + var none = new Slots(); + Eq(none.Request(Craft, 100, t), V.LeaveToClient, "unarmed: the client's"); + } + + private static void OneShotGoesFirstAndNeverFights() + { + // A tinker run arms a one-shot per step (Yes at its own minimum, else No) and disarms it when a + // step fails to go out or the run stops; a sticky arm stands the whole time. + long t = 40_000; + var s = new Slots(); + s.Arm(Craft, 100 | Flag, 60_000, t); + s.Arm(Craft, 70, 15_000, t + 1); + Check(s.Sticky.Armed && s.OneShot.Armed, "both armed"); + Eq(s.Request(Craft, 60, t + 2), V.Decline, "the step's prompt: the one-shot's own rule (60% under 70 is No)"); + Check(!s.OneShot.Armed, "the one-shot is spent"); + Check(s.Sticky.Armed, "the sticky arm is untouched"); + Eq(s.Request(Craft, 100, t + 3), V.AcceptSticky, "the next (hand-made) prompt: the sticky arm"); + + s.Arm(Craft, 0, 15_000, t + 4); + Eq(s.Request(Craft, 100, t + 5), V.Accept, "a one-shot's Yes is the one-shot's (not counted as the sticky arm's)"); + + // The sticky arm re-arming mid-step does not replace the step's one-shot. + s.Arm(Craft, 70, 15_000, t + 6); + s.Arm(Craft, 100 | Flag, 60_000, t + 7); + Check(s.OneShot.Armed && s.OneShot.MinPercent == 70, "a sticky re-arm leaves the one-shot as it was"); + Eq(s.Request(Craft, 80, t + 8), V.Accept, "80% on the step: the one-shot's Yes"); + + // The run's disarm (timeout 0, no flag) leaves the sticky arm. + s.Arm(Craft, 70, 15_000, t + 9); + Eq(s.Arm(Craft, 0, 0, t + 10), P.ArmOk, "the run disarms its one-shot"); + Check(!s.OneShot.Armed && s.Sticky.Armed, "only the one-shot is gone"); + Eq(s.Request(Craft, 100, t + 11), V.AcceptSticky, "a 100% prompt after the run: the sticky arm"); + Eq(s.Request(Craft, 50, t + 12), V.LeaveToClient, "a 50% prompt after the run: the client's"); + + // An expired one-shot falls through to the sticky arm. + s.Arm(Craft, 70, 15_000, t + 13); + Eq(s.Request(Craft, 100, t + 13 + 15_001), V.AcceptSticky, "past the one-shot's timeout: the sticky arm"); + } + + private static void DisarmPicksTheSlot() + { + long t = 50_000; + var s = new Slots(); + s.Arm(Craft, 100 | Flag, 60_000, t); + s.Arm(Craft, 70, 15_000, t); + Eq(s.Arm(Craft, Flag, 0, t + 1), P.ArmOk, "sticky disarm (the flag, timeout 0)"); + Check(!s.Sticky.Armed && s.OneShot.Armed, "only the sticky arm is gone"); + Eq(s.Arm(Craft, 100 | Flag, -1, t + 2), P.ArmOk, "a negative timeout with the flag disarms too"); + s.Arm(Craft, 100 | Flag, 60_000, t + 3); + Eq(s.Arm(Craft, 100 | Flag, 0, t + 4), P.ArmOk, "the flag with a minimum and timeout 0: disarm"); + Check(!s.Sticky.Armed, "gone"); + Eq(s.Request(Craft, 100, t + 5), V.Accept, "the one-shot is still there"); + } + + private static void Unavailable() + { + var s = new Slots { Available = false }; + Eq(s.Arm(Craft, 100 | Flag, 60_000, 0), P.ArmUnavailable, "no sender or hook: 0"); + Eq(s.Arm(Craft, 100, 15_000, 0), P.ArmUnavailable, "one-shot: 0"); + Eq(s.Arm(Craft, 101 | Flag, 60_000, 0), P.ArmBadArgs, "bad arguments still -3 first"); + Check(!s.OneShot.Armed && !s.Sticky.Armed, "nothing armed"); + Eq(s.Arm(Craft, Flag, 0, 0), P.ArmOk, "a disarm still answers 1"); + } + + private static int Pct(string s) => P.ParsePercent(Encoding.Latin1.GetBytes(s)); + + private static void PercentParse() + { + Eq(Pct("You determine that you have a 38 percent chance to succeed."), 38, "38"); + Eq(Pct("You determine that you have a 100 percent chance to succeed."), 100, "100"); + Eq(Pct("You determine that you have a 0 percent chance to succeed."), 0, "0"); + Eq(Pct("You determine that you have a 5 percent chance to succeed."), 5, "5"); + Eq(Pct("Are you sure?"), -1, "no percent"); + Eq(Pct(" percent at the start"), -1, "' percent' first"); + Eq(Pct("a percent chance"), -1, "no digits"); + Eq(Pct("1000 percent"), -1, "four digits"); + Eq(Pct("999 percent"), 100, "over 100 reads as 100"); + Eq(Pct(""), -1, "empty"); + } +} diff --git a/tools/PanelLayoutTests/PanelLayoutTests.csproj b/tools/PanelLayoutTests/PanelLayoutTests.csproj index 5d237ee..cd3d439 100644 --- a/tools/PanelLayoutTests/PanelLayoutTests.csproj +++ b/tools/PanelLayoutTests/PanelLayoutTests.csproj @@ -25,6 +25,8 @@ + + diff --git a/tools/PanelLayoutTests/Program.cs b/tools/PanelLayoutTests/Program.cs index 8c2780d..0c0bef0 100644 --- a/tools/PanelLayoutTests/Program.cs +++ b/tools/PanelLayoutTests/Program.cs @@ -66,6 +66,9 @@ namespace PanelLayoutTests Run(HotReloadWithTheNameNotKnownYet); Run(TheDefaultIsOnlyReadInUse); Run(CommandReplies); + Run(PulledOnScreenNeverMovesTheSavedSpot); + Run(TheBarKeepsItsHome); + Run(HomeSurvivesAReloadThroughTheStore); } finally { @@ -328,6 +331,152 @@ namespace PanelLayoutTests NoTempFiles(root); } + // ── where a docked window draws versus its home (UI/PanelPlacement, 2026-11-12) ── + // + // 2026-11-12, reported: "a few of the panels still move around on reload and login (shortcuts, our own + // toolbar)". The Shortcuts bar sits in the bottom-right corner (a fit-height plugin window: its + // height follows its content), the toolbar's size follows its icons, rows and text size. Before, + // a placement pulled onto a smaller screen, or for a taller first frame, was what the open saved + // (ImGuiPanelHost.Apply -> Persist(entry.Pos)) and what the bar's size step saved, and only a + // display change ever undid it. Numbers are the live layout's (1600x900 client). + + private static readonly System.Numerics.Vector2 Full = new(1600, 900); + + private static System.Numerics.Vector2 V(float x, float y) => new(x, y); + + private static void PulledOnScreenNeverMovesTheSavedSpot() + { + Case("placement: a pull onto the screen is drawn, never the home"); + Eq(HomePlace.OnScreen(V(1301, 811), V(299, 89), Full), V(1301, 811), "flush in the bottom-right corner fits as saved"); + Eq(HomePlace.OnScreen(V(1301, 811), V(299, 120), Full), V(1301, 780), "taller than saved: pulled up by the difference"); + Eq(HomePlace.OnScreen(V(1700, -5), V(100, 50), Full), V(1500, 0), "off the right and top: onto the screen"); + Eq(HomePlace.OnScreen(V(1301, 811), V(299, 89), V(0, 0)), V(1301, 811), "the display not known yet: drawn at its home"); + Eq(HomePlace.OnScreen(V(50, 50), V(2000, 1000), Full), V(0, 0), "bigger than the display: its top-left corner"); + Check(HomePlace.Near(V(1319.6f, 811), V(1320, 811)) && !HomePlace.Near(V(1319, 811), V(1320, 811)), "Near is half a pixel"); + + Case("placement: login on a client smaller for a moment"); + var p = new HomePlace(); + p.Set(V(1301, 811), V(299, 89), V(800, 600)); + Eq(p.Drawn, V(501, 511), "on 800x600 it draws inside the screen"); + Check(p.Pulled, "...and knows it was pulled"); + Eq(p.Home, V(1301, 811), "the home (what the open saves) is still the saved spot"); + Check(p.Fit(V(299, 89), Full), "the client grows: drawn again"); + Eq(p.Drawn, V(1301, 811), "back in the corner"); + Check(!p.Pulled, "...not pulled any more"); + Check(!p.Fit(V(299, 89), Full), "nothing changed: nothing to do"); + + Case("placement: a fit-height window, a taller then a shorter first frame"); + p = new HomePlace(); + p.Set(V(1301, 811), V(299, 89), Full); + Check(!p.Pulled, "saved flush in the corner at its height: as saved"); + Check(p.Fit(V(299, 120), Full), "a taller frame (a key row, a bigger draw size) at the bottom edge"); + Eq(p.Drawn, V(1301, 780), "pulled up while it is taller"); + Eq(p.Home, V(1301, 811), "the home doesn't move"); + Check(p.Fit(V(299, 50), Full), "one line tall ('Your shortcuts show once you're in the world.')"); + Eq(p.Drawn, V(1301, 811), "back at its home"); + p.Fit(V(299, 89), Full); + Eq(p.Drawn, V(1301, 811), "its real height: where the player left it"); + + Case("placement: the saved row's height is stale (fit heights aren't saved)"); + p = new HomePlace(); + p.Set(V(1301, 811), V(299, 120), Full); // the row says 120, the content is 89 + Eq(p.Drawn, V(1301, 780), "the first frame at the saved 120 is pulled up"); + p.Fit(V(299, 89), Full); + Eq(p.Drawn, V(1301, 811), "fitted to 89 a frame later: back in the corner"); + Eq(p.Home, V(1301, 811), "the home was never the pulled spot"); + + Case("placement: the player's drag is the new home"); + p.MoveTo(V(900, 700), V(299, 89), Full); + Eq(p.Home, V(900, 700), "dragged: that is the home"); + Eq(p.Drawn, V(900, 700), "...and where it draws"); + p.MoveTo(V(1301, 811), V(299, 89), Full); + p.Fit(V(299, 89), V(1280, 720)); + Eq(p.Drawn, V(981, 631), "a smaller client later pulls it in"); + Eq(p.Home, V(1301, 811), "...and keeps the player's spot"); + + Case("placement: the load line says where and why"); + p = new HomePlace(); + p.Set(V(1301, 811), V(299, 89), V(800, 600)); + string line = p.Describe("Shortcuts", "its saved place"); + Check(line.Contains("Shortcuts placed at (501,511) 299x89 from its saved place (1301,811)", StringComparison.Ordinal) + && line.Contains("pulled onto the 800x600 display", StringComparison.Ordinal), $"a pulled placement: {line}"); + p = new HomePlace(); + p.Set(V(1301, 811), V(299, 89), Full); + line = p.Describe("Shortcuts", "its saved place"); + Check(line.EndsWith("on the 1600x900 display: as saved.", StringComparison.Ordinal), $"as saved: {line}"); + p = new HomePlace(); + p.Set(V(148, 0), V(0, 0), V(0, 0)); + line = p.Describe("the bar", "its saved bar row"); + Check(line.StartsWith("the bar placed at (148,0) from its saved bar row (148,0)", StringComparison.Ordinal) + && line.Contains("isn't known yet", StringComparison.Ordinal), $"no size, no display yet: {line}"); + p = new HomePlace(); + p.Set(V(1301, 811), V(299, 89), Full); + p.Fit(V(299, 120), Full); + line = p.DescribePull("Shortcuts"); + Check(line.Contains("(1301,780)", StringComparison.Ordinal) && line.Contains("home (1301,811) at 299x120", StringComparison.Ordinal) + && line.Contains("Not saved", StringComparison.Ordinal), $"the pull line: {line}"); + Check(!new HomePlace().Fit(V(10, 10), Full), "a window never placed has nothing to fit"); + } + + private static void TheBarKeepsItsHome() + { + Case("the toolbar: icons that come in as plugins load near the right edge"); + var bar = new HomePlace(); + bar.Set(V(1450, 0), V(0, 0), Full); // the size isn't known before its first frame + Eq(bar.Drawn, V(1450, 0), "first frame at its bar row"); + bar.Fit(V(120, 53), Full); + Eq(bar.Drawn, V(1450, 0), "the engine's icons fit"); + Check(bar.Fit(V(260, 53), Full), "plugin windows add icons: wider than the room left"); + Eq(bar.Drawn, V(1340, 0), "pulled left while it is that wide"); + Eq(bar.Home, V(1450, 0), "the bar row's spot is kept (the old _sizeWatch saved the pull)"); + bar.Fit(V(140, 79), Full); + Eq(bar.Drawn, V(1450, 0), "fewer icons a row (three rows): back where the player left it"); + + Case("the toolbar: a text size step and a smaller client"); + bar.Fit(V(150, 400), V(1600, 300)); + Eq(bar.Drawn, V(1450, 0), "taller than a short client: its top stays at 0"); + bar.Fit(V(150, 60), V(1024, 768)); + Eq(bar.Drawn, V(874, 0), "a narrower client: pulled in"); + bar.Fit(V(150, 60), Full); + Eq(bar.Drawn, V(1450, 0), "the client back to full size: back home"); + } + + private static void HomeSurvivesAReloadThroughTheStore() + { + Case("placement through panel_state.txt: what an open saves, read back by the next load"); + string root = NewDir("placement"); + string file = Path.Combine(root, "layouts", "s", "a", "panel_state.txt"); + Directory.CreateDirectory(Path.GetDirectoryName(file)!); + File.WriteAllText(file, "bar=1450,0\r\npanel.Shortcuts=open,1301,811,299,89,docked,0,0\r\n"); + PanelStateStore.SwitchTo(file, flushCurrent: false); + + // The load: a client 800x600 for a moment (or a first frame taller than saved). + Check(PanelStateStore.TryGetPanel("Shortcuts", out var saved), "the row is read"); + var place = new HomePlace(); + place.Set(V((float)saved.Left, (float)saved.Top), V((float)saved.Width, (float)saved.Height), V(800, 600)); + Check(place.Pulled, "drawn pulled in"); + // ImGuiPanelHost.Persist (the open's save) writes the home: + PanelStateStore.SetPanel("Shortcuts", new PanelStateStore.PanelEntry(true, place.Home.X, place.Home.Y, saved.Width, saved.Height)); + Check(File.ReadAllText(file).Contains("panel.Shortcuts=open,1301,811,299,89", StringComparison.Ordinal), "the file keeps the corner"); + Check(place.Drawn != place.Home, "(the drawn spot, which the open wrote before, is somewhere else)"); + + // The bar's pull isn't written at all; only a drag is. + var bar = new HomePlace(); + var row = PanelStateStore.BarPosition!.Value; + bar.Set(V((float)row.Left, (float)row.Top), V(0, 0), Full); + bar.Fit(V(260, 53), Full); + Check(bar.Pulled, "the bar is pulled left"); + + // The next load (a hot reload): the same file, read again. + PanelStateStore.SwitchTo(file, flushCurrent: false); + Check(PanelStateStore.TryGetPanel("Shortcuts", out var again) && again.Left == 1301 && again.Top == 811, "reloaded: Shortcuts in the corner"); + Eq(PanelStateStore.BarPosition, ((double)1450, (double)0), "reloaded: the bar where its row says"); + var next = new HomePlace(); + next.Set(V((float)again.Left, (float)again.Top), V((float)again.Width, (float)again.Height), Full); + Eq(next.Drawn, V(1301, 811), "and drawn there"); + NoTempFiles(root); + } + // ── the session: when to switch, when panels may draw ─────────────── private static readonly LayoutOwner WhoA = PanelLayoutPolicy.Owner(ServerOne, CharA)!; diff --git a/tools/PluginManifestTests/PluginManifestTests.csproj b/tools/PluginManifestTests/PluginManifestTests.csproj index 7a335aa..e6da12d 100644 --- a/tools/PluginManifestTests/PluginManifestTests.csproj +++ b/tools/PluginManifestTests/PluginManifestTests.csproj @@ -42,6 +42,8 @@ + + diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index 9180535..35ec458 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -63,6 +63,7 @@ internal static class Program Run(nameof(WebPanelStructsMatch), WebPanelStructsMatch); Run(nameof(WebPanelCodesMatch), WebPanelCodesMatch); Run(nameof(HasWebPanel_FalseOnOldOrPartialTable), HasWebPanel_FalseOnOldOrPartialTable); + Run(nameof(ConfirmationLeaveBelow_SdkMatchesEngine), ConfirmationLeaveBelow_SdkMatchesEngine); Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum); Run(nameof(DedupeSamePathTwice), DedupeSamePathTwice); Run(nameof(DedupeCaseAndSlashes), DedupeCaseAndSlashes); @@ -690,6 +691,59 @@ internal static class Program Eq(live.NavigateWebPanel(1, ""), (int)WebPanelResult.BadArgs, "navigate empty URL: BadArgs"); } + // v97: ArmConfirmation's leave-below flag (no table change). The SDK's flag is the engine's, the Has* + // needs Version >= 97 and both v85 slots, a bad minimum is refused before the engine is called, and an + // engine before v97 (v85's argument check) refuses the flag as bad arguments. + private static unsafe void ConfirmationLeaveBelow_SdkMatchesEngine() + { + Eq(RynthCoreHost.ConfirmationArmFlags.LeaveBelow, RynthCore.Engine.Compatibility.ConfirmationArmPolicy.ArmFlagLeaveBelow, "SDK flag = engine flag"); + Eq(PluginContractVersion.ConfirmationLeaveBelow, 97u, "ConfirmationLeaveBelow is 97 (96 is reserved)"); + Check(PluginContractVersion.ConfirmationLeaveBelow <= PluginContractVersion.Current, "ConfirmationLeaveBelow at or below current"); + + IntPtr x = (IntPtr)0xDEAD; + RynthCoreHost Host(uint version, IntPtr arm, IntPtr last) + => new RynthCoreHost(new RynthCoreApiNative { Version = version, ArmConfirmationFn = arm, GetLastConfirmationFn = last }); + Check(Host(96, x, x).HasConfirmationAnswers, "v96: one-shot answers"); + Check(!Host(96, x, x).HasConfirmationLeaveBelow, "v96: no leave-below"); + Check(!Host(97, IntPtr.Zero, x).HasConfirmationLeaveBelow, "v97, Arm slot zero: false"); + Check(!Host(97, x, IntPtr.Zero).HasConfirmationLeaveBelow, "v97, GetLast slot zero: false"); + Check(Host(97, x, x).HasConfirmationLeaveBelow, "v97, both slots: true"); + // Refused before the (garbage) slot is called. + Eq(Host(97, x, x).ArmConfirmationLeaveBelow(5, 0, 60_000), -3, "minimum 0: bad arguments"); + Eq(Host(97, x, x).ArmConfirmationLeaveBelow(5, 101, 60_000), -3, "minimum 101: bad arguments"); + + IntPtr oldArm = (IntPtr)(delegate* unmanaged[Cdecl])&OldEngineArm; + IntPtr newArm = (IntPtr)(delegate* unmanaged[Cdecl])&NewEngineArm; + _lastArmMin = 0; + Eq(Host(96, oldArm, x).ArmConfirmationLeaveBelow(5, 100, 60_000), -3, "an engine before v97 refuses the flag"); + Eq(Host(97, newArm, x).ArmConfirmationLeaveBelow(5, 100, 60_000), 1, "a v97 engine arms it"); + Eq(_lastArmMin, 100 | 0x100, "the minimum reaches the engine with the flag"); + Eq(Host(97, newArm, x).ArmConfirmation(5, 100, 15_000), 1, "a one-shot arm on a v97 engine, as before"); + Eq(RynthCoreHost.ConfirmationOutcome.AcceptedSticky, 5, "outcome 5: the sticky arm's Yes (ABI)"); + // The sticky disarm: the flag with timeout 0 on a v97 engine; nothing on an older one (whose disarm + // would clear the one-shot arm instead; the garbage slot shows it is not called). + _lastArmMin = 0; + Eq(Host(97, newArm, x).DisarmConfirmationLeaveBelow(5), 1, "v97: sticky disarm"); + Eq(_lastArmMin, 0x100, "sent as the flag alone"); + Eq(Host(96, x, x).DisarmConfirmationLeaveBelow(5), 0, "v96: not called"); + Eq(Host(97, x, x).ArmConfirmationLeaveBelow(5, 100, 0), -3, "a zero timeout is not a disarm here"); + } + + private static int _lastArmMin; + + // ConfirmationResponder.Arm's checks before v97. + [System.Runtime.InteropServices.UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + private static int OldEngineArm(uint type, int minPercent, int timeoutMs) + => timeoutMs <= 0 ? 1 : type == 0 || minPercent < 0 || minPercent > 100 || timeoutMs > 120_000 ? -3 : 1; + + // v97: the engine's own check. + [System.Runtime.InteropServices.UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] + private static int NewEngineArm(uint type, int minPercent, int timeoutMs) + { + _lastArmMin = minPercent; + return timeoutMs <= 0 ? 1 : RynthCore.Engine.Compatibility.ConfirmationArmPolicy.Validate(type, minPercent, timeoutMs, out _, out _); + } + // v79: the SDK's copies of the training structs must be the engine's, byte for byte. private static void TrainingStructsMirror() { diff --git a/tools/SettingsLayoutTests/OldPinKeys.txt b/tools/SettingsLayoutTests/OldPinKeys.txt new file mode 100644 index 0000000..e89452d --- /dev/null +++ b/tools/SettingsLayoutTests/OldPinKeys.txt @@ -0,0 +1,301 @@ +Display//Show Target Stamina / Mana +Display//RynthAi Dashboard Look +Display//Insert Key Releases the UI +Display//Borderless Windowed +Display/Window and HUD Layout/Remember Open Windows and Positions +Display/Window and HUD Layout/Panel Layout Per Character +Display/Window and HUD Layout/Layout for New Characters +Display/Window and HUD Layout/Reset This Character's Layout +Display/Window and HUD Layout/Remember Game Window Position +Display/Window and HUD Layout/Save Layout Now +Display/Colour Theme/Theme +Display/Colour Theme/Save colours as +Display/Colour Theme/Saved scheme +Display/Colour Theme/Accent +Display/Colour Theme/Highlight +Display/Colour Theme/Background +Display/Colour Theme/Title bars +Display/Colour Theme/Buttons +Display/Colour Theme/Borders +Display/Colour Theme/Text +Display/Colour Theme/Muted text +Display/Colour Theme/Reset Colours +Display/Text Size (in-game panels)/All Panels +Display/Text Size (in-game panels)/Toolbar +Display/Text Size (in-game panels)/Toolbar Rows +Display/Text Size (in-game panels)/Toolbar Icons Per Row +Display/Text Size (in-game panels)/Size Each Panel Separately +Display/Text Size (in-game panels)/RynthAi Dashboard +Display/Text Size (in-game panels)/Meta +Display/Text Size (in-game panels)/Damage +Display/Text Size (in-game panels)/Settings +Display/Text Size (in-game panels)/Monsters +Display/Text Size (in-game panels)/Nav +Display/Text Size (in-game panels)/Items +Display/Text Size (in-game panels)/Lua +Display/Text Size (in-game panels)/Radar +Display/Text Size (in-game panels)/Chat Filters +Display/Text Size (in-game panels)/RynthNav +Display/Text Size (in-game panels)/Vision +Display/Text Size (in-game panels)/Status +Display/Text Size (in-game panels)/Log +Display/Text Size (in-game panels)/Tracker +Display/Item Info/Describe Items When Selected +Display/Item Info/Item Info Options +UI/Radar/Hide retail radar +UI/Power Bar/Hide retail power bar +UI/Vitals/Hide retail vitals bar +UI/Vitals/Lock your vitals plate +UI/Vitals/Grey out what debuffs take +UI/Toolbar/Hide retail toolbar +UI/Toolbar/Shortcut bar +UI/Toolbar/Shortcut bar size +UI/Toolbar/Game panel buttons +UI/Toolbar/Game panel buttons size +UI/Toolbar/Selection +UI/Toolbar/Selection size +UI/Toolbar/Day/Night timer +UI/Toolbar/Day/Night timer size +UI/Toolbar/Shortcut bar 2 +UI/Toolbar/Shortcut bar 2 size +UI/Toolbar/Shortcut bar 3 +UI/Toolbar/Shortcut bar 3 size +UI/Toolbar/Shortcut bar 4 +UI/Toolbar/Shortcut bar 4 size +Misc//Enable FPS Limit +Misc//Focused FPS +Misc//Background FPS +Misc//Video patch +Misc//Frame cap while patched +Misc//Close Client on Server Disconnect +Misc//Background Identify +Misc//Hold reloads while in the world +Misc//Give up holding after (min) +Misc//Auto Cram +Misc//Peace Mode When Idle +Misc//Weapons Back After Heals +Misc//Start Macro On Login +Misc//Patrol On Login +Misc//Resume Meta After Reload +Misc//Escape Acid and Lava +Misc//Yield to VTank +Misc//Enable Raycasting +Misc/Missile Arc Velocities (m/s)/Use Arcs for Missile LoS +Misc/Missile Arc Velocities (m/s)/Bow +Misc/Missile Arc Velocities (m/s)/Crossbow +Misc/Missile Arc Velocities (m/s)/Atlatl +Misc/Missile Arc Velocities (m/s)/Magic Arc +Misc/Missile Arc Velocities (m/s)/Arc Clearance (m) +Misc/Missile Arc Velocities (m/s)/LoS Debug Log +Misc/Monster Blacklist/Attempts Before Blacklist +Misc/Monster Blacklist/Blacklist Timeout (sec) +Misc/Monster Blacklist/No Progress Timeout (sec) +Misc/Give Queue/Give Interval (ms) +Recharge/In Combat — target within Monster Range (%)/Heal At +Recharge/In Combat — target within Monster Range (%)/Re-stam At +Recharge/In Combat — target within Monster Range (%)/Re-stam To +Recharge/In Combat — target within Monster Range (%)/Get Mana At +Recharge/Idle Top-Off — no targets in range (%)/Top HP +Recharge/Idle Top-Off — no targets in range (%)/Top Stam +Recharge/Idle Top-Off — no targets in range (%)/Top Mana +Recharge/Kits & Potions/Use Potions +Recharge/Kits & Potions/Use Buff Items +Recharge/Kits & Potions/Make Field Rations Below +Recharge/Kits & Potions/Use Kits In Magic Mode +Recharge/Kits & Potions/Peace Mode For Kits +Recharge/Kits & Potions/Emergency Heal At +Recharge/Kits & Potions/Stamina To Health At +Recharge/Kits & Potions/Stamina To Health Min Stamina +Recharge/Kits & Potions/Kit Min Success % +Recharge/Kits & Potions/Stamina Kit Min Success % +Recharge/Safety Stops/Stop Macro On Death +Recharge/Safety Stops/Stop Macro On No Components +Recharge/Safety Stops/Recall When Low On Components +Recharge/Safety Stops/Low Tapers At +Recharge/Safety Stops/Low Scarabs At +Recharge/Safety Stops/Stop Macro When Pack Full +Recharge/On Death/Recall On Death +Recharge/On Death/Recall Spell +Recharge/On Death/Recall Item +Recharge/Helper Settings (%) — NOT WIRED YET/Heal Others +Recharge/Helper Settings (%) — NOT WIRED YET/Re-stam Others +Recharge/Helper Settings (%) — NOT WIRED YET/Infuse Others +Melee Combat/Attack Power & Height/Use Recklessness +Melee Combat/Attack Power & Height/Melee Auto Power +Melee Combat/Attack Power & Height/Melee Power % +Melee Combat/Attack Power & Height/Melee Attack Height +Melee Combat/Attack Power & Height/Missile Auto Power +Melee Combat/Attack Power & Height/Missile Power % +Melee Combat/Attack Power & Height/Missile Attack Height +Melee Combat/Variable Power (monster rules)/Variable Min % +Melee Combat/Variable Power (monster rules)/Variable Max % +Melee Combat/Hitting the Environment/Missile Response +Melee Combat/Hitting the Environment/Hits to trip +Melee Combat/Hitting the Environment/Window (s) +Melee Combat/Hitting the Environment/Move closer by (m) +Melee Combat/Hitting the Environment/Closest (m) +Melee Combat/Hitting the Environment/Skip target (s) +Melee Combat/Pull Away (Kite)/Pull Distance (m) +Melee Combat/Pull Away (Kite)/Tag Before Fleeing +Melee Combat/Pull Away (Kite)/Use Native Attack +Melee Combat/Pull Away (Kite)/Summon Pets +Melee Combat/Pull Away (Kite)/Pet Min Monsters +Melee Combat/Pull Away (Kite)/Pet Range +Spell Combat/War/Void Casting Settings/Buff Spell Interval (ms) +Spell Combat/War/Void Casting Settings/Attack Spell Delay (ms) +Spell Combat/War/Void Casting Settings/Cast Dispel Self +Spell Combat/War/Void Casting Settings/Use Dispel Items +Spell Combat/War/Void Casting Settings/Auto Fellowship Management +Spell Combat/War/Void Casting Settings/Open fellowship on create +Spell Combat/War/Void Casting Settings/M. Charges When Off +Spell Combat/Ring Spell Override/Min Ring Targets +Spell Combat/Blast Spell Override/Blast Range (yd) +Spell Combat/Blast Spell Override/Min Blast Targets +Spell Combat/Wall Spell Override/Wall Range (yd) +Spell Combat/Wall Spell Override/Min Wall Targets +Spell Combat/Hitting the Environment/Magic Response +Spell Combat/Spell Difficulty (Min Buffed Skill)/Level 1 +Spell Combat/Spell Difficulty (Min Buffed Skill)/Level 2 +Spell Combat/Spell Difficulty (Min Buffed Skill)/Level 3 +Spell Combat/Spell Difficulty (Min Buffed Skill)/Level 4 +Spell Combat/Spell Difficulty (Min Buffed Skill)/Level 5 +Spell Combat/Spell Difficulty (Min Buffed Skill)/Level 6 +Spell Combat/Spell Difficulty (Min Buffed Skill)/Level 7 +Spell Combat/Spell Difficulty (Min Buffed Skill)/Level 8 +Ranges/Standard Ranges (Yards)/Monster Range +Ranges/Standard Ranges (Yards)/Ring Range +Ranges/Standard Ranges (Yards)/Approach Range +Ranges/Standard Ranges (Yards)/Disengage Range +Ranges/Combat Targeting/Targeting +Ranges/Combat Targeting/Target Lock +Ranges/Combat Targeting/Fight the monster I select +Ranges/Corpse Acquisition (Yards)/Corpse Max (yd) +Ranges/Corpse Acquisition (Yards)/Corpse Min (yd) +Navigation//Boost Nav Priority +Navigation//Nav point reach (yd) +Navigation/Infinite Leaftide/Vaulted Dungeons +Navigation/Nav Marker Display/Breadcrumbs +Navigation/Nav Marker Display/Route Overlay +Navigation/Nav Marker Display/Ring Thickness +Navigation/Nav Marker Display/Line Thickness +Navigation/Nav Marker Display/Height Offset +Navigation/Nav Marker Display/Slope Sink +Navigation/Nav Marker Display/Show Terrain Passability +Navigation/Nav Marker Display/Waypoint Labels +Navigation/Nav Marker Display/Guide Line +Navigation/Doors/Open Doors While Navigating +Navigation/Doors/Door Detection Range (yd) +Navigation/Doors/Only Doors On My Path +Navigation/Doors/Auto-Unlock Doors +Navigation/Getting Back On Route/Go To Closest Waypoint +Navigation/Dungeon Patrol/Coverage +Navigation/Dungeon Patrol/Sight Distance (yd) +Navigation/Dungeon Patrol/Skip Dead Ends Up To (cells) +Navigation/Dungeon Patrol/Avoid Lava/Acid Floors +Navigation/Dungeon Patrol/Distance From Walls (yd) +Navigation/Dungeon Patrol/Walk Into Rooms From (yd) +Navigation/Outdoor Hunt/Hunt Range (yd) +Navigation/Outdoor Hunt/Hunt Radius (yd) +Navigation/Outdoor Hunt/Go for +Navigation/Steering/Stop & Turn Angle +Navigation/Steering/Resume Run Angle +Navigation/Steering/Dead Zone +Navigation/Steering/Sweep Detect Mult +Navigation/Steering/Lookahead (yd) +Navigation/Steering/Turn Rate (deg/s) +Navigation/Steering/Post-Portal Delay (s) +Navigation/Tier 2 Tuning/Speed +Navigation/Tier 2 Tuning/Walk Within (yd) +Navigation/Tier 2 Tuning/Stop Distance (yd) +Navigation/Tier 2 Tuning/Reissue Timeout (ms) +Navigation/Tier 2 Tuning/Max Range (yd) +Navigation/Tier 2 Tuning/Max Landblock Dist +Buffing//Enable Buffing +Buffing//Buff Profiles +Buffing//Rebuff When Idle +Buffing//Rebuff With (seconds left) +Buffing//Also Refresh Under (seconds left) +Buffing//Cast buffs even when an item gives them +Buffing//Buffs Left Out +Buffing/Protections (untick to skip)/Armor +Buffing/Protections (untick to skip)/Fire Protection +Buffing/Protections (untick to skip)/Cold Protection +Buffing/Protections (untick to skip)/Acid Protection +Buffing/Protections (untick to skip)/Lightning Protection +Buffing/Protections (untick to skip)/Blade Protection +Buffing/Protections (untick to skip)/Piercing Protection +Buffing/Protections (untick to skip)/Bludgeoning Protection +Buffing/Banes (untick to skip)/Impenetrability +Buffing/Banes (untick to skip)/Flame Bane +Buffing/Banes (untick to skip)/Frost Bane +Buffing/Banes (untick to skip)/Acid Bane +Buffing/Banes (untick to skip)/Lightning Bane +Buffing/Banes (untick to skip)/Blade Bane +Buffing/Banes (untick to skip)/Piercing Bane +Buffing/Banes (untick to skip)/Bludgeoning Bane +Buffing/Buff Difficulty (Min Buffed Skill)/Level 1 +Buffing/Buff Difficulty (Min Buffed Skill)/Level 2 +Buffing/Buff Difficulty (Min Buffed Skill)/Level 3 +Buffing/Buff Difficulty (Min Buffed Skill)/Level 4 +Buffing/Buff Difficulty (Min Buffed Skill)/Level 5 +Buffing/Buff Difficulty (Min Buffed Skill)/Level 6 +Buffing/Buff Difficulty (Min Buffed Skill)/Level 7 +Buffing/Buff Difficulty (Min Buffed Skill)/Level 8 +Crafting/Missile Ammo Crafting/Enable Missile Crafting +Looting//Enable Looting +Looting//Boost Loot Priority +Looting//Loot Only Rare Corpses +Looting//Learn Unknown Spells +Looting//Pickup with macro off +Looting//Leave the chest open +Looting//Stop Looting When Pack Full +Looting//Jump When Looting +Looting//Jump Height +Looting//Loot Items On Ground +Looting/Corpse Ownership/Loot From +Looting/Corpse Ownership/Recover My Corpse +Looting/Corpse Ownership/Travel Back To My Corpse +Looting/Corpse Ownership/Where Is My Corpse +Looting/Corpse Ownership/Go To My Corpse +Looting/Corpse Ownership/Stop Going To My Corpse +Looting/Inventory Management/Enable Autostack +Looting/Inventory Management/Enable Autocram +Looting/Inventory Management/Unbox Aetheria When Idle +Looting/Inventory Management/Unbox Aetheria Now +Looting/Inventory Management/Combine Salvage Bags +Looting/Inventory Management/Combine Bags During Salvage +Looting/Inventory Management/Tidy Packs Now +Looting/Inventory Management/Floating HUDs +Looting/Inventory Management/Salvage Without The Panel +Looting/Loot Timers (ms)/Optimized defaults +Looting/Loot Timers (ms)/Inter-Item Delay +Looting/Loot Timers (ms)/Content Settle +Looting/Loot Timers (ms)/Empty Corpse Wait +Looting/Loot Timers (ms)/Closing Delay +Looting/Loot Timers (ms)/Assess Window +Looting/Loot Timers (ms)/Loot Retry Timeout +Looting/Loot Timers (ms)/Corpse Open Retry +Looting/Loot Timers (ms)/Corpse Timeout +Looting/Salvage Timers (ms) - First / Fast/Open (First) +Looting/Salvage Timers (ms) - First / Fast/Open (Fast) +Looting/Salvage Timers (ms) - First / Fast/Add Item (First) +Looting/Salvage Timers (ms) - First / Fast/Add Item (Fast) +Looting/Salvage Timers (ms) - First / Fast/Salvage Click +Looting/Salvage Timers (ms) - First / Fast/Result (First) +Looting/Salvage Timers (ms) - First / Fast/Result (Fast) +Vendoring/AutoVendor/Enabled +Vendoring/AutoVendor/Test Mode (only print what it would do) +Vendoring/AutoVendor/Buy +Vendoring/AutoVendor/Sell +Vendoring/AutoVendor/Only Sell From Main Pack +Vendoring/AutoVendor/Show Merchant Info +Vendoring/AutoVendor/Think When Finished +Vendoring//ub vendor open/Tries +Vendoring//ub vendor open/Time Between Tries (ms) +Diagnostics/Logging & Debugging/Debug to chat +Diagnostics/Logging & Debugging/Daily RynthAi log file +Diagnostics/Logging & Debugging/Log Folder +Diagnostics/Logging & Debugging/Old Log Files +Diagnostics/UI Frame Cost/Time the UI frame's parts +Diagnostics/UI Frame Cost/Slow frame (ms) +Diagnostics/UI Frame Cost/Breakdown diff --git a/tools/SettingsLayoutTests/Program.cs b/tools/SettingsLayoutTests/Program.cs new file mode 100644 index 0000000..95e2654 --- /dev/null +++ b/tools/SettingsLayoutTests/Program.cs @@ -0,0 +1,265 @@ +using System.Collections; +using System.Reflection; + +namespace SettingsLayoutTests +{ + // Reaches RynthCore.Engine's internal settings schema and QuickSettings by reflection. See the csproj. + internal static class Program + { + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + + private const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; + + private static Assembly _engine = null!; + private static Type _schema = null!, _quick = null!; + + private static IList Tabs => (IList)_schema.GetField("Tabs", All)!.GetValue(null)!; + private static string Name(object tab) => (string)tab.GetType().GetProperty("Name")!.GetValue(tab)!; + private static IList Rows(object tab) => (IList)tab.GetType().GetProperty("Rows")!.GetValue(tab)!; + private static string Label(object row) => (string?)row.GetType().GetProperty("Label")!.GetValue(row) ?? ""; + private static string Kind(object row) => row.GetType().GetProperty("Kind")!.GetValue(row)!.ToString()!; + private static string? KeyOf(object row) => (string?)_quick.GetMethod("KeyOf", All)!.Invoke(null, new[] { row }); + private static object? RowOf(string key) => _quick.GetMethod("RowOf", All)!.Invoke(null, new object[] { key }); + + private static IEnumerable AllKeys() + { + foreach (object tab in Tabs) + foreach (object row in Rows(tab)) + if (KeyOf(row) is { } key) yield return key; + } + + private static int Main(string[] args) + { + _engine = Assembly.Load("RynthCore.Engine"); + _schema = _engine.GetType("RynthCore.Engine.UI.Data.SettingsSchema", throwOnError: true)!; + _quick = _engine.GetType("RynthCore.Engine.UI.QuickSettings", throwOnError: true)!; + + // -dump : every pin key of this build's layout, one per line (how OldPinKeys.txt was made). + if (args.Length == 2 && args[0] == "-dump") + { + File.WriteAllLines(args[1], AllKeys()); + Console.WriteLine($"wrote {AllKeys().Count()} keys to {args[1]}"); + return 0; + } + + TabList(); + OldPins(); + OldTabNames(); + Moves(); + HuntAndDirtyFighting(); + return Finish(); + } + + // ── Hunt On Login and the Dirty Fighting rotation (rows added 2026-11-11, after the regroup) ────── + private static void HuntAndDirtyFighting() + { + Type settings = _engine.GetType("RynthCore.Engine.UI.Data.RynthAiSettings", throwOnError: true)!; + 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)!; + object Parse(string json) => System.Text.Json.JsonSerializer.Deserialize(json, info)!; + object? P(object s, string name) => settings.GetProperty(name, All)!.GetValue(s); + + object? Row(string tab, string label) + { + foreach (object t in Tabs) + if (Name(t) == tab) + foreach (object r in Rows(t)) + if (Label(r).Trim() == label) return r; + return null; + } + bool Visible(object row, object s) => (bool)row.GetType().GetMethod("IsVisible")!.Invoke(row, new[] { s })!; + double Get(object row, object s) => (double)((Delegate)row.GetType().GetProperty("Get")!.GetValue(row)!).DynamicInvoke(s)!; + void Set(object row, object s, double v) => ((Delegate)row.GetType().GetProperty("Set")!.GetValue(row)!).DynamicInvoke(s, v); + + object? hunt = Row("General", "Hunt On Login"), patrol = Row("General", "Patrol On Login"); + object? rot = Row("Combat", "Dirty Fighting rotation"), order = Row("Combat", "Effect order"), then = Row("Combat", "Then attack"); + Check(hunt != null && patrol != null, "General has Patrol On Login and Hunt On Login"); + Check(rot != null && order != null && then != null, "Combat has the Dirty Fighting rotation, its order and its Then attack"); + if (hunt == null || patrol == null || rot == null || order == null || then == null) return; + Check(KeyOf(hunt) == "General/Starting Up/Hunt On Login", $"Hunt On Login sits under Starting Up (got {KeyOf(hunt)})"); + Check(KeyOf(rot) == "Combat/Attack Power & Height/Dirty Fighting rotation", $"the rotation sits under Attack Power & Height (got {KeyOf(rot)})"); + + // A RynthAi that doesn't send them: the rows hide, and nothing is claimed. + object older = Parse("{\"PatrolOnLogin\":true}"); + Check(!Visible(hunt, older) && !Visible(rot, older) && !Visible(order, older) && !Visible(then, older), "hidden for a RynthAi that doesn't send them"); + Check(P(older, "HuntOnLogin") == null && P(older, "DfHeightRotation") == null, "...and their values stay null (a save leaves them alone)"); + + // One or the other, as RynthAi keeps them. + object s1 = Parse("{\"PatrolOnLogin\":true,\"HuntOnLogin\":false}"); + Check(Visible(hunt, s1) && Get(hunt, s1) == 0, "Hunt On Login shows once RynthAi sends it"); + Set(hunt, s1, 1); + Check((bool?)P(s1, "HuntOnLogin") == true && (bool)P(s1, "PatrolOnLogin")! == false, "ticking Hunt On Login clears Patrol On Login"); + Set(patrol, s1, 1); + Check((bool)P(s1, "PatrolOnLogin")! && (bool?)P(s1, "HuntOnLogin") == false, "ticking Patrol On Login clears Hunt On Login"); + Set(patrol, s1, 0); + Check(!(bool)P(s1, "PatrolOnLogin")! && (bool?)P(s1, "HuntOnLogin") == false, "unticking one leaves the other as it was"); + object s2 = Parse("{\"PatrolOnLogin\":false}"); + Set(patrol, s2, 1); + Check(P(s2, "HuntOnLogin") == null, "Patrol On Login with a RynthAi that has no Hunt On Login sends no Hunt On Login"); + + // The rotation: its two choices show while it's on; RynthAi's values both ways. + object d = Parse("{\"DfHeightRotation\":false,\"DfHeightOrder\":\"HML\",\"DfDefaultHeight\":-1}"); + Check(Visible(rot, d) && !Visible(order, d) && !Visible(then, d), "the rotation shows; its order and Then attack only while it's on"); + Set(rot, d, 1); + Check((bool?)P(d, "DfHeightRotation") == true && Visible(order, d) && Visible(then, d), "on: the order and Then attack show"); + Check(Get(order, d) == 0 && Get(then, d) == 0, "HML is the first order; -1 is 'Attack Height setting'"); + Set(order, d, 5); + Set(then, d, 3); + Check((string?)P(d, "DfHeightOrder") == "LMH" && (int?)P(d, "DfDefaultHeight") == 2, "the last order is LMH; High is 2"); + object d2 = Parse("{\"DfHeightRotation\":true,\"DfHeightOrder\":\"mlh\",\"DfDefaultHeight\":0}"); + Check(Get(order, d2) == 3 && Get(then, d2) == 1, "RynthAi's MLH (any case) and Low (0) read back as theirs"); + var items = (string[])order.GetType().GetProperty("Items")!.GetValue(order)!; + Check(items.Length == 6 && items[0] == "High, Medium, Low" && items[5] == "Low, Medium, High", "the order choices read as RynthAi's window shows them"); + } + + // ── The tabs, in order, and the sidebar's groups ─────────────────────────────── + private static void TabList() + { + string[] want = + { + "Interface", "Game Client", "Hotkeys", + "General", "Recharge", "Combat", "Spell Combat", "Ranges", "Navigation", "Buffing", "Looting", "Inventory", "Vendoring", + "Diagnostics", + }; + string[] got = Tabs.Cast().Select(Name).ToArray(); + Check(got.SequenceEqual(want), $"the tabs, in order (got {string.Join(", ", got)})"); + + var groups = new List(); + foreach (object tab in Tabs) + if (tab.GetType().GetProperty("Group")!.GetValue(tab) is string g) groups.Add(Name(tab) + "=" + g); + Check(groups.SequenceEqual(new[] { "Interface=RynthCore · this PC", "General=RynthAi · saved in the profile", "Diagnostics=Support" }), + $"the sidebar's three group headings sit over Interface, General and Diagnostics (got {string.Join("; ", groups)})"); + + // Every pinnable row has its own key (a duplicate would make two rows one pin). + var keys = AllKeys().ToList(); + Check(keys.Count == keys.Distinct(StringComparer.OrdinalIgnoreCase).Count(), + "no two pinnable rows share a pin key: " + string.Join(", ", keys.GroupBy(k => k, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1).Select(g => g.Key))); + + // No tab starts or ends on an empty heading, and no tab is empty. + foreach (object tab in Tabs) + { + IList rows = Rows(tab); + Check(rows.Count > 0, $"{Name(tab)} has rows"); + if (rows.Count == 0) continue; + Check(Kind(rows[rows.Count - 1]!) is not ("Section" or "Spacer"), $"{Name(tab)} doesn't end on a heading or a spacer"); + } + } + + // ── Every pin of the old layout still finds its row ─────────────────────────── + private static void OldPins() + { + string file = Path.Combine(AppContext.BaseDirectory, "OldPinKeys.txt"); + Check(File.Exists(file), "OldPinKeys.txt is beside the test"); + if (!File.Exists(file)) return; + string[] old = File.ReadAllLines(file).Where(l => l.Trim().Length > 0).ToArray(); + Check(old.Length > 250, $"OldPinKeys.txt holds the old layout's keys ({old.Length})"); + + MethodInfo? migrate = _quick.GetMethod("MigrateKey", All); + Check(migrate != null, "QuickSettings.MigrateKey exists"); + if (migrate == null) return; + string? Migrate(string k) => (string?)migrate.Invoke(null, new object[] { k }); + + // Rows taken out of the panel on purpose (their values stay in the payload). + var gone = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "Misc//Auto Cram", // the same switch as Inventory > Packs > Enable Autocram + "Recharge/Helper Settings (%) — NOT WIRED YET/Heal Others", // inert sliders: hidden until they do something + "Recharge/Helper Settings (%) — NOT WIRED YET/Re-stam Others", + "Recharge/Helper Settings (%) — NOT WIRED YET/Infuse Others", + }; + int moved = 0; + foreach (string key in old) + { + string? now = Migrate(key); + if (gone.Contains(key)) + { + // Auto Cram's pin goes to the one Autocram switch left; the inert sliders' pins go nowhere. + if (key == "Misc//Auto Cram") Check(now != null && RowOf(now) is { } r && Label(r) == "Enable Autocram", $"{key} -> Enable Autocram (got {now})"); + else Check(now == null, $"{key}: its row is gone, so the pin leads nowhere (got {now})"); + continue; + } + // Labels and sections can hold '/', so the old key must end with the row's whole label. + object? row = now == null ? null : RowOf(now); + Check(row != null && key.EndsWith("/" + Label(row).Trim(), StringComparison.Ordinal) && now!.EndsWith("/" + Label(row).Trim(), StringComparison.Ordinal), + $"{key} -> the row with the same label (got {now ?? "nothing"})"); + if (now != null && !string.Equals(now, key, StringComparison.OrdinalIgnoreCase)) moved++; + } + Check(moved > 80, $"a good share of the old keys moved ({moved})"); + + // The owner's two pins (2026-11-11), by name. + Check(Migrate("Misc//Video patch") == "Game Client/Performance/Video patch", "Misc//Video patch -> Game Client/Performance/Video patch"); + Check(Migrate("Spell Combat/Ring Spell Override/Min Ring Targets") == "Spell Combat/Ring Spell Override/Min Ring Targets", "a pin that didn't move stays as it is"); + Check(Migrate("Nowhere/At All/Nothing") == null, "a key no layout ever had leads nowhere (kept in the file, not drawn)"); + } + + // ── /rc settings still opens the tab ─────────────────────────────── + private static void OldTabNames() + { + MethodInfo? find = _schema.GetMethod("FindTab", All); + Check(find != null, "SettingsSchema.FindTab exists"); + if (find == null) return; + string? Find(string n) => find.Invoke(null, new object[] { n }) is { } t ? Name(t) : null; + foreach (var (from, to) in new[] + { + ("Display", "Interface"), ("ui", "Interface"), ("misc", "General"), ("Melee Combat", "Combat"), ("melee", "Combat"), + ("Crafting", "Combat"), ("interface", "Interface"), ("game client", "Game Client"), ("inventory", "Inventory"), + ("buffing", "Buffing"), ("Hotkeys", "Hotkeys"), ("Diagnostics", "Diagnostics"), + }) + Check(Find(from) == to, $"'{from}' opens {to} (got {Find(from) ?? "nothing"})"); + Check(Find("No Such Tab") == null, "an unknown name opens nothing"); + } + + // ── Where a few rows went (the ones other code finds by tab or label) ───────── + private static void Moves() + { + string? Where(string label) + { + foreach (object tab in Tabs) + foreach (object row in Rows(tab)) + if (Label(row).Trim() == label && KeyOf(row) is { } k) return k; + return null; + } + foreach (var (label, key) in new[] + { + ("Hide retail radar", "Interface/Hide The Game's Own/Hide retail radar"), + ("Lock your vitals plate", "Interface/Your Vitals/Lock your vitals plate"), + ("Borderless Windowed", "Game Client/Game Window/Borderless Windowed"), + ("Insert Key Releases the UI", "Hotkeys//Insert Key Releases the UI"), + ("Enable FPS Limit", "Game Client/Performance/Enable FPS Limit"), + ("Close Client on Server Disconnect", "Game Client/Disconnects And Updates/Close Client on Server Disconnect"), + ("Vaulted Dungeons", "General/Server Features/Vaulted Dungeons"), + ("Auto Fellowship Management", "General/Fellowship/Auto Fellowship Management"), + ("Stop Macro On Death", "General/Safety Stops/Stop Macro On Death"), + ("Recall On Death", "General/On Death/Recall On Death"), + ("Buff Spell Interval (ms)", "Buffing//Buff Spell Interval (ms)"), + ("Use Buff Items", "Buffing//Use Buff Items"), + ("Targeting", "Combat/Targeting/Targeting"), + ("Attempts Before Blacklist", "Combat/Targeting/Attempts Before Blacklist"), + ("Enable Raycasting", "Combat/Line Of Sight/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"), + ("Give Interval (ms)", "Inventory/Giving And Trading/Give Interval (ms)"), + ("Describe Items When Selected", "Inventory/Item Info/Describe Items When Selected"), + ("Monster Range", "Ranges/Standard Ranges (Yards)/Monster Range"), + ("Corpse Max (yd)", "Ranges/Corpse Acquisition (Yards)/Corpse Max (yd)"), + ("Coverage", "Navigation/Dungeon Patrol/Coverage"), + }) + Check(Where(label) == key, $"{label} is at {key} (got {Where(label) ?? "nothing"})"); + Check(Where("Auto Cram") == null, "the duplicate Auto Cram row is gone (Inventory > Packs > Enable Autocram stays)"); + Check(Where("Heal Others") == null, "the inert Helper sliders are hidden"); + } + + private static int Finish() + { + Console.WriteLine(_fails == 0 ? $"PASS ({_asserts} checks)" : $"FAIL: {_fails} of {_asserts} checks"); + return _fails == 0 ? 0 : 1; + } + } +} diff --git a/tools/SettingsLayoutTests/SettingsLayoutTests.csproj b/tools/SettingsLayoutTests/SettingsLayoutTests.csproj new file mode 100644 index 0000000..eba9c0a --- /dev/null +++ b/tools/SettingsLayoutTests/SettingsLayoutTests.csproj @@ -0,0 +1,33 @@ + + + + + Exe + net10.0-windows + x86 + win-x86 + false + x86 + enable + enable + true + SettingsLayoutTests + + + + + + + + diff --git a/tools/TrackerSettingsTests/Program.cs b/tools/TrackerSettingsTests/Program.cs index fcd36ac..674ef10 100644 --- a/tools/TrackerSettingsTests/Program.cs +++ b/tools/TrackerSettingsTests/Program.cs @@ -13,7 +13,7 @@ namespace RynthCore.Engine.UI namespace TrackerSettingsTests { // Offline tests for the Tracker's settings file. See the csproj. TrackerSettings loads once per - // process, so the order matters: an old-style file first, then saves. + // process, so the order matters: an old-style file first, then saves; other files go through Parse. internal static class Program { private static int _fails, _asserts; @@ -67,6 +67,83 @@ namespace TrackerSettingsTests Check(!TrackerSettings.TextOnly, "Text only is off at once"); using (var doc = JsonDocument.Parse(File.ReadAllText(file))) Check(!doc.RootElement.GetProperty("textOnly").GetBoolean(), "Text only off is saved"); + + // 2026-11-12: full click-through and hidden stats. + // The old file had neither: click-through off, every stat shown. + Check(!TrackerSettings.ClickThrough, "an old file (no clickThrough) leaves click-through off"); + Check(TrackerSettings.HiddenIds.Length == 0, "an old file (no hidden) shows every stat"); + foreach (TrackerStat s in TrackerSettings.Stats) + Check(!TrackerSettings.IsLabelHidden(s.Label), $"{s.Label} shown by default"); + + // Click-through on: saved with the rest. + TrackerSettings.SetTextOnly(true); + TrackerSettings.SetClickThrough(true); + Check(TrackerSettings.ClickThrough, "click-through is on at once"); + using (var doc = JsonDocument.Parse(File.ReadAllText(file))) + { + Check(doc.RootElement.GetProperty("clickThrough").GetBoolean(), "click-through on is saved"); + Check(doc.RootElement.GetProperty("textOnly").GetBoolean(), "saving click-through keeps Text only"); + Check(doc.RootElement.GetProperty("bgAlpha").GetInt32() == 40, "saving click-through keeps the opacity"); + } + + // Hiding stats: by id, the version goes up, saved in the table's order, the rest kept. + int v0 = TrackerSettings.HiddenVersion; + TrackerSettings.SetHidden("deaths", true); + TrackerSettings.SetHidden("lum5m", true); + Check(TrackerSettings.HiddenVersion > v0, "hiding a stat bumps HiddenVersion"); + Check(TrackerSettings.IsLabelHidden("Deaths") && TrackerSettings.IsLabelHidden("Lum/5m"), "hidden by their labels"); + Check(!TrackerSettings.IsLabelHidden("XP"), "XP still shown"); + int v1 = TrackerSettings.HiddenVersion; + TrackerSettings.SetHidden("deaths", true); + Check(TrackerSettings.HiddenVersion == v1, "hiding a hidden stat again changes nothing"); + TrackerSettings.SetHidden("nonsense", true); + Check(TrackerSettings.HiddenVersion == v1 && !TrackerSettings.IsHidden("nonsense"), "an unknown id is not hidden"); + Check(TrackerSettings.IsLabelHidden("Some new row") == false, "a label not in the table is shown"); + using (var doc = JsonDocument.Parse(File.ReadAllText(file))) + { + var arr = doc.RootElement.GetProperty("hidden").EnumerateArray().Select(e => e.GetString()).ToArray(); + Check(arr.SequenceEqual(new[] { "lum5m", "deaths" }), $"hidden saved in order (got [{string.Join(",", arr)}])"); + Check(doc.RootElement.GetProperty("clickThrough").GetBoolean(), "saving hidden keeps click-through"); + } + TrackerSettings.SetHidden("deaths", false); + Check(!TrackerSettings.IsLabelHidden("Deaths"), "a stat shown again"); + using (var doc = JsonDocument.Parse(File.ReadAllText(file))) + Check(doc.RootElement.GetProperty("hidden").GetArrayLength() == 1, "showing a stat is saved"); + TrackerSettings.ShowAll(); + Check(TrackerSettings.HiddenIds.Length == 0, "Show all clears the hidden set"); + using (var doc = JsonDocument.Parse(File.ReadAllText(file))) + Check(doc.RootElement.GetProperty("hidden").GetArrayLength() == 0, "Show all is saved"); + TrackerSettings.SetClickThrough(false); + using (var doc = JsonDocument.Parse(File.ReadAllText(file))) + Check(!doc.RootElement.GetProperty("clickThrough").GetBoolean(), "click-through off is saved"); + + // The stat ids are unique and every TrackerSource label is in the table. + Check(TrackerSettings.Stats.Select(s => s.Id).Distinct().Count() == TrackerSettings.Stats.Length, "stat ids unique"); + Check(TrackerSettings.Stats.Select(s => s.Label).Distinct().Count() == TrackerSettings.Stats.Length, "stat labels unique"); + foreach (string label in new[] { "Session", "XP/hr", "Lum/hr", "Lum/5m", "Pass/hr", "Rad/hr", "Kls/hr", "XP", "Lum", "Pass-up", "Rad", "Kills", "XP/kl", "Deaths" }) + Check(TrackerSettings.StatId(label) != label, $"{label} has a stat id"); + + // Parse: round trip of ToJson, old files, bad values. + var full = TrackerSettings.Parse(TrackerSettings.ToJson(77, true, true, new[] { "kills", "session", "rad" })); + Check(full.BgAlpha == 77 && full.TextOnly && full.ClickThrough, "Parse(ToJson) keeps opacity, Text only, click-through"); + Check(full.Hidden.SequenceEqual(new[] { "session", "rad", "kills" }), "Parse(ToJson) keeps hidden, in table order"); + var old = TrackerSettings.Parse("{\"bgAlpha\":100,\"textOnly\":true}"); + Check(old.BgAlpha == 100 && old.TextOnly && !old.ClickThrough && old.Hidden.Length == 0, "an old file parses with the new defaults"); + var empty = TrackerSettings.Parse("{}"); + Check(empty.BgAlpha == 0xCC && !empty.TextOnly && !empty.ClickThrough && empty.Hidden.Length == 0, "an empty file is all defaults"); + var bad = TrackerSettings.Parse("{\"bgAlpha\":\"x\",\"textOnly\":1,\"clickThrough\":\"yes\",\"hidden\":\"deaths\"}"); + Check(bad.BgAlpha == 0xCC && !bad.TextOnly && !bad.ClickThrough && bad.Hidden.Length == 0, "values of the wrong kind are ignored"); + var mixed = TrackerSettings.Parse("{\"bgAlpha\":999,\"clickThrough\":true,\"hidden\":[\"deaths\",5,null,\"bogus\",\"deaths\",\"xp\",{}]}"); + Check(mixed.BgAlpha == 255, "an opacity over 255 is clamped"); + Check(mixed.ClickThrough, "a good key beside bad ones is still read"); + Check(mixed.Hidden.SequenceEqual(new[] { "xp", "deaths" }), $"only known string ids kept, once (got [{string.Join(",", mixed.Hidden)}])"); + var notObject = TrackerSettings.Parse("[1,2]"); + Check(notObject.BgAlpha == 0xCC && notObject.Hidden.Length == 0, "a file that is not an object is all defaults"); + using (var doc = JsonDocument.Parse(TrackerSettings.ToJson(10, false))) + { + Check(!doc.RootElement.GetProperty("clickThrough").GetBoolean(), "ToJson defaults click-through off"); + Check(doc.RootElement.GetProperty("hidden").GetArrayLength() == 0, "ToJson defaults to nothing hidden"); + } } catch (Exception ex) { diff --git a/tools/TrackerSettingsTests/TrackerSettingsTests.csproj b/tools/TrackerSettingsTests/TrackerSettingsTests.csproj index d24abd9..2997aef 100644 --- a/tools/TrackerSettingsTests/TrackerSettingsTests.csproj +++ b/tools/TrackerSettingsTests/TrackerSettingsTests.csproj @@ -3,7 +3,8 @@ diff --git a/tools/TrainingCostTests/Program.cs b/tools/TrainingCostTests/Program.cs index 9ce20f3..07dd1de 100644 --- a/tools/TrainingCostTests/Program.cs +++ b/tools/TrainingCostTests/Program.cs @@ -23,6 +23,9 @@ internal static class Program CostsOnTheRealTable(t); AffordableMatchesALinearScan(t); RaiseChecks(t); + MaxAfterUntrainAndRetrain(t); + MaxAcrossTheSpecializedSwitch(t); + MaxNeverAsksPastTheTop(t); } TrainChecks(); ParserRefusesJunk(); @@ -54,8 +57,7 @@ internal static class Program if (raw == null) return null; bool ok = TrainingCosts.TryParseXpTable(raw, out XpTableData t); Check(ok, "XpTable parses"); - Console.WriteLine($" ranks: attributes {t.AttributeXp.Length - 1}, vitals {t.VitalXp.Length - 1}, trained {t.TrainedXp.Length - 1}, specialized {t.SpecializedXp.Length - 1}, levels {t.LevelXp.Length - 1}"); - return ok ? t : null; + Console.WriteLine($" ranks: attributes {t.AttributeXp.Length - 1}, vitals {t.VitalXp.Length - 1}, trained {t.TrainedXp.Length - 1}, specialized {t.SpecializedXp.Length - 1}, levels {t.LevelXp.Length - 1}"); return ok ? t : null; } private static void TableShape(XpTableData t) @@ -163,6 +165,154 @@ internal static class Program Check(TrainingCosts.CheckRaise(a, 50, a[51], long.MaxValue, 1, 0, out _) == RaiseStatus.NotRaisable, "spent already covers the next rank (cost 0) -> NotRaisable, nothing sent"); } + // ── Max after untrain / train again, and across trained <-> specialized ── + // + // A model of ACE's own rules (Player_Skills.cs): UntrainSkill / UnspecializeSkill / ResetSkill + // refund ExperienceSpent and zero ranks and XP; TrainSkill (credits) starts at rank 0 with nothing + // spent; SpecializeSkill at the temple keeps the XP and re-ranks it on the specialized table + // (CalcSkillRank); HandleActionRaiseSkill / SpendSkillXp refuse, without a word, an amount over the + // unassigned XP or over ExperienceLeft (table[top] - spent, never below 0) and otherwise spend it all. + + private sealed class AceSkill + { + public uint[]? Table; // null = untrained + public uint Ranks, Spent; + } + + private static uint AceRank(uint[] table, uint spent) + { + for (int i = table.Length - 1; i >= 0; i--) if (spent >= table[i]) return (uint)i; + return 0; + } + + private static bool AceRaise(AceSkill k, ref long unassigned, long amount) + { + if (k.Table == null || amount <= 0 || amount > uint.MaxValue || amount > unassigned) return false; + if (k.Ranks >= k.Table.Length - 1) return false; // IsMaxRank + long left = Math.Max(0L, (long)k.Table[^1] - k.Spent); // ExperienceLeft + if (amount > left) return false; + unassigned -= amount; + k.Spent += (uint)amount; + k.Ranks = AceRank(k.Table, k.Spent); + return true; + } + + private static void AceUntrain(AceSkill k, ref long unassigned) + { + unassigned += k.Spent; + k.Table = null; k.Ranks = 0; k.Spent = 0; + } + + /// The panel's Max on the numbers the client shows, sent to the model server. True when it was taken. + private static bool PanelMax(AceSkill k, ref long unassigned, out MaxRaisePlan plan) + { + plan = TrainingCosts.PlanMax(k.Table!, k.Ranks, k.Spent, unassigned); + return plan.Ranks > 0 && AceRaise(k, ref unassigned, plan.Cost); + } + + private static void MaxAfterUntrainAndRetrain(XpTableData t) + { + Section("Max after untrain -> train again (ACE: XP refunded, back at rank 0 with nothing spent)"); + uint[] tr = t.TrainedXp; + int top = tr.Length - 1; + + // A maxed trained skill, untrained and trained again: the refund buys every rank back in one Max. + var k = new AceSkill { Table = tr, Ranks = (uint)top, Spent = tr[top] }; + long xp = 50_000_000; + Check(TrainingCosts.IsMax(tr, k.Ranks) && TrainingCosts.PlanMax(tr, k.Ranks, k.Spent, xp) is { Ranks: 0, RanksLeft: 0, Missing: 0 }, + "before: at the top, Max has nothing to buy"); + AceUntrain(k, ref xp); + k.Table = tr; // trained again with credits + Check(k.Ranks == 0 && k.Spent == 0 && xp == 50_000_000 + tr[top], "untrain refunded the XP; trained again at rank 0, nothing spent"); + bool sent = PanelMax(k, ref xp, out MaxRaisePlan p); + Check(p.ReachesTop && p.Ranks == top && p.Cost == tr[top] && p.Missing == 0, + $"Max from rank 0 offers all {top} ranks for {tr[top]:N0} XP (got +{p.Ranks}, {p.Cost:N0})"); + Check(p.Cost <= uint.MaxValue, "rank 0 to the top fits one 32-bit raise"); + Check(sent && k.Ranks == top && TrainingCosts.IsMax(tr, k.Ranks), "the server takes it: the skill is at the top again"); + MaxRaisePlan after = TrainingCosts.PlanMax(tr, k.Ranks, k.Spent, xp); + Check(after.Ranks == 0 && after.RanksLeft == 0 && TrainingCosts.CostOf(tr, k.Ranks, k.Spent, 1) == -1, + "at the true top it still shows max (nothing left, +1 prices -1)"); + + // Partly raised (rank 150 and some way to 151), untrained, trained again: the refund alone buys rank 150 back and more. + uint part = tr[150] + (tr[151] - tr[150]) / 3; + k = new AceSkill { Table = tr, Ranks = 150, Spent = part }; + xp = 0; + AceUntrain(k, ref xp); + k.Table = tr; + sent = PanelMax(k, ref xp, out p); + Check(sent && p.Ranks == 150 && k.Ranks == 150 && k.Spent == tr[150] && xp == part - tr[150], + $"refund only: Max buys the 150 ranks back exactly (+{p.Ranks}); the rest stays unassigned ({xp:N0})"); + Check(!p.ReachesTop && p.Missing == tr[top] - (long)part && p.RanksLeft == top, + $"and says it stops short: {p.Missing:N0} more XP for the top"); + + // Specialized and maxed, untrained (temple: specialized -> trained -> untrained), trained again with + // credits: the trained top costs more than the specialized one, so the refund alone falls short. + uint[] sp = t.SpecializedXp; + k = new AceSkill { Table = sp, Ranks = (uint)(sp.Length - 1), Spent = sp[^1] }; + xp = 0; + AceUntrain(k, ref xp); + k.Table = tr; + p = TrainingCosts.PlanMax(tr, 0, 0, xp); + Check(!p.ReachesTop && p.Ranks < top && p.Missing == (long)tr[top] - sp[^1], + $"specialized max refunded ({sp[^1]:N0}) and trained again: Max (+{p.Ranks} of {top}), {p.Missing:N0} XP short of the trained top"); + sent = PanelMax(k, ref xp, out _); + Check(sent && k.Ranks == p.Ranks, "that partial Max is taken as offered"); + xp += p.Missing; + sent = PanelMax(k, ref xp, out p); + Check(sent && p.ReachesTop && TrainingCosts.IsMax(tr, k.Ranks), "with the missing XP the next Max reaches the top"); + } + + private static void MaxAcrossTheSpecializedSwitch(XpTableData t) + { + Section("Max across trained <-> specialized (the table follows the skill's class)"); + uint[] tr = t.TrainedXp, sp = t.SpecializedXp; + Check(TrainingCosts.TableFor(t, 3, 2) == tr && TrainingCosts.TableFor(t, 3, 3) == sp, "class 2 -> trained table, class 3 -> specialized"); + + // Temple specialize: the XP stays, the ranks are counted again on the specialized table. + uint spent = tr[150] + 12_345; + var k = new AceSkill { Table = sp, Ranks = AceRank(sp, spent), Spent = spent }; + Check(k.Ranks > 150 && sp[k.Ranks] <= spent && (k.Ranks + 1 >= sp.Length || sp[k.Ranks + 1] > spent), + $"trained rank 150 specialized: rank {k.Ranks} on the specialized table, XP kept"); + long xp = long.MaxValue / 4; + MaxRaisePlan p = TrainingCosts.PlanMax(sp, k.Ranks, k.Spent, xp); + Check(p.ReachesTop && p.Cost == sp[^1] - (long)spent, $"Max prices the rest on the specialized table ({p.Cost:N0} XP)"); + Check(PanelMax(k, ref xp, out _) && TrainingCosts.IsMax(sp, k.Ranks), "the server takes it: specialized top"); + + // A trained skill raised past the specialized top, then specialized: already at the top (ACE's ExperienceLeft is 0). + spent = tr[^1]; + k = new AceSkill { Table = sp, Ranks = AceRank(sp, spent), Spent = spent }; + p = TrainingCosts.PlanMax(sp, k.Ranks, k.Spent, xp); + Check(TrainingCosts.IsMax(sp, k.Ranks) && p.Ranks == 0 && p.RanksLeft == 0, "trained XP over the specialized top: shows max, Max buys nothing"); + + // Unspecialize (refund, trained at rank 0): priced on the trained table from rank 0. + k = new AceSkill { Table = sp, Ranks = (uint)(sp.Length - 1), Spent = sp[^1] }; + xp = tr[^1]; + AceUntrain(k, ref xp); + k.Table = tr; + Check(PanelMax(k, ref xp, out p) && p.ReachesTop && p.Ranks == tr.Length - 1 && TrainingCosts.IsMax(tr, k.Ranks), + "unspecialized (XP refunded, trained at rank 0): Max from the trained table reaches the top"); + } + + private static void MaxNeverAsksPastTheTop(XpTableData t) + { + Section("Max never asks the server for more than it allows"); + var rnd = new Random(1112); + bool allTaken = true, neverOver = true; + foreach (var (_, tab) in Tables(t)) + for (int i = 0; i < 500; i++) + { + uint r = (uint)rnd.Next(0, tab.Length - 1); + uint spent = tab[r] + (uint)rnd.Next(0, (int)Math.Min(int.MaxValue, tab[r + 1] - tab[r])); + long xp = rnd.Next(3) switch { 0 => rnd.Next(), 1 => (long)rnd.Next() * 3, _ => long.MaxValue / 4 }; + MaxRaisePlan p = TrainingCosts.PlanMax(tab, r, spent, xp); + if (p.Cost > Math.Max(0L, (long)tab[^1] - spent) || p.Cost > xp) neverOver = false; + var k = new AceSkill { Table = tab, Ranks = r, Spent = spent }; + if (p.Ranks > 0 && !AceRaise(k, ref xp, p.Cost)) allTaken = false; + } + Check(neverOver, "2,000 states: Max's XP is within the unassigned XP and the XP left to the top"); + Check(allTaken, "and the server model takes every one of them"); + } + private static void TrainChecks() { Section("the checks before a train is sent (CheckTrain)"); diff --git a/tools/VaultedSettingTests/Program.cs b/tools/VaultedSettingTests/Program.cs index 4bfb171..cc0b68c 100644 --- a/tools/VaultedSettingTests/Program.cs +++ b/tools/VaultedSettingTests/Program.cs @@ -47,8 +47,8 @@ namespace VaultedSettingTests // The schema row. object? nav = null; foreach (object t in (IEnumerable)schemaType.GetField("Tabs", All)!.GetValue(null)!) - if ((string)t.GetType().GetProperty("Name")!.GetValue(t)! == "Navigation") nav = t; - Check(nav != null, "a Navigation tab"); + if ((string)t.GetType().GetProperty("Name")!.GetValue(t)! == "General") nav = t; + Check(nav != null, "a General tab (the row moved there from Navigation on 2026-11-11)"); if (nav == null) return Finish(); string label = (string)schemaType.GetField("VaultedDungeonsLabel", All)!.GetValue(null)!; @@ -56,7 +56,7 @@ namespace VaultedSettingTests var matches = new List(); foreach (object r in (IEnumerable)nav.GetType().GetProperty("Rows")!.GetValue(nav)!) if ((string?)r.GetType().GetProperty("Label")!.GetValue(r) == label) matches.Add(r); - Check(matches.Count == 1, "exactly one Vaulted Dungeons row, under Navigation"); + Check(matches.Count == 1, "exactly one Vaulted Dungeons row, under General"); if (matches.Count != 1) return Finish(); object row = matches[0]; diff --git a/tools/VaultedSettingTests/VaultedSettingTests.csproj b/tools/VaultedSettingTests/VaultedSettingTests.csproj index 6c5d528..ba596fa 100644 --- a/tools/VaultedSettingTests/VaultedSettingTests.csproj +++ b/tools/VaultedSettingTests/VaultedSettingTests.csproj @@ -1,7 +1,7 @@