diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 64e5ea8..fa14668 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -33,6 +33,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` +## Barlow Semi Condensed + +- What: the Barlow Semi Condensed font, SemiBold and Bold (`BarlowSemiCondensed-SemiBold.ttf`, `BarlowSemiCondensed-Bold.ttf`), the narrow label face of the instrument dashboard (plugin windows get it through GetUiFont, Narrow*). +- Where: `src/RynthCore.Engine/Assets/Fonts/`, embedded in `RynthCore.Engine.dll` as resources. +- Source: https://github.com/google/fonts/tree/main/ofl/barlowsemicondensed (The Barlow Project Authors, https://github.com/jpt/barlow) +- Licence: SIL Open Font License 1.1, in full in `src/RynthCore.Engine/Assets/Fonts/Barlow.LICENSE`. The fonts are bundled unmodified; the licence allows bundling them with software, not selling them alone. + +``` +Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +``` + ## Chorizite DatReaderWriter (format reference for the dat readers) - What: the layout of Asheron's Call .dat files (header, block chains, the directory B-tree) and of the Texture and Palette files, used as the reference when RynthCore's own dat reader and icon decoder were written (2026-10-05). The code is RynthCore's own (MIT); this notice is kept because the library was the format reference. diff --git a/installer/Publish-Update.ps1 b/installer/Publish-Update.ps1 index 8dcc940..afba766 100644 --- a/installer/Publish-Update.ps1 +++ b/installer/Publish-Update.ps1 @@ -307,7 +307,7 @@ if ($SkipTests) { # engine checks at load and what the launcher's EngineBlocker holds updates by. This used to force # -p:RynthPluginMinEngineApi=88 on every plugin, a constant that offered plugins calling v89 SDK # members to API-88 cores (structural audit 2026-10-21, F5 / #7). -$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory", "RynthSort", "RynthNet" +$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory", "RynthSort", "RynthNet", "RynthDefective" # Server plugins (the RynthServers repository since 2026-10-21; ServerPack is SilentKelpie's): one per # game server, each loaded by the engine only for its own server. They go in the feed only, so the # launcher offers each one on its Server plugins tab for the player to install; not in @@ -412,6 +412,7 @@ Extract this zip into C:\Games - it creates: C:\Games\RynthSuite\RynthInventory\ RynthInventory plugin (search every character's items) C:\Games\RynthSuite\RynthSort\ RynthSort plugin (keeps your packs sorted; replaces the RynthSort Lua script) C:\Games\RynthSuite\RynthNet\ RynthNet plugin (links your clients on this PC: /ub bc, shared vitals, the Characters panel) + C:\Games\RynthSuite\RynthDefective\ RynthDefective plugin (a shortcut bar, AC's panel buttons and the Selection, in place of the retail toolbar) C:\Games\RynthCore\NavData\ RynthNav's portals and Atlas Plugins for one game server (RynthILT for Infinite Leaftide, RynthThreads for @@ -550,6 +551,7 @@ $pluginDescriptions = @{ RynthILT = "Infinite Leaftide only: the ILT Hub (the Mini Remote's banking, gear, charms and games tabs), the Guardian, bounty tracking and progression planning." RynthThreads = "DreamWeave only: records Fragment Press results and works out what each component brings." RynthNet = "Links your characters on this PC: broadcast commands (/ub bc), shared vitals and the Characters panel." + RynthDefective = "A shortcut bar with AC's own keys, buttons for AC's panels and the Selection, in place of the retail toolbar." } # Plugin manifests (embedded in each DLL by the SDK's build targets): each plugin's minEngineApi # goes into its feed entry, and the core entry says its engine's API ("engineApi"), so launchers diff --git a/runtime-patches/.gitattributes b/runtime-patches/.gitattributes new file mode 100644 index 0000000..a204813 --- /dev/null +++ b/runtime-patches/.gitattributes @@ -0,0 +1,3 @@ +# Byte for byte: a patch with CRLF line endings no longer applies. +*.patch -text +*.dll binary diff --git a/runtime-patches/coreclr-10.0.12-x86/README.md b/runtime-patches/coreclr-10.0.12-x86/README.md new file mode 100644 index 0000000..2eaf862 --- /dev/null +++ b/runtime-patches/coreclr-10.0.12-x86/README.md @@ -0,0 +1,57 @@ +# Patched CoreCLR 10.0.12 (x86) + +`coreclr.dll`, `mscordaccore.dll` (the DAC) and `mscordbi.dll` built from dotnet/runtime **v10.0.12** +with one change, `tls-no-reuse.patch`. `scripts\Publish-EngineCoreClr.ps1` lays them over the +runtime pack's own files in `Runtime\dotnet` (the installer's staging and a full local deploy). The +official ReadyToRun `System.Private.CoreLib.dll` and `clrjit.dll` stay: their source is unchanged. + +File version 10.0.1226.52301, product version `@Commit: f2f2e4642…` (the patch commit), so a crash +event or dump shows which runtime it was. + +## Why + +Clients that had hot-reloaded the engine crashed minutes later: random statics of live engine and +plugin types read null or garbage, then an access violation (.NET Runtime event 1023/1026, a 1 GB +`clr__*.dmp`). It is a CoreCLR bug, open upstream as dotnet/runtime #135441 (also #135588, +#134928; Microsoft's fix, PR #134983, was unmerged on 2026-10-23 and in no released 10.0.x; 10.0.13 +has the bug too). + +When a thread exits, `FreeLoaderAllocatorHandlesForTLSData` frees each of its collectible +thread-static handles against whichever LoaderAllocator *now* owns that TLS index. Unloading a context +only marks its indices cleared, and `GetTLSIndexForThreadStatic` hands a cleared index to the next +type that asks. So a thread that touched a thread static before a hot reload (a ThreadPool worker, +retiring ~20 s after it goes idle) frees an unrelated live slot in the new generation's handle table +when it exits, and whatever was kept alive there is collected. + +The patch: a cleared collectible index is never reused (always `g_NextTLSSlot++`). A thread's +leftover handles then only ever point at cleared indices, which `CollectibleEntries()` skips, and +they are dropped with the thread's arrays. Cost: the index space grows by the number of collectible +types with thread statics per generation (a few bytes per thread per type). + +## Tested (2026-10-23) + +- Offline repro `C:\Projects\reloadbug` (Host.dll + Victim.dll, `run.ps1`, `test-patched.ps1`): stock + 10.0.12 and 10.0.13 corrupt 16 statics per round or crash (AV); patched, 0 in 300 rounds in every + mode (dedicated thread, statics in the reused slots, ThreadPool workers retiring); the control + (thread exits before the unload) is clean on both. +- Freya (test client) on the patched runtime: 20 engine hot reloads 4 minutes apart, no crash, no + dump, each old generation unloaded (+38 MB). On the stock runtime that morning both hot reloads + crashed within 3-16 minutes. + +## Build it again + +``` +git clone --depth 1 -b v10.0.12 https://github.com/dotnet/runtime C:\Projects\rt (core.longpaths true) +git -C C:\Projects\rt am tls-no-reuse.patch +C:\Projects\rt\build.cmd -subset clr.runtime -arch x86 -c Release /p:NuGetAudit=false /p:OfficialBuildId=20261023.1 +``` + +Output: `artifacts\bin\coreclr\windows.x86.Release\` (symbols in `PDB\`; kept on Tom's PC at +`C:\Projects\runtime-symbols\coreclr-10.0.1226.52301`). `NuGetAudit=false`: two build-time tasks use a +package with advisories published after the tag; nothing of them ships. Needs ~10 GB free. + +## When to drop it + +When a 10.0.x with the upstream fix ships: move the runtime pack to it and delete this folder. +A runtime pack of another version than 10.0.12 makes `Publish-EngineCoreClr.ps1` refuse (a coreclr +must match its CoreLib): rebuild the patch for that version, or drop it. diff --git a/runtime-patches/coreclr-10.0.12-x86/coreclr.dll b/runtime-patches/coreclr-10.0.12-x86/coreclr.dll new file mode 100644 index 0000000..f2576b4 Binary files /dev/null and b/runtime-patches/coreclr-10.0.12-x86/coreclr.dll differ diff --git a/runtime-patches/coreclr-10.0.12-x86/mscordaccore.dll b/runtime-patches/coreclr-10.0.12-x86/mscordaccore.dll new file mode 100644 index 0000000..11ae9d0 Binary files /dev/null and b/runtime-patches/coreclr-10.0.12-x86/mscordaccore.dll differ diff --git a/runtime-patches/coreclr-10.0.12-x86/mscordbi.dll b/runtime-patches/coreclr-10.0.12-x86/mscordbi.dll new file mode 100644 index 0000000..0bb286a Binary files /dev/null and b/runtime-patches/coreclr-10.0.12-x86/mscordbi.dll differ diff --git a/runtime-patches/coreclr-10.0.12-x86/tls-no-reuse.patch b/runtime-patches/coreclr-10.0.12-x86/tls-no-reuse.patch new file mode 100644 index 0000000..8847dc8 --- /dev/null +++ b/runtime-patches/coreclr-10.0.12-x86/tls-no-reuse.patch @@ -0,0 +1,44 @@ +From f2f2e4642c7d86fd6cf4503762051b1ecb6f12f7 Mon Sep 17 00:00:00 2001 +From: Tom Bohar +Date: Fri, 23 Oct 2026 08:07:39 -0400 +Subject: [PATCH] Never reuse a cleared collectible thread-static TLS index + (RynthCore hot-reload statics crash, dotnet/runtime #135441) + +Co-Authored-By: Claude Opus 5.5 +--- + src/coreclr/vm/threadstatics.cpp | 19 +++++++++++++------ + 1 file changed, 13 insertions(+), 6 deletions(-) + +diff --git a/src/coreclr/vm/threadstatics.cpp b/src/coreclr/vm/threadstatics.cpp +index dcff2bc8c..1b174463e 100644 +--- a/src/coreclr/vm/threadstatics.cpp ++++ b/src/coreclr/vm/threadstatics.cpp +@@ -766,12 +766,19 @@ void GetTLSIndexForThreadStatic(MethodTable* pMT, bool gcStatic, TLSIndex* pInde + } + else + { +- if (!g_pThreadStaticCollectibleTypeIndices->FindClearedIndex(&newTLSIndex)) +- { +- uint32_t tlsRawIndex = g_NextTLSSlot; +- newTLSIndex = TLSIndex(TLSIndexType::Collectible, tlsRawIndex); +- g_NextTLSSlot += 1; +- } ++ // RynthCore patch (2026-10-23, dotnet/runtime #135441 / #134928): never reuse a cleared ++ // collectible index. A thread that outlived the old owner's unload still holds ++ // pLoaderHandles[index] (and its TLS array entry) for it. Once the index was reused, ++ // FreeLoaderAllocatorHandlesForTLSData freed that stale handle against the NEW owner's ++ // LoaderAllocator when the thread exited, unrooting whatever live object the new owner kept ++ // in that slot (random statics of live types read null or garbage, then crashed). A cleared ++ // index is skipped by CollectibleEntries(), so its stale state is simply dropped with the ++ // thread's arrays. Cost: the index space grows with every collectible type with thread ++ // statics ever loaded (a few bytes per thread per type), which is bounded for a host that ++ // unloads a context per hot reload. ++ uint32_t tlsRawIndex = g_NextTLSSlot; ++ newTLSIndex = TLSIndex(TLSIndexType::Collectible, tlsRawIndex); ++ g_NextTLSSlot += 1; + + g_pThreadStaticCollectibleTypeIndices->Set(newTLSIndex, pMT, gcStatic); + pMT->GetLoaderAllocator()->GetTLSIndexList().Append(newTLSIndex); +-- +2.54.0.windows.1 + diff --git a/scripts/Publish-EngineCoreClr.ps1 b/scripts/Publish-EngineCoreClr.ps1 index b20b93c..071b539 100644 --- a/scripts/Publish-EngineCoreClr.ps1 +++ b/scripts/Publish-EngineCoreClr.ps1 @@ -140,6 +140,34 @@ if (-not $EngineOnly) { } else { Write-Warning "createdump.exe is missing from $dotnet and no runtime pack matches coreclr $have; a CoreCLR crash will leave no dump." } } + + # Patched CoreCLR (2026-10-23, runtime-patches\coreclr-10.0.12-x86\README.md): the hot-reload + # statics crash, dotnet/runtime #135441. Its coreclr.dll, DAC and DBI go over the runtime pack's; + # the official CoreLib and JIT stay. Refused for a runtime of another version: a coreclr has to + # match its CoreLib. In use by a running client: moved aside, as the loader and shim are. + $patch = Join-Path $repo "runtime-patches\coreclr-10.0.12-x86" + if (Test-Path "$patch\coreclr.dll") { + $lib = (Get-Item "$dotnet\System.Private.CoreLib.dll").VersionInfo + $pv = (Get-Item "$patch\coreclr.dll").VersionInfo + if ($lib.FileMajorPart -ne $pv.FileMajorPart -or $lib.FileMinorPart -ne $pv.FileMinorPart -or $lib.FileBuildPart -ne $pv.FileBuildPart) { + throw "runtime-patches\coreclr-10.0.12-x86 was built for runtime $($pv.FileMajorPart).$($pv.FileMinorPart).$($pv.FileBuildPart), but $dotnet has CoreLib $($lib.FileMajorPart).$($lib.FileMinorPart).$($lib.FileBuildPart): rebuild the patch for it or remove the folder (see its README)." + } + $dacName = "mscordaccore_x86_x86_{0}.{1}.{2}.{3}.dll" -f $pv.FileMajorPart, $pv.FileMinorPart, $pv.FileBuildPart, $pv.FilePrivatePart + $copied = 0 + foreach ($pair in @(@('coreclr.dll', 'coreclr.dll'), @('mscordaccore.dll', 'mscordaccore.dll'), @('mscordbi.dll', 'mscordbi.dll'), @('mscordaccore.dll', $dacName))) { + $src = Join-Path $patch $pair[0] + $dest = Join-Path $dotnet $pair[1] + if ((Test-Path $dest) -and (Get-FileHash $dest).Hash -eq (Get-FileHash $src).Hash) { continue } + try { Copy-Item $src $dest -Force -ErrorAction Stop } + catch { + Rename-Item $dest ("{0}.old-{1:yyyyMMddHHmmss}" -f $pair[1], (Get-Date)) -ErrorAction Stop + Copy-Item $src $dest -Force -ErrorAction Stop + Write-Host "$($pair[1]) was in use: moved the old one aside; new launches get the patched one." + } + $copied++ + } + if ($copied -gt 0) { Write-Host "Patched CoreCLR $($pv.FileVersion) -> $dotnet ($copied file(s); runtime-patches\coreclr-10.0.12-x86)" } + } } # Engine + dependencies. The canonical RynthCore.Engine.dll goes last: the loader's file diff --git a/scripts/Test-ClrWorld.ps1 b/scripts/Test-ClrWorld.ps1 index 5b5d51b..7fee942 100644 --- a/scripts/Test-ClrWorld.ps1 +++ b/scripts/Test-ClrWorld.ps1 @@ -51,6 +51,10 @@ $env:RYNTHCORE_TEST_CLIENT = "Test-ClrWorld" # the loader logs "TestClient: .. # clients: a test client gets its own so it never moves the player's bar or panels. $env:LOCALAPPDATA = "C:\Games\RynthCore\Test\localappdata" New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null +# The engine finds %LOCALAPPDATA% through the known-folder API, which ignores the variable above: +# the hotkeys (shared by every client, and changed by the item bar's keys) get their own file here. +New-Item -ItemType Directory -Force "$env:LOCALAPPDATA\RynthCore" | Out-Null +$env:RYNTHCORE_HOTKEYS_FILE = "$env:LOCALAPPDATA\RynthCore\hotkeys.txt" $dispatch = "C:\Games\RynthCore\Test\dispatch.txt" $env:RYNTHCORE_DISPATCH_FILE = $dispatch Set-Content $dispatch "# test dispatch file" diff --git a/src/RynthCore.App.Avalonia/RynthUpdater.Available.cs b/src/RynthCore.App.Avalonia/RynthUpdater.Available.cs index 43d9cb5..4ab1e1d 100644 --- a/src/RynthCore.App.Avalonia/RynthUpdater.Available.cs +++ b/src/RynthCore.App.Avalonia/RynthUpdater.Available.cs @@ -71,6 +71,7 @@ internal sealed partial class RynthUpdater ["RynthILT"] = "Infinite Leaftide only: the ILT Hub, the Guardian, bounty tracking and progression planning.", ["RynthThreads"] = "DreamWeave only: records Fragment Press results and works out what each component brings.", ["RynthNet"] = "Links your characters on this PC: broadcast commands, shared vitals and the Characters panel.", + ["RynthDefective"] = "A shortcut bar with AC's own keys, buttons for AC's panels and the Selection, in place of the retail toolbar.", }; /// The feed's description, else the launcher's own line, else "". diff --git a/src/RynthCore.Engine/Assets/Fonts/Barlow.LICENSE b/src/RynthCore.Engine/Assets/Fonts/Barlow.LICENSE new file mode 100644 index 0000000..2f22ba6 --- /dev/null +++ b/src/RynthCore.Engine/Assets/Fonts/Barlow.LICENSE @@ -0,0 +1,93 @@ +Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/RynthCore.Engine/Assets/Fonts/BarlowSemiCondensed-Bold.ttf b/src/RynthCore.Engine/Assets/Fonts/BarlowSemiCondensed-Bold.ttf new file mode 100644 index 0000000..ee04b09 Binary files /dev/null and b/src/RynthCore.Engine/Assets/Fonts/BarlowSemiCondensed-Bold.ttf differ diff --git a/src/RynthCore.Engine/Assets/Fonts/BarlowSemiCondensed-SemiBold.ttf b/src/RynthCore.Engine/Assets/Fonts/BarlowSemiCondensed-SemiBold.ttf new file mode 100644 index 0000000..082c763 Binary files /dev/null and b/src/RynthCore.Engine/Assets/Fonts/BarlowSemiCondensed-SemiBold.ttf differ diff --git a/src/RynthCore.Engine/Compatibility/AcKeymap.cs b/src/RynthCore.Engine/Compatibility/AcKeymap.cs new file mode 100644 index 0000000..bd964fa --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AcKeymap.cs @@ -0,0 +1,241 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/AcKeymap.cs +// +// The player's AC key bindings, read from the keymap file AC uses: Documents\ +// Asheron's Call\UserPreferences.ini's [Input] KeymapFile= (saving one from +// Configure Keyboard makes it the default), else the client's own +// ".keymap". Plugin API v90 GetActionKeys: an action's keys as the +// player reads them ("1, Ctrl+1"), for RynthDefective's bar (each slot shows +// the UseQuickSlot_N keys the retail toolbar answers to). +// +// The file (AC:TD's own comments in it): a MetaKeys block numbers the +// modifier keys (1 [ 0 DIK_LSHIFT ], 2 [ 0 DIK_LCONTROL ] ...); each binding +// is Action [ "" [ device KEY subcontrol? ] metakeys? activation? ] where +// device 0 is the keyboard and 1 the mouse, and metakeys is a bit mask, the +// bit of metakey n being 1 << (n - 1) (0x3 = Ctrl+Shift). +// +// Read again when the file (or UserPreferences.ini) changes, looked at no +// more than every 2 s. Any thread; reads only. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; + +namespace RynthCore.Engine.Compatibility; + +internal static class AcKeymap +{ + /// One binding: device (0 keyboard, 1 mouse), the DirectInput name, the metakey mask. + public readonly record struct Binding(int Device, string Key, uint Meta); + + private static readonly object Sync = new(); + private static Dictionary> _bindings = new(StringComparer.OrdinalIgnoreCase); + private static string[] _metaNames = Array.Empty(); // index n-1: metakey n's name + private static string _file = string.Empty; + private static DateTime _fileTime, _prefsTime; + private static long _checkedMs = long.MinValue / 2; + + /// Documents\Asheron's Call, where AC keeps UserPreferences.ini and the keymaps. + internal static string AcUserFolder => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Asheron's Call"); + + /// The keymap file AC uses ("" when there is none). + public static string FilePath { get { Refresh(); lock (Sync) return _file; } } + + /// The action's bindings (none for an unknown action or no keymap). + public static IReadOnlyList BindingsFor(string action) + { + Refresh(); + lock (Sync) + return _bindings.TryGetValue(action, out List? list) ? list.ToArray() : Array.Empty(); + } + + /// The action's keys as the player reads them, "1, Ctrl+1"; "" when unbound. + public static string KeysText(string action) + { + IReadOnlyList list = BindingsFor(action); + if (list.Count == 0) return string.Empty; + var sb = new StringBuilder(); + foreach (Binding b in list) + { + string one = Describe(b); + if (one.Length == 0) continue; + if (sb.Length > 0) sb.Append(", "); + sb.Append(one); + } + return sb.ToString(); + } + + /// One binding as text: its modifiers (by the file's MetaKeys) and the key. + public static string Describe(Binding b) + { + var sb = new StringBuilder(); + string[] metas; + lock (Sync) metas = _metaNames; + for (int n = 1; n <= 32; n++) + { + if ((b.Meta & (1u << (n - 1))) == 0) continue; + string name = n - 1 < metas.Length && metas[n - 1].Length > 0 ? metas[n - 1] : "Meta" + n; + sb.Append(name).Append('+'); + } + sb.Append(KeyName(b.Device, b.Key)); + return sb.ToString(); + } + + /// The file changed (AcKeymapLive wrote it): read it again at the next look. + public static void Invalidate() + { + lock (Sync) + { + _checkedMs = long.MinValue / 2; + _fileTime = DateTime.MinValue; + } + } + + private static void Refresh() + { + long now = Environment.TickCount64; + lock (Sync) + { + if (now - _checkedMs < 2000) return; + _checkedMs = now; + } + try + { + string folder = AcUserFolder; + string prefs = Path.Combine(folder, "UserPreferences.ini"); + DateTime prefsTime = File.Exists(prefs) ? File.GetLastWriteTimeUtc(prefs) : DateTime.MinValue; + string file = Path.Combine(folder, KeymapName(prefs)); + DateTime fileTime = File.Exists(file) ? File.GetLastWriteTimeUtc(file) : DateTime.MinValue; + lock (Sync) + if (file == _file && fileTime == _fileTime && prefsTime == _prefsTime) return; + Parse(file, out var bindings, out string[] metas); + lock (Sync) + { + _file = File.Exists(file) ? file : string.Empty; + _fileTime = fileTime; + _prefsTime = prefsTime; + _bindings = bindings; + _metaNames = metas; + } + RynthLog.Compat($"AcKeymap: {(File.Exists(file) ? file : "no keymap file")} - {bindings.Count} action(s) bound."); + } + catch (Exception ex) + { + RynthLog.Compat($"AcKeymap: could not read the keymap: {ex.GetType().Name}: {ex.Message}"); + } + } + + /// [Input] KeymapFile= in UserPreferences.ini, else "<the client exe>.keymap". + private static string KeymapName(string prefs) + { + if (File.Exists(prefs)) + { + bool input = false; + foreach (string raw in File.ReadLines(prefs)) + { + string line = raw.Trim(); + if (line.StartsWith('[')) { input = line.Equals("[Input]", StringComparison.OrdinalIgnoreCase); continue; } + if (!input) continue; + int eq = line.IndexOf('='); + if (eq > 0 && line[..eq].Trim().Equals("KeymapFile", StringComparison.OrdinalIgnoreCase)) + { + string name = line[(eq + 1)..].Trim(); + if (name.Length > 0 && name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0) return name; + } + } + } + string exe = "acclient"; + try { exe = Process.GetCurrentProcess().ProcessName; } catch { } + return exe + ".keymap"; + } + + // Action [ "" [ device KEY ...] mask? ... + private static readonly Regex BindingLine = new( + @"^\s*([A-Za-z0-9_]+)\s*\[\s*""[^""]*""\s*\[\s*(\d+)\s+([A-Za-z0-9_]+)[^\]]*\]\s*(0x[0-9A-Fa-f]+)?", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + + // n [ device KEY ] + private static readonly Regex MetaLine = new(@"^\s*(\d+)\s*\[\s*\d+\s+([A-Za-z0-9_]+)", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private static void Parse(string file, out Dictionary> bindings, out string[] metas) + { + bindings = new Dictionary>(StringComparer.OrdinalIgnoreCase); + var metaList = new List(); + if (!File.Exists(file)) { metas = Array.Empty(); return; } + string section = string.Empty; + foreach (string raw in File.ReadLines(file)) + { + string line = raw.Trim(); + if (line.Length == 0 || line.StartsWith('#')) continue; + if (line is "Devices" or "MetaKeys" or "Bindings") { section = line; continue; } + if (section == "MetaKeys") + { + Match m = MetaLine.Match(line); + if (!m.Success) continue; + int n = int.Parse(m.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture); + if (n < 1 || n > 32) continue; + while (metaList.Count < n) metaList.Add(string.Empty); + if (metaList[n - 1].Length == 0) metaList[n - 1] = MetaName(m.Groups[2].Value); + continue; + } + if (section != "Bindings") continue; + Match b = BindingLine.Match(line); + if (!b.Success) continue; + uint mask = 0; + if (b.Groups[4].Success) + uint.TryParse(b.Groups[4].Value.AsSpan(2), System.Globalization.NumberStyles.HexNumber, null, out mask); + var binding = new Binding(int.Parse(b.Groups[2].Value, System.Globalization.CultureInfo.InvariantCulture), b.Groups[3].Value, mask); + if (!bindings.TryGetValue(b.Groups[1].Value, out List? list)) + bindings[b.Groups[1].Value] = list = new List(); + if (!list.Contains(binding)) list.Add(binding); + } + metas = metaList.ToArray(); + } + + private static string MetaName(string key) => key.ToUpperInvariant() switch + { + "DIK_LSHIFT" or "DIK_RSHIFT" => "Shift", + "DIK_LCONTROL" or "DIK_RCONTROL" => "Ctrl", + "DIK_LMENU" or "DIK_RMENU" or "DIK_RALT" or "DIK_LALT" => "Alt", + "DIK_LWIN" or "DIK_RWIN" => "Win", + _ => KeyName(key.StartsWith("DIMOFS_", StringComparison.OrdinalIgnoreCase) ? 1 : 0, key), + }; + + /// A DirectInput key or mouse name as the player reads it: DIK_1 "1", DIK_NUMPAD5 "Num5", DIMOFS_BUTTON3 "Mouse4". + public static string KeyName(int device, string key) + { + string k = key.ToUpperInvariant(); + if (k.StartsWith("DIMOFS_BUTTON", StringComparison.Ordinal) && int.TryParse(k.AsSpan(13), out int button)) + return "Mouse" + (button + 1); + if (k == "DIMOFS_Z") return "Wheel"; + if (!k.StartsWith("DIK_", StringComparison.Ordinal)) return key; + string n = k[4..]; + if (n.StartsWith("NUMPAD", StringComparison.Ordinal) && n.Length > 6) + { + string rest = n[6..]; + return rest switch + { + "ENTER" => "NumEnter", "COMMA" => "Num,", "EQUALS" => "Num=", "STAR" => "Num*", "SLASH" => "Num/", + "PLUS" => "Num+", "MINUS" => "Num-", "PERIOD" => "Num.", _ => "Num" + rest, + }; + } + return n switch + { + "MINUS" => "-", "EQUALS" => "=", "LBRACKET" => "[", "RBRACKET" => "]", "SEMICOLON" => ";", + "APOSTROPHE" => "'", "GRAVE" => "`", "BACKSLASH" => "\\", "COMMA" => ",", "PERIOD" => ".", "SLASH" => "/", + "MULTIPLY" => "Num*", "SUBTRACT" => "Num-", "ADD" => "Num+", "DECIMAL" => "Num.", "DIVIDE" => "Num/", + "SPACE" => "Space", "RETURN" => "Enter", "ESCAPE" => "Esc", "BACK" => "Backspace", "TAB" => "Tab", + "CAPITAL" or "CAPSLOCK" => "CapsLock", "PRIOR" or "PGUP" => "PgUp", "NEXT" or "PGDN" => "PgDn", + "INSERT" => "Ins", "DELETE" => "Del", "HOME" => "Home", "END" => "End", "BACKSPACE" => "Backspace", + "UP" or "UPARROW" => "Up", "DOWN" or "DOWNARROW" => "Down", "LEFT" or "LEFTARROW" => "Left", "RIGHT" or "RIGHTARROW" => "Right", + "SYSRQ" => "PrintScreen", "SCROLL" => "ScrollLock", "PAUSE" => "Pause", + "LSHIFT" or "RSHIFT" => "Shift", "LCONTROL" or "RCONTROL" => "Ctrl", "LMENU" or "RMENU" => "Alt", + _ => n.Length == 1 ? n : char.ToUpperInvariant(n[0]) + n[1..].ToLowerInvariant(), + }; + } +} diff --git a/src/RynthCore.Engine/Compatibility/AcKeymapLive.cs b/src/RynthCore.Engine/Compatibility/AcKeymapLive.cs new file mode 100644 index 0000000..fbf7436 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AcKeymapLive.cs @@ -0,0 +1,484 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/AcKeymapLive.cs +// +// Changing the player's keys so every running client follows (Tom 2026-10-22: +// the item bar's keys are the player's retail keys, and they change together; +// with the retail toolbar back, its keys have changed too). Plugin API v90 +// KeyCapture / SetActionKey, for RynthDefective's bar, and /rc keymap. +// +// AC keeps its keymap in memory: it loads the file when it starts and writes +// it back when it closes, and its own Configure Keyboard changes only the +// memory. So a change is, on AC's game thread after its tick: +// 1. this client's keys go to the file first (CInputManager_WIN32:: +// SaveKeyMap, vtable +0x30, what Configure Keyboard's "save as" does), so +// a key the player changed there isn't lost; +// 2. the file's text is edited (AcKeymapText: the key comes off whatever had +// it, and off RynthCore's own hotkeys, which would take it before AC); +// 3. it is loaded again the way AC loads it when it starts (gmClient:: +// InitKeymap): InitializeKeymap (+0x08, clears), AddKeyMap_(path) (+0x28, +// the file), AddKeyMap(0x10000001) and AddKeyMap(1) (+0x2C, the game's +// fixed maps from the dat); +// 4. the file's new time goes in ".rynthcore" beside it. +// Every other client looks at the file once a second and loads it the same +// way when it changed with that time noted. A file a closing client wrote (AC's +// own save on shutdown) isn't loaded: that would throw away keys the others +// changed in Configure Keyboard and haven't saved, as AC would never do. +// +// A key for one of RynthCore's own commands (RynthDefective's slots past the +// game's 18: "/rdef use 2") is an engine hotkey; it takes its key the same way +// (off AC's actions too, so no key shows on two slots). +// +// ICIDM::s_cidm (the CInputManager*, by code-xref), the four functions and +// PStringBase(const char*) (0x00401340) are found by pattern only, and +// the input manager's vtable must hold exactly those functions, or nothing is +// called. The first change backs the file up as ".before-rynthcore". +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore.Engine.Hotkeys; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class AcKeymapLive +{ + // ClientUISystem::UseTime: mov ebp,[ICIDM::s_cidm]; push esi; push edi; lea eax,[esp+0x10] (as LogoffOriginProbe). + private static readonly byte?[] InputManagerXref = [0x8B, 0x2D, null, null, null, null, 0x56, 0x57, 0x8D, 0x44, 0x24, 0x10]; + // CInputManager_WIN32::InitializeKeymap: this->ClearKeyMap(); if (m_actionMap) m_actionMap->vt54(); return 1. + private static readonly byte?[] InitializePattern = + [0x56, 0x8B, 0xF1, 0x8B, 0x06, 0xFF, 0x50, 0x24, 0x8B, 0x8E, 0x8C, 0x00, 0x00, 0x00, 0x85, 0xC9, 0x5E, 0x74, 0x05, 0x8B, 0x11, 0xFF, 0x52, 0x54, 0xB0, 0x01, 0xC3]; + // CInputManager_WIN32::AddKeyMap_(PStringBase file): PFileParser::LoadFromFile, CMasterInputMap::Merge. + private static readonly byte?[] LoadFilePattern = + [0xA1, null, null, null, null, 0x81, 0xEC, 0x68, 0x01, 0x00, 0x00, 0x85, 0xC0, 0x56, 0x57, 0x8B, 0xF9, 0x75, 0x0A, 0xB9, null, null, null, null, 0xE8]; + // CInputManager_WIN32::AddKeyMap(uint id): DBObj::GetByEnum(id, 10, 0x1D), CMasterInputMap::Merge. + private static readonly byte?[] LoadDbPattern = + [0x8B, 0x44, 0x24, 0x04, 0x56, 0x57, 0x6A, 0x1D, 0x6A, 0x0A, 0x50, 0x8B, 0xF9, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC4, 0x0C, 0x32, 0xC0, 0x85, 0xF6, 0x74, 0x1B, 0x53, 0x6A, 0x01, 0x56]; + // CInputManager_WIN32::SaveKeyMap(PStringBase file): CMasterInputMap::ToFileNode, PFileParser::SaveToFile. + private static readonly byte?[] SavePattern = + [0xA1, null, null, null, null, 0x83, 0xEC, 0x20, 0x85, 0xC0, 0x56, 0x57, 0x8B, 0xF9, 0x75, 0x0A, 0xB9, null, null, null, null, 0xE8, null, null, null, null, 0x8B, 0x0D]; + // PStringBase::PStringBase(const char*): the string's characters, refcount at -0x10. + private static readonly byte?[] StringPattern = + [0x56, 0x8B, 0x74, 0x24, 0x08, 0x85, 0xF6, 0x57, 0x8B, 0xF9, 0x74, 0x35, 0x80, 0x3E, 0x00, 0x74, 0x30, 0x8B, 0xC6, 0x8D, 0x50, 0x01, + 0x8A, 0x08, 0x40, 0x84, 0xC9, 0x75, 0xF9, 0x2B, 0xC2, 0x50, 0x8B, 0xCF, 0xE8, null, null, null, null, 0x8B, 0x17]; + + private const int VtInitialize = 0x08, VtLoadFile = 0x28, VtLoadDb = 0x2C, VtSave = 0x30; + private const uint FixedMapA = 0x10000001, FixedMapB = 1; // the dat's maps gmClient::InitKeymap merges after the file + + private static IntPtr _cidmSlot, _init, _loadFile, _loadDb, _save, _string; + private static bool _initialized; + private static string _status = "Not initialized."; + public static string Status => _status; + public static bool CanChange => _cidmSlot != IntPtr.Zero && _init != IntPtr.Zero && _loadFile != IntPtr.Zero + && _loadDb != IntPtr.Zero && _save != IntPtr.Zero && _string != IntPtr.Zero; + + public static void Initialize() + { + if (_initialized) return; + _initialized = true; + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + _status = "acclient.exe not available."; + return; + } + IntPtr Fn(string name, byte?[] pattern) + { + var r = HookResolver.Resolve(text, "AcKeymapLive." + name, pattern, 0); + return r.Success && r.Source == HookResolver.ResolveSource.PatternScan ? r.Address : IntPtr.Zero; + } + var slot = HookResolver.ResolveData(text, "AcKeymapLive.ICIDM_s_cidm", InputManagerXref, 2, 0); + _cidmSlot = slot.Success && slot.Source == HookResolver.ResolveSource.PatternScan ? slot.Address : IntPtr.Zero; + _init = Fn("InitializeKeymap", InitializePattern); + _loadFile = Fn("AddKeyMap_", LoadFilePattern); + _loadDb = Fn("AddKeyMap", LoadDbPattern); + _save = Fn("SaveKeyMap", SavePattern); + _string = Fn("PStringBase_char_ctor", StringPattern); + _status = CanChange ? "ready." : "missing " + string.Join(", ", Missing()) + ": keys can't be changed from here."; + RynthLog.Compat("AcKeymapLive: " + _status); + } + + private static IEnumerable Missing() + { + if (_cidmSlot == IntPtr.Zero) yield return "the input manager"; + if (_init == IntPtr.Zero) yield return "InitializeKeymap"; + if (_loadFile == IntPtr.Zero) yield return "AddKeyMap_"; + if (_loadDb == IntPtr.Zero) yield return "AddKeyMap"; + if (_save == IntPtr.Zero) yield return "SaveKeyMap"; + if (_string == IntPtr.Zero) yield return "PStringBase"; + } + + /// The CInputManager, when its vtable holds the functions found (else zero: never called). + private static IntPtr InputManager() + { + if (!CanChange || !ClientObjectHooks.IsReadableSpan(_cidmSlot, 4)) return IntPtr.Zero; + IntPtr im = Marshal.ReadIntPtr(_cidmSlot); + if (im == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(im, 4)) return IntPtr.Zero; + IntPtr vt = Marshal.ReadIntPtr(im); + if (vt == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(vt, VtSave + 4)) return IntPtr.Zero; + bool ok = Marshal.ReadIntPtr(vt, VtInitialize) == _init && Marshal.ReadIntPtr(vt, VtLoadFile) == _loadFile + && Marshal.ReadIntPtr(vt, VtLoadDb) == _loadDb && Marshal.ReadIntPtr(vt, VtSave) == _save; + if (!ok && !_vtWarned) + { + _vtWarned = true; + RynthLog.Compat($"AcKeymapLive: the input manager's vtable 0x{vt.ToInt32():X8} isn't the expected one; keys won't be reloaded."); + } + return ok ? im : IntPtr.Zero; + } + + private static bool _vtWarned; + + /// An AC PStringBase<char> of the path (one reference, handed to the callee); zero for a path AC can't take. + private static IntPtr AcString(string path) + { + string p = path; + if (!IsAscii(p)) + { + // AC opens files with the ANSI functions: a name with other letters goes by its short (8.3) form. + var sb = new StringBuilder(520); + if (GetShortPathNameW(path, sb, sb.Capacity) > 0) p = sb.ToString(); + if (!IsAscii(p)) return IntPtr.Zero; + } + byte[] bytes = new byte[p.Length + 1]; + for (int i = 0; i < p.Length; i++) bytes[i] = (byte)p[i]; + IntPtr s = IntPtr.Zero; + fixed (byte* b = bytes) + ((delegate* unmanaged[Thiscall])_string)(&s, b); + return s; + } + + private static bool IsAscii(string s) + { + foreach (char c in s) if (c >= 0x80 || c == 0) return false; + return true; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern int GetShortPathNameW(string longPath, StringBuilder shortPath, int size); + + // ── Watching (every client) ────────────────────────────────────────────── + + private static DateTime _seenUtc = DateTime.MinValue; + private static string _seenFile = string.Empty; + private static long _nextCheckMs; + private static readonly DateTime ProcessStartUtc = SafeStartUtc(); + + private static DateTime SafeStartUtc() + { + try { return Process.GetCurrentProcess().StartTime.ToUniversalTime(); } + catch { return DateTime.UtcNow; } + } + + private static string MarkerPath(string keymap) => keymap + ".rynthcore"; + + private static long ReadMarker(string keymap) + { + try + { + string m = MarkerPath(keymap); + return File.Exists(m) && long.TryParse(File.ReadAllText(m).Trim(), out long t) ? t : 0; + } + catch { return 0; } + } + + /// Game thread, after AC's tick: the queued changes, then (once a second) another client's change. + public static void Tick() + { + if (!CanChange || !LoginLifecycleHooks.HasObservedLoginComplete) return; + DrainRequests(); + if (_dumpTo is { } dump) + { + _dumpTo = null; + string said = SaveOwn(dump) ? $"AC's keys in memory written to {dump}." : "AC couldn't write its keys there."; + RynthLog.Compat("AcKeymapLive: " + said); + AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + said, 1); + } + long now = Environment.TickCount64; + if (now < _nextCheckMs) return; + _nextCheckMs = now + 1000; + try + { + string file = AcKeymap.FilePath; + if (file.Length == 0) return; + DateTime t = File.GetLastWriteTimeUtc(file); + bool first = !string.Equals(file, _seenFile, StringComparison.OrdinalIgnoreCase); + if (!first && t == _seenUtc) return; + _seenFile = file; + _seenUtc = t; + // RynthCore's change (the time noted beside it); at the first look, only one made after this client loaded the file. + if (ReadMarker(file) != t.Ticks) return; + if (first && t <= ProcessStartUtc.AddSeconds(5)) return; + Reload(file, "another client changed a key"); + } + catch (Exception ex) + { + RynthLog.Compat($"AcKeymapLive: watching the keymap failed: {ex.GetType().Name}: {ex.Message}"); + } + } + + /// Loads the file into AC as AC does when it starts. Game thread. + private static bool Reload(string file, string why) + { + IntPtr im = InputManager(); + if (im == IntPtr.Zero) return false; + IntPtr path = AcString(file); + if (path == IntPtr.Zero) + { + RynthLog.Compat($"AcKeymapLive: AC can't open '{file}' (its name has letters AC's file functions don't take)."); + return false; + } + IntPtr vt = Marshal.ReadIntPtr(im); + var init = (delegate* unmanaged[Thiscall])Marshal.ReadIntPtr(vt, VtInitialize); + var load = (delegate* unmanaged[Thiscall])Marshal.ReadIntPtr(vt, VtLoadFile); + var db = (delegate* unmanaged[Thiscall])Marshal.ReadIntPtr(vt, VtLoadDb); + init(im); + bool loaded = load(im, path) != 0; + if (!loaded) init(im); // as gmClient::InitKeymap: a file that didn't load leaves the game's own keys + db(im, FixedMapA); + db(im, FixedMapB); + AcKeymap.Invalidate(); + RynthLog.Compat($"AcKeymapLive: keys loaded again from {Path.GetFileName(file)} ({why}){(loaded ? "" : " - the file didn't load: the game's default keys")}."); + return loaded; + } + + /// This client's keys to the file (AC's own writer). Game thread. + private static bool SaveOwn(string file) + { + IntPtr im = InputManager(); + if (im == IntPtr.Zero) return false; + IntPtr path = AcString(file); + if (path == IntPtr.Zero) return false; + var save = (delegate* unmanaged[Thiscall])Marshal.ReadIntPtr(Marshal.ReadIntPtr(im), VtSave); + return save(im, path) != 0; + } + + // ── Changing (queued from any thread, done on the game thread) ─────────── + + public enum Op { Bind = 1, Unbind = 2 } + + private readonly record struct Request(string Action, string Key, Op Op, long QueuedMs); + + private static readonly ConcurrentQueue Requests = new(); + + /// The engine hotkeys' commands look like this: "/rdef use 2". + public static bool IsCommand(string action) => action.StartsWith('/'); + + private static bool ValidAction(string action) => + action.Length is > 0 and <= 64 && (IsCommand(action) || System.Text.RegularExpressions.Regex.IsMatch(action, "^[A-Za-z0-9_]+$")); + + /// + /// What ("Ctrl+F5") would take from others if bound to + /// (a keymap action "UseQuickSlot_5", or an engine command "/rdef use 2"). 0 free, 1 taken (the message + /// says from what), -1 can't (the message says why). Any thread. + /// + public static int Check(string action, string keyText, out string message) + { + message = string.Empty; + action = action.Trim(); + if (!ValidAction(action)) { message = "Not an action."; return -1; } + if (!HotkeyKeys.TryParse(keyText, out KeyCombo combo, out string err)) { message = err; return -1; } + if (!IsCommand(action) && !CanChange) { message = "This client can't change AC's keys (" + _status + ")"; return -1; } + + var takes = new List(); + string file = AcKeymap.FilePath; + string? dik = AcKeymapText.DikForVk(combo.Vk); + if (!IsCommand(action) && dik == null) { message = $"AC's keymap can't hold {combo}."; return -1; } + if (file.Length > 0 && dik != null) + { + try + { + List lines = AcKeymapText.Split(File.ReadAllText(file), out _); + if (AcKeymapText.TryMeta(lines, combo.Mods, out uint meta, out string metaErr)) + { + foreach (AcKeymapText.Line l in AcKeymapText.Uses(lines, 0, dik, meta)) + if (!l.Action.Equals(action, StringComparison.OrdinalIgnoreCase)) takes.Add(AcKeymapText.Describe(l.Action) + " (the game)"); + } + else if (!IsCommand(action)) { message = metaErr; return -1; } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + message = "The keymap can't be read right now; try again."; + return -1; + } + } + foreach (HotkeyBinding b in HotkeyService.Current.Bindings) + if (b.Combo == combo && !(b.IsCommand && SameCommand(b.Command, action))) + takes.Add(HotkeyActions.Describe(b) + " (a RynthCore hotkey)"); + if (takes.Count == 0) return 0; + message = $"{combo} is " + string.Join(", ", takes) + "."; + return 1; + } + + /// Queues binding or unbinding the key; done on the game thread. False (with why) when it can't be. + public static bool Enqueue(string action, string keyText, Op op, out string message) + { + message = string.Empty; + action = action.Trim(); + keyText = keyText.Trim(); + if (!ValidAction(action)) { message = "Not an action."; return false; } + if (keyText.Length == 0 || keyText.Length > 40) { message = "No key."; return false; } + if (op == Op.Bind && !HotkeyKeys.TryParse(keyText, out _, out string err)) { message = err; return false; } + if (!CanChange && (!IsCommand(action) || op == Op.Bind)) { message = "This client can't change AC's keys (" + _status + ")"; return false; } + if (Requests.Count >= 16) { message = "Too many changes at once."; return false; } + Requests.Enqueue(new Request(action, keyText, op, Environment.TickCount64)); + return true; + } + + private static volatile string? _dumpTo; + + /// /rc keymap dump: AC's keys as it holds them in memory, written by AC to (game thread, next tick). + public static void RequestDump(string path) => _dumpTo = path; + + /// Logout: nothing queued for the old character. + public static void Reset() + { + while (Requests.TryDequeue(out _)) { } + } + + private static void DrainRequests() + { + while (Requests.TryDequeue(out Request r)) + { + if (Environment.TickCount64 - r.QueuedMs > 10000) continue; + string result; + try { result = Apply(r); } + catch (Exception ex) { result = $"Changing the key failed: {ex.GetType().Name}: {ex.Message}"; } + RynthLog.Compat("AcKeymapLive: " + result); + if (result.Length > 0) AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + result, 1); + } + } + + private static string Apply(Request r) + { + string file = AcKeymap.FilePath; + bool command = IsCommand(r.Action); + + if (r.Op == Op.Unbind) + { + if (command) + { + int n = RemoveHotkeys(b => b.IsCommand && SameCommand(b.Command, r.Action) && KeyMatches(b.Combo, r.Key)); + return n > 0 ? $"{r.Key} no longer does {r.Action}." : $"{r.Action} has no key {r.Key}."; + } + if (file.Length == 0) return "There is no AC keymap file to change."; + Backup(file); + SaveOwn(file); + List ul = AcKeymapText.Split(File.ReadAllText(file), out string unl); + if (!UnbindAc(ul, r.Action, r.Key)) return $"{AcKeymapText.Describe(r.Action)} has no key {r.Key}."; + WriteAndLoad(file, ul, unl); + return $"{r.Key} no longer does {AcKeymapText.Describe(r.Action)}."; + } + + HotkeyKeys.TryParse(r.Key, out KeyCombo combo, out _); + string? dik = AcKeymapText.DikForVk(combo.Vk); + if (!command && dik == null) return $"AC's keymap can't hold {combo}."; + if (!command && file.Length == 0) return "There is no AC keymap file to change."; + + // AC's side: the key comes off AC's other actions (a command's hotkey would take it before AC anyway). + var from = new List(); + if (file.Length > 0 && dik != null) + { + List lines = AcKeymapText.Split(File.ReadAllText(file), out string nl); + bool metaOk = AcKeymapText.TryMeta(lines, combo.Mods, out uint meta, out string metaErr); + if (!command && !metaOk) return metaErr; + if (metaOk && (!command || AcKeymapText.Uses(lines, 0, dik, meta).Count > 0)) + { + // This client's keys first (a key changed in Configure Keyboard lives only in memory), then the edit. + Backup(file); + if (SaveOwn(file)) lines = AcKeymapText.Split(File.ReadAllText(file), out nl); + else RynthLog.Compat("AcKeymapLive: couldn't save this client's keys first; changing the file as it is."); + List taken; + if (command) + { + taken = AcKeymapText.Uses(lines, 0, dik, meta); + for (int k = taken.Count - 1; k >= 0; k--) lines.RemoveAt(taken[k].Index); + } + else if (!AcKeymapText.Bind(lines, r.Action, 0, dik, meta, out taken, out string bindErr)) return bindErr; + foreach (AcKeymapText.Line l in taken) from.Add(AcKeymapText.Describe(l.Action)); + WriteAndLoad(file, lines, nl); + } + } + + // RynthCore's hotkeys: none other keeps the key; a command gets its binding. + int hk = RemoveHotkeys(b => b.Combo == combo && !(command && b.IsCommand && SameCommand(b.Command, r.Action))); + if (hk > 0) from.Add(hk == 1 ? "a RynthCore hotkey" : $"{hk} RynthCore hotkeys"); + if (command && !HotkeyService.Current.Bindings.Exists(b => b.Combo == combo && b.IsCommand && SameCommand(b.Command, r.Action))) + HotkeyService.Add(new HotkeyBinding(combo, HotkeyActions.Command, r.Action)); + string what = command ? r.Action : AcKeymapText.Describe(r.Action); + return $"{combo} now does {what}" + (from.Count > 0 ? " (taken from " + string.Join(", ", from) + ")." : "."); + } + + /// The edited file written (backed up the first time), its time noted, and loaded here; the others follow within a second. + private static void WriteAndLoad(string file, List lines, string newline) + { + Backup(file); + string tmp = file + ".tmp"; + File.WriteAllText(tmp, AcKeymapText.Join(lines, newline), Encoding.ASCII); + File.Move(tmp, file, overwrite: true); + DateTime t = File.GetLastWriteTimeUtc(file); + File.WriteAllText(MarkerPath(file), t.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); + _seenFile = file; + _seenUtc = t; + Reload(file, "a key changed here"); + } + + /// Removes the action's key: by combo ("Ctrl+1") or by the text GetActionKeys showed ("Mouse4"). + private static bool UnbindAc(List lines, string action, string keyText) + { + if (HotkeyKeys.TryParse(keyText, out KeyCombo combo, out _) && AcKeymapText.DikForVk(combo.Vk) is { } dik + && AcKeymapText.TryMeta(lines, combo.Mods, out uint meta, out _) + && AcKeymapText.Unbind(lines, action, 0, dik, meta)) + return true; + foreach (AcKeymapText.Line l in AcKeymapText.Bindings(lines)) + { + if (!l.Action.Equals(action, StringComparison.OrdinalIgnoreCase)) continue; + if (AcKeymap.Describe(new AcKeymap.Binding(l.Device, l.Dik, l.Meta)).Equals(keyText, StringComparison.OrdinalIgnoreCase)) + return AcKeymapText.Unbind(lines, action, l.Device, l.Dik, l.Meta); + } + return false; + } + + private static void Backup(string file) + { + try + { + string b = file + ".before-rynthcore"; + if (!File.Exists(b)) File.Copy(file, b); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + RynthLog.Compat($"AcKeymapLive: couldn't back up {file}: {ex.Message}"); + } + } + + private static int RemoveHotkeys(Predicate match) + { + var list = new List(HotkeyService.Current.Bindings); + int n = list.RemoveAll(match); + if (n > 0) HotkeyService.SetAll(list); + return n; + } + + private static bool SameCommand(string a, string b) => string.Equals(a.Trim(), b.Trim(), StringComparison.OrdinalIgnoreCase); + + private static bool KeyMatches(KeyCombo combo, string keyText) => + HotkeyKeys.TryParse(keyText, out KeyCombo k, out _) && k == combo; + + // ── Keys of an engine command ─────────────────────────────────────────── + + /// The engine hotkeys running , "F9, Ctrl+F9" (switched-off ones left out). + public static string CommandKeysText(string command) + { + var sb = new StringBuilder(); + foreach (HotkeyBinding b in HotkeyService.Current.Bindings) + { + if (!b.Enabled || !b.IsCommand || !SameCommand(b.Command, command)) continue; + if (sb.Length > 0) sb.Append(", "); + sb.Append(HotkeyKeys.Format(b.Combo)); + } + return sb.ToString(); + } +} diff --git a/src/RynthCore.Engine/Compatibility/AcKeymapText.cs b/src/RynthCore.Engine/Compatibility/AcKeymapText.cs new file mode 100644 index 0000000..03dad25 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AcKeymapText.cs @@ -0,0 +1,345 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/AcKeymapText.cs +// +// Changing a key in AC's keymap file, as text: the pure part (no engine +// dependencies, so tools/KeymapTests compiles it as is with Hotkeys/ +// HotkeyModel.cs). AC reads the file when it starts (gmClient::InitKeymap) +// and writes its keys back when it closes (gmClient::Cleanup); RynthCore +// changes a binding by editing the file and having every running client load +// it again (AcKeymapLive), so a key changed on the item bar is the key the +// retail toolbar and every client answer to. +// +// Bindings +// [ +// QuickslotCommands +// [ +// UseQuickSlot_1 [ "" [ 0 DIK_1 ] ] +// UseQuickSlot_1 [ "" [ 0 DIK_1 ] 0x00000002 ] +// ] +// ] +// +// A binding takes its key, as AC's Configure Keyboard does: the same key with +// the same modifiers comes off every other action in the groups the game +// reads while playing. The text-editing groups keep theirs (a chat box still +// has Home and Ctrl+C). The key names written are the ones AC writes itself +// (DIK_PGUP, DIK_UPARROW...), all in its own name table; any name it accepts +// is matched (DIK_PRIOR is DIK_PGUP). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; +using RynthCore.Engine.Hotkeys; + +namespace RynthCore.Engine.Compatibility; + +internal static class AcKeymapText +{ + /// One binding line: where it is, its group and action, the device (0 keyboard), the key (canonical DIK name), the modifier mask. + internal readonly record struct Line(int Index, string Group, string Action, int Device, string Dik, uint Meta); + + /// Groups for typing: a key bound there never conflicts with one the game uses while playing. + public static readonly string[] TextGroups = { "EditControls", "CopyAndPasteControls", "DialogBoxes", "ScrollableControls" }; + + /// The group a new key for an action no group has yet goes in. + public static string? DefaultGroup(string action) => + action.StartsWith("UseQuickSlot_", StringComparison.OrdinalIgnoreCase) ? "QuickslotCommands" : null; + + // Action [ "name" [ device KEY sub? ] mask? activation? ] + private static readonly Regex BindingLine = new( + @"^\s*([A-Za-z0-9_]+)\s*\[\s*""[^""]*""\s*\[\s*(\d+)\s+([A-Za-z0-9_]+)[^\]]*\]\s*(0x[0-9A-Fa-f]+)?", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + + // n [ device KEY ] + private static readonly Regex MetaLine = new(@"^\s*(\d+)\s*\[\s*\d+\s+([A-Za-z0-9_]+)", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private static readonly Regex Name = new(@"^[A-Za-z0-9_]+$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + // ── Text in and out ───────────────────────────────────────────────────── + + /// The file's lines and its line ending ("\r\n" as AC writes it). + public static List Split(string text, out string newline) + { + newline = text.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n"; + var lines = new List(text.Split('\n')); + for (int i = 0; i < lines.Count; i++) lines[i] = lines[i].TrimEnd('\r'); + return lines; + } + + public static string Join(List lines, string newline) => string.Join(newline, lines); + + // ── Key names ─────────────────────────────────────────────────────────── + + private static readonly Dictionary Aliases = new(StringComparer.OrdinalIgnoreCase) + { + ["DIK_PRIOR"] = "DIK_PGUP", ["DIK_NEXT"] = "DIK_PGDN", ["DIK_UP"] = "DIK_UPARROW", ["DIK_DOWN"] = "DIK_DOWNARROW", + ["DIK_RIGHT"] = "DIK_RIGHTARROW", ["DIK_LEFTARROW"] = "DIK_LEFT", ["DIK_BACKSPACE"] = "DIK_BACK", + ["DIK_CAPSLOCK"] = "DIK_CAPITAL", ["DIK_LALT"] = "DIK_LMENU", ["DIK_RALT"] = "DIK_RMENU", + ["DIK_MULTIPLY"] = "DIK_NUMPADSTAR", ["DIK_DIVIDE"] = "DIK_NUMPADSLASH", ["DIK_ADD"] = "DIK_NUMPADPLUS", + ["DIK_SUBTRACT"] = "DIK_NUMPADMINUS", ["DIK_NUMPADPERIOD"] = "DIK_DECIMAL", + }; + + /// One name per key (upper case): DIK_PRIOR and DIK_PGUP are both DIK_PGUP. + public static string Canonical(string dik) + { + string d = dik.Trim().ToUpperInvariant(); + return Aliases.TryGetValue(d, out string? c) ? c : d; + } + + /// + /// The DirectInput name AC writes for a Windows virtual key (the engine's hotkey keys), or null for + /// one AC's keymap can't hold (F16 and up). + /// + public static string? DikForVk(int vk) + { + if (vk is >= 'A' and <= 'Z' or >= '0' and <= '9') return "DIK_" + (char)vk; + if (vk is >= 0x70 and <= 0x7E) return "DIK_F" + (vk - 0x70 + 1); // F1-F15 + if (vk is >= 0x60 and <= 0x69) return "DIK_NUMPAD" + (vk - 0x60); // Num0-Num9 + return vk switch + { + 0x6A => "DIK_NUMPADSTAR", 0x6B => "DIK_NUMPADPLUS", 0x6D => "DIK_NUMPADMINUS", 0x6E => "DIK_DECIMAL", 0x6F => "DIK_NUMPADSLASH", + 0x08 => "DIK_BACK", 0x09 => "DIK_TAB", 0x0D => "DIK_RETURN", 0x13 => "DIK_PAUSE", 0x20 => "DIK_SPACE", + 0x21 => "DIK_PGUP", 0x22 => "DIK_PGDN", 0x23 => "DIK_END", 0x24 => "DIK_HOME", + 0x25 => "DIK_LEFT", 0x26 => "DIK_UPARROW", 0x27 => "DIK_RIGHTARROW", 0x28 => "DIK_DOWNARROW", + 0x2D => "DIK_INSERT", 0x2E => "DIK_DELETE", 0x91 => "DIK_SCROLL", + 0xBA => "DIK_SEMICOLON", 0xBB => "DIK_EQUALS", 0xBC => "DIK_COMMA", 0xBD => "DIK_MINUS", 0xBE => "DIK_PERIOD", + 0xBF => "DIK_SLASH", 0xC0 => "DIK_GRAVE", 0xDB => "DIK_LBRACKET", 0xDC => "DIK_BACKSLASH", 0xDD => "DIK_RBRACKET", + 0xDE => "DIK_APOSTROPHE", + _ => null, + }; + } + + // ── Reading ───────────────────────────────────────────────────────────── + + /// The MetaKeys block: each modifier key (canonical name) and its number (its bit is 1 << (n - 1)). + public static Dictionary MetaKeys(List lines) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + string section = string.Empty; + foreach (string raw in lines) + { + string t = raw.Trim(); + if (t is "Devices" or "MetaKeys" or "Bindings") { section = t; continue; } + if (section != "MetaKeys") continue; + Match m = MetaLine.Match(t); + if (m.Success && int.TryParse(m.Groups[1].Value, out int n) && n is >= 1 and <= 32) + map.TryAdd(Canonical(m.Groups[2].Value), n); + } + return map; + } + + /// + /// The modifier mask for Ctrl/Alt/Shift by the file's own MetaKeys numbers (the default file: Shift 1, + /// Ctrl 2, Alt 4). False, with the reason, when the file has no metakey for one of them. + /// + public static bool TryMeta(List lines, HotkeyMods mods, out uint mask, out string error) + { + mask = 0; + error = string.Empty; + Dictionary meta = MetaKeys(lines); + bool Add(string left, string right, string what, ref uint m, out string err) + { + err = string.Empty; + if (meta.TryGetValue(left, out int n) || meta.TryGetValue(right, out n)) { m |= 1u << (n - 1); return true; } + err = $"Your keymap has no {what} modifier (MetaKeys)."; + return false; + } + if ((mods & HotkeyMods.Shift) != 0 && !Add("DIK_LSHIFT", "DIK_RSHIFT", "Shift", ref mask, out error)) return false; + if ((mods & HotkeyMods.Ctrl) != 0 && !Add("DIK_LCONTROL", "DIK_RCONTROL", "Ctrl", ref mask, out error)) return false; + if ((mods & HotkeyMods.Alt) != 0 && !Add("DIK_LMENU", "DIK_RMENU", "Alt", ref mask, out error)) return false; + return true; + } + + /// Every binding line in the Bindings block, with its group. + public static List Bindings(List lines) + { + var list = new List(); + bool inBindings = false; + int depth = 0; + string group = string.Empty; + for (int i = 0; i < lines.Count; i++) + { + string t = lines[i].Trim(); + if (t.Length == 0 || t.StartsWith('#')) continue; + if (!inBindings) + { + if (t == "Bindings") { inBindings = true; depth = 0; } + continue; + } + if (t == "[") { depth++; continue; } + if (t == "]") { depth--; if (depth <= 0) inBindings = false; continue; } + if (depth == 1 && Name.IsMatch(t)) { group = t; continue; } + Match b = BindingLine.Match(t); + if (!b.Success) continue; + uint mask = 0; + if (b.Groups[4].Success) uint.TryParse(b.Groups[4].Value.AsSpan(2), System.Globalization.NumberStyles.HexNumber, null, out mask); + list.Add(new Line(i, group, b.Groups[1].Value, int.Parse(b.Groups[2].Value, System.Globalization.CultureInfo.InvariantCulture), + Canonical(b.Groups[3].Value), mask)); + } + return list; + } + + public static bool IsTextGroup(string group) => Array.Exists(TextGroups, g => g.Equals(group, StringComparison.OrdinalIgnoreCase)); + + /// The bindings of this key with these modifiers in the groups the game reads while playing. + public static List Uses(List lines, int device, string dik, uint meta) + { + string d = Canonical(dik); + return Bindings(lines).FindAll(l => l.Device == device && l.Dik == d && l.Meta == meta && !IsTextGroup(l.Group)); + } + + // ── Changing ──────────────────────────────────────────────────────────── + + /// + /// Binds the key to , taking it from every other action that has it (game + /// groups). : the bindings it came off. Returns false (lines unchanged) with + /// when there is nowhere to put it. + /// + public static bool Bind(List lines, string action, int device, string dik, uint meta, out List taken, out string error) + { + error = string.Empty; + string d = Canonical(dik); + List all = Bindings(lines); + taken = all.FindAll(l => l.Device == device && l.Dik == d && l.Meta == meta && !IsTextGroup(l.Group) + && !l.Action.Equals(action, StringComparison.OrdinalIgnoreCase)); + bool already = all.Exists(l => l.Device == device && l.Dik == d && l.Meta == meta + && l.Action.Equals(action, StringComparison.OrdinalIgnoreCase)); + + // Where the new line goes: after the action's last line, else at the end of its group. + string? group = null; + int insertAt = -1; + if (!already) + { + foreach (Line l in all) + if (l.Action.Equals(action, StringComparison.OrdinalIgnoreCase) && !IsTextGroup(l.Group)) { group = l.Group; insertAt = l.Index + 1; } + if (insertAt < 0) + { + group = DefaultGroup(action); + if (group == null) { error = $"No group for {action} in the keymap."; taken = new(); return false; } + } + } + + // Take the key: drop the other lines (bottom up so the indexes hold). + for (int k = taken.Count - 1; k >= 0; k--) + { + lines.RemoveAt(taken[k].Index); + if (insertAt > taken[k].Index) insertAt--; + } + if (already) return true; + + if (insertAt >= 0) + { + lines.Insert(insertAt, Indent(lines[insertAt - 1]) + Format(action, device, d, meta)); + return true; + } + int close = GroupClose(lines, group!, out int open); + if (close >= 0) + { + lines.Insert(close, Indent(lines[close]) + " " + Format(action, device, d, meta)); + return true; + } + if (open >= 0) + { + // The group's name with no [ ] block under it (an empty group). + string gi = Indent(lines[open]); + lines.InsertRange(open + 1, new[] { gi + "[", gi + " " + Format(action, device, d, meta), gi + "]" }); + return true; + } + int end = BindingsClose(lines); + if (end < 0) { error = "The keymap has no Bindings block."; return false; } + lines.InsertRange(end, new[] { string.Empty, " " + group, " [", " " + Format(action, device, d, meta), " ]" }); + return true; + } + + /// Removes the action's binding of this key with these modifiers. False when it had none. + public static bool Unbind(List lines, string action, int device, string dik, uint meta) + { + string d = Canonical(dik); + List mine = Bindings(lines).FindAll(l => l.Device == device && l.Dik == d && l.Meta == meta + && l.Action.Equals(action, StringComparison.OrdinalIgnoreCase)); + for (int k = mine.Count - 1; k >= 0; k--) lines.RemoveAt(mine[k].Index); + return mine.Count > 0; + } + + /// A binding line as AC writes it: UseQuickSlot_1 [ "" [ 0 DIK_1 ] 0x00000002 ]. + public static string Format(string action, int device, string dik, uint meta) => + meta == 0 ? $"{action} [ \"\" [ {device} {dik} ] ]" : $"{action} [ \"\" [ {device} {dik} ] 0x{meta:X8} ]"; + + /// An action's name as the player reads it: "shortcut slot 5", "Toggle Spellbook Panel". + public static string Describe(string action) + { + if (action.StartsWith("UseQuickSlot_", StringComparison.OrdinalIgnoreCase)) return "shortcut slot " + action[13..]; + var sb = new StringBuilder(action.Length + 8); + for (int i = 0; i < action.Length; i++) + { + char c = action[i]; + if (c == '_') { sb.Append(' '); continue; } + if (i > 0 && char.IsUpper(c) && (char.IsLower(action[i - 1]) || i + 1 < action.Length && char.IsLower(action[i + 1]) && char.IsUpper(action[i - 1]))) + sb.Append(' '); + sb.Append(c); + } + return sb.ToString(); + } + + private static string Indent(string line) + { + int n = 0; + while (n < line.Length && line[n] == ' ') n++; + return line[..n]; + } + + /// The line of the group's closing ']' (and of its name), or -1. + private static int GroupClose(List lines, string group, out int nameLine) + { + nameLine = -1; + bool inBindings = false; + int depth = 0; + for (int i = 0; i < lines.Count; i++) + { + string t = lines[i].Trim(); + if (!inBindings) + { + if (t == "Bindings") inBindings = true; + continue; + } + if (t == "[") + { + depth++; + continue; + } + if (t == "]") + { + if (nameLine >= 0 && depth == 2) return i; + depth--; + if (depth <= 0) return -1; + continue; + } + if (depth == 1 && Name.IsMatch(t)) + { + if (nameLine >= 0) return -1; // the next group: ours had no [ ] block + if (t.Equals(group, StringComparison.OrdinalIgnoreCase)) nameLine = i; + } + } + return -1; + } + + /// The line of the Bindings block's closing ']', or -1. + private static int BindingsClose(List lines) + { + bool inBindings = false; + int depth = 0; + for (int i = 0; i < lines.Count; i++) + { + string t = lines[i].Trim(); + if (!inBindings) + { + if (t == "Bindings") inBindings = true; + continue; + } + if (t == "[") depth++; + else if (t == "]" && --depth == 0) return i; + } + return -1; + } +} diff --git a/src/RynthCore.Engine/Compatibility/AcPanels.cs b/src/RynthCore.Engine/Compatibility/AcPanels.cs new file mode 100644 index 0000000..8f99298 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AcPanels.cs @@ -0,0 +1,250 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/AcPanels.cs +// +// AC's own panels (the pack, the character, the spellbook, fellowship, +// allegiance, the map, the options...), opened and closed the way AC does it +// (Tom 2026-10-22: with the retail toolbar hidden, tiny buttons for them). +// Plugin API v90 GetAcPanels / AcPanelAction, and /rc panels. +// +// AC shows and hides a panel with a notice, CM_UI::SendNotice_SetPanelVisibility +// (panel id, visible) (0x0047A4A0, cdecl; gmVitaeUI opens the vitae panel with +// (0xF, 1)). The containers that answer it hold their panels in a table at +// +0x5FC, the count at +0x604 (their notice handler's +4 and +0xC): +// gmFloatyPanelUI 0x1000004F {element, id}: the pack, character... +// gmFloatyEnvPanelUI 0x1000004E {element, id, keep}: vendor, trade, salvage... +// 0x10000054 {element, id, keep}: spellcasting +// gmPanelUI 0x10000008 and gmEnvPanelUI 0x10000033, the docked versions, alike. +// (Read from the test client, 2026-10-22.) A panel is open when its element +// and its container both show (+0xA4 bit 1). A table entry is the panel +// itself (gmInventoryUI) or a frame around it: it is named after the first +// class AC names inside. The containers are found in the UI manager's element +// registry, as RetailToolbarHooks finds the toolbar, and checked by class +// before each use. +// +// Opening and closing is queued and done on AC's game thread after its tick. +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class AcPanels +{ + // CM_UI::SendNotice_SetPanelVisibility: the notice list (0x0047A810), its 0x4DD1F8 handlers, each told (id, visible). + private static readonly byte?[] NoticePattern = + [0xE8, null, null, null, null, 0x8B, 0x10, 0x68, 0xF8, 0xD1, 0x4D, 0x00, 0x8B, 0xC8, 0xFF, 0x52, 0x10, 0x85, 0xC0, 0x74, 0x3A, 0x57, 0x8B, 0x78, 0x04]; + + // The containers: class and table stride. + private static readonly (int Type, int Stride)[] Hosts = + [(0x1000004F, 8), (0x10000008, 8), (0x1000004E, 12), (0x10000033, 12), (0x10000054, 12)]; + + private const int TableOffset = 0x5FC, CountOffset = 0x604, RegionFlagsOffset = 0xA4, VisibleBit = 0x2; + private const int MgrElements = 0x14, MgrElementCount = 0x1C, MaxRegistered = 200_000, MaxPanels = 64; + private const int ChildCountOffset = 0x120, ChildHeadOffset = 0x124; + + private static IntPtr _notice; + private static bool _initialized; + private static string _status = "Not initialized."; + public static string Status => _status; + public static bool CanToggle => _notice != IntPtr.Zero; + + public static void Initialize() + { + if (_initialized) return; + _initialized = true; + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) { _status = "acclient.exe not available."; return; } + var r = HookResolver.Resolve(text, "AcPanels.SendNotice_SetPanelVisibility", NoticePattern, 0); + _notice = r.Success && r.Source == HookResolver.ResolveSource.PatternScan ? r.Address : IntPtr.Zero; + _status = CanToggle ? "ready." : "the panel notice wasn't found."; + RynthLog.Compat("AcPanels: " + _status); + } + + /// One of AC's panels: its id (the notice's), the class AC gives it, open or not. + public readonly record struct Panel(uint Id, string Class, bool Open); + + // The classes AC's own GetUIElementType functions return (Ghidra symbols, read from the client). + private static readonly Dictionary ClassNames = new() + { + [0x1000000D] = "gmExternalContainerUI", [0x10000011] = "gmSalvageUI", [0x10000012] = "gmSecureTradeUI", + [0x10000015] = "gmSpellcastingUI", [0x10000017] = "gmVendorUI", [0x10000018] = "gmAbuseUI", [0x10000019] = "gmBookUI", + [0x1000001A] = "gmCharacterInfoUI", [0x1000001B] = "gmEffectsUI", [0x1000001D] = "gmLinkStatusUI", + [0x1000001E] = "gmMiniGameUI", [0x1000001F] = "gmUrgentAssistanceUI", [0x10000020] = "gmVitaeUI", + [0x10000021] = "gm3DItemsUI", [0x10000022] = "gmBackpackUI", [0x10000023] = "gmInventoryUI", + [0x10000024] = "gmPaperDollUI", [0x10000026] = "gmMapUI", [0x10000028] = "gmConfigUI", + [0x10000029] = "gmGameplayOptionsUI", [0x1000002A] = "gmAttributeUI", [0x1000002B] = "gmSkillUI", + [0x1000002C] = "gmAllegianceUI", [0x1000002D] = "gmFellowshipUI", [0x1000002E] = "gmSpellbookUI", + [0x10000041] = "gmMainChatUI", [0x10000045] = "gmFriendsUI", [0x10000047] = "gmSquelchUI", [0x1000004A] = "gmBarberUI", + }; + + private static readonly IntPtr[] _found = new IntPtr[Hosts.Length]; + private static long _nextFindMs; + private static bool _searchLogged; + + /// + /// The panels AC holds now. : each panel's class names (only /rc panels asks: + /// naming a frame looks inside it, a bounded walk); without, only ids and open (what the corner + /// buttons need, read several times a second). AC's main thread (the render or the game tick). + /// + public static List List(bool names = false) + { + var list = new List(); + using var probe = MemoryProbe.BeginWalk(); + bool any = false; + for (int h = 0; h < Hosts.Length; h++) any |= Valid(h); + if (!any) Find(); + for (int h = 0; h < Hosts.Length; h++) + if (Valid(h)) Read(_found[h], Hosts[h].Stride, names, list); + return list; + } + + private static bool Valid(int h) => _found[h] != IntPtr.Zero && RetailToolbarHooks.TypeOf(_found[h]) == Hosts[h].Type; + + private static void Find() + { + long now = Environment.TickCount64; + if (now < _nextFindMs) return; + _nextFindMs = now + 10000; // a scan of every UI element: rarely (the containers live as long as the UI) + IntPtr mgr = UiElementHooks.Manager; + if (mgr == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(mgr, MgrElementCount + 4)) return; + int count = Marshal.ReadInt32(mgr, MgrElementCount); + IntPtr arr = Marshal.ReadIntPtr(mgr, MgrElements); + if (count <= 0 || count > MaxRegistered || !ClientObjectHooks.IsReadableSpan(arr, count * IntPtr.Size)) return; + for (int i = 0; i < count; i++) + { + IntPtr e = Marshal.ReadIntPtr(arr, i * IntPtr.Size); + if (e == IntPtr.Zero) continue; + int t = RetailToolbarHooks.TypeOf(e); + for (int h = 0; h < Hosts.Length; h++) + if (t == Hosts[h].Type && !Valid(h)) _found[h] = e; + } + if (!_searchLogged) + { + _searchLogged = true; + int n = 0; + for (int h = 0; h < Hosts.Length; h++) if (Valid(h)) n++; + RynthLog.Compat($"AcPanels: {n} panel container(s) among {count} UI elements."); + } + } + + private static bool Shows(IntPtr e) => + ClientObjectHooks.IsReadableSpan(e, RegionFlagsOffset + 4) && (Marshal.ReadInt32(e, RegionFlagsOffset) & VisibleBit) != 0; + + private static void Read(IntPtr host, int stride, bool names, List into) + { + if (!ClientObjectHooks.IsReadableSpan(host, CountOffset + 4)) return; + int n = Marshal.ReadInt32(host, CountOffset); + IntPtr table = Marshal.ReadIntPtr(host, TableOffset); + if (n <= 0 || n > MaxPanels || !ClientObjectHooks.IsReadableSpan(table, n * stride)) return; + bool hostShows = Shows(host); + for (int i = 0; i < n; i++) + { + IntPtr e = Marshal.ReadIntPtr(table, i * stride); + uint id = unchecked((uint)Marshal.ReadInt32(table, i * stride + 4)); + if (e == IntPtr.Zero || id == 0 || id > 0xFFFF || !ClientObjectHooks.IsReadableSpan(e, ChildHeadOffset + 4)) continue; + into.Add(new Panel(id, names ? NameOf(e, 0) : string.Empty, hostShows && Shows(e))); + } + } + + /// The element's class as AC names it, else the named classes inside it ("gmAllegianceUI+gmFellowshipUI"). + private static string NameOf(IntPtr e, int depth) + { + int t = RetailToolbarHooks.TypeOf(e); + if (ClassNames.TryGetValue(t, out string? name)) return name; + var inside = new List(); + int budget = 2000; // a frame around a list of hundreds (a contracts page, a chest) must not cost much + Collect(e, 0, inside, ref budget); + return inside.Count > 0 ? string.Join("+", inside) : $"0x{t:X8}"; + } + + private static void Collect(IntPtr e, int depth, List into, ref int budget) + { + if (depth > 3 || into.Count >= 4 || --budget <= 0 || !ClientObjectHooks.IsReadableSpan(e, ChildHeadOffset + 4) || Marshal.ReadInt32(e, ChildCountOffset) <= 0) return; + IntPtr head = Marshal.ReadIntPtr(e, ChildHeadOffset); + IntPtr node = head == IntPtr.Zero ? IntPtr.Zero : head - 8; + for (int k = 0; node != IntPtr.Zero && k < 64; k++) + { + if (!ClientObjectHooks.IsReadableSpan(node, 0x14)) break; + IntPtr child = Marshal.ReadIntPtr(node, 0x10); + if (child != IntPtr.Zero) + { + if (ClassNames.TryGetValue(RetailToolbarHooks.TypeOf(child), out string? n)) { if (!into.Contains(n)) into.Add(n); } + else Collect(child, depth + 1, into, ref budget); + if (budget <= 0) return; + } + IntPtr next = Marshal.ReadIntPtr(node, 8); + node = next == IntPtr.Zero ? IntPtr.Zero : next - 8; + } + } + + private static List _cached = new(); + private static long _cachedMs = long.MinValue / 2; + + /// 1 open, 0 closed, -1 not one of AC's panels. AC's main thread; read at most 5 times a second. + public static int State(uint id) + { + long now = Environment.TickCount64; + if (now - _cachedMs > 200) + { + _cached = List(); + _cachedMs = now; + } + foreach (Panel p in _cached) + if (p.Id == id) return p.Open ? 1 : 0; + return -1; + } + + // ── Opening and closing (queued, game thread) ──────────────────────────── + + /// What to do with a panel: open it, close it, or the other of what it is now. + public enum Op { Toggle = 0, Open = 1, Close = 2 } + + private readonly record struct Request(uint Id, Op Op, long QueuedMs); + + private static readonly ConcurrentQueue Requests = new(); + + /// Queues a panel to open, close or toggle (by its id, ). Any thread. + public static bool Enqueue(uint id, Op op) + { + if (!CanToggle || id == 0 || id > 0xFFFF || Requests.Count >= 8) return false; + Requests.Enqueue(new Request(id, op, Environment.TickCount64)); + return true; + } + + /// Game thread, after AC's tick. + public static void Drain() + { + if (Requests.IsEmpty) return; + long now = Environment.TickCount64; + if (PlayerLifecycleLog.HoldQueuedWork(now)) return; + while (Requests.TryDequeue(out Request r)) + { + if (now - r.QueuedMs > 3000) continue; + try + { + bool open = r.Op == Op.Open; + if (r.Op == Op.Toggle) + { + List all = List(); + int at = all.FindIndex(x => x.Id == r.Id); + if (at < 0) { RynthLog.Compat($"AcPanels: no panel {r.Id}."); continue; } + open = !all[at].Open; + } + ((delegate* unmanaged[Cdecl])_notice)(r.Id, open ? 1 : 0); + _cachedMs = long.MinValue / 2; + } + catch (Exception ex) + { + RynthLog.Compat($"AcPanels: panel {r.Id} threw {ex.GetType().Name}: {ex.Message}"); + } + } + } + + public static void Reset() + { + while (Requests.TryDequeue(out _)) { } + Array.Clear(_found); + } +} diff --git a/src/RynthCore.Engine/Compatibility/AcShortcuts.cs b/src/RynthCore.Engine/Compatibility/AcShortcuts.cs new file mode 100644 index 0000000..5a3ce22 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AcShortcuts.cs @@ -0,0 +1,233 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/AcShortcuts.cs +// +// The player's shortcut slots, AC's own (Tom 2026-10-22: the keys a plugin's +// item bar shows must be the ones the player had in retail, work the same, +// and change together with the retail toolbar). Plugin API v90: +// GetShortcuts (what is in the 18 slots) and ShortcutAction (use a slot, put +// an item in one, empty one), for RynthDefective's bar. +// +// Where they live (Ghidra symbols + disassembly of the 4,841,472-byte client): +// CPlayerSystem (CharacterManagementHooks) + 0x34 is the PlayerModule +// (gmToolbarUI::AddShortcut: lea ecx,[eax+0x34]; PlayerModule::AddShortCut); +// its +0x04 is the ShortCutManager (0x4C bytes: a vtable, then 18 slot +// pointers, ShortCutManager::AddShortCut keeps the index in 0..0x11); a slot +// is a ShortCutData (0x10 bytes: vtable, +4 its index, +8 the object id, +// +0xC a spell id). That list is what the server saved and what the retail +// toolbar shows. +// +// Doing, through the retail toolbar's own functions on the gmToolbarUI that +// holds the slots (RetailToolbarHooks.ShortcutToolbar), shown or hidden: +// use gmToolbarUI::UseShortcut(slot, 1) 0x004BDFE0, ret 8: what +// AC's UseQuickSlot_N key does (ListenToGlobalMessage). +// set gmToolbarUI::CreateShortcutToItem(id, slot, 0, 0) 0x004BE750, +// ret 0x10: what retail's own "make a shortcut" does: AC's checks +// (shortcut eligible, owned by the player; it says why not, in AC's +// words), the item out of any slot it is in already (RemoveShortcut: +// it moves, as dragging it does), then AddShortcut(id, slot, 1) at +// 0x004BE630: the slot's list, the server (Event_AddShortCut) and the +// PlayerModule's list. The third argument 0: an item not carried is +// never picked up for it (retail's key passes 1). +// clear gmToolbarUI::RemoveShortcutInSlotNum(slot, 1) 0x004BE180, ret 8. +// Queued from any thread and run on AC's game thread just before its tick +// (GameTickHooks, beside the cast drain: AC's own input -> UseTime order), +// held while the player is between worlds (PlayerLifecycleLog), dropped after +// 6 s. The slots are read on the game thread after the tick, 4 times a second, +// into a snapshot GetShortcuts returns from any thread. +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class AcShortcuts +{ + public const int SlotCount = 18; + + private const int PlayerModuleOffset = 0x34, ShortCutManagerOffset = 0x04, SlotArrayOffset = 0x04; + private const int SlotObjectOffset = 0x08, SlotSpellOffset = 0x0C, SlotDataSize = 0x10; + + private const int UseFallbackVa = 0x004BDFE0, CreateFallbackVa = 0x004BE750, RemoveFallbackVa = 0x004BE180; + + // gmToolbarUI::UseShortcut(int slot, bool): range checks against +0x63C, the slot's list at +0x634. + private static readonly byte?[] UsePattern = + [ + 0x8B, 0x44, 0x24, 0x04, 0x85, 0xC0, 0x0F, 0x8C, null, null, null, null, + 0x3B, 0x81, 0x3C, 0x06, 0x00, 0x00, 0x0F, 0x8D, null, null, null, null, + 0x8B, 0x89, 0x34, 0x06, 0x00, 0x00, 0x8B, 0x0C, 0x81 + ]; + + // gmToolbarUI::CreateShortcutToItem(uint id, int slot, bool pickUp, bool quiet): a 0x9C frame, ebp = the + // object (0 = nothing to do), esi = this, then GetWeenieObject(id); ret 0x10. + private static readonly byte?[] CreatePattern = + [ + 0x81, 0xEC, 0x9C, 0x00, 0x00, 0x00, 0x55, 0x8B, 0xAC, 0x24, 0xA4, 0x00, 0x00, 0x00, 0x85, 0xED, + 0x56, 0x8B, 0xF1, 0x0F, 0x84, null, null, null, null, 0x53, 0x57, 0x55, 0xE8 + ]; + + // gmToolbarUI::RemoveShortcutInSlotNum(int slot, bool save): edi = this, against +0x63C. + private static readonly byte?[] RemovePattern = + [ + 0x8B, 0x44, 0x24, 0x04, 0x85, 0xC0, 0x56, 0x57, 0x8B, 0xF9, 0x7C, null, + 0x3B, 0x87, 0x3C, 0x06, 0x00, 0x00, 0x7D, null + ]; + + private static IntPtr _use, _create, _remove; + private static bool _initialized; + private static string _status = "Not initialized."; + public static string Status => _status; + public static bool CanUse => _use != IntPtr.Zero; + public static bool CanEdit => _create != IntPtr.Zero && _remove != IntPtr.Zero; + + /// Resolves the three toolbar functions (pattern only: a guessed address is never called). + public static void Initialize() + { + if (_initialized) return; + _initialized = true; + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + _status = "acclient.exe not available."; + return; + } + IntPtr Resolve(string name, byte?[] pattern, int fallback) + { + var r = HookResolver.Resolve(text, "AcShortcuts." + name, pattern, fallback); + return r.Success && r.Source == HookResolver.ResolveSource.PatternScan ? r.Address : IntPtr.Zero; + } + _use = Resolve("gmToolbarUI::UseShortcut", UsePattern, UseFallbackVa); + _create = Resolve("gmToolbarUI::CreateShortcutToItem", CreatePattern, CreateFallbackVa); + _remove = Resolve("gmToolbarUI::RemoveShortcutInSlotNum", RemovePattern, RemoveFallbackVa); + _status = $"use {(_use != IntPtr.Zero ? "ok" : "missing")}, set {(_create != IntPtr.Zero ? "ok" : "missing")}, clear {(_remove != IntPtr.Zero ? "ok" : "missing")}."; + RynthLog.Compat("AcShortcuts: " + _status); + } + + // ── The slots (snapshot, read on the game thread after its tick) ───────── + + /// One slot: the object in it (0 = empty) and a spell id (0 for an item). + public readonly record struct Slot(uint ObjectId, uint SpellId); + + private static volatile Slot[] _slots = Array.Empty(); + private static long _nextReadMs; + + /// The 18 slots as last read (empty out of the world). Any thread. + public static Slot[] Slots => _slots; + + /// Game thread, after AC's tick: the slots again, 4 times a second. + public static void ReadTick() + { + long now = Environment.TickCount64; + if (now < _nextReadMs) return; + _nextReadMs = now + 250; + if (!LoginLifecycleHooks.HasObservedLoginComplete) { _slots = Array.Empty(); return; } + Slot[]? read = ReadSlots(); + if (read == null) return; + Slot[] old = _slots; + if (old.Length == read.Length) + { + bool same = true; + for (int i = 0; i < read.Length && same; i++) same = old[i] == read[i]; + if (same) return; + } + _slots = read; + } + + private static Slot[]? ReadSlots() + { + IntPtr ps = CharacterManagementHooks.PlayerSystemOnMainThread(); + if (ps == IntPtr.Zero) return null; + IntPtr module = ps + PlayerModuleOffset; + if (!ClientObjectHooks.IsReadableSpan(module, ShortCutManagerOffset + 4)) return null; + IntPtr mgr = Marshal.ReadIntPtr(module, ShortCutManagerOffset); + var slots = new Slot[SlotCount]; + if (mgr == IntPtr.Zero) return slots; // no shortcuts made yet: all empty + if (!ClientObjectHooks.IsReadableSpan(mgr, SlotArrayOffset + SlotCount * 4)) return null; + for (int i = 0; i < SlotCount; i++) + { + IntPtr entry = Marshal.ReadIntPtr(mgr, SlotArrayOffset + i * 4); + if (entry == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(entry, SlotDataSize)) continue; + slots[i] = new Slot(unchecked((uint)Marshal.ReadInt32(entry, SlotObjectOffset)), + unchecked((uint)Marshal.ReadInt32(entry, SlotSpellOffset))); + } + return slots; + } + + // ── Doing (queued; run on the game thread before its tick) ─────────────── + + public enum Op { Use = 0, Set = 1, Clear = 2 } + + private readonly record struct Request(Op Op, int Slot, uint ObjectId, long QueuedMs); + + private static readonly ConcurrentQueue Queue = new(); + private const int MaxQueued = 16; + private const long GiveUpMs = 6000; + + /// + /// Queues on slot (0-17); Set needs the object. + /// False when it can't be done here (out of range, the function wasn't found, a full queue). + /// Any thread. + /// + public static bool Enqueue(Op op, int slot, uint objectId) + { + if (slot < 0 || slot >= SlotCount) return false; + if (op == Op.Use ? !CanUse : !CanEdit) return false; + if (op == Op.Set && objectId == 0) return false; + if (Queue.Count >= MaxQueued) return false; + Queue.Enqueue(new Request(op, slot, objectId, Environment.TickCount64)); + return true; + } + + /// Game thread, before AC's tick. Alloc-free when nothing is queued; never throws. + public static void Drain() + { + if (Queue.IsEmpty) return; + long now = Environment.TickCount64; + if (PlayerLifecycleLog.HoldQueuedWork(now)) + { + // Between worlds: keep them, unless they waited too long. + while (Queue.TryPeek(out Request old) && now - old.QueuedMs > GiveUpMs) Queue.TryDequeue(out _); + return; + } + IntPtr toolbar = RetailToolbarHooks.ShortcutToolbar(); + while (Queue.TryDequeue(out Request r)) + { + if (now - r.QueuedMs > GiveUpMs) continue; + if (toolbar == IntPtr.Zero) + { + RynthLog.Compat($"AcShortcuts: {r.Op} slot {r.Slot + 1} dropped: the shortcut toolbar isn't found."); + continue; + } + try + { + switch (r.Op) + { + case Op.Use: + ((delegate* unmanaged[Thiscall])_use)(toolbar, r.Slot, 1); + break; + case Op.Set: + ((delegate* unmanaged[Thiscall])_create)(toolbar, r.ObjectId, r.Slot, 0, 0); + RynthLog.Compat($"AcShortcuts: slot {r.Slot + 1} = 0x{r.ObjectId:X8}."); + break; + case Op.Clear: + ((delegate* unmanaged[Thiscall])_remove)(toolbar, r.Slot, 1); + RynthLog.Compat($"AcShortcuts: slot {r.Slot + 1} emptied."); + break; + } + } + catch (Exception ex) + { + RynthLog.Compat($"AcShortcuts: {r.Op} slot {r.Slot + 1} threw {ex.GetType().Name}: {ex.Message}"); + } + _nextReadMs = 0; // show the change on the next read + } + } + + /// Logout / relog: nothing queued for the old character, nothing shown. + public static void Reset() + { + while (Queue.TryDequeue(out _)) { } + _slots = Array.Empty(); + } +} diff --git a/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs b/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs index 02ad215..b12da1a 100644 --- a/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs @@ -652,6 +652,28 @@ internal static class CharacterManagementHooks : IntPtr.Zero; } + /// + /// The CPlayerSystem singleton for AcShortcuts (the player's shortcut list lives in its + /// PlayerModule). AC's main thread; zero when it can't be read. + /// + internal static IntPtr PlayerSystemOnMainThread() + { + if (!MainThreadGuard.IsOnMainThread()) return IntPtr.Zero; + var get = _getPlayerSystem; + if (get != null) + { + try + { + IntPtr p = get(); + if (p != IntPtr.Zero) return p; + } + catch { } + } + IntPtr addr = new(_playerSystemAddr); + if (_playerSystemAddr == 0 || !ClientObjectHooks.IsReadablePointer(addr)) return IntPtr.Zero; + return Marshal.ReadIntPtr(addr); + } + private static IntPtr GetPlayerSystemPointer() { if (!MainThreadGuard.IsOnMainThread()) diff --git a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs index ad293a3..3ae2a97 100644 --- a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs +++ b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs @@ -148,6 +148,10 @@ internal static class GameTickHooks // pending. Must never throw into AC's native frame. try { AcMainThreadQueue.DrainCasts(); } catch { } + // Shortcut slots used or changed from RynthCore (AcShortcuts), the same moment AC's own + // keys reach the toolbar: before this tick. Alloc-free when nothing is queued. + try { AcShortcuts.Drain(); } + catch { } // Run AC's own game-logic + physics + animation pass. int result; @@ -229,6 +233,12 @@ internal static class GameTickHooks // cast gate, pose, ...). Post-tick, so they reflect this tick's physics. try { MainThreadSnapshots.Tick(); } catch { } + try { AcShortcuts.ReadTick(); } + catch { } + try { AcKeymapLive.Tick(); } + catch { } + try { AcPanels.Drain(); } + catch { } // Decal clients only (no EndScene hook): the prefetches EngineFrameController // runs per frame. False for every other client - one flag check. if (HeadlessPrefetch) diff --git a/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs b/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs index afe541c..0fce0bf 100644 --- a/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs +++ b/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs @@ -234,6 +234,7 @@ internal static unsafe class LogoffOriginProbe ChatHooks.OnLogoffRequested(); RadarHooks.OnLogoffRequested(); RetailVitalsHooks.OnLogoffRequested(); + RetailToolbarHooks.OnLogoffRequested(); long now = Environment.TickCount64; IntPtr caller = LogoutLifecycleHooks.LogCaller(fn, "LogoffProbe"); string callerText = DescribeAcclientAddress(caller); diff --git a/src/RynthCore.Engine/Compatibility/PowerbarHooks.cs b/src/RynthCore.Engine/Compatibility/PowerbarHooks.cs index 4780641..526145a 100644 --- a/src/RynthCore.Engine/Compatibility/PowerbarHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PowerbarHooks.cs @@ -119,6 +119,18 @@ internal static class PowerbarHooks // not edited for it); it resolves and hooks on its own and never throws. try { RetailVitalsHooks.Initialize(); } catch (Exception ex) { RynthLog.Compat($"PowerbarHooks: RetailVitalsHooks.Initialize threw {ex.GetType().Name}: {ex.Message}"); } + // "Hide retail toolbar" likewise (2026-10-22). + try { RetailToolbarHooks.Initialize(); } + catch (Exception ex) { RynthLog.Compat($"PowerbarHooks: RetailToolbarHooks.Initialize threw {ex.GetType().Name}: {ex.Message}"); } + // The shortcut slots' functions (AcShortcuts, plugin API v90). + try { AcShortcuts.Initialize(); } + catch (Exception ex) { RynthLog.Compat($"PowerbarHooks: AcShortcuts.Initialize threw {ex.GetType().Name}: {ex.Message}"); } + // Changing keys so every client follows (AcKeymapLive, plugin API v90). + try { AcKeymapLive.Initialize(); } + catch (Exception ex) { RynthLog.Compat($"PowerbarHooks: AcKeymapLive.Initialize threw {ex.GetType().Name}: {ex.Message}"); } + // AC's own panels, opened and closed as AC does (AcPanels, plugin API v90). + try { AcPanels.Initialize(); } + catch (Exception ex) { RynthLog.Compat($"PowerbarHooks: AcPanels.Initialize threw {ex.GetType().Name}: {ex.Message}"); } if (_hookInstalled) return; diff --git a/src/RynthCore.Engine/Compatibility/RetailToolbarHooks.cs b/src/RynthCore.Engine/Compatibility/RetailToolbarHooks.cs new file mode 100644 index 0000000..55792b2 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/RetailToolbarHooks.cs @@ -0,0 +1,883 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/RetailToolbarHooks.cs +// +// "Hide retail toolbar": hides AC's toolbar panel (the combat-mode button, the +// panel buttons, the selection's name and health, examine, the backpack, and +// the two rows of shortcut slots under them; Tom 2026-10-22: bulky, and its +// buttons are on keys anyway). Same shape as RetailVitalsHooks: capture the +// UIElement, then EndSceneHook calls TickHide every frame, which calls +// UIElement::SetVisible on it. +// +// What the panel is (Ghidra symbols + disassembly of the 4,841,472-byte client): +// gmToolbarUI (element class 0x10000007, 0x64C bytes) derives from +// UIElement_Field like gmVitalsUI, so the UIElement is at offset 0 and the +// NoticeHandler sits at +0x5F8 (its RecvNotice_* thunks: add ecx,-0x5F8). +// What AC draws is gmFloatyToolbarUI (class 0x10000051), a movable window +// that derives from gmToolbarUI and holds the gmToolbarUI with the buttons +// and slots; hiding only that inner one leaves the panel on screen. So the +// floaty window is what is hidden, with the base UIElement::SetVisible +// called directly: the floaty's own override (0x004D0E00) also saves the +// window's open state to the player's options, which must not change. +// +// Capture, from two functions that run with the primary (UIElement) pointer: +// gmToolbarUI::HandleSelectionChanged (0x004C0010, thiscall, no arguments): +// every selection change (through RecvNotice_SelectionChanged's thunk). +// gmToolbarUI::ListenToGlobalMessage (0x004BF170, thiscall, 2 arguments): +// every key action broadcast to it (UIElementManager::BroadcastGlobalMessage +// calls every registered listener, shown or not). This is where the +// shortcut keys run (UseShortcut), so a hidden toolbar keeps them working. +// And without waiting for either (a reload in the world, a bot that selects +// nothing): TickHide looks for it in AC's UI tree by memory reads (SearchTree). +// As for the vitals, an instance is only kept if its vtable's slot 0x18 is +// UIElement::SetVisible (directly or through a one-jmp thunk). +// +// Restore, freed instances, logoff and relog: exactly RetailVitalsHooks'. +// Installed from PowerbarHooks.Initialize beside it. Both hook targets go +// through HookResolver and are only hooked on a pattern match. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class RetailToolbarHooks +{ + // Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth. + private const int SelectionChangedFallbackVa = 0x004C0010; + private const int ListenGlobalFallbackVa = 0x004BF170; + private const int UIElementSetVisibleFallbackVa = 0x00462390; + + // gmToolbarUI::HandleSelectionChanged(): 0x1C-byte frame, ebx = the selection global, + // then the compare against its own last selection at +0x630. Unique in the text window + // with the global's address wildcarded (checked with tools\pe_pattern.py). + private static readonly byte?[] SelectionChangedPattern = + [ + 0x83, 0xEC, 0x1C, // sub esp, 0x1C + 0x53, // push ebx + 0x8B, 0x1D, null, null, null, null, // mov ebx, [selected id global] + 0x56, // push esi + 0x8B, 0xF1, // mov esi, ecx + 0x39, 0x9E, 0x30, 0x06, 0x00, 0x00, // cmp [esi+0x630], ebx + 0x89, 0x5C, 0x24, 0x0C, // mov [esp+0Ch], ebx + 0x0F, 0x84 // je rel32 + ]; + + // gmToolbarUI::ListenToGlobalMessage(int message, int action): message 1 only, then + // its quantity box's focus (+0x624) and the 0x27 action. Unique likewise; ret 8. + private static readonly byte?[] ListenGlobalPattern = + [ + 0x83, 0x7C, 0x24, 0x04, 0x01, // cmp dword [esp+4], 1 + 0x56, // push esi + 0x8B, 0xF1, // mov esi, ecx + 0x0F, 0x85, null, null, null, null, // jne rel32 + 0x8B, 0x8E, 0x24, 0x06, 0x00, 0x00, // mov ecx, [esi+0x624] + 0xE8, null, null, null, null, // call rel32 (UIElement::GetHasFocus) + 0x84, 0xC0, // test al, al + 0x74, null, // je rel8 + 0x83, 0x7C, 0x24, 0x0C, 0x27 // cmp dword [esp+0Ch], 0x27 + ]; + + // UIElement::SetVisible(bool): the pattern ChatHooks / RadarHooks / PowerbarHooks / + // RetailVitalsHooks resolve; each consumer resolves it independently. + private static readonly byte?[] UIElementSetVisiblePattern = + [ + 0x51, 0x53, 0x56, 0x57, + 0x8B, 0x3D, null, null, null, null, // mov edi, ds:[imm32] + 0x8B, 0xF1, + 0xE8, null, null, null, null, // call rel32 + 0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00, + 0x88, 0x44, 0x24, 0x0F + ]; + + // UIRegion's own "visible" flag: bit 1 of the dword at +0xA4 (see RetailVitalsHooks). + private const int RegionFlagsOffset = 0xA4; + private const int RegionVisibleBit = 0x2; + private const int SetVisibleVtableSlot = 0x18; + + // AC builds the docked toolbar and its floaty twin; room for a stray third. + private const int MaxInstances = 4; + + private struct Slot + { + public IntPtr Instance; + public IntPtr Vtable; // the instance's vtable when captured + public bool HiddenByUs; // TickHide turned it off; show it again when the option goes off + } + + // Written by the detours and read by TickHide, all on AC's main thread only. + private static readonly Slot[] Slots = new Slot[MaxInstances]; + + // Set when a logoff is requested, cleared when the logout completes (as RetailVitalsHooks). + private static volatile bool _logoffInProgress; + + private static IntPtr _uiElementSetVisibleAddress; + private static IntPtr _originalSelectionChanged, _originalListenGlobal; + private static bool _hookInstalled; + private static string _statusMessage = "Not initialized."; + private static int _captureLogs, _rejectLogs, _hideLogs; + + public static bool IsInstalled => _hookInstalled; + public static string StatusMessage => _statusMessage; + + // ── The setting ─────────────────────────────────────────────────────────── + + private static readonly object SettingSync = new(); + private static volatile bool _hide; + private static bool _settingLoaded; + + private static string SettingPath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "retail_ui.txt"); + private const string HideToolbarKey = "HideRetailToolbar"; + + /// + /// 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 + /// and writes the file; TickHide applies it on AC's main thread. + /// + public static bool HideRetailToolbar + { + get { EnsureSettingLoaded(); return _hide; } + set + { + EnsureSettingLoaded(); + lock (SettingSync) + { + if (_hide == value) return; + _hide = value; + SaveSetting(); + if (!value) { _unhidePending = true; _unhideFallback = true; } + } + RynthLog.Compat($"RetailToolbarHooks: Hide retail toolbar -> {value} (installed={_hookInstalled}, captured={CountCaptured()})."); + } + } + + public static void EnsureSettingLoaded() + { + if (_settingLoaded) return; + lock (SettingSync) + { + if (_settingLoaded) return; + _settingLoaded = true; + _hide = ReadSetting(out _settingWriteUtc); + // Off at the start (a new generation, or another client switched it off): one toolbar shows, + // whatever an earlier generation hid (it may not have noted it). + if (!_hide) { _unhidePending = true; _unhideFallback = true; } + } + } + + private static bool ReadSetting(out DateTime writeUtc) + { + writeUtc = DateTime.MinValue; + bool hide = false; + try + { + string path = SettingPath; + if (!File.Exists(path)) return false; + writeUtc = File.GetLastWriteTimeUtc(path); + foreach (string line in File.ReadAllLines(path)) + { + int eq = line.IndexOf('='); + if (eq <= 0 || !line[..eq].Trim().Equals(HideToolbarKey, StringComparison.OrdinalIgnoreCase)) continue; + if (int.TryParse(line.AsSpan(eq + 1).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int v)) + hide = v != 0; + } + } + catch (Exception ex) + { + RynthLog.Compat($"RetailToolbarHooks: could not read {SettingPath}: {ex.GetType().Name}: {ex.Message}"); + } + return hide; + } + + // The file is the PC's: another client's change applies here too (checked every 2 s, main thread). + private static DateTime _settingWriteUtc; + private static long _nextSettingCheckMs; + + private static void FollowSettingFile() + { + long now = Environment.TickCount64; + if (now < _nextSettingCheckMs) return; + _nextSettingCheckMs = now + 2000; + try + { + string path = SettingPath; + DateTime w = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue; + if (w == _settingWriteUtc) return; + bool hide = ReadSetting(out DateTime read); + lock (SettingSync) + { + _settingWriteUtc = read; + if (hide == _hide) return; + _hide = hide; + if (!hide) { _unhidePending = true; _unhideFallback = true; } + } + RynthLog.Compat($"RetailToolbarHooks: Hide retail toolbar -> {hide} (changed in another client)."); + } + catch { } + } + + // ── What this process hid, across engine generations ───────────────────── + // + // A hot reload starts with no memory of what the last generation hid, so the addresses of the + // toolbar elements RynthCore hid are kept in the process's environment (it outlives every + // engine generation, and no other process sees it). "Show the retail toolbar" shows those + // again, whichever generation hid them. + + private const string HiddenEnv = "RYNTHCORE_RETAIL_TOOLBAR_HIDDEN"; + private static volatile bool _unhidePending, _unhideFallback; + + private static List HiddenByUsBefore() + { + var list = new List(); + string? v = Environment.GetEnvironmentVariable(HiddenEnv); + if (string.IsNullOrEmpty(v)) return list; + foreach (string part in v.Split(',', StringSplitOptions.RemoveEmptyEntries)) + if (int.TryParse(part, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int a) && a != 0) list.Add(new IntPtr(a)); + return list; + } + + private static void NoteHiddenByUs(IntPtr inst) + { + List list = HiddenByUsBefore(); + if (list.Contains(inst)) return; + list.Add(inst); + Environment.SetEnvironmentVariable(HiddenEnv, string.Join(",", list.ConvertAll(p => p.ToInt32().ToString("X8", CultureInfo.InvariantCulture)))); + } + + private static bool IsToolbarElement(IntPtr inst) + { + if (!ClientObjectHooks.IsReadableSpan(inst, RegionFlagsOffset + 4)) return false; + int t = TypeOf(inst); + return t == FloatyToolbarType || (t == ToolbarType && IsSetVisibleSlot(Marshal.ReadIntPtr(inst))); + } + + /// + /// The setting went off: everything RynthCore hid (this generation or an earlier one) shows again. + /// (it was just switched off): if that leaves no toolbar on screen (it was + /// hidden before RynthCore kept track), the floaty toolbar window shows, else the docked one: one + /// toolbar, never both twins. Main thread. + /// + private static void Unhide(IntPtr setVisible, bool fallback) + { + int shown = 0; + var done = new HashSet(); + void Show(IntPtr inst) + { + if (!done.Add(inst) || !IsToolbarElement(inst) || IsOwnVisible(inst)) return; + try { ((delegate* unmanaged[Thiscall])setVisible)(inst, 1); shown++; } + catch { /* best-effort */ } + } + foreach (IntPtr inst in HiddenByUsBefore()) Show(inst); + for (int i = 0; i < Slots.Length; i++) + { + if (Slots[i].HiddenByUs && Slots[i].Instance != IntPtr.Zero) Show(Slots[i].Instance); + Slots[i].HiddenByUs = false; + } + Environment.SetEnvironmentVariable(HiddenEnv, null); + + bool anyVisible = false; + IntPtr floaty = IntPtr.Zero, docked = IntPtr.Zero; + for (int i = 0; i < Slots.Length; i++) + { + IntPtr inst = Slots[i].Instance; + if (inst == IntPtr.Zero || !StillAlive(Slots[i])) continue; + if (IsOwnVisible(inst)) anyVisible = true; + int t = TypeOf(inst); + if (t == FloatyToolbarType && floaty == IntPtr.Zero) floaty = inst; + else if (t == ToolbarType && docked == IntPtr.Zero) docked = inst; + } + if (fallback && !anyVisible) + { + IntPtr pick = floaty != IntPtr.Zero ? floaty : docked; + if (pick != IntPtr.Zero) Show(pick); + } + RynthLog.Compat($"RetailToolbarHooks: retail toolbar shown again ({shown} element(s); {CountCaptured()} held)."); + } + + // Caller holds SettingSync. Keeps every other key=value line in the file (HideRetailVitals ...). + private static void SaveSetting() + { + try + { + string path = SettingPath; + var lines = new List(); + if (File.Exists(path)) + { + foreach (string line in File.ReadAllLines(path)) + { + int eq = line.IndexOf('='); + if (eq > 0 && line[..eq].Trim().Equals(HideToolbarKey, StringComparison.OrdinalIgnoreCase)) continue; + if (line.Trim().Length > 0) lines.Add(line); + } + } + lines.Add($"{HideToolbarKey}={(_hide ? 1 : 0)}"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllLines(path, lines); + } + catch (Exception ex) + { + RynthLog.Compat($"RetailToolbarHooks: could not save {SettingPath}: {ex.GetType().Name}: {ex.Message}"); + } + } + + // ── Install ─────────────────────────────────────────────────────────────── + + public static void Initialize() + { + EnsureSettingLoaded(); + if (_hookInstalled) + return; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection)) + { + _statusMessage = "acclient.exe not available."; + return; + } + + var setVisible = HookResolver.Resolve(textSection, "RetailToolbarHooks.UIElement::SetVisible", + UIElementSetVisiblePattern, UIElementSetVisibleFallbackVa); + if (!setVisible.Success) + { + _statusMessage = $"UIElement::SetVisible resolve failed ({setVisible.Detail})."; + RynthLog.Compat($"RetailToolbarHooks: {_statusMessage} Not hooked."); + return; + } + + var selection = HookResolver.Resolve(textSection, "RetailToolbarHooks.gmToolbarUI::HandleSelectionChanged", + SelectionChangedPattern, SelectionChangedFallbackVa); + var listen = HookResolver.Resolve(textSection, "RetailToolbarHooks.gmToolbarUI::ListenToGlobalMessage", + ListenGlobalPattern, ListenGlobalFallbackVa); + + // Only hook through a pattern match: a guessed address for a hook target is worse than no + // "Hide retail toolbar" (as RetailVitalsHooks). Either capture alone is enough. + bool selectionOk = selection.Success && selection.Source == HookResolver.ResolveSource.PatternScan; + bool listenOk = listen.Success && listen.Source == HookResolver.ResolveSource.PatternScan; + if (!selectionOk && !listenOk) + { + _statusMessage = $"no capture point by pattern (HandleSelectionChanged: {selection.Detail}; ListenToGlobalMessage: {listen.Detail}); not hooked."; + RynthLog.Compat($"RetailToolbarHooks: {_statusMessage}"); + return; + } + + _uiElementSetVisibleAddress = setVisible.Address; + var hooked = new List(); + if (selectionOk) + { + try + { + delegate* unmanaged[Thiscall] detour = &SelectionChangedDetour; + MinHook.Hook(selection.Address, (IntPtr)detour, out _originalSelectionChanged); + hooked.Add($"HandleSelectionChanged @ 0x{selection.Address.ToInt32():X8}"); + } + catch (Exception ex) + { + _originalSelectionChanged = IntPtr.Zero; + RynthLog.Compat($"RetailToolbarHooks: HandleSelectionChanged hook threw {ex.GetType().Name}: {ex.Message}"); + } + } + if (listenOk) + { + try + { + delegate* unmanaged[Thiscall] detour = &ListenGlobalDetour; + MinHook.Hook(listen.Address, (IntPtr)detour, out _originalListenGlobal); + hooked.Add($"ListenToGlobalMessage @ 0x{listen.Address.ToInt32():X8}"); + } + catch (Exception ex) + { + _originalListenGlobal = IntPtr.Zero; + RynthLog.Compat($"RetailToolbarHooks: ListenToGlobalMessage hook threw {ex.GetType().Name}: {ex.Message}"); + } + } + + _hookInstalled = hooked.Count > 0; + _statusMessage = _hookInstalled + ? $"Hooked {string.Join(", ", hooked)}; SetVisible @ 0x{setVisible.Address.ToInt32():X8}." + : "both hooks failed; not hooked."; + RynthLog.Compat($"RetailToolbarHooks: {_statusMessage} Hide retail toolbar={_hide}."); + } + + // ── Capture (AC's main thread; must never throw into AC) ───────────────── + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })] + private static void SelectionChangedDetour(IntPtr thisPtr) + { + try + { + RecursionGuard.Tick("RetailToolbarHooks.SelectionChanged"); + if (thisPtr != IntPtr.Zero && !_logoffInProgress && MainThreadGuard.IsOnMainThread()) + CaptureWithWrapper(thisPtr, "selection"); + } + catch { } + ((delegate* unmanaged[Thiscall])_originalSelectionChanged)(thisPtr); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })] + private static void ListenGlobalDetour(IntPtr thisPtr, int message, int action) + { + try + { + RecursionGuard.Tick("RetailToolbarHooks.ListenGlobal"); + if (thisPtr != IntPtr.Zero && !_logoffInProgress && MainThreadGuard.IsOnMainThread()) + CaptureWithWrapper(thisPtr, "key action"); + } + catch { } + ((delegate* unmanaged[Thiscall])_originalListenGlobal)(thisPtr, message, action); + } + + private static void Capture(IntPtr inst, string via) + { + int free = -1; + for (int i = 0; i < Slots.Length; i++) + { + if (Slots[i].Instance == inst) return; // already have it + if (free < 0 && Slots[i].Instance == IntPtr.Zero) free = i; + } + + if (!ClientObjectHooks.IsReadableSpan(inst, RegionFlagsOffset + 4)) + { + Reject(inst, "object not readable"); + return; + } + IntPtr vtable = Marshal.ReadIntPtr(inst); + // The floaty toolbar overrides SetVisible (it saves the window's open state to the player's + // options after the base call); TickHide calls the base UIElement::SetVisible directly, so + // that one is accepted by its type instead and nothing is ever saved. + if (!IsSetVisibleSlot(vtable) && TypeOf(inst) != FloatyToolbarType) + { + Reject(inst, $"vtable 0x{vtable.ToInt32():X8} slot 0x{SetVisibleVtableSlot:X} is not UIElement::SetVisible"); + return; + } + + if (free < 0) + { + // Full: reuse a slot whose object is gone. With none, keep the ones we have. + for (int i = 0; i < Slots.Length; i++) + { + if (!StillAlive(Slots[i])) { free = i; break; } + } + if (free < 0) + { + Reject(inst, "all slots hold live instances"); + return; + } + } + + Slots[free] = new Slot { Instance = inst, Vtable = vtable, HiddenByUs = false }; + if (++_captureLogs <= 8) + RynthLog.Compat($"RetailToolbarHooks: captured toolbar element 0x{inst.ToInt32():X8} by {via} (vtable 0x{vtable.ToInt32():X8}, visible={IsOwnVisible(inst)})."); + } + + // gmFloatyToolbarUI (element class 0x10000051, registered by gmFloatyToolbarUI::Register + // 0x004D0450): the movable window AC actually draws, holding the gmToolbarUI (0x10000007) + // with the buttons and slots. Hiding only the inner one leaves the panel on screen + // (2026-10-22, the test client), so the wrapper is hidden too. + private const int ToolbarType = 0x10000007, FloatyToolbarType = 0x10000051; + private const int VtGetUIElementType = 0x98; + + /// + /// The element's class id, read (not called) from its GetUIElementType, which in these classes + /// is "mov eax, imm32; ret" (gmToolbarUI 0x004BE480, gmFloatyToolbarUI 0x004D01D0). 0 otherwise. + /// + internal static int TypeOf(IntPtr inst) + { + if (!ClientObjectHooks.IsReadablePointer(inst)) return 0; + IntPtr vtable = Marshal.ReadIntPtr(inst); + if (!ClientObjectHooks.IsReadableSpan(vtable, VtGetUIElementType + 4)) return 0; + IntPtr fn = Marshal.ReadIntPtr(vtable, VtGetUIElementType); + if (!ClientObjectHooks.IsReadableSpan(fn, 6)) return 0; + if (Marshal.ReadByte(fn) != 0xB8 || Marshal.ReadByte(fn, 5) != 0xC3) return 0; + return Marshal.ReadInt32(fn, 1); + } + + /// + /// The toolbar to hide: the floaty window around it when there is one (a few levels up at + /// most), else the toolbar itself. Inside a floaty window the toolbar is never hidden (AC opens + /// and closes the window, not its content); one found hidden there (an earlier build hid it) is + /// shown again, so the window is whole whenever it shows. + /// + private static void CaptureWithWrapper(IntPtr inst, string via) + { + if (TypeOf(inst) == ToolbarType) NoteInner(inst); + IntPtr p = inst; + for (int d = 0; d < 4; d++) + { + if (!ClientObjectHooks.IsReadableSpan(p, ParentOffset + 4)) break; + p = Marshal.ReadIntPtr(p, ParentOffset); + if (p == IntPtr.Zero) break; + if (TypeOf(p) != FloatyToolbarType) continue; + Capture(p, via + " (its floaty window)"); + ShowInner(inst); + return; + } + Capture(inst, via); + } + + /// The toolbar inside a floaty window: visible again if its own flag is off. Main thread. + private static void ShowInner(IntPtr inner) + { + IntPtr setVisible = _uiElementSetVisibleAddress; + if (setVisible == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(inner, RegionFlagsOffset + 4) || IsOwnVisible(inner)) return; + if (!IsSetVisibleSlot(Marshal.ReadIntPtr(inner))) return; + try { ((delegate* unmanaged[Thiscall])setVisible)(inner, 1); } + catch { /* best-effort */ } + RynthLog.Compat($"RetailToolbarHooks: showed the toolbar 0x{inner.ToInt32():X8} inside its floaty window again (visible={IsOwnVisible(inner)})."); + } + + private static void Reject(IntPtr inst, string why) + { + if (++_rejectLogs <= 8) + RynthLog.Compat($"RetailToolbarHooks: not capturing 0x{inst.ToInt32():X8}: {why}."); + } + + /// + /// The vtable's SetVisible slot must be UIElement::SetVisible itself, or a one-instruction + /// "jmp rel32" thunk to it (incremental-link thunks, as the floaty classes have). + /// + private static bool IsSetVisibleSlot(IntPtr vtable) + { + IntPtr setVisible = _uiElementSetVisibleAddress; + if (setVisible == IntPtr.Zero) return false; + if (!ClientObjectHooks.IsReadableSpan(vtable, SetVisibleVtableSlot + 4)) return false; + IntPtr fn = Marshal.ReadIntPtr(vtable, SetVisibleVtableSlot); + if (fn == setVisible) return true; + if (!ClientObjectHooks.IsReadableSpan(fn, 5)) return false; + if (Marshal.ReadByte(fn) != 0xE9) return false; + int rel = Marshal.ReadInt32(fn, 1); + return unchecked(fn.ToInt32() + 5 + rel) == setVisible.ToInt32(); + } + + // ── Per-frame visibility (EndSceneHook, AC's main thread) ───────────────── + + public static void TickHide() + { + if (!_hookInstalled) return; + if (!LoginLifecycleHooks.HasObservedLoginComplete) return; + if (_logoffInProgress) return; + if (!MainThreadGuard.IsOnMainThread()) return; + IntPtr setVisible = _uiElementSetVisibleAddress; + if (setVisible == IntPtr.Zero) return; + + FollowSettingFile(); + bool hide = _hide; + if (!hide && _unhidePending) + { + _unhidePending = false; + bool fallback = _unhideFallback; + _unhideFallback = false; + try + { + if (CountCaptured() == 0) SearchTree(); + Unhide(setVisible, fallback); + } + catch (Exception ex) { RynthLog.Compat($"RetailToolbarHooks: showing the toolbar again threw {ex.GetType().Name}: {ex.Message}"); } + return; + } + if (hide) + { + long now = Environment.TickCount64; + if (now >= _nextSearchMs) + { + _nextSearchMs = now + (CountCaptured() == 0 ? 2000 : 20000); + try { SearchTree(); } + catch (Exception ex) { if (++_rejectLogs <= 8) RynthLog.Compat($"RetailToolbarHooks: tree search threw {ex.GetType().Name}: {ex.Message}"); } + } + } + for (int i = 0; i < Slots.Length; i++) + { + IntPtr inst = Slots[i].Instance; + if (inst == IntPtr.Zero) continue; + if (!StillAlive(Slots[i])) + { + RynthLog.Compat($"RetailToolbarHooks: toolbar element 0x{inst.ToInt32():X8} is gone (freed); dropped until it is captured again."); + Slots[i] = default; + continue; + } + + bool visible = IsOwnVisible(inst); + if (hide) + { + // Only the one AC is showing; its hidden twin (docked vs floaty) stays AC's business. + if (visible) + { + try { ((delegate* unmanaged[Thiscall])setVisible)(inst, 0); } + catch { /* best-effort */ } + if (!Slots[i].HiddenByUs && ++_hideLogs <= 8) + RynthLog.Compat($"RetailToolbarHooks: hid toolbar element 0x{inst.ToInt32():X8} (now visible={IsOwnVisible(inst)})."); + Slots[i].HiddenByUs = true; + NoteHiddenByUs(inst); + } + } + else if (Slots[i].HiddenByUs) + { + if (!visible) + { + try { ((delegate* unmanaged[Thiscall])setVisible)(inst, 1); } + catch { /* best-effort */ } + } + Slots[i].HiddenByUs = false; + } + } + } + + private static bool IsOwnVisible(IntPtr inst) => + (Marshal.ReadInt32(inst, RegionFlagsOffset) & RegionVisibleBit) != 0; + + // ── Finding the toolbar without waiting ─────────────────────────────────── + // + // After a reload in the world nothing may select anything or press a key for a long time + // (a bot fighting: combat is selection-free), so the detours alone could leave the panel up. + // TickHide then looks for it in AC's UI tree, by memory reads only (no calls into AC): from + // an element the engine already holds (the chat, the radar) up to the top, then through every + // descendant for the toolbar's Use button (element 0x1000019D); the toolbar is the ancestor + // that keeps that button at +0x60C (gmToolbarUI::PostInit stores it there). Both twins are + // found that way. Layout (UIElement::GetParentconst, GetChildconst, GetRootElement): + // +0xAC parent; +0x120 child count, +0x124 the first child's list node + 8 (node +0x08 the + // next node + 8, node +0x10 the child); +0x2E4 the element id; +0x554 bit 21 a root. + + private const int ParentOffset = 0xAC, ChildCountOffset = 0x120, ChildHeadOffset = 0x124, + ElementIdOffset = 0x2E4, RootFlagsOffset = 0x554, RootFlagBit = 1 << 21, UseButtonFieldOffset = 0x60C; + private const int UseButtonId = 0x1000019D; + private const int MaxVisited = 60_000, MaxDepth = 48; + private static long _nextSearchMs; + + // The UI manager (UiElementHooks.Manager, `this` of its per-frame tooltip detour): +0x9C the + // root; +0x14 an array of +0x1C elements that UIElementManager::GetElement (0x00459A00) scans + // by id: the top-level windows, the floaty ones (each its own root) among them. + private const int MgrRoot = 0x9C, MgrElements = 0x14, MgrElementCount = 0x1C, MaxRegistered = 200_000; + private static int _searchLogs; + + private static void SearchTree() + { + // One page query per page for the whole search (AC isn't running: EndScene, main thread). + using var probeScope = MemoryProbe.BeginWalk(); + int before = CountCaptured(), buttons = 0, registered = -1, visited = 0, nRoots = 0; + + // First the manager's element array: every Use button in it, whichever window holds it. + IntPtr mgr = UiElementHooks.Manager; + if (mgr != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(mgr, MgrRoot + 4)) + { + int count = Marshal.ReadInt32(mgr, MgrElementCount); + IntPtr arr = Marshal.ReadIntPtr(mgr, MgrElements); + if (count > 0 && count <= MaxRegistered && ClientObjectHooks.IsReadableSpan(arr, count * IntPtr.Size)) + { + registered = count; + for (int i = 0; i < count; i++) + { + IntPtr e = Marshal.ReadIntPtr(arr, i * IntPtr.Size); + if (e == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(e, ElementIdOffset + 4)) continue; + if (Marshal.ReadInt32(e, ElementIdOffset) != UseButtonId) continue; + buttons++; + CaptureOwnerOf(e); + } + } + } + + // Then, if that found none, the UI tree from the roots the engine can reach. + if (buttons == 0) + { + Span roots = stackalloc IntPtr[8]; + void AddRoot(IntPtr e, Span list, ref int n) + { + IntPtr top = TopOf(e); + if (top == IntPtr.Zero || n >= list.Length) return; + for (int i = 0; i < n; i++) if (list[i] == top) return; + list[n++] = top; + } + if (mgr != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(mgr, MgrRoot + 4)) + AddRoot(Marshal.ReadIntPtr(mgr, MgrRoot), roots, ref nRoots); + AddRoot(ChatHooks.GmMainChatInstance, roots, ref nRoots); + AddRoot(RadarHooks.GmRadarUIInstance, roots, ref nRoots); + for (int i = 0; i < nRoots; i++) Walk(roots[i], 0, ref visited); + } + + if (++_searchLogs <= 4 || CountCaptured() != before) + RynthLog.Compat($"RetailToolbarHooks: search: manager {(mgr == IntPtr.Zero ? "not seen" : "seen")}, {registered} registered element(s), " + + $"{buttons} Use button(s); tree {nRoots} root(s), {visited} element(s); {CountCaptured()} toolbar element(s) held."); + } + + /// The element's root (or its topmost readable ancestor); zero when it can't be read. + private static IntPtr TopOf(IntPtr e) + { + for (int depth = 0; depth < MaxDepth && e != IntPtr.Zero; depth++) + { + if (!ClientObjectHooks.IsReadableSpan(e, RootFlagsOffset + 4)) return IntPtr.Zero; + if ((Marshal.ReadInt32(e, RootFlagsOffset) & RootFlagBit) != 0) return e; + IntPtr parent = Marshal.ReadIntPtr(e, ParentOffset); + if (parent == IntPtr.Zero) return e; + e = parent; + } + return IntPtr.Zero; + } + + private static void Walk(IntPtr e, int depth, ref int visited) + { + if (depth > MaxDepth || ++visited > MaxVisited) return; + if (!ClientObjectHooks.IsReadableSpan(e, ElementIdOffset + 4)) return; + if (Marshal.ReadInt32(e, ElementIdOffset) == UseButtonId) CaptureOwnerOf(e); + if (Marshal.ReadInt32(e, ChildCountOffset) == 0) return; + IntPtr head = Marshal.ReadIntPtr(e, ChildHeadOffset); + IntPtr node = head == IntPtr.Zero ? IntPtr.Zero : head - 8; + for (int n = 0; node != IntPtr.Zero && n < MaxVisited; n++) + { + if (!ClientObjectHooks.IsReadableSpan(node, 0x14)) return; + IntPtr child = Marshal.ReadIntPtr(node, 0x10); + if (child != IntPtr.Zero) Walk(child, depth + 1, ref visited); + if (visited > MaxVisited) return; + IntPtr next = Marshal.ReadIntPtr(node, 8); + node = next == IntPtr.Zero ? IntPtr.Zero : next - 8; + } + } + + /// The Use button's toolbar: the ancestor holding it at +0x60C (a few levels up at most). + private static void CaptureOwnerOf(IntPtr button) + { + if (!ClientObjectHooks.IsReadableSpan(button, ParentOffset + 4)) return; + IntPtr a = Marshal.ReadIntPtr(button, ParentOffset); + for (int d = 0; d < 8 && a != IntPtr.Zero; d++) + { + if (!ClientObjectHooks.IsReadableSpan(a, UseButtonFieldOffset + 4)) return; + if (Marshal.ReadIntPtr(a, UseButtonFieldOffset) == button) + { + NoteInner(a); + CaptureWithWrapper(a, "the UI tree"); // held either way: hidden, or shown again (Unhide) + return; + } + a = Marshal.ReadIntPtr(a, ParentOffset); + } + } + + // ── The toolbar with the shortcut slots (AcShortcuts) ───────────────────── + // + // The gmToolbarUI that owns the Use button also owns the 18 shortcut slots' item lists + // (+0x634, count +0x63C): AcShortcuts calls its UseShortcut / AddShortcut / + // RemoveShortcutInSlotNum, so a slot used or changed from RynthCore goes exactly the way + // the retail toolbar's own do (the server, the player's shortcut list, the retail slots). + // Found the same way (the element registry), whether the retail toolbar is hidden or not. + + private static IntPtr _inner, _innerVtable; + private static long _nextInnerSearchMs; + + private static void NoteInner(IntPtr toolbar) + { + if (!ClientObjectHooks.IsReadablePointer(toolbar)) return; + if (_inner != toolbar && ++_captureLogs <= 8) + RynthLog.Compat($"RetailToolbarHooks: the shortcut toolbar is 0x{toolbar.ToInt32():X8}."); + _inner = toolbar; + _innerVtable = Marshal.ReadIntPtr(toolbar); + } + + /// + /// The gmToolbarUI holding the shortcut slots, or zero (not in the world, not found yet: + /// it is looked for at most every 2 s). AC's main thread. + /// + public static IntPtr ShortcutToolbar() + { + if (!MainThreadGuard.IsOnMainThread() || !LoginLifecycleHooks.HasObservedLoginComplete || _logoffInProgress) + return IntPtr.Zero; + IntPtr t = _inner; + if (t != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(t, 0x640) && Marshal.ReadIntPtr(t) == _innerVtable) + return t; + _inner = IntPtr.Zero; + long now = Environment.TickCount64; + if (now < _nextInnerSearchMs) return IntPtr.Zero; + _nextInnerSearchMs = now + 2000; + try { SearchTree(); } + catch { return IntPtr.Zero; } + return _inner; + } + + /// Still readable and still starting with the vtable it had when captured (see RetailVitalsHooks). + private static bool StillAlive(in Slot s) + { + if (s.Instance == IntPtr.Zero) return false; + if (!ClientObjectHooks.IsReadableSpan(s.Instance, RegionFlagsOffset + 4)) return false; + return Marshal.ReadIntPtr(s.Instance) == s.Vtable; + } + + private static int CountCaptured() + { + int n = 0; + for (int i = 0; i < Slots.Length; i++) + if (Slots[i].Instance != IntPtr.Zero) n++; + return n; + } + + /// + /// /rc ui retailtoolbar status: into the log, each held toolbar's parents up to the root and its + /// direct children (id, own visible flag, vtable, child count). AC's main thread. + /// + public static void LogStructure() + { + if (!MainThreadGuard.IsOnMainThread()) return; + using var probeScope = MemoryProbe.BeginWalk(); + for (int s = 0; s < Slots.Length; s++) + { + IntPtr inst = Slots[s].Instance; + if (inst == IntPtr.Zero || !StillAlive(Slots[s])) continue; + var line = new System.Text.StringBuilder($"RetailToolbarHooks: toolbar 0x{inst.ToInt32():X8} parents:"); + IntPtr e = inst; + for (int d = 0; d < 12 && e != IntPtr.Zero; d++) + { + if (!ClientObjectHooks.IsReadableSpan(e, RootFlagsOffset + 4)) break; + line.Append($" [0x{e.ToInt32():X8} id=0x{Marshal.ReadInt32(e, ElementIdOffset):X8} vis={IsOwnVisible(e)} vt=0x{Marshal.ReadInt32(e):X8} kids={Marshal.ReadInt32(e, ChildCountOffset)}{((Marshal.ReadInt32(e, RootFlagsOffset) & RootFlagBit) != 0 ? " root" : "")}]"); + e = Marshal.ReadIntPtr(e, ParentOffset); + } + RynthLog.Compat(line.ToString()); + var kids = new System.Text.StringBuilder($"RetailToolbarHooks: toolbar 0x{inst.ToInt32():X8} children:"); + IntPtr head = Marshal.ReadIntPtr(inst, ChildHeadOffset); + IntPtr node = head == IntPtr.Zero ? IntPtr.Zero : head - 8; + for (int n = 0; node != IntPtr.Zero && n < 64; n++) + { + if (!ClientObjectHooks.IsReadableSpan(node, 0x14)) break; + IntPtr child = Marshal.ReadIntPtr(node, 0x10); + if (child != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(child, RootFlagsOffset + 4)) + kids.Append($" [id=0x{Marshal.ReadInt32(child, ElementIdOffset):X8} vis={IsOwnVisible(child)} kids={Marshal.ReadInt32(child, ChildCountOffset)}]"); + IntPtr next = Marshal.ReadIntPtr(node, 8); + node = next == IntPtr.Zero ? IntPtr.Zero : next - 8; + } + RynthLog.Compat(kids.ToString()); + } + } + + /// One line for /rc ui retailtoolbar. + public static string Describe() + { + int hidden = 0; + for (int i = 0; i < Slots.Length; i++) + if (Slots[i].Instance != IntPtr.Zero && Slots[i].HiddenByUs) hidden++; + string state = !_hookInstalled + ? $"not available ({_statusMessage})" + : CountCaptured() == 0 + ? "the toolbar isn't found yet (it is looked for every 2 s while this is on)" + : $"{CountCaptured()} toolbar element(s) found, {hidden} hidden by RynthCore"; + return $"Hide retail toolbar is {(HideRetailToolbar ? "ON" : "OFF")} - {state}. Its shortcut keys keep working."; + } + + // ── Logout / relog ──────────────────────────────────────────────────────── + + /// A logoff was requested (LogoffOriginProbe): drop the elements now, before AC frees them. + public static void OnLogoffRequested() + { + _logoffInProgress = true; + for (int i = 0; i < Slots.Length; i++) Slots[i] = default; + _inner = IntPtr.Zero; + } + + /// The logout completed (PluginManager's logout dispatch): the next login builds new ones. + public static void ResetCachedInstance() + { + for (int i = 0; i < Slots.Length; i++) Slots[i] = default; + _logoffInProgress = false; + _nextSearchMs = 0; + _inner = IntPtr.Zero; + _nextInnerSearchMs = 0; + } +} diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 1afac02..126b105 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -27,6 +27,9 @@ namespace RynthCore.Engine.Compatibility; /// /rc ui retailvitals [on|off|status] — hide AC's own /// health/stamina/mana bars (; saved for the /// PC, also in Settings > UI). Alone it reports the state. +/// /rc ui retailtoolbar [on|off|status] — hide AC's toolbar panel and +/// its shortcut slots (; the shortcut keys keep +/// working; saved for the PC, also in Settings > UI). /// /rc ui barsize [0-10|+|-|status] - the RynthCore bar's size (its own text /// size step, ; saved for the PC, also in Settings > /// Display). Alone it reports the size. @@ -493,6 +496,111 @@ internal static class RynthCoreChatCommands } return true; } + // /rc settings [tab] : the Settings panel (toggled), or opened on a tab ("/rc settings buffing"). + // A plugin's own window links to a tab this way (RynthAi's dashboard: the Buffing key's + // right-click), as it can't reach the engine's panel otherwise. 2026-10-21. + // /rc shortcuts [use N]: the player's 18 AC shortcut slots and their keys (AcShortcuts, + // AcKeymap), or use slot N the way its key does. 2026-10-22, for checking the item bar's base. + if (IsVerb(sub, "shortcuts", out string shortcutArgs)) + { + string[] sa = shortcutArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (sa.Length >= 2 && sa[0].Equals("use", StringComparison.OrdinalIgnoreCase) && int.TryParse(sa[1], out int useSlot)) + { + Reply(AcShortcuts.Enqueue(AcShortcuts.Op.Use, useSlot - 1, 0) + ? $"Using shortcut {useSlot}." : $"Shortcut {useSlot} can't be used ({AcShortcuts.Status})"); + return true; + } + // /rc shortcuts set N: the selected item into slot N; clear N: empty it (the retail toolbar's way). + if (sa.Length >= 2 && sa[0].Equals("set", StringComparison.OrdinalIgnoreCase) && int.TryParse(sa[1], out int setSlot)) + { + uint sel = sa.Length >= 3 && uint.TryParse(sa[2].Replace("0x", "", StringComparison.OrdinalIgnoreCase), + System.Globalization.NumberStyles.HexNumber, null, out uint given) ? given : ClientHelperHooks.GetSelectedItemId(); + Reply(sel == 0 ? "Select the item first." + : AcShortcuts.Enqueue(AcShortcuts.Op.Set, setSlot - 1, sel) ? $"Shortcut {setSlot}: 0x{sel:X8}." : $"Shortcut {setSlot} can't be set ({AcShortcuts.Status})"); + return true; + } + if (sa.Length >= 2 && sa[0].Equals("clear", StringComparison.OrdinalIgnoreCase) && int.TryParse(sa[1], out int clearSlot)) + { + Reply(AcShortcuts.Enqueue(AcShortcuts.Op.Clear, clearSlot - 1, 0) + ? $"Shortcut {clearSlot} emptied." : $"Shortcut {clearSlot} can't be emptied ({AcShortcuts.Status})"); + return true; + } + AcShortcuts.Slot[] slots = AcShortcuts.Slots; + if (slots.Length == 0) { Reply("No shortcut slots read yet (in the world? " + AcShortcuts.Status + ")"); return true; } + Reply($"Shortcuts (keymap {System.IO.Path.GetFileName(AcKeymap.FilePath)}):"); + for (int i = 0; i < slots.Length; i++) + { + uint id = slots[i].ObjectId; + string what = id == 0 ? "-" : ClientObjectHooks.TryGetSnapshotName(id, out string n) && n.Length > 0 ? n : $"0x{id:X8}"; + string keys = AcKeymap.KeysText($"UseQuickSlot_{i + 1}"); + Reply($" {i + 1,2}: {what}{(keys.Length > 0 ? " [" + keys + "]" : "")}"); + } + return true; + } + + // /rc keymap [check|bind|unbind | reload]: AC's keys, changed so every client follows + // (AcKeymapLive). is a keymap action (UseQuickSlot_5) or a quoted-free /command. 2026-10-22. + if (IsVerb(sub, "keymap", out string keymapArgs)) + { + string[] ka = keymapArgs.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries); + string verb = ka.Length > 0 ? ka[0].ToLowerInvariant() : ""; + if (verb is "check" or "bind" or "unbind" && ka.Length == 3) + { + // The key is the last word; the action is everything between (a command has spaces). + int last = ka[2].LastIndexOf(' '); + string action = last < 0 ? ka[1] : ka[1] + " " + ka[2][..last]; + string key = last < 0 ? ka[2] : ka[2][(last + 1)..]; + if (verb == "check") + { + int r = AcKeymapLive.Check(action, key, out string msg); + Reply(r == 0 ? $"{key} is free for {action}." : msg); + } + else if (!AcKeymapLive.Enqueue(action, key, verb == "bind" ? AcKeymapLive.Op.Bind : AcKeymapLive.Op.Unbind, out string why)) + Reply(why); + return true; + } + if (verb == "dump") + { + AcKeymapLive.RequestDump(System.IO.Path.Combine(System.IO.Path.GetTempPath(), "rynthcore-keymap-memory.keymap")); + return true; + } + Reply($"Keymap {AcKeymap.FilePath} - {AcKeymapLive.Status} Usage: /rc keymap check|bind|unbind | dump, e.g. /rc keymap bind UseQuickSlot_10 F11"); + return true; + } + + // /rc panels [open|close|toggle ]: AC's own panels (AcPanels): their ids, classes and which are open. + if (IsVerb(sub, "panels", out string acPanelArgs)) + { + string[] pa = acPanelArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (pa.Length == 2 && uint.TryParse(pa[1].Replace("0x", "", StringComparison.OrdinalIgnoreCase), + pa[1].StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? System.Globalization.NumberStyles.HexNumber : System.Globalization.NumberStyles.Integer, + null, out uint panelId)) + { + AcPanels.Op op = pa[0].ToLowerInvariant() switch { "open" => AcPanels.Op.Open, "close" => AcPanels.Op.Close, _ => AcPanels.Op.Toggle }; + if (!AcPanels.Enqueue(panelId, op)) Reply("Can't: " + AcPanels.Status); + return true; + } + var panels = AcPanels.List(names: true); + Reply($"AC panels ({panels.Count}; {AcPanels.Status}):"); + foreach (var p in panels) + Reply($" {p.Id,3} {p.Class}{(p.Open ? " - open" : "")}"); + return true; + } + + if (IsVerb(sub, "settings", out string settingsArgs)) + { + string settingsTitle = ImGuiBackend.Panels.SettingsFace.Title; + if (!ImGuiBackend.ImGuiPanelHost.HasFace(settingsTitle)) + Reply("The Settings panel isn't available (the ImGui layer is off?)."); + else if (settingsArgs.Length == 0) + UI.PanelRouter.Toggle(settingsTitle); + else + { + ImGuiBackend.Panels.SettingsFace.RequestTab(settingsArgs); + if (!ImGuiBackend.ImGuiPanelHost.IsOpen(settingsTitle)) UI.PanelRouter.Toggle(settingsTitle); + } + return true; + } if (IsVerb(sub, "hotkey", out hotkeyArgs) || IsVerb(sub, "hotkeys", out hotkeyArgs)) { try @@ -627,6 +735,22 @@ internal static class RynthCoreChatCommands return; } + // /rc ui retailtoolbar [on|off]: hide AC's toolbar panel and its shortcut slots + // (RetailToolbarHooks). Alone it reports; anything but on/off toggles. + if (parts[0].Equals("retailtoolbar", StringComparison.OrdinalIgnoreCase)) + { + if (parts.Length >= 2 && parts[1].Equals("status", StringComparison.OrdinalIgnoreCase)) + { + try { RetailToolbarHooks.LogStructure(); } catch { } + Reply(RetailToolbarHooks.Describe()); + return; + } + if (parts.Length >= 2) + RetailToolbarHooks.HideRetailToolbar = Flag(parts[1], RetailToolbarHooks.HideRetailToolbar); + Reply(RetailToolbarHooks.Describe()); + return; + } + // /rc ui barsize [0-10|+|-|status]: the bar's size. Alone it reports it. if (parts[0].Equals("barsize", StringComparison.OrdinalIgnoreCase)) { @@ -696,6 +820,13 @@ internal static class RynthCoreChatCommands return; } + // /rc ui channels: the chat's channels drawer opens or closes, as its button does (tests, keys). + if (parts[0].Equals("channels", StringComparison.OrdinalIgnoreCase)) + { + ImGuiBackend.Panels.ChatFace.ToggleChannelsRequested = true; + return; + } + // /rc ui open|close|popout|redock|snap : drive a panel by name (tests, // dispatch.txt). Names may have spaces ("Monster Detail"). string verb = parts[0].ToLowerInvariant(); @@ -733,7 +864,7 @@ internal static class RynthCoreChatCommands return; } - Reply("Usage: /rc ui list | /rc ui open|close|popout|redock|snap | /rc ui retailvitals [on|off] | /rc ui barsize [0-10|+|-|status] | /rc ui barrows [1-6|+|-] | /rc ui baricons [2-30|none|+|-]"); + Reply("Usage: /rc ui list | /rc ui open|close|popout|redock|snap | /rc ui retailvitals [on|off] | /rc ui retailtoolbar [on|off] | /rc ui barsize [0-10|+|-|status] | /rc ui barrows [1-6|+|-] | /rc ui baricons [2-30|none|+|-]"); } /// diff --git a/src/RynthCore.Engine/Compatibility/UiFlowHooks.cs b/src/RynthCore.Engine/Compatibility/UiFlowHooks.cs index ffebc1f..9ffc5ff 100644 --- a/src/RynthCore.Engine/Compatibility/UiFlowHooks.cs +++ b/src/RynthCore.Engine/Compatibility/UiFlowHooks.cs @@ -278,6 +278,10 @@ internal static unsafe class UiFlowHooks try { RadarHooks.ResetCachedInstance(); } catch { } try { PowerbarHooks.ResetCachedInstance(); } catch { } try { RetailVitalsHooks.ResetCachedInstance(); } catch { } + try { RetailToolbarHooks.ResetCachedInstance(); } catch { } + try { AcShortcuts.Reset(); } catch { } + try { AcKeymapLive.Reset(); } catch { } + try { AcPanels.Reset(); } catch { } try { UiElementHooks.OnScreenLeaving(); } catch { } } diff --git a/src/RynthCore.Engine/D3D9/EndSceneHook.cs b/src/RynthCore.Engine/D3D9/EndSceneHook.cs index 67f3620..b2aca30 100644 --- a/src/RynthCore.Engine/D3D9/EndSceneHook.cs +++ b/src/RynthCore.Engine/D3D9/EndSceneHook.cs @@ -343,6 +343,8 @@ internal static class EndSceneHook try { PowerbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ } // Per-frame retail health/stamina/mana bars visibility ("Hide retail vitals"). try { RetailVitalsHooks.TickHide(); } catch { /* never let this bring down EndScene */ } + // Per-frame retail toolbar + shortcut bar visibility ("Hide retail toolbar"). + try { RetailToolbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ } } if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0) diff --git a/src/RynthCore.Engine/Hotkeys/HotkeyService.cs b/src/RynthCore.Engine/Hotkeys/HotkeyService.cs index 253697e..3ffb5bd 100644 --- a/src/RynthCore.Engine/Hotkeys/HotkeyService.cs +++ b/src/RynthCore.Engine/Hotkeys/HotkeyService.cs @@ -160,6 +160,9 @@ internal static class HotkeyService return true; } + /// All the bindings at once (AcKeymapLive: a key taken for a shortcut slot comes off the others). + public static void SetAll(List bindings) => Commit(Current with { Bindings = new List(bindings) }); + public static bool RemoveAt(int index) { List list = Copy(); diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 21de28a..c2ab966 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -789,6 +789,8 @@ internal static class EngineFrameController if (ImGuiBar.Visible) ImGuiBar.Draw(_uiScale); ImGuiPanelHost.DrawAll(_uiScale); + // Settings drawer bodies RynthAi's window didn't draw this frame let their sources go. + Panels.SettingsDrawerBodies.EndFrame(); ImGuiBar.SyncPopOut(_uiScale); } if (ImGuiFontTest.Enabled) diff --git a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs index 85cc710..3a43440 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs @@ -16,6 +16,11 @@ // of the atlas's input data for three glyphs (2026-10-15). DX9Backend frees the // input data once the texture is uploaded (ClearInputData). // +// Narrow labels (2026-10-21): Barlow Semi Condensed SemiBold and Bold (OFL, +// Assets/Fonts, embedded like Phosphor) at 9/10/11 and bold 11/13, for plugin +// windows (GetUiFont Narrow*: the instrument dashboard's caps labels). They +// get the icons but never Segoe UI Symbol (nothing draws those three with them). +// // Icons: the Phosphor icon font (MIT, Assets/Fonts/Phosphor.ttf, embedded in // this assembly) is merged into every baked font, the scaled sets included, // at the web font's code points (U+E000 up), so an icon is text @@ -54,6 +59,8 @@ internal enum UiFont // Scaled-up nameplate text and big combat numbers: picked by Sharp() so text is // shrunk from a bigger bake, never stretched from a smaller one. Ui18, NumBold48, + // Narrow labels for plugin windows (Barlow Semi Condensed SemiBold, then Bold). + Narrow9, Narrow10, Narrow11, NarrowBold11, NarrowBold13, Count, } @@ -75,9 +82,11 @@ internal static unsafe class ImGuiFonts 0x25CF, // ● (Meta source: unapplied edits) }; - private static byte[]? _segoe, _segoeBold, _consolas, _cascadia, _symbol, _phosphor; + private static byte[]? _segoe, _segoeBold, _consolas, _cascadia, _symbol, _phosphor, _narrow, _narrowBold; private const string PhosphorResource = "RynthCore.Engine.Assets.Fonts.Phosphor.ttf"; + private const string NarrowResource = "RynthCore.Engine.Assets.Fonts.BarlowSemiCondensed-SemiBold.ttf"; + private const string NarrowBoldResource = "RynthCore.Engine.Assets.Fonts.BarlowSemiCondensed-Bold.ttf"; // Icon size relative to the text's em, capped at the line height (x0.95) for // fonts whose em fills the line (Consolas): bigger icons climb out of the line. private const float IconScale = 1.2f, IconMaxOfLine = 0.95f; @@ -140,7 +149,7 @@ internal static unsafe class ImGuiFonts } // Native copies of the font files and glyph ranges, made once: rebuilds reuse them. - private static IntPtr _nSegoe, _nSegoeBold, _nMono, _nCode, _nSymbol, _nPhosphor; + private static IntPtr _nSegoe, _nSegoeBold, _nMono, _nCode, _nSymbol, _nPhosphor, _nNarrow, _nNarrowBold; private static ushort* _mainRanges, _symbolRanges, _iconRanges; /// Reads the font files. Engine init worker thread; safe to skip (Build reads them itself). @@ -152,7 +161,9 @@ internal static unsafe class ImGuiFonts _consolas = TryRead("consola.ttf"); _cascadia = TryRead("CascadiaMono.ttf"); _symbol = TryRead("seguisym.ttf"); - _phosphor = TryReadResource(PhosphorResource); + _phosphor = TryReadResource(PhosphorResource, "icons will not draw"); + _narrow = TryReadResource(NarrowResource, "plugin windows' narrow labels use their fallback"); + _narrowBold = TryReadResource(NarrowBoldResource, "plugin windows' narrow labels use their fallback"); _preloaded = true; } @@ -217,7 +228,9 @@ internal static unsafe class ImGuiFonts double ms = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency; RynthLog.UI($"ImGuiFonts: {CountBaked()} fonts queued at scale {scale:0.##} in {ms:0.0} ms " + - $"(Cascadia Mono {(_cascadia != null ? "found" : "missing, using Consolas")}, symbols from the main fonts{(_symbolMerges > 0 ? $" (Segoe UI Symbol merged into {_symbolMerges})" : "")}, " + + $"(Cascadia Mono {(_cascadia != null ? "found" : "missing, using Consolas")}, " + + $"Barlow {(_narrow != null && _narrowBold != null ? "embedded" : "missing")}, " + + $"symbols from the main fonts{(_symbolMerges > 0 ? $" (Segoe UI Symbol merged into {_symbolMerges})" : "")}, " + $"icons {(_phosphor != null ? $"{IconCount()} merged" : "missing")})."); Compatibility.MemoryUse.Mark("ImGui fonts queued"); } @@ -234,6 +247,7 @@ internal static unsafe class ImGuiFonts _iconRanges = PinRanges(IconRanges()); _nSegoe = ToNative(_segoe); _nSegoeBold = ToNative(_segoeBold); _nMono = ToNative(mono); _nCode = ToNative(code); _nSymbol = ToNative(_symbol); _nPhosphor = ToNative(_phosphor); + _nNarrow = ToNative(_narrow); _nNarrowBold = ToNative(_narrowBold); } /// @@ -251,11 +265,12 @@ internal static unsafe class ImGuiFonts ushort* symbolRanges = _symbolRanges; ushort* iconRanges = _iconRanges; IntPtr segoe = _nSegoe, segoeBold = _nSegoeBold, consolas = _nMono, codeFont = _nCode, symbol = _nSymbol, - phosphor = _nPhosphor; + phosphor = _nPhosphor, narrow = _nNarrow, narrowBold = _nNarrowBold; // Each base font's em and cap height, to size and place the icons merged into it. FaceMetrics mSegoe = FaceMetrics.Read(_segoe), mSegoeBold = FaceMetrics.Read(_segoeBold), - mMono = FaceMetrics.Read(mono), mCode = FaceMetrics.Read(code); + mMono = FaceMetrics.Read(mono), mCode = FaceMetrics.Read(code), + mNarrow = FaceMetrics.Read(_narrow), mNarrowBold = FaceMetrics.Read(_narrowBold); ImFontPtr[] target = baseSet; float factor = 1f; @@ -270,7 +285,8 @@ internal static unsafe class ImGuiFonts return need; } - void Add(UiFont id, IntPtr data, byte[]? bytes, FaceMetrics metrics, float px) + // symbols: false for the narrow label faces (no ≤ ≥ ● drawn with them; Segoe UI Symbol is 2.4 MB per merge). + void Add(UiFont id, IntPtr data, byte[]? bytes, FaceMetrics metrics, float px, bool symbols = true) { if (data == IntPtr.Zero || bytes == null) return; float size = MathF.Round(px * scale * factor); @@ -279,7 +295,7 @@ internal static unsafe class ImGuiFonts { cfg.FontDataOwnedByAtlas = false; target[(int)id] = atlas.AddFontFromMemoryTTF(data, bytes.Length, size, cfg, (IntPtr)mainRanges); - if (symbol != IntPtr.Zero && _symbol != null && NeedsSymbol(bytes)) + if (symbols && symbol != IntPtr.Zero && _symbol != null && NeedsSymbol(bytes)) { _symbolMerges++; cfg.MergeMode = true; @@ -327,6 +343,17 @@ internal static unsafe class ImGuiFonts Add(UiFont.NumBold48, segoeBold, _segoeBold, mSegoeBold, 48); for (int i = 0; i < 6; i++) Add(UiFont.Chat8 + i, consolas, mono, mMono, 8 + i * 2); + AddNarrow(); + + // The narrow label faces (plugin windows), in the base set and in each scaled one. + void AddNarrow() + { + Add(UiFont.Narrow9, narrow, _narrow, mNarrow, 9, symbols: false); + Add(UiFont.Narrow10, narrow, _narrow, mNarrow, 10, symbols: false); + Add(UiFont.Narrow11, narrow, _narrow, mNarrow, 11, symbols: false); + Add(UiFont.NarrowBold11, narrowBold, _narrowBold, mNarrowBold, 11, symbols: false); + Add(UiFont.NarrowBold13, narrowBold, _narrowBold, mNarrowBold, 13, symbols: false); + } // Bigger copies for each panel text size in use (chat keeps its own size setting). foreach (int step in steps) @@ -347,6 +374,10 @@ internal static unsafe class ImGuiFonts Add(UiFont.Dash10, codeFont, code, mCode, 10); Add(UiFont.Dash11, codeFont, code, mCode, 11); Add(UiFont.Dash14, codeFont, code, mCode, 14); + // Plugin windows draw their icons from Ui18's (GetUiFont Ui18: about 16 px icons at + // normal size), so it grows with the panel's text size too, and stays sharp. + Add(UiFont.Ui18, segoe, _segoe, mSegoe, 18); + AddNarrow(); scaled[step] = target; } } @@ -514,7 +545,7 @@ internal static unsafe class ImGuiFonts Array.Clear(Fonts); ScaledFonts.Clear(); _mainRanges = _symbolRanges = _iconRanges = null; - _nSegoe = _nSegoeBold = _nMono = _nCode = _nSymbol = _nPhosphor = IntPtr.Zero; + _nSegoe = _nSegoeBold = _nMono = _nCode = _nSymbol = _nPhosphor = _nNarrow = _nNarrowBold = IntPtr.Zero; } private static int CountBaked() @@ -668,15 +699,15 @@ internal static unsafe class ImGuiFonts return (IntPtr)p; } - /// A font embedded in this assembly (the Phosphor icons); null when missing. - private static byte[]? TryReadResource(string name) + /// A font embedded in this assembly (the Phosphor icons, the narrow labels); null when missing. + private static byte[]? TryReadResource(string name, string whenMissing) { try { using Stream? stream = typeof(ImGuiFonts).Assembly.GetManifestResourceStream(name); if (stream == null) { - RynthLog.UI($"ImGuiFonts: embedded font {name} missing; icons will not draw."); + RynthLog.UI($"ImGuiFonts: embedded font {name} missing; {whenMissing}."); return null; } var bytes = new byte[stream.Length]; diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index 55af0e9..cb14807 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -36,6 +36,9 @@ using RynthCore.Engine.UI; namespace RynthCore.Engine.ImGuiBackend; +/// Where a panel first opens when nothing is saved for it (v90 plugin windows' "corner"). +internal enum PanelCorner { None, TopLeft, TopRight, BottomLeft, BottomRight, Top, Bottom } + internal enum PanelChrome { /// DRAG + title + pop-out + close header, resize grip. @@ -77,7 +80,15 @@ internal sealed record PanelSpec( bool OpenCentered = false, // No resize grip, docked or popped out: the face sizes itself (the RynthNav arrow // fits its height to what it shows). Chromeless and GripInBody panels only. - bool NoResize = false); + bool NoResize = false, + // The grip over the body's corner shows only while the mouse is near it (or resizing): + // a frameless plugin window's corner is its own content (RynthAi's footer clock). + bool GripOnHover = false, + // With nothing saved: open in this corner of the game view (a plugin window's "corner", v90). + PanelCorner OpenCorner = PanelCorner.None, + // The panel draws its own content at any size (a plugin window's "scale": "draw", v90): Ctrl+wheel + // steps its draw size (PanelDrawScale, 30-250%) instead of its text size. + bool DrawScale = false); /// An ImGui panel face. One instance per open; dropped on close. internal interface IImGuiPanel @@ -590,6 +601,51 @@ internal static class ImGuiPanelHost } DrawPanel(entry, uiScale, placeScale, null); } + DrawSizeNote(); + } + + // ── One way to resize every panel (Tom 2026-10-23) ─────────────────── + // + // Ctrl+wheel anywhere over a panel - engine panel, plugin window, framed or frameless, docked + // or popped out - makes that panel one step bigger or smaller; each panel keeps its own size. + // A panel that draws its own content at any size (a plugin window with "scale": "draw") steps + // its draw size 10% (30-250%, PanelDrawScale); the others their text size (100-250%, + // PanelTextScale). The wheel is used up, so the panel doesn't also scroll. A face that has its + // own Ctrl+wheel inside it (the Mini Remote's boxes) clears the wheel first and keeps it. + // A note by the cursor says the new size for a moment. + + private static string _sizeNote = string.Empty; + private static long _sizeNoteUntilMs; + + private static void StepSizeWithWheel(Entry entry) + { + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + if (!io.KeyCtrl || io.MouseWheel == 0f) return; + if (!ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem)) return; + int dir = io.MouseWheel > 0f ? 1 : -1; + io.MouseWheel = 0f; + int pct; + if (entry.Spec.DrawScale) + { + int now = PanelDrawScale.Get(entry.Title); + if (now == 0) now = (int)MathF.Round(PanelTextScale.Factor(PanelTextScale.Get(entry.Title)) * 10f) * 10; + pct = Math.Clamp(now + dir * PanelDrawScale.Step, PanelDrawScale.Min, PanelDrawScale.Max); + PanelDrawScale.Set(entry.Title, pct); + } + else + { + int step = Math.Clamp(PanelTextScale.Get(entry.Title) + dir, 0, PanelTextScale.SizeNames.Length - 1); + PanelTextScale.SetForWindow(entry.Title, step); + pct = (int)MathF.Round(PanelTextScale.Factor(step) * 100f); + } + _sizeNote = $"{entry.Title}: {pct.ToString(System.Globalization.CultureInfo.InvariantCulture)}%"; + _sizeNoteUntilMs = Environment.TickCount64 + 1200; + } + + private static void DrawSizeNote() + { + if (_sizeNote.Length == 0 || Environment.TickCount64 > _sizeNoteUntilMs) return; + ImGuiNET.ImGui.SetTooltip(_sizeNote + " (Ctrl+wheel)"); } private static bool HiddenWhileDocked(Entry entry) @@ -781,6 +837,10 @@ internal static class ImGuiPanelHost { pos = defaultPos; // the face's own first spot (a script window's FirstUseEver position) } + else if (entry.Spec.OpenCorner != PanelCorner.None && CornerLogicalPos(entry.Spec.OpenCorner, size, placeScale) is Vector2 corner) + { + pos = corner; + } else if (entry.Spec.OpenCentered && CenteredLogicalPos(size, placeScale) is Vector2 centered) { pos = centered; @@ -904,6 +964,19 @@ internal static class ImGuiPanelHost return Vector2.Max(Vector2.Zero, (display / placeScale - size) * 0.5f); } + /// A corner of the game view, 8 units in from its edges (logical units). + private static Vector2? CornerLogicalPos(PanelCorner corner, Vector2 size, float placeScale) + { + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + if (display.X <= 1 || display.Y <= 1 || placeScale <= 0) return null; + Vector2 view = display / placeScale; + const float m = 8f; + float x = corner is PanelCorner.TopRight or PanelCorner.BottomRight ? view.X - size.X - m + : corner is PanelCorner.Top or PanelCorner.Bottom ? (view.X - size.X) * 0.5f : m; + float y = corner is PanelCorner.BottomLeft or PanelCorner.BottomRight or PanelCorner.Bottom ? view.Y - size.Y - m : m; + return Vector2.Max(Vector2.Zero, new Vector2(x, y)); + } + private static Vector2 ClampToDisplay(Vector2 pos, Vector2 size) { Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; @@ -1098,7 +1171,8 @@ internal static class ImGuiPanelHost } // Grip painted on top of the face when the body covers the corner // (a GripInBody face's even while it lets clicks through: its slot stays). - if ((manualGrip || inlineGrip || (popped && !standard)) && gripRoom == 0f) + if ((manualGrip || inlineGrip || (popped && !standard)) && gripRoom == 0f + && (!spec.GripOnHover || gHot || NearGrip(gMin, gSize))) GripPaint(entry, uiScale, gMin, gHot, ImGuiNET.ImGui.GetWindowDrawList()); entry.BodyScrolls = ImGuiNET.ImGui.GetScrollMaxY() > 0f; } @@ -1115,6 +1189,8 @@ internal static class ImGuiPanelHost DrawGrip(entry, uiScale, minSize); if (resizing) _pendingDragDelta = Vector2.Zero; // the face's window-drag doesn't also move it + StepSizeWithWheel(entry); + // A drag started from the panel's own surface (DragWindowWithLastItem). if (popped) _pendingDragDelta = Vector2.Zero; if (_pendingDragDelta != Vector2.Zero) @@ -1405,17 +1481,7 @@ internal static class ImGuiPanelHost } ImGuiNET.ImGui.PopStyleVar(); - // Ctrl+wheel anywhere on the title bar steps this window's size. Only the - // header: the body's wheel belongs to the face (lists, chat, radar zoom). - // Popped out, the drag band is the window's own caption and never reaches - // ImGui, so there it works over the buttons. - ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); - if (!gone && io.KeyCtrl && io.MouseWheel != 0f - && ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) - && ImGuiNET.ImGui.IsMouseHoveringRect(winPos, winPos + new Vector2(width, h), false)) - { - PanelTextScale.SetForWindow(entry.Title, step + (io.MouseWheel > 0f ? 1 : -1)); - } + // Ctrl+wheel anywhere over the panel steps its size (StepSizeWithWheel, for every panel). // Under the header, right-aligned to the button: never over a pop-out's drag band. ImGuiNET.ImGui.SetNextWindowPos(winPos + new Vector2(tsX + btn, h), ImGuiCond.Appearing, new Vector2(1, 0)); @@ -1537,6 +1603,10 @@ internal static class ImGuiPanelHost /// The resize grip at the bottom-right (16 px, teal, rounded outer corner). private static float GripSize(Entry entry, float s) => (entry.Spec.GoldGrip ? 14f : 16f) * s; + /// The mouse within a grip's width of the grip (PanelSpec.GripOnHover shows it then). + private static bool NearGrip(Vector2 gMin, float gSize) => + ImGuiNET.ImGui.IsMouseHoveringRect(gMin - new Vector2(gSize, gSize), gMin + new Vector2(2 * gSize, 2 * gSize), false); + /// Top-left of the grip for a corner (bottom-right point). private static Vector2 GripMin(Entry entry, float s, Vector2 corner) { diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index 80b3f63..a6d4113 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -58,6 +58,9 @@ internal sealed class ChatFace : IImGuiPanel private readonly DashboardDrawers _drawers; private bool _openTabsPopup; + /// /rc ui channels: the channels drawer opens or closes on the next draw, as its button does. + public static volatile bool ToggleChannelsRequested; + public ChatFace() { _channels = new ChannelsDrawer(this); @@ -1101,6 +1104,12 @@ internal sealed class ChatFace : IImGuiPanel private void DrawPopups() { + if (ToggleChannelsRequested) + { + ToggleChannelsRequested = false; + if (ImGuiPopOuts.InPopOutFrame) _openTabsPopup = true; + else _drawers.Toggle(_channels); + } if (_openSettings) { _openSettings = false; diff --git a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicDashboard.cs b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicDashboard.cs index f3a4dd0..c0439d1 100644 --- a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicDashboard.cs +++ b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicDashboard.cs @@ -201,12 +201,7 @@ internal sealed class ClassicDashboard ImGuiPanelHost.DragWindowWithLastItem(); SafeImGui.SetItemTooltip("Drag to move. Right-click: size. Ctrl+wheel: bigger or smaller."); if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) ImGuiNET.ImGui.OpenPopup(SizePopupId); - if (ImGuiNET.ImGui.IsItemHovered()) - { - ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); - if (io.KeyCtrl && io.MouseWheel != 0f) - PanelTextScale.SetForWindow(RynthAiFace.Title, PanelTextScale.Get(RynthAiFace.Title) + (io.MouseWheel > 0f ? 1 : -1)); - } + // Ctrl+wheel: the panel host steps its size (over any panel). // "RynthAi" in gold, then the profile and what the bot is doing. float tx = o.X + Px(10); diff --git a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicTuningTab.cs b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicTuningTab.cs index 7079baf..18b94e2 100644 --- a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicTuningTab.cs +++ b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicTuningTab.cs @@ -204,7 +204,7 @@ internal sealed class ClassicTuningTab : IClassicTab case SettingKind.Int: case SettingKind.Float: case SettingKind.Double: return NumberRow(row, w); - case SettingKind.Combo when row.Items is { Length: > 0 }: ComboRow(ctx, row, w); return false; + case SettingKind.Combo when row.CurrentItems.Length > 0: ComboRow(ctx, row, w); return false; default: // The special rows (buttons, hotkeys, colours, server picker, status): the Settings panel's drawing. _rows.DrawRow(row, w); @@ -296,7 +296,7 @@ internal sealed class ClassicTuningTab : IClassicTab private void ComboRow(ClassicContext ctx, SettingRow row, float w) { RynthAiSettings data = _rows.Data; - string[] items = row.Items!; + string[] items = row.CurrentItems; int cur = row.Get != null ? Math.Clamp((int)Math.Round(row.Get(data)), 0, items.Length - 1) : 0; Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); float rh = Px(22), ddW = Math.Min(Px(170), w * 0.55f); diff --git a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs index cb83e5a..d9a2679 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs @@ -373,7 +373,10 @@ internal sealed partial class MiniRemoteFace : IImGuiPanel if (ready && io.KeyCtrl && io.MouseWheel != 0 && ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGuiNET.ImGui.IsMouseHoveringRect(start, start + new Vector2(w, shownH))) + { ResizeSlots(io.MouseWheel > 0 ? SlotSizeStep : -SlotSizeStep); + io.MouseWheel = 0f; // the boxes took it: not the panel's size too + } if (clicked >= 0 && ready) Click(data, items, clicked); else if (clicked >= 0) ShowMessage(ItemHudStore.Loaded ? "Waiting for your character..." : "Loading...", Amber); diff --git a/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs b/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs index 2ff9954..6bab36d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs @@ -11,6 +11,10 @@ // (ImGuiStackGuard): whatever the plugin left open (colours, style vars, fonts, // IDs, groups, child windows, tables...) is ended and popped there, so the // panels drawn after it start clean; logged once per window, then counted. +// A "fitHeight" window (v90) takes the height the plugin's draw asks for +// (wantHeight) as its minimum and is fitted to it whenever it changes and the +// mouse is up (a frameless window's empty rows would still catch clicks meant +// for the game); a text size change scales its width along with its fonts. // docs/PLUGIN_WINDOWS.md. AC's render thread. // ============================================================================ @@ -18,6 +22,7 @@ using System; using System.Numerics; using System.Text; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI; using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; namespace RynthCore.Engine.ImGuiBackend.Panels; @@ -32,20 +37,37 @@ internal sealed class PluginWindowFace : IImGuiPanel private long _failedAtMs = -1; private const long RetryMs = 5000; - public PluginWindowFace(string plugin, string surface, string title) + // "fitHeight" (v90): the content height the plugin asked for (logical units; 0 = not known + // yet), and the text size factor and width (logical) the window was last fitted at. + private readonly bool _fitHeight; + private readonly float _minWidth; + private float _contentHeight, _fitK, _fitWidth; + + public PluginWindowFace(string plugin, string surface, string title, bool fitHeight = false, float minWidth = 0f) { _plugin = plugin; _title = title; _surface = Encoding.UTF8.GetBytes(surface + "\0"); _idScope = "##pw_" + surface; + _fitHeight = fitHeight; + _minWidth = minWidth; } + /// A fitHeight window's minimum: its minimum width at its text size, and the content's height. + public Vector2? MinSize => _fitHeight && _contentHeight > 0f + ? new Vector2(_minWidth * TextFactor(), _contentHeight) + : null; + + /// The panel's text size factor at the size its fonts are baked for. + private float TextFactor() => PanelTextScale.Factor(ImGuiFonts.BakedStepNear(PanelTextScale.Get(_title))); + public void Draw() { Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); Vector2 avail = ImGuiNET.ImGui.GetContentRegionAvail(); long now = Environment.TickCount64; int result = PluginManager.EmbedFailed; + Vector2 want = Vector2.Zero; if (_failedAtMs < 0 || now - _failedAtMs >= RetryMs) { // Two stack records: the body's base (where a recovery goes back to: the panel host @@ -57,7 +79,7 @@ internal sealed class PluginWindowFace : IImGuiPanel ImGuiNET.ImGui.PushID(_idScope); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); ImGuiStackGuard.Mark given = guarded ? ImGuiStackGuard.Take() : default; - try { result = PluginManager.RenderEmbed(_plugin, _surface, avail, out _); } + try { result = PluginManager.RenderEmbed(_plugin, _surface, avail, out want); } finally { ImGuiStackGuard.Mark after = default; @@ -78,7 +100,11 @@ internal sealed class PluginWindowFace : IImGuiPanel else if (result == PluginManager.EmbedDrawn) _failedAtMs = -1; else if (_failedAtMs >= 0) { _failedAtMs = now; result = PluginManager.EmbedFailed; } // still off since the throw } - if (result == PluginManager.EmbedDrawn) return; + if (result == PluginManager.EmbedDrawn) + { + if (_fitHeight) Fit(want.Y, avail.X); + return; + } ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(6, 6)); Label(result switch @@ -89,6 +115,39 @@ internal sealed class PluginWindowFace : IImGuiPanel }, Mute); } + /// + /// fitHeight: keeps the window as tall as the content the plugin drew (, + /// client px) and scales its width with a text size change. Docked only (popped out, the OS window + /// is the player's to size); never while the mouse is down, so a drag or a resize isn't fought. + /// + private void Fit(float wantPx, float widthPx) + { + if (wantPx <= 0f || ImGuiPopOuts.InPopOutFrame) return; + float place = Math.Max(0.01f, ImGuiPanelHost.PlacementScale()); + float height = MathF.Ceiling(wantPx / place); + float width = widthPx / place; + float k = PanelTextScale.Factor(ImGuiFonts.CurrentStep); + float shownHeight = ImGuiNET.ImGui.GetWindowHeight() / place; + bool mouseUp = !ImGuiNET.ImGui.IsMouseDown(ImGuiNET.ImGuiMouseButton.Left); + _contentHeight = height; + if (_fitK > 0f && MathF.Abs(k - _fitK) > 0.001f) + { + // A text size change: the width from the one it had at the old size. + width = MathF.Max(_fitWidth * (k / _fitK), _minWidth * k); + 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. + ImGuiPanelHost.RequestPos(_title, ImGuiNET.ImGui.GetWindowPos() / place); + } + else if (mouseUp && MathF.Abs(shownHeight - height) > 0.5f) + { + ImGuiPanelHost.RequestSize(_title, new Vector2(width, height)); + } + _fitK = k; + _fitWidth = width; + } + // Unbalanced draws by plugin + surface: logged the first time, then every RepeatEvery-th. private static readonly System.Collections.Generic.Dictionary Unbalanced = new(StringComparer.Ordinal); private const int RepeatEvery = 1000; diff --git a/src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs b/src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs index f7c1467..deaff4d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs +++ b/src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs @@ -78,16 +78,34 @@ internal sealed class QuickSettingsDrawer : RynthAiDrawer ImGuiNET.ImGui.OpenPopup(AddPopupId); } ImGuiNET.ImGui.SetItemTooltip("Pin or unpin settings"); + DrawBody(x, y, w, MathF.Max(1, origin.Y + panelH - Pad * k - y), k, openPicker: false); + } + + /// + /// The pinned rows at (, ) in a x + /// child that scrolls (RynthAi's own dashboard window draws the frame and the + /// + button: opens the pin list at the mouse, SettingsDrawerBodies). + /// Returns the rows' height (pixels). + /// + public float DrawBody(float x, float y, float w, float h, float k, bool openPicker) + { + if (openPicker) + { + _filter = string.Empty; + ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos() + new Vector2(0, 8 * k), ImGuiCond.Always, new Vector2(1, 0)); + ImGuiNET.ImGui.OpenPopup(AddPopupId); + } AddPopup(k); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); - Vector2 size = new(w, MathF.Max(1, origin.Y + panelH - Pad * k - y)); + Vector2 size = new(w, MathF.Max(1, h)); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); bool open = ImGuiNET.ImGui.BeginChild("##quick_body", size, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground); ImGuiNET.ImGui.PopStyleVar(); + float contentH = EmptyH * k; try { - if (!open) return; + if (!open) return contentH; _rows.Sync(); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 0)); @@ -116,6 +134,8 @@ internal sealed class QuickSettingsDrawer : RynthAiDrawer ImGuiNET.ImGui.PopTextWrapPos(); ImGuiNET.ImGui.PopStyleColor(); } + // What the rows took (unscrolled), for a host that fits its height to them. + contentH = ImGuiNET.ImGui.GetCursorPosY() + 2 * k; // content space: the scroll is in it } finally { @@ -124,6 +144,7 @@ internal sealed class QuickSettingsDrawer : RynthAiDrawer } } finally { ImGuiNET.ImGui.EndChild(); } + return contentH; } /// A pinned row's right-click, after Remove: Move up / Move down. diff --git a/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs index 4bb448b..db464e4 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs @@ -158,10 +158,18 @@ internal sealed class RangesSlideOut : RynthAiDrawer public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) { - var dl = ImGuiNET.ImGui.GetWindowDrawList(); // Title row: ruler + RANGES (yards) | close. float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.Ruler, "RANGES", "yards", "Hide the ranges"); - float x = origin.X + Pad * k, w = panelW - 2 * Pad * k; + DrawBody(origin.X + Pad * k, y, panelW - 2 * Pad * k, k); + } + + /// The body's height under the title row (pixels): RynthAi's own dashboard window draws the frame (SettingsDrawerBodies). + public static float BodyHeight(float k) => (3 * LineH + 6 + 3 + Math.Max(1, Rows.Length) * (RowH + RowGap)) * k; + + /// The selected monster and the range rows at (, ), wide. + public void DrawBody(float x, float y, float w, float k) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10); MonsterBlock(dl, x, y, w, k); diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs index d87de76..7b3e19a 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs @@ -100,8 +100,14 @@ internal sealed partial class RynthAiFace } } - /// The Dungeon Patrol settings, hazard cells and saved routes (the Patrol launcher's right-click). - private sealed class PatrolDrawer : RynthAiDrawer + /// The size factor the static helpers (Px) draw at, for a drawer body drawn outside the face (SettingsDrawerBodies). + internal static void UseScale(float k) => _k = k; + + /// + /// The Dungeon Patrol settings, hazard cells and saved routes (the Patrol launcher's right-click). + /// Internal: RynthAi's own dashboard window shows its body too (SettingsDrawerBodies). + /// + internal sealed class PatrolDrawer : RynthAiDrawer { private bool _sub; // Settings > Navigation > Dungeon Patrol, drawn here too (2026-10-14). @@ -147,13 +153,24 @@ internal sealed partial class RynthAiFace { float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.Footprints, "PATROL & ROUTES", null, "Hide the patrol drawer"); float x = origin.X + Pad * k; + DrawBody(x, y, panelW - 2 * Pad * k, MathF.Max(1, origin.Y + panelH - Pad * k - y), k); + } + + /// + /// Start patrol, the settings and the lists in a x child at + /// (, ) that scrolls. Returns what they took (pixels), for a + /// host that fits its height to them (RynthAi's own dashboard window, SettingsDrawerBodies). + /// + public float DrawBody(float x, float y, float w, float h, float k) + { // A scrolling child for the lists. A child window is clipped to its parent's clip rect, // so the host's slide clip covers it too. ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); - Vector2 size = new(panelW - 2 * Pad * k, MathF.Max(1, origin.Y + panelH - Pad * k - y)); + Vector2 size = new(w, MathF.Max(1, h)); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); bool open = ImGuiNET.ImGui.BeginChild("##patrol_body", size, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground); ImGuiNET.ImGui.PopStyleVar(); + float contentH = 200 * k; try { if (open) @@ -165,7 +182,7 @@ internal sealed partial class RynthAiFace // The settings, with the Settings panel's rows (right-click one to pin it to My settings). Section("SETTINGS"); _rows.Sync(); - float w = ImGuiNET.ImGui.GetContentRegionAvail().X - 2 * k; + float rw = ImGuiNET.ImGui.GetContentRegionAvail().X - 2 * k; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 0)); SettingRow[] rows = SettingRows; @@ -173,7 +190,7 @@ internal sealed partial class RynthAiFace { if (!rows[i].IsVisible(_rows.Data)) continue; ImGuiNET.ImGui.PushID(i); - _rows.DrawRow(rows[i], w); + _rows.DrawRow(rows[i], rw); ImGuiNET.ImGui.PopID(); } ImGuiNET.ImGui.PopStyleVar(); @@ -181,9 +198,11 @@ internal sealed partial class RynthAiFace PatrolInfo info = UiSources.Patrol.Current?.Value ?? new PatrolInfo(); PatrolBody(info, withTitle: false); + contentH = ImGuiNET.ImGui.GetCursorPosY() + 2 * k; // content space: the scroll is in it } } finally { ImGuiNET.ImGui.EndChild(); } + return contentH; } } diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs index 88abd44..f0720c0 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -410,9 +410,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) && ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x0, y), new Vector2(x0 + width, y + rowH), false)) { - ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); - if (io.KeyCtrl && io.MouseWheel != 0f) - PanelTextScale.SetForWindow(Title, PanelTextScale.Get(Title) + (io.MouseWheel > 0f ? 1 : -1)); + // Ctrl+wheel: the panel host steps its size (over any panel). if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) ImGuiNET.ImGui.OpenPopup(SizePopupId); } diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsDrawerBodies.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsDrawerBodies.cs new file mode 100644 index 0000000..da50111 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsDrawerBodies.cs @@ -0,0 +1,112 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/SettingsDrawerBodies.cs +// The dashboard drawers that show Settings rows, drawn into RynthAi's own +// dashboard window (2026-10-21, plugin API v90 RenderSettingsDrawer). RynthAi +// draws its dashboard itself now, its drawers' tabs and frames included, but +// three drawers show the Settings panel's rows, and the Settings panel is still +// RynthCore's: until it moves to RynthAi, RynthAi's drawer windows ask for +// these bodies here (the frame and the title row are RynthAi's): +// ranges the selected monster and the key ranges (RangesSlideOut.cs) +// patrol Start patrol, the Dungeon Patrol settings, this dungeon's hazard +// cells, the recorded hazards and the saved routes (the Patrol +// drawer, RynthAiFace.Drawers.cs) +// pinned My settings, the rows the player pinned (QuickSettingsDrawer.cs) +// Each is the same drawer the engine's own dashboard shows, so a value changed +// here is saved the same way and a pin made here is the same pin. A drawer +// that wasn't drawn in a frame drops its hub subscriptions (EndFrame). +// +// AC thread only (inside RynthAi's window, and EndFrame after the panels). +// ============================================================================ + +using System; +using System.Numerics; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class SettingsDrawerBodies +{ + private static RangesSlideOut? _ranges; + private static RynthAiFace.PatrolDrawer? _patrol; + private static QuickSettingsDrawer? _pinned; + + // The frame each was last drawn in (EndFrame counts frames). + private static long _frame, _rangesDrawn = -1, _patrolDrawn = -1, _pinnedDrawn = -1; + + /// + /// Draws 's body at the cursor, pixels wide, in at most + /// pixels of height (0: as tall as it wants); : + /// open My settings' list of settings to pin. Returns the height it wants (pixels), or -1 for a key + /// that isn't one of these. + /// + public static float Draw(string key, float width, float room, bool openPicker) + { + Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos(); + float w = MathF.Max(1, width); + float k = MathF.Max(1f, ImGuiFonts.Get(UiFont.Dash11).FontSize / 11f); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash10)); + try + { + switch (key) + { + case "ranges": + { + _ranges ??= new RangesSlideOut(); + _rangesDrawn = _frame; + _ranges.Update(true); + float h = RangesSlideOut.BodyHeight(k); + ImGuiNET.ImGui.PushID("##sdb_ranges"); + try { _ranges.DrawBody(at.X, at.Y, w, k); } + finally { ImGuiNET.ImGui.PopID(); } + ImGuiNET.ImGui.SetCursorScreenPos(at); + ImGuiNET.ImGui.Dummy(new Vector2(w, h)); + return h; + } + case "patrol": + { + _patrol ??= new RynthAiFace.PatrolDrawer(); + _patrolDrawn = _frame; + _patrol.Update(true); + RynthAiFace.UseScale(k); + float h = room > 0 ? room : 400 * k; + float want; + ImGuiNET.ImGui.PushID("##sdb_patrol"); + try { want = _patrol.DrawBody(at.X, at.Y, w, h, k); } + finally { ImGuiNET.ImGui.PopID(); } + ImGuiNET.ImGui.SetCursorScreenPos(at); + ImGuiNET.ImGui.Dummy(new Vector2(w, h)); + return want; + } + case "pinned": + { + _pinned ??= new QuickSettingsDrawer(); + _pinnedDrawn = _frame; + _pinned.Update(true); + float h = room > 0 ? room : 120 * k; + float want; + ImGuiNET.ImGui.PushID("##sdb_pinned"); + try { want = _pinned.DrawBody(at.X, at.Y, w, h, k, openPicker); } + finally { ImGuiNET.ImGui.PopID(); } + ImGuiNET.ImGui.SetCursorScreenPos(at); + ImGuiNET.ImGui.Dummy(new Vector2(w, h)); + return want; + } + default: + return -1f; + } + } + finally + { + ImGuiNET.ImGui.PopFont(); + } + } + + /// After the panels each frame: a body that wasn't drawn this frame lets its hub sources go. + public static void EndFrame() + { + if (_ranges != null && _rangesDrawn != _frame) _ranges.Update(false); + if (_patrol != null && _patrolDrawn != _frame) _patrol.Update(false); + if (_pinned != null && _pinnedDrawn != _frame) _pinned.Update(false); + _frame++; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs index 2469e20..6f2ad5e 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs @@ -416,7 +416,8 @@ internal sealed class SettingsRows private void ComboRow(SettingRow row, float w) { var dl = ImGuiNET.ImGui.GetWindowDrawList(); - string[] items = row.Items!; + string[] items = row.CurrentItems; + if (items.Length == 0) return; int current = Math.Clamp((int)row.Get!(_data), 0, items.Length - 1); ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); diff --git a/src/RynthCore.Engine/ImGui/PhosphorIcons.cs b/src/RynthCore.Engine/ImGui/PhosphorIcons.cs index f8369b7..f2ee3bfd4 100644 --- a/src/RynthCore.Engine/ImGui/PhosphorIcons.cs +++ b/src/RynthCore.Engine/ImGui/PhosphorIcons.cs @@ -172,7 +172,8 @@ internal static unsafe class PhosphorIcons + Binoculars + Crown + Sun + CastleTurret + ClockCounterClockwise + GlobeHemisphereWest + Path + Star + Target + User + TextAa + Leaf + Keyboard - + PushPin + SlidersHorizontal + Wrench; + + PushPin + SlidersHorizontal + Wrench + + Scroll; /// /// Draws (one icon) centred in the box at diff --git a/src/RynthCore.Engine/ImGui/RynthTheme.cs b/src/RynthCore.Engine/ImGui/RynthTheme.cs index 9711112..043a21f 100644 --- a/src/RynthCore.Engine/ImGui/RynthTheme.cs +++ b/src/RynthCore.Engine/ImGui/RynthTheme.cs @@ -7,7 +7,8 @@ // // Colour themes (Tom 2026-10-14): the structural colours come from a palette // the player can change in Settings > Display: a preset (RynthCore, Ember, -// Verdant, Amethyst, Crimson, Slate) or their own eight colours (accent, +// 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). // The other shades (selected rows, fields, hover, the dashboard's border...) // are worked out from those eight; the RynthCore preset keeps every original @@ -15,8 +16,9 @@ // toggles, radar gold) don't follow the theme. The faces read the tokens // (properties) every frame, so a change shows at once; the base ImGui style // is re-coloured before the next frame (RefreshStyle, each ImGui context). -// Saved to %AppData%\RynthCore\theme.txt (preset=, then name=AARRGGBB for a -// custom palette's eight colours). +// Saved to %AppData%\RynthCore\theme.txt (preset=, then name=AARRGGBB for the +// player's own eight colours, kept whichever theme is in use since 2026-10-22); +// the schemes a player saved are in ThemeSchemes.cs. // // Apply() sets the base style once at context creation; per-window colours // (bar, RynthAi, Radar) are pushed around Begin by the panel host. @@ -45,6 +47,10 @@ internal sealed class ThemePalette public uint AccentFill, AccentAlt, BoxBg, Field, Selected, WindowBorder, DashBorder, PanelGlass, BarBg, FrameBg, FrameHover, FrameActive, BarButtonBorder, RowAlt, MuteAlt, StyleText, PopupBg, FrameBgHover, FrameBgActive, SliderGrab; + // The instrument look's shades (2026-10-21, plugin windows: UiColorToken KeyFace..Faint), worked + // out from the eight for every palette, Default included (DeriveInstrument). + public uint KeyFace, Hairline, Inset, Faint; + /// A copy (its own array of the eight). public ThemePalette Clone() { @@ -55,6 +61,7 @@ internal sealed class ThemePalette FrameHover = FrameHover, FrameActive = FrameActive, BarButtonBorder = BarButtonBorder, RowAlt = RowAlt, MuteAlt = MuteAlt, StyleText = StyleText, PopupBg = PopupBg, FrameBgHover = FrameBgHover, FrameBgActive = FrameBgActive, SliderGrab = SliderGrab, + KeyFace = KeyFace, Hairline = Hairline, Inset = Inset, Faint = Faint, }; Array.Copy(P, c.P, Primaries); return c; @@ -71,6 +78,7 @@ internal sealed class ThemePalette t.BarBg = 0xFF0A0A14; t.FrameBg = 0xFF1A2230; t.FrameHover = 0xFF2A3850; t.FrameActive = 0xFF34466A; t.BarButtonBorder = 0xFF3A4A5A; t.RowAlt = 0xFF101822; t.MuteAlt = 0xFFC8D6E4; t.StyleText = 0xFFE6E6E6; t.PopupBg = 0xFF14141E; t.FrameBgHover = 0xFF243044; t.FrameBgActive = 0xFF2C3A52; t.SliderGrab = 0xFF26A18C; + t.DeriveInstrument(); return t; } @@ -107,6 +115,20 @@ internal sealed class ThemePalette FrameBgHover = Mix(FrameBg, FrameHover, 0.50f); FrameBgActive = Mix(FrameHover, FrameActive, 0.50f); SliderGrab = Mix(AccentAlt, bg, 0.17f); + DeriveInstrument(); + } + + /// + /// The instrument look's shades from the eight: a key's face (a step up from the background), + /// the hairlines, the inset wells (the activity line, bar tracks) and the faint text. + /// + public void DeriveInstrument() + { + uint bg = P[2], button = P[4], border = P[5], muted = P[7]; + KeyFace = Mix(bg, button, 0.60f); + Hairline = Mix(bg, border, 0.45f); + Inset = Mix(bg, 0xFF000000, 0.45f); + Faint = Mix(muted, bg, 0.28f); } /// #AARRGGBB mix: of the way from to , opaque. @@ -120,7 +142,10 @@ internal sealed class ThemePalette } // ── Presets ───────────────────────────────────────────────────────── - public static readonly string[] PresetNames = { "RynthCore", "Ember", "Verdant", "Amethyst", "Crimson", "Slate" }; + // Brass, Volt and Ivory (2026-10-21): the instrument dashboard's three, from its Claude Design + // canvas. Their Buttons and Borders are chosen so DeriveInstrument lands on the canvas's key + // face and hairline; appended, so the older presets keep their places in the picker. + public static readonly string[] PresetNames = { "RynthCore", "Ember", "Verdant", "Amethyst", "Crimson", "Slate", "Brass", "Volt", "Ivory" }; public static ThemePalette Preset(int index) => index switch { @@ -129,6 +154,9 @@ internal sealed class ThemePalette 3 => From(0xB98CFF, 0xFFC857, 0x0F0A16, 0x1C1428, 0x2A1C40, 0x5A4A8A, 0xF6F2FC, 0xCBBEDC), 4 => From(0xFF5C6C, 0xFFC857, 0x140A0C, 0x241216, 0x3A161E, 0x7A3442, 0xFCF2F3, 0xD8B8BE), 5 => From(0xD0D8E0, 0xF0C060, 0x0E0F11, 0x1A1C20, 0x24282E, 0x4A5260, 0xF4F5F7, 0xB4BAC2), + 6 => From(0xE3B662, 0x85C7B2, 0x12100D, 0x1C1915, 0x26221E, 0x595349, 0xEEE9DC, 0xB0A89B), + 7 => From(0xCBF559, 0xF7B245, 0x0E1115, 0x161A1F, 0x1F2329, 0x4C5661, 0xEDF0F4, 0xA7ADB5), + 8 => From(0xFCF7E7, 0xF7B245, 0x100F0E, 0x191918, 0x222322, 0x535451, 0xF1EEE6, 0xABA9A5), _ => Default(), }; @@ -157,7 +185,8 @@ internal static class RynthTheme { public uint Accent, Highlight, Background, TitleBar, Button, Border, Text, TextMuted, AccentFill, AccentAlt, BoxBg, Field, Selected, WindowBorder, DashBorder, PanelGlass, BarBg, FrameBg, - FrameHover, FrameActive, BarButtonBorder, RowAlt, MuteAlt, StyleText, PopupBg, FrameBgHover, FrameBgActive, SliderGrab; + FrameHover, FrameActive, BarButtonBorder, RowAlt, MuteAlt, StyleText, PopupBg, FrameBgHover, FrameBgActive, SliderGrab, + KeyFace, Hairline, Inset, Faint; public Tokens(ThemePalette p) { @@ -169,6 +198,7 @@ internal static class RynthTheme FrameActive = Argb(p.FrameActive); BarButtonBorder = Argb(p.BarButtonBorder); RowAlt = Argb(p.RowAlt); MuteAlt = Argb(p.MuteAlt); StyleText = Argb(p.StyleText); PopupBg = Argb(p.PopupBg); FrameBgHover = Argb(p.FrameBgHover); FrameBgActive = Argb(p.FrameBgActive); SliderGrab = Argb(p.SliderGrab); + KeyFace = Argb(p.KeyFace); Hairline = Argb(p.Hairline); Inset = Argb(p.Inset); Faint = Argb(p.Faint); } } @@ -206,6 +236,11 @@ internal static class RynthTheme public static uint BarButtonBorder => _t.BarButtonBorder; public static uint RowAlt => _t.RowAlt; public static uint MuteAlt => _t.MuteAlt; + // ...and the instrument look's (plugin windows, UiColorToken KeyFace..Faint): + public static uint KeyFace => _t.KeyFace; + public static uint Hairline => _t.Hairline; + public static uint Inset => _t.Inset; + public static uint Faint => _t.Faint; // ── Bar (AvaloniaOverlay.cs BuildRoot) ───────────────────────────── public static uint BarBackground => WithAlpha(_t.BarBg, 0xE6); @@ -243,30 +278,74 @@ internal static class RynthTheme public static readonly uint RadarGripHover = Argb(0xA00A121A); // ── Choosing a theme (Settings > Display) ─────────────────────────── + // + // 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): + // a preset RynthCore, Ember ... Brass, Volt, Ivory (ThemePalette.PresetNames) + // a saved scheme a named set of the eight the player saved (ThemeSchemes, themes\*.theme) + // Custom the player's own eight colours. Kept whichever theme is in use and always + // written to theme.txt, so picking Custom again brings them back. + // Changing a colour makes the theme Custom with that change; when the player's own colours would + // be replaced that way (the change was made on a preset or a scheme) and aren't kept anywhere + // else, they are saved as a scheme first ("My colours"), so no click loses them. - /// The preset in use (ThemePalette.PresetNames index), or Custom. + public const int Scheme = -2; + private static ThemePalette _custom = ThemePalette.Default(); // the player's own eight (Custom) + private static bool _customSet; // theme.txt had them, or the player made them + private static string _scheme = string.Empty; // the saved scheme in use (Scheme) + + /// The preset in use (ThemePalette.PresetNames index), Scheme, or Custom. public static int Preset { get { EnsureLoaded(); return _preset; } } - /// Settings' Theme picker: the presets, then "Custom" while the player's own colours are in use. - public static readonly string[] PickerNames = BuildPickerNames(); - public static int PickerIndex => Preset == Custom ? PickerNames.Length - 1 : Preset; + /// The saved scheme in use ("" unless is Scheme). + public static string SchemeName { get { EnsureLoaded(); lock (Sync) return _preset == Scheme ? _scheme : string.Empty; } } - private static string[] BuildPickerNames() + public static bool SchemeInUse => Preset == Scheme; + + /// Settings' Theme picker now: the presets, the saved schemes, then Custom. + public static string[] PickerNames() { - var names = new string[ThemePalette.PresetNames.Length + 1]; + string[] schemes = ThemeSchemes.Names; + var names = new string[ThemePalette.PresetNames.Length + schemes.Length + 1]; Array.Copy(ThemePalette.PresetNames, names, ThemePalette.PresetNames.Length); + Array.Copy(schemes, 0, names, ThemePalette.PresetNames.Length, schemes.Length); names[^1] = "Custom"; return names; } - /// Uses preset (the picker's last item, Custom, keeps the colours as they are). + public static int PickerIndex + { + get + { + int p = Preset; + string[] schemes = ThemeSchemes.Names; + if (p >= 0) return p; + if (p == Scheme) + { + int i = Array.FindIndex(schemes, n => n.Equals(SchemeName, StringComparison.OrdinalIgnoreCase)); + if (i >= 0) return ThemePalette.PresetNames.Length + i; + } + return ThemePalette.PresetNames.Length + schemes.Length; + } + } + + /// The picker's item : a preset, a saved scheme, or Custom (the player's own colours). + public static void SetPicker(int index) + { + if (index >= 0 && index < ThemePalette.PresetNames.Length) { SetPreset(index); return; } + string[] schemes = ThemeSchemes.Names; + int s = index - ThemePalette.PresetNames.Length; + if (s >= 0 && s < schemes.Length) { UseScheme(schemes[s]); return; } + UseCustom(); + } + + /// Uses preset ; out of range means Custom (the player's own colours). public static void SetPreset(int index) { EnsureLoaded(); if (index < 0 || index >= ThemePalette.PresetNames.Length) { - lock (Sync) _preset = Custom; - Changed(); + UseCustom(); return; } lock (Sync) @@ -277,6 +356,72 @@ internal static class RynthTheme Changed(); } + /// The player's own colours (Custom), as they last left them. + public static void UseCustom() + { + EnsureLoaded(); + lock (Sync) + { + _preset = Custom; + _palette = _custom.Clone(); + } + Changed(); + } + + /// A saved scheme by name; false when there is none by that name (or it can't be read). + public static bool UseScheme(string name) + { + EnsureLoaded(); + ThemePalette? p = ThemeSchemes.Load(name); + if (p == null) return false; + lock (Sync) + { + _preset = Scheme; + _scheme = ThemeSchemes.DisplayName(name); + _palette = p; + } + Changed(); + return true; + } + + /// + /// Saves the colours in use as scheme (replacing one of that name) and + /// switches to it. Returns the name saved, or "" for an empty or unusable name. + /// + public static string SaveScheme(string name) + { + EnsureLoaded(); + name = ThemeSchemes.CleanName(name); + if (name.Length == 0) return string.Empty; + ThemePalette p; + lock (Sync) p = _palette.Clone(); + if (!ThemeSchemes.Save(name, p)) return string.Empty; + lock (Sync) + { + _preset = Scheme; + _scheme = name; + } + Changed(); + return name; + } + + /// Deletes the scheme in use; its colours stay on screen as the player's own (Custom). + public static bool DeleteCurrentScheme() + { + EnsureLoaded(); + string name = SchemeName; + if (name.Length == 0 || !ThemeSchemes.Delete(name)) return false; + lock (Sync) + { + _custom = _palette.Clone(); + _customSet = true; + _preset = Custom; + _scheme = string.Empty; + } + Changed(); + return true; + } + /// One of the eight colours (#AARRGGBB). public static uint GetPrimary(int i) { @@ -284,20 +429,33 @@ internal static class RynthTheme lock (Sync) return _palette.P[Math.Clamp(i, 0, ThemePalette.Primaries - 1)]; } - /// Changes one of the eight colours (#RRGGBB, opaque): the theme becomes Custom and its shades follow. + /// + /// Changes one of the eight colours (#RRGGBB, opaque): the theme becomes Custom with the change and + /// its shades follow. Made on a preset or a scheme, it replaces the player's own colours, which are + /// saved as a scheme first when they aren't kept anywhere yet. + /// public static void SetPrimary(int i, uint argb) { EnsureLoaded(); if (i < 0 || i >= ThemePalette.Primaries) return; argb |= 0xFF000000; + ThemePalette? keep = null; lock (Sync) { if (_palette.P[i] == argb) return; + if (_preset != Custom && _customSet) keep = _custom.Clone(); + } + if (keep != null) ThemeSchemes.KeepIfNew("My colours", keep); + lock (Sync) + { var p = _palette.Clone(); p.P[i] = argb; p.Derive(); _palette = p; + _custom = p.Clone(); + _customSet = true; _preset = Custom; + _scheme = string.Empty; } Changed(); } @@ -321,7 +479,12 @@ internal static class RynthTheme ApplyColors(ImGuiNET.ImGui.GetStyle()); } - /// Reads theme.txt if it hasn't been read yet. Engine init calls this so AC's thread never does. + /// + /// Reads theme.txt if it hasn't been read yet. Engine init calls this so AC's thread never does. + /// "preset=" names a preset, "scheme:Name" a saved scheme, or Custom; the eight colour lines are the + /// player's own colours whatever the preset (before 2026-10-22 they were written only for Custom). + /// A scheme that is gone falls back to the player's own colours. + /// public static void EnsureLoaded() { if (_loaded) return; @@ -333,7 +496,9 @@ internal static class RynthTheme if (File.Exists(FilePath)) { int preset = 0; + string scheme = string.Empty; var custom = ThemePalette.Default(); + bool anyColour = false; foreach (string raw in File.ReadAllLines(FilePath)) { string line = raw.Trim(); @@ -342,6 +507,12 @@ internal static class RynthTheme string key = line[..eq].Trim(), value = line[(eq + 1)..].Trim(); if (key.Equals("preset", StringComparison.OrdinalIgnoreCase)) { + if (value.StartsWith("scheme:", StringComparison.OrdinalIgnoreCase)) + { + scheme = value["scheme:".Length..].Trim(); + preset = Scheme; + continue; + } int idx = Array.FindIndex(ThemePalette.PresetNames, n => n.Equals(value, StringComparison.OrdinalIgnoreCase)); preset = idx >= 0 ? idx : Custom; continue; @@ -349,11 +520,19 @@ internal static class RynthTheme for (int i = 0; i < ThemePalette.Primaries; i++) if (key.Equals(ThemePalette.Key(i), StringComparison.OrdinalIgnoreCase) && uint.TryParse(value, System.Globalization.NumberStyles.HexNumber, null, out uint c)) + { custom.P[i] = 0xFF000000 | c; + anyColour = true; + } } + custom.Derive(); + _custom = custom; + _customSet = anyColour; + ThemePalette? fromScheme = preset == Scheme ? ThemeSchemes.Load(scheme) : null; + if (preset == Scheme && fromScheme == null) preset = Custom; _preset = preset; - if (preset == Custom) { custom.Derive(); _palette = custom; } - else _palette = ThemePalette.Preset(preset); + _scheme = preset == Scheme ? ThemeSchemes.DisplayName(scheme) : string.Empty; + _palette = preset == Custom ? custom.Clone() : preset == Scheme ? fromScheme! : ThemePalette.Preset(preset); _t = new Tokens(_palette); _version++; } @@ -363,8 +542,13 @@ internal static class RynthTheme } } - private static string FilePath => - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "theme.txt"); + /// %AppData%\RynthCore, or RYNTHCORE_THEME_DIR when set (tools\ThemeTests' temp folder). + internal static string Folder => + Environment.GetEnvironmentVariable("RYNTHCORE_THEME_DIR") is { Length: > 0 } dir + ? dir + : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore"); + + private static string FilePath => Path.Combine(Folder, "theme.txt"); private static void Save() { @@ -373,10 +557,13 @@ internal static class RynthTheme var sb = new System.Text.StringBuilder(); lock (Sync) { - sb.Append("preset=").Append(_preset == Custom ? "Custom" : ThemePalette.PresetNames[_preset]).Append('\n'); - if (_preset == Custom) + sb.Append("preset=") + .Append(_preset == Custom ? "Custom" : _preset == Scheme ? "scheme:" + _scheme : ThemePalette.PresetNames[_preset]) + .Append('\n'); + // The player's own colours, whatever is in use (an older engine reads them only for Custom). + if (_customSet || _preset == Custom) for (int i = 0; i < ThemePalette.Primaries; i++) - sb.Append(ThemePalette.Key(i)).Append('=').Append((_palette.P[i] & 0xFFFFFF).ToString("X6")).Append('\n'); + sb.Append(ThemePalette.Key(i)).Append('=').Append((_custom.P[i] & 0xFFFFFF).ToString("X6")).Append('\n'); } Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); File.WriteAllText(FilePath, sb.ToString()); diff --git a/src/RynthCore.Engine/ImGui/ThemeSchemes.cs b/src/RynthCore.Engine/ImGui/ThemeSchemes.cs new file mode 100644 index 0000000..9cccc84 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ThemeSchemes.cs @@ -0,0 +1,230 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ThemeSchemes.cs +// The colour schemes a player saved (Tom 2026-10-22: "a profile people can +// 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 +// presets and Custom; "Save colours as" adds one, Delete removes the one in +// use. +// +// The list is read from the folder at most every 3 s (a scheme saved in one +// client shows in the others' pickers without a restart) and at once after +// this client saves or deletes one. Any thread; the files are small. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class ThemeSchemes +{ + private const int MaxNameLength = 40; + private const long RescanMs = 3000; + + private static readonly object Sync = new(); + private static string[] _names = Array.Empty(); + private static Dictionary _files = new(StringComparer.OrdinalIgnoreCase); // display name -> file + private static long _scannedAt = long.MinValue / 2; + + private static string Folder => Path.Combine(RynthTheme.Folder, "themes"); + + /// The saved schemes' names, A-Z (read again from the folder at most every 3 s). + public static string[] Names + { + get + { + long now = Environment.TickCount64; + lock (Sync) + { + if (now - _scannedAt < RescanMs) return _names; + _scannedAt = now; + } + Rescan(); + lock (Sync) return _names; + } + } + + private static void Rescan() + { + var files = new Dictionary(StringComparer.OrdinalIgnoreCase); + try + { + if (Directory.Exists(Folder)) + foreach (string file in Directory.GetFiles(Folder, "*.theme")) + { + string name = ReadName(file); + if (name.Length > 0 && !files.ContainsKey(name)) files[name] = file; + } + } + catch { /* unreadable folder: no schemes */ } + string[] names = files.Keys.OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToArray(); + lock (Sync) + { + _files = files; + _names = names; + } + } + + private static void Invalidate() + { + lock (Sync) _scannedAt = long.MinValue / 2; + } + + /// The name as saved (its own capitals), or when there's none by it. + public static string DisplayName(string name) + { + _ = Names; + lock (Sync) + return _names.FirstOrDefault(n => n.Equals(name, StringComparison.OrdinalIgnoreCase)) ?? name; + } + + /// + /// A name a scheme can have: trimmed, at most 40 characters, not a preset's or "Custom" + /// (those get "My " in front, so the picker never shows two alike). "" when nothing is left. + /// + public static string CleanName(string name) + { + name = new string((name ?? string.Empty).Where(c => !char.IsControl(c)).ToArray()).Trim(); + if (name.Length > MaxNameLength) name = name[..MaxNameLength].TrimEnd(); + if (name.Length == 0) return string.Empty; + if (name.Equals("Custom", StringComparison.OrdinalIgnoreCase) + || ThemePalette.PresetNames.Any(p => p.Equals(name, StringComparison.OrdinalIgnoreCase))) + name = "My " + name; + return name; + } + + /// The scheme's eight colours (and its shades), or null when there's none by that name. + public static ThemePalette? Load(string name) + { + string? file; + _ = Names; + lock (Sync) _files.TryGetValue(name, out file); + if (file == null) return null; + try + { + var p = ThemePalette.Default(); + int found = 0; + foreach (string raw in File.ReadAllLines(file)) + { + string line = raw.Trim(); + int eq = line.IndexOf('='); + if (eq <= 0) continue; + string key = line[..eq].Trim(), value = line[(eq + 1)..].Trim(); + for (int i = 0; i < ThemePalette.Primaries; i++) + if (key.Equals(ThemePalette.Key(i), StringComparison.OrdinalIgnoreCase) + && uint.TryParse(value, System.Globalization.NumberStyles.HexNumber, null, out uint c)) + { + p.P[i] = 0xFF000000 | c; + found++; + } + } + if (found == 0) return null; + p.Derive(); + return p; + } + catch { return null; } + } + + /// Saves (or replaces) scheme (already cleaned). False when the file can't be written. + public static bool Save(string name, ThemePalette palette) + { + try + { + Directory.CreateDirectory(Folder); + string? existing; + lock (Sync) _files.TryGetValue(name, out existing); + string file = existing ?? Path.Combine(Folder, FileStem(name) + ".theme"); + var sb = new StringBuilder(); + sb.Append("name=").Append(name).Append('\n'); + for (int i = 0; i < ThemePalette.Primaries; i++) + sb.Append(ThemePalette.Key(i)).Append('=').Append((palette.P[i] & 0xFFFFFF).ToString("X6")).Append('\n'); + File.WriteAllText(file, sb.ToString()); + Invalidate(); + RynthLog.UI($"ThemeSchemes: saved \"{name}\" ({file})."); + return true; + } + catch (Exception ex) + { + RynthLog.UI($"ThemeSchemes: could not save \"{name}\": {ex.GetType().Name}: {ex.Message}"); + return false; + } + } + + public static bool Delete(string name) + { + string? file; + _ = Names; + lock (Sync) _files.TryGetValue(name, out file); + if (file == null) return false; + try + { + File.Delete(file); + Invalidate(); + RynthLog.UI($"ThemeSchemes: deleted \"{name}\"."); + return true; + } + catch { return false; } + } + + /// + /// Keeps as a scheme unless it's already kept: the same eight colours as + /// a preset or a saved scheme. Saved as , or "baseName 2", 3... when taken. + /// + public static void KeepIfNew(string baseName, ThemePalette palette) + { + for (int i = 0; i < ThemePalette.PresetNames.Length; i++) + if (SameColours(ThemePalette.Preset(i), palette)) return; + foreach (string n in Names) + { + ThemePalette? s = Load(n); + if (s != null && SameColours(s, palette)) return; + } + string name = baseName; + for (int k = 2; Names.Any(n => n.Equals(name, StringComparison.OrdinalIgnoreCase)) && k < 100; k++) + name = baseName + " " + k; + Save(name, palette); + } + + private static bool SameColours(ThemePalette a, ThemePalette b) + { + for (int i = 0; i < ThemePalette.Primaries; i++) + if ((a.P[i] & 0xFFFFFF) != (b.P[i] & 0xFFFFFF)) return false; + return true; + } + + private static string ReadName(string file) + { + try + { + foreach (string raw in File.ReadLines(file)) + { + string line = raw.Trim(); + if (line.StartsWith("name=", StringComparison.OrdinalIgnoreCase)) + return CleanStored(line[5..]); + } + } + catch { return string.Empty; } + return CleanStored(Path.GetFileNameWithoutExtension(file)); + } + + private static string CleanStored(string name) + { + name = name.Trim(); + return name.Length > MaxNameLength ? name[..MaxNameLength].TrimEnd() : name; + } + + /// A file name for the scheme: its letters and digits, the rest as '_'. + private static string FileStem(string name) + { + var sb = new StringBuilder(name.Length); + foreach (char c in name) + sb.Append(char.IsLetterOrDigit(c) || c is ' ' or '-' ? c : '_'); + string stem = sb.ToString().Trim(); + return stem.Length == 0 ? "scheme" : stem; + } +} diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 9bede37..aea946f 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -972,6 +972,73 @@ internal struct RynthCoreAPI /// 1 open / 0 closed (after the change, which lands on the next frame), -1 no such panel. Any /// thread. Requires API v89+. public IntPtr SetPanelOpenFn; + + // ── v90: plugin windows that draw their own frame ("chrome": "none"; docs/PLUGIN_WINDOWS.md) ── + + /// v90: void PanelDragWithLastItem(void): while ImGui's last item is held and + /// dragged, the panel being drawn follows the mouse (a frameless window's own title row; popped + /// out, its OS window). AC's render thread, inside a window's RynthPluginRenderEmbed; anywhere + /// else it does nothing. Requires API v90+. + public IntPtr PanelDragWithLastItemFn; + /// v90: int SetPanelPopOut(const char* key, int mode): an open panel into its own + /// window or back: mode 1 pop out, 0 dock, 2 toggle, -1 just ask. Returns 1 popped out / 0 docked + /// (after the change, which lands on the next frame), -1 no such panel or not open. Any thread. + /// Requires API v90+. + public IntPtr SetPanelPopOutFn; + /// v90: int PanelTextSize(const char* key, int delta): steps a panel's text size + /// by delta (0 = just ask; Ctrl+wheel and the size menu of a frameless window) and returns + /// it as a percentage of normal (100, 110, ... 250), -1 for no such panel. The fonts re-bake a + /// moment later. Any thread. Requires API v90+. + public IntPtr PanelTextSizeFn; + /// v90: float RenderSettingsDrawer(const char* key, float width, float room, int flags): + /// the body of a dashboard drawer that shows Settings rows, which are still RynthCore's (the + /// Settings panel hasn't moved to RynthAi): "ranges" (the selected monster and the key ranges), + /// "patrol" (the Dungeon Patrol settings, hazards and routes), "pinned" (My settings; flags 1 = + /// open its list of settings to pin). Drawn at the cursor of the window being drawn, width + /// pixels wide and at most room tall (0 = its own height). Returns the height it wants + /// (pixels), -1 for another key. AC's render thread, inside a docked window's + /// RynthPluginRenderEmbed. Requires API v90+. + public IntPtr RenderSettingsDrawerFn; + /// v90: int GetShortcuts(uint* objectIds, uint* spellIds, int max): the player's + /// 18 shortcut slots (AC's own, the retail toolbar's), object id 0 = empty. Returns 18, or 0 out + /// of the world. Any thread. Requires API v90+. + public IntPtr GetShortcutsFn; + /// v90: int ShortcutAction(int op, int slot, uint objectId): op 0 use the slot + /// (as its key does), 1 put the object in it, 2 empty it; slot 0-17. Done on AC's game thread + /// through the retail toolbar's own functions (saved to the server). 1 queued, 0 refused. Any + /// thread. Requires API v90+. + public IntPtr ShortcutActionFn; + /// v90: int GetActionKeys(const char* action, char* buffer, int length): AC's keys + /// for a keymap action ("UseQuickSlot_1") as UTF-8 text ("1, Ctrl+1"). Returns the bytes needed + /// (0 = unbound), -1 for a bad call. Any thread. Requires API v90+. + public IntPtr GetActionKeysFn; + /// v90: void* GetIconTexture(int kind, uint id): kind 0 icon id, 1 object, 2 + /// spell: an ImGui texture id, or null while it is made. AC's render thread, in a docked + /// window's draw. Requires API v90+. + public IntPtr GetIconTextureFn; + /// v90: int KeyCapture(int op, char* buffer, int length): op 0 waits for the next key + /// the player presses (it never reaches AC; Esc cancels), 1 asks (0 waiting, 1 pressed: its name + /// "Ctrl+F5" in the buffer, 2 cancelled), 2 stops. AC's main thread. Requires API v90+. + public IntPtr KeyCaptureFn; + /// v90: int SetActionKey(const char* action, const char* key, int op, char* message, int + /// length): a keymap action ("UseQuickSlot_5") or engine command ("/rdef use 2") and a key: op 0 + /// checks (0 free, 1 taken from what the message names, -1 can't), 1 binds it (off everything else, + /// every client follows), 2 removes it (1 queued, -1 refused). Any thread. Requires API v90+. + public IntPtr SetActionKeyFn; + /// v90: int AcPanel(int id, int op): AC's own panel by the id its panel notice uses (7 + /// the pack, 12 fellowship/allegiance, 13 spellbook, 16 the map...): op 0 asks (1 open, 0 closed, -1 + /// none; AC's main thread), 1 toggles, 2 opens, 3 closes (1 queued, -1 refused). Requires API v90+. + 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+. + 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 + /// (ImGui screen coordinates; flags 1 = accepting; published each frame it draws). Returns the object + /// dropped since the last call (0 = none); *dragging = 1 while an item drag is on. A claimed drop never + /// reaches AC. AC's main thread, in the window's draw. Requires API v90+. + public IntPtr DropTargetFn; } /// v89 GetUiColor tokens. Append only: plugins compiled against these numbers keep them. @@ -980,6 +1047,9 @@ internal enum UiColorToken Text = 0, TextMuted = 1, Accent = 2, Highlight = 3, Button = 4, Border = 5, Field = 6, Selected = 7, RowAlt = 8, Background = 9, PanelGlass = 10, AccentFill = 11, BoxBg = 12, FrameBg = 13, FrameHover = 14, FrameActive = 15, Green = 16, Red = 17, TitleBar = 18, WindowBorder = 19, + // v90: the theme's own muted text (TextMuted is a lighter mix) and the instrument look's shades + // worked out from the eight colours (ThemePalette.DeriveInstrument). 0 on a v89 engine. + Muted = 20, KeyFace = 21, Hairline = 22, Inset = 23, Faint = 24, } /// v89 GetUiFont fonts. Append only. @@ -987,6 +1057,10 @@ internal enum UiFontToken { Ui9 = 0, Ui10 = 1, Ui11 = 2, Ui14 = 3, Ui18 = 4, UiBold11 = 5, UiBold14 = 6, Mono9 = 7, Mono10 = 8, Mono12 = 9, Chat10 = 10, Chat12 = 11, Chat14 = 12, + // v90: Cascadia Mono (Consolas without it), the dashboard's numbers, and the narrow labels + // (Barlow Semi Condensed SemiBold 9/10/11, Bold 11/13). Null on a v89 engine. + Dash9 = 13, Dash10 = 14, Dash11 = 15, Dash14 = 16, + Narrow9 = 17, Narrow10 = 18, Narrow11 = 19, NarrowBold11 = 20, NarrowBold13 = 21, } /// v79 bits. @@ -1778,6 +1852,45 @@ internal delegate IntPtr GetUiFontCallbackDelegate(int font); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int SetPanelOpenCallbackDelegate(byte* key, int mode); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate void PanelDragWithLastItemCallbackDelegate(); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int SetPanelPopOutCallbackDelegate(byte* key, int mode); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int PanelTextSizeCallbackDelegate(byte* key, int delta); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate float RenderSettingsDrawerCallbackDelegate(byte* key, float width, float room, int flags); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetShortcutsCallbackDelegate(uint* objectIds, uint* spellIds, int max); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int ShortcutActionCallbackDelegate(int op, int slot, uint objectId); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetActionKeysCallbackDelegate(byte* action, byte* buffer, int length); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate IntPtr GetIconTextureCallbackDelegate(int kind, uint id); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int KeyCaptureCallbackDelegate(int op, byte* buffer, int length); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int SetActionKeyCallbackDelegate(byte* action, byte* key, int op, byte* message, int length); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int AcPanelCallbackDelegate(int id, int op); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int PanelScaleCallbackDelegate(byte* key, int percent); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate uint DropTargetCallbackDelegate(byte* window, float x0, float y0, float x1, float y1, int flags, int* dragging); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate uint VendorBuyCallbackDelegate(uint vendorId, VendorTradeEntryNative* entries, int count); diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index 51f1348..d6f8088 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -30,5 +30,8 @@ internal static class PluginContractVersion // plugins managed (collectible: a reload frees them) and they declare minEngineApi 88. // v89: plugin windows: GetUiColor, GetUiFont and SetPanelOpen (the engine hosts the windows // a plugin's sections manifest declares; the plugin draws them; docs/PLUGIN_WINDOWS.md). - public const uint Current = 89; + // v90: windows that draw their own frame (manifest "chrome": "none", "fitHeight"): + // PanelDragWithLastItem, SetPanelPopOut, PanelTextSize; GetUiColor's Muted and instrument + // shades (KeyFace, Hairline, Inset, Faint), GetUiFont's Dash and Narrow fonts (2026-10-21). + public const uint Current = 90; } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index c44dc70..e01860a 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -288,6 +288,19 @@ internal static partial class PluginManager private static GetUiColorCallbackDelegate? _getUiColorCallback; // v89 private static GetUiFontCallbackDelegate? _getUiFontCallback; // v89 private static SetPanelOpenCallbackDelegate? _setPanelOpenCallback; // v89 + private static PanelDragWithLastItemCallbackDelegate? _panelDragWithLastItemCallback; // v90 + private static SetPanelPopOutCallbackDelegate? _setPanelPopOutCallback; // v90 + private static PanelTextSizeCallbackDelegate? _panelTextSizeCallback; // v90 + private static RenderSettingsDrawerCallbackDelegate? _renderSettingsDrawerCallback; // v90 + private static GetShortcutsCallbackDelegate? _getShortcutsCallback; // v90 + private static ShortcutActionCallbackDelegate? _shortcutActionCallback; // v90 + private static GetActionKeysCallbackDelegate? _getActionKeysCallback; // v90 + private static GetIconTextureCallbackDelegate? _getIconTextureCallback; // v90 + private static KeyCaptureCallbackDelegate? _keyCaptureCallback; // v90 + private static SetActionKeyCallbackDelegate? _setActionKeyCallback; // v90 + private static AcPanelCallbackDelegate? _acPanelCallback; // v90 + private static PanelScaleCallbackDelegate? _panelScaleCallback; // v90 + private static DropTargetCallbackDelegate? _dropTargetCallback; // v90 private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback; private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback; private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback; @@ -1663,6 +1676,10 @@ internal static partial class PluginManager Compatibility.RadarHooks.ResetCachedInstance(); Compatibility.PowerbarHooks.ResetCachedInstance(); Compatibility.RetailVitalsHooks.ResetCachedInstance(); + Compatibility.RetailToolbarHooks.ResetCachedInstance(); + Compatibility.AcShortcuts.Reset(); + Compatibility.AcKeymapLive.Reset(); + Compatibility.AcPanels.Reset(); Compatibility.ChatCallbackHooks.ResetOutgoingTarget(); // Drop the cached PlayerDesc/CACQualities pointer so the next call into the @@ -3194,6 +3211,19 @@ internal static partial class PluginManager _getUiColorCallback ??= UiKit.GetUiColor; _getUiFontCallback ??= UiKit.GetUiFont; unsafe { _setPanelOpenCallback ??= UiKit.SetPanelOpen; } + _panelDragWithLastItemCallback ??= UiKit.PanelDragWithLastItem; // v90 + unsafe { _setPanelPopOutCallback ??= UiKit.SetPanelPopOut; } + unsafe { _panelTextSizeCallback ??= UiKit.PanelTextSize; } + unsafe { _renderSettingsDrawerCallback ??= UiKit.RenderSettingsDrawer; } + unsafe { _getShortcutsCallback ??= ShortcutApi.GetShortcuts; } + _shortcutActionCallback ??= ShortcutApi.ShortcutAction; + unsafe { _getActionKeysCallback ??= ShortcutApi.GetActionKeys; } + _getIconTextureCallback ??= ShortcutApi.GetIconTexture; + unsafe { _keyCaptureCallback ??= ShortcutApi.KeyCapture; } + unsafe { _setActionKeyCallback ??= ShortcutApi.SetActionKey; } + _acPanelCallback ??= ShortcutApi.AcPanel; + unsafe { _panelScaleCallback ??= UiKit.PanelScale; } + unsafe { _dropTargetCallback ??= ShortcutApi.DropTarget; } _api.Version = PluginContractVersion.Current; _api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback); @@ -3351,6 +3381,19 @@ internal static partial class PluginManager _api.GetUiColorFn = Marshal.GetFunctionPointerForDelegate(_getUiColorCallback); _api.GetUiFontFn = Marshal.GetFunctionPointerForDelegate(_getUiFontCallback); _api.SetPanelOpenFn = Marshal.GetFunctionPointerForDelegate(_setPanelOpenCallback); + _api.PanelDragWithLastItemFn = Marshal.GetFunctionPointerForDelegate(_panelDragWithLastItemCallback); + _api.SetPanelPopOutFn = Marshal.GetFunctionPointerForDelegate(_setPanelPopOutCallback); + _api.PanelTextSizeFn = Marshal.GetFunctionPointerForDelegate(_panelTextSizeCallback); + _api.RenderSettingsDrawerFn = Marshal.GetFunctionPointerForDelegate(_renderSettingsDrawerCallback); + _api.GetShortcutsFn = Marshal.GetFunctionPointerForDelegate(_getShortcutsCallback); + _api.ShortcutActionFn = Marshal.GetFunctionPointerForDelegate(_shortcutActionCallback); + _api.GetActionKeysFn = Marshal.GetFunctionPointerForDelegate(_getActionKeysCallback); + _api.GetIconTextureFn = Marshal.GetFunctionPointerForDelegate(_getIconTextureCallback); + _api.KeyCaptureFn = Marshal.GetFunctionPointerForDelegate(_keyCaptureCallback); + _api.SetActionKeyFn = Marshal.GetFunctionPointerForDelegate(_setActionKeyCallback); + _api.AcPanelFn = Marshal.GetFunctionPointerForDelegate(_acPanelCallback); + _api.PanelScaleFn = Marshal.GetFunctionPointerForDelegate(_panelScaleCallback); + _api.DropTargetFn = Marshal.GetFunctionPointerForDelegate(_dropTargetCallback); RouteApiThroughLoader(); } diff --git a/src/RynthCore.Engine/Plugins/ShortcutApi.cs b/src/RynthCore.Engine/Plugins/ShortcutApi.cs new file mode 100644 index 0000000..67e7037 --- /dev/null +++ b/src/RynthCore.Engine/Plugins/ShortcutApi.cs @@ -0,0 +1,201 @@ +// ============================================================================ +// RynthCore.Engine - Plugins/ShortcutApi.cs +// Plugin API v90 (2026-10-22), for an item bar that stands in for AC's +// toolbar (RynthDefective): the player's shortcut slots (AcShortcuts), their +// keys in AC's keymap (AcKeymap) and changing them so every client follows +// (AcKeymapLive, with the engine's "press a key" capture), and item / spell +// pictures for ImGui windows (the script windows' icon cache, ScriptIcons). +// Nothing here throws across the boundary. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.ImGuiBackend; +using RynthCore.Engine.UI.ScriptWindows; + +namespace RynthCore.Engine.Plugins; + +internal static unsafe class ShortcutApi +{ + /// + /// v90 GetShortcuts: the 18 slots as last read (object id, 0 = empty; spell id) into the + /// caller's arrays. Returns the slot count (18), or 0 out of the world. Any thread. + /// + public static int GetShortcuts(uint* objectIds, uint* spellIds, int max) + { + try + { + AcShortcuts.Slot[] slots = AcShortcuts.Slots; + if (slots.Length == 0) return 0; + int n = Math.Min(Math.Max(max, 0), slots.Length); + for (int i = 0; i < n; i++) + { + if (objectIds != null) objectIds[i] = slots[i].ObjectId; + if (spellIds != null) spellIds[i] = slots[i].SpellId; + } + return slots.Length; + } + catch { return 0; } + } + + /// + /// v90 ShortcutAction: op 0 use slot (as its key does), 1 put object + /// in it, 2 empty it; slot 0-17. Done on AC's game thread through the retail toolbar's own + /// functions (saved to the server). 1 queued, 0 refused. Any thread. + /// + public static int ShortcutAction(int op, int slot, uint objectId) + { + try + { + if (op is < 0 or > 2) return 0; + return AcShortcuts.Enqueue((AcShortcuts.Op)op, slot, objectId) ? 1 : 0; + } + catch { return 0; } + } + + /// + /// v90 GetActionKeys: AC's keys for keymap action ("UseQuickSlot_1") + /// as text ("1, Ctrl+1"), UTF-8 into (NUL-terminated when it fits). + /// Returns the bytes the text needs ("" = 0: unbound), -1 for a bad call. Any thread. + /// + public static int GetActionKeys(byte* action, byte* buffer, int length) + { + try + { + if (action == null) return -1; + string? name = Marshal.PtrToStringUTF8((IntPtr)action); + if (string.IsNullOrWhiteSpace(name) || name.Length > 64) return -1; + name = name.Trim(); + return Write(AcKeymapLive.IsCommand(name) ? AcKeymapLive.CommandKeysText(name) : AcKeymap.KeysText(name), buffer, length); + } + catch { return -1; } + } + + /// + /// v90 AcPanel: AC's own panel (the id AC's panel notice uses: 7 the pack, 12 + /// fellowship and allegiance...): op 0 asks (1 open, 0 closed, -1 no such panel; AC's main thread), + /// 1 toggles, 2 opens, 3 closes it (1 queued for AC's game thread, -1 refused). See AcPanels. + /// + public static int AcPanel(int id, int op) + { + try + { + if (id <= 0 || id > 0xFFFF) return -1; + if (op == 0) return MainThreadGuard.IsOnMainThread() ? AcPanels.State((uint)id) : -1; + AcPanels.Op what = op switch { 1 => AcPanels.Op.Toggle, 2 => AcPanels.Op.Open, 3 => AcPanels.Op.Close, _ => (AcPanels.Op)(-1) }; + if ((int)what < 0) return -1; + return AcPanels.Enqueue((uint)id, what) ? 1 : -1; + } + catch { return -1; } + } + + /// + /// v90 DropTarget: the plugin window takes items dragged out of AC's UI + /// (a pack, the inventory) and let go over x0,y0-x1,y1 (ImGui screen coordinates, this frame's): + /// published every frame it draws, as the engine's own panels do (UiDropTargets), flags bit 0 = + /// a drop would be used now. A claimed drop never reaches AC (the item stays where it was, as on + /// the retail toolbar). Returns the object dropped since the last call (0 = none); *dragging = 1 + /// while an item is being dragged (for a "drop here" look). AC's main thread, in the window's draw. + /// + public static uint DropTarget(byte* window, float x0, float y0, float x1, float y1, int flags, int* dragging) + { + try + { + if (dragging != null) *dragging = 0; + if (window == null || !MainThreadGuard.IsOnMainThread()) return 0; + string? title = Marshal.PtrToStringUTF8((IntPtr)window); + if (string.IsNullOrWhiteSpace(title) || title.Length > 64) return 0; + string key = "plugin:" + title; + UiDropTargets.Publish(key, title, new System.Numerics.Vector2(x0, y0), new System.Numerics.Vector2(x1, y1), (flags & 1) != 0); + if (dragging != null) *dragging = UiDropTargets.AnyDragInProgress ? 1 : 0; + return UiDropTargets.TryTake(key, out uint item) ? item : 0; + } + catch { return 0; } + } + + /// UTF-8 into the caller's buffer (NUL-terminated when it fits); the bytes the text needs. + private static int Write(string s, byte* buffer, int length) + { + byte[] text = Encoding.UTF8.GetBytes(s); + if (buffer != null && length > 0) + { + int n = Math.Min(text.Length, length - 1); + for (int i = 0; i < n; i++) buffer[i] = text[i]; + buffer[n] = 0; + } + return text.Length; + } + + /// + /// v90 KeyCapture: op 0 starts waiting for the next key the player presses (it never reaches AC; Esc + /// cancels), 1 asks: 0 still waiting, 1 pressed (its name, "Ctrl+F5", in the buffer), 2 cancelled or + /// timed out (why, if anything, in the buffer); 2 stops waiting. AC's main thread (the render). + /// + public static int KeyCapture(int op, byte* buffer, int length) + { + try + { + switch (op) + { + case 0: + Hotkeys.HotkeyService.BeginCapture(); + return 0; + case 2: + if (Hotkeys.HotkeyService.Capturing) Hotkeys.HotkeyService.CancelCapture(); + Hotkeys.HotkeyService.TryTakeCapture(out _); + return 0; + case 1: + string note = Hotkeys.HotkeyService.CaptureNote; // a key that can't be one ("Numpad Enter..."): still waiting + if (!Hotkeys.HotkeyService.TryTakeCapture(out Hotkeys.KeyCombo? combo)) { Write(note, buffer, length); return 0; } + if (combo is { } c) { Write(c.ToString(), buffer, length); return 1; } + Write(note, buffer, length); + return 2; + default: + return -1; + } + } + catch { return -1; } + } + + /// + /// v90 SetActionKey: for a keymap action ("UseQuickSlot_5") or an engine command ("/rdef use 2"), key + /// "Ctrl+F5" (or a key as GetActionKeys wrote it, to remove): op 0 checks (0 free, 1 it would be taken + /// from what the message names, -1 it can't be, why in the message), 1 binds it (it comes off + /// everything else; every client follows within a second), 2 removes it. 1/2 return 1 queued (done on + /// AC's game thread; the result goes to chat), -1 refused (why in the message). Any thread. + /// + public static int SetActionKey(byte* action, byte* key, int op, byte* message, int length) + { + try + { + if (action == null || key == null) return -1; + string a = Marshal.PtrToStringUTF8((IntPtr)action) ?? string.Empty; + string k = Marshal.PtrToStringUTF8((IntPtr)key) ?? string.Empty; + string msg; + int result; + if (op == 0) result = AcKeymapLive.Check(a, k, out msg); + else if (op is 1 or 2) result = AcKeymapLive.Enqueue(a, k, op == 1 ? AcKeymapLive.Op.Bind : AcKeymapLive.Op.Unbind, out msg) ? 1 : -1; + else { result = -1; msg = "Unknown op."; } + Write(msg, message, length); + return result; + } + catch { return -1; } + } + + /// + /// v90 GetIconTexture: kind 0 an icon (0x06) id, 1 an object (its icon with underlay and + /// overlay), 2 a spell. An ImGui texture id for ImGui.Image, or 0 while it is being made (ask + /// again next frame). AC's render thread, inside a docked window's draw. + /// + public static IntPtr GetIconTexture(int kind, uint id) + { + try + { + if (kind is < 0 or > 2 || id == 0 || !MainThreadGuard.IsOnMainThread() || ImGuiPopOuts.InPopOutFrame) return IntPtr.Zero; + return ScriptIcons.TryGet((ScriptIconKind)kind, id, out IntPtr texture) ? texture : IntPtr.Zero; + } + catch { return IntPtr.Zero; } + } +} diff --git a/src/RynthCore.Engine/Plugins/UiKit.cs b/src/RynthCore.Engine/Plugins/UiKit.cs index d984812..92cf29c 100644 --- a/src/RynthCore.Engine/Plugins/UiKit.cs +++ b/src/RynthCore.Engine/Plugins/UiKit.cs @@ -3,7 +3,11 @@ // Plugin API v89, for the windows plugins draw (docs/PLUGIN_WINDOWS.md): the // player's colour theme (GetUiColor), the engine's UI fonts at the current // panel's text size (GetUiFont), and opening or closing a panel by its key -// (SetPanelOpen). Nothing here throws across the boundary. +// (SetPanelOpen). v90 (2026-10-21), for windows that draw their own frame +// ("chrome": "none"): dragging the panel from the plugin's own title row +// (PanelDragWithLastItem), popping it out (SetPanelPopOut), its text size +// (PanelTextSize), and the instrument look's colours and fonts. +// Nothing here throws across the boundary. // ============================================================================ using System; @@ -50,6 +54,11 @@ internal static unsafe class UiKit UiColorToken.Red => FaceKit.Red, UiColorToken.TitleBar => RynthTheme.TitleBar, UiColorToken.WindowBorder => RynthTheme.WindowBorder, + UiColorToken.Muted => RynthTheme.TextMuted, + UiColorToken.KeyFace => RynthTheme.KeyFace, + UiColorToken.Hairline => RynthTheme.Hairline, + UiColorToken.Inset => RynthTheme.Inset, + UiColorToken.Faint => RynthTheme.Faint, _ => 0, }; @@ -69,6 +78,15 @@ internal static unsafe class UiKit UiFontToken.Chat10 => UiFont.Chat10, UiFontToken.Chat12 => UiFont.Chat12, UiFontToken.Chat14 => UiFont.Chat14, + UiFontToken.Dash9 => UiFont.Dash9, + UiFontToken.Dash10 => UiFont.Dash10, + UiFontToken.Dash11 => UiFont.Dash11, + UiFontToken.Dash14 => UiFont.Dash14, + UiFontToken.Narrow9 => UiFont.Narrow9, + UiFontToken.Narrow10 => UiFont.Narrow10, + UiFontToken.Narrow11 => UiFont.Narrow11, + UiFontToken.NarrowBold11 => UiFont.NarrowBold11, + UiFontToken.NarrowBold13 => UiFont.NarrowBold13, _ => null, }; @@ -112,4 +130,121 @@ internal static unsafe class UiKit } catch { return -1; } } + + /// + /// v90 PanelDragWithLastItem: the panel being drawn follows the mouse while ImGui's last item is + /// held and dragged (ImGuiPanelHost.DragWindowWithLastItem: docked, the window moves, clamped to + /// the client; popped out, its OS window). Only inside a panel's draw on AC's thread. + /// + public static void PanelDragWithLastItem() + { + try + { + if (!MainThreadGuard.IsOnMainThread() || ImGuiPanelHost.DrawingTitle == null) return; + ImGuiPanelHost.DragWindowWithLastItem(); + } + catch { } + } + + /// + /// v90 SetPanelPopOut: mode 1 pop out, 0 dock, 2 toggle, -1 ask. 1 popped out / 0 docked + /// afterwards (the request lands on the next frame), -1 for no such panel, one that isn't open, + /// or a bad call. Popping out needs the pop-out windows (else it stays docked: 0). Any thread. + /// + public static int SetPanelPopOut(byte* key, int mode) + { + try + { + if (ReadKey(key) is not string title || !ImGuiPanelHost.IsOpen(title)) return -1; + bool popped = ImGuiPanelHost.IsPopped(title); + bool want = mode switch { 0 => false, 1 => true, 2 => !popped, -1 => popped, _ => popped }; + if (mode is < -1 or > 2) return -1; + if (want && !PanelRouter.CanPopOut) return popped ? 1 : 0; + if (want != popped) + { + if (want) ImGuiPanelHost.PopOut(title); + else ImGuiPanelHost.Redock(title); + } + return want ? 1 : 0; + } + catch { return -1; } + } + + /// + /// v90 PanelTextSize: steps the panel's text size by (its own size, as + /// Ctrl+wheel on a header does: PanelTextScale.SetForWindow) and returns the size as a percentage + /// of normal; 0 just asks. -1 for no such panel. Any thread. + /// + public static int PanelTextSize(byte* key, int delta) + { + try + { + if (ReadKey(key) is not string title) return -1; + int step = PanelTextScale.Get(title); + if (delta != 0) + { + step = Math.Clamp(step + Math.Clamp(delta, -10, 10), 0, PanelTextScale.SizeNames.Length - 1); + PanelTextScale.SetForWindow(title, step); + } + return (int)MathF.Round(PanelTextScale.Factor(step) * 100f); + } + catch { return -1; } + } + + /// + /// v90 PanelScale: how big a frameless window draws itself (PanelDrawScale), in percent of normal: + /// 0 asks, -1 goes back to following the text size, 30-250 sets it. + /// Returns the size now (0 = it follows the text size), -1 for a bad call. Any thread. + /// + public static int PanelScale(byte* key, int percent) + { + try + { + if (ReadKey(key) is not string title) return -1; + if (percent == -1) PanelDrawScale.Set(title, 0); + else if (percent > 0) PanelDrawScale.Set(title, percent); + return PanelDrawScale.Get(title); + } + catch { return -1; } + } + + /// + /// v90 RenderSettingsDrawer: the body of a dashboard drawer that shows Settings rows ("ranges", + /// "patrol", "pinned"; SettingsDrawerBodies) at the cursor, pixels wide + /// and at most tall (0 = its own height); flags 1: open My settings' list + /// of settings to pin. Returns the height it wants (pixels), -1 for another key or outside a + /// docked panel's draw on AC's thread. + /// + public static float RenderSettingsDrawer(byte* key, float width, float room, int flags) + { + try + { + if (key == null || !MainThreadGuard.IsOnMainThread() || ImGuiPanelHost.DrawingTitle == null + || ImGuiPopOuts.InPopOutFrame || !float.IsFinite(width) || !float.IsFinite(room)) return -1f; + string? name = Marshal.PtrToStringUTF8((IntPtr)key); + if (string.IsNullOrEmpty(name) || name.Length > MaxKeyLength) return -1f; + return SettingsDrawerBodies.Draw(name, width, MathF.Max(0f, room), (flags & 1) != 0); + } + catch (Exception ex) + { + if (!_settingsDrawerFailLogged) + { + _settingsDrawerFailLogged = true; + RynthLog.Warn("UiKit.RenderSettingsDrawer: " + ex.GetType().Name + ": " + ex.Message); + } + return -1f; + } + } + + private static bool _settingsDrawerFailLogged; + + /// A registered panel's key from a plugin's UTF-8 text (the router's name for it), or null. + private static string? ReadKey(byte* key) + { + if (key == null) return null; + string? title = Marshal.PtrToStringUTF8((IntPtr)key); + if (string.IsNullOrWhiteSpace(title) || title.Length > MaxKeyLength) return null; + title = PanelRouter.Canonical(title.Trim()); + return ImGuiPanelHost.HasFace(title) ? title : null; + } } diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj index c736d87..df21097 100644 --- a/src/RynthCore.Engine/RynthCore.Engine.csproj +++ b/src/RynthCore.Engine/RynthCore.Engine.csproj @@ -111,6 +111,13 @@ + + + + + + diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index 0dbf833..f0e5447 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -490,9 +490,15 @@ internal sealed record SettingRow( string? Hint = null, // Button rows that change settings: applied to the panel's copy, which is then saved like // any other edit (Click, when also set, runs after). - Action? Edit = null) + Action? Edit = null, + // Combo rows whose list changes while the game runs (the Theme picker's saved schemes): + // asked each time the row draws, in place of Items. + Func? ItemsNow = null) { public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s); + + /// A Combo row's list now: ItemsNow's when it has one, else Items. + public string[] CurrentItems => ItemsNow?.Invoke() ?? Items ?? Array.Empty(); } internal sealed record SettingsTab(string Name, SettingRow[] Rows); @@ -592,9 +598,25 @@ internal static class SettingsSchema // Text size rows are stored by the engine (PanelTextScale), not in the // RynthAi profile, so the settings object is ignored here. + // RynthDefective's window titles (its sections manifest). + private const string ShortcutsWindow = "Shortcuts", GamePanelsWindow = "Game Panels", SelectionWindow = "Selection"; + + // A plugin window shown or not; the row shows only while a plugin hosts it. + private static SettingRow WindowShown(string label, string title, string tip) => + Bool(label, _ => ImGuiBackend.ImGuiPanelHost.IsOpen(title), + (_, v) => { if (v) ImGuiBackend.ImGuiPanelHost.Open(title); else ImGuiBackend.ImGuiPanelHost.Close(title); }, + tip, when: _ => ImGuiBackend.ImGuiPanelHost.HasFace(title)); + + // Its size: how big it draws itself, 30% to 250% of normal, or with its text size (PanelDrawScale). + private static SettingRow WindowSize(string label, string title) => + Combo(" " + label, PanelDrawScale.Names, _ => PanelDrawScale.ToIndex(PanelDrawScale.Get(title)), + (_, v) => PanelDrawScale.Set(title, PanelDrawScale.FromIndex(v)), + "How big it is: 30% to 250% of normal. \"Text size\" = as big as the panels' text (Text Size above).\nAlso: Ctrl+wheel over it.", + when: _ => ImGuiBackend.ImGuiPanelHost.HasFace(title)); + private static SettingRow TextSize(string label, string panelTitle) => Combo(" " + label, PanelTextScale.SizeNames, _ => PanelTextScale.GetOwn(panelTitle), (_, v) => PanelTextScale.Set(panelTitle, v), - "Text size for this panel in the game: 0 = normal, each step 10% bigger, yourjokin = 2.5x.") + "This panel's size: 100% = normal, 10% a step. Also: Ctrl+wheel over the panel.") with { VisibleWhen = _ => PanelTextScale.PerPanel }; // One of the theme's eight colours (ImGuiBackend.RynthTheme); the settings object is ignored. @@ -725,8 +747,20 @@ internal static class SettingsSchema Spacer(), // The colour theme is stored by the engine (theme.txt, ImGuiBackend.RynthTheme), not in the RynthAi profile. Section("Colour Theme"), - Combo("Theme", ImGuiBackend.RynthTheme.PickerNames, _ => ImGuiBackend.RynthTheme.PickerIndex, (_, v) => ImGuiBackend.RynthTheme.SetPreset(v), - "The colours of every RynthCore window: RynthCore's own, a preset, or Custom (your own colours below).\nChanging any colour below makes the theme Custom. Applies to all your clients as they start."), + // 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" + + "Changing any colour below makes the theme Custom. Your own colours are kept whichever theme you pick: Custom brings them back.\n" + + "Applies to all your clients as they start.", + _ => ImGuiBackend.RynthTheme.PickerIndex, (_, v) => ImGuiBackend.RynthTheme.SetPicker((int)v), 0, 1000, 1, + ItemsNow: ImGuiBackend.RynthTheme.PickerNames), + Text("Save colours as", _ => string.Empty, (_, name) => ImGuiBackend.RynthTheme.SaveScheme(name), + "Saves the colours in use under a name, as a scheme in the Theme list (the same name replaces it).\n" + + "Saved for this PC (%AppData%\\RynthCore\\themes), so every character and client can pick it.", + hint: "A name for these colours, then Enter"), + Button("Saved scheme", "Delete it", () => ImGuiBackend.RynthTheme.DeleteCurrentScheme(), + "Deletes the saved scheme in use. Its colours stay on screen as your own (Custom).") + with { VisibleWhen = _ => ImGuiBackend.RynthTheme.SchemeInUse }, Colour(0, "The main highlight: outlines, selected tabs and buttons, toggles that are on, the dashboard's accent line."), Colour(1, "Values, section headings and the bot's busy states (amber in RynthCore's colours)."), Colour(2, "Window and drawer backgrounds. The fields, rows and popups are shades of it."), @@ -740,7 +774,7 @@ internal static class SettingsSchema Spacer(), Section("Text Size (in-game panels)"), Combo("All Panels", PanelTextScale.SizeNames, _ => PanelTextScale.GetAll(), (_, v) => PanelTextScale.SetAll(v), - "Text size for every in-game panel: 0 = normal, each step 10% bigger, yourjokin = 2.5x."), + "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. @@ -798,6 +832,24 @@ internal static class SettingsSchema 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."), + 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."), + // 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. + WindowShown("Shortcut bar", ShortcutsWindow, + "RynthDefective's bar of your shortcut slots, in place of the retail toolbar's: the game's 18 with their keys, then RynthCore's.\nAlso: /rdef."), + WindowSize("Shortcut bar size", ShortcutsWindow), + WindowShown("Game panel buttons", GamePanelsWindow, + "Small buttons for the game's panels (pack, attributes, spellbook, fellowship, map...), in place of the retail toolbar's.\nAlso: /rdef panels."), + WindowSize("Game panel buttons size", GamePanelsWindow), + WindowShown("Selection", SelectionWindow, + "What you have selected, as the retail toolbar showed it: its name, how far and which way it is, a creature's health, and Use.\nAlso: /rdef selection."), + WindowSize("Selection size", SelectionWindow), }), // The user hotkeys: stored by the engine for the PC (Hotkeys/HotkeyService.cs, hotkeys.txt), diff --git a/src/RynthCore.Engine/UI/PanelDrawScale.cs b/src/RynthCore.Engine/UI/PanelDrawScale.cs new file mode 100644 index 0000000..569c528 --- /dev/null +++ b/src/RynthCore.Engine/UI/PanelDrawScale.cs @@ -0,0 +1,105 @@ +// ============================================================================ +// RynthCore.Engine - UI/PanelDrawScale.cs +// How big a frameless plugin window draws itself (plugin API v90 PanelScale), +// 30% to 250% of normal, or "follow the text size" (the default). Text size +// (PanelTextScale) can't go under 100%: the fonts are baked at 100% and up. +// A window that draws its own content (RynthDefective's shortcut bar and panel +// buttons) scales its layout by this and draws its text smaller from the baked +// font (Tom 2026-10-22: "the shortcut size needs to go a lot smaller"). +// Stored for the whole PC in %LOCALAPPDATA%\RynthCore\panel_draw_scale.txt as +// "Title=percent" lines; every client looks for a change at most every 2 s. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; + +namespace RynthCore.Engine.UI; + +internal static class PanelDrawScale +{ + public const int Min = 30, Max = 250, Step = 10; + + /// Settings picker labels: index 0 follows the text size, then 30% ... 250%. + public static readonly string[] Names = BuildNames(); + + private static string[] BuildNames() + { + var list = new List { "Text size" }; + for (int p = Min; p <= Max; p += Step) list.Add(p.ToString(CultureInfo.InvariantCulture) + "%"); + return list.ToArray(); + } + + public static int ToIndex(int percent) => percent <= 0 ? 0 : (Math.Clamp(percent, Min, Max) - Min) / Step + 1; + public static int FromIndex(int index) => index <= 0 ? 0 : Min + (index - 1) * Step; + + private static readonly object Sync = new(); + private static readonly Dictionary Scales = new(StringComparer.OrdinalIgnoreCase); + private static DateTime _fileTime = DateTime.MinValue; + private static long _checkedMs = long.MinValue / 2; + + private static string FilePath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_draw_scale.txt"); + + /// The window's size in percent, 0 = it follows its text size. Any thread. + public static int Get(string title) + { + lock (Sync) + { + Refresh(); + return Scales.TryGetValue(title, out int p) ? p : 0; + } + } + + /// Sets it (30-250, rounded to 10%), or 0 to follow the text size again. Any thread. + public static void Set(string title, int percent) + { + percent = percent <= 0 ? 0 : (int)Math.Round(Math.Clamp(percent, Min, Max) / (double)Step) * Step; + lock (Sync) + { + Refresh(); + if ((Scales.TryGetValue(title, out int cur) ? cur : 0) == percent) return; + if (percent == 0) Scales.Remove(title); else Scales[title] = percent; + try + { + string path = FilePath; + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var lines = new List { "# RynthCore: how big each self-drawn window is (percent; Settings > UI > Toolbar)." }; + foreach (var kv in Scales) lines.Add($"{kv.Key}={kv.Value.ToString(CultureInfo.InvariantCulture)}"); + File.WriteAllLines(path, lines); + _fileTime = File.GetLastWriteTimeUtc(path); + } + catch (Exception ex) + { + RynthLog.UI($"PanelDrawScale: could not save {FilePath}: {ex.GetType().Name}: {ex.Message}"); + } + } + } + + // Caller holds Sync. Reads the file again when it changed (another client), looked at every 2 s. + private static void Refresh() + { + long now = Environment.TickCount64; + if (now - _checkedMs < 2000) return; + _checkedMs = now; + try + { + string path = FilePath; + DateTime t = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue; + if (t == _fileTime) return; + _fileTime = t; + Scales.Clear(); + if (t == DateTime.MinValue) return; + foreach (string raw in File.ReadAllLines(path)) + { + string line = raw.Trim(); + if (line.Length == 0 || line.StartsWith('#')) continue; + int eq = line.LastIndexOf('='); + if (eq <= 0 || !int.TryParse(line.AsSpan(eq + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out int p)) continue; + if (p >= Min && p <= Max) Scales[line[..eq].Trim()] = p; + } + } + catch { /* the old values stay */ } + } +} diff --git a/src/RynthCore.Engine/UI/PanelTextScale.cs b/src/RynthCore.Engine/UI/PanelTextScale.cs index c194c98..5d6372a 100644 --- a/src/RynthCore.Engine/UI/PanelTextScale.cs +++ b/src/RynthCore.Engine/UI/PanelTextScale.cs @@ -21,7 +21,7 @@ namespace RynthCore.Engine.UI; internal static class PanelTextScale { /// Picker labels, index = size. - public static readonly string[] SizeNames = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "yourjokin" }; + public static readonly string[] SizeNames = { "100%", "110%", "120%", "130%", "140%", "150%", "160%", "170%", "180%", "190%", "250%" }; private static readonly float[] Scales = { 1.0f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f, 1.6f, 1.7f, 1.8f, 1.9f, 2.5f }; @@ -158,7 +158,7 @@ internal static class PanelTextScale { step = Math.Clamp(step, 0, SizeNames.Length - 1); int pct = (int)MathF.Round(Factor(step) * 100f); - return step == 0 ? "normal (100%)" : $"{SizeNames[step]} ({pct.ToString(CultureInfo.InvariantCulture)}%)"; + return step == 0 ? "normal (100%)" : pct.ToString(CultureInfo.InvariantCulture) + "%"; } /// Font size factor for a size step. diff --git a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs index a7cf1f6..882ed0d 100644 --- a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs @@ -328,7 +328,7 @@ internal static class SettingsPanel case SettingKind.Double: return DoubleRow(row.Label, row.Get!(d), row.Min, row.Max, row.Step, v => Changed(v), row.Tooltip); case SettingKind.Combo: - return ComboRow(row.Label, row.Items!, (int)row.Get!(d), v => Changed(v), picker, row.Tooltip); + return ComboRow(row.Label, row.CurrentItems, (int)row.Get!(d), v => Changed(v), picker, row.Tooltip); case SettingKind.Section: return SectionHeader(row.Label); case SettingKind.Spacer: diff --git a/src/RynthCore.Engine/UI/Sections/PluginWindows.cs b/src/RynthCore.Engine/UI/Sections/PluginWindows.cs index 9a6b6a4..7f9e4b9 100644 --- a/src/RynthCore.Engine/UI/Sections/PluginWindows.cs +++ b/src/RynthCore.Engine/UI/Sections/PluginWindows.cs @@ -101,7 +101,7 @@ internal static class PluginWindows string sig = WindowPlan.Signature(w); if (Live.TryGetValue(title, out Hosted? h) && h.Signature == sig) continue; SectionWindowDecl decl = w; - Func face = () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title); + Func face = () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title, decl.FitHeight, decl.MinWidth); if (takeOvers.Contains(title)) { // An engine panel's place: its key, saved place and open state stay; nothing to reopen. @@ -146,7 +146,20 @@ internal static class PluginWindows : ImGuiPanelHost.HasFace(title) && !Live.ContainsKey(title) ? TitleUse.Other : TitleUse.Free; - private static PanelSpec Spec(SectionWindowDecl w) => new( - new Vector2(w.Width, w.Height), new Vector2(w.MinWidth, w.MinHeight), - EdgeToEdge: w.EdgeToEdge, GripInBody: w.EdgeToEdge); + // A frameless window ("chrome": "none", v90) has no header, a transparent background and no + // border: the plugin paints the whole window and drags it from its own title row. Its resize + // grip sits over the body's bottom-right corner, like the engine's chromeless panels, and shows + // only while the mouse is near it: that corner is the plugin's own content. + private static PanelSpec Spec(SectionWindowDecl w) => w.Frameless + ? new(new Vector2(w.Width, w.Height), new Vector2(w.MinWidth, w.MinHeight), PanelChrome.None, + Background: 0, Rounding: 0f, EdgeToEdge: true, GripOnHover: true, OpenCorner: Corner(w.Corner), DrawScale: w.DrawScale) + : new(new Vector2(w.Width, w.Height), new Vector2(w.MinWidth, w.MinHeight), + EdgeToEdge: w.EdgeToEdge, GripInBody: w.EdgeToEdge, OpenCorner: Corner(w.Corner), DrawScale: w.DrawScale); + + private static PanelCorner Corner(string c) => c switch + { + "topLeft" => PanelCorner.TopLeft, "topRight" => PanelCorner.TopRight, + "bottomLeft" => PanelCorner.BottomLeft, "bottomRight" => PanelCorner.BottomRight, + "top" => PanelCorner.Top, "bottom" => PanelCorner.Bottom, _ => PanelCorner.None, + }; } diff --git a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs index 20fa045..9ecf103 100644 --- a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs +++ b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs @@ -20,7 +20,8 @@ // "windows": [ // { "id": "characters", "title": "Characters", "surface": "window:characters", // "icon": "\uE68E", "width": 420, "height": 260, "minWidth": 280, "minHeight": 140, -// "bar": true, "edgeToEdge": true, "server": "", "takeOver": false } ] +// "bar": true, "edgeToEdge": true, "server": "", "takeOver": false, +// "chrome": "", "fitHeight": false } ] // } // servers servers the plugin knows. A built-in id (ilt, aelrynth) keeps the // engine's own detection; a new id is detected from its lists. @@ -40,6 +41,16 @@ // and the engine's face comes back when the plugin goes. Engines // before that ignore the key and keep their face (the title refused). // "server" set: only while that server is active. docs/PLUGIN_WINDOWS.md. +// v90 (2026-10-21): "chrome": "none" = no header and no background or +// border: the plugin draws the whole window, its own title row included +// (PanelDragWithLastItem moves it), edge to edge. "fitHeight": true = the +// window's height follows the height the plugin's draw asks for +// (RynthPluginRenderEmbed's wantHeight) and its width scales with the +// panel's text size. Engines before v90 ignore both. "corner": +// "bottomRight" (or topLeft, topRight, bottomLeft, top, bottom: centred) = where it first +// opens when nothing is saved for it (v90, 2026-10-22). "scale": "draw" = +// the window draws its content at any size (PanelScale): Ctrl+wheel over +// it steps that size, 30-250%, not its text size (v90, 2026-10-23). // // Everything from a plugin is checked here: ids are short lower-case words, // text is capped, a command must be a single "/..." chat command, and the lists @@ -99,7 +110,15 @@ internal sealed record SectionWindowDecl( bool EdgeToEdge, string Server, // Takes the place of the engine panel with this title while hosted ("takeOver": true). - bool TakeOver = false) + bool TakeOver = false, + // v90: no header, background or border; the plugin draws the whole window ("chrome": "none"). + bool Frameless = false, + // v90: the height follows the plugin's wantHeight; the width scales with the text size ("fitHeight"). + bool FitHeight = false, + // v90: where it first opens with nothing saved: "", "topLeft", "topRight", "bottomLeft", "bottomRight" ("corner"). + string Corner = "", + // v90: it draws its own content at any size, so Ctrl+wheel steps its draw size (PanelScale), not its text ("scale": "draw"). + bool DrawScale = false) { /// For every world, not one server. public bool IsUniversal => Server.Length == 0; @@ -217,7 +236,11 @@ internal static class SectionManifestParser float minHeight = Math.Min(WindowSize(Size(e, "minHeight"), MinWindowSize), height); windows.Add(new SectionWindowDecl(plugin, id, title, surface, Icon(Str(e, "icon")), width, height, minWidth, minHeight, Bool(e, "bar", false), Bool(e, "edgeToEdge", false), server, - Bool(e, "takeOver", false))); + Bool(e, "takeOver", false), + Frameless: Str(e, "chrome").Trim().Equals("none", StringComparison.OrdinalIgnoreCase), + FitHeight: Bool(e, "fitHeight", false), + Corner: Str(e, "corner").Trim() is "topLeft" or "topRight" or "bottomLeft" or "bottomRight" or "top" or "bottom" ? Str(e, "corner").Trim() : "", + DrawScale: Str(e, "scale").Trim().Equals("draw", StringComparison.OrdinalIgnoreCase))); } return new SectionManifest(plugin, servers.ToArray(), sections.ToArray(), contributions.ToArray()) diff --git a/src/RynthCore.Engine/UI/Sections/WindowPlan.cs b/src/RynthCore.Engine/UI/Sections/WindowPlan.cs index c582252..e11fb52 100644 --- a/src/RynthCore.Engine/UI/Sections/WindowPlan.cs +++ b/src/RynthCore.Engine/UI/Sections/WindowPlan.cs @@ -65,5 +65,6 @@ internal static class WindowPlan /// What a hosted window's panel depends on: a change re-registers it. public static string Signature(SectionWindowDecl w) => - string.Join("|", w.Plugin, w.Surface, w.Icon, w.Width, w.Height, w.MinWidth, w.MinHeight, w.Bar, w.EdgeToEdge, w.TakeOver); + string.Join("|", w.Plugin, w.Surface, w.Icon, w.Width, w.Height, w.MinWidth, w.MinHeight, w.Bar, w.EdgeToEdge, w.TakeOver, + w.Frameless, w.FitHeight); } diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 49240ae..3f65f32 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -185,6 +185,20 @@ public struct RynthCoreApiNative public IntPtr GetUiColorFn; // uint GetUiColor(int token) -> ABGR, 0 unknown public IntPtr GetUiFontFn; // void* GetUiFont(int font) -> ImFont*, null unknown / off AC's thread public IntPtr SetPanelOpenFn; // int SetPanelOpen(const char* key, int mode) -> 1 open, 0 closed, -1 no such panel + // v90: plugin windows that draw their own frame ("chrome": "none") + public IntPtr PanelDragWithLastItemFn; // void PanelDragWithLastItem(void): the panel being drawn follows a drag of ImGui's last item + public IntPtr SetPanelPopOutFn; // int SetPanelPopOut(const char* key, int mode) -> 1 popped out, 0 docked, -1 no such open panel + public IntPtr PanelTextSizeFn; // int PanelTextSize(const char* key, int delta) -> text size in % (100..250), -1 no such panel + public IntPtr RenderSettingsDrawerFn; // float RenderSettingsDrawer(const char* key, float width, float room, int flags) -> wanted height, -1 unknown + public IntPtr GetShortcutsFn; // int GetShortcuts(uint* objectIds, uint* spellIds, int max) -> 18, or 0 out of the world + public IntPtr ShortcutActionFn; // int ShortcutAction(int op, int slot, uint objectId) -> 1 queued, 0 refused + public IntPtr GetActionKeysFn; // int GetActionKeys(const char* action, char* buffer, int length) -> bytes needed, -1 bad call + public IntPtr GetIconTextureFn; // void* GetIconTexture(int kind, uint id) -> ImGui texture id, null while it is made + public IntPtr KeyCaptureFn; // int KeyCapture(int op, char* buffer, int length) -> 0 waiting, 1 key (name in buffer), 2 cancelled + public IntPtr SetActionKeyFn; // int SetActionKey(const char* action, const char* key, int op, char* message, int length) + public IntPtr AcPanelFn; // int AcPanel(int id, int op) -> op 0: 1 open, 0 closed, -1 none; else 1 queued, -1 refused + public IntPtr PanelScaleFn; // int PanelScale(const char* key, int percent) -> percent now, 0 = follows the text size + public IntPtr DropTargetFn; // uint DropTarget(const char* window, float x0, y0, x1, y1, int flags, int* dragging) -> dropped object, 0 none } /// diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 8461189..b7b88f2 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -150,6 +150,17 @@ public readonly unsafe struct RynthCoreHost public bool HasUiTheme => _api.Version >= 89 && _api.GetUiColorFn != IntPtr.Zero && _api.GetUiFontFn != IntPtr.Zero; /// v89: (open, close or toggle a panel by its key, a plugin window's title included). public bool HasSetPanelOpen => _api.Version >= 89 && _api.SetPanelOpenFn != IntPtr.Zero; + /// v90: windows that draw their own frame: the manifest's "chrome": "none" and "fitHeight", + /// , , , and the + /// v90 colours (Muted, KeyFace, Hairline, Inset, Faint) and fonts (Dash*, Narrow*). + public bool HasFramelessWindows => _api.Version >= 90 && _api.PanelDragWithLastItemFn != IntPtr.Zero + && _api.SetPanelPopOutFn != IntPtr.Zero && _api.PanelTextSizeFn != IntPtr.Zero; + /// v90: (the dashboard drawers that show Settings rows). + public bool HasSettingsDrawers => _api.Version >= 90 && _api.RenderSettingsDrawerFn != IntPtr.Zero; + /// v90: the player's AC shortcut slots (, ), + /// AC's key bindings () and item pictures (). + public bool HasShortcuts => _api.Version >= 90 && _api.GetShortcutsFn != IntPtr.Zero && _api.ShortcutActionFn != IntPtr.Zero + && _api.GetActionKeysFn != IntPtr.Zero && _api.GetIconTextureFn != IntPtr.Zero; /// v76: (close a corpse or chest like the client's window close). public bool HasCloseContainer => _api.Version >= 76 && _api.CloseContainerFn != IntPtr.Zero; /// v77: , and the UI callbacks @@ -1543,6 +1554,258 @@ public readonly unsafe struct RynthCoreHost return ((delegate* unmanaged[Cdecl])_api.SetPanelOpenFn)(p, (int)mode); } + /// + /// v90: while ImGui's last item is held and dragged, the panel being drawn follows the mouse (a + /// frameless window's own title row: call it right after that row's InvisibleButton). Docked, the + /// window moves within the game view; popped out, its OS window. Only from RynthPluginRenderEmbed + /// on AC's render thread; does nothing elsewhere or on an older engine. + /// + public void PanelDragWithLastItem() + { + if (!HasFramelessWindows) return; + ((delegate* unmanaged[Cdecl])_api.PanelDragWithLastItemFn)(); + } + + /// + /// v90: pops the open panel out into its own window, docks it back, toggles, + /// or asks. Returns 1 popped out / 0 docked afterwards (the change lands on the next frame), -1 for + /// no such open panel or an older engine. Any thread. + /// + public int SetPanelPopOut(string key, RynthPanelPopOut mode) => CallWithKey(_api.SetPanelPopOutFn, key, (int)mode); + + /// + /// v90: steps the panel 's text size by (0 = just ask) + /// and returns it as a percentage of normal (100 to 250); -1 for no such panel or an older engine. + /// The fonts re-bake a moment later. Any thread. + /// + public int PanelTextSize(string key, int delta) => CallWithKey(_api.PanelTextSizeFn, key, delta); + + /// + /// 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 + /// 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. + /// + public int PanelScale(string key, int percent = 0) => + _api.Version >= 90 && _api.PanelScaleFn != IntPtr.Zero ? CallWithKey(_api.PanelScaleFn, key, percent) : -1; + + /// + /// v90: draws the body of one of the dashboard drawers that show Settings rows, which are still + /// RynthCore's (the Settings panel hasn't moved to RynthAi): "ranges" (the selected monster and the + /// key ranges), "patrol" (the Dungeon Patrol settings, hazards and routes) or "pinned" (My settings; + /// opens its list of settings to pin). At ImGui's cursor in the window + /// being drawn, pixels wide and at most tall (0 = its + /// own height). Returns the height it wants (pixels), or -1 for another key, an older engine, or a + /// call outside a docked window's RynthPluginRenderEmbed on AC's render thread. + /// + public float RenderSettingsDrawer(string key, float width, float room, bool openPinList = false) + { + if (!HasSettingsDrawers || string.IsNullOrEmpty(key) || key.Length > 64) return -1f; + Span utf8 = stackalloc byte[260]; + int n = System.Text.Encoding.UTF8.GetBytes(key, utf8[..^1]); + utf8[n] = 0; + fixed (byte* p = utf8) + return ((delegate* unmanaged[Cdecl])_api.RenderSettingsDrawerFn)(p, width, room, openPinList ? 1 : 0); + } + + /// + /// v90: the player's 18 shortcut slots (AC's own: what the retail toolbar shows and its keys + /// use): each slot's object id (0 = empty) and spell id. Returns 18, or 0 out of the world or on + /// an older engine. Any thread. + /// + public int GetShortcuts(Span objectIds, Span spellIds) + { + if (!HasShortcuts) return 0; + int max = Math.Min(objectIds.Length, spellIds.Length); + fixed (uint* o = objectIds) + fixed (uint* s = spellIds) + return ((delegate* unmanaged[Cdecl])_api.GetShortcutsFn)(o, s, max); + } + + /// + /// v90: uses shortcut slot (0-17) as its key would, puts + /// in it, or empties it: through the retail toolbar's own functions + /// on AC's game thread, so the server, the retail toolbar and the keys all follow. True when + /// queued. Any thread. + /// + public bool ShortcutAction(RynthShortcutOp op, int slot, uint objectId = 0) + { + if (!HasShortcuts) return false; + return ((delegate* unmanaged[Cdecl])_api.ShortcutActionFn)((int)op, slot, objectId) == 1; + } + + /// + /// v90: AC's keys for keymap action (e.g. "UseQuickSlot_1") as the player + /// reads them, "1, Ctrl+1", or the engine hotkeys running a chat command ("/rdef use 2"); "" when + /// unbound, unknown, or on an older engine. Any thread. + /// + public string GetActionKeys(string action) + { + if (!HasShortcuts || string.IsNullOrEmpty(action) || action.Length > 64) return string.Empty; + Span name = stackalloc byte[260]; + int n = System.Text.Encoding.UTF8.GetBytes(action, name[..^1]); + name[n] = 0; + Span text = stackalloc byte[256]; + int len; + fixed (byte* a = name) + fixed (byte* t = text) + len = ((delegate* unmanaged[Cdecl])_api.GetActionKeysFn)(a, t, text.Length); + if (len <= 0) return string.Empty; + return System.Text.Encoding.UTF8.GetString(text[..Math.Min(len, text.Length - 1)]); + } + + /// + /// v90: an item's (kind Object: its icon with underlay and overlay), a spell's or an icon id's + /// picture as an ImGui texture id for ImGui.Image; IntPtr.Zero while it is being made (ask again + /// next frame). AC's render thread, inside a docked window's draw. + /// + public IntPtr GetIconTexture(RynthIconKind kind, uint id) + { + if (!HasShortcuts || id == 0) return IntPtr.Zero; + return ((delegate* unmanaged[Cdecl])_api.GetIconTextureFn)((int)kind, id); + } + + /// v90: changing keys: ("press a key") and . + public bool HasKeyBinding => _api.Version >= 90 && _api.KeyCaptureFn != IntPtr.Zero && _api.SetActionKeyFn != IntPtr.Zero; + + /// + /// v90: waits for the next key the player presses (with Ctrl/Alt/Shift held); it never reaches AC, and + /// Esc cancels. Ask with each frame. AC's main thread (a window's draw). + /// + public void BeginKeyCapture() + { + if (HasKeyBinding) ((delegate* unmanaged[Cdecl])_api.KeyCaptureFn)(0, null, 0); + } + + /// v90: stops waiting for a key. + public void CancelKeyCapture() + { + if (HasKeyBinding) ((delegate* unmanaged[Cdecl])_api.KeyCaptureFn)(2, null, 0); + } + + /// + /// v90: the key capture: still waiting (: why the last key couldn't be taken, or + /// ""), pressed (: its name, "Ctrl+F5") or cancelled. AC's main thread. + /// + public RynthKeyCapture PollKeyCapture(out string text) + { + text = string.Empty; + if (!HasKeyBinding) return RynthKeyCapture.Cancelled; + Span buf = stackalloc byte[128]; + int r; + fixed (byte* b = buf) + r = ((delegate* unmanaged[Cdecl])_api.KeyCaptureFn)(1, b, buf.Length); + int n = buf.IndexOf((byte)0); + text = System.Text.Encoding.UTF8.GetString(buf[..(n < 0 ? buf.Length : n)]); + return r switch { 1 => RynthKeyCapture.Pressed, 0 => RynthKeyCapture.Waiting, _ => RynthKeyCapture.Cancelled }; + } + + /// + /// v90: what binding ("Ctrl+F5") to would take from + /// others. The action is AC's keymap action ("UseQuickSlot_5": AC's own keys, the retail toolbar's) or a + /// chat command for an engine hotkey ("/rdef use 2"). names what has the key + /// now, or why it can't be bound. Any thread. + /// + public RynthKeyCheck CheckActionKey(string action, string key, out string message) => + (RynthKeyCheck)Math.Clamp(CallSetActionKey(action, key, 0, out message), -1, 1); + + /// + /// v90: binds to (see ): it + /// comes off everything else that had it, in AC's keymap and RynthCore's hotkeys, and every running + /// client follows within a second. Done on AC's game thread; the result goes to chat. False (why in + /// ) when it can't be. Any thread. + /// + public bool BindActionKey(string action, string key, out string message) => CallSetActionKey(action, key, 1, out message) == 1; + + /// + /// v90: removes from ; the key may be one of the names + /// gave ("Ctrl+1", "Mouse4"). Queued like . + /// + public bool UnbindActionKey(string action, string key, out string message) => CallSetActionKey(action, key, 2, out message) == 1; + + /// v90: items dragged out of AC's UI can be dropped on a plugin window (). + public bool HasDropTargets => _api.Version >= 90 && _api.DropTargetFn != IntPtr.Zero; + + /// + /// v90: the plugin window (its panel title) takes items dragged out of AC's + /// UI (a pack, the inventory) and let go over - (ImGui + /// screen coordinates). Call it every frame the window draws; false = + /// drawn but a drop isn't wanted now (it goes to AC as usual). A drop taken never reaches AC: the item + /// stays where it was. Returns the object dropped since the last call (0 = none); + /// : an item is being dragged now. AC's main thread, in the window's draw. + /// + public uint DropTarget(string window, System.Numerics.Vector2 min, System.Numerics.Vector2 max, bool accepting, out bool dragging) + { + dragging = false; + if (!HasDropTargets || string.IsNullOrEmpty(window) || window.Length > 64) return 0; + Span utf8 = stackalloc byte[260]; + int n = System.Text.Encoding.UTF8.GetBytes(window, utf8[..^1]); + utf8[n] = 0; + int drag = 0; + uint item; + fixed (byte* p = utf8) + item = ((delegate* unmanaged[Cdecl])_api.DropTargetFn)( + p, min.X, min.Y, max.X, max.Y, accepting ? 1 : 0, &drag); + dragging = drag != 0; + return item; + } + + /// v90: AC's own panels (, ). + public bool HasAcPanels => _api.Version >= 90 && _api.AcPanelFn != IntPtr.Zero; + + /// + /// v90: whether AC's panel is open: true, false, or null when this client has no such panel or the + /// engine can't tell. AC's main thread (a window's draw); cheap to ask every frame. + /// + public bool? IsAcPanelOpen(RynthAcPanel panel) + { + if (!HasAcPanels) return null; + int r = ((delegate* unmanaged[Cdecl])_api.AcPanelFn)((int)panel, 0); + return r < 0 ? null : r == 1; + } + + /// + /// v90: opens, closes or toggles AC's own panel, the way AC's toolbar buttons and keys do (one main + /// panel shows at a time, as in AC). Done on AC's game thread; true when queued. Any thread. + /// + public bool AcPanel(RynthAcPanel panel, RynthAcPanelOp op = RynthAcPanelOp.Toggle) + { + if (!HasAcPanels) return false; + return ((delegate* unmanaged[Cdecl])_api.AcPanelFn)((int)panel, (int)op) == 1; + } + + private int CallSetActionKey(string action, string key, int op, out string message) + { + message = string.Empty; + if (!HasKeyBinding) { message = "This RynthCore can't change keys."; return -1; } + if (string.IsNullOrEmpty(action) || action.Length > 64 || string.IsNullOrEmpty(key) || key.Length > 40) { message = "No action or key."; return -1; } + Span a = stackalloc byte[260]; + Span k = stackalloc byte[164]; + Span msg = stackalloc byte[512]; + int an = System.Text.Encoding.UTF8.GetBytes(action, a[..^1]); + a[an] = 0; + int kn = System.Text.Encoding.UTF8.GetBytes(key, k[..^1]); + k[kn] = 0; + int r; + fixed (byte* ap = a) + fixed (byte* kp = k) + fixed (byte* mp = msg) + r = ((delegate* unmanaged[Cdecl])_api.SetActionKeyFn)(ap, kp, op, mp, msg.Length); + int n = msg.IndexOf((byte)0); + message = System.Text.Encoding.UTF8.GetString(msg[..(n < 0 ? msg.Length : n)]); + return r; + } + + private int CallWithKey(IntPtr fn, string key, int arg) + { + if (!HasFramelessWindows || fn == IntPtr.Zero || string.IsNullOrEmpty(key) || key.Length > 64) return -1; + Span utf8 = stackalloc byte[260]; + int n = System.Text.Encoding.UTF8.GetBytes(key, utf8[..^1]); + utf8[n] = 0; + fixed (byte* p = utf8) + return ((delegate* unmanaged[Cdecl])fn)(p, arg); + } + public bool InvokeChatParser(string text) { if (_api.InvokeChatParserFn == IntPtr.Zero || string.IsNullOrEmpty(text)) diff --git a/src/RynthCore.PluginSdk/UiKitTypes.cs b/src/RynthCore.PluginSdk/UiKitTypes.cs index 5195d9d..7821ed1 100644 --- a/src/RynthCore.PluginSdk/UiKitTypes.cs +++ b/src/RynthCore.PluginSdk/UiKitTypes.cs @@ -20,6 +20,16 @@ public enum RynthUiColor /// Fixed, whatever the theme: good / bad. Green = 16, Red = 17, TitleBar = 18, WindowBorder = 19, + /// v90: the theme's own muted text ( is a lighter mix of it and the text). + Muted = 20, + /// v90, the instrument look (worked out from the theme's eight colours): a key's face, a step up from the background. + KeyFace = 21, + /// v90: hairlines and key borders. + Hairline = 22, + /// v90: inset wells (an activity line, bar tracks), darker than the background. + Inset = 23, + /// v90: faint text (units, secondary numbers). + Faint = 24, } /// A font the engine bakes (RynthCoreHost.GetUiFont): sizes in pixels at 100% text size. @@ -30,6 +40,12 @@ public enum RynthUiFont Ui11 = 2, Ui14 = 3, Ui18 = 4, UiBold11 = 5, UiBold14 = 6, Mono9 = 7, Mono10 = 8, Mono12 = 9, Chat10 = 10, Chat12 = 11, Chat14 = 12, + /// v90: Cascadia Mono (Consolas without it): numbers that line up. + Dash9 = 13, Dash10 = 14, Dash11 = 15, Dash14 = 16, + /// v90: Barlow Semi Condensed SemiBold, narrow labels. + Narrow9 = 17, Narrow10 = 18, Narrow11 = 19, + /// v90: Barlow Semi Condensed Bold. + NarrowBold11 = 20, NarrowBold13 = 21, } /// What RynthCoreHost.SetPanelOpen does. @@ -37,3 +53,90 @@ public enum RynthPanelOpen { Ask = -1, Close = 0, Open = 1, Toggle = 2, } + +/// What RynthCoreHost.SetPanelPopOut does (v90). +public enum RynthPanelPopOut +{ + Ask = -1, Dock = 0, PopOut = 1, Toggle = 2, +} + +/// What RynthCoreHost.ShortcutAction does to an AC shortcut slot (v90). +public enum RynthShortcutOp +{ + Use = 0, Set = 1, Clear = 2, +} + +/// What RynthCoreHost.GetIconTexture draws (v90). +public enum RynthIconKind +{ + /// An icon (0x06 texture) id. + Icon = 0, + /// An object id: the item's icon with its underlay and overlay. + Object = 1, + /// A spell id: the spell's icon. + Spell = 2, +} + +/// Where RynthCoreHost.PollKeyCapture is (v90). +public enum RynthKeyCapture +{ + /// Still waiting for a key (the text, if any, says why the last one couldn't be taken). + Waiting = 0, + /// A key was pressed: its name ("Ctrl+F5") is the text. + Pressed = 1, + /// Esc, the time ran out, or it was stopped. + Cancelled = 2, +} + +/// +/// AC's own panels for RynthCoreHost.AcPanel (v90): the ids AC's panel notice uses +/// (CM_UI::SendNotice_SetPanelVisibility), read from the client 2026-10-22. +/// +public enum RynthAcPanel +{ + /// Book (gmBookUI). + Book = 2, + /// Character information: titles, birth, deaths (gmCharacterInfoUI). + CharacterInfo = 3, + /// Beneficial spells in effect. + HelpfulSpells = 4, + /// Harmful spells in effect. + HarmfulSpells = 5, + /// The pack: paper doll and backpack (gmInventoryUI). + Inventory = 7, + /// Link status. + LinkStatus = 8, + /// Options: gameplay and configuration (gmGameplayOptionsUI, gmConfigUI). + Options = 10, + /// Attributes and skills (gmAttributeUI, gmSkillUI). + Character = 11, + /// Allegiance, fellowship, friends and squelch, one tabbed panel. + Social = 12, + /// The spellbook and spell components (gmSpellbookUI). + Spellbook = 13, + /// Urgent assistance (help). + Help = 14, + /// Vitae. + Vitae = 15, + /// The map (gmMapUI). + Map = 16, + /// Contracts, journal and page list (quests). + Quests = 25, +} + +/// What RynthCoreHost.AcPanel does (v90). +public enum RynthAcPanelOp +{ + Toggle = 1, Open = 2, Close = 3, +} + +/// What RynthCoreHost.CheckActionKey found (v90). +public enum RynthKeyCheck +{ + /// The key can't be bound to it (the message says why). + Invalid = -1, + /// Nothing else uses the key. + Free = 0, + /// Binding it takes it from what the message names. + Taken = 1, +} diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index 8a56d05..d61c8bd 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -36,7 +36,7 @@ - 89 + 90 88 <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true diff --git a/tools/FlightRecorderTests/Program.cs b/tools/FlightRecorderTests/Program.cs index a383371..388a1f1 100644 --- a/tools/FlightRecorderTests/Program.cs +++ b/tools/FlightRecorderTests/Program.cs @@ -924,11 +924,18 @@ internal static unsafe class Program fixed (byte* p = d) { for (int i = 0; i < 2000; i++) c.OnDatagram(outbound, p, d.Length); // warm up - long before = GC.GetAllocatedBytesForCurrentThread(); - long t0 = Stopwatch.GetTimestamp(); - for (int i = 0; i < n; i++) c.OnDatagram(outbound, p, d.Length); - long ticks = Stopwatch.GetTimestamp() - t0; - long alloc = GC.GetAllocatedBytesForCurrentThread() - before; + // Up to three tries, the fewest bytes counted: a one-off allocation on this thread inside + // the timed loop (tiered JIT settling: 5296 bytes in one of four runs, 2026-10-23) is not + // the hot path's. An allocation per datagram shows in every try (n of them). + long alloc = long.MaxValue, ticks = 0; + for (int attempt = 0; attempt < 3 && alloc != 0; attempt++) + { + long before = GC.GetAllocatedBytesForCurrentThread(); + long t0 = Stopwatch.GetTimestamp(); + for (int i = 0; i < n; i++) c.OnDatagram(outbound, p, d.Length); + ticks = Stopwatch.GetTimestamp() - t0; + alloc = Math.Min(alloc, GC.GetAllocatedBytesForCurrentThread() - before); + } double ns = ticks * 1e9 / Stopwatch.Frequency / n; Console.WriteLine($" {what,-44} {ns,7:0} ns/datagram, {alloc} bytes allocated over {n}"); _case = "cost"; diff --git a/tools/KeymapTests/KeymapTests.csproj b/tools/KeymapTests/KeymapTests.csproj new file mode 100644 index 0000000..d5abf98 --- /dev/null +++ b/tools/KeymapTests/KeymapTests.csproj @@ -0,0 +1,27 @@ + + + + + Exe + net10.0 + enable + enable + true + KeymapTests + + + + + + + + diff --git a/tools/KeymapTests/Program.cs b/tools/KeymapTests/Program.cs new file mode 100644 index 0000000..21da86b --- /dev/null +++ b/tools/KeymapTests/Program.cs @@ -0,0 +1,296 @@ +// Offline checks for AcKeymapText (see KeymapTests.csproj). +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Hotkeys; + +namespace KeymapTests; + +internal static class Program +{ + private static int _failed, _passed; + + private static void Check(bool ok, string what) + { + if (ok) { _passed++; return; } + _failed++; + Console.WriteLine("FAIL: " + what); + } + + private static void Eq(T actual, T expected, string what) => + Check(EqualityComparer.Default.Equals(actual, expected), $"{what}: got '{actual}', expected '{expected}'"); + + // The shape AC writes (CRLF, two-space groups, four-space bindings), cut down. + private static readonly string Sample = string.Join("\r\n", new[] + { + "#Asheron's Call: Throne of Destiny Keymap File", + "\"User Defined Keymap\" [ 0000003B-02D0-0000-4002-000016000000 ]", + "", + "Devices", + "[", + " Keyboard [ GUID_SysKeyboard ]", + " Mouse [ GUID_SysMouse ]", + "]", + "", + "MetaKeys", + "[", + " 1 [ 0 DIK_LSHIFT ]", + " 2 [ 0 DIK_LCONTROL ]", + " 2 [ 0 DIK_RCONTROL ]", + " 3 [ 0 DIK_LMENU ]", + " 3 [ 0 DIK_RALT ]", + " 5 [ 1 DIMOFS_BUTTON3 ]", + "]", + "", + "Bindings", + "[", + " MovementCommands", + " [", + " MovementForward [ \"\" [ 0 DIK_W ] ]", + " MovementForward [ \"\" [ 0 DIK_UPARROW ] ]", + " ]", + "", + " UICommands", + " [", + " ToggleSpellbookPanel [ \"\" [ 0 DIK_F5 ] ]", + " ToggleOptionsPanel [ \"\" [ 0 DIK_F11 ] ]", + " TogglePluginManager [ \"\" [ 0 DIK_F1 ] 0x00000003 ]", + " ]", + "", + " QuickslotCommands", + " [", + " UseQuickSlot_1 [ \"\" [ 0 DIK_1 ] ]", + " UseQuickSlot_5 [ \"\" [ 0 DIK_5 ] ]", + " UseQuickSlot_14 [ \"\" [ 0 DIK_5 ] 0x00000004 ]", + " CreateShortcut [ \"\" [ 0 DIK_0 ] ]", + " UseQuickSlot_1 [ \"\" [ 0 DIK_1 ] 0x00000002 ]", + " ]", + "", + " ToggleChatEntry", + "", + " MouseCommands", + " [", + " SelectLeft [ \"\" [ 1 DIMOFS_BUTTON0 ] ]", + " ]", + "", + " EditControls", + " [", + " CursorStartOfLine [ \"\" [ 0 DIK_HOME ] ]", + " CursorPreviousPage [ \"\" [ 0 DIK_PGUP ] ]", + " ]", + "", + " CopyAndPasteControls", + " [", + " CopyText [ \"\" [ 0 DIK_C ] 0x00000002 ]", + " ]", + "]", + "", + }); + + private static List Lines(string text = "") => AcKeymapText.Split(text.Length > 0 ? text : Sample, out _); + + private static List Of(List lines, string action) => + AcKeymapText.Bindings(lines).FindAll(l => l.Action == action); + + private static int Main() + { + Reading(); + Names(); + Meta(); + BindTakes(); + BindKeepsTextGroups(); + BindAlready(); + BindNewSlot(); + BindMissingGroup(); + BindEmptyGroup(); + BindUnknownAction(); + Unbind(); + RoundTrip(); + Describe(); + RealFile(); + Console.WriteLine($"{_passed} passed, {_failed} failed."); + return _failed == 0 ? 0 : 1; + } + + private static void Reading() + { + List lines = Lines(); + List all = AcKeymapText.Bindings(lines); + Eq(all.Count, 14, "binding lines read"); + List slot1 = Of(lines, "UseQuickSlot_1"); + Eq(slot1.Count, 2, "UseQuickSlot_1 lines"); + Check(slot1.TrueForAll(l => l.Group == "QuickslotCommands"), "UseQuickSlot_1 in QuickslotCommands"); + Eq(slot1[1].Meta, 2u, "Ctrl+1's mask"); + Eq(Of(lines, "MovementForward")[1].Dik, "DIK_UPARROW", "an alias read as its one name"); + Eq(Of(lines, "SelectLeft")[0].Device, 1, "the mouse is device 1"); + Eq(Of(lines, "CursorPreviousPage")[0].Group, "EditControls", "group after an empty group"); + Eq(AcKeymapText.Uses(lines, 0, "DIK_F5", 0).Count, 1, "F5 used once"); + Eq(AcKeymapText.Uses(lines, 0, "DIK_HOME", 0).Count, 0, "Home in a text group isn't a game use"); + Eq(AcKeymapText.Uses(lines, 0, "DIK_5", 4).Count, 1, "Alt+5 used"); + } + + private static void Names() + { + Eq(AcKeymapText.DikForVk('A'), "DIK_A", "A"); + Eq(AcKeymapText.DikForVk('7'), "DIK_7", "7"); + Eq(AcKeymapText.DikForVk(0x7A), "DIK_F11", "F11"); + Eq(AcKeymapText.DikForVk(0x7E), "DIK_F15", "F15"); + Eq(AcKeymapText.DikForVk(0x7F), (string?)null, "F16: AC has none"); + Eq(AcKeymapText.DikForVk(0x21), "DIK_PGUP", "PageUp as AC writes it"); + Eq(AcKeymapText.DikForVk(0x26), "DIK_UPARROW", "Up as AC writes it"); + Eq(AcKeymapText.DikForVk(0x65), "DIK_NUMPAD5", "Num5"); + Eq(AcKeymapText.DikForVk(0x6A), "DIK_NUMPADSTAR", "Num*"); + Eq(AcKeymapText.DikForVk(0xC0), "DIK_GRAVE", "`"); + Eq(AcKeymapText.Canonical("dik_prior"), "DIK_PGUP", "PRIOR is PGUP"); + Eq(AcKeymapText.Canonical("DIK_UP"), "DIK_UPARROW", "UP is UPARROW"); + Eq(AcKeymapText.Canonical("DIK_LEFTARROW"), "DIK_LEFT", "LEFTARROW is LEFT"); + Eq(AcKeymapText.Canonical("DIK_F3"), "DIK_F3", "a plain name"); + } + + private static void Meta() + { + List lines = Lines(); + Check(AcKeymapText.TryMeta(lines, HotkeyMods.None, out uint m0, out _) && m0 == 0, "no modifiers: 0"); + Check(AcKeymapText.TryMeta(lines, HotkeyMods.Ctrl, out uint m1, out _) && m1 == 2, "Ctrl: 0x2"); + Check(AcKeymapText.TryMeta(lines, HotkeyMods.Alt, out uint m2, out _) && m2 == 4, "Alt: 0x4 (metakey 3)"); + Check(AcKeymapText.TryMeta(lines, HotkeyMods.Ctrl | HotkeyMods.Shift, out uint m3, out _) && m3 == 3, "Ctrl+Shift: 0x3"); + List noAlt = Lines(Sample.Replace(" 3 [ 0 DIK_LMENU ]\r\n", "").Replace(" 3 [ 0 DIK_RALT ]\r\n", "")); + Check(!AcKeymapText.TryMeta(noAlt, HotkeyMods.Alt, out _, out string err) && err.Contains("Alt"), "no Alt metakey: an error naming it"); + } + + private static void BindTakes() + { + List lines = Lines(); + Check(AcKeymapText.Bind(lines, "UseQuickSlot_10", 0, "DIK_F11", 0, out var taken, out _), "bind slot 10 to F11"); + Eq(taken.Count, 1, "one action had F11"); + Eq(taken.Count > 0 ? taken[0].Action : "", "ToggleOptionsPanel", "taken from Options"); + Eq(Of(lines, "ToggleOptionsPanel").Count, 0, "Options lost F11"); + List s10 = Of(lines, "UseQuickSlot_10"); + Check(s10.Count == 1 && s10[0].Group == "QuickslotCommands" && s10[0].Dik == "DIK_F11" && s10[0].Meta == 0, "slot 10 has F11 in QuickslotCommands"); + Check(s10.Count == 1 && lines[s10[0].Index] == " UseQuickSlot_10 [ \"\" [ 0 DIK_F11 ] ]", "written as AC writes it: " + (s10.Count == 1 ? lines[s10[0].Index] : "")); + // Taking Ctrl+1 for slot 2: only the Ctrl one goes. + Check(AcKeymapText.Bind(lines, "UseQuickSlot_2", 0, "DIK_1", 2, out taken, out _), "bind slot 2 to Ctrl+1"); + Check(taken.Count == 1 && taken[0].Action == "UseQuickSlot_1" && taken[0].Meta == 2, "Ctrl+1 taken from slot 1"); + List s1 = Of(lines, "UseQuickSlot_1"); + Check(s1.Count == 1 && s1[0].Meta == 0, "slot 1 keeps plain 1"); + List s2 = Of(lines, "UseQuickSlot_2"); + Check(s2.Count == 1 && lines[s2[0].Index].EndsWith("[ 0 DIK_1 ] 0x00000002 ]"), "slot 2 has Ctrl+1"); + // An alias in the file is the same key: PRIOR takes PGUP's other game use, not EditControls'. + Check(AcKeymapText.Bind(lines, "UseQuickSlot_3", 0, "DIK_PRIOR", 0, out taken, out _) && taken.Count == 0, "PgUp: only a text group has it"); + Eq(Of(lines, "CursorPreviousPage").Count, 1, "the chat box keeps PgUp"); + } + + private static void BindKeepsTextGroups() + { + List lines = Lines(); + Check(AcKeymapText.Bind(lines, "UseQuickSlot_4", 0, "DIK_C", 2, out var taken, out _), "bind slot 4 to Ctrl+C"); + Eq(taken.Count, 0, "Ctrl+C isn't taken from copy"); + Eq(Of(lines, "CopyText").Count, 1, "copy keeps Ctrl+C"); + Check(AcKeymapText.Bind(lines, "UseQuickSlot_6", 0, "DIK_HOME", 0, out _, out _), "bind slot 6 to Home"); + Eq(Of(lines, "CursorStartOfLine").Count, 1, "the chat box keeps Home"); + } + + private static void BindAlready() + { + List lines = Lines(); + int before = lines.Count; + Check(AcKeymapText.Bind(lines, "UseQuickSlot_5", 0, "DIK_5", 0, out var taken, out _) && taken.Count == 0, "slot 5 already has 5"); + Eq(lines.Count, before, "nothing added"); + Eq(Of(lines, "UseQuickSlot_5").Count, 1, "still one line"); + } + + private static void BindNewSlot() + { + List lines = Lines(); + Check(AcKeymapText.Bind(lines, "UseQuickSlot_12", 0, "DIK_F12", 0, out _, out _), "slot 12, no line yet"); + List s = Of(lines, "UseQuickSlot_12"); + Check(s.Count == 1 && s[0].Group == "QuickslotCommands", "goes in QuickslotCommands"); + // At the end of the group, before its ']'. + Check(s.Count == 1 && lines[s[0].Index + 1].Trim() == "]", "at the group's end"); + // A second key goes right after the slot's own line. + Check(AcKeymapText.Bind(lines, "UseQuickSlot_12", 0, "DIK_F12", 1, out _, out _), "slot 12, Shift+F12 too"); + s = Of(lines, "UseQuickSlot_12"); + Check(s.Count == 2 && s[1].Index == s[0].Index + 1, "next to the first"); + } + + private static void BindMissingGroup() + { + string text = Sample.Replace(" QuickslotCommands\r\n [\r\n", " OldSlots\r\n [\r\n"); + List lines = Lines(text); + // The slot's existing lines are in OldSlots: a new key goes beside them. + Check(AcKeymapText.Bind(lines, "UseQuickSlot_1", 0, "DIK_F3", 0, out _, out _), "slot 1 beside its lines"); + Check(Of(lines, "UseQuickSlot_1").TrueForAll(l => l.Group == "OldSlots"), "stays in its group"); + // A slot with no line and no QuickslotCommands: the group is made at the end of Bindings. + Check(AcKeymapText.Bind(lines, "UseQuickSlot_9", 0, "DIK_9", 0, out _, out _), "slot 9, no group"); + List s9 = Of(lines, "UseQuickSlot_9"); + Check(s9.Count == 1 && s9[0].Group == "QuickslotCommands", "QuickslotCommands made"); + Eq(AcKeymapText.Bindings(lines).Count, 16, "every line still read"); + } + + private static void BindEmptyGroup() + { + // ToggleChatEntry is a name with no [ ] block: a binding there gets one. + string text = Sample.Replace(" QuickslotCommands", " QuickslotCommandsX").Replace(" ToggleChatEntry", " QuickslotCommands"); + List lines = Lines(text); + Check(AcKeymapText.Bind(lines, "UseQuickSlot_11", 0, "DIK_F2", 0, out _, out _), "bind into an empty group"); + List s = Of(lines, "UseQuickSlot_11"); + Check(s.Count == 1 && s[0].Group == "QuickslotCommands", "in the empty group, now with a block"); + Eq(Of(lines, "SelectLeft").Count, 1, "the next group still read"); + } + + private static void BindUnknownAction() + { + List lines = Lines(); + int before = lines.Count; + Check(!AcKeymapText.Bind(lines, "SomeNewAction", 0, "DIK_F7", 0, out _, out string err) && err.Length > 0, "no group for an unknown action"); + Eq(lines.Count, before, "nothing changed"); + } + + private static void Unbind() + { + List lines = Lines(); + Check(AcKeymapText.Unbind(lines, "UseQuickSlot_1", 0, "DIK_1", 2), "Ctrl+1 off slot 1"); + List s1 = Of(lines, "UseQuickSlot_1"); + Check(s1.Count == 1 && s1[0].Meta == 0, "plain 1 stays"); + Check(!AcKeymapText.Unbind(lines, "UseQuickSlot_1", 0, "DIK_1", 2), "again: nothing to remove"); + Check(AcKeymapText.Unbind(lines, "MovementForward", 0, "DIK_UP", 0), "by an alias"); + Eq(Of(lines, "MovementForward").Count, 1, "W stays"); + } + + private static void RoundTrip() + { + List lines = AcKeymapText.Split(Sample, out string nl); + Eq(nl, "\r\n", "CRLF kept"); + Eq(AcKeymapText.Join(lines, nl), Sample, "split and join give the same text"); + List lf = AcKeymapText.Split(Sample.Replace("\r\n", "\n"), out string nl2); + Eq(nl2, "\n", "LF kept"); + Eq(lf.Count, lines.Count, "same lines either way"); + Eq(AcKeymapText.Format("UseQuickSlot_1", 0, "DIK_1", 2), "UseQuickSlot_1 [ \"\" [ 0 DIK_1 ] 0x00000002 ]", "a line with a mask"); + Eq(AcKeymapText.Format("UseQuickSlot_1", 0, "DIK_1", 0), "UseQuickSlot_1 [ \"\" [ 0 DIK_1 ] ]", "a line without"); + } + + private static void Describe() + { + Eq(AcKeymapText.Describe("UseQuickSlot_5"), "shortcut slot 5", "a slot"); + Eq(AcKeymapText.Describe("ToggleSpellbookPanel"), "Toggle Spellbook Panel", "camel case"); + Eq(AcKeymapText.Describe("AltF4"), "Alt F4", "a key name"); + Eq(AcKeymapText.Describe("LOGOUT"), "LOGOUT", "all capitals"); + } + + private static void RealFile() + { + string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Asheron's Call", "Normal.keymap"); + if (!File.Exists(path)) { Console.WriteLine("(no Normal.keymap here: the real-file case is skipped)"); return; } + string text = File.ReadAllText(path); + List lines = AcKeymapText.Split(text, out string nl); + Eq(AcKeymapText.Join(lines, nl), text, "the real file round trips"); + int count = AcKeymapText.Bindings(lines).Count; + Check(count > 50, $"the real file's bindings read ({count})"); + Check(Of(lines, "UseQuickSlot_1").Count >= 1, "the real file has slot 1"); + Check(AcKeymapText.TryMeta(lines, HotkeyMods.Ctrl, out uint ctrl, out _) && ctrl != 0, "the real file has Ctrl"); + // In memory only: slot 10 to F11 takes it from whatever has it, and every other line is still read. + int had = AcKeymapText.Uses(lines, 0, "DIK_F11", 0).Count; + Check(AcKeymapText.Bind(lines, "UseQuickSlot_10", 0, "DIK_F11", 0, out var taken, out _), "real file: bind slot 10 to F11"); + Eq(taken.Count, had, "real file: F11 taken from all its game uses"); + Eq(AcKeymapText.Bindings(lines).Count, count - had + 1, "real file: one line in, the taken ones out"); + Eq(AcKeymapText.Uses(lines, 0, "DIK_F11", 0).Count, 1, "real file: F11 does one thing now"); + } +} diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index 04631d5..5b75278 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -601,11 +601,12 @@ internal static class Program Eq((int)Marshal.OffsetOf(f.Name), (int)Marshal.OffsetOf(f.Name), "TrainingEntryNative." + f.Name + " offset"); Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); - // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v89 follow). - var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(11).TakeLast(6).ToArray(); + // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v90 follow: + // eleven slots to v89, then v90's thirteen). + var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(24).TakeLast(6).ToArray(); Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }), "v79, v80 then v81 slots last: " + string.Join(",", names)); - var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(11).TakeLast(6).ToArray(); + var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(24).TakeLast(6).ToArray(); Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order"); } @@ -614,8 +615,21 @@ internal static class Program // order on both sides, and the same size. private static void ContainerOrderSlots() { - var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray(); - var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray(); + var all = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray(); + var sdkAll = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray(); + // v90: the frameless-window slots and the settings drawers end the table; the checks after these + // are on the table before them. + string[] v90 = { "PanelDragWithLastItemFn", "SetPanelPopOutFn", "PanelTextSizeFn", "RenderSettingsDrawerFn", + "GetShortcutsFn", "ShortcutActionFn", "GetActionKeysFn", "GetIconTextureFn", "KeyCaptureFn", "SetActionKeyFn", "AcPanelFn", "PanelScaleFn", "DropTargetFn" }; + Check(all.TakeLast(v90.Length).SequenceEqual(v90), "v90 slots last: " + string.Join(",", all.TakeLast(v90.Length))); + Check(sdkAll.TakeLast(v90.Length).SequenceEqual(v90), "SDK v90 slots last: " + string.Join(",", sdkAll.TakeLast(v90.Length))); + foreach (string slot in v90) + Eq((int)Marshal.OffsetOf(slot), + (int)Marshal.OffsetOf(slot), slot + " offset"); + Eq((int)Marshal.OffsetOf("PanelDragWithLastItemFn"), + (int)Marshal.OffsetOf("SetPanelOpenFn") + IntPtr.Size, "PanelDragWithLastItemFn right after SetPanelOpenFn"); + var names = all.SkipLast(v90.Length).ToArray(); + var sdkNames = sdkAll.SkipLast(v90.Length).ToArray(); // v81's GetMergeStackResultFn follows v80's two slots. Check(names.SkipLast(12).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v85's: " + string.Join(",", names.SkipLast(12).TakeLast(2))); Check(sdkNames.SkipLast(12).TakeLast(2).SequenceEqual(names.SkipLast(12).TakeLast(2)), "SDK v80 slots in the same order"); @@ -630,8 +644,8 @@ internal static class Program Check(names.SkipLast(4).Last() == "GetServerStateJsonFn", "v86 slot before v87's: " + names.SkipLast(4).Last()); // v87: GetWieldedItems (what the player wields, from the server's messages), then v89's three. Check(names.SkipLast(3).Last() == "GetWieldedItemsFn", "v87 slot before v89's: " + names.SkipLast(3).Last()); - // v89: plugin windows (the engine's look, panels by key) end the table. - Check(names.TakeLast(3).SequenceEqual(new[] { "GetUiColorFn", "GetUiFontFn", "SetPanelOpenFn" }), "v89 slots last: " + string.Join(",", names.TakeLast(3))); + // v89: plugin windows (the engine's look, panels by key) end the table before v90's. + Check(names.TakeLast(3).SequenceEqual(new[] { "GetUiColorFn", "GetUiFontFn", "SetPanelOpenFn" }), "v89 slots before v90's: " + string.Join(",", names.TakeLast(3))); Check(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SequenceEqual(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name)), "SDK table has the engine's slots in the same order"); Eq(Marshal.SizeOf(), Marshal.SizeOf(), "SDK table size = engine table size"); Eq((int)Marshal.OffsetOf("PutItemInContainerFn"), diff --git a/tools/SectionsTests/Program.cs b/tools/SectionsTests/Program.cs index aa9bf8b..13807e4 100644 --- a/tools/SectionsTests/Program.cs +++ b/tools/SectionsTests/Program.cs @@ -32,6 +32,7 @@ internal static class Program ManifestWindows(); WindowPlanChoices(); WindowTakeOver(); + WindowFrameless(); StackCheckAfterPluginDraw(); Console.WriteLine(); @@ -559,6 +560,31 @@ internal static class Program Check(after.Count == 0 && taken2.Count == 0, "no manifest: nothing hosted, nothing taken over"); } + // v90: a window that draws its own frame ("chrome": "none") and fits its height to its content. + private const string FramelessManifest = """ + { "version": 1, "windows": [ + { "id": "dashboard", "title": "RynthAi", "surface": "window:dashboard", "takeOver": true, + "chrome": "none", "fitHeight": true, "width": 296, "height": 240, "minWidth": 280, "minHeight": 54 }, + { "id": "plain", "title": "Notes", "surface": "window:notes" }, + { "id": "odd", "title": "Odd", "surface": "window:odd", "chrome": " NONE ", "fitHeight": "yes" }, + { "id": "framed", "title": "Framed", "surface": "window:framed", "chrome": "standard" } ] } + """; + + private static void WindowFrameless() + { + Case("plugin windows: frameless and fitted (v90)"); + SectionManifest m = SectionManifestParser.Parse("RynthAi", FramelessManifest, out string err); + Check(err.Length == 0 && m.Windows.Length == 4, "parses: " + err); + Check(m.Windows[0].Frameless && m.Windows[0].FitHeight && m.Windows[0].TakeOver, "\"chrome\": \"none\" and \"fitHeight\": true read"); + Check(!m.Windows[1].Frameless && !m.Windows[1].FitHeight, "absent: framed and sized by the player (as before)"); + Check(m.Windows[2].Frameless && !m.Windows[2].FitHeight, "\"none\" in any case, padded; fitHeight not a boolean: off"); + Check(!m.Windows[3].Frameless, "any other chrome: the engine's frame"); + Check(m.Windows[0].Width == 296 && m.Windows[0].MinWidth == 280, "sizes kept (the minimum height has the parser's floor)"); + Check(WindowPlan.Signature(m.Windows[0]) != WindowPlan.Signature(m.Windows[0] with { Frameless = false }) + && WindowPlan.Signature(m.Windows[0]) != WindowPlan.Signature(m.Windows[0] with { FitHeight = false }), + "chrome and fitHeight are in the signature (a change re-registers)"); + } + // ImGui 1.91.6's ImGuiErrorRecoveryState, in field order: windows, IDs, tree nodes, colours, // style vars, fonts, focus scopes, groups, item flags, popups, disabled. The base values are // the ones a 32-bit probe of our cimgui.dll read inside a panel's body child (2026-10-21). diff --git a/tools/ThemeTests/Program.cs b/tools/ThemeTests/Program.cs new file mode 100644 index 0000000..bb73c7b --- /dev/null +++ b/tools/ThemeTests/Program.cs @@ -0,0 +1,188 @@ +// tools/ThemeTests: the colour theme's presets, the player's own colours and saved schemes +// (RynthTheme.cs, ThemeSchemes.cs). Each case runs in its own process with RYNTHCORE_THEME_DIR +// pointing at a fresh temp folder (the theme reads its files once per process). +using System.Diagnostics; +using RynthCore.Engine.ImGuiBackend; + +namespace RynthCore.Engine.UI +{ + /// Stub: the engine saves in the background; here at once, so a case can read the file back. + internal static class UiBackgroundWriter + { + public static void Enqueue(string label, Action work) => work(); + } +} + +namespace RynthCore.Engine +{ + internal static class RynthLog + { + public static void UI(string message) { } + } +} + +namespace ThemeTests +{ + internal static class Program + { + private const string Mine = "accent=112233\nhighlight=445566\nbackground=010203\ntitlebar=0A0B0C\nbutton=202122\nborder=303132\ntext=F0F1F2\nmuted=A0A1A2\n"; + private static readonly uint[] MineColours = { 0x112233, 0x445566, 0x010203, 0x0A0B0C, 0x202122, 0x303132, 0xF0F1F2, 0xA0A1A2 }; + + private static int _failures; + + private static void Check(bool ok, string what) + { + Console.WriteLine((ok ? " ok " : " FAIL ") + what); + if (!ok) _failures++; + } + + private static string Dir => Environment.GetEnvironmentVariable("RYNTHCORE_THEME_DIR")!; + private static string ThemeFile => File.ReadAllText(Path.Combine(Dir, "theme.txt")).Replace("\r", ""); + private static string[] SchemeFiles => Directory.Exists(Path.Combine(Dir, "themes")) + ? Directory.GetFiles(Path.Combine(Dir, "themes"), "*.theme") : Array.Empty(); + + private static bool IsMine() + { + for (int i = 0; i < 8; i++) + if ((RynthTheme.GetPrimary(i) & 0xFFFFFF) != MineColours[i]) return false; + return true; + } + + private static int Brass => Array.IndexOf(ThemePalette.PresetNames, "Brass"); + + private static readonly (string Name, string? ThemeTxt, Action Run)[] Cases = + { + ("an older Custom file loads as Custom with its colours", "preset=Custom\n" + Mine, () => + { + Check(RynthTheme.Preset == RynthTheme.Custom, "Custom in use"); + Check(IsMine(), "the eight colours as saved"); + }), + ("picking a preset keeps the player's own colours, and Custom brings them back", "preset=Custom\n" + Mine, () => + { + RynthTheme.SetPreset(Brass); + Check(RynthTheme.Preset == Brass, "Brass in use"); + Check(!IsMine(), "Brass's colours on screen"); + string file = ThemeFile; + Check(file.StartsWith("preset=Brass\n"), "theme.txt says Brass"); + Check(file.Contains("accent=112233") && file.Contains("muted=A0A1A2"), "theme.txt still has the player's eight"); + RynthTheme.SetPicker(RynthTheme.PickerNames().Length - 1); // Custom + Check(RynthTheme.Preset == RynthTheme.Custom && IsMine(), "Custom: the player's colours again"); + }), + ("a preset file with the player's colours (written by this engine) restarts on the preset, Custom intact", "preset=Brass\n" + Mine, () => + { + Check(RynthTheme.Preset == Brass, "Brass in use after a restart"); + RynthTheme.UseCustom(); + Check(IsMine(), "Custom: the player's colours"); + }), + ("Reset Colours (RynthCore's) keeps the player's colours too", "preset=Custom\n" + Mine, () => + { + RynthTheme.SetPreset(0); + Check(RynthTheme.Preset == 0, "RynthCore in use"); + Check(ThemeFile.Contains("accent=112233"), "the player's colours still in theme.txt"); + }), + ("no theme.txt: RynthCore's colours, nothing new written until a change", null, () => + { + Check(RynthTheme.Preset == 0, "RynthCore (the default) in use"); + Check(!File.Exists(Path.Combine(Dir, "theme.txt")), "no theme.txt written"); + }), + ("a preset-only file (an older engine's) writes no colours of its own", "preset=Ember\n", () => + { + RynthTheme.SetPreset(Brass); + Check(ThemeFile == "preset=Brass\n", "only the preset line: " + ThemeFile.Replace("\n", " | ")); + }), + ("Save colours as: a scheme file, in the picker, in use, and back after a restart (part 1)", "preset=Custom\n" + Mine, () => + { + Check(RynthTheme.SaveScheme(" Night watch ") == "Night watch", "saved as \"Night watch\" (trimmed)"); + Check(SchemeFiles.Length == 1, "one scheme file"); + Check(RynthTheme.PickerNames().Contains("Night watch"), "listed in the Theme picker"); + Check(RynthTheme.SchemeInUse && RynthTheme.SchemeName == "Night watch", "the scheme is in use"); + Check(ThemeFile.StartsWith("preset=scheme:Night watch\n"), "theme.txt names the scheme"); + int idx = RynthTheme.PickerIndex; + Check(RynthTheme.PickerNames()[idx] == "Night watch", "the picker shows it selected"); + }), + ("a scheme picked from the picker shows its colours; a scheme that is gone falls back to Custom", "preset=Custom\n" + Mine, () => + { + RynthTheme.SaveScheme("Copy"); + RynthTheme.SetPreset(Brass); + int i = Array.IndexOf(RynthTheme.PickerNames(), "Copy"); + RynthTheme.SetPicker(i); + Check(RynthTheme.SchemeInUse && IsMine(), "\"Copy\" in use with its colours"); + Check(!RynthTheme.UseScheme("No such scheme"), "an unknown name is refused"); + }), + ("names: a preset's or Custom get My in front; empty is refused; 40 characters at most", null, () => + { + Check(ThemeSchemes.CleanName("Brass") == "My Brass", "Brass -> My Brass"); + Check(ThemeSchemes.CleanName("custom") == "My custom", "custom -> My custom"); + Check(ThemeSchemes.CleanName(" ") == "", "blank refused"); + Check(ThemeSchemes.CleanName(new string('x', 60)).Length == 40, "60 characters cut to 40"); + Check(RynthTheme.SaveScheme("") == "", "Save with no name does nothing"); + }), + ("the same name replaces the scheme; Delete removes the one in use and keeps its colours as Custom", "preset=Custom\n" + Mine, () => + { + RynthTheme.SaveScheme("Mine"); + RynthTheme.SaveScheme("mine"); + Check(SchemeFiles.Length == 1, "still one file after saving the same name again"); + Check(RynthTheme.DeleteCurrentScheme(), "deleted"); + Check(SchemeFiles.Length == 0, "the file is gone"); + Check(RynthTheme.Preset == RynthTheme.Custom && IsMine(), "Custom with the same colours"); + Check(!RynthTheme.PickerNames().Contains("Mine"), "not in the picker any more"); + }), + ("changing a colour on a preset first keeps the player's own colours as \"My colours\"", "preset=Brass\n" + Mine, () => + { + RynthTheme.SetPrimary(0, 0xFF00FF00); + Check(RynthTheme.Preset == RynthTheme.Custom, "Custom after the change"); + Check(RynthTheme.PickerNames().Contains("My colours"), "\"My colours\" saved"); + int i = Array.IndexOf(RynthTheme.PickerNames(), "My colours"); + RynthTheme.SetPicker(i); + Check(IsMine(), "\"My colours\" holds the colours from before"); + RynthTheme.UseCustom(); + Check((RynthTheme.GetPrimary(0) & 0xFFFFFF) == 0x00FF00, "Custom holds the change (Brass + green accent)"); + }), + ("no second \"My colours\" when they are already kept", "preset=Brass\n" + Mine, () => + { + RynthTheme.UseCustom(); + RynthTheme.SaveScheme("Already"); // the player's own colours, kept by name + RynthTheme.SetPreset(Brass); + RynthTheme.SetPrimary(0, 0xFF00FF00); + Check(!RynthTheme.PickerNames().Contains("My colours"), "nothing new: \"Already\" has them"); + }), + ("changing a colour while on Custom saves nothing extra", "preset=Custom\n" + Mine, () => + { + RynthTheme.SetPrimary(1, 0xFFFF0000); + Check(SchemeFiles.Length == 0, "no scheme files"); + Check(ThemeFile.Contains("highlight=FF0000"), "theme.txt has the change"); + }), + }; + + private static int Main(string[] args) + { + if (args.Length == 2 && args[0] == "--case") + { + Cases[int.Parse(args[1])].Run(); + return _failures == 0 ? 0 : 1; + } + + string exe = Environment.ProcessPath!; + string root = Path.Combine(Path.GetTempPath(), "rynth-themetests-" + Environment.ProcessId); + int failed = 0; + for (int i = 0; i < Cases.Length; i++) + { + string dir = Path.Combine(root, i.ToString()); + Directory.CreateDirectory(dir); + if (Cases[i].ThemeTxt != null) File.WriteAllText(Path.Combine(dir, "theme.txt"), Cases[i].ThemeTxt); + var psi = new ProcessStartInfo(exe, $"--case {i}") { RedirectStandardOutput = true, UseShellExecute = false }; + psi.Environment["RYNTHCORE_THEME_DIR"] = dir; + using var p = Process.Start(psi)!; + string output = p.StandardOutput.ReadToEnd(); + p.WaitForExit(); + Console.WriteLine($"-- {Cases[i].Name}"); + Console.Write(output); + if (p.ExitCode != 0) failed++; + } + try { Directory.Delete(root, true); } catch { } + Console.WriteLine(); + Console.WriteLine(failed == 0 ? $"PASS ({Cases.Length} cases)" : $"FAIL ({failed} of {Cases.Length} cases)"); + return failed == 0 ? 0 : 1; + } + } +} diff --git a/tools/ThemeTests/ThemeTests.csproj b/tools/ThemeTests/ThemeTests.csproj new file mode 100644 index 0000000..82aff7e --- /dev/null +++ b/tools/ThemeTests/ThemeTests.csproj @@ -0,0 +1,32 @@ + + + + + Exe + net10.0 + enable + enable + true + true + ThemeTests + $(NoWarn);CS0162;CS0414 + + + + + + + + + + + +