From c68204f160951ce0477cf657b719fa24d034d10a Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Sun, 8 Nov 2026 15:48:45 -0500 Subject: [PATCH] RynthCore as of 2026-11-08 (internal 9297e93): release 2026.11.8.1 --- .../Compatibility/AcCellSight.cs | 294 +++++++++++++++ .../Compatibility/AcPanels.cs | 118 +++++- .../Compatibility/CharacterTitleAction.cs | 98 +++++ .../Compatibility/ChatCommandReplies.cs | 10 +- .../Compatibility/ClientActionGates.cs | 6 +- .../Compatibility/ClientCombatHooks.cs | 131 +++++++ .../Compatibility/ClientObjectHooks.cs | 34 ++ .../Compatibility/CombatModeHooks.cs | 16 + .../Compatibility/NativeAttackRearm.cs | 97 +++++ .../Compatibility/RynthCoreChatCommands.cs | 35 +- src/RynthCore.Engine/EntryPoint.cs | 3 + src/RynthCore.Engine/Hotkeys/HotkeyModel.cs | 16 +- src/RynthCore.Engine/Hotkeys/HotkeyService.cs | 15 +- src/RynthCore.Engine/ImGui/DX9Backend.cs | 16 +- .../ImGui/EngineFrameController.cs | 7 +- src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs | 82 +++- .../ImGui/MonsterHud/DebuffIcon.cs | 27 +- .../ImGui/MonsterHud/DebuffIconRow.cs | 96 ++++- .../ImGui/MonsterHud/DebuffTip.cs | 106 ++++++ .../ImGui/MonsterHud/MonsterHud.cs | 43 ++- .../ImGui/MonsterHud/MonsterHudData.cs | 41 +- .../ImGui/MonsterHud/MonsterHudSettings.cs | 12 +- .../ImGui/MonsterHud/MonsterHudSettingsUi.cs | 4 + .../ImGui/MonsterHud/PlateDebuffs.cs | 4 + .../ImGui/MonsterHud/PlateSight.cs | 354 ++++++++++++++++++ .../ImGui/MonsterHud/PlateSightRules.cs | 116 ++++++ .../ImGui/MonsterHud/PlayerPlate.cs | 13 +- .../ImGui/MonsterHud/SelfDebuffs.cs | 11 +- .../ImGui/Panels/Classic/ClassicGearTab.cs | 15 +- .../ImGui/Panels/DamageFace.cs | 6 +- .../ImGui/Panels/ItemToolFace.cs | 42 +++ .../ImGui/Panels/ItemsFace.cs | 35 +- .../ImGui/Panels/PluginWindowFace.cs | 15 +- .../ImGui/Panels/RadarDrag.cs | 37 ++ .../ImGui/Panels/RadarFace.cs | 76 +++- .../ImGui/Panels/RadarRangeRing.cs | 47 +++ src/RynthCore.Engine/ImGui/PhosphorIcons.cs | 4 +- src/RynthCore.Engine/ImGui/RetailCursors.cs | 170 +++++++++ src/RynthCore.Engine/ImGui/RetailSprites.cs | 36 +- src/RynthCore.Engine/ImGui/UnderUiLayer.cs | 72 +++- src/RynthCore.Engine/ImGui/Win32Backend.cs | 11 + src/RynthCore.Engine/LogPaths.cs | 75 ++-- src/RynthCore.Engine/LogRotation.cs | 171 +++++++++ src/RynthCore.Engine/LogSettings.cs | 20 + .../Plugins/PluginContract.cs | 18 +- .../Plugins/PluginContractVersion.cs | 9 +- src/RynthCore.Engine/Plugins/PluginManager.cs | 45 ++- src/RynthCore.Engine/Plugins/ShortcutApi.cs | 11 +- src/RynthCore.Engine/UI/AcWindowChrome.cs | 7 +- src/RynthCore.Engine/UI/Data/ChatData.cs | 9 +- .../UI/Data/ChatLineColors.cs | 7 + src/RynthCore.Engine/UI/Data/ChatOwnColors.cs | 158 ++++++++ src/RynthCore.Engine/UI/Data/ChatRouting.cs | 58 ++- .../UI/Data/ChatRuleMatching.cs | 30 ++ .../UI/Data/DamageRowStats.cs | 142 ++++++- src/RynthCore.Engine/UI/Data/ItemToolData.cs | 10 +- src/RynthCore.Engine/UI/Data/SettingsData.cs | 81 +++- src/RynthCore.Engine/UI/PanelLayout.cs | 88 ++++- src/RynthCore.Engine/UI/PanelLayoutPolicy.cs | 79 +++- src/RynthCore.Engine/UI/PanelStateStore.cs | 34 ++ src/RynthCore.Engine/UI/Panels/ItemsPanel.cs | 13 +- .../UI/Panels/RadarSettingsStore.cs | 10 + .../UI/ScriptWindows/AcIconDecoder.cs | 39 ++ .../UI/Sections/PluginWindows.cs | 11 +- .../UI/Sections/SectionManifest.cs | 8 +- src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 2 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 29 ++ src/RynthCore.PluginSdk/UiKitTypes.cs | 12 + .../build/RynthCore.PluginSdk.targets | 2 +- tools/ChatCommandReplyTests/Program.cs | 2 + tools/ChatFilterTests/ChatFilterTests.csproj | 2 + tools/ChatFilterTests/EngineStubs.cs | 2 + tools/ChatFilterTests/Program.cs | 134 +++++++ tools/ChatHistoryBench/Stubs.cs | 1 + .../CleaveGhostTests/CleaveGhostTests.csproj | 4 + tools/CleaveGhostTests/HudFeedStub.cs | 10 + tools/CleaveGhostTests/Program.cs | 92 +++++ tools/DamageRowStatsTests/Program.cs | 112 ++++++ .../EngineRobustnessTests.csproj | 4 + .../NativeAttackRearmTests.cs | 119 ++++++ tools/EngineRobustnessTests/Program.cs | 2 + tools/HotkeyTests/Program.cs | 11 +- .../ItemsNoBuffTests/ItemsNoBuffTests.csproj | 27 ++ tools/ItemsNoBuffTests/Program.cs | 79 ++++ .../OutdoorHuntPickTests.csproj | 31 ++ tools/OutdoorHuntPickTests/Program.cs | 110 ++++++ tools/PanelLayoutTests/Program.cs | 146 +++++++- tools/PlateSightTests/PlateSightTests.csproj | 25 ++ tools/PlateSightTests/Program.cs | 274 ++++++++++++++ tools/PlateSizingTests/Program.cs | 31 ++ tools/PluginManifestTests/Program.cs | 15 +- .../ProblemReportTests.csproj | 4 + tools/ProblemReportTests/Program.cs | 155 ++++++++ tools/RadarSettingsTests/Program.cs | 62 +++ .../RadarSettingsTests.csproj | 8 +- tools/SelfPlateTests/Program.cs | 58 +++ tools/SelfPlateTests/SelfPlateTests.csproj | 1 + tools/plate_sight_check.py | 139 +++++++ tools/soak_scorecard.py | 8 +- 99 files changed, 5032 insertions(+), 185 deletions(-) create mode 100644 src/RynthCore.Engine/Compatibility/AcCellSight.cs create mode 100644 src/RynthCore.Engine/Compatibility/CharacterTitleAction.cs create mode 100644 src/RynthCore.Engine/Compatibility/NativeAttackRearm.cs create mode 100644 src/RynthCore.Engine/ImGui/MonsterHud/DebuffTip.cs create mode 100644 src/RynthCore.Engine/ImGui/MonsterHud/PlateSight.cs create mode 100644 src/RynthCore.Engine/ImGui/MonsterHud/PlateSightRules.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/RadarDrag.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/RadarRangeRing.cs create mode 100644 src/RynthCore.Engine/ImGui/RetailCursors.cs create mode 100644 src/RynthCore.Engine/LogRotation.cs create mode 100644 src/RynthCore.Engine/UI/Data/ChatOwnColors.cs create mode 100644 tools/CleaveGhostTests/HudFeedStub.cs create mode 100644 tools/EngineRobustnessTests/NativeAttackRearmTests.cs create mode 100644 tools/ItemsNoBuffTests/ItemsNoBuffTests.csproj create mode 100644 tools/ItemsNoBuffTests/Program.cs create mode 100644 tools/OutdoorHuntPickTests/OutdoorHuntPickTests.csproj create mode 100644 tools/OutdoorHuntPickTests/Program.cs create mode 100644 tools/PlateSightTests/PlateSightTests.csproj create mode 100644 tools/PlateSightTests/Program.cs create mode 100644 tools/plate_sight_check.py diff --git a/src/RynthCore.Engine/Compatibility/AcCellSight.cs b/src/RynthCore.Engine/Compatibility/AcCellSight.cs new file mode 100644 index 0000000..4b5061e --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AcCellSight.cs @@ -0,0 +1,294 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/AcCellSight.cs +// +// What AC's own renderer knows about indoor visibility, read out of its cells: +// which EnvCells (dungeon and building interior cells) it drew this frame, +// whether a cell can see outside, the cell's visible-cell list and its doorways +// to the outside. The nameplates (ImGui/MonsterHud/PlateSight) use it to hide +// a plate or a name label for an object behind building and dungeon walls +// (2026-11-04, problem report R-20261105-020337-67aa: "NPC and Mob labels show +// up through walls", and in a town the labels caught the clicks meant for the +// shop). Read only: nothing here writes AC memory or calls into AC. +// +// Evidence (AC client decompile, C:\Projects\GhidraTools\decompiled; our client, +// 4,841,472 bytes, both copies; tools\plate_sight_check.py checks every fact): +// Draw stamps. RenderDevice* lives in a global (0x00870340 here); its +0xB0 is +// a frame stamp. PView::DrawCells (0x005A5950) adds 1 to it, then draws each +// cell of the portal walk it just built (PView::ConstructView: the cells seen +// through portals from the viewer, clipped) with RenderDeviceD3D::DrawEnvCell +// (0x005A0280), which marks the cell with CEnvCell::SetDrawnThisFrame +// (0x0052CCF0: cell+0x130 = stamp). RenderDeviceD3D::Flip (0x005A0F60, after +// Present) adds 1 more. DrawCells runs from PView::DrawInside (the viewer is +// indoors) and PView::DrawPortal (a building's doorway seen from outdoors), +// so the stamp moves several times a frame: a cell AC drew since the stamp +// we sampled one or two frames ago carries a newer stamp than that sample. +// CEnvCell::GetDrawnThisFrame (0x0052CCD0) is the pattern below: it compares +// cell+0x130 with [global]+0xB0, so the one match pins the global and both +// offsets at once. +// The cell an object is in: CPhysicsObj::enter_cell (0x005119A0) stores the +// CObjCell* at CPhysicsObj+0x90 and the cell's id (cell+0x28, the DBObj id) +// at +0x4C (m_position.objcell_id); leave_cell / change_cell clear both +// (ClientObjectHooks.TryGetObjectCell reads them). +// The viewer's cell: SmartBox+0x08 is the camera's Position (GameMatrixCapture +// reads it; +0x0C its cell id) and +0x50 the CObjCell* AC renders from: +// SmartBox::RenderNormalMode (0x00453B40) tests +0x0C < 0x100 (outdoors) and +// [+0x50]+0xE8, then hands +0x50 to the device's DrawInside. +// Sees outside: CObjCell+0xE8 (seen_outside; CEnvCell::UnPack 0x0052E0D0 sets +// it from the dat flags & 1). CellManager::ChangePosition (0x00455AD0) +// releases the whole landscape (LScape::release_all) for a cell without it: +// from a dungeon cell AC draws nothing outdoors. +// Visible cells: CObjCell+0xE0 count, +0xE4 uint[] of full cell ids (UnPack: +// each dat ushort | the landblock); PView::DrawInside hands exactly these to +// PView::add_views, so no cell outside the list is ever drawn from this one. +// Doorways: CEnvCell+0x108 portal count (UnPack reads a byte), +0x10C the +// CCellPortal array, 0x18 each: +0 other cell id (0xFFFFFFFF = outdoors, +// CCellPortal::UnPack 0x0053C810), +4 the other CEnvCell* (filled by +// PView::ClipPortals as the walk reaches it), +8 the CPolygon*. CPolygon: +// +0 CVertex**, +0xE byte point count (D3DPolyRender::DrawPortalPolyInternal +// 0x0059CCA0); a CVertex starts with x, y, z in the cell's frame. The cell's +// Position is at +0x54: +0x58 id, frame +0x5C (qw, qx, qy, qz; +0x90 the +// origin, landblock-local), as CellManager::ChangePosition copies it. +// +// Threads: AC's main thread only (EndScene and the MonsterHud update run there); +// every read is probed first (MemoryProbe), a failed read is "unknown", never a +// guess. No fixed address is used: no pattern match = no draw stamps (logged +// once) and PlateSight falls back to the cell lists. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class AcCellSight +{ + // CEnvCell::GetDrawnThisFrame on the 4,841,472-byte client. Pattern is the source of truth. + private const int GetDrawnThisFrameFallbackVa = 0x0052CCD0; + + // mov eax,[ecx+130h] (the cell's draw stamp); mov ecx,[render device global]; + // cmp eax,[ecx+0B0h] (the device's frame stamp); sete al; ret. + // Unique in the scanned window on both client copies (C:\Turbine and + // C:\Games\RynthCore\AcClient, 2026-11-04); CPhysicsPart's twin (0x0050DFA0) reads +0DCh. + // The global (bytes 8-11) is wildcarded and read back from the match. + private static readonly byte?[] GetDrawnThisFramePattern = + [ + 0x8B, 0x81, 0x30, 0x01, 0x00, 0x00, + 0x8B, 0x0D, null, null, null, null, + 0x3B, 0x81, 0xB0, 0x00, 0x00, 0x00, + 0x0F, 0x94, 0xC0, + 0xC3, + ]; + private const int PatternGlobalOperand = 8; + + // ── Layout (see the header for where each comes from) ──────────────── + private const int DeviceFrameStamp = 0xB0; + internal const int CellId = 0x28; + private const int CellFrameQw = 0x5C; // qw, qx, qy, qz + private const int CellFrameOrigin = 0x90; // x, y, z (landblock-local) + private const int CellNumStabs = 0xE0; + private const int CellStabList = 0xE4; + private const int CellSeenOutside = 0xE8; + private const int EnvCellNumPortals = 0x108; + private const int EnvCellPortals = 0x10C; + private const int EnvCellDrawStamp = 0x130; + private const int PortalSize = 0x18; + private const int PortalOtherId = 0x00; + private const int PortalOtherPtr = 0x04; + private const int PortalPolygon = 0x08; + private const int PolygonVertices = 0x00; + private const int PolygonNumPts = 0x0E; + private const int SmartBoxViewerCellId = 0x0C; + private const int SmartBoxViewerCell = 0x50; + + /// CCellPortal other cell id of a doorway to the outside. + public const uint OutdoorsId = 0xFFFFFFFF; + + // Sanity caps: a real cell has a handful of portals and at most a few hundred visible cells. + private const int MaxPortals = 64, MaxStabs = 1024, MaxPolygonPoints = 32; + + private static int _initialized; + private static IntPtr _deviceGlobal; // address of the RenderDevice* global (0 = not resolved) + private static string _status = "not initialised"; + private static int _stampFailLogged; + + /// The draw stamps can be read (the pattern matched). + public static bool StampsAvailable => _deviceGlobal != IntPtr.Zero; + + /// One line for "/rv plates status". + public static string Status => _status; + + /// InitWorker step: finds the render-device global from CEnvCell::GetDrawnThisFrame. Idempotent. + public static void Initialize() + { + if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0) + return; + try + { + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + _status = "acclient.exe not available"; + RynthLog.Compat("AcCellSight: acclient.exe not available - nameplates use the cell lists only."); + return; + } + HookResolver.ResolveResult r = HookResolver.Resolve(text, "AcCellSight.CEnvCell::GetDrawnThisFrame", GetDrawnThisFramePattern, GetDrawnThisFrameFallbackVa); + // Only a real match: a fallback VA on another build could read some other global as the stamp. + if (r.Source != HookResolver.ResolveSource.PatternScan) + { + _status = "draw stamps unavailable (pattern not found)"; + RynthLog.Compat("AcCellSight: CEnvCell::GetDrawnThisFrame not found - nameplates use the cell lists only."); + return; + } + int off = r.Address.ToInt32() - text.TextBaseVa + PatternGlobalOperand; + int global = BitConverter.ToInt32(text.Bytes, off); + long moduleBase = text.ModuleBase.ToInt64(); + if (global < moduleBase || global >= moduleBase + text.ImageSize) + { + _status = $"draw stamps unavailable (global 0x{global:X8} outside the client)"; + RynthLog.Compat($"AcCellSight: render device global 0x{global:X8} is outside acclient.exe - nameplates use the cell lists only."); + return; + } + _deviceGlobal = new IntPtr(global); + _status = $"draw stamps from the render device at [0x{global:X8}]+0x{DeviceFrameStamp:X}"; + RynthLog.Compat($"AcCellSight: ready (render device global 0x{global:X8}, CEnvCell::GetDrawnThisFrame @ 0x{r.Address.ToInt32():X8})."); + } + catch (Exception ex) + { + _deviceGlobal = IntPtr.Zero; + _status = $"draw stamps unavailable ({ex.GetType().Name})"; + RynthLog.Compat($"AcCellSight: init failed - {ex.GetType().Name}: {ex.Message}"); + } + } + + /// The render device's frame stamp now. False when it can't be read (logged once). + public static bool TryReadFrameStamp(out uint stamp) + { + stamp = 0; + IntPtr g = _deviceGlobal; + if (g == IntPtr.Zero || !MainThreadGuard.IsOnMainThread()) return false; + if (!MemoryProbe.IsReadable(g, 4)) return Fail("the render device global is unreadable"); + IntPtr dev = *(IntPtr*)g; + if (dev == IntPtr.Zero) return false; // no device yet (login): not worth a log line + if (!MemoryProbe.IsReadable(dev + DeviceFrameStamp, 4)) return Fail("the render device is unreadable"); + stamp = *(uint*)(dev + DeviceFrameStamp); + return true; + } + + private static bool Fail(string why) + { + if (Interlocked.Exchange(ref _stampFailLogged, 1) == 0) + RynthLog.Compat($"AcCellSight: {why} - nameplates use the cell lists only while it lasts."); + return false; + } + + /// The cell AC renders the world from (the camera's): its id and CObjCell*. Main thread. + public static bool TryGetViewer(out uint cellId, out IntPtr cell) + { + cellId = 0; + cell = IntPtr.Zero; + if (!MainThreadGuard.IsOnMainThread()) return false; + if (!SmartBoxLocator.TryGetSmartBox(out IntPtr sb, out _, out _)) return false; + if (!MemoryProbe.IsReadable(sb + SmartBoxViewerCellId, SmartBoxViewerCell + 4 - SmartBoxViewerCellId)) return false; + cellId = *(uint*)(sb + SmartBoxViewerCellId); + cell = *(IntPtr*)(sb + SmartBoxViewerCell); + if ((cellId >> 16) == 0) return false; + // The pointer must be that cell (it lags a frame across a cell change; outdoors it is a land cell). + if (cell != IntPtr.Zero && !IsCell(cell, cellId)) cell = IntPtr.Zero; + return true; + } + + /// A CObjCell* that is readable and holds . + public static bool IsCell(IntPtr cell, uint cellId) => + cell != IntPtr.Zero && MemoryProbe.IsReadable(cell + CellId, 4) && *(uint*)(cell + CellId) == cellId; + + /// The cell's seen_outside flag (outdoor land cells are outside). Null when unreadable. + public static bool? SeesOutside(IntPtr cell, uint cellId) + { + if ((cellId & 0xFFFF) < 0x100) return true; + if (!IsCell(cell, cellId) || !MemoryProbe.IsReadable(cell + CellSeenOutside, 4)) return null; + return *(int*)(cell + CellSeenOutside) != 0; + } + + /// An EnvCell's draw stamp (cell+0x130). False when unreadable or not an EnvCell. + public static bool TryReadDrawStamp(IntPtr cell, uint cellId, out uint stamp) + { + stamp = 0; + if ((cellId & 0xFFFF) < 0x100 || !IsCell(cell, cellId)) return false; + if (!MemoryProbe.IsReadable(cell + EnvCellDrawStamp, 4)) return false; + stamp = *(uint*)(cell + EnvCellDrawStamp); + return true; + } + + /// + /// The cell's visible-cell list (full ids) into ; the count, or -1 when + /// it can't be read (or doesn't fit). + /// + public static int ReadVisibleCells(IntPtr cell, uint cellId, uint[] into) + { + if ((cellId & 0xFFFF) < 0x100 || !IsCell(cell, cellId)) return -1; + if (!MemoryProbe.IsReadable(cell + CellNumStabs, 8)) return -1; + int n = *(int*)(cell + CellNumStabs); + IntPtr list = *(IntPtr*)(cell + CellStabList); + if (n == 0) return 0; + if (n < 0 || n > MaxStabs || n > into.Length || list == IntPtr.Zero || !MemoryProbe.IsReadable(list, n * 4)) return -1; + uint* p = (uint*)list; + for (int i = 0; i < n; i++) into[i] = p[i]; + return n; + } + + /// One CCellPortal of an EnvCell. + public struct PortalRead + { + public uint OtherId; // OutdoorsId: a doorway to the outside + public IntPtr OtherCell; // 0 until AC's portal walk reached it + /// Outside doorways only: the polygon, landblock-local (x east, y north, z up). Null when unreadable. + public Vector3[]? World; + } + + /// + /// An EnvCell's portals into (appended), with the outside doorways' polygons + /// moved into the landblock's frame. False when the cell or its portal array can't be read. + /// Allocates for the polygons: call it when the viewer changes cell, not every frame. + /// + public static bool ReadPortals(IntPtr cell, uint cellId, List into) + { + if ((cellId & 0xFFFF) < 0x100 || !IsCell(cell, cellId)) return false; + if (!MemoryProbe.IsReadable(cell + EnvCellNumPortals, 8) || !MemoryProbe.IsReadable(cell + CellFrameQw, CellFrameOrigin + 12 - CellFrameQw)) + return false; + int n = *(int*)(cell + EnvCellNumPortals); + IntPtr arr = *(IntPtr*)(cell + EnvCellPortals); + if (n == 0) return true; + if (n < 0 || n > MaxPortals || arr == IntPtr.Zero || !MemoryProbe.IsReadable(arr, n * PortalSize)) return false; + + float* q = (float*)(cell + CellFrameQw); + float* o = (float*)(cell + CellFrameOrigin); + var rot = new Quaternion(q[1], q[2], q[3], q[0]); + var origin = new Vector3(o[0], o[1], o[2]); + for (int i = 0; i < n; i++) + { + IntPtr e = arr + i * PortalSize; + var pr = new PortalRead { OtherId = *(uint*)(e + PortalOtherId), OtherCell = *(IntPtr*)(e + PortalOtherPtr) }; + if (pr.OtherId == OutdoorsId) pr.World = ReadPolygon(*(IntPtr*)(e + PortalPolygon), rot, origin); + into.Add(pr); + } + return true; + } + + private static Vector3[]? ReadPolygon(IntPtr poly, Quaternion rot, Vector3 origin) + { + if (poly == IntPtr.Zero || !MemoryProbe.IsReadable(poly, PolygonNumPts + 1)) return null; + int n = *(byte*)(poly + PolygonNumPts); + IntPtr verts = *(IntPtr*)(poly + PolygonVertices); + if (n < 3 || n > MaxPolygonPoints || verts == IntPtr.Zero || !MemoryProbe.IsReadable(verts, n * 4)) return null; + var world = new Vector3[n]; + for (int i = 0; i < n; i++) + { + IntPtr v = *(IntPtr*)(verts + i * 4); + if (v == IntPtr.Zero || !MemoryProbe.IsReadable(v, 12)) return null; + float* f = (float*)v; + if (!float.IsFinite(f[0]) || !float.IsFinite(f[1]) || !float.IsFinite(f[2])) return null; + world[i] = Vector3.Transform(new Vector3(f[0], f[1], f[2]), rot) + origin; + } + return world; + } +} diff --git a/src/RynthCore.Engine/Compatibility/AcPanels.cs b/src/RynthCore.Engine/Compatibility/AcPanels.cs index 4c0f3d6..9beba2b 100644 --- a/src/RynthCore.Engine/Compatibility/AcPanels.cs +++ b/src/RynthCore.Engine/Compatibility/AcPanels.cs @@ -22,12 +22,24 @@ // before each use. // // Opening and closing is queued and done on AC's game thread after its tick. +// +// Replacing a panel (2026-11-07, Tom: AC's Character window "still popping up +// here and there" when RynthDreamWeave's Character panel opens in its place): +// the notice is hooked, and a panel a plugin claims ("/rc panels replace +// ") never opens: the open notice is dropped before AC draws +// anything and the plugin's command runs on the next game tick instead +// (AC's toolbar button and key both send it). A command no plugin takes +// (the plugin unloaded) drops the claim and opens AC's panel after all. // ============================================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading; using System.Runtime.InteropServices; +using RynthCore.Engine.Hooking; +using RynthCore.Engine.Plugins; namespace RynthCore.Engine.Compatibility; @@ -60,6 +72,99 @@ internal static unsafe class AcPanels _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); + if (CanToggle) HookNotice(); + } + + // ── Replacing a panel (a plugin's window opens instead) ───────────────── + + private static readonly ConcurrentDictionary Replacements = new(); + private static readonly ConcurrentQueue<(uint Id, string Command)> Pressed = new(); + private static IntPtr _noticeOriginal; + private static bool _hooked, _bypass; + private static int _noticeLogged, _claimedLogged; + + /// Whether AC's open notice can be held back (the hook is in). + public static bool CanReplace => _hooked; + + private static unsafe void HookNotice() + { + try + { + delegate* unmanaged[Cdecl] detour = &NoticeDetour; + MinHook.Hook(_notice, (IntPtr)detour, out _noticeOriginal); + _hooked = true; + RynthLog.Compat($"AcPanels: hooked SendNotice_SetPanelVisibility @ 0x{_notice.ToInt32():X8} (panels can be replaced)."); + } + catch (Exception ex) + { + _noticeOriginal = IntPtr.Zero; + RynthLog.Compat($"AcPanels: the notice hook failed - {ex.Message}; panels open as AC's."); + } + } + + /// + /// Claims AC's panel : AC asked to open it, runs instead + /// (null or empty drops the claim). True when it changed. Any thread. + /// + public static bool Replace(uint id, string? command) + { + if (string.IsNullOrWhiteSpace(command)) return Replacements.TryRemove(id, out _); + command = command.Trim(); + if (Replacements.TryGetValue(id, out string? now) && now == command) return false; + Replacements[id] = command; + return true; + } + + public static IReadOnlyDictionary Replaced => Replacements; + + /// AC's own show/hide of a panel: an open of a claimed one is held back (AC's main thread). + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static unsafe byte NoticeDetour(uint id, int visible) + { + try + { + // visible is a bool in the low byte: AC leaves junk above it (0x3001 / 0x3000, read 2026-11-07). + bool open = (visible & 0xFF) != 0; + bool claimed = Replacements.TryGetValue(id, out string? command); + // Every notice for a claimed panel (to see AC's button and key reach it), a few of the rest: the + // loot window alone sends two a second. + if (claimed ? Interlocked.Increment(ref _claimedLogged) <= 200 : Interlocked.Increment(ref _noticeLogged) <= 10) + RynthLog.Compat($"AcPanels: notice panel {id} {(open ? "open" : "close")}{(_bypass ? " (ours)" : claimed && open ? " - held back, runs " + command : "")}."); + if (open && claimed && !_bypass) + { + if (Pressed.Count < 8) Pressed.Enqueue((id, command!)); + return 1; + } + } + catch { /* never in AC's way */ } + return ((delegate* unmanaged[Cdecl])_noticeOriginal)(id, visible); + } + + /// Game thread: the claimed panels AC asked to open run their plugin's command. + private static void RunPressed() + { + while (Pressed.TryDequeue(out var p)) RunClaim(p.Id, p.Command); + } + + /// Game thread: a claimed panel's command in place of opening it. + private static void RunClaim(uint id, string command) + { + bool taken = false; + try { taken = PluginManager.DispatchChatBarEnter(command); } + catch (Exception ex) { RynthLog.Compat($"AcPanels: '{command}' threw {ex.GetType().Name}: {ex.Message}"); } + if (taken) return; + // No plugin took it (unloaded): AC's own panel after all, and no more claim. + Replacements.TryRemove(id, out _); + RynthLog.Compat($"AcPanels: no plugin took '{command}' - panel {id} is AC's again."); + Send(id, open: true); + } + + private static unsafe void Send(uint id, bool open) + { + _bypass = true; + try { ((delegate* unmanaged[Cdecl])_notice)(id, open ? 1 : 0); } + finally { _bypass = false; } + _cachedMs = long.MinValue / 2; } /// One of AC's panels: its id (the notice's), the class AC gives it, open or not. @@ -216,6 +321,7 @@ internal static unsafe class AcPanels /// Game thread, after AC's tick. public static void Drain() { + if (!Pressed.IsEmpty) RunPressed(); if (Requests.IsEmpty) return; long now = Environment.TickCount64; // Not held between worlds: a panel opens and closes in portal space as with AC's own keys @@ -233,8 +339,15 @@ internal static unsafe class AcPanels 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; + // RynthCore's own buttons and keys for a claimed panel (the corner strip's Character button) + // do what AC's do: the plugin's window, never AC's (Tom 2026-11-07: AC's "flashes when clicked"). + if (open && Replacements.TryGetValue(r.Id, out string? command)) + { + RynthLog.Compat($"AcPanels: panel {r.Id} asked open by RynthCore - runs {command}."); + RunClaim(r.Id, command); + continue; + } + Send(r.Id, open); } catch (Exception ex) { @@ -246,6 +359,7 @@ internal static unsafe class AcPanels public static void Reset() { while (Requests.TryDequeue(out _)) { } + while (Pressed.TryDequeue(out _)) { } Array.Clear(_found); } } diff --git a/src/RynthCore.Engine/Compatibility/CharacterTitleAction.cs b/src/RynthCore.Engine/Compatibility/CharacterTitleAction.cs new file mode 100644 index 0000000..4914cfd --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/CharacterTitleAction.cs @@ -0,0 +1,98 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/CharacterTitleAction.cs +// Choosing the character's displayed title (game action 0x002C TitleSet), as +// the retail Character panel's Titles page does with its button (element +// 0x10000535 -> CM_Social::Event_SetDisplayCharacterTitle(titleId)). +// "/rc title " calls it; RynthDreamWeave's Skills panel (its Titles tab) +// sends that command, so no plugin API is needed (2026-11-07). +// +// The sender, read off acclient.exe 2026-11-07: 0x006A6680, +// bool __cdecl CM_Social::Event_SetDisplayCharacterTitle(uint titleId) +// prologue 83 EC 0C 53 56 57 E8 (as the combat senders), and at +0x5A +// "mov dword ptr [edx], 0x2C" (C7 02 2C 00 00 00) then the id. (The Ghidra +// index also names 0x0049AA1D so; that is a mislabelled thunk.) The address +// is used only when those bytes are there; otherwise the 0x2C store is looked +// for with the same prologue before it, and used only when exactly one fits. +// +// A game-action send (AC blob + send queue): AC's main thread only. A chat +// command runs inside AC's outgoing-chat hook, which is that thread. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.Compatibility; + +internal static class CharacterTitleAction +{ + private const int KnownVa = 0x006A6680; + private const int StoreOffset = 0x5A; + private static readonly byte[] Prologue = [0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8]; + private static readonly byte[] TitleSetStore = [0xC7, 0x02, 0x2C, 0x00, 0x00, 0x00]; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + [return: MarshalAs(UnmanagedType.U1)] + private delegate bool SetTitleDelegate(uint titleId); + + private static SetTitleDelegate? _send; + private static bool _probed; + private static string _status = "not looked for yet"; + + public static string Status => _status; + + private static void Probe() + { + _probed = true; + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + _status = "acclient.exe not available"; + return; + } + byte[] bytes = text.Bytes; + int known = KnownVa - text.TextBaseVa; + int func = -1; + if (known >= 0 && known + StoreOffset + TitleSetStore.Length <= bytes.Length + && PatternScanner.VerifyBytes(bytes, known, Prologue) + && PatternScanner.VerifyBytes(bytes, known + StoreOffset, TitleSetStore)) + func = known; + else + { + // Another client build: every 0x2C store with this prologue close before it; exactly one. + int found = -1, count = 0; + for (int at = PatternScanner.FindPattern(bytes, TitleSetStore); at >= 0; + at = PatternScanner.FindPatternInRegion(bytes, TitleSetStore, at + 1, bytes.Length)) + { + int p = PatternScanner.FindPrologueBefore(bytes, at, Prologue, 0x80); + if (p >= 0 && at - p == StoreOffset) { found = p; count++; } + } + if (count == 1) func = found; + else + { + _status = count == 0 ? "the title sender (0x2C) wasn't found in this client" : $"{count} candidates for the title sender; none used"; + RynthLog.Compat("CharacterTitleAction: " + _status); + return; + } + } + int va = text.TextBaseVa + func; + _send = Marshal.GetDelegateForFunctionPointer(new IntPtr(va)); + _status = $"CM_Social::Event_SetDisplayCharacterTitle at 0x{va:X8}"; + RynthLog.Compat("CharacterTitleAction: " + _status); + } + + /// Sends TitleSet for ; why not, or null when sent. AC's main thread. + public static string? SetTitle(uint titleId) + { + if (titleId == 0) return "no title id"; + if (!MainThreadGuard.IsOnMainThread()) return "not on AC's thread"; + if (!_probed) Probe(); + if (_send == null) return _status; + try + { + return _send(titleId) ? null : "AC didn't send it"; + } + catch (Exception ex) + { + return $"{ex.GetType().Name}: {ex.Message}"; + } + } +} diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs index 6427050..2a0e746 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs @@ -122,7 +122,7 @@ internal static class ChatCommandReplies "debuffs [on|off] | debuffs size <50-200%> | others [on|off] | numbers [dealt|taken|heals|kills] [on|off] | " + "gains [xp|lum|radiance] [on|off] | npcs [on|off] | npcs dist |max | players [on|off] | portals [on|off] | portals dist | " + "all|engaged |dist |max |scale |opacity |lift | " + - "names|hp|level|weak|distance|fade|click [on|off] | refresh [on|off] | refresh | reset | status | test"; + "names|hp|level|weak|distance|fade|click|walls [on|off] | refresh [on|off] | refresh | reset | status | test"; public const string ServerUsage = "Usage: /rc server [ auto|on|off] | pick |auto | [aelrynth|other|auto] | names ilt [add|remove ]"; @@ -185,7 +185,8 @@ internal static class ChatCommandReplies V("settings", "Usage: /rc settings [tab]", null), V("shortcuts", "Usage: /rc shortcuts [use <1-18> | set <1-18> [id] | clear <1-18>]", ShortcutsArgs), V("keymap", "Usage: /rc keymap check|bind|unbind | dump, e.g. /rc keymap bind UseQuickSlot_10 F11", KeymapArgs), - V("panels", "Usage: /rc panels [open|close|toggle ]", PanelsArgs), + V("panels", "Usage: /rc panels [open|close|toggle ] | replace ", PanelsArgs), + V("title", "Usage: /rc title ", a => uint.TryParse(a.Trim(), out uint t) && t != 0), V("hotkey", HotkeyUsage, null), V("rl", "Usage: /rc rl (reloads RynthCore, as the bar's RL button)", NoArgs, "reload"), V("inventory", "Usage: /rc inventory (opens or closes the Inventory panel)", NoArgs, "inv"), @@ -332,11 +333,12 @@ internal static class ChatCommandReplies return verb == "dump" || (verb is "check" or "bind" or "unbind" && ka.Length == 3); } - /// <summary>"<op> <id>" (open, close, anything else toggles, as before), or nothing (the list).</summary> + /// <summary>"<op> <id>" (open, close, anything else toggles, as before), "replace <id> <command|off>", or nothing (the list).</summary> private static bool PanelsArgs(string a) { string[] pa = a.Split(' ', StringSplitOptions.RemoveEmptyEntries); - return pa.Length == 0 || (pa.Length == 2 && TryPanelId(pa[1], out _)); + return pa.Length == 0 || (pa.Length == 2 && TryPanelId(pa[1], out _)) + || (pa.Length >= 3 && pa[0].Equals("replace", StringComparison.OrdinalIgnoreCase) && TryPanelId(pa[1], out _)); } /// <summary>An AC panel id: decimal, or hex with 0x.</summary> diff --git a/src/RynthCore.Engine/Compatibility/ClientActionGates.cs b/src/RynthCore.Engine/Compatibility/ClientActionGates.cs index ebaa41b..1b08ff2 100644 --- a/src/RynthCore.Engine/Compatibility/ClientActionGates.cs +++ b/src/RynthCore.Engine/Compatibility/ClientActionGates.cs @@ -558,14 +558,16 @@ internal static class ClientActionGates // 5. Combat system. IntPtr combat = CombatModeHooks.ReadCombatSystemPtr(); - if (combat != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(combat, 0x48)) + if (combat != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(combat, 0x50)) { int mode = Marshal.ReadInt32(combat + 0x1C); string modeName = mode switch { 1 => "NonCombat", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => mode.ToString() }; byte busyHeld = Marshal.ReadByte(combat + 0x3C); byte inAttack = Marshal.ReadByte(combat + 0x3D); byte autoRepeat = Marshal.ReadByte(combat + 0x44); - lines.Add($" Combat: mode {modeName}; attack holds busy {busyHeld}; attack in progress {inAttack}; auto-repeat {autoRepeat}"); + byte queued = Marshal.ReadByte(combat + 0x47); + lines.Add($" Combat: mode {modeName}; attack holds busy {busyHeld}; attack in progress {inAttack}; auto-repeat {autoRepeat}; queued attack {queued}"); + lines.Add($" {ClientCombatHooks.DescribeRearms()}"); } lines.Add($" World transition (portal/death): {(PlayerLifecycleLog.InWorldTransition ? "yes" : "no")}; logged in: {(LoginLifecycleHooks.HasObservedLoginComplete ? "yes" : "no")}"); diff --git a/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs b/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs index a3b5166..b39e2ee 100644 --- a/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs @@ -190,12 +190,25 @@ internal static class ClientCombatHooks cs = globalPtr; } if (!ClientObjectHooks.IsReadablePointer(cs)) return false; + if (!ClientObjectHooks.IsReadableSpan(cs, AttackStateSpan)) return false; + + // Only in Melee or Missile. Elsewhere ExecuteAttack sends nothing but still sets the + // attack-in-progress flag, which then holds every later native attack (NativeAttackRearm). + // A queued NativeAttack can run after a stance change the plugin hadn't seen yet. + int mode = Marshal.ReadInt32(cs + ModeOffset); + if (!NativeAttackRearm.AttackMode(mode)) + { + LogRefusedMode(mode); + return false; + } + RearmIfStuck(cs); // Notify client of height change via CM_Combat (same path as keyboard Del/End/PgDn) _sendAttackHeightChanged?.Invoke(attackHeight); _setAttackHeight!(cs, attackHeight); _startAttackRequest(cs); _endAttackRequest(cs, attackHeight, power); + _modeChangesAtLastSend = CombatModeHooks.ModeChanges; return true; } catch (Exception ex) @@ -205,6 +218,124 @@ internal static class ClientCombatHooks } } + // ── The client's attack state (ClientCombatSystem fields) ──────────── + // From the decompile of StartAttackRequest / EndAttackRequest / ExecuteAttack / UseTime / + // HandleCommenceAttackEvent / HandleAttackDoneEvent (0x0056CD90, 0x0056CE30, 0x0056C8C0, + // 0x0056CF40, 0x0056BA60, 0x0056D250); +0x3C/+0x3D are also in ClientActionGates' AttackDone + // pattern and +0x3E in EndAttackRequest's. See NativeAttackRearm for how they wedge. + private const int ModeOffset = 0x1C; // combat mode + private const int BarStartOffset = 0x28; // power bar start time (a double, +0x28..+0x2F) + private const int BarBuildingOffset = 0x30; // power bar filling: UseTime attacks when it is full + private const int InProgressOffset = 0x3D; // attack in progress: set by ExecuteAttack, cleared by AttackDone + private const int RequestOffset = 0x3E; // between StartAttackRequest and EndAttackRequest + private const int AutoRepeatOffset = 0x44; // the client's auto-repeat: AttackDone attacks again + private const int BarNoAttackOffset = 0x45; // 1 = the filling bar only shows, it doesn't attack + private const int QueuedOffset = 0x47; // EndAttackRequest while in progress: AttackDone replays it + private const int QueuedPowerOffset = 0x48; // its power (float) + private const int AttackStateSpan = 0x50; + + private static int _modeChangesAtLastSend = -1; // CombatModeHooks.ModeChanges at the last native attack + private static long _stuckSinceMs; + private static long _rearms, _disarms; + private static long _lastRefusedLogMs = long.MinValue / 2; + + public static long RearmCount => Interlocked.Read(ref _rearms); + public static long DisarmCount => Interlocked.Read(ref _disarms); + + // MAIN THREAD ONLY (NativeAttack's direct part). Clears a stuck attack-in-progress flag + // (NativeAttackRearm) so this attack goes out instead of being queued behind it. + private static void RearmIfStuck(IntPtr cs) + { + bool inProgress = Marshal.ReadByte(cs + InProgressOffset) != 0; + bool? swinging = ClientActionGates.TryReadAttacking(out bool attacking) ? attacking : null; + bool stanceChanged = CombatModeHooks.ModeChanges != _modeChangesAtLastSend; + NativeAttackRearm.Verdict v = NativeAttackRearm.Judge(inProgress, swinging, stanceChanged, + Environment.TickCount64, ref _stuckSinceMs); + if (v == NativeAttackRearm.Verdict.Leave) + return; + + byte queued = Marshal.ReadByte(cs + QueuedOffset); + ClearAttackState(cs, inProgressToo: true); + long n = Interlocked.Increment(ref _rearms); + string why = v == NativeAttackRearm.Verdict.AfterStanceChange + ? "left from before the last stance change" + : $"for {NativeAttackRearm.StuckMs / 1000}s with no swing"; + RynthLog.Compat($"ClientCombat: the client's attack-in-progress flag was set {why} (queued request {queued}, " + + $"server swinging {(swinging == null ? "unknown" : "no")}): cleared, so this native attack goes out " + + $"instead of waiting for an AttackDone that never comes (re-arm #{n})."); + } + + /// <summary> + /// AC's main thread, after the client's combat mode changed (CombatModeHooks). Out of Melee + /// and Missile no attack can go out, so a queued request, a filling power bar or the + /// auto-repeat left from the last stance is cleared: fired in Peace or Magic it would set the + /// attack-in-progress flag with nothing sent (NativeAttackRearm). The flag itself is left + /// to the server's AttackDone (a swing may still be finishing); a stuck one is cleared at the + /// next native attack. + /// </summary> + internal static void DisarmOutOfAttackStance(string why) + { + if (!MainThreadGuard.IsOnMainThread()) + return; + try + { + IntPtr cs = CombatModeHooks.ReadCombatSystemPtr(); + if (cs == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(cs, AttackStateSpan)) + return; + int mode = Marshal.ReadInt32(cs + ModeOffset); + if (!NativeAttackRearm.DisarmFor(mode)) + return; + byte queued = Marshal.ReadByte(cs + QueuedOffset); + byte bar = Marshal.ReadByte(cs + BarBuildingOffset); + byte barAttacks = (byte)(bar != 0 && Marshal.ReadByte(cs + BarNoAttackOffset) == 0 ? 1 : 0); + byte request = Marshal.ReadByte(cs + RequestOffset); + byte repeat = Marshal.ReadByte(cs + AutoRepeatOffset); + if (queued == 0 && bar == 0 && request == 0 && repeat == 0) + return; + ClearAttackState(cs, inProgressToo: false); + long n = Interlocked.Increment(ref _disarms); + // Only an attack that could have fired is worth a line (the auto-repeat and a show-only + // bar are left after every fight with AC's auto-repeat on). + if (queued != 0 || barAttacks != 0 || request != 0) + RynthLog.Compat($"ClientCombat: {why}: mode {mode} with an attack still armed (queued request {queued}, " + + $"power bar attacking {barAttacks}, request held {request}): disarmed, so it can't fire with nothing sent (disarm #{n})."); + } + catch { } + } + + // MAIN THREAD ONLY. The stores ExecuteAttack and HandleAttackDoneEvent make, all at once. + private static void ClearAttackState(IntPtr cs, bool inProgressToo) + { + if (!MainThreadGuard.IsOnMainThread()) + return; + Marshal.WriteByte(cs + QueuedOffset, 0); + Marshal.WriteInt32(cs + QueuedPowerOffset, 0); + Marshal.WriteByte(cs + RequestOffset, 0); + if (Marshal.ReadByte(cs + BarBuildingOffset) != 0) + { + Marshal.WriteByte(cs + BarBuildingOffset, 0); + Marshal.WriteInt32(cs + BarStartOffset, 0); + Marshal.WriteInt32(cs + BarStartOffset + 4, 0); + } + Marshal.WriteByte(cs + AutoRepeatOffset, 0); + if (inProgressToo) + Marshal.WriteByte(cs + InProgressOffset, 0); + } + + private static void LogRefusedMode(int mode) + { + long now = Environment.TickCount64; + if (now - _lastRefusedLogMs < 10_000) + return; + _lastRefusedLogMs = now; + RynthLog.Compat($"ClientCombat: NativeAttack refused: the client's combat mode is {mode}, not Melee or Missile " + + "(the attack would send nothing and leave the client's attack-in-progress flag set)."); + } + + /// <summary>One line for /rc actionstate: the native attack's re-arms and disarms this session.</summary> + public static string DescribeRearms() => + $"native attack: re-arms {RearmCount} (a stuck attack-in-progress flag cleared), disarms {DisarmCount} (an armed attack cleared out of Melee/Missile)"; + /// <summary> /// Check if the player is in a ready position to begin an attack. /// </summary> diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index 6a9ebb1..aed72a1 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -3764,6 +3764,40 @@ internal static class ClientObjectHooks return ReadPhysicsFromWeenie(objectId, weeniePtr, out objCellId, out x, out y, out z, out _, out _, out _, out _); } + // CPhysicsObj.cell: CPhysicsObj::enter_cell (0x005119A0) stores the CObjCell* here and the cell's + // id at +0x4C (m_position.objcell_id); leave_cell (0x00511A20) and change_cell clear it. + private const int PhysicsCellOffset = 0x90; + private const int PhysicsCellIdOffset = PhysicsPositionOffset + PositionObjCellIdOffset; // 0x4C + + /// <summary> + /// The CObjCell* an object's CPhysicsObj is in, and that cell's id (2026-11-04: the nameplates + /// ask whether AC drew the object's cell, report R-20261105-020337-67aa). The pointer is only + /// returned when the cell holds the same id (AcCellSight.IsCell). MAIN THREAD ONLY: false off it. + /// </summary> + internal static bool TryGetObjectCell(uint objectId, out IntPtr cell, out uint cellId) + { + cell = IntPtr.Zero; + cellId = 0; + if (!MainThreadGuard.IsOnMainThread() || _weeniePhysicsObjOffset < 0) return false; + if (!TryGetWeenieObjectPtr(objectId, out IntPtr weeniePtr)) return false; + try + { + if (!IsReadableSpan(weeniePtr + _weeniePhysicsObjOffset, 4)) return false; + IntPtr physicsObj = Marshal.ReadIntPtr(weeniePtr + _weeniePhysicsObjOffset); + if (physicsObj == IntPtr.Zero || !IsReadableSpan(physicsObj, PhysicsCellOffset + 4)) return false; + if (!SmartBoxLocator.IsPointerInModule(Marshal.ReadIntPtr(physicsObj))) return false; + cellId = unchecked((uint)Marshal.ReadInt32(physicsObj + PhysicsCellIdOffset)); + IntPtr c = Marshal.ReadIntPtr(physicsObj + PhysicsCellOffset); + if ((cellId >> 16) == 0) return false; + if (AcCellSight.IsCell(c, cellId)) cell = c; + return true; + } + catch + { + return false; + } + } + /// <summary> /// Reads cell/origin plus the heading quaternion's qw/qz and CPhysicsObj m_state /// from a weenie pointer resolved on the main thread. MAIN THREAD ONLY (callers: diff --git a/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs b/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs index 94cf993..6ba8295 100644 --- a/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs @@ -49,6 +49,12 @@ internal static class CombatModeHooks public static bool IsInstalled { get; private set; } public static string StatusMessage => _statusMessage; + // Every combat mode change this engine saw (the detour, our own client-level request, a + // healed cache). ClientCombatHooks compares it with the count at its last native attack: + // an attack-in-progress flag left from another stance is cleared (NativeAttackRearm). + private static int _modeChanges; + public static int ModeChanges => Volatile.Read(ref _modeChanges); + /// <summary>The ClientCombatSystem singleton, or Zero. Read-only (diagnostics).</summary> internal static IntPtr ReadCombatSystemPtr() { @@ -183,6 +189,13 @@ internal static class CombatModeHooks } _originalSetCombatMode(combatSystem, combatMode, 1); + // The trampoline sets the client's field at once (unless the player isn't ready: + // UseTime applies it later, through the detour), without our detour seeing it. + if (*(int*)(combatSystem + CombatModeOffset) != cur) + { + Interlocked.Increment(ref _modeChanges); + ClientCombatHooks.DisarmOutOfAttackStance($"stance change {cur} -> {combatMode}"); + } LogRequestPath(combatMode, cur, "sent via ClientCombatSystem::SetCombatMode(playerRequested=1)"); return true; @@ -298,6 +311,8 @@ internal static class CombatModeHooks if (currentCombatMode == previousCombatMode) return; + Interlocked.Increment(ref _modeChanges); + ClientCombatHooks.DisarmOutOfAttackStance($"stance change {previousCombatMode} -> {currentCombatMode}"); PluginManager.QueueCombatModeChange(currentCombatMode, previousCombatMode); } @@ -332,6 +347,7 @@ internal static class CombatModeHooks return; // not a mode (a singleton being torn down): leave the cache alone int previous = Interlocked.Exchange(ref _lastObservedCombatMode, raw); if (raw == previous) return; + Interlocked.Increment(ref _modeChanges); RynthLog.Compat($"CombatModeHooks: the cached combat mode was {previous} but the client reads {raw} " + "(no SetCombatMode seen since this engine started, e.g. after a hot reload): cache healed, plugins told."); PluginManager.QueueCombatModeChange(raw, previous); diff --git a/src/RynthCore.Engine/Compatibility/NativeAttackRearm.cs b/src/RynthCore.Engine/Compatibility/NativeAttackRearm.cs new file mode 100644 index 0000000..6251445 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/NativeAttackRearm.cs @@ -0,0 +1,97 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/NativeAttackRearm.cs +// +// When the native attack (ClientCombatHooks.NativeAttack) clears the client's +// stuck attack-in-progress flag first. Pure: no AC memory, so the host test +// (tools/EngineRobustnessTests) compiles it in. +// +// ClientCombatSystem keeps one byte, +0x3D, for "an attack is in progress". +// ExecuteAttack sets it when it sends the attack (and HandleCommenceAttackEvent +// when the server starts the swing); only HandleAttackDoneEvent (0x01A7) clears +// it. While it is set EndAttackRequest sends nothing: it queues the request +// (+0x47) for that AttackDone to replay. ExecuteAttack also sets it when the +// client's mode is neither Melee nor Missile, where it sends no attack at all +// (decompile 0x0056C8C0): a power bar that finished filling, or a queued request +// replayed by a late AttackDone, after a stance change to Peace or Magic. No +// attack went out, so no AttackDone ever comes, and every native attack after +// that is queued forever: the server never swings and never turns the character +// to the target. A regular attack (the raw 0x0008 game action) gets a swing and +// its AttackDone, which is why turning Use Native Attack off made the character +// fight again at once (2026-11-06, a melee character back from a buff-wand swap +// mid-fight: 37 minutes of no swings, 01:29-02:06). +// +// The flag is stuck when it is set while the server is not swinging (AC's +// attacking flag 0x00871EE0, set by CommenceAttack, cleared by AttackDone, is +// clear) and either +// * the combat mode changed since the last native attack: nothing armed in +// the old stance can still be answered in this one; or +// * it has stayed that way for StuckMs: a sent attack is answered (a swing, or +// AttackDone) within a round trip; a move-to the target starts no swing for +// longer, and clearing the flag then only sends a second attack request the +// server folds into the one it is already running. +// With the attacking flag unknown (its patterns didn't resolve) only the stance +// rule applies: a swing in progress can't be told from a stuck flag. +// ============================================================================ +namespace RynthCore.Engine.Compatibility; + +internal static class NativeAttackRearm +{ + /// <summary>How long the flag may stay set with no swing before it counts as stuck.</summary> + public const long StuckMs = 2000; + + // CombatActionHooks.CombatModeMelee / CombatModeMissile (kept here so the rule compiles alone). + private const int Melee = 2, Missile = 4; + + public enum Verdict + { + /// <summary>Nothing stuck (or not yet long enough): attack as usual.</summary> + Leave, + /// <summary>Stuck from before a stance change: clear it now.</summary> + AfterStanceChange, + /// <summary>Stuck for <see cref="StuckMs"/> with no swing: clear it now.</summary> + Stale, + } + + /// <summary> + /// One look before a native attack. <paramref name="stuckSinceMs"/> is the caller's state: + /// when the flag was first seen set with no swing (0 = not seen); this updates it. + /// </summary> + /// <param name="inProgress">ClientCombatSystem +0x3D.</param> + /// <param name="serverSwinging">AC's attacking flag; null when it can't be read.</param> + /// <param name="stanceChangedSinceLastSend">The combat mode changed since the last native attack.</param> + public static Verdict Judge(bool inProgress, bool? serverSwinging, bool stanceChangedSinceLastSend, + long nowMs, ref long stuckSinceMs) + { + if (!inProgress || serverSwinging == true) + { + stuckSinceMs = 0; + return Verdict.Leave; + } + if (stanceChangedSinceLastSend) + { + stuckSinceMs = 0; + return Verdict.AfterStanceChange; + } + if (serverSwinging == null) + return Verdict.Leave; + if (stuckSinceMs == 0) + { + stuckSinceMs = nowMs; + return Verdict.Leave; + } + if (nowMs - stuckSinceMs < StuckMs) + return Verdict.Leave; + stuckSinceMs = 0; + return Verdict.Stale; + } + + /// <summary> + /// True when the client's attack state must be disarmed for <paramref name="mode"/>: out of + /// Melee and Missile no attack can go out, so a queued request (+0x47), a filling power bar + /// (+0x30) or the auto-repeat (+0x44) left from the last stance would only arm the stuck flag. + /// </summary> + public static bool DisarmFor(int mode) => mode != Melee && mode != Missile; + + /// <summary>The native attack goes out only in Melee or Missile (see <see cref="DisarmFor"/>).</summary> + public static bool AttackMode(int mode) => !DisarmFor(mode); +} diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 4daaf54..3330ce1 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -597,6 +597,20 @@ internal static class RynthCoreChatCommands if (IsVerb(sub, "panels", out string acPanelArgs)) { string[] pa = acPanelArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries); + // /rc panels replace <id> <command> | off: AC opening that panel runs the command instead + // (a plugin's own window in its place; AcPanels). Quiet when nothing changed: plugins re-send it. + if (pa.Length >= 3 && pa[0].Equals("replace", StringComparison.OrdinalIgnoreCase) + && ChatCommandReplies.TryPanelId(pa[1], out uint replaceId)) + { + if (!AcPanels.CanReplace) { Fail("Can't replace AC's panels: " + AcPanels.Status); return; } + string command = pa.Length == 3 && pa[2].Equals("off", StringComparison.OrdinalIgnoreCase) + ? string.Empty + : string.Join(' ', pa, 2, pa.Length - 2); + bool changed = AcPanels.Replace(replaceId, command); + if (!changed) { _answered = true; return; } + Reply(command.Length == 0 ? $"AC panel {replaceId} opens as AC's again." : $"AC panel {replaceId} now runs '{command}'."); + return; + } if (pa.Length == 2 && ChatCommandReplies.TryPanelId(pa[1], out uint panelId)) { AcPanels.Op op = pa[0].ToLowerInvariant() switch { "open" => AcPanels.Op.Open, "close" => AcPanels.Op.Close, _ => AcPanels.Op.Toggle }; @@ -607,10 +621,25 @@ internal static class RynthCoreChatCommands 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" : "")}"); + Reply($" {p.Id,3} {p.Class}{(p.Open ? " - open" : "")}" + + (AcPanels.Replaced.TryGetValue(p.Id, out string? by) ? $" - replaced: {by}" : "")); return; } + // /rc title <id>: show that character title (game action 0x2C, CharacterTitleAction; the + // Titles tab of RynthDreamWeave's Skills panel sends it, 2026-11-07). + if (IsVerb(sub, "title", out string titleArgs)) + { + if (!uint.TryParse(titleArgs.Trim(), out uint titleId) || titleId == 0) + { + Fail("Usage: /rc title <title id>"); + return; + } + string? why = CharacterTitleAction.SetTitle(titleId); + if (why == null) Reply($"Title {titleId} asked for."); + else Fail($"Couldn't set title {titleId}: {why}."); + return; + } if (IsVerb(sub, "settings", out string settingsArgs)) { SettingsCommand(settingsArgs); @@ -1488,6 +1517,10 @@ internal static class RynthCoreChatCommands case "onscreen": case "keeponscreen": S.KeepOnScreen = Flag(value, S.KeepOnScreen); break; + case "walls": + case "behindwalls": + // "Hide behind walls" (2026-11-04, report R-20261105-020337-67aa). + S.HideBehindWalls = Flag(value, S.HideBehindWalls); break; case "debuffs": case "debuff": if (sub == "size") diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 5dea9c3..8d6486b 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -948,6 +948,9 @@ public static class EntryPoint // plugin can set (API v91; RynthVision's dungeon light). No floor until one is set. // Kill switch: engine.json DisabledUiHooks ["AmbientLight"]. Step("ambient light hook", AmbientLight.Initialize); + // CEnvCell::GetDrawnThisFrame: where AC keeps its draw stamps, so the nameplates can hide what is + // behind walls (2026-11-04, report R-20261105-020337-67aa). A read, not a hook; no match = cell lists only. + Step("cell sight (nameplates)", AcCellSight.Initialize); Step("vendor hooks", VendorHooks.Initialize); Step("chat callback hooks", ChatCallbackHooks.Initialize); // Flight recorder (Net/FlightRecorder.cs): before the packet hooks that feed it. diff --git a/src/RynthCore.Engine/Hotkeys/HotkeyModel.cs b/src/RynthCore.Engine/Hotkeys/HotkeyModel.cs index b2c6edb..ddb3b08 100644 --- a/src/RynthCore.Engine/Hotkeys/HotkeyModel.cs +++ b/src/RynthCore.Engine/Hotkeys/HotkeyModel.cs @@ -423,15 +423,19 @@ internal enum HotkeyGate internal static class HotkeyRules { /// <summary> - /// Whether a bound key may fire. Never while the player is typing: in a RynthCore text box or in - /// AC's own chat entry. When AC's focus can't be read, only keys that can't be typing fire. + /// Whether a bound key may fire. Not while the player is typing (in a RynthCore text box or in AC's + /// own chat entry), except an F key, with or without modifiers: it types nothing, so it fires there + /// too (owner, 2026-11-06: a stamina kit on an F key "rarely goes off" because the presses came + /// while AC's chat held the keyboard). Ctrl combos stay held while typing (copy, paste, select all). + /// When AC's focus can't be read, only keys that can't be typing fire. /// </summary> public static HotkeyGate Check(in TypingState s, KeyCombo combo) { if (!s.InWorld) return HotkeyGate.NotInWorld; if (!s.GameFocused) return HotkeyGate.NotFocused; - if (s.RynthTextFocus) return HotkeyGate.RynthTyping; - if (s.AcTextFocus == true) return HotkeyGate.AcTyping; + bool fKey = HotkeyKeys.IsFunctionKey(combo.Vk); + if (s.RynthTextFocus && !fKey) return HotkeyGate.RynthTyping; + if (s.AcTextFocus == true && !fKey) return HotkeyGate.AcTyping; if (s.AcTextFocus == null && !CantBeTyping(combo)) return HotkeyGate.AcUnknownTextKey; return HotkeyGate.Fire; } @@ -445,8 +449,8 @@ internal static class HotkeyRules HotkeyGate.Fire => "hotkeys fire", HotkeyGate.NotInWorld => "not in the world", HotkeyGate.NotFocused => "the game window isn't focused", - HotkeyGate.RynthTyping => "typing in a RynthCore text box", - HotkeyGate.AcTyping => "typing in AC's chat (or another AC text box)", + HotkeyGate.RynthTyping => "typing in a RynthCore text box (F-key hotkeys still fire)", + HotkeyGate.AcTyping => "typing in AC's chat or another AC text box (F-key hotkeys still fire)", HotkeyGate.AcUnknownTextKey => "AC's typing state is unknown; only Ctrl/Alt/F-key hotkeys fire", _ => g.ToString(), }; diff --git a/src/RynthCore.Engine/Hotkeys/HotkeyService.cs b/src/RynthCore.Engine/Hotkeys/HotkeyService.cs index b1a1f59..3ba7e63 100644 --- a/src/RynthCore.Engine/Hotkeys/HotkeyService.cs +++ b/src/RynthCore.Engine/Hotkeys/HotkeyService.cs @@ -68,6 +68,8 @@ internal static class HotkeyService private static string _captureNote = string.Empty; private static HotkeyGate _lastGate = HotkeyGate.Fire; + private const long HeldBackLogMs = 2000; + private static long _lastHeldLogAt; private static readonly uint OurPid = (uint)Environment.ProcessId; // The ILT section's panels are offered only where the bar shows its ILT button. @@ -318,11 +320,18 @@ internal static class HotkeyService if (b == null) return false; HotkeyGate gate = HotkeyRules.Check(ReadTypingState(rynthTextFocus), combo); - if (gate != _lastGate) + // Every held-back press is logged (at most one line per HeldBackLogMs), not only a change + // of reason: a stamina kit on a hotkey "rarely goes off" and the log showed one held-back + // line, so the presses that followed for the same reason left no trace (report + // R-20261106-040904-bb4b, 2026-11-05). AC's focus element says which text box had the keys. + long now = Environment.TickCount64; + if (gate != HotkeyGate.Fire && (gate != _lastGate || now - _lastHeldLogAt >= HeldBackLogMs)) { - _lastGate = gate; - if (gate != HotkeyGate.Fire) RynthLog.UI($"Hotkeys: {combo} held back - {HotkeyRules.Describe(gate)}."); + _lastHeldLogAt = now; + RynthLog.UI($"Hotkeys: {combo} held back - {HotkeyRules.Describe(gate)}." + + (gate == HotkeyGate.AcTyping ? " " + AcKeyboardFocus.Describe() : "")); } + _lastGate = gate; if (gate != HotkeyGate.Fire) return false; Tracker.Took(vk); diff --git a/src/RynthCore.Engine/ImGui/DX9Backend.cs b/src/RynthCore.Engine/ImGui/DX9Backend.cs index 4b48d45..77f4a66 100644 --- a/src/RynthCore.Engine/ImGui/DX9Backend.cs +++ b/src/RynthCore.Engine/ImGui/DX9Backend.cs @@ -540,8 +540,20 @@ internal static unsafe class DX9Backend if (!_initialized) return; ImDrawData* dd = drawData.NativePtr; if (dd == null) return; - RenderLists((ImDrawList**)dd->CmdLists.Data, dd->CmdListsCount, dd->TotalVtxCount, dd->DisplayPos, dd->DisplaySize, - pDevice, midFrame: false); + ImDrawList** lists = (ImDrawList**)dd->CmdLists.Data; + int count = dd->CmdListsCount; + // Windows drawn under AC's UI (UnderUiLayer, a plugin window's "layer": "underUi") were presented + // at AC's UI pass: left out here, the rest keep their order. + if (UnderUiLayer.HasWindowLists && count > 0 && count <= 512) + { + ImDrawList** kept = stackalloc ImDrawList*[count]; + int n = 0; + for (int i = 0; i < count; i++) + if (!UnderUiLayer.IsWindowList(lists[i])) kept[n++] = lists[i]; + RenderLists(kept, n, dd->TotalVtxCount, dd->DisplayPos, dd->DisplaySize, pDevice, midFrame: false); + return; + } + RenderLists(lists, count, dd->TotalVtxCount, dd->DisplayPos, dd->DisplaySize, pDevice, midFrame: false); } /// <summary> diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index acec36a..89ba804 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -998,9 +998,14 @@ internal static class EngineFrameController // A docked click-through panel under the cursor that zooms with the wheel (the radar's // "Mouse wheel still zooms"): the wheel is its own, clicks and moves still the game's. Win32Backend.UpdateCaptureFlags(io.WantCaptureMouse || Hud.MonsterHud.WantsMouse, typing, - mouseMovesToGame: !io.WantCaptureMouse && Hud.MonsterHud.MouseMovesToGame, + // An under-UI panel only hovered: the same (ImGuiPanelHost.UnderUiHovered). + mouseMovesToGame: (!io.WantCaptureMouse && Hud.MonsterHud.MouseMovesToGame) + || (PanelsLive && ImGuiPanelHost.UnderUiHovered), wheelToUi: !io.WantCaptureMouse && PanelsLive && ImGuiPanelHost.WheelWanted); Compatibility.AcMouseOver.Tick(); // /rc acmouse watch, when on + // A RynthCore window's move or resize spot: retail's window-control cursor (RetailCursors). + RetailCursors.Update(ImGuiNET.ImGui.GetMouseCursor(), + Win32Backend.UiCaptureEnabled && (io.WantCaptureMouse || (PanelsLive && ImGuiPanelHost.UnderUiHovered))); // The UI is released (Insert): no text box keeps the keyboard. Keys are not // gated by the toggle any more (Win32Backend.UpdateCaptureFlags), so the edit // ends instead and the next keys go to the game. diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index 1fdcbc7..2236b4b 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -88,7 +88,11 @@ internal sealed record PanelSpec( 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); + bool DrawScale = false, + // Drawn under AC's own UI, like a native AC window (a plugin window's "layer": "underUi", + // 2026-11-07): built in the normal frame, presented at AC's UI pass (UnderUiLayer), and + // click-through wherever an AC window covers the cursor (AcMouseOver). Docked only. + bool UnderUi = false); /// <summary>An ImGui panel face. One instance per open; dropped on close.</summary> internal interface IImGuiPanel @@ -594,6 +598,12 @@ internal static class ImGuiPanelHost /// </summary> public static bool WheelWanted { get; private set; } + /// <summary> + /// The last DrawAll: an under-UI panel (PanelSpec.UnderUi) is only hovered (no button held), so the + /// mouse moves still go to AC and its own mouse-over stays current (EngineFrameController). AC thread. + /// </summary> + public static bool UnderUiHovered { get; private set; } + // ── Frame (AC thread) ────────────────────────────────────────────── /// <summary> @@ -608,6 +618,7 @@ internal static class ImGuiPanelHost int drawn = 0; _frameScale = uiScale; WheelWanted = false; + UnderUiHovered = false; float placeScale = PlacementScale(); ApplyFaceChanges(placeScale); // plugin windows taking over (or giving back) engine panels ApplyLayoutSwitch(placeScale); // another character's panel layout (UI/PanelLayout) @@ -725,25 +736,43 @@ internal static class ImGuiPanelHost OpenSavedOpen(); } - /// <summary>Opens the engine panels the panel store has saved open (ImGui or Both docked face). AC thread.</summary> + /// <summary> + /// Opens the engine panels and plugin windows the panel store has saved open (ImGui or Both docked + /// face). AC thread. + /// </summary> private static void OpenSavedOpen() { List<string> titles = new(); - // Script windows (dynamic) open when their owner says so, not from the saved state. + // Script windows (dynamic) open when their owner says so, not from the saved state. Plugin + // windows (dynamic too) follow it like engine panels (2026-11-05): one registered before the + // character's layout was in use (a hot reload, a name that came late, a relogin) decided its + // open state from the layout before, and opened here it comes back as this layout left it. lock (Sync) foreach (Entry e in Entries.Values) - if (!e.Dynamic) titles.Add(e.Title); + if (PanelLayoutPolicy.FollowsSavedOpenState(KindOf(e))) titles.Add(e.Title); foreach (string title in titles) { if (!PanelStateStore.TryGetPanel(title, out PanelStateStore.PanelEntry saved)) continue; if (!saved.Open) continue; - PanelFace face = PanelRouter.ResolveDockedFace(title); - if (face is not (PanelFace.ImGui or PanelFace.Both)) continue; - // Saved popped out: it reopens popped out (Apply reads the saved entry). - Open(title); + OpenSaved(title); } } + /// <summary>Opens a panel saved open, when its docked face is ImGui (or Both). AC thread.</summary> + private static void OpenSaved(string title) + { + PanelFace face = PanelRouter.ResolveDockedFace(title); + if (face is not (PanelFace.ImGui or PanelFace.Both)) return; + // Saved popped out: it reopens popped out (Apply reads the saved entry). + Open(title); + } + + /// <summary>An engine panel, a plugin's window (UI/Sections/PluginWindows) or a script window. AC thread.</summary> + private static WindowKind KindOf(Entry e) => + !e.Dynamic ? WindowKind.EnginePanel + : !e.PendingRemoval && UI.Sections.PluginWindows.IsHosted(e.Title) ? WindowKind.PluginWindow + : WindowKind.ScriptWindow; + // ── Panel layout per character (UI/PanelLayout) ─────────────────────── private static volatile bool _layoutSwitched; @@ -756,9 +785,12 @@ internal static class ImGuiPanelHost /// <summary> /// After a layout switch: each shown panel is placed from the new layout (docked spot and size, popped - /// out or not, and where); an engine panel the layout has saved closed closes, without saving over - /// it; engine panels it has saved open open. Plugin and script windows stay open (their owners + /// out or not, and where); an engine panel or plugin window the layout has saved closed closes, + /// without saving over it; the ones it has saved open open. Script windows stay open (their owners /// decide that) and move. Nothing shown (a hot reload, the first login): only the opening. AC thread. + /// (Plugin windows follow the layout's open state since 2026-11-05: they register from the plugins' + /// manifests seconds after a login, and one registered while the store held another layout kept + /// that layout's open state for the whole session.) /// </summary> private static void ApplyLayoutSwitch(float placeScale) { @@ -769,12 +801,17 @@ internal static class ImGuiPanelHost lock (Sync) order = DrawOrder; foreach (Entry e in order) { - if (!e.Shown) continue; bool has = PanelStateStore.TryGetPanel(e.Title, out PanelStateStore.PanelEntry saved); - if (!e.Dynamic && remember && has && !saved.Open) + switch (PanelLayoutPolicy.StepAtSwitch(KindOf(e), e.Shown, remember, has, saved.Open)) { - CloseQuietly(e); - continue; + case SwitchStep.Leave: + continue; + case SwitchStep.Open: + OpenSaved(e.Title); // queued; applied by this DrawAll, placed from the new layout + continue; + case SwitchStep.Close: + CloseQuietly(e); + continue; } if (e.Popped) { @@ -787,7 +824,6 @@ internal static class ImGuiPanelHost else if (!has) Persist(e, open: true, placeScale); // new to this layout: saved here, so it reopens here } - if (remember) OpenSavedOpen(); // queued; applied by this DrawAll (an open one is skipped) RynthLog.UI("ImGuiPanelHost: the open panels took their places from the panel layout now in use."); } @@ -1183,10 +1219,25 @@ internal static class ImGuiPanelHost bool clickThrough = false; // Popped out, a panel is always interactive (like the Avalonia pop-out was). if (!popped) try { clickThrough = entry.Instance?.ClickThrough ?? false; } catch { } + // Under AC's UI: where an AC window covers the cursor the click is AC's (unless a press that + // began on this panel is still held, so a drag over an AC window isn't dropped). + bool underUi = spec.UnderUi && !popped; + if (underUi && !clickThrough && !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) + && Compatibility.AcMouseOver.Current() == Compatibility.AcMouseTarget.AcWindow) + clickThrough = true; if (clickThrough) flags |= ImGuiWindowFlags.NoInputs; bool childOpen = false; ImGuiNET.ImGui.Begin(entry.WindowId, flags); + if (underUi) + { + UnderUiLayer.AddWindowList(ImGuiNET.ImGui.GetWindowDrawList()); + // Only hovered: the mouse moves still reach AC, so its own mouse-over follows the cursor + // onto an AC window covering this one (as the nameplates do, MonsterHud.MouseMovesToGame). + if (!clickThrough && !ImGuiNET.ImGui.IsAnyMouseDown() + && ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows)) + UnderUiHovered = true; + } try { ImGuiNET.ImGui.PopStyleVar(3); // the frame's own vars; the body gets normal padding @@ -1263,6 +1314,7 @@ internal static class ImGuiPanelHost if (clickThrough) bodyFlags |= ImGuiWindowFlags.NoInputs; childOpen = ImGuiNET.ImGui.BeginChild("##body", bodySize, ImGuiChildFlags.AlwaysUseWindowPadding, bodyFlags); ImGuiNET.ImGui.PopStyleVar(); + if (underUi && childOpen) UnderUiLayer.AddWindowList(ImGuiNET.ImGui.GetWindowDrawList()); if (childOpen) { diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/DebuffIcon.cs b/src/RynthCore.Engine/ImGui/MonsterHud/DebuffIcon.cs index e378650..f3a7283 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/DebuffIcon.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/DebuffIcon.cs @@ -15,11 +15,36 @@ internal enum DebuffKind : byte Imperil, MagicYield, Defense, Attributes, Vitals, Movement, Skills, Dot, Other, } -/// <summary>One icon: the kind, when its soonest entry expires, that entry's full length, and how many categories it merges.</summary> +/// <summary> +/// One icon: the kind, when its soonest entry expires, that entry's full length, how many categories it +/// merges, and (2026-11-07, for the hover tooltip) the spell heading each merged category, up to +/// <see cref="MaxSpells"/> (Stack can be higher: the tooltip says how many more). +/// </summary> internal struct DebuffIcon { + public const int MaxSpells = 4; + public DebuffKind Kind; public long Expiry; // Stopwatch ticks public float Duration; // seconds, of the entry expiring first public int Stack; + public uint Spell0, Spell1, Spell2, Spell3; + public int SpellCount; // ids held (<= MaxSpells) + + /// <summary>Adds a spell id (0 and repeats are skipped; past MaxSpells it is only counted by Stack).</summary> + public void AddSpell(uint id) + { + if (id == 0 || SpellCount >= MaxSpells) return; + for (int i = 0; i < SpellCount; i++) if (SpellAt(i) == id) return; + switch (SpellCount) + { + case 0: Spell0 = id; break; + case 1: Spell1 = id; break; + case 2: Spell2 = id; break; + default: Spell3 = id; break; + } + SpellCount++; + } + + public readonly uint SpellAt(int i) => i switch { 0 => Spell0, 1 => Spell1, 2 => Spell2, 3 => Spell3, _ => 0 }; } diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/DebuffIconRow.cs b/src/RynthCore.Engine/ImGui/MonsterHud/DebuffIconRow.cs index c1ce395..e945a0b 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/DebuffIconRow.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/DebuffIconRow.cs @@ -14,19 +14,84 @@ // the plate's scale x its own "Debuff icon size" setting (monster plates and // your plate apart, neither tied to a text size); the stack digit and "+N" // scale the plate's small text by it. At 100 % the row is exactly as before. +// Hover tooltips (2026-11-07): a row painted with tips on notes the icon +// under the cursor (the last row painted wins: it is on top); after every +// plate is painted, MonsterHud.Draw calls ShowHoverTip, which names the +// kind, what it does, its spells and when the first ends (DebuffTip), the +// "+N" count, or what the "debuffed by others" marker means. No tip while an +// ImGui panel has the mouse, the Insert UI toggle is off, the plate is +// fading, or (rows drawn under AC's windows) one of AC's windows covers it. // Render thread only. Engine-owned statics. // ============================================================================ using System; +using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Numerics; using ImGuiNET; +using RynthCore.Engine.Compatibility; namespace RynthCore.Engine.ImGuiBackend.Hud; +/// <summary>Whose row it is, for the hover tooltip (Off: no tooltip).</summary> +internal enum DebuffRowTips : byte { Off, Monster, Self } + internal static class DebuffIconRow { + private enum Hit : byte { None, Icon, More, Others } + + private readonly record struct TipKey(Hit Hit, DebuffKind Kind, uint S0, uint S1, uint S2, uint S3, int Stack, int Secs, DebuffRowTips Row, int More); + + // The icon under the cursor this frame (BeginHover clears it; the topmost row painted wins). + private static Hit _hit; + private static DebuffIcon _hitIcon; + private static int _hitMore; + private static DebuffRowTips _hitRow; + private static bool _hitUnderUi; + // The last tooltip built, kept while the cursor stays on the same icon and second. + private static TipKey _tipKey; + private static string _tipText = ""; + private static readonly List<string> TipNames = new(DebuffIcon.MaxSpells); + + /// <summary>Start of a HUD frame: nothing hovered yet.</summary> + internal static void BeginHover() => _hit = Hit.None; + + /// <summary> + /// End of a HUD frame (inside the ImGui frame): the tooltip of the icon the cursor is on, if any. + /// A row drawn under AC's windows gets none where one of AC's windows covers the cursor. + /// </summary> + internal static void ShowHoverTip(long now) + { + if (_hit == Hit.None) return; + if (_hitUnderUi && MonsterHud.AcWindowCoversCursor()) return; + int secs = _hit == Hit.Icon ? (int)Math.Ceiling((_hitIcon.Expiry - now) / (double)Stopwatch.Frequency) : 0; + var key = new TipKey(_hit, _hitIcon.Kind, _hitIcon.Spell0, _hitIcon.Spell1, _hitIcon.Spell2, _hitIcon.Spell3, + _hitIcon.Stack, secs, _hitRow, _hitMore); + if (key != _tipKey || _tipText.Length == 0) + { + _tipKey = key; + _tipText = _hit switch + { + Hit.Others => DebuffTip.Others, + Hit.More => DebuffTip.More(_hitMore), + _ => IconTip(in _hitIcon, secs, _hitRow), + }; + } + SafeImGui.SetTooltip(_tipText); + } + + private static string IconTip(in DebuffIcon ic, int secs, DebuffRowTips row) + { + TipNames.Clear(); + for (int i = 0; i < ic.SpellCount; i++) + if (PortalSpellTable.TryGetById(ic.SpellAt(i), out DebuffSpell s) && s.Name.Length > 0) + TipNames.Add(s.Name); + return DebuffTip.Text(ic.Kind, TipNames, ic.Stack, secs, estimated: row == DebuffRowTips.Monster, self: row == DebuffRowTips.Self); + } + + private static bool Inside(Vector2 m, Vector2 p0, Vector2 p1) => m.X >= p0.X && m.X <= p1.X && m.Y >= p0.Y && m.Y <= p1.Y; + /// <summary>Icons per row; more shows "+N" (the last slot makes room for it).</summary> internal const int MaxIcons = 5; /// <summary>Icons blink in their last seconds.</summary> @@ -66,12 +131,23 @@ internal static class DebuffIconRow /// <paramref name="row"/> holds every length (the plate's scale x its icon size setting); /// <paramref name="smallFont"/>/<paramref name="smallSize"/> are the plate's small text, which the /// stack digit and "+N" scale by the icon size; <paramref name="overflowKey"/>/<paramref name="overflowText"/> - /// cache the "+N" string per row. <paramref name="now"/> is Stopwatch ticks. + /// cache the "+N" string per row. <paramref name="now"/> is Stopwatch ticks. <paramref name="tips"/>: + /// whose row, for the hover tooltip (Off: none); <paramref name="underUi"/>: drawn under AC's windows. /// </summary> internal static void Paint(ImDrawListPtr dl, DebuffIcon[] icons, int count, bool others, in DebuffRowMetrics row, ImFontPtr smallFont, float smallSize, ref int overflowKey, ref string overflowText, - float cx, float top, float a, long now) + float cx, float top, float a, long now, DebuffRowTips tips = DebuffRowTips.Off, bool underUi = false) { + // Hover: only a settled plate, with the UI toggle on and no ImGui panel holding the mouse. + Vector2 mouse = default; + bool hover = false; + if (tips != DebuffRowTips.Off && a >= 0.25f && Win32Backend.IsUiCaptureEnabled()) + { + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + hover = !io.WantCaptureMouse; + mouse = io.MousePos; + } + float sz = row.Icon, gap = row.Gap; int shown = Prepare(icons.Length, count, in row, ref smallFont, ref smallSize, ref overflowKey, ref overflowText, out int overflow, out string more, out float moreTextW); @@ -110,6 +186,9 @@ internal static class DebuffIconRow dl.AddRectFilled(new Vector2(i0.X, ly), new Vector2(i1.X, ly + lineH), MonsterHud.Mul(MonsterHud.Outline, a * 0.8f)); if (frac > 0f) dl.AddRectFilled(new Vector2(i0.X, ly), new Vector2(i0.X + MathF.Max(1f, sz * frac), ly + lineH), MonsterHud.Mul(tint, a * blink)); + // The icon and its countdown line, with the gap to the next icon split between them (no dead spots). + if (hover && Inside(mouse, i0 - new Vector2(gap * 0.5f, 0f), new Vector2(i1.X + gap * 0.5f, ly + lineH))) + Note(Hit.Icon, in ic, 0, tips, underUi); x += sz + gap; } @@ -118,6 +197,8 @@ internal static class DebuffIconRow var mp = new Vector2(x, MathF.Round(top + (sz - smallSize) * 0.5f)); MonsterHud.OutlinedText(dl, smallFont, smallSize, mp, a, more); dl.AddText(smallFont, smallSize, mp, MonsterHud.Mul(MonsterHud.DimText, a), more); + if (hover && Inside(mouse, new Vector2(x, top), new Vector2(x + moreW, top + sz))) + Note(Hit.More, default, overflow, tips, underUi); x += moreW + gap; } @@ -126,9 +207,20 @@ internal static class DebuffIconRow var i0 = new Vector2(x, top); dl.AddRectFilled(i0, i0 + new Vector2(sz, sz), MonsterHud.Mul(IconBack, a * 0.8f), row.Round); PhosphorIcons.DrawCentered(dl, iconFont, glyphPx, PhosphorIcons.UsersThree, i0, new Vector2(sz, sz), MonsterHud.Mul(OthersTint, a * 0.8f)); + if (hover && Inside(mouse, i0, i0 + new Vector2(sz, sz))) + Note(Hit.Others, default, 0, tips, underUi); } } + private static void Note(Hit hit, in DebuffIcon icon, int more, DebuffRowTips row, bool underUi) + { + _hit = hit; + _hitIcon = icon; + _hitMore = more; + _hitRow = row; + _hitUnderUi = underUi; + } + /// <summary> /// The row's width as <see cref="Paint"/> lays it out (same arguments): the plates' layout uses it so /// their box (crowding, clicks, the screen clamp) holds an enlarged row. diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/DebuffTip.cs b/src/RynthCore.Engine/ImGui/MonsterHud/DebuffTip.cs new file mode 100644 index 0000000..09bcd2c --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/DebuffTip.cs @@ -0,0 +1,106 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/DebuffTip.cs +// The words of the debuff icons' hover tooltip (2026-11-07), on the monster +// plates and your own plate: what the kind is, what it does, the spells +// behind the icon and when the first of them ends. DebuffIconRow finds the +// icon under the cursor and shows the text. +// Plain text, no engine dependencies (the offline tests compile it in). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +internal static class DebuffTip +{ + /// <summary>The kind's name, the tooltip's first line.</summary> + internal static string Title(DebuffKind kind) => kind switch + { + DebuffKind.VulnFire => "Fire vulnerability", + DebuffKind.VulnCold => "Cold vulnerability", + DebuffKind.VulnLightning => "Lightning vulnerability", + DebuffKind.VulnAcid => "Acid vulnerability", + DebuffKind.VulnSlash => "Slashing vulnerability", + DebuffKind.VulnPierce => "Piercing vulnerability", + DebuffKind.VulnBludgeon => "Bludgeoning vulnerability", + DebuffKind.Imperil => "Imperil", + DebuffKind.MagicYield => "Magic Yield", + DebuffKind.Defense => "Defense lowered", + DebuffKind.Attributes => "Attributes lowered", + DebuffKind.Vitals => "Vitals lowered", + DebuffKind.Movement => "Slowed", + DebuffKind.Skills => "Skills lowered", + DebuffKind.Dot => "Damage over time", + _ => "Debuff", + }; + + /// <summary>What it does, on a monster (<paramref name="self"/> false) or on you.</summary> + internal static string Effect(DebuffKind kind, bool self) + { + string who = self ? "You take" : "Takes"; + return kind switch + { + DebuffKind.VulnFire => $"{who} more fire damage.", + DebuffKind.VulnCold => $"{who} more cold damage.", + DebuffKind.VulnLightning => $"{who} more lightning damage.", + DebuffKind.VulnAcid => $"{who} more acid damage.", + DebuffKind.VulnSlash => $"{who} more slashing damage.", + DebuffKind.VulnPierce => $"{who} more piercing damage.", + DebuffKind.VulnBludgeon => $"{who} more bludgeoning damage.", + DebuffKind.Imperil => self ? "Your armor is lowered: physical hits land harder." : "Armor lowered: physical hits land harder.", + DebuffKind.MagicYield => self ? "Your magic defense is lowered: spells land on you more often." : "Magic defense lowered: spells land more often.", + DebuffKind.Defense => self ? "Your melee or missile defense is lowered: attacks hit you more often." : "Melee or missile defense lowered: attacks hit more often.", + DebuffKind.Attributes => "Strength, Endurance, Quickness, Coordination, Focus or Self lowered.", + DebuffKind.Vitals => "Maximum health, stamina or mana, or how fast they come back, lowered.", + DebuffKind.Movement => "Run speed lowered.", + DebuffKind.Skills => self ? "One or more of your skills lowered." : "One or more skills lowered.", + DebuffKind.Dot => $"{who} damage every few seconds.", + _ => self ? "A harmful spell on you." : "A harmful spell of yours on it.", + }; + } + + /// <summary> + /// An icon's tooltip. <paramref name="spells"/> are the names known (the icon holds up to + /// DebuffIcon.MaxSpells; <paramref name="stack"/> counts every category it merges). + /// <paramref name="estimated"/>: the end is worked out from the spell's length (the monster + /// plates), not read from the server (your plate). + /// </summary> + internal static string Text(DebuffKind kind, IReadOnlyList<string> spells, int stack, double remainingSec, + bool estimated, bool self) + { + var sb = new StringBuilder(160); + sb.Append(Title(kind)).Append('\n').Append(Effect(kind, self)); + foreach (string s in spells) + if (s.Length > 0) sb.Append("\n ").Append(s); + int more = Math.Max(stack, spells.Count) - spells.Count; + if (more > 0 && spells.Count > 0) + sb.Append("\n and ").Append(more.ToString(CultureInfo.InvariantCulture)).Append(" more"); + if (remainingSec > 0) + { + sb.Append('\n').Append(stack > 1 ? "First one ends in " : "Ends in "); + if (estimated) sb.Append("about "); + sb.Append(Time(remainingSec)); + } + return sb.ToString(); + } + + /// <summary>The "debuffed by others" marker's tooltip (monster plates only).</summary> + internal const string Others = + "Debuffed by someone else\nIts last appraisal showed attributes or vitals lowered that your own spells don't explain."; + + /// <summary>The "+N" tooltip.</summary> + internal static string More(int n) => + n == 1 ? "1 more debuff than fits in the row." : $"{n.ToString(CultureInfo.InvariantCulture)} more debuffs than fit in the row."; + + /// <summary>"42 s", "1:05", "1:02:03".</summary> + internal static string Time(double sec) + { + int s = (int)Math.Ceiling(Math.Max(0, sec)); + if (s < 60) return s.ToString(CultureInfo.InvariantCulture) + " s"; + if (s < 3600) return $"{s / 60}:{s % 60:00}"; + return $"{s / 3600}:{s / 60 % 60:00}:{s % 60:00}"; + } +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs index f4f8a58..8b3727f 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs @@ -41,6 +41,10 @@ // position is read (main thread, a handful of objects) and projected with // the engine's camera capture (GameMatrixCapture), so plates stick to // moving monsters without the 10 Hz snapshot's stepping. +// Behind walls (2026-11-04, report R-20261105-020337-67aa; PlateSight): the +// scan skips objects AC's cell lists rule out from the camera's cell, and +// each frame a plate whose room AC didn't draw (or, seen from inside, an +// outdoor object no drawn doorway covers) is hidden and takes no click. // // World -> screen: AC transforms geometry on the CPU; GameMatrixCapture // rebuilds the view from SmartBox's camera frame and hooks SetTransform for @@ -121,6 +125,7 @@ internal static class MonsterHud public bool Chosen; // in the latest snapshot public bool Gone; // live position read failed (despawned / died) public bool OnScreen; + public bool Hidden; // behind walls this frame (PlateSight): fades out, takes no click public bool Appeared; // became visible this frame: layout snaps instead of easing public float Alpha; // smoothed, 0..1 public float Scale = 1f; // smoothed @@ -324,6 +329,7 @@ internal static class MonsterHud PlateDebuffs.Clear(); CombatText.Clear(); PlayerPlate.Reset(); + PlateSight.Reset(); Classes.Clear(); _playerId = 0; } @@ -387,6 +393,11 @@ internal static class MonsterHud float portalD2 = portalD * portalD; float portalTargetD2 = MathF.Max(portalD2, 100f * 100f); // and a selected portal bool targetIsPortal = false; + // Behind walls (2026-11-04, report R-20261105-020337-67aa): objects the cell lists already rule + // out (another room, another building, outdoors from a dungeon) are no candidates, so the + // hidden NPCs of a town don't use up the caps; DrawPlates asks AC's draw stamps each frame. + bool walls = MonsterHudSettings.HideBehindWalls; + if (walls) PlateSight.Refresh(pCell); int pass = ++_classPass; Candidates.Clear(); @@ -442,6 +453,7 @@ internal static class MonsterHud if (!ClientObjectHooks.TryGetSnapshotPosition(id, out uint cell, out float x, out float y, out float z)) continue; if (!TryOffset(pCell, cell, out float ox, out float oy)) continue; + if (walls && !PlateSight.ShowCoarse(cell)) continue; float dx = x + ox - px, dy = y + oy - py, dz = z - pz; float d2 = dx * dx + dy * dy + dz * dz; if (portal) @@ -797,6 +809,7 @@ internal static class MonsterHud /// </summary> public static void Draw(float uiScale, bool worldVisible = true) { + DebuffIconRow.BeginHover(); if (!_hasContent) { ResetClick(); PlayerPlate.DropDrag(); return; } try { @@ -809,6 +822,8 @@ internal static class MonsterHud } // The player plate fixed on screen: ImGui's background list (the normal UI pass), not the layer above. PlayerPlate.DrawScreen(ref f); + // The debuff icon under the cursor (any plate's): its tooltip. + DebuffIconRow.ShowHoverTip(f.Now); } catch (Exception ex) { @@ -902,6 +917,9 @@ internal static class MonsterHud float kScale = 1f - MathF.Exp(-dt * 10f); float kBar = 1f - MathF.Exp(-dt * 14f); uint target = ClientHelperHooks.GetSelectedItemId(); + // Behind walls (2026-11-04, report R-20261105-020337-67aa): AC's draw stamp, sampled once a frame. + bool walls = MonsterHudSettings.HideBehindWalls; + if (walls) PlateSight.BeginFrame(f.PlayerCell); DrawOrder.Clear(); Evict.Clear(); @@ -937,9 +955,13 @@ internal static class MonsterHud p.IsAttacker = !label && MonsterHudData.AttackedRecently(p.Name, AttackerMemorySec); p.OnScreen = false; + bool headFront = false; + Vector2 headPx = default; // where the head projects, before Keep on screen pins it if (p.HasWorld && GameMatrixCapture.WorldToScreen(p.LastWx, p.LastWy, p.LastWz, out float sx, out float sy)) { sx *= f.MapX; sy *= f.MapY; + headFront = true; + headPx = new Vector2(sx, sy); const float margin = 60f; if (MonsterHudSettings.KeepOnScreen) { @@ -964,7 +986,11 @@ internal static class MonsterHud float maxD = !label ? monsterMaxD : p.Kind == RadarKind.Portal ? portalMaxD : labelMaxD; float t = maxD > 1f ? Math.Clamp(p.Distance / maxD, 0f, 1f) : 0f; float distFade = fade ? 1f - 0.55f * SmoothStep(0.45f, 1f, t) : 1f; - bool show = p.OnScreen && (p.Chosen || p.IsTarget) && !p.Gone; + // An object the player can't see because of walls: no plate (it fades as one leaving the + // screen does) and, from this frame, no click (PlateClick skips it). Asked only for a plate that would draw. + p.Hidden = walls && p.OnScreen && (p.Chosen || p.IsTarget) && !p.Gone && + !PlateSight.Show(ref f, p.Id, p.LastCell, headFront, headPx, p.LastWx, p.LastZ, p.LastWz); + bool show = p.OnScreen && !p.Hidden && (p.Chosen || p.IsTarget) && !p.Gone; float alphaTarget = show ? opacity * (p.IsTarget ? 1f : distFade) : 0f; bool wasVisible = p.Alpha > 0.01f; p.Appeared = !wasVisible; @@ -1013,6 +1039,7 @@ internal static class MonsterHud PlateClick(f.UiScale, f.UnderUi); // ── Paint: farthest first, nearest (and the target) on top ── + _paintUnderUi = f.UnderUi; for (int i = DrawOrder.Count - 1; i >= 0; i--) { Plate p = DrawOrder[i]; @@ -1213,7 +1240,7 @@ internal static class MonsterHud Vector2 m = io.MousePos; foreach (Plate p in DrawOrder) { - if (p.Gone || p.Alpha < 0.25f) continue; // fading in or out: not a target yet + if (p.Gone || p.Hidden || p.Alpha < 0.25f) continue; // fading in or out (or behind walls): not a target Vector4 r = RectAt(p, p.Nudge, uiScale); if (m.X < r.X || m.X > r.Z || m.Y < r.Y || m.Y > r.W) continue; _hoverId = p.Id; @@ -1251,6 +1278,14 @@ internal static class MonsterHud } private static int _leftToAcLogged; + private static bool _paintUnderUi; // this frame's plates are on the layer under AC's windows + + /// <summary> + /// One of AC's windows is under the cursor (the debuff tooltips of rows drawn under AC's UI skip it). + /// Same rule as the plate click, without its log line. AC's UI state unreadable: false. + /// </summary> + internal static bool AcWindowCoversCursor() => + !AcMouseOverRules.UnderUiOverlayMayTakeClick(AcMouseOver.Read().Target); /// <summary>AC's own UI has one of its windows under the cursor (not the 3D world). AC's main thread.</summary> private static bool AcWindowUnderCursor() @@ -1352,7 +1387,8 @@ internal static class MonsterHud // Under the bar: the debuff icons. if (icons) DebuffIconRow.Paint(dl, p.Icons, p.IconCount, p.Others, in p.Row, p.SmallFont, p.SmallSize, - ref p.OverflowKey, ref p.OverflowString, cx, iconTop, a, now); + ref p.OverflowKey, ref p.OverflowString, cx, iconTop, a, now, + p.Gone || p.Hidden ? DebuffRowTips.Off : DebuffRowTips.Monster, _paintUnderUi); // ── Name line: [level badge] Name ── if (p.NameW > 0 || p.BadgeW > 0) @@ -1757,6 +1793,7 @@ internal static class MonsterHud $"({HealthProbe.ProbeCount} quer{(HealthProbe.ProbeCount == 1 ? "y" : "ies")} sent).", PlateDebuffs.Describe(), PlayerPlate.Describe() + " " + CombatText.Describe(), + PlateSight.Describe(), AcMouseOver.Describe(), }; } diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudData.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudData.cs index eb8929b..793b288 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudData.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudData.cs @@ -14,6 +14,11 @@ // Both run on AC's main thread today; the lock keeps them safe if a caller // ever moves. Bounded: a full table is cleared wholesale (advisory data). // Engine-owned statics only (collectible with the engine generation). +// +// Plugin API v93 (2026-11-07) reads it from plugin threads too: +// TryGetServerHealth hands out the last SERVER reading (probe replies +// included, CleaveHealth estimates never) and its age, under the same lock. +// Compiled into tools/CleaveGhostTests (with a stand-in HudFeed). // ============================================================================ using System; @@ -24,9 +29,11 @@ namespace RynthCore.Engine.ImGuiBackend.Hud; /// <summary>Last health observation for one object. <paramref name="Prev"/>: the ratio before it /// (-1 = first). <paramref name="Estimated"/>: worked out from a hit (CleaveHealth), not sent by the server. -/// <paramref name="ServerTicks"/>: when the server last sent this object's health (0 = never; estimates keep it).</summary> +/// <paramref name="ServerTicks"/>: when the server last sent this object's health (0 = never; estimates keep it). +/// <paramref name="ServerRatio"/>: the ratio the server last sent (-1 = never; an estimate keeps it, so it stays +/// the server's number while <paramref name="Ratio"/> shows the estimate).</summary> internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks, float Prev = -1f, bool Estimated = false, - long ServerTicks = 0); + long ServerTicks = 0, float ServerRatio = -1f); internal static class MonsterHudData { @@ -61,7 +68,8 @@ internal static class MonsterHudData if (Health.Count >= MaxHealthEntries && !Health.ContainsKey(id)) Health.Clear(); long serverTicks = estimated ? (had ? prev.ServerTicks : 0) : now; - Health[id] = new HealthObservation(ratio, current, max, now, before, estimated, serverTicks); + float serverRatio = estimated ? (had ? prev.ServerRatio : -1f) : ratio; + Health[id] = new HealthObservation(ratio, current, max, now, before, estimated, serverTicks, serverRatio); } // An estimate never kills (CleaveHealth keeps it above 0) and the server correcting one // isn't a heal: the combat text sees an estimate's successor as a first observation. @@ -76,6 +84,33 @@ internal static class MonsterHudData return Health.TryGetValue(id, out h); } + /// <summary> + /// Plugin API v93 GetMonsterHealth: the last health ratio the SERVER sent for <paramref name="id"/> + /// (0x01C0 UpdateHealth, the HUD's own probe replies included; QueryHealthResponse; appraisal) and + /// how many ms ago (saturates at uint.MaxValue). Never an estimate (CleaveHealth): an id the server + /// never sent health for is false. Read-only, any thread (the table's lock), no game calls. + /// </summary> + public static bool TryGetServerHealth(uint id, out float ratio, out uint ageMs) + => TryGetServerHealth(id, Stopwatch.GetTimestamp(), out ratio, out ageMs); + + /// <summary><see cref="TryGetServerHealth(uint, out float, out uint)"/> at <paramref name="nowTicks"/> + /// (Stopwatch ticks; tests pass their own).</summary> + public static bool TryGetServerHealth(uint id, long nowTicks, out float ratio, out uint ageMs) + { + ratio = -1f; + ageMs = uint.MaxValue; + if (id == 0) return false; + HealthObservation h; + lock (Sync) + if (!Health.TryGetValue(id, out h)) return false; + if (h.ServerTicks == 0 || h.ServerRatio < 0f) return false; + long ticks = Math.Max(0, nowTicks - h.ServerTicks); + double ms = ticks * 1000.0 / Stopwatch.Frequency; + ratio = h.ServerRatio; + ageMs = ms >= uint.MaxValue ? uint.MaxValue : (uint)ms; + return true; + } + /// <summary>A monster named <paramref name="name"/> hit the player. Any thread.</summary> public static void RecordAttacker(string? name) { diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs index ddfde8c..a631191 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs @@ -50,6 +50,12 @@ internal static class MonsterHudSettings /// <summary>A left-click on a monster plate selects that monster in game.</summary> public static bool ClickToSelect = true; /// <summary> + /// "Hide behind walls" (2026-11-04, report R-20261105-020337-67aa): no plate or label (and no click) for + /// an object the player can't see because of building or dungeon walls (PlateSight). Off: every object + /// in range gets one, as before. + /// </summary> + public static bool HideBehindWalls = true; + /// <summary> /// "Refresh others' health" (2026-10-31): the server streams health only for the selected / queried /// monster, so the HUD asks for the other plates' health itself, one monster per HealthRefreshSec /// (HealthProbe). Off: only the selected / queried monster's plate is live. @@ -233,6 +239,7 @@ internal static class MonsterHudSettings case "scale": if (TryF(val, out float s)) Scale = Math.Clamp(s, MinScale, MaxScale); break; case "opacity": if (TryF(val, out float o)) Opacity = Math.Clamp(o, MinOpacity, MaxOpacity); break; case "clickSelect": ClickToSelect = val == "1"; break; + case "hideBehindWalls": HideBehindWalls = val == "1"; break; case "refreshOthersHealth": RefreshOthersHealth = val == "1"; break; case "healthRefreshSec": if (TryF(val, out float hr)) HealthRefreshSec = Math.Clamp(hr, HealthProbe.MinIntervalSec, HealthProbe.MaxIntervalSec); @@ -357,6 +364,7 @@ internal static class MonsterHudSettings sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}")); sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}")); sw.WriteLine($"clickSelect={B(ClickToSelect)}"); + sw.WriteLine($"hideBehindWalls={B(HideBehindWalls)}"); sw.WriteLine($"refreshOthersHealth={B(RefreshOthersHealth)}"); sw.WriteLine(FormattableString.Invariant($"healthRefreshSec={HealthRefreshSec:0.##}")); sw.WriteLine($"npcNames={B(NpcNames)}"); @@ -417,7 +425,7 @@ internal static class MonsterHudSettings { Enabled = true; MaxDistance = 35f; MaxPlates = 20; Filter = PlateFilter.All; ShowNames = true; ShowHpNumbers = true; ShowDistance = false; ShowLevel = true; ShowWeakness = true; - FadeWithDistance = true; Scale = 1.0f; Opacity = 0.9f; HeightLift = 0f; ClickToSelect = true; + FadeWithDistance = true; Scale = 1.0f; Opacity = 0.9f; HeightLift = 0f; ClickToSelect = true; HideBehindWalls = true; RefreshOthersHealth = true; HealthRefreshSec = HealthProbe.DefaultIntervalSec; ShowDebuffs = true; ShowOthersDebuff = true; NpcNames = true; NpcMaxDistance = 30f; MaxNpcLabels = 15; PlayerNames = false; PlayerBars = false; @@ -484,7 +492,7 @@ internal static class MonsterHudSettings $"RynthVision nameplates: monsters {(Enabled ? "ON" : "OFF")} ({(Filter == PlateFilter.Engaged ? "engaged only" : "all monsters")}, " + $"{MaxDistance:0}yd, max {MaxPlates}, scale {Scale:0.##}, opacity {Opacity:0.##}, lift {HeightLift:0.#}m; " + $"names {OnOff(ShowNames)}, hp {OnOff(ShowHpNumbers)}, level {OnOff(ShowLevel)}, weak {OnOff(ShowWeakness)}, " + - $"distance {OnOff(ShowDistance)}, fade {OnOff(FadeWithDistance)}, click to select {OnOff(ClickToSelect)}, " + + $"distance {OnOff(ShowDistance)}, fade {OnOff(FadeWithDistance)}, click to select {OnOff(ClickToSelect)}, hide behind walls {OnOff(HideBehindWalls)}, " + $"refresh others' health {(RefreshOthersHealth ? $"every {HealthRefreshSec:0.0#} s" : "off")}), debuffs {OnOff(ShowDebuffs)} (others {OnOff(ShowOthersDebuff)}); " + $"NPC names {OnOff(NpcNames)} ({NpcMaxDistance:0}yd, max {MaxNpcLabels}), player names {OnOff(PlayerNames)} (bars {OnOff(PlayerBars)}), " + $"portal names {OnOff(PortalNames)} ({PortalMaxDistance:0}yd); " + diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs index ec15356..27b2af2 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs @@ -212,6 +212,10 @@ internal static class MonsterHudSettingsUi changed |= SliderF("Scale", ref MonsterHudSettings.Scale, MonsterHudSettings.MinScale, MonsterHudSettings.MaxScale, "%.2f", w); changed |= Toggle("Keep on screen", ref MonsterHudSettings.KeepOnScreen, "When the camera closes in (walls), plates and numbers stay pinned to the screen edge instead of leaving it. Chat: /rv plates onscreen."); + changed |= Toggle("Hide behind walls", ref MonsterHudSettings.HideBehindWalls, + "No plate or name (and no click) for monsters, NPCs, players and portals you can't see because of building " + + "or dungeon walls: in another room, another building, or outdoors where no doorway shows them. " + + "Off: everything in range gets one. Chat: /rv plates walls."); changed |= SliderF("Opacity", ref MonsterHudSettings.Opacity, MonsterHudSettings.MinOpacity, MonsterHudSettings.MaxOpacity, "%.2f", w); changed |= SliderF("Height lift (m)", ref MonsterHudSettings.HeightLift, MonsterHudSettings.MinLift, MonsterHudSettings.MaxLift, "%.1f", w); changed |= Toggle("Fade and shrink with distance", ref MonsterHudSettings.FadeWithDistance, null); diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlateDebuffs.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlateDebuffs.cs index 16bbe0e..e5c14cb 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/PlateDebuffs.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlateDebuffs.cs @@ -406,6 +406,7 @@ internal static class PlateDebuffs { if (dst[i].Kind != e.Kind) continue; dst[i].Stack++; + dst[i].AddSpell(e.SpellId); if (e.Expiry < dst[i].Expiry) { dst[i].Expiry = e.Expiry; dst[i].Duration = e.Duration; } break; } @@ -413,7 +414,10 @@ internal static class PlateDebuffs } seen |= 1UL << k; if (n < dst.Length) + { dst[n] = new DebuffIcon { Kind = e.Kind, Expiry = e.Expiry, Duration = e.Duration, Stack = 1 }; + dst[n].AddSpell(e.SpellId); + } n++; } // Stable order on the plate: by kind. diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlateSight.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlateSight.cs new file mode 100644 index 0000000..8b8931d --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlateSight.cs @@ -0,0 +1,354 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/PlateSight.cs +// "Behind walls" for the nameplates (2026-11-04, problem report +// R-20261105-020337-67aa, Conquest, indoors in a town shop: "NPC and Mob +// labels show up through walls. When in a town I find it hard to even click +// on interface items and buying things because my mouse wants to click on the +// labels of the NPC's."). A plate or label for an object the player can't see +// because of building or dungeon walls no longer draws, and so never takes a +// click; MonsterHudSettings.HideBehindWalls (default on) turns it off. +// +// Where the answers come from (AC memory: Compatibility/AcCellSight.cs; the +// rules: PlateSightRules.cs): +// - The viewer: the cell AC renders from (the camera's), its seen_outside +// flag and its visible-cell list. Read when the scan or the frame asks; +// the list (and the doorways below) is cached until the viewer changes +// cell. +// - Per frame: the render device's draw stamp, sampled once a frame. An +// EnvCell whose stamp is newer than the sample taken two frames ago was +// drawn by AC in the last frame or two, through the portals from the viewer. +// - Per plate, per frame: the object's own cell (its CPhysicsObj's cell) and +// that cell's stamp and seen_outside. +// - The doorways: the portals to the outside of the cells the viewer can see, +// cached as landblock-local polygons; each frame those of cells AC drew are +// projected to screen rects (only while the viewer is indoors and an outdoor +// object asks). A doorway partly behind the camera counts as the whole screen. +// The 4 Hz scan (MonsterHud.Snapshot) skips objects the cell lists already rule +// out, so a town's hidden NPCs no longer use up the label cap; the frame check +// (MonsterHud.DrawPlates) does the rest. A plate that goes out of sight fades +// out as one leaving the screen does, and takes no click from the first frame. +// +// Cost: one viewer read per scan and per frame, one cell read per drawn plate, +// the cached doorways projected while they matter (a handful of points); the +// visible-cell list and the doorway polygons are read again only when the +// viewer changes cell (or, while some visible rooms weren't reachable yet, +// twice a second). Anything unreadable shows the plate (today's behaviour) and +// is logged once. +// +// AC's main thread only. Unload-safe: engine-owned statics, no hooks. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Numerics; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.D3D9; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +internal static class PlateSight +{ + private const int MaxVisible = 1024; // AcCellSight's cap on a visible-cell list + private const int MaxRooms = 96; // rooms walked for doorways + private const int MaxDoorwayRects = 24; + private static readonly long RebuildIncompleteTicks = Stopwatch.Frequency / 2; + private static readonly long RebuildAnywayTicks = Stopwatch.Frequency * 5; + private const float DoorwayMarginPx = 6f; + + // ── The viewer (refreshed by the scan and every frame) ─────────────── + private static uint _viewerCell, _playerCell; + private static IntPtr _viewerPtr; + private static SightFact _viewerSeesOutside; + + // ── Cached for one viewer cell ─────────────────────────────────────── + private static uint _cacheCell; + private static IntPtr _cachePtr; + private static long _cacheTicks; + private static bool _cacheIncomplete; + private static readonly uint[] Visible = new uint[MaxVisible]; + private static int _visibleCount = -1; // -1: the list couldn't be read + private struct Doorway { public IntPtr Cell; public uint CellId; public Vector3[] World; } + private static readonly List<Doorway> Doorways = new(16); + private static bool _doorwaysKnown; + private static readonly List<AcCellSight.PortalRead> PortalWork = new(16); + private static readonly Queue<(IntPtr Cell, uint Id)> RoomQueue = new(32); + private static readonly HashSet<uint> RoomSeen = new(); + + // ── Per frame ──────────────────────────────────────────────────────── + private static uint _stampPrev1, _stampPrev2; // the device stamp one and two frames ago + private static int _stampSamples; // consecutive good samples (2+: _since is usable) + private static uint _since; + private static bool _stampsOk; + private static int _frame; + private static int _rectsFrame = -1; + private static readonly List<Vector4> Rects = new(MaxDoorwayRects); + private static SightFact _rectsState; // Unknown: the doorways couldn't be worked out this frame + private static int _doorwaysDrawn; + private static int _hiddenThisFrame, _hiddenLastFrame; + + private static int _hideLogged, _viewerFailLogged; + + /// <summary>The plates in the last frame that were out of sight (diagnostics).</summary> + public static int HiddenCount => _hiddenLastFrame; + + /// <summary>Drops every cache (logout, character switch). The next read starts again.</summary> + public static void Reset() + { + _viewerCell = _playerCell = 0; + _viewerPtr = IntPtr.Zero; + _viewerSeesOutside = SightFact.Unknown; + _cacheCell = 0; + _cachePtr = IntPtr.Zero; + _visibleCount = -1; + Doorways.Clear(); + _doorwaysKnown = false; + _stampSamples = 0; + _stampsOk = false; + _rectsFrame = -1; + _hiddenThisFrame = _hiddenLastFrame = 0; + } + + /// <summary> + /// Reads the viewer (camera) cell and, when it changed, its visible-cell list and doorways. + /// <paramref name="playerCell"/>: the player's own cell. AC's main thread. + /// </summary> + public static void Refresh(uint playerCell) + { + _playerCell = playerCell; + if (!AcCellSight.TryGetViewer(out uint cell, out IntPtr ptr)) + { + // No SmartBox viewer: the player's own cell stands in (no lists, no doorways from it). + if (_viewerFailLogged == 0) + { + _viewerFailLogged = 1; + RynthLog.UI("MonsterHud: can't read AC's viewer cell - plates behind walls go by your own cell only."); + } + cell = playerCell; + ptr = IntPtr.Zero; + } + _viewerCell = cell; + _viewerPtr = ptr; + bool? outside = PlateSightRules.IsIndoor(cell) ? AcCellSight.SeesOutside(ptr, cell) : true; + _viewerSeesOutside = outside == null ? SightFact.Unknown : outside.Value ? SightFact.Yes : SightFact.No; + + long now = Stopwatch.GetTimestamp(); + bool rebuild = cell != _cacheCell || ptr != _cachePtr || + (_cacheIncomplete && now - _cacheTicks >= RebuildIncompleteTicks) || + (PlateSightRules.IsIndoor(cell) && now - _cacheTicks >= RebuildAnywayTicks); + if (rebuild) Rebuild(cell, ptr, now); + } + + private static void Rebuild(uint cell, IntPtr ptr, long now) + { + _cacheCell = cell; + _cachePtr = ptr; + _cacheTicks = now; + _cacheIncomplete = false; + Doorways.Clear(); + _rectsFrame = -1; + if (!PlateSightRules.IsIndoor(cell)) + { + // Outdoors: no list and no doorways are needed. + _visibleCount = 0; + _doorwaysKnown = true; + return; + } + _visibleCount = ptr == IntPtr.Zero ? -1 : AcCellSight.ReadVisibleCells(ptr, cell, Visible); + if (_viewerSeesOutside == SightFact.No) + { + // A dungeon: AC draws nothing outdoors from here, so there are no doorways to look through. + _doorwaysKnown = true; + return; + } + _doorwaysKnown = ptr != IntPtr.Zero && _visibleCount >= 0 && WalkRooms(cell, ptr); + } + + /// <summary> + /// The doorways to the outside of the viewer's room and of every room it can see that AC's + /// portal walk has reached (the portal's other-cell pointer is filled as AC walks into it). + /// </summary> + private static bool WalkRooms(uint cell, IntPtr ptr) + { + RoomQueue.Clear(); + RoomSeen.Clear(); + RoomQueue.Enqueue((ptr, cell)); + RoomSeen.Add(cell); + int rooms = 0; + while (RoomQueue.Count > 0 && rooms < MaxRooms) + { + (IntPtr c, uint id) = RoomQueue.Dequeue(); + rooms++; + PortalWork.Clear(); + if (!AcCellSight.ReadPortals(c, id, PortalWork)) + { + if (id == cell) return false; // the viewer's own room unreadable: no doorway answer + _cacheIncomplete = true; + continue; + } + foreach (AcCellSight.PortalRead pr in PortalWork) + { + if (pr.OtherId == AcCellSight.OutdoorsId) + { + if (pr.World != null) Doorways.Add(new Doorway { Cell = c, CellId = id, World = pr.World }); + else return false; // a doorway we can't place: no doorway answer (plates show) + continue; + } + if (!RoomSeen.Add(pr.OtherId) || !InVisible(pr.OtherId)) continue; + if (pr.OtherCell == IntPtr.Zero || !AcCellSight.IsCell(pr.OtherCell, pr.OtherId)) + { + _cacheIncomplete = true; // AC hasn't walked in yet: look again shortly + continue; + } + RoomQueue.Enqueue((pr.OtherCell, pr.OtherId)); + } + } + if (RoomQueue.Count > 0) _cacheIncomplete = true; + return true; + } + + private static bool InVisible(uint cell) + { + for (int i = 0; i < _visibleCount; i++) + if (Visible[i] == cell) return true; + return false; + } + + private static ReadOnlySpan<uint> VisibleSpan => _visibleCount > 0 ? Visible.AsSpan(0, _visibleCount) : ReadOnlySpan<uint>.Empty; + + /// <summary>The scan's question for an object in <paramref name="objectCell"/>: the cell lists only.</summary> + public static bool ShowCoarse(uint objectCell) => + PlateSightRules.ShowCoarse(_viewerCell, _playerCell, _viewerSeesOutside, VisibleSpan, _visibleCount >= 0, objectCell); + + /// <summary>Once a frame, before the plates ask: the viewer and the draw stamp.</summary> + public static void BeginFrame(uint playerCell) + { + _frame++; + _hiddenLastFrame = _hiddenThisFrame; + _hiddenThisFrame = 0; + Refresh(playerCell); + if (AcCellSight.TryReadFrameStamp(out uint stamp)) + { + _since = _stampPrev2; + _stampsOk = _stampSamples >= 2; + _stampPrev2 = _stampPrev1; + _stampPrev1 = stamp; + if (_stampSamples < 2) _stampSamples++; + } + else + { + _stampSamples = 0; + _stampsOk = false; + } + } + + /// <summary> + /// Does this object's plate or label show this frame? <paramref name="objectCell"/>: its live cell. + /// <paramref name="headFront"/>: the head point is in front of the camera, at <paramref name="head"/> + /// (ImGui pixels, not pinned); <paramref name="feetWx"/>.. the feet in the projection's frame + /// (D3D axes, as Plate.LastW*). + /// </summary> + public static bool Show(ref MonsterHud.Frame f, uint id, uint objectCell, bool headFront, Vector2 head, + float feetWx, float feetWy, float feetWz) + { + bool feetFront = GameMatrixCapture.WorldToScreen(feetWx, feetWy, feetWz, out float fsx, out float fsy); + var feet = new Vector2(fsx * f.MapX, fsy * f.MapY); + bool onScreen = (headFront && Inside(ref f, head)) || (feetFront && Inside(ref f, feet)); + + var q = new SightQuery + { + ViewerCell = _viewerCell, PlayerCell = _playerCell, ViewerSeesOutside = _viewerSeesOutside, + ViewerVisible = VisibleSpan, VisibleKnown = _visibleCount >= 0, + ObjectCell = objectCell, OnScreen = onScreen, + }; + bool viewerIndoor = PlateSightRules.IsIndoor(_viewerCell); + if (PlateSightRules.IsIndoor(objectCell) && objectCell != _viewerCell && objectCell != _playerCell) + { + // The object's room: AC's draw stamp on it, and whether it sees outside. + if (ClientObjectHooks.TryGetObjectCell(id, out IntPtr cell, out uint cellId) && cellId == objectCell && cell != IntPtr.Zero) + { + if (_stampsOk && AcCellSight.TryReadDrawStamp(cell, cellId, out uint st)) + q.ObjectCellDrawn = PlateSightRules.DrawnSince(st, _since) ? SightFact.Yes : SightFact.No; + bool? so = AcCellSight.SeesOutside(cell, cellId); + q.ObjectSeesOutside = so == null ? SightFact.Unknown : so.Value ? SightFact.Yes : SightFact.No; + } + } + else if (!PlateSightRules.IsIndoor(objectCell) && viewerIndoor && onScreen && _viewerSeesOutside != SightFact.No) + { + q.InDoorway = InDoorway(ref f, headFront ? head : feet, feetFront ? feet : head); + } + + bool show = PlateSightRules.Show(in q); + if (!show) + { + _hiddenThisFrame++; + if (_hideLogged < 3) + { + _hideLogged++; + RynthLog.UI($"MonsterHud: a plate is behind walls - hidden (viewer cell 0x{_viewerCell:X8}, sees outside {_viewerSeesOutside}, " + + $"object cell 0x{objectCell:X8}, on screen {onScreen}, drawn {q.ObjectCellDrawn}, doorway {q.InDoorway}, " + + $"{_visibleCount} visible cells, {Doorways.Count} doorways)."); + } + } + return show; + } + + private static bool Inside(ref MonsterHud.Frame f, Vector2 p) => + p.X >= 0f && p.Y >= 0f && p.X <= f.Display.X && p.Y <= f.Display.Y; + + /// <summary>An outdoor object seen from inside: does a doorway AC drew cover its head-to-feet line on screen?</summary> + private static SightFact InDoorway(ref MonsterHud.Frame f, Vector2 a, Vector2 b) + { + if (_rectsFrame != _frame) BuildRects(ref f); + if (_rectsState != SightFact.Yes) return SightFact.Unknown; + float x0 = MathF.Min(a.X, b.X), x1 = MathF.Max(a.X, b.X), y0 = MathF.Min(a.Y, b.Y), y1 = MathF.Max(a.Y, b.Y); + float margin = DoorwayMarginPx * f.UiScale; + foreach (Vector4 r in Rects) + if (PlateSightRules.Overlaps(x0, y0, x1, y1, r.X, r.Y, r.Z, r.W, margin)) return SightFact.Yes; + return SightFact.No; + } + + /// <summary>This frame's screen rects of the doorways to the outside in rooms AC drew.</summary> + private static void BuildRects(ref MonsterHud.Frame f) + { + _rectsFrame = _frame; + Rects.Clear(); + _doorwaysDrawn = 0; + if (!_stampsOk || !_doorwaysKnown) { _rectsState = SightFact.Unknown; return; } + var full = new Vector4(0f, 0f, f.Display.X, f.Display.Y); + foreach (Doorway d in Doorways) + { + if (!AcCellSight.TryReadDrawStamp(d.Cell, d.CellId, out uint st)) { _rectsState = SightFact.Unknown; return; } + if (!PlateSightRules.DrawnSince(st, _since)) continue; // AC didn't draw that room: its doorway isn't in view + _doorwaysDrawn++; + if (!MonsterHud.TryOffset(f.FrameCell, d.CellId, out float ox, out float oy)) continue; + int front = 0, behind = 0; + float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue; + foreach (Vector3 v in d.World) + { + if (!GameMatrixCapture.WorldToScreen(v.X + ox, v.Z, v.Y + oy, out float sx, out float sy)) { behind++; continue; } + front++; + sx *= f.MapX; sy *= f.MapY; + x0 = MathF.Min(x0, sx); x1 = MathF.Max(x1, sx); + y0 = MathF.Min(y0, sy); y1 = MathF.Max(y1, sy); + } + if (front == 0) continue; // wholly behind the camera + Vector4 r = behind > 0 ? full : new Vector4(x0, y0, x1, y1); // straddling the camera: anywhere + if (Rects.Count < MaxDoorwayRects) Rects.Add(r); + else { Rects[0] = full; break; } // too many to keep apart: the whole screen + } + _rectsState = SightFact.Yes; + } + + /// <summary>One line for "/rv plates status".</summary> + public static string Describe() + { + bool indoor = PlateSightRules.IsIndoor(_viewerCell); + return $"Behind walls: {(MonsterHudSettings.HideBehindWalls ? "hidden" : "shown (setting off)")}; " + + $"viewer cell 0x{_viewerCell:X8} ({(_viewerCell == 0 ? "unknown" : indoor ? "indoors" : "outdoors")}, sees outside {_viewerSeesOutside}), " + + $"{(_visibleCount < 0 ? "visible cells unreadable" : $"{_visibleCount} visible cells")}, " + + $"{(_doorwaysKnown ? $"{Doorways.Count} doorways ({_doorwaysDrawn} drawn)" : "doorways unknown")}" + + $"{(_cacheIncomplete ? ", some rooms not reached yet" : "")}; " + + $"{AcCellSight.Status}{(_stampsOk ? "" : " (no stamp window yet)")}; {_hiddenLastFrame} out of sight last frame."; + } +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlateSightRules.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlateSightRules.cs new file mode 100644 index 0000000..4d38c09 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlateSightRules.cs @@ -0,0 +1,116 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/PlateSightRules.cs +// The pure half of PlateSight (2026-11-04, problem report +// R-20261105-020337-67aa: "NPC and Mob labels show up through walls", and in a +// town the labels caught the clicks meant for the shop): given what was read +// out of AC's cells, can the player see this object, or is it behind building +// or dungeon walls? No AC memory, no engine state: tools/PlateSightTests +// compiles this file in and checks every case offline. +// +// Cells: an id's low word is the cell in its landblock; 0x0001-0x0040 are the +// outdoor land cells, 0x0100 and up the EnvCells (dungeon and building rooms). +// "The viewer" is the cell AC renders from (the camera's; SmartBox's viewer +// cell), which is what decides what is on screen. +// +// Order of the answers, best first (AcCellSight.cs has the evidence): +// 1. AC's own draw stamps: an EnvCell AC drew this frame is on screen through +// the portals from the viewer; one it didn't draw is behind walls. Used only +// for objects that project onto the screen: AC also skips cells outside the +// view, and a plate pinned to the screen edge ("Keep on screen") must not +// vanish just because its room is off to the side. +// 2. AC's doorways: from inside, an outdoor object counts only where a doorway +// to the outside that AC drew covers it on screen. +// 3. The cell lists: from an EnvCell, only its visible-cell list (and itself) +// can ever be drawn, and the outdoors only when it sees outside; from +// outdoors, an EnvCell that doesn't see outside (a dungeon, a sealed room) +// can't be seen. +// Anything unknown keeps today's behaviour: the plate shows. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +/// <summary>A yes / no that may not be known.</summary> +internal enum SightFact : byte { Unknown, No, Yes } + +/// <summary>What is known about one object this frame (or this scan, with less filled in).</summary> +internal ref struct SightQuery +{ + /// <summary>The cell AC renders from (0: unknown).</summary> + public uint ViewerCell; + /// <summary>The player's own cell (0: unknown); objects in it always count.</summary> + public uint PlayerCell; + /// <summary>The viewer cell's seen_outside (outdoors: Yes).</summary> + public SightFact ViewerSeesOutside; + /// <summary>The viewer cell's visible-cell list; only read when <see cref="VisibleKnown"/>.</summary> + public ReadOnlySpan<uint> ViewerVisible; + public bool VisibleKnown; + + /// <summary>The object's cell (0: unknown).</summary> + public uint ObjectCell; + /// <summary>The object's head or feet projects inside the screen (not only pinned to its edge).</summary> + public bool OnScreen; + /// <summary>AC drew the object's EnvCell in the last frames (Unknown: no stamps, no cell pointer).</summary> + public SightFact ObjectCellDrawn; + /// <summary>The object's EnvCell sees outside (Unknown: not read).</summary> + public SightFact ObjectSeesOutside; + /// <summary>An outdoor object seen from inside: a doorway AC drew covers it on screen (Unknown: not worked out).</summary> + public SightFact InDoorway; +} + +internal static class PlateSightRules +{ + /// <summary>A cell id is an EnvCell (dungeon / building room): low word 0x0100 and up.</summary> + public static bool IsIndoor(uint cellId) => (cellId & 0xFFFF) >= 0x0100; + + /// <summary>Does the plate or label for this object show?</summary> + public static bool Show(in SightQuery q) + { + // Nothing to go on: today's behaviour. + if ((q.ViewerCell >> 16) == 0 || (q.ObjectCell >> 16) == 0) return true; + if (q.ObjectCell == q.ViewerCell || q.ObjectCell == q.PlayerCell) return true; + + bool viewerIndoor = IsIndoor(q.ViewerCell); + if (IsIndoor(q.ObjectCell)) + { + // 1. AC drew the object's room this frame, or it didn't. + if (q.OnScreen && q.ObjectCellDrawn != SightFact.Unknown) return q.ObjectCellDrawn == SightFact.Yes; + // 3. The cell lists. + if (viewerIndoor) return !q.VisibleKnown || Contains(q.ViewerVisible, q.ObjectCell); + return q.ObjectSeesOutside != SightFact.No; + } + + // An outdoor object. + if (!viewerIndoor) return true; // both outdoors: no change (no terrain or building occlusion) + if (q.ViewerSeesOutside == SightFact.No) return false; // a dungeon: AC draws nothing outdoors from here + if (q.OnScreen && q.InDoorway != SightFact.Unknown) return q.InDoorway == SightFact.Yes; + return true; + } + + /// <summary>The 4 Hz scan's question: the cell lists only (no frame, no screen).</summary> + public static bool ShowCoarse(uint viewerCell, uint playerCell, SightFact viewerSeesOutside, ReadOnlySpan<uint> viewerVisible, + bool visibleKnown, uint objectCell) + { + var q = new SightQuery + { + ViewerCell = viewerCell, PlayerCell = playerCell, ViewerSeesOutside = viewerSeesOutside, + ViewerVisible = viewerVisible, VisibleKnown = visibleKnown, ObjectCell = objectCell, + }; + return Show(in q); + } + + /// <summary>A stamp written at or after the sample <paramref name="since"/> was taken (wraps).</summary> + public static bool DrawnSince(uint cellStamp, uint since) => unchecked((int)(cellStamp - since)) > 0; + + /// <summary>Two screen rects (x0, y0, x1, y1) overlap, the second grown by <paramref name="margin"/>.</summary> + public static bool Overlaps(float ax0, float ay0, float ax1, float ay1, float bx0, float by0, float bx1, float by1, float margin) => + ax0 <= bx1 + margin && ax1 >= bx0 - margin && ay0 <= by1 + margin && ay1 >= by0 - margin; + + private static bool Contains(ReadOnlySpan<uint> cells, uint cell) + { + foreach (uint c in cells) + if (c == cell) return true; + return false; + } +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs index e12620f..31527fa 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs @@ -200,7 +200,7 @@ internal static class PlayerPlate left = l.M.ClampLeft(left, f.Display.X); y = l.M.ClampTop(y, f.Display.Y); } - float top = Paint(f.Dl, ref l, MathF.Round(left), MathF.Round(y), f.Now); + float top = Paint(f.Dl, ref l, MathF.Round(left), MathF.Round(y), f.Now, f.UnderUi); // Gain text floats above the plate when it's over the head, else above the head itself. PlateTop = where == SelfPlatePosition.Above ? top : head.Y; } @@ -265,7 +265,7 @@ internal static class PlayerPlate dl.AddRectFilled(r0, r1, MonsterHud.Mul(hot ? 0x40000000u : 0x28000000u, a), 3f); dl.AddRect(r0, r1, MonsterHud.Mul(hot ? FrameHot : FrameCol, a), 3f, ImDrawFlags.None, hot ? 1.5f : 1f); } - Paint(dl, ref l, left, y, f.Now); + Paint(dl, ref l, left, y, f.Now, underUi: false); } private static uint FrameCol => RynthTheme.WithAlpha(RynthTheme.Accent, 0xB0); @@ -406,18 +406,21 @@ internal static class PlayerPlate /// <summary> /// Paints the three bars (and the name over them, the debuff row under them) with the bars' top-left - /// at (left, y); returns the plate's top. <paramref name="now"/> is Stopwatch ticks. + /// at (left, y); returns the plate's top. <paramref name="now"/> is Stopwatch ticks; <paramref name="underUi"/>: + /// <paramref name="dl"/> is the layer under AC's windows (the debuff tooltips then give way to them). /// </summary> - private static float Paint(ImDrawListPtr dl, ref Layout l, float left, float y, long now) + private static float Paint(ImDrawListPtr dl, ref Layout l, float left, float y, long now, bool underUi) { float a = Math.Clamp(_alpha, 0f, 1f); ref SelfPlateMetrics m = ref l.M; PaintOne(dl, ref _hp, ref l, left, y, a, HealthCol); PaintOne(dl, ref _st, ref l, left, y + m.BarH + m.Gap, a, StaminaCol); PaintOne(dl, ref _mn, ref l, left, y + 2 * (m.BarH + m.Gap), a, ManaCol); + // No tooltip mid-drag: the drag owns the cursor. if (_iconCount > 0) DebuffIconRow.Paint(dl, _icons, _iconCount, others: false, in m.Row, l.IconText, l.IconTextSize, - ref _overflowKey, ref _overflowText, left + m.BarW * 0.5f, y + m.RowTop, a, now); + ref _overflowKey, ref _overflowText, left + m.BarW * 0.5f, y + m.RowTop, a, now, + _dragging ? DebuffRowTips.Off : DebuffRowTips.Self, underUi); float top = y - 1f; if (MonsterHudSettings.SelfName) { diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/SelfDebuffs.cs b/src/RynthCore.Engine/ImGui/MonsterHud/SelfDebuffs.cs index 88dddb8..65581e9 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/SelfDebuffs.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/SelfDebuffs.cs @@ -18,7 +18,8 @@ // - one icon per kind (DebuffKind); a kind merging several categories shows // their count and the soonest end, like the monster row; // - icons in kind order (the monster row's), as many as fit in dst; the -// count returned includes the rest (the "+N"). +// count returned includes the rest (the "+N"); +// - each icon carries its categories' spell ids (the hover tooltip names them). // No engine dependencies beyond DebuffIcon.cs (the offline tests compile it). // ============================================================================ @@ -58,6 +59,7 @@ internal static class SelfDebuffs Span<double> catEnd = stackalloc double[MaxEntries]; Span<float> catDur = stackalloc float[MaxEntries]; Span<byte> catKind = stackalloc byte[MaxEntries]; + Span<uint> catSpell = stackalloc uint[MaxEntries]; int cats = 0; for (int i = 0; i < n; i++) { @@ -82,6 +84,7 @@ internal static class SelfDebuffs catEnd[c] = end; catDur[c] = dur; catKind[c] = (byte)Math.Min((int)kind, KindCount - 1); + catSpell[c] = id; } if (cats == 0) return 0; @@ -114,6 +117,12 @@ internal static class SelfDebuffs dst[count] = new DebuffIcon { Kind = (DebuffKind)k, Expiry = kindEnd[k], Duration = kindDur[k], Stack = kindStack[k] }; count++; } + + // 4. The hover tooltip's spell names: each category's spell on its kind's icon. + int shown = Math.Min(count, dst.Length); + for (int c = 0; c < cats; c++) + for (int i = 0; i < shown; i++) + if ((int)dst[i].Kind == catKind[c]) { dst[i].AddSpell(catSpell[c]); break; } return count; } } diff --git a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicGearTab.cs b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicGearTab.cs index f91ac9d..93ff930 100644 --- a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicGearTab.cs +++ b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicGearTab.cs @@ -3,7 +3,8 @@ // The Classic look's Gear tab: RynthAi's Items lists (UiSources.Items, the // Items panel's source) in the retail style. Weapons with their element (a // drop-down; a weapon no longer carried shows "missing"), consumables with -// their kind, a remove mark on each row; add the item selected in game as a +// their kind, a remove mark on each row, a "No buff" gem on a shield row +// (when RynthAi sends noBuff); add the item selected in game as a // weapon, a shield or a consumable; drop the missing ones; the shield and // mana-tap settings that ride the same list. Saved like the Items panel: the // whole payload (ItemsCommands.SetJson), older snapshots ignored after a save @@ -176,6 +177,18 @@ internal sealed class ClassicGearTab : IClassicTab } SafeImGui.SetItemTooltip("The damage this weapon deals (picks it for monsters weak to it)"); } + else if (e.ShowsNoBuff) + { + // A shield has no element: its column is the "No buff" toggle (a RynthAi that sends noBuff). + bool nb = e.NoBuff == true; + if (Gem("##nobuff", "No buff", new Vector2(p.X + listW - xW - ddW - Px(2), p.Y), ddW, nb, 19)) + { + e.NoBuff = !nb; + Save(); + } + SafeImGui.SetItemTooltip("Never buff this shield - for a shield that already carries its buffs.\n" + + "RynthAi then aims no armor spells at it, and its spells running low never start a rebuff."); + } if (RemoveMark("##x", new Vector2(p.X + listW - xW, p.Y), rowH)) remove = i; SafeImGui.SetItemTooltip("Remove " + e.Name + " from the list"); ImGuiNET.ImGui.PopID(); diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs index 6a458a2..148ce8d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs @@ -18,7 +18,11 @@ // automatic. // Under a monster's row, when the plugin sends them (the row's "mstats", // UI/Data/DamageRowStats.cs, 2026-10-30): how often it evades and resists you -// and you it since login, the full numbers on hover. +// and you it since login, the full numbers on hover; "XP/kill" first when the +// plugin counts XP ("xp"/"xk", 2026-11-08), then "corpse 2.1 s" when it times +// the death animation ("cd"/"cn"), then "Hits taken: shield 11 avg (front 95%), +// no shield 54 avg" when the plugin has learned its hits by shield and facing +// ("h/d/m" + sf..nu, 2026-11-08; kept across logins, not since login). // Where the server plugin reports difficulty tiers: a tier chip after Reset stats // (DamageView.Tier) - which tier the numbers are for, and a picker; "~" marks an // HP estimated from tier 0's. Hidden elsewhere. diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemToolFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemToolFace.cs index 7a61065..53f27a5 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ItemToolFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ItemToolFace.cs @@ -8,6 +8,8 @@ // current loot profile until it's out of keys." // Select the chest in the world, press Use selected as chest; // select the key in your pack, press Use selected as key; Start. +// Chest re-lock wait (s): how long after the open the next key +// goes on (RynthAi's setting, "/ra itemtool relock N"). // Quick give Select an item in your pack (Use selected as item) and a player // or NPC in the world (Use selected as target), press Give: every // such item in your packs is handed over, one give at a time. @@ -76,6 +78,8 @@ internal sealed class ItemToolFace : IImGuiPanel if (hit == 0) ItemToolCommands.Send("chest set"); else if (hit == 1) ItemToolCommands.Send("chest key"); + DrawRelockWait(c, w); + hit = StartStop("##chest_run", "Start", "Stop", ready && !c.Running, c.Running, w); if (hit == 0) ItemToolCommands.Send("chest start"); else if (hit == 1) ItemToolCommands.Send("chest stop"); @@ -83,6 +87,44 @@ internal sealed class ItemToolFace : IImGuiPanel Wrapped(c.Status, c.Running ? Amber : Text, w); } + // The slider's value while it is dragged, and after the release until RynthAi reports it back + // (the snapshot is 250 ms behind; without this the slider jumps back for a moment). + private static int _relockEdit; + private static bool _relockPending; + private static long _relockSentAt; + private const long RelockPendingMs = 2000; + + /// <summary> + /// "Chest re-lock wait (s)" (2026-11-05): how long after the chest was opened the next key goes on + /// it. Sent on release as "relock N" (RynthAi clamps, saves it in the profile and answers in chat). + /// Hidden for a RynthAi that predates it (no relockSec); greyed until the profile has loaded. + /// </summary> + private static void DrawRelockWait(ChestToolState c, float w) + { + if (c.RelockSec <= 0) return; + int min = Math.Max(1, c.RelockMin), max = Math.Max(min, c.RelockMax); + long now = Environment.TickCount64; + if (_relockPending && (c.RelockSec == _relockEdit || now - _relockSentAt >= RelockPendingMs)) _relockPending = false; + + Label("Chest re-lock wait (s)", Mute); + int v = _relockPending ? _relockEdit : c.RelockSec; + ImGuiNET.ImGui.BeginDisabled(!c.RelockReady); + ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 4)); + ImGuiNET.ImGui.SliderInt("##chest_relock", ref v, min, max, "%d s", ImGuiSliderFlags.AlwaysClamp); + if (ImGuiNET.ImGui.IsItemActive()) { _relockEdit = v; _relockPending = true; _relockSentAt = now; } + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _relockEdit = v; + _relockPending = true; + _relockSentAt = now; + ItemToolCommands.Send("relock " + v.ToString(System.Globalization.CultureInfo.InvariantCulture)); + } + SafeImGui.SetItemTooltip(c.RelockReady + ? "How long after the chest was opened the next key goes on it (sooner when it reads locked again).\n125 s fits the usual 2-minute chest reset; a chest that resets sooner can use less.\nToo short costs nothing: the key is only tried again, never spent. Ctrl+click to type a value." + : "Waiting for this character's settings profile to load."); + ImGuiNET.ImGui.EndDisabled(); + } + // ── Quick give ────────────────────────────────────────────────────── private static void DrawGive(GiveToolState g, float w) diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs index 18af241..ce43405 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs @@ -5,6 +5,9 @@ // and mana stone tapping (on/off, keep count, min max-mana to tap). A listed // weapon the character no longer carries (RynthAi's missingIds) shows in amber // with a warning icon and "(missing)", and says what to do in its tooltip. +// A shield row (Action "Shield") from a RynthAi that sends noBuff shows a +// "No buff" toggle in place of its element column: on = RynthAi never buffs +// that shield. Weapon rows are unchanged. // // Edits change a private copy and save the whole payload (ItemsCommands, // pump thread). A newer snapshot replaces the copy; snapshots from before @@ -91,8 +94,15 @@ internal sealed class ItemsFace : IImGuiPanel int i = idx[k]; ItemsPanel.WeaponEntry wpn = _data.Weapons[i]; ImGuiNET.ImGui.PushID("w" + i); - int r = Row(wpn.Name, wpn.Element, shown++, bw, _data.MissingIds.Contains(wpn.Id), k > 0, k < idx.Count - 1); + int r = Row(wpn.Name, wpn.Element, shown++, bw, _data.MissingIds.Contains(wpn.Id), k > 0, k < idx.Count - 1, + wpn.ShowsNoBuff ? wpn.NoBuff : null); ImGuiNET.ImGui.PopID(); + if (r == 5) + { + wpn.NoBuff = !(wpn.NoBuff ?? false); + Save(); + continue; + } // Up / down inside its group: the order is RynthAi's preference (the buff wand, the // first weapon of a kind), and it couldn't be changed but by removing and re-adding. if (r == 3 || r == 4) @@ -273,13 +283,19 @@ internal sealed class ItemsFace : IImGuiPanel // The up / down buttons' width in a row (two 20 px buttons and their gaps). private const float MoveW = 46; + private const string NoBuffTip = "Never buff this shield - for a shield that already carries its buffs.\n" + + "RynthAi then aims no armor spells at it, and its spells running low never start a rebuff."; + /// <summary> /// Name | up | down | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, - /// 3 for up, 4 for down, else 0. Up / down are drawn dim and do nothing at the ends. - /// <paramref name="missing"/>: the item isn't carried any more (amber, a warning icon, - /// "(missing)" and a tooltip saying what to do). + /// 3 for up, 4 for down, 5 for the "No buff" toggle, else 0. Up / down are drawn dim and do + /// nothing at the ends. <paramref name="missing"/>: the item isn't carried any more (amber, a + /// warning icon, "(missing)" and a tooltip saying what to do). <paramref name="noBuff"/> + /// non-null (a shield row, RynthAi sending noBuff): the value column is the "No buff" toggle + /// instead of the picker (a shield has no element; its column only said "Shield"). /// </summary> - private static int Row(string name, string value, int index, float w, bool missing, bool canUp = false, bool canDown = false) + private static int Row(string name, string value, int index, float w, bool missing, bool canUp = false, bool canDown = false, + bool? noBuff = null) { Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); var dl = ImGuiNET.ImGui.GetWindowDrawList(); @@ -311,7 +327,14 @@ internal sealed class ItemsFace : IImGuiPanel if (IconButton("##down", PhosphorIcons.CaretDown, new Vector2(bx + 22, p.Y + 2), new Vector2(20, 20), canDown ? Teal : Mute, BtnFill) && canDown) result = 4; ImGuiNET.ImGui.SetItemTooltip("Move down"); bx += MoveW; - if (Button("##pick", value, new Vector2(bx, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1; + if (noBuff is bool nb) + { + // The tapping toggle's look: lit while the shield is left out of buffing. + if (Button("##nobuff", (nb ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " No buff", new Vector2(bx, p.Y + 2), new Vector2(96, 20), + nb ? OnText : Mute, nb ? OnBg : BtnFill)) result = 5; + ImGuiNET.ImGui.SetItemTooltip(NoBuffTip); + } + else if (Button("##pick", value, new Vector2(bx, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1; if (IconButton("##del", PhosphorIcons.Trash, new Vector2(bx + 100, p.Y + 2), new Vector2(42, 20), Red, BtnFill)) result = 2; ImGuiNET.ImGui.SetItemTooltip("Remove"); NextLine(p, 24); diff --git a/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs b/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs index 5862201..9a17ca1 100644 --- a/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs @@ -119,7 +119,7 @@ internal sealed class PluginWindowFace : IImGuiPanel } if (result == PluginManager.EmbedDrawn) { - if (_fitHeight) Fit(want.Y, avail.X); + if (_fitHeight) Fit(want.Y, avail.X, want.X); return; } @@ -137,12 +137,23 @@ internal sealed class PluginWindowFace : IImGuiPanel /// 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. /// </summary> - private void Fit(float wantPx, float widthPx) + private void Fit(float wantPx, float widthPx, float wantWidthPx = 0f) { if (wantPx <= 0f || ImGuiPopOuts.InPopOutFrame) return; float place = Math.Max(0.01f, ImGuiPanelHost.PlacementScale()); float height = MathF.Ceiling(wantPx / place); float width = widthPx / place; + // A plugin that sizes its own width too (2026-11-07: RynthDreamWeave's retail Character panel, a + // fixed design width at its text size) reports a width other than the one it was given: the window + // takes it, as it takes the height. Every other plugin hands back the width it got: no change. + if (wantWidthPx > 0f && MathF.Abs(wantWidthPx - widthPx) > 1f && ImGuiNET.ImGui.IsMouseDown(ImGuiNET.ImGuiMouseButton.Left) == false) + { + _contentHeight = height; + _fitWidth = MathF.Ceiling(wantWidthPx / place); + _fitK = PanelTextScale.Factor(ImGuiFonts.CurrentStep); + ImGuiPanelHost.RequestSize(_title, new Vector2(_fitWidth, height)); + return; + } float k = PanelTextScale.Factor(ImGuiFonts.CurrentStep); float shownHeight = ImGuiNET.ImGui.GetWindowHeight() / place; bool mouseUp = !ImGuiNET.ImGui.IsMouseDown(ImGuiNET.ImGuiMouseButton.Left); diff --git a/src/RynthCore.Engine/ImGui/Panels/RadarDrag.cs b/src/RynthCore.Engine/ImGui/Panels/RadarDrag.cs new file mode 100644 index 0000000..77c8c79 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RadarDrag.cs @@ -0,0 +1,37 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RadarDrag.cs +// Whether a press on the radar may move it (2026-11-04). Docked click-through +// ("Docked click-through (dots still work; Ctrl for the rest)") gives the game +// every click, except on a dot or the buttons: there the radar's window takes +// input for that press (RadarFace._hot / _pressHot) so the dot can be hovered and +// clicked to select. The surface under the dot is the same InvisibleButton that +// drags the panel (ImGuiPanelHost.DragWindowWithLastItem), so holding on a dot +// and moving the mouse moved the radar, Ctrl or not (Discord, 2026-11-02). Now a +// press moves the radar only when click-through is off, Ctrl was held when the +// press began, or the radar is popped out (always interactive there). It is +// decided when the press begins and holds until the button is up, so Ctrl let go +// or pressed mid-drag neither stops a move nor starts one. +// +// Pure (no ImGui), so tools\RadarSettingsTests links it. +// ============================================================================ + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class RadarDrag +{ + private bool _moves = true; + + /// <summary>A press with these settings may move the radar.</summary> + public static bool PressMoves(bool clickThroughOn, bool ctrlHeld, bool poppedOut) => + !clickThroughOn || ctrlHeld || poppedOut; + + /// <summary> + /// Call once a frame right after the surface item: <paramref name="pressBegan"/> is the surface's + /// IsItemActivated. Answers whether this press may move the radar (as decided when it began). + /// </summary> + public bool Update(bool pressBegan, bool clickThroughOn, bool ctrlHeld, bool poppedOut) + { + if (pressBegan) _moves = PressMoves(clickThroughOn, ctrlHeld, poppedOut); + return _moves; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs index e71e44d..45ad766 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs @@ -17,6 +17,8 @@ // The object selected in game is highlighted (RadarSettingsStore.HighlightSelected, RadarSelection): // a ring in its own colour round its marker and the hover label beside it, or an arrow on the // edge when it is off the picture. +// Range rings round you at RynthAi's Monster Range and Ring Range (RadarRangeRing; each has a box in +// the settings), read from RynthAi's settings while one is on. // // Data: UiSources.Radar (RadarView, lookups precomputed). World geometry is // drawn without anti-aliasing (crisp tiling like the Avalonia face's aliased @@ -71,6 +73,7 @@ internal sealed class RadarFace : IImGuiPanel private bool _settingsSub; // subscribed to RynthAi's settings (the retail radar switch) while the window is open private bool? _hidePending; // the retail-radar switch as just set, until RynthAi's answer shows it private long _hidePendingAt; + private bool _rangeSub; // subscribed to RynthAi's settings while a range ring is on // The round radar (RadarSettingsStore.RoundRadar): this frame's circle, read by the drawing helpers. private static bool _round; @@ -86,6 +89,8 @@ internal sealed class RadarFace : IImGuiPanel // dot can always be hovered and clicked. A press that began on a dot keeps the panel interactive // until the button is released. private bool _hot, _pressHot, _downPrev; + // Whether the current press on the surface may move the panel (off for a dot press under click-through). + private readonly RadarDrag _drag = new(); public bool ClickThrough => RadarSettingsStore.CtrlGatedClickThrough && !ImGuiNET.ImGui.GetIO().KeyCtrl && !_hot; @@ -106,10 +111,19 @@ internal sealed class RadarFace : IImGuiPanel { UiSources.Radar.Unsubscribe(); if (_settingsSub) { UiSources.Settings.Unsubscribe(); _settingsSub = false; } + if (_rangeSub) { UiSources.Settings.Unsubscribe(); _rangeSub = false; } } public void Draw() { + // The range rings need RynthAi's settings (Monster Range, Ring Range): polled only while one is on. + bool wantRange = RadarSettingsStore.ShowMonsterRangeRing || RadarSettingsStore.ShowRingRangeRing; + if (wantRange != _rangeSub) + { + if (wantRange) { UiSources.Settings.Subscribe(); UiSources.Settings.RequestRefresh(); } + else UiSources.Settings.Unsubscribe(); + _rangeSub = wantRange; + } bool clickThroughNow = ClickThrough; // what the host gave this frame's window (before UpdateHot moves _hot) _wheelHere = false; var dl = ImGuiNET.ImGui.GetWindowDrawList(); @@ -216,7 +230,11 @@ internal sealed class RadarFace : IImGuiPanel // ── Surface: drag moves the panel, a click on a dot selects, wheel zooms, right-click menu ── ImGuiNET.ImGui.SetCursorScreenPos(origin); bool surfaceClicked = ImGuiNET.ImGui.InvisibleButton("##radar_surface", size); - ImGuiPanelHost.DragWindowWithLastItem(); + // 2026-11-04: with docked click-through, a press on a dot only selects it; it never moves the + // radar unless Ctrl was held when it began (RadarDrag; holding on a dot used to drag the panel). + if (_drag.Update(ImGuiNET.ImGui.IsItemActivated(), RadarSettingsStore.CtrlGatedClickThrough, + ImGuiNET.ImGui.GetIO().KeyCtrl, ImGuiPopOuts.InPopOutFrame)) + ImGuiPanelHost.DragWindowWithLastItem(); UpdateHot(view, centre, worldMin, worldMax, gearPos, new Vector2(closePos.X + btn, closePos.Y + btn)); if (view != null && RadarSettingsStore.ClickToSelect) MarkerInput(dl, view, centre, worldMin, worldMax, surfaceClicked); @@ -310,6 +328,8 @@ internal sealed class RadarFace : IImGuiPanel if (cur + 1 < count && cur >= 0) DrawLayer(dl, view, cur + 1, 0.30f, false, proj, rotate, clipMin, clipMax); if (cur >= 0) DrawLayer(dl, view, cur, 1.00f, true, proj, rotate, clipMin, clipMax); + DrawRangeRings(dl, centre, clipMin, clipMax, MathF.Max(0.5f, RadarSettingsStore.Zoom)); + // Markers (shapes: RadarMarkerStyle). Corpses and items first, creatures on top. RadarMarkerStyle.FillColors(KindCols); MarkerStyleSettings markers = RadarSettingsStore.Markers; @@ -350,6 +370,33 @@ internal sealed class RadarFace : IImGuiPanel dl.AddLine(centre, tip, PlayerCol, 2); } + // ── Range rings ──────────────────────────────────────────────────────── + // Thin circles round you at RynthAi's Monster Range (warm white) and Ring Range (pale blue), over + // the floors and under the markers, each on a faint dark line so it reads on the dark canvas and + // on the world map alike. Nothing until RynthAi has sent its settings (UiSources.Settings). + private static readonly uint MonsterRangeCol = C(0xB3FFE6B3), RingRangeCol = C(0xA680CCFF), RangeUnder = C(0x59000000); + + private static void DrawRangeRings(ImDrawListPtr dl, Vector2 centre, Vector2 clipMin, Vector2 clipMax, float zoom) + { + bool monster = RadarSettingsStore.ShowMonsterRangeRing, ring = RadarSettingsStore.ShowRingRangeRing; + if (!monster && !ring) return; + RynthAiSettings? ra = UiSources.Settings.Current?.Value; + if (ra == null) return; + ImDrawListFlags saved = dl.Flags; + dl.Flags = saved | ImDrawListFlags.AntiAliasedLines; // the world is drawn aliased; a circle looks ragged that way + RoundMask? round = _round ? _mask : null; + if (monster) RangeRing(dl, centre, clipMin, clipMax, round, RadarRangeRing.RadiusPx(ra.MonsterRange, zoom), MonsterRangeCol); + if (ring) RangeRing(dl, centre, clipMin, clipMax, round, RadarRangeRing.RadiusPx(ra.RingRange, zoom), RingRangeCol); + dl.Flags = saved; + } + + private static void RangeRing(ImDrawListPtr dl, Vector2 centre, Vector2 clipMin, Vector2 clipMax, RoundMask? round, float r, uint col) + { + if (!RadarRangeRing.Shows(r, centre, clipMin, clipMax, round)) return; + dl.AddCircle(centre, r, RangeUnder, 0, 3f); // 0 segments: ImGui picks enough for the radius + dl.AddCircle(centre, r, col, 0, 1.25f); + } + // ── The selected object ──────────────────────────────────────────────── // A ring in the selection colour round its marker (the marker drawn over everything, even when its // kind's box is off), and the hover label beside it; off the picture, an arrow on the edge pointing @@ -521,7 +568,8 @@ internal sealed class RadarFace : IImGuiPanel // ── Click-to-select ───────────────────────────────────────────────────── // Left-click a dot: that object is selected in game, as a click on it in the // 3D world would. A press that moves more than a few pixels is a drag (the - // panel moves) and selects nothing. Hover shows the object's name and + // panel moves; with docked click-through and no Ctrl it stays put, RadarDrag) + // and selects nothing. Hover shows the object's name and // distance (and its last known health, when the engine has seen one). // RynthAi 2026-10-01 and later send each marker's object id, and the click // selects exactly that id. Older RynthAi builds send no id (Id = 0): then @@ -864,6 +912,7 @@ internal sealed class RadarFace : IImGuiPanel if (!WorldMapTiles.IsOpen && WorldMapTiles.Status.Length > 0) SafeImGui.TextDisabled(WorldMapTiles.Status); } + changed |= RangeRingRows(); RetailRadarRow(); ImGuiNET.ImGui.Separator(); changed |= KindRows(); @@ -879,6 +928,29 @@ internal sealed class RadarFace : IImGuiPanel private static bool Check(string label, ref bool value) => ImGuiNET.ImGui.Checkbox(label, ref value); + /// <summary> + /// The range rings' boxes. Each label shows the range RynthAi has now (its Settings > Ranges set it); + /// the boxes are the radar's own and save with the radar's settings. True when one changed. + /// </summary> + private static bool RangeRingRows() + { + RynthAiSettings? ra = UiSources.Settings.Current?.Value; + var inv = System.Globalization.CultureInfo.InvariantCulture; + string Yards(int v) => ra == null ? "" : " (" + v.ToString(inv) + " yd)"; + bool changed = Check("Monster Range ring" + Yards(ra?.MonsterRange ?? 0) + "###mrring", ref RadarSettingsStore.ShowMonsterRangeRing); + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("A ring round you at RynthAi's Monster Range: monsters inside it are ones the bot will attack.\nIt follows the setting (Settings > Ranges). Measured along the ground; RynthAi counts height too,\nso a monster a floor up or down can be inside the ring and still out of range."); + changed |= Check("Ring Range ring" + Yards(ra?.RingRange ?? 0) + "###rrring", ref RadarSettingsStore.ShowRingRangeRing); + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("A second, blue ring at RynthAi's Ring Range: how close monsters must be for its ring spells."); + if (ra == null && (RadarSettingsStore.ShowMonsterRangeRing || RadarSettingsStore.ShowRingRangeRing)) + { + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextDisabled("(waiting for RynthAi)"); + } + return changed; + } + /// <summary> /// "Hide the retail radar": RynthAi's own SuppressRetailRadar setting (RynthAi pushes it to the engine every /// tick), the same switch as Settings > UI > Hide retail radar. This reads it from RynthAi's settings payload diff --git a/src/RynthCore.Engine/ImGui/Panels/RadarRangeRing.cs b/src/RynthCore.Engine/ImGui/Panels/RadarRangeRing.cs new file mode 100644 index 0000000..b90672d --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RadarRangeRing.cs @@ -0,0 +1,47 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RadarRangeRing.cs +// The range rings round the player on the Radar (2026-11-06, player request): RynthAi's +// Monster Range (how far away a monster can be for the bot to attack it) and, optionally, +// its Ring Range (ring spells), drawn as circles at that many yards. The radar's world is +// in yards (192 per landblock, the same units RynthAi measures in) and its zoom is pixels +// per yard, so the ring's radius on the screen is range x zoom. +// +// Pure (no ImGui), so tools\RadarSettingsTests links it. +// ============================================================================ + +using System; +using System.Numerics; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class RadarRangeRing +{ + /// <summary>Rings smaller than this (px) aren't drawn: they would only blot out your own arrow.</summary> + public const float MinRadiusPx = 4f; + + /// <summary> + /// The ring's radius in pixels for a range of <paramref name="yards"/> at the radar's + /// <paramref name="zoom"/> (px per yard, at least 0.5 as the radar's projection keeps it). + /// 0 for no range (0, negative or not a number). + /// </summary> + public static float RadiusPx(double yards, float zoom) + { + if (!(yards > 0) || !double.IsFinite(yards)) return 0f; + float z = float.IsFinite(zoom) ? MathF.Max(0.5f, zoom) : 0.5f; + return (float)yards * z; + } + + /// <summary> + /// Whether any of a ring of <paramref name="radius"/> round <paramref name="centre"/> (the player) + /// shows on the picture: not too small, and inside the circle for the round radar (the two share + /// a centre), or reaching no further than the farthest corner of the square one. + /// </summary> + public static bool Shows(float radius, Vector2 centre, Vector2 min, Vector2 max, RoundMask? round) + { + if (!(radius >= MinRadiusPx)) return false; + if (round is { } circle) return radius <= circle.Radius; + float fx = MathF.Max(centre.X - min.X, max.X - centre.X); + float fy = MathF.Max(centre.Y - min.Y, max.Y - centre.Y); + return radius * radius <= fx * fx + fy * fy; + } +} diff --git a/src/RynthCore.Engine/ImGui/PhosphorIcons.cs b/src/RynthCore.Engine/ImGui/PhosphorIcons.cs index f2ee3bfd4..fbb7049 100644 --- a/src/RynthCore.Engine/ImGui/PhosphorIcons.cs +++ b/src/RynthCore.Engine/ImGui/PhosphorIcons.cs @@ -104,6 +104,7 @@ internal static unsafe class PhosphorIcons public const string MapTrifold = "\uE31A"; public const string Minus = "\uE32A"; public const string Monitor = "\uE32E"; + public const string Moon = "\uE330"; // baked for plugins: RynthDefective's Day/Night timer (2026-11-04) public const string NavigationArrow = "\uEADE"; public const string Path = "\uE39C"; public const string PencilSimple = "\uE3B4"; @@ -173,7 +174,8 @@ internal static unsafe class PhosphorIcons + CastleTurret + ClockCounterClockwise + GlobeHemisphereWest + Path + Star + Target + User + TextAa + Leaf + Keyboard + PushPin + SlidersHorizontal + Wrench - + Scroll; + + Scroll + + Moon; /// <summary> /// Draws <paramref name="glyph"/> (one icon) centred in the box at diff --git a/src/RynthCore.Engine/ImGui/RetailCursors.cs b/src/RynthCore.Engine/ImGui/RetailCursors.cs new file mode 100644 index 0000000..f969821 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/RetailCursors.cs @@ -0,0 +1,170 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/RetailCursors.cs +// The retail window cursors for RynthCore's windows (2026-11-07, Tom: "on retail mouse +// cursor changes when move/resize is going to happen"). AC's cursor is a Windows cursor: +// UIElementManager::SetCursor (0x0045A910) makes one from a 0x06 picture +// (Device::SetCursorFromImage -> CreateIconFromRenderSurface) and sets it as the game +// window's class cursor (SetClassLong GCL_HCURSOR) and with SetCursor. ImGui's cursor +// shapes (ImGui.SetMouseCursor: a panel's drag band, a resize edge or grip) never reached +// it, so the cursor stayed AC's. +// +// Now, when the frame's ImGui cursor is a move or resize shape, the game window shows +// retail's own window-control cursor for it (the pictures AC's windows use, read off the +// dat as OpenAC's RetailCursorCatalog has them; 32x32, hotspot 16,16): +// ResizeAll -> 0x06006119 (move) ResizeNS -> 0x06005E66 +// ResizeEW -> 0x06006128 ResizeNWSE -> 0x06006126 ResizeNESW -> 0x06006127 +// Win32Backend answers WM_SETCURSOR with it (AC's class cursor is left alone), and when the +// shape goes back to the arrow AC's own cursor (its class cursor) is put back. Other shapes +// (hand, text) keep AC's cursor, as before. The cursors are made once, from portal.dat. +// +// AC's main thread only (the ImGui frame and the window procedure both run on it). +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using ImGuiNET; +using RynthCore.Engine.UI.ScriptWindows; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static unsafe class RetailCursors +{ + private const int Hotspot = 16; + private static readonly (ImGuiMouseCursor Shape, uint Picture)[] Map = + { + (ImGuiMouseCursor.ResizeAll, 0x06006119u), + (ImGuiMouseCursor.ResizeNS, 0x06005E66u), + (ImGuiMouseCursor.ResizeEW, 0x06006128u), + (ImGuiMouseCursor.ResizeNWSE, 0x06006126u), + (ImGuiMouseCursor.ResizeNESW, 0x06006127u), + }; + + private static readonly IntPtr[] Handles = new IntPtr[Map.Length]; + private static bool _made, _failedLogged; + private static IntPtr _current; + + /// <summary>The retail cursor wanted now, or zero (AC's own). Win32Backend's WM_SETCURSOR reads it.</summary> + public static IntPtr Current => _current; + + /// <summary> + /// End of the ImGui frame: the shape ImGui asks for (<paramref name="shape"/>) while a RynthCore window has + /// the mouse (<paramref name="overUi"/>). Sets the retail cursor at once when it changes, and gives AC's back. + /// </summary> + public static void Update(ImGuiMouseCursor shape, bool overUi) + { + IntPtr want = IntPtr.Zero; + if (overUi) + { + int i = Array.FindIndex(Map, m => m.Shape == shape); + if (i >= 0) + { + if (!_made) Make(); + want = Handles[i]; + } + } + if (want == _current) return; + _current = want; + try + { + if (want != IntPtr.Zero) SetCursor(want); + else + { + IntPtr hwnd = Win32Backend.GameHwnd; + IntPtr ac = hwnd != IntPtr.Zero ? (IntPtr)GetClassLongW(hwnd, GclHCursor) : IntPtr.Zero; + if (ac != IntPtr.Zero) SetCursor(ac); + } + } + catch { } + } + + private static void Make() + { + _made = true; + try + { + string? path = AcDatFile.FindPortalDat(); + using AcDatFile? dat = path != null ? AcDatFile.Open(path, out _) : null; + if (dat == null) { Log("client_portal.dat not found"); return; } + int made = 0; + for (int i = 0; i < Map.Length; i++) + { + AcIconImage? img = AcIconDecoder.Decode(dat, Map[i].Picture, AcIconDecoder.MaxUiSide); + if (img == null) continue; + Handles[i] = CreateCursor(img); + if (Handles[i] != IntPtr.Zero) made++; + } + RynthLog.UI($"RetailCursors: {made} of {Map.Length} retail window cursors made."); + } + catch (Exception ex) { Log($"{ex.GetType().Name}: {ex.Message}"); } + } + + private static void Log(string why) + { + if (_failedLogged) return; + _failedLogged = true; + RynthLog.UI("RetailCursors: no retail window cursors (" + why + "); AC's cursor stays."); + } + + /// <summary>A Windows cursor from an RGBA picture (32-bit with alpha), hotspot in the middle as retail's.</summary> + private static IntPtr CreateCursor(AcIconImage img) + { + int w = img.Width, h = img.Height; + var bi = new BITMAPV5HEADER + { + bV5Size = (uint)sizeof(BITMAPV5HEADER), bV5Width = w, bV5Height = -h, bV5Planes = 1, bV5BitCount = 32, + bV5Compression = 3 /* BI_BITFIELDS */, bV5RedMask = 0x00FF0000, bV5GreenMask = 0x0000FF00, + bV5BlueMask = 0x000000FF, bV5AlphaMask = 0xFF000000, + }; + IntPtr dc = GetDC(IntPtr.Zero); + IntPtr color = CreateDIBSection(dc, ref bi, 0, out IntPtr bits, IntPtr.Zero, 0); + ReleaseDC(IntPtr.Zero, dc); + if (color == IntPtr.Zero || bits == IntPtr.Zero) return IntPtr.Zero; + var dst = new Span<byte>((void*)bits, w * h * 4); + byte[] src = img.Pixels; + for (int p = 0; p < w * h; p++) + { + dst[p * 4 + 0] = src[p * 4 + 2]; // B + dst[p * 4 + 1] = src[p * 4 + 1]; // G + dst[p * 4 + 2] = src[p * 4 + 0]; // R + dst[p * 4 + 3] = src[p * 4 + 3]; // A + } + IntPtr mask = CreateBitmap(w, h, 1, 1, IntPtr.Zero); + var info = new ICONINFO { fIcon = false, xHotspot = Math.Min(Hotspot, w - 1), yHotspot = Math.Min(Hotspot, h - 1), hbmMask = mask, hbmColor = color }; + IntPtr cursor = CreateIconIndirect(ref info); + DeleteObject(color); + DeleteObject(mask); + return cursor; + } + + private const int GclHCursor = -12; + + [StructLayout(LayoutKind.Sequential)] + private struct ICONINFO + { + [MarshalAs(UnmanagedType.Bool)] public bool fIcon; + public int xHotspot, yHotspot; + public IntPtr hbmMask, hbmColor; + } + + [StructLayout(LayoutKind.Sequential)] + private struct BITMAPV5HEADER + { + public uint bV5Size; + public int bV5Width, bV5Height; + public ushort bV5Planes, bV5BitCount; + public uint bV5Compression, bV5SizeImage; + public int bV5XPelsPerMeter, bV5YPelsPerMeter; + public uint bV5ClrUsed, bV5ClrImportant, bV5RedMask, bV5GreenMask, bV5BlueMask, bV5AlphaMask, bV5CSType; + public int e0, e1, e2, e3, e4, e5, e6, e7, e8; // CIEXYZTRIPLE + public uint bV5GammaRed, bV5GammaGreen, bV5GammaBlue, bV5Intent, bV5ProfileData, bV5ProfileSize, bV5Reserved; + } + + [DllImport("user32.dll")] private static extern IntPtr SetCursor(IntPtr hCursor); + [DllImport("user32.dll")] private static extern uint GetClassLongW(IntPtr hWnd, int nIndex); + [DllImport("user32.dll")] private static extern IntPtr CreateIconIndirect(ref ICONINFO piconinfo); + [DllImport("user32.dll")] private static extern IntPtr GetDC(IntPtr hWnd); + [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); + [DllImport("gdi32.dll")] private static extern IntPtr CreateDIBSection(IntPtr hdc, ref BITMAPV5HEADER pbmi, uint usage, out IntPtr bits, IntPtr section, uint offset); + [DllImport("gdi32.dll")] private static extern IntPtr CreateBitmap(int w, int h, uint planes, uint bitCount, IntPtr bits); + [DllImport("gdi32.dll")] private static extern bool DeleteObject(IntPtr obj); +} diff --git a/src/RynthCore.Engine/ImGui/RetailSprites.cs b/src/RynthCore.Engine/ImGui/RetailSprites.cs index 32229e4..db3641c 100644 --- a/src/RynthCore.Engine/ImGui/RetailSprites.cs +++ b/src/RynthCore.Engine/ImGui/RetailSprites.cs @@ -18,7 +18,9 @@ // The two meet only in two small queues under one lock. // // Bounded: at most 192 pictures, each at most 512 x 512 (the biggest the -// inventory uses is its 300 x 362 background, ~0.4 MB). A picture that isn't +// inventory uses is its 300 x 362 background, ~0.4 MB). A retail font's glyph +// sheet (TryGetFontSheet, 2026-11-07) may be 2048 wide (Palatino 24's is 2048 x +// 279, ~2.3 MB); only a plugin drawing retail text asks for them, a few at most. A picture that isn't // in the dat or doesn't decode is tried again after 30 s; until then the caller // draws its own stand-in (TryGet returns false). // ============================================================================ @@ -80,7 +82,30 @@ internal static class RetailSprites public static bool TryGet(uint textureId, out IntPtr texture) { texture = IntPtr.Zero; - if (!AcIconDecoder.IsTextureId(textureId)) return false; + return AcIconDecoder.IsTextureId(textureId) && TryGetKey(textureId, out texture); + } + + // A font's glyph sheet is keyed with this bit set, so it never shares a slot with the same + // texture drawn as a picture (a sheet decodes white, its level as alpha). + private const uint FontSheetBit = 0x80000000u; + + /// <summary> + /// A retail font's glyph sheet (its Font file's foreground or background surface, an A8 + /// 0x06 texture up to <see cref="AcIconDecoder.MaxFontSheetSide"/> wide) as a texture: + /// white, the sheet's level as alpha, so ImGui's tint colours the text (2026-11-07, for + /// plugins that draw the retail look with its own fonts). Otherwise as <see cref="TryGet"/>. + /// AC's render thread. + /// </summary> + public static bool TryGetFontSheet(uint textureId, out IntPtr texture) + { + texture = IntPtr.Zero; + return AcIconDecoder.IsTextureId(textureId) && TryGetKey(textureId | FontSheetBit, out texture); + } + + private static bool TryGetKey(uint key, out IntPtr texture) + { + texture = IntPtr.Zero; + uint textureId = key; if (!Sprites.TryGetValue(textureId, out Sprite? sprite)) { if (Sprites.Count >= MaxSprites) return false; @@ -219,7 +244,12 @@ internal static class RetailSprites } AcIconImage? image = null; - try { image = dat == null ? null : AcIconDecoder.Decode(dat, r.Id, AcIconDecoder.MaxUiSide); } + try + { + image = dat == null ? null + : (r.Id & FontSheetBit) != 0 ? AcIconDecoder.DecodeFontSheet(dat, r.Id & ~FontSheetBit) + : AcIconDecoder.Decode(dat, r.Id, AcIconDecoder.MaxUiSide); + } catch { image = null; } lock (Sync) { diff --git a/src/RynthCore.Engine/ImGui/UnderUiLayer.cs b/src/RynthCore.Engine/ImGui/UnderUiLayer.cs index f8a374f..a116dda 100644 --- a/src/RynthCore.Engine/ImGui/UnderUiLayer.cs +++ b/src/RynthCore.Engine/ImGui/UnderUiLayer.cs @@ -26,6 +26,16 @@ // the ImGui panels - the same place RenderNav3D's fallback draws. // A list is presented at most once: no double draw. // +// Windows under AC's UI (2026-11-07, PanelSpec.UnderUi: a plugin window's +// "layer": "underUi", RynthDreamWeave's Skills panel): the panel host builds +// the window as usual in the main frame and hands its draw lists (the window's +// and its body child's) here. EndScene's draw leaves them out +// (DX9Backend.RenderDrawData asks IsWindowList), and they are presented with +// the plates, after them, at the next frame's UI pass. ImGui keeps a window's +// draw list until the window's next Begin (the next EndScene, after that UI +// pass), so no copy is needed. At the EndScene fallback the lists already hold +// that frame's content: drawn without the lag, still under the panels. +// // The plates are therefore one frame behind the frame they were built in - // the same lag the Nav3D markers have, since both project with the camera // GameMatrixCapture took at the previous EndScene - on both paths, so a frame @@ -55,6 +65,33 @@ internal static unsafe class UnderUiLayer private static int _presenting; // a present is in flight (Shutdown waits for it) private static volatile bool _shutDown; + // Under-UI windows' draw lists (ImGui's own, owned by their windows): those of the frame being + // built, and those to present this frame (built last frame). AC's render thread only. + private static System.Collections.Generic.List<IntPtr> _winBuilding = new(), _winReady = new(); + private static Vector2 _winBuildingSize, _winReadySize; + + /// <summary> + /// Panel host, inside the main ImGui frame: a draw list of a window drawn under AC's UI. It is left + /// out of EndScene's draw and presented at the next UI pass with the world overlays. AC's render thread. + /// </summary> + public static void AddWindowList(ImDrawListPtr list) + { + if (_shutDown || list.NativePtr == null) return; + IntPtr p = (IntPtr)list.NativePtr; + if (!_winBuilding.Contains(p)) _winBuilding.Add(p); + _winBuildingSize = ImGuiNET.ImGui.GetIO().DisplaySize; + } + + /// <summary>True when any window draws under AC's UI (DX9Backend filters EndScene's lists then).</summary> + public static bool HasWindowLists => _winBuilding.Count > 0 || _winReady.Count > 0; + + /// <summary> + /// DX9Backend.RenderDrawData: a list EndScene must leave out (an under-UI window's, this frame's or + /// last frame's: a window's list pointer is the same every frame). AC's render thread. + /// </summary> + public static bool IsWindowList(ImDrawList* list) + => list != null && (_winBuilding.Contains((IntPtr)list) || _winReady.Contains((IntPtr)list)); + /// <summary>True after <see cref="BeginBuild"/> returned a list this frame. AC's render thread.</summary> public static bool IsBuilding => _building != null; @@ -124,12 +161,31 @@ internal static unsafe class UnderUiLayer Interlocked.Exchange(ref _presenting, 1); try { + if (_shutDown) return false; ImDrawList* list = _ready; - if (list == null || _shutDown) return false; - _presented = true; - if (list->VtxBuffer.Size == 0) return false; - DX9Backend.RenderDrawList(list, _readySize, device); - return true; + bool drew = false; + if (list != null) + { + _presented = true; + if (list->VtxBuffer.Size > 0) + { + DX9Backend.RenderDrawList(list, _readySize, device); + drew = true; + } + } + // The under-UI windows, over the plates (they are windows, the plates are the world's). + if (_winReady.Count > 0) + { + _presented = true; + foreach (IntPtr p in _winReady) + { + var w = (ImDrawList*)p; + if (w->VtxBuffer.Size == 0) continue; + DX9Backend.RenderDrawList(w, _winReadySize, device); + drew = true; + } + } + return drew; } finally { @@ -147,6 +203,10 @@ internal static unsafe class UnderUiLayer _readySize = _buildingSize; _building = null; _presented = false; + (_winReady, _winBuilding) = (_winBuilding, _winReady); + _winBuilding.Clear(); + if (_shutDown) _winReady.Clear(); + _winReadySize = _winBuildingSize; } /// <summary>One line for /rc imgui diag.</summary> @@ -164,6 +224,8 @@ internal static unsafe class UnderUiLayer _ready = null; _building = null; _listA = _listB = null; + _winReady.Clear(); + _winBuilding.Clear(); Thread.MemoryBarrier(); var spin = new SpinWait(); long deadline = Environment.TickCount64 + 200; diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs index 3b5d1c7..a3f2177 100644 --- a/src/RynthCore.Engine/ImGui/Win32Backend.cs +++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs @@ -134,6 +134,9 @@ internal static unsafe class Win32Backend private static bool IsExtendedKey(IntPtr lParam) => ((int)(long)lParam & 0x01000000) != 0; // ─── Win32 P/Invoke ─────────────────────────────────────────────── + [DllImport("user32.dll", EntryPoint = "SetCursor")] + private static extern IntPtr SetCursorNative(IntPtr hCursor); + // On x86, SetWindowLongPtr doesn't exist — use SetWindowLong [DllImport("user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true)] private static extern IntPtr SetWindowLong32(IntPtr hWnd, int nIndex, IntPtr dwNewLong); @@ -881,6 +884,14 @@ internal static unsafe class Win32Backend if (IsRemoteClientMouse(hWnd, msg, lParam)) return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam); + // A RynthCore window's move or resize spot under the mouse: retail's window-control cursor + // (RetailCursors), in the client area only; AC's own cursor everywhere else. + if (msg == WM_SETCURSOR && ((long)lParam & 0xFFFF) == 1 /* HTCLIENT */ && RetailCursors.Current != IntPtr.Zero) + { + SetCursorNative(RetailCursors.Current); + return (IntPtr)1; + } + // ── Chat capture: consume all key input for the chat TextBox ──── // Game HWND keeps Win32 focus throughout; callbacks dispatch Text // updates to the panel on Avalonia's UI thread — no Avalonia focus needed. diff --git a/src/RynthCore.Engine/LogPaths.cs b/src/RynthCore.Engine/LogPaths.cs index e6b99ee..4956292 100644 --- a/src/RynthCore.Engine/LogPaths.cs +++ b/src/RynthCore.Engine/LogPaths.cs @@ -10,6 +10,9 @@ // engine, and plugins inside one acclient.exe // (they all share that client's PID). One file per // running client. +// RynthCore.<pid>.log.old Its newest rotated copy (5 MB); older ones are +// RynthCore.<pid>.log.old.N .old.1 (next newest) ... .old.7 (LogRotation.cs; +// engine.json "LogKeepCopies", default 8 copies). // // Why per-client: a daily multi-boxer runs N acclient.exe at once. With one // shared file their lines interleave, the "scan hb #N for a gap" silent-death @@ -45,7 +48,7 @@ internal static class LogPaths /// <summary>Full path to this client's per-PID session log (loader + engine + plugins).</summary> internal static string LogFilePath => Path.Combine(LogDirectory, LogFileName); - /// <summary>Rotated previous copy of this client's session log.</summary> + /// <summary>Newest rotated copy of this client's session log (older ones: .old.1, .old.2, ... - LogRotation).</summary> internal static string RotatedLogFilePath => Path.Combine(LogDirectory, LogFileName + ".old"); /// <summary>Full path to the shared launch/orchestration log.</summary> @@ -80,10 +83,11 @@ internal static class LogPaths /// <summary> /// Engine-startup rotation: if THIS client's per-PID log exceeds - /// <see cref="MaxLogBytes"/>, move it to RynthCore.<pid>.log.old. With per-PID - /// files this only ever touches the current client's own file, so there is no - /// cross-process rotation race (the bug the old shared-file design had). Rotation - /// still matters because Windows reuses PIDs across launches. + /// <see cref="MaxLogBytes"/>, move it to RynthCore.<pid>.log.old, after shifting the + /// older copies to .old.1 ... .old.<N-1> (<see cref="LogRotation"/>; N = engine.json + /// "LogKeepCopies", default 8). With per-PID files this only ever touches the current + /// client's own files, so there is no cross-process rotation race (the bug the old + /// shared-file design had). Rotation still matters because Windows reuses PIDs across launches. /// </summary> internal static void RotateAtStartup() { @@ -99,18 +103,8 @@ internal static class LogPaths if (size < MaxLogBytes) return; - string rotated = RotatedLogFilePath; EntryPoint.ReleaseLogFile(); // the engine's open handle would follow the file to .old - try { if (File.Exists(rotated)) File.Delete(rotated); } catch { } - - try { File.Move(active, rotated); } - catch - { - // A hot-reloaded engine generation in this same process may hold - // the handle. Best-effort truncate so the file doesn't grow without - // bound. Safe under per-PID: only ever our own client's file. - try { File.WriteAllText(active, string.Empty); } catch { } - } + LogRotation.Rotate(active, LogSettings.KeepCopies); } catch { @@ -151,10 +145,11 @@ internal static class LogPaths } /// <summary> - /// Startup housekeeping: delete per-client session logs (and their .old + /// Startup housekeeping: delete per-client session logs (and their .old / .old.N /// rotations) older than <see cref="MaxLogAge"/>. Each client launch produces a /// new RynthCore.<pid>.log, so without this the directory grows without bound. - /// Never touches the shared RynthCore.log or the current client's own file. + /// Never touches the shared RynthCore.log, the current client's own files, or the files + /// of a client that is still running (<see cref="LogRotation.ShouldPrune"/>). /// Best-effort; never throws. /// </summary> internal static void PruneOldLogs() @@ -164,15 +159,18 @@ internal static class LogPaths EnsureLogDirectory(); string self = LogFileName; DateTime cutoff = DateTime.Now - MaxLogAge; + var live = new System.Collections.Generic.Dictionary<int, bool>(); + bool IsLive(int pid) + { + if (!live.TryGetValue(pid, out bool alive)) live[pid] = alive = IsPidAlive(pid); + return alive; + } foreach (string path in Directory.GetFiles(LogDirectory, "RynthCore.*.log*")) { string name = Path.GetFileName(path); - // Skip the shared log and our own current session file. - if (name.Equals(SharedLogFileName, StringComparison.OrdinalIgnoreCase)) continue; - if (name.StartsWith(self, StringComparison.OrdinalIgnoreCase)) continue; try { - if (File.GetLastWriteTime(path) < cutoff) + if (LogRotation.ShouldPrune(name, self, SharedLogFileName, File.GetLastWriteTime(path), cutoff, IsLive)) File.Delete(path); } catch { /* locked by a live client or already gone — skip */ } @@ -225,6 +223,39 @@ internal static class LogPaths /// </summary> internal static void RotateIfOversized() => RotateAtStartup(); + [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr OpenProcess(uint dwDesiredAccess, [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId); + + [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] + [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)] + private static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode); + + [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] + [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)] + private static extern bool CloseHandle(IntPtr hObject); + + /// <summary> + /// Whether a process with this PID is running (Win32, like PluginLoader.IsPidAliveWin32: + /// Process.GetProcessById is avoided in acclient). Errs towards "alive": access denied means + /// the process exists, so its logs are kept. A PID reused by another program only delays a prune. + /// </summary> + private static bool IsPidAlive(int pid) + { + if (pid <= 0) return false; + if (pid == Environment.ProcessId) return true; + IntPtr h = OpenProcess(0x1000 /* PROCESS_QUERY_LIMITED_INFORMATION */, false, pid); + if (h == IntPtr.Zero) + return System.Runtime.InteropServices.Marshal.GetLastWin32Error() == 5; // ERROR_ACCESS_DENIED: it exists + try + { + return !GetExitCodeProcess(h, out uint code) || code == 259 /* STILL_ACTIVE */; + } + finally + { + CloseHandle(h); + } + } + /// <summary> /// Append a single best-effort line to the SHARED RynthCore.log so it acts as /// an index of client sessions ("which PID, which build, which file"). Keeps diff --git a/src/RynthCore.Engine/LogRotation.cs b/src/RynthCore.Engine/LogRotation.cs new file mode 100644 index 0000000..494a0de --- /dev/null +++ b/src/RynthCore.Engine/LogRotation.cs @@ -0,0 +1,171 @@ +// ============================================================================ +// RynthCore.Engine - LogRotation.cs +// The per-client log's rotated copies (2026-11-08). One .old copy kept a busy +// client's last 30-60 minutes at most, so the log of a death an hour earlier +// was already gone. Now a rotation shifts the older copies down a chain: +// +// RynthCore.<pid>.log live +// RynthCore.<pid>.log.old newest rotated copy (the name every reader knows) +// RynthCore.<pid>.log.old.1 the one before it +// ... +// RynthCore.<pid>.log.old.<keep-1> the oldest kept +// +// ".old" stays the newest so the problem report, the launcher, soak_scorecard +// and everyone's habits keep working unchanged; older copies only ever gain a +// number. Pure file work with no engine state: tools\ProblemReportTests +// compiles this file in. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; + +namespace RynthCore.Engine; + +internal static class LogRotation +{ + /// <summary>Rotated copies kept per client by default (.old + .old.1 ... .old.7, ~40 MB at 5 MB each).</summary> + public const int DefaultKeepCopies = 8; + + /// <summary>1 = only .old, the behaviour before 2026-11-08.</summary> + public const int MinKeepCopies = 1; + + /// <summary>Upper bound for engine.json "LogKeepCopies" (250 MB per client at 5 MB each).</summary> + public const int MaxKeepCopies = 50; + + public static int ClampKeepCopies(int value) => + value < MinKeepCopies ? MinKeepCopies : value > MaxKeepCopies ? MaxKeepCopies : value; + + /// <summary>Rotated copy <paramref name="index"/> of <paramref name="active"/>: 0 = ".old" (newest), n = ".old.n".</summary> + public static string CopyPath(string active, int index) => + index <= 0 ? active + ".old" : active + ".old." + index.ToString(System.Globalization.CultureInfo.InvariantCulture); + + /// <summary>What <see cref="Rotate"/> did with the live file.</summary> + public enum Outcome + { + /// <summary>The live file was moved to .old (the older copies shifted first).</summary> + Moved, + /// <summary>The live file couldn't be moved (a handle without delete sharing); it was emptied instead.</summary> + Truncated, + /// <summary>Neither worked; the file is as it was.</summary> + Failed, + /// <summary>No live file.</summary> + Missing, + } + + /// <summary> + /// Rotates <paramref name="active"/>: the copies shift one step older (.old -> .old.1 -> ...), + /// the one that would pass <paramref name="keepCopies"/> is deleted (and any left from a larger + /// setting), and the live file becomes .old. Each step is best-effort: a copy that can't be + /// moved stays where it is, and when .old itself can't be moved it is deleted as before, so the + /// live file still rotates. The caller lets go of its own handle first. + /// </summary> + public static Outcome Rotate(string active, int keepCopies) + { + if (!File.Exists(active)) return Outcome.Missing; + int keep = ClampKeepCopies(keepCopies); + + // Drop the oldest (index keep-1 would shift to keep) and anything past the cap. + foreach (int index in NumberedCopies(active)) + { + if (index >= keep - 1) + try { File.Delete(CopyPath(active, index)); } catch { } + } + + // Shift oldest-first so nothing is overwritten that hasn't moved on. + for (int index = keep - 2; index >= 0; index--) + { + string from = CopyPath(active, index); + if (!File.Exists(from)) continue; + try { File.Move(from, CopyPath(active, index + 1), overwrite: true); } catch { } + } + + string newest = CopyPath(active, 0); + try { if (File.Exists(newest)) File.Delete(newest); } catch { } // only when it couldn't shift (or keep = 1) + + try + { + File.Move(active, newest); + return Outcome.Moved; + } + catch + { + // A hot-reloaded engine generation in this same process may hold the handle. + // Truncate so the file doesn't grow without bound (only ever our own client's file). + try { File.WriteAllText(active, string.Empty); return Outcome.Truncated; } + catch { return Outcome.Failed; } + } + } + + /// <summary>The n of every existing "<paramref name="active"/>.old.n" (n ≥ 1), unordered.</summary> + public static List<int> NumberedCopies(string active) + { + var found = new List<int>(); + try + { + string? dir = Path.GetDirectoryName(active); + if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir)) return found; + string prefix = Path.GetFileName(active) + ".old."; + // Win32 pattern rules make "x.old.*" match "x.old" too: check the prefix by hand. + foreach (string path in Directory.EnumerateFiles(dir, prefix + "*")) + { + string name = Path.GetFileName(path); + if (name.Length <= prefix.Length || !name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue; + string suffix = name.Substring(prefix.Length); + if (suffix.Length > 0 && suffix.Length <= 6 && IsDigits(suffix) + && int.TryParse(suffix, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int n) + && n >= 1) + found.Add(n); + } + } + catch { } + return found; + } + + /// <summary> + /// The client PID in a per-client log name: RynthCore.<pid>.log, .log.old or .log.old.<n>. + /// Null for anything else (the shared RynthCore.log, a renamed copy). + /// </summary> + public static int? PidOf(string fileName) + { + const string head = "RynthCore."; + if (!fileName.StartsWith(head, StringComparison.OrdinalIgnoreCase)) return null; + int dot = fileName.IndexOf('.', head.Length); + if (dot <= head.Length) return null; + string digits = fileName.Substring(head.Length, dot - head.Length); + if (digits.Length > 10 || !IsDigits(digits)) return null; + string rest = fileName.Substring(dot); // ".log", ".log.old", ".log.old.3" + bool known = rest.Equals(".log", StringComparison.OrdinalIgnoreCase) + || rest.Equals(".log.old", StringComparison.OrdinalIgnoreCase) + || (rest.StartsWith(".log.old.", StringComparison.OrdinalIgnoreCase) && rest.Length > 9 && IsDigits(rest.Substring(9))); + if (!known) return null; + return int.TryParse(digits, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int pid) ? pid : null; + } + + /// <summary> + /// The startup pruner's rule for one file matching RynthCore.*.log*: delete it when it is older + /// than <paramref name="cutoff"/>, is not the shared log, is not one of this client's own files + /// (<paramref name="selfLogName"/> and its copies), and does not belong to a client that is still + /// running (<paramref name="isLive"/>; a running client's oldest copies can pass 7 days on a long + /// soak). A name with no PID in it is judged on age alone, as before. + /// </summary> + public static bool ShouldPrune(string fileName, string selfLogName, string sharedLogName, + DateTime lastWrite, DateTime cutoff, Func<int, bool> isLive) + { + if (fileName.Equals(sharedLogName, StringComparison.OrdinalIgnoreCase)) return false; + if (fileName.Equals(selfLogName, StringComparison.OrdinalIgnoreCase) + || fileName.StartsWith(selfLogName + ".", StringComparison.OrdinalIgnoreCase)) return false; + if (lastWrite >= cutoff) return false; + int? pid = PidOf(fileName); + if (pid is int p && isLive(p)) return false; + return true; + } + + private static bool IsDigits(string s) + { + if (s.Length == 0) return false; + foreach (char c in s) + if (c < '0' || c > '9') return false; + return true; + } +} diff --git a/src/RynthCore.Engine/LogSettings.cs b/src/RynthCore.Engine/LogSettings.cs index cda2df7..070e469 100644 --- a/src/RynthCore.Engine/LogSettings.cs +++ b/src/RynthCore.Engine/LogSettings.cs @@ -37,6 +37,7 @@ internal enum LogCategory /// The emit level is the level a category's lines are written AT, so a line shows when /// its emit level is within the global threshold. Setting a Trace/Debug category to /// Info puts it in the normal (Info) log; Off silences the category entirely.</item> +/// <item><c>"LogKeepCopies"</c> — rotated copies of the per-client log to keep (<see cref="KeepCopies"/>).</item> /// </list> /// A background thread polls the file's timestamp once a second, so launcher edits apply to a /// running client without a restart. Errors are always written, even when the level is Off. @@ -65,6 +66,18 @@ internal static class LogSettings // thread can index it without a lock. private static EntryPoint.EngineLogLevel[] _levels = (EntryPoint.EngineLogLevel[])Defaults.Clone(); + /// <summary>engine.json property: rotated copies of the per-client log to keep (LogRotation).</summary> + internal const string KeepCopiesProperty = "LogKeepCopies"; + + private static int _keepCopies = LogRotation.DefaultKeepCopies; + + /// <summary> + /// engine.json "LogKeepCopies" (default 8, valid 1-50, clamped): how many rotated copies of + /// RynthCore.<pid>.log a client keeps (.old, then .old.1 ...; 5 MB each). 1 = only .old, as + /// before 2026-11-08. Hand-set in the file; read at init and whenever the file changes. + /// </summary> + internal static int KeepCopies => Volatile.Read(ref _keepCopies); + private static readonly object WatcherLock = new(); private static Thread? _watcherThread; private static ManualResetEventSlim? _stopSignal; @@ -103,6 +116,7 @@ internal static class LogSettings { string? globalText = null; var levels = (EntryPoint.EngineLogLevel[])Defaults.Clone(); + int keepCopies = LogRotation.DefaultKeepCopies; try { @@ -127,16 +141,22 @@ internal static class LogSettings levels[(int)cat] = lvl; } } + + if (root.TryGetProperty(KeepCopiesProperty, out JsonElement keepEl) && keepEl.ValueKind == JsonValueKind.Number + && keepEl.TryGetInt32(out int keep)) + keepCopies = LogRotation.ClampKeepCopies(keep); } } catch { // Half-written / corrupt file: keep defaults for this pass; the next timestamp change retries. globalText ??= EngineSettings.LoggingLevel; + keepCopies = Volatile.Read(ref _keepCopies); // never drop copies over a half-written file } EntryPoint.LoggingLevel = EntryPoint.ParseLoggingLevel(globalText); Volatile.Write(ref _levels, levels); + Volatile.Write(ref _keepCopies, keepCopies); EntryPoint.VerboseLogging = IsEnabled(LogCategory.Verbose); return Describe(); } diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 9fb87b5..8ad0b04 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -1016,8 +1016,9 @@ internal struct RynthCoreAPI /// (0 = unbound), -1 for a bad call. Any thread. Requires API v90+.</summary> public IntPtr GetActionKeysFn; /// <summary>v90: <c>void* GetIconTexture(int kind, uint id)</c>: 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+.</summary> + /// spell, 3 a retail UI picture at its own size, 4 a retail font's glyph sheet as white + alpha + /// (3 and 4 2026-11-07, no version bump): an ImGui texture + /// id, or null while it is made. AC's render thread, in a docked window's draw. Requires API v90+.</summary> public IntPtr GetIconTextureFn; /// <summary>v90: <c>int KeyCapture(int op, char* buffer, int length)</c>: op 0 waits for the next key /// the player presses (it never reaches AC; Esc cancels), 1 asks (0 waiting, 1 pressed: its name @@ -1058,6 +1059,16 @@ internal struct RynthCoreAPI /// asked for and the one drawn (0xAARRGGBB; 0 before the first frame). Returns 1 when the hook is /// live, 0 when it isn't (both 0). Either pointer may be null. Any thread. Requires API v91+.</summary> public IntPtr GetAmbientLightFn; + + // ── v93: the monster plates' health readings (ImGui/MonsterHud/MonsterHudData.cs) ── + + /// <summary>v93: <c>int GetMonsterHealth(uint id, float* ratio, uint* ageMs)</c>: the last health ratio + /// (0..1) the SERVER sent for the object, as the monster plates keep it, and how many ms ago. That + /// includes the replies to the plates' own round-robin probes (HealthProbe), which plugins never get + /// as UpdateHealth events, and never the plates' estimates from the player's hits. Returns 1 with a + /// reading, 0 without (never read; *ratio = -1, *ageMs = 0xFFFFFFFF). Either pointer may be null. + /// Read-only, any thread, no game calls. Requires API v93+.</summary> + public IntPtr GetMonsterHealthFn; } /// <summary>v89 GetUiColor tokens. Append only: plugins compiled against these numbers keep them.</summary> @@ -1916,6 +1927,9 @@ internal delegate int SetAmbientLightFloorCallbackDelegate(uint rgb); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetAmbientLightCallbackDelegate(uint* client, uint* applied); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetMonsterHealthCallbackDelegate(uint id, float* ratio, uint* ageMs); + [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 b500dcd..627dcad 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -40,5 +40,12 @@ internal static class PluginContractVersion // v92: SetActionKey op 3, a RynthCore command's key as an engine hotkey only (AC's keymap untouched), // and the SDK's BindCommandKeyOnly / UnbindCommandKeyOnly; no new function or field, but a plugin // calling them needs this SDK in Runtime\PluginShared (fix/keymap-follow-change, 2026-10-27). - public const uint Current = 92; + // v93: GetMonsterHealth: the monster plates' last SERVER health reading for an object and its age in ms + // (MonsterHudData.TryGetServerHealth; the plates' round-robin probe replies included, their hit + // estimates never), so a plugin can rank every nearby monster by health while the server streams + // only the queried one. The probe replies still don't reach plugins as UpdateHealth. Read-only, + // any thread (feature/hud-health-for-plugins, 2026-11-07). Note: feature/reload-state, + // feature/engine-events and the branches built on them (unmerged) also use 93 and 94; whichever + // merges second renumbers. + public const uint Current = 93; } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index bb0849b..d939a73 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -303,6 +303,7 @@ internal static partial class PluginManager private static DropTargetCallbackDelegate? _dropTargetCallback; // v90 private static SetAmbientLightFloorCallbackDelegate? _setAmbientLightFloorCallback; // v91 private static GetAmbientLightCallbackDelegate? _getAmbientLightCallback; // v91 + private static GetMonsterHealthCallbackDelegate? _getMonsterHealthCallback; // v93 private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback; private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback; private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback; @@ -930,7 +931,8 @@ internal static partial class PluginManager /// One health observation. <paramref name="healthReply"/>: it is a 0x01C0 UpdateHealth (a QueryHealth /// reply or the server's stream); one that answers the nameplates' own probe (HealthProbe) is the /// HUD's alone - plugins never asked for it, and a bot must not read someone else's hit on a monster - /// it isn't fighting as its own. + /// it isn't fighting as its own. (A plugin can still ask for the plates' last reading by id, API v93 + /// GetMonsterHealth: a number to rank by, not an UpdateHealth event.) /// </summary> public static void QueueUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth, bool healthReply = false) { @@ -3251,6 +3253,7 @@ internal static partial class PluginManager unsafe { _dropTargetCallback ??= ShortcutApi.DropTarget; } _setAmbientLightFloorCallback ??= AmbientLight.SetFloor; // v91 unsafe { _getAmbientLightCallback ??= AmbientLight.Get; } + unsafe { _getMonsterHealthCallback ??= GetMonsterHealthAction; } // v93 _api.Version = PluginContractVersion.Current; _api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback); @@ -3423,6 +3426,7 @@ internal static partial class PluginManager _api.DropTargetFn = Marshal.GetFunctionPointerForDelegate(_dropTargetCallback); _api.SetAmbientLightFloorFn = Marshal.GetFunctionPointerForDelegate(_setAmbientLightFloorCallback); _api.GetAmbientLightFn = Marshal.GetFunctionPointerForDelegate(_getAmbientLightCallback); + _api.GetMonsterHealthFn = Marshal.GetFunctionPointerForDelegate(_getMonsterHealthCallback); RouteApiThroughLoader(); } @@ -3620,6 +3624,27 @@ internal static partial class PluginManager /// v86: the server list as JSON (UI/Sections/ServerStateJson.cs) from the published snapshot. /// Any thread: the snapshot is immutable and the strings are volatile reads. -1 on failure. /// </summary> + /// <summary> + /// v93: the monster plates' last SERVER health reading for <paramref name="id"/> and its age + /// (MonsterHudData.TryGetServerHealth; probe replies included, estimates never). The probe replies + /// still don't reach plugins as UpdateHealth (QueueUpdateHealth drops them): a plugin asking here + /// gets a number, not someone else's hit as its own. Read-only, any thread, no game calls. + /// </summary> + private static unsafe int GetMonsterHealthAction(uint id, float* ratio, uint* ageMs) + { + try + { + bool ok = ImGuiBackend.Hud.MonsterHudData.TryGetServerHealth(id, out float r, out uint age); + if (ratio != null) *ratio = ok ? r : -1f; + if (ageMs != null) *ageMs = ok ? age : uint.MaxValue; + return ok ? 1 : 0; + } + catch + { + return 0; + } + } + /// <summary>v87: what the player wields (EquipmentTracker). -1 while it can't start.</summary> private static unsafe int GetWieldedItemsAction(uint* ids, uint* locations, int max) { @@ -4233,7 +4258,16 @@ internal static partial class PluginManager private static int WriteToChat(IntPtr textUtf16, int chatType) { string? text = textUtf16 != IntPtr.Zero ? Marshal.PtrToStringUni(textUtf16) : null; - return ToAbiBool(ClientHelperHooks.WriteToChat(text, chatType)); + // A colour the plugin armed just before (SendPluginCommand "RynthCore.Chat" nextcolor): + // RynthCore's chat draws this line in it; the chat type still decides where it goes. + long now = Environment.TickCount64; + uint? own = UI.Data.ChatOwnColors.TakeArmed(now); + if (own != null && !string.IsNullOrEmpty(text)) + UI.Data.ChatOwnColors.Lines.Expect(text, chatType, own.Value, now); + bool written = ClientHelperHooks.WriteToChat(text, chatType); + if (!written && own != null && !string.IsNullOrEmpty(text)) + UI.Data.ChatOwnColors.Lines.Forget(text, chatType); + return ToAbiBool(written); } private static int InvokeChatParser(IntPtr textUtf16) @@ -4876,6 +4910,13 @@ internal static partial class PluginManager string? value = valueAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(valueAnsi) : null; return Net.FlightRecorder.HandlePluginCommand(action, value) ? 1 : 0; } + // So does a line's own colour in RynthCore's chat (UI/Data/ChatOwnColors.cs, 2026-11-05). + if (name == UI.Data.ChatOwnColors.CommandTarget) + { + string? action = actionAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(actionAnsi) : null; + string? value = valueAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(valueAnsi) : null; + return UI.Data.ChatOwnColors.HandlePluginCommand(action, value, Environment.TickCount64) ? 1 : 0; + } IntPtr export = ResolvePluginExport(name, "RynthPluginApplyRemoteCommand"); if (export == IntPtr.Zero) diff --git a/src/RynthCore.Engine/Plugins/ShortcutApi.cs b/src/RynthCore.Engine/Plugins/ShortcutApi.cs index 71237f9..4798551 100644 --- a/src/RynthCore.Engine/Plugins/ShortcutApi.cs +++ b/src/RynthCore.Engine/Plugins/ShortcutApi.cs @@ -191,12 +191,21 @@ internal static unsafe class ShortcutApi /// 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. + /// Kind 3 (2026-11-07, no API bump: older engines answer 0 for it): a retail UI picture, any 0x06 + /// texture up to 512 x 512 at its own size (window backgrounds, banners, frame pieces), kept for + /// the session in RetailSprites, the cache the Inventory's Classic view draws from. For plugins + /// that draw the retail look (RynthDreamWeave's Skills panel); icons stay kind 0. + /// Kind 4 (same date): a retail font's glyph sheet (its Font file's foreground or background + /// surface, A8, up to 2048 wide) as white with the sheet's level as alpha, so the plugin draws + /// the retail UI's own text from the Font file's glyph table, tinted. /// </summary> public static IntPtr GetIconTexture(int kind, uint id) { try { - if (kind is < 0 or > 2 || id == 0 || !MainThreadGuard.IsOnMainThread() || ImGuiPopOuts.InPopOutFrame) return IntPtr.Zero; + if (kind is < 0 or > 4 || id == 0 || !MainThreadGuard.IsOnMainThread() || ImGuiPopOuts.InPopOutFrame) return IntPtr.Zero; + if (kind == 3) return RetailSprites.TryGet(id, out IntPtr sprite) ? sprite : IntPtr.Zero; + if (kind == 4) return RetailSprites.TryGetFontSheet(id, out IntPtr sheet) ? sheet : IntPtr.Zero; return ScriptIcons.TryGet((ScriptIconKind)kind, id, out IntPtr texture) ? texture : IntPtr.Zero; } catch { return IntPtr.Zero; } diff --git a/src/RynthCore.Engine/UI/AcWindowChrome.cs b/src/RynthCore.Engine/UI/AcWindowChrome.cs index 4a55b9f..0ba24a6 100644 --- a/src/RynthCore.Engine/UI/AcWindowChrome.cs +++ b/src/RynthCore.Engine/UI/AcWindowChrome.cs @@ -289,7 +289,12 @@ internal static class AcWindowChrome try { - AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Saved open windows and HUD positions.", 1); + // The PC-wide default with Panel Layout Per Character on is only read (2026-11-05): say so. + string? problem = PanelLayout.SavePlacesProblem(); + if (problem == null) + AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Saved open windows and HUD positions.", 1); + else + AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Saved HUD positions. Open windows and their places weren't saved: " + problem + ".", 0x1A); } catch { /* chat may not be ready */ } } diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index 0924e28..b173fdc 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -169,6 +169,8 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]> dto.Sender is { Length: > 0 } s ? StripAcLinks(s, out _) : linkedName, text) { Seq = dto.Seq, + // A plugin's own colour for it (ChatOwnColors), matched by the text as AC printed it. + OwnArgb = ChatOwnColors.Lines.Take(dto.Text, dto.Type, Environment.TickCount64), }; line.Route = router.Evaluate(line, null); if (line.Route.Mention) ChatModel.PumpMentionSound(); @@ -356,9 +358,10 @@ internal static class ChatModel /// settings), else the built-in one (ChatLineColors.BuiltInTabArgb).</summary> public static uint ChannelArgb(string chan) => ChatLineColors.TabArgb(chan); - /// <summary>The line's colour: a rule's line colour, else the colour set for its kind - /// (say, fellowship, [General]...), else its channel's. 0xAARRGGBB.</summary> - public static uint LineArgb(ChatLine line) => ChatLineColors.Resolve(line.Route.LineArgb, line.ColorKind, line.Channel, line.ChatType); + /// <summary>The line's colour: a rule's line colour, else the one its plugin asked for, else + /// the colour set for its kind (say, fellowship, [General]...), else its channel's. 0xAARRGGBB.</summary> + public static uint LineArgb(ChatLine line) => + ChatLineColors.ResolveLine(line.Route.LineArgb, line.OwnArgb, line.ColorKind, line.Channel, line.ChatType); /// <summary> /// What a rule's "When" can be: (stored value, label). Channel tabs, then diff --git a/src/RynthCore.Engine/UI/Data/ChatLineColors.cs b/src/RynthCore.Engine/UI/Data/ChatLineColors.cs index 26839e5..541ab8f 100644 --- a/src/RynthCore.Engine/UI/Data/ChatLineColors.cs +++ b/src/RynthCore.Engine/UI/Data/ChatLineColors.cs @@ -8,6 +8,8 @@ // // A line's colour, first that applies: // 1. a rule's line colour (ChatRoute.LineArgb), +// 1b. the colour the plugin that wrote the line asked for (ChatLine.OwnArgb, +// ChatOwnColors.cs, 2026-11-05: RynthAi's Info text colour), // 2. the colour the user set for the line's kind, // 3. the colour the user set for its tab, // 4. with Retail colours on (2026-10-28, the default), AC's own colour for @@ -272,6 +274,11 @@ internal static class ChatLineColors public static uint Resolve(uint? ruleArgb, string? kind, string channel, int chatType = -1) => ruleArgb ?? Get(kind) ?? Get(TabPrefix + channel) ?? RetailFor(chatType, channel) ?? BuiltInTabArgb(channel); + /// <summary>A scrollback line's colour: <see cref="Resolve"/> with the plugin's own colour for + /// it (<paramref name="ownArgb"/>, null = none) just below the rule's.</summary> + public static uint ResolveLine(uint? ruleArgb, uint? ownArgb, string? kind, string channel, int chatType = -1) => + Resolve(ruleArgb ?? ownArgb, kind, channel, chatType); + /// <summary>A key worth keeping from the settings file: a listed kind, a base tab, or a sane channel tag.</summary> public static bool IsValidKey(string? key) { diff --git a/src/RynthCore.Engine/UI/Data/ChatOwnColors.cs b/src/RynthCore.Engine/UI/Data/ChatOwnColors.cs new file mode 100644 index 0000000..63d3e26 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatOwnColors.cs @@ -0,0 +1,158 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatOwnColors.cs +// A plugin's own colour for a chat line it writes (2026-11-05). A player asked +// for RynthAi's item info in, say, allegiance orange without the line moving +// to where allegiance lines go: the chat type picks the tab, AC's own chat +// window and its colour, so the colour has to travel on its own. +// +// No API table change (any engine since v64 can be asked): the plugin calls +// SendPluginCommand("RynthCore.Chat", "nextcolor", "#RRGGBB") +// and then WriteToChat(text, chatType) on the same thread. The engine arms the +// colour for that thread (ArmWindowMs), the next WriteToChat takes it and +// notes (text, type, colour) here, and when RynthChat's copy of the line +// reaches ChatSource it is drawn in that colour (ChatLine.OwnArgb). The line +// keeps its chat type: the same tab, the same rules, the same retail window +// (which can only show the type's colour). An engine without this finds no +// plugin called "RynthCore.Chat" and answers 0; the plugin then just writes +// the line, as before. "nextcolor" with "" or "none" disarms. +// +// Matching is by the text and chat type (RynthChat passes both through +// unchanged; a line AC cut at 1,024 characters matches by its start). Each +// noted line colours one arriving line, oldest first. Lines nobody picked up +// (RynthChat not loaded, the chat face closed for a long time, AC refused the +// line) are forgotten after LineTtlMs, and at most MaxLines are kept. +// +// Pure (no engine state), so tools/ChatFilterTests compiles it in. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Threading; + +namespace RynthCore.Engine.UI.Data; + +/// <summary>Lines a plugin wrote with a colour of their own, waiting for RynthChat's copy (any thread).</summary> +internal sealed class ChatOwnColorQueue +{ + /// <summary>A noted line nobody picked up is forgotten after this long.</summary> + public const long LineTtlMs = 5 * 60_000; + /// <summary>At most this many lines wait; the oldest goes first.</summary> + public const int MaxLines = 256; + /// <summary>AC's longest incoming chat line (ChatCallbackHooks.MaxIncomingChatChars): a longer line arrives cut.</summary> + public const int MaxArrivingChars = 1024; + + private readonly record struct Entry(string Text, int ChatType, uint Argb, long AtMs); + + private readonly object _lock = new(); + private readonly LinkedList<Entry> _lines = new(); + private int _count; // read without the lock: the fast "nothing waiting" check + + public int Count => Volatile.Read(ref _count); + + /// <summary>The key a line is matched by: its text as AC printed it (CR / LF trimmed, as WriteToChat does).</summary> + public static string Key(string text) => text.TrimEnd('\r', '\n'); + + /// <summary>The plugin is about to write <paramref name="text"/> as <paramref name="chatType"/>, drawn in <paramref name="argb"/>.</summary> + public void Expect(string text, int chatType, uint argb, long nowMs) + { + string key = Key(text); + if (key.Length == 0) return; + lock (_lock) + { + Expire(nowMs); + while (_lines.Count >= MaxLines) _lines.RemoveFirst(); + _lines.AddLast(new Entry(key, chatType, argb | 0xFF000000, nowMs)); + Volatile.Write(ref _count, _lines.Count); + } + } + + /// <summary>WriteToChat refused the line: it never arrives, so it colours nothing (the newest such entry goes).</summary> + public void Forget(string text, int chatType) + { + string key = Key(text); + lock (_lock) + { + for (var n = _lines.Last; n != null; n = n.Previous) + if (n.Value.ChatType == chatType && n.Value.Text == key) + { + _lines.Remove(n); + break; + } + Volatile.Write(ref _count, _lines.Count); + } + } + + /// <summary> + /// The colour for an arriving line, or null: the oldest waiting entry with this text and chat + /// type is used up. <paramref name="chatType"/> -1 (RynthChat before 0.2.0) matches any type. + /// </summary> + public uint? Take(string? text, int chatType, long nowMs) + { + if (Count == 0 || string.IsNullOrEmpty(text)) return null; + string key = Key(text); + lock (_lock) + { + Expire(nowMs); + for (var n = _lines.First; n != null; n = n.Next) + { + Entry e = n.Value; + if (chatType >= 0 && e.ChatType != chatType) continue; + bool same = e.Text == key + || (key.Length >= MaxArrivingChars && e.Text.StartsWith(key, StringComparison.Ordinal)); + if (!same) continue; + _lines.Remove(n); + Volatile.Write(ref _count, _lines.Count); + return e.Argb; + } + Volatile.Write(ref _count, _lines.Count); + return null; + } + } + + private void Expire(long nowMs) + { + while (_lines.First is { } f && nowMs - f.Value.AtMs > LineTtlMs) _lines.RemoveFirst(); + } +} + +/// <summary>SendPluginCommand("RynthCore.Chat", ...) and the lines it colours; see the file header.</summary> +internal static class ChatOwnColors +{ + /// <summary>The plugin name plugins pass to SendPluginCommand to reach this.</summary> + public const string CommandTarget = "RynthCore.Chat"; + /// <summary>"#RRGGBB": the next WriteToChat on this thread is drawn in it; "" / "none" disarms.</summary> + public const string NextColorAction = "nextcolor"; + /// <summary>An armed colour the next WriteToChat doesn't follow within this long is dropped.</summary> + public const long ArmWindowMs = 2_000; + + public static readonly ChatOwnColorQueue Lines = new(); + + [ThreadStatic] private static uint t_armed; // 0 = none (an armed colour is always opaque) + [ThreadStatic] private static long t_armedAtMs; + + /// <summary>The command. True when it was understood (the plugin then knows the engine has this).</summary> + public static bool HandlePluginCommand(string? action, string? value, long nowMs) + { + if (!string.Equals((action ?? "").Trim(), NextColorAction, StringComparison.OrdinalIgnoreCase)) return false; + string v = (value ?? "").Trim(); + if (v.Length == 0 || v.Equals("none", StringComparison.OrdinalIgnoreCase)) + { + t_armed = 0; + return true; + } + uint? argb = ChatLineColors.ParseColor(v); + if (argb == null) return false; + t_armed = argb.Value | 0xFF000000; + t_armedAtMs = nowMs; + return true; + } + + /// <summary>This thread's armed colour, used up (null when none, or armed too long ago).</summary> + public static uint? TakeArmed(long nowMs) + { + uint armed = t_armed; + if (armed == 0) return null; + t_armed = 0; + return nowMs - t_armedAtMs <= ArmWindowMs ? armed : null; + } +} diff --git a/src/RynthCore.Engine/UI/Data/ChatRouting.cs b/src/RynthCore.Engine/UI/Data/ChatRouting.cs index 2eb3b3d..65b06ac 100644 --- a/src/RynthCore.Engine/UI/Data/ChatRouting.cs +++ b/src/RynthCore.Engine/UI/Data/ChatRouting.cs @@ -53,6 +53,9 @@ internal sealed class ChatLine /// <summary>Which line colour setting applies ("say", "chan:General", ...), or null: /// its tab's colour (ChatLineColors.KindOf, worked out once here).</summary> public string? ColorKind { get; } + /// <summary>The colour the plugin that wrote the line asked for (RynthAi's Info text colour; + /// ChatOwnColors), or null. Below a rule's line colour, above the kind / tab / retail ones.</summary> + public uint? OwnArgb { get; init; } /// <summary>"HH:mm:ss text": copy, log and the Avalonia face.</summary> public string FormattedText { get; } @@ -213,16 +216,28 @@ internal sealed class ChatFilterRule public volatile bool Invalid; /// <summary>Why it doesn't compile; null when it does or is just empty.</summary> public volatile string? Error; - /// <summary>A match timed out: skipped until the pattern is edited.</summary> + /// <summary>Too slow SlowStrikesToSkip times within SlowStrikeWindowMs: skipped until the pattern is edited.</summary> public volatile bool Slow; + /// <summary>Compiled non-backtracking (ChatRuleMatching.CompileForRouter): linear time, never Slow.</summary> + public volatile bool Linear; + + /// <summary>One slow reading (a timeout, or a re-route over budget) is a strike, not a verdict: a + /// busy PC slows every rule now and then. This many within the window mark the rule Slow.</summary> + public const int SlowStrikesToSkip = 3; + public const long SlowStrikeWindowMs = 10 * 60_000; + internal int SlowStrikes; + internal long FirstStrikeMs; /// <summary>Compiles the pattern once (after every pattern edit). Any thread.</summary> public void Recompile() { Slow = false; - // A Regex rule compiles exactly as before; plain text is escaped (ChatRuleMatching). - Regex? rx = ChatRuleMatching.Compile(Mode, Pattern, TimeoutMs, out string? error); + SlowStrikes = 0; + // Non-backtracking when the pattern allows it (linear, no timeout); otherwise a Regex rule + // compiles exactly as before and plain text is escaped (ChatRuleMatching). + Regex? rx = ChatRuleMatching.CompileForRouter(Mode, Pattern, TimeoutMs, out string? error, out bool linear); Compiled = rx; + Linear = linear; Error = error; Invalid = rx == null; } @@ -329,11 +344,11 @@ internal sealed class ChatRouter /// <summary>Adds a rule's matching time during a pass; marks it Slow past the budget. False once it's Slow.</summary> private bool Charge(int i, long ticks, List<Step>? trace) { - if (!_inPass) return true; + if (!_inPass || _rules[i].Linear) return true; // linear time: the clock only measures the PC _passTicks[i] += Math.Min(ticks, MaxChargeTicks); if (_passTicks[i] <= _passBudgetTicks) return true; - MarkSlow(_rules[i], trace, i, $"over {PassBudgetMs:0} ms per {PassBudgetLines} lines to re-route the kept lines"); - return false; + _passTicks[i] = 0; // one strike per budget's worth, not one per line after it + return !MarkSlow(_rules[i], trace, i, $"over {PassBudgetMs:0} ms per {PassBudgetLines} lines to re-route the kept lines"); } /// <summary>Before routing every kept line again.</summary> @@ -499,16 +514,33 @@ internal sealed class ChatRouter tabs.Add(tab); } - private static void MarkSlow(ChatFilterRule rule, List<Step>? trace, int index, string why) + /// <summary>A slow reading for <paramref name="rule"/>: a strike, and on the + /// SlowStrikesToSkip-th within the window the rule is skipped until edited. True when it is.</summary> + private static bool MarkSlow(ChatFilterRule rule, List<Step>? trace, int index, string why) { - if (!rule.Slow) + if (!rule.Slow && !rule.Linear) { - rule.Slow = true; - RynthLog.UI($"ChatModel: rule \"{rule.Pattern}\" is too slow ({why}) and is skipped until edited."); - // Lines already routed with it are routed again without it. - ChatModel.BumpFiltersVersion(); + long now = Environment.TickCount64; + if (rule.SlowStrikes == 0 || now - rule.FirstStrikeMs > ChatFilterRule.SlowStrikeWindowMs) + { + rule.SlowStrikes = 0; + rule.FirstStrikeMs = now; + } + rule.SlowStrikes++; + if (rule.SlowStrikes >= ChatFilterRule.SlowStrikesToSkip) + { + rule.Slow = true; + RynthLog.Info($"ChatModel: rule \"{rule.Pattern}\" is too slow ({why}, {rule.SlowStrikes} times in " + + $"{(now - rule.FirstStrikeMs) / 1000} s) and is skipped until edited."); + // Lines already routed with it are routed again without it. + ChatModel.BumpFiltersVersion(); + } + else + RynthLog.Info($"ChatModel: rule \"{rule.Pattern}\" was slow ({why}), {rule.SlowStrikes} of " + + $"{ChatFilterRule.SlowStrikesToSkip} before it is skipped; still used."); } - trace?.Add(new Step(index, "too slow - now skipped until edited")); + trace?.Add(new Step(index, rule.Slow ? "too slow - now skipped until edited" : "slow this once - still used")); + return rule.Slow; } /// <summary>Overlapping spans: the earlier one (a higher rule) keeps its characters.</summary> diff --git a/src/RynthCore.Engine/UI/Data/ChatRuleMatching.cs b/src/RynthCore.Engine/UI/Data/ChatRuleMatching.cs index d2b4109..1ee44d0 100644 --- a/src/RynthCore.Engine/UI/Data/ChatRuleMatching.cs +++ b/src/RynthCore.Engine/UI/Data/ChatRuleMatching.cs @@ -71,6 +71,36 @@ internal static class ChatRuleMatching catch (ArgumentException ex) { error = ex.Message; return null; } } + /// <summary> + /// The router's compile (2026-11-07): the rule first as a non-backtracking regex, which runs in + /// time linear in the line's length whatever the pattern, so it gets no match timeout and can + /// never be "too slow" (<paramref name="linear"/> true). Every plain-text rule and most regex + /// rules compile this way. A pattern that needs backtracking (lookarounds, backreferences, + /// atomic groups, conditionals) compiles as <see cref="Compile"/> does, with the timeout. + /// + /// Why: the rules were timed by the clock. On a PC running several game clients a plain-text + /// rule's first match after a compile, a GC pause or a descheduled pump thread ran past the 15 ms + /// timeout, and the rule was skipped until edited - "too slow and skipped all the time" (the + /// owner, 2026-11-07, with eight plain-text rules). Rules recompile whenever the shared chat + /// settings file is saved by any client. + /// </summary> + public static Regex? CompileForRouter(ChatMatchMode mode, string? pattern, int timeoutMs, out string? error, out bool linear) + { + error = null; + linear = false; + string? expr = ToRegex(mode, pattern); + if (expr == null) return null; + try + { + var rx = new Regex(expr, Options | RegexOptions.NonBacktracking, Regex.InfiniteMatchTimeout); + linear = true; + return rx; + } + catch (NotSupportedException) { } // needs backtracking: the timed compile below + catch (ArgumentException) { } // a bad pattern: the compile below reports it as before + return Compile(mode, pattern, timeoutMs, out error); + } + /// <summary>The "mode" a rule's JSON carries: absent (an older file or a Regex rule) is Regex.</summary> public static ChatMatchMode Parse(string? json) => (json ?? "").Trim().ToLowerInvariant() switch { diff --git a/src/RynthCore.Engine/UI/Data/DamageRowStats.cs b/src/RynthCore.Engine/UI/Data/DamageRowStats.cs index 1d36ac3..00abe5a 100644 --- a/src/RynthCore.Engine/UI/Data/DamageRowStats.cs +++ b/src/RynthCore.Engine/UI/Data/DamageRowStats.cs @@ -9,11 +9,25 @@ // // "mstats": { "sw": swings, "ev": evaded, "sp": spells, "rs": resisted, "ne": no effect, // "at": attacks, "yev": you evaded, "ysp": spells at you, "yrs": you resisted, -// "yne": no effect on you, "k": kills, "dd": damage dealt, "dt": damage taken } +// "yne": no effect on you, "k": kills, "dd": damage dealt, "dt": damage taken, +// "xp": XP from its kills, "xk": the kills that XP is from, +// "cd": average ms from our kill to its corpse appearing, "cn": kills that was timed over, +// "h<c>": hits it landed on you, "d<c>": their total damage, "m<c>": the biggest, +// per cell c = shield (s: one in the off hand in a combat stance, n: none) + +// facing (f: it stood within 90 degrees of your facing, b: outside it, u: unknown): +// sf sb su nf nb nu } +// +// The h/d/m cells (RynthAi 2026-11-08: does a shield cut a boss's hits?) are learned across +// logins (monster_damage.txt's TS rows), not since login; RynthAi sends them even with nothing +// counted since login, and then nothing else. ACE counts a shield only against an attacker in +// front (Creature_Combat.GetShieldMod), so "front" is the share of shield hits where it could. // // sw = your melee and missile attacks at it (hits + its evades), sp = your spells that -// reached it (landed + resisted + no effect); at / ysp the same from it to you. Missing -// numbers are 0. The engine only words them; the plugin counts. +// reached it (landed + resisted + no effect); at / ysp the same from it to you. xp / xk +// (RynthAi 2026-11-08, for Outdoor Hunt's Most XP) give "XP/kill" first on the line; an +// older RynthAi sends neither. cd / cn (its death animation) give "Death animation 2.1 s" +// last on the line, only when cn > 0. Missing numbers are 0. The engine only words them; the +// plugin counts. // // Pure (System.Text.Json only): tools/DamageRowStatsTests compiles this file as is. // The plugin sees an engine that draws them through GetUiHookFlags bit 8. @@ -29,19 +43,110 @@ namespace RynthCore.Engine.UI.Data; internal sealed record DamageRowStats( int Swings, int Evaded, int Spells, int Resisted, int NoEffect, int Attacks, int YouEvaded, int SpellsAtYou, int YouResisted, int NoEffectOnYou, - int Kills, long Dealt, long Taken) + int Kills, long Dealt, long Taken, long Xp = 0, int XpKills = 0, int CorpseMs = 0, int CorpseKills = 0) { + /// <summary>One cell of the hits it landed by shield and facing: count, total damage, biggest.</summary> + internal readonly record struct TakenCell(int Hits, long Total, long Max) + { + public double Avg => Hits > 0 ? (double)Total / Hits : 0; + } + + /// <summary>The cells' keys, in <see cref="ShieldCells"/> order: shield front, behind, unknown; no shield the same.</summary> + public static readonly string[] CellKeys = { "sf", "sb", "su", "nf", "nb", "nu" }; + + /// <summary>The hits it landed on you by shield and facing (<see cref="CellKeys"/> order); all zero when not sent.</summary> + public TakenCell[] ShieldCells { get; init; } = new TakenCell[6]; + /// <summary>The row's "mstats", or null when it has none (or nothing counted in it).</summary> public static DamageRowStats? Parse(JsonElement row) { if (row.ValueKind != JsonValueKind.Object || !row.TryGetProperty("mstats", out JsonElement m) || m.ValueKind != JsonValueKind.Object) return null; + var cells = new TakenCell[6]; + for (int i = 0; i < 6; i++) + { + string k = CellKeys[i]; + int h = I(m, "h" + k); + cells[i] = h > 0 ? new TakenCell(h, L(m, "d" + k), L(m, "m" + k)) : default; + } var s = new DamageRowStats(I(m, "sw"), I(m, "ev"), I(m, "sp"), I(m, "rs"), I(m, "ne"), - I(m, "at"), I(m, "yev"), I(m, "ysp"), I(m, "yrs"), I(m, "yne"), I(m, "k"), L(m, "dd"), L(m, "dt")); + I(m, "at"), I(m, "yev"), I(m, "ysp"), I(m, "yrs"), I(m, "yne"), I(m, "k"), L(m, "dd"), L(m, "dt"), + L(m, "xp"), I(m, "xk"), I(m, "cd"), I(m, "cn")) { ShieldCells = cells }; return s.IsEmpty ? null : s; } - public bool IsEmpty => Swings == 0 && Spells == 0 && Attacks == 0 && SpellsAtYou == 0 && Kills == 0; + /// <summary>Something was counted since login (the evades, resists, kills, XP, corpse times).</summary> + public bool HasSession => Swings != 0 || Spells != 0 || Attacks != 0 || SpellsAtYou != 0 || Kills != 0 || XpKills != 0 || CorpseKills != 0; + + /// <summary>Hits learned by shield and facing.</summary> + public bool HasShieldTaken => ShieldHits(true) + ShieldHits(false) > 0; + + public bool IsEmpty => !HasSession && !HasShieldTaken; + + /// <summary>Hits it landed with a shield up (<paramref name="shield"/>) or without, every facing.</summary> + public int ShieldHits(bool shield) + { + int o = shield ? 0 : 3; + return ShieldCells[o].Hits + ShieldCells[o + 1].Hits + ShieldCells[o + 2].Hits; + } + + /// <summary>Their mean damage (0 with none).</summary> + public double ShieldAvg(bool shield) + { + int o = shield ? 0 : 3; + int n = ShieldHits(shield); + return n > 0 ? (double)(ShieldCells[o].Total + ShieldCells[o + 1].Total + ShieldCells[o + 2].Total) / n : 0; + } + + /// <summary> + /// "Hits taken: shield 11 avg (front 95%), no shield 54 avg": the mean hit with a shield up and + /// the share of those from in front (of the ones measured; "facing unknown" when none was), + /// then without one; each half only with hits; "" with none. + /// </summary> + public string ShieldLine() + { + var parts = new List<string>(2); + int sh = ShieldHits(true); + if (sh > 0) + { + int front = ShieldCells[0].Hits, behind = ShieldCells[1].Hits; + string facing = front + behind > 0 ? $"front {Percent(front, front + behind)}" : "facing unknown"; + parts.Add($"shield {N(Whole(ShieldAvg(true)))} avg ({facing})"); + } + if (ShieldHits(false) > 0) parts.Add($"no shield {N(Whole(ShieldAvg(false)))} avg"); + return parts.Count == 0 ? "" : "Hits taken: " + string.Join(", ", parts); + } + + /// <summary>The tooltip's block: every cell in full, and ACE's rule.</summary> + public string ShieldTip() + { + if (!HasShieldTaken) return ""; + string Cell(int i, string facing) + { + TakenCell c = ShieldCells[i]; + return c.Hits == 0 ? $"{facing} -" : $"{facing} {N(c.Hits)} {(c.Hits == 1 ? "hit" : "hits")}, avg {N(Whole(c.Avg))}, max {N(c.Max)}"; + } + string Half(bool shield) + { + int o = shield ? 0 : 3; + int n = ShieldHits(shield); + return (shield ? "Shield up: " : "No shield: ") + + (n == 0 ? "no hits" : $"{N(n)} {(n == 1 ? "hit" : "hits")}, avg {N(Whole(ShieldAvg(shield)))} - " + + Cell(o, "front") + "; " + Cell(o + 1, "behind") + "; " + Cell(o + 2, "facing unknown")); + } + return "Damage it did to you, learned across logins:\n" + + Half(true) + ".\n" + Half(false) + ".\n" + + "A shield counts only in a combat stance and against an attacker within 90 degrees of your facing (front)."; + } + + private static long Whole(double v) => (long)Math.Round(v, MidpointRounding.AwayFromZero); + + /// <summary>The death animation in seconds, one decimal ("2.1"): cd / 1000, halves rounded up.</summary> + public string CorpseSeconds + => (Math.Round(CorpseMs / 100.0, MidpointRounding.AwayFromZero) / 10).ToString("0.0", CultureInfo.InvariantCulture); + + /// <summary>XP per kill, rounded (xp / xk); 0 when no kill counted XP.</summary> + public long XpPerKill => XpKills > 0 ? (long)Math.Round((double)Xp / XpKills, MidpointRounding.AwayFromZero) : 0; /// <summary>"23%" (whole from 10% up), "4.5%" (one decimal below), "-" with nothing to divide by. RynthAi words it the same.</summary> public static string Percent(int part, int whole) @@ -53,21 +158,36 @@ internal sealed record DamageRowStats( } /// <summary> - /// The line under the row: "It evades 23% (14/61) · It resists 10% (3/30) · You evade 42% (50/120) · - /// You resist 13% (1/8)", each part only when there is something to divide by; "" for none. + /// The line under the row: "XP/kill 1,234,567 · Hits taken: shield 24 avg (front 95%), no shield 54 avg · + /// It evades 23% (14/61) · It resists 10% (3/30) · You evade 42% (50/120) · You resist 13% (1/8) · + /// Death animation 2.1 s", each part only when there is something to divide by; "" for none. XP/kill + /// leads so a narrow panel's clip never cuts it, the hits taken by shield (<see cref="ShieldLine"/>) + /// follow it, and the death animation sits at the far right (Tom 2026-11-08). /// </summary> public string Line() { - var parts = new List<string>(4); + var parts = new List<string>(7); + if (XpKills > 0) parts.Add($"XP/kill {N(XpPerKill)}"); + string shield = ShieldLine(); + if (shield.Length > 0) parts.Add(shield); if (Swings > 0) parts.Add($"It evades {Percent(Evaded, Swings)} ({N(Evaded)}/{N(Swings)})"); if (Spells > 0) parts.Add($"It resists {Percent(Resisted, Spells)} ({N(Resisted)}/{N(Spells)})"); if (Attacks > 0) parts.Add($"You evade {Percent(YouEvaded, Attacks)} ({N(YouEvaded)}/{N(Attacks)})"); if (SpellsAtYou > 0) parts.Add($"You resist {Percent(YouResisted, SpellsAtYou)} ({N(YouResisted)}/{N(SpellsAtYou)})"); + if (CorpseKills > 0) parts.Add($"Death animation {CorpseSeconds} s"); return string.Join(" · ", parts); } - /// <summary>The tooltip: both ways in full.</summary> + /// <summary>The tooltip: both ways in full, then the hits taken by shield and facing.</summary> public string Tip() + { + string shield = ShieldTip(); + if (!HasSession) return shield; + return SessionTip() + (shield.Length > 0 ? "\n\n" + shield : ""); + } + + /// <summary>The numbers since login in full.</summary> + private string SessionTip() { string noEffect = NoEffect > 0 ? $", {N(NoEffect)} no effect (immune)" : ""; string noEffectYou = NoEffectOnYou > 0 ? $", {N(NoEffectOnYou)} no effect (immune)" : ""; @@ -78,6 +198,8 @@ internal sealed record DamageRowStats( + $"It at you: {N(Attacks)} melee/missile attacks, {N(Attacks - YouEvaded)} hit, you evaded {N(YouEvaded)} ({Percent(YouEvaded, Attacks)}); " + $"{N(SpellsAtYou)} spells reached you, you resisted {N(YouResisted)} ({Percent(YouResisted, SpellsAtYou)}){noEffectYou}; " + $"{N(Taken)} damage.\n" + + (XpKills > 0 ? $"XP: {N(Xp)} from {N(XpKills)} {(XpKills == 1 ? "kill" : "kills")}, {N(XpPerKill)} per kill.\n" : "") + + (CorpseKills > 0 ? $"Corpse appears {CorpseSeconds} s after the kill (over {N(CorpseKills)} {(CorpseKills == 1 ? "kill" : "kills")}).\n" : "") + "The killing blow counts as a hit (melee, missile) or a landed spell (magic)."; } diff --git a/src/RynthCore.Engine/UI/Data/ItemToolData.cs b/src/RynthCore.Engine/UI/Data/ItemToolData.cs index bf87132..010b479 100644 --- a/src/RynthCore.Engine/UI/Data/ItemToolData.cs +++ b/src/RynthCore.Engine/UI/Data/ItemToolData.cs @@ -33,6 +33,12 @@ internal sealed class ChestToolState [JsonPropertyName("status")] public string Status { get; set; } = string.Empty; [JsonPropertyName("running")] public bool Running { get; set; } [JsonPropertyName("looted")] public int Looted { get; set; } + // "Chest re-lock wait (s)" (2026-11-05). 0 = a RynthAi that predates it: the panel hides the control. + [JsonPropertyName("relockSec")] public int RelockSec { get; set; } + [JsonPropertyName("relockMin")] public int RelockMin { get; set; } = 5; + [JsonPropertyName("relockMax")] public int RelockMax { get; set; } = 600; + // False until the character's settings profile loaded (RynthAi refuses the change then). + [JsonPropertyName("relockReady")] public bool RelockReady { get; set; } } internal sealed class GiveToolState @@ -89,8 +95,8 @@ internal static unsafe class ItemToolCommands } /// <summary> - /// Posts one Item Tool command ("chest set", "chest key", "chest start", "chest stop", "giveitem", - /// "givetarget", "give", "givestop"). Runs on the pump; RynthAi older than this build has no such + /// Posts one Item Tool command ("chest set", "chest key", "chest start", "chest stop", "relock N", + /// "giveitem", "givetarget", "give", "givestop"). Runs on the pump; RynthAi older than this build has no such /// export: the click is logged and dropped. /// </summary> public static void Send(string words) => UiDataHub.Post("Item Tool " + words, () => diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index e24df27..e463bd2 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -47,6 +47,9 @@ internal sealed class RynthAiSettings public bool? RearmAfterVitals { get; set; } public bool StartMacroOnLogin { get; set; } public bool PatrolOnLogin { get; set; } + // RynthAi's Resume Meta After Reload (2026-11-07). Nullable: an older RynthAi doesn't send it, + // and then the row is hidden and nothing is sent back. + public bool? ResumeMetaOnReload { get; set; } // RynthAi's Escape Acid and Lava. Default on; an older RynthAi doesn't send it, and a missing // field must not read as "off". public bool EscapeHazards { get; set; } = true; @@ -205,6 +208,11 @@ internal sealed class RynthAiSettings public float DunPatrolWallDistance { get; set; } = 1f; // every patrol point this far from walls where there is room public float DunPatrolLookInSize { get; set; } = 10f; // rooms this big the patrol only skirts get a walk to their middle public float DunPatrolSightYd { get; set; } = 20f; // sweep: how far a monster notices you (lane spacing) + // RynthAi outdoor hunt (/ra hunt; OutdoorHunt, 2026-10-23). Null = a RynthAi without it: the rows hide, + // and a save sends null back, which RynthAi reads as unchanged. + public float? OutdoorHuntRange { get; set; } // yd from the character: how far the next monster may be + public float? OutdoorHuntRadius { get; set; } // yd from where the hunt started (0 = anywhere) + public int? OutdoorHuntPick { get; set; } // what it goes for: 0 nearest monster, 1 biggest pack, 2 most XP public bool OpenDoors { get; set; } public float OpenDoorRange { get; set; } = 5f; // RynthAi OpenDoorsOnPathOnly: Open Doors opens only a closed door on the path of travel. An older plugin ignores it. @@ -267,6 +275,8 @@ internal sealed class RynthAiSettings public bool ItemInfoOnSelect { get; set; } = true; public bool EnableAutostack { get; set; } = true; public bool ReadUnknownScrolls { get; set; } = true; // VTank's default + // Unbox Aetheria When Idle (default off; a RynthAi that predates it doesn't send it: off). + public bool UnboxAetheriaWhenIdle { get; set; } public bool EnableCombineSalvage { get; set; } = true; public bool CombineBagsDuringSalvage { get; set; } = true; // Salvage with the 0x027D request sent straight to the server, no salvage panel on screen @@ -304,6 +314,8 @@ internal sealed class RynthAiSettings // hidden, and a save sends null, which RynthAi leaves alone. public bool? UseDispelItems { get; set; } public bool? AutoFellowMgmt { get; set; } + // Open fellowship on create (2026-11-04): a fellowship RynthAi creates is opened, with AutoFellowMgmt on. + public bool? OpenFellowOnCreate { get; set; } public bool? MChargesWhenOff { get; set; } public int? CustomPetRange { get; set; } @@ -620,6 +632,8 @@ internal static class SettingsSchema public static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" }; public static readonly string[] NavLabelModes = { "Off", "Numbers", "Numbers and names" }; public static readonly string[] DunPatrolCoverages = { "Whole dungeon", "Loops only", "Everything", "Sweep (by sight)" }; + // RynthAi OutdoorHuntPick: 0 = nearest monster, 1 = biggest pack, 2 = most XP. + public static readonly string[] OutdoorHuntPicks = { "Nearest monster", "Biggest pack", "Most XP" }; public static readonly string[] DeathRecallModes = { "Off", "Cast a recall spell", "Use a recall item" }; // The nav editor's recall spells. Filled with "Spell N (N)" and named from the client's spell @@ -666,7 +680,15 @@ 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"; + private const string ShortcutsWindow = "Shortcuts", GamePanelsWindow = "Game Panels", SelectionWindow = "Selection", + DayNightWindow = "Day/Night"; + + // RynthDefective's extra Shortcuts bars (2026-11-04): "Shortcuts 2" ... "Shortcuts 5". + private static string ExtraShortcutsWindow(int n) => ShortcutsWindow + " " + n.ToString(System.Globalization.CultureInfo.InvariantCulture); + + private static string ExtraShortcutsTip(int n) => + $"RynthDefective's extra shortcut bar {n}: slots of its own, clicked (no keys), in a window you can put anywhere.\n" + + $"Add or remove bars from the Shortcuts bar's right-click menu. Also: /rdef bars show {n}."; // 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) => @@ -924,7 +946,7 @@ internal static class SettingsSchema Bool("Describe Items When Selected", s => s.ItemInfoOnSelect, (s, v) => s.ItemInfoOnSelect = v, "Print a Mag-style description of an item in chat when you select it, identifying it\nfirst when needed. Items the bot selects while looting are skipped.\nAlso: /ra iteminfo on|off."), Button("Item Info Options", "Open...", () => RynthAiCommands.ApplyRemoteCommand("iteminfo", "window"), - "Which fields the description shows and which item types are described on select (/ra iteminfo window)."), + "Which fields the description shows, which item types are described on select, and its chat\ntype and text colour (/ra iteminfo window)."), }), new("UI", new[] @@ -986,6 +1008,17 @@ internal static class SettingsSchema 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), + WindowShown("Day/Night timer", DayNightWindow, + "A small timer: day or night in Dereth now, and the real time until the next dawn or dusk (a Dereth day is 2 h 7 min).\nAlso: /rdef daynight."), + WindowSize("Day/Night timer size", DayNightWindow), + // RynthDefective's extra bars (2026-11-04): up to three more windows, "Shortcuts 2" ... "Shortcuts 4" + // (its ExtraBar), each row shown only while the plugin hosts that bar (the character has it). + WindowShown("Shortcut bar 2", ExtraShortcutsWindow(2), ExtraShortcutsTip(2)), + WindowSize("Shortcut bar 2 size", ExtraShortcutsWindow(2)), + WindowShown("Shortcut bar 3", ExtraShortcutsWindow(3), ExtraShortcutsTip(3)), + WindowSize("Shortcut bar 3 size", ExtraShortcutsWindow(3)), + WindowShown("Shortcut bar 4", ExtraShortcutsWindow(4), ExtraShortcutsTip(4)), + WindowSize("Shortcut bar 4 size", ExtraShortcutsWindow(4)), }), // The user hotkeys: stored by the engine for the PC (Hotkeys/HotkeyService.cs, hotkeys.txt), @@ -1049,6 +1082,12 @@ internal static class SettingsSchema "Automatically starts the macro when RynthAi loads."), Bool("Patrol On Login", s => s.PatrolOnLogin, (s, v) => s.PatrolOnLogin = v, "Automatically starts dungeon patrol when RynthAi loads."), + Bool("Resume Meta After Reload", s => s.ResumeMetaOnReload != false, (s, v) => s.ResumeMetaOnReload = v, + "After a hot reload (RynthCore or RynthAi updated while you play), the meta carries on where it was:\n" + + "the same state, its variables, the rules that had already fired, the call stack, the watchdog and\n" + + "the route with its waypoint. Nothing in Default runs again, so a meta that recalls in Default doesn't recall.\n" + + "A real login (or a changed meta file) still starts in Default. Off: every reload starts the meta in Default.", + when: s => s.ResumeMetaOnReload != null), Bool("Escape Acid and Lava", s => s.EscapeHazards, (s, v) => s.EscapeHazards = v, "When acid or lava hurts you, stop everything (combat, buffs, healing, looting)\nand walk back out the way you came. The spot is remembered so the patrol avoids it.\nTurn off for a character that walks through acid on purpose."), Bool("Yield to VTank", s => s.YieldToVTank, (s, v) => s.YieldToVTank = v, @@ -1250,7 +1289,12 @@ internal static class SettingsSchema when: s => s.UseDispelItems.HasValue), Bool("Auto Fellowship Management", s => s.AutoFellowMgmt ?? false, (s, v) => s.AutoFellowMgmt = v, "VTank's Auto Fellow Mgmt., saved with the profile. Metas read it (AutoFellowMgmt).", - when: s => s.AutoFellowMgmt.HasValue), + when: s => s.AutoFellowMgmt.HasValue, gates: true), + Bool(" Open fellowship on create", s => s.OpenFellowOnCreate ?? true, (s, v) => s.OpenFellowOnCreate = v, + "A fellowship RynthAi creates (/mt fellow create, or a meta's /fellowship create) is opened\n" + + "as soon as you lead it, so every member can recruit, not just the leader. AC makes a new\n" + + "fellowship closed.\nOnly right after RynthAi creates it: one you made or closed by hand is left alone.", + when: s => s.AutoFellowMgmt == true && s.OpenFellowOnCreate.HasValue), Bool("M. Charges When Off", s => s.MChargesWhenOff ?? false, (s, v) => s.MChargesWhenOff = v, "VTank's option of this name, saved with the profile for VTank users. RynthAi doesn't act on it yet.", when: s => s.MChargesWhenOff.HasValue), @@ -1408,6 +1452,27 @@ internal static class SettingsSchema "(across its corners). Smaller rooms are only looked into from the doorway. Once per room per lap. Default 10."), Note("Changing these rebuilds a running patrol from where you stand; the macro keeps running."), Spacer(), + Section("Outdoor Hunt", when: s => s.OutdoorHuntRange.HasValue), + Float("Hunt Range (yd)", s => s.OutdoorHuntRange ?? 60f, (s, v) => s.OutdoorHuntRange = Math.Clamp(v, 10f, 2000f), 10f, 2000f, 5f, + "Outdoor hunting (/ra hunt, the dashboard's Hunt button) walks from monster to monster round buildings,\n" + + "trees, rocks and slopes too steep to climb (RynthNav's map; portals are kept clear of). This is how far\n" + + "from you the next monster may be. It picks the one with the shortest walk, a higher Priority first, from\n" + + "the monsters combat would fight; combat takes over once it is in range and in sight. Default 60.", + when: s => s.OutdoorHuntRange.HasValue), + Float("Hunt Radius (yd)", s => s.OutdoorHuntRadius ?? 0f, (s, v) => s.OutdoorHuntRadius = Math.Clamp(v, 0f, 2000f), 0f, 2000f, 10f, + "Only monsters within this far of where you started hunting are picked. 0 = anywhere: it follows the\n" + + "monsters across the map. With none in range it waits where it is. Default 0.", + when: s => s.OutdoorHuntRadius.HasValue), + Combo("Go for", OutdoorHuntPicks, + s => Math.Clamp(s.OutdoorHuntPick ?? 0, 0, OutdoorHuntPicks.Length - 1), + (s, v) => s.OutdoorHuntPick = Math.Clamp(v, 0, OutdoorHuntPicks.Length - 1), + "Nearest monster: the closest one, as before.\n" + + "Biggest pack: the most monsters together, a near pack preferred unless a farther one is clearly bigger.\n" + + "Most XP: the pack worth the most experience, learned from your kills (unknown monsters count like a pack).", + when: s => s.OutdoorHuntPick.HasValue), + Note("Outdoors only (in a dungeon the Dungeon Patrol hunts). Loading a route, stopping the macro or going\ninto a dungeon ends it. Needs RynthNav.", + when: s => s.OutdoorHuntRange.HasValue), + Spacer(), Section("Steering"), Float("Stop & Turn Angle", s => s.NavStopTurnAngle, (s, v) => s.NavStopTurnAngle = v, 1f, 90f, 1f, "Stop forward motion and turn in place when heading error exceeds this."), @@ -1508,6 +1573,14 @@ internal static class SettingsSchema Bool("Enable Autocram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v, "Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack.", disabledWhen: s => s.AutoSortOn, disabledTip: CramOffForSortTip), + Bool("Unbox Aetheria When Idle", s => s.UnboxAetheriaWhenIdle, (s, v) => s.UnboxAetheriaWhenIdle = v, + "With the macro on and nothing to fight or loot, uses an Aetheria Mana Stone on each Coalesced\n" + + "Aetheria in your pack, one at a time, to reveal its sigil. The server puts you in peace mode for\n" + + "the clap; combat takes its stance again for the next fight. The stone isn't used up.\n" + + "Says once in chat when coalesced aetheria are left and no stone is. Status: /ra aetheria."), + ChatButton("Unbox Aetheria Now", "Unbox", "/ra aetheria unbox", + "Unbox every Coalesced Aetheria in your pack now, one at a time, setting on or off\n" + + "(with the macro on it waits for a quiet moment) (/ra aetheria unbox)."), Bool("Combine Salvage Bags", s => s.EnableCombineSalvage, (s, v) => s.EnableCombineSalvage = v, "After the salvage queue empties, move same-name bags together so the server merges them."), Bool("Combine Bags During Salvage", s => s.CombineBagsDuringSalvage, (s, v) => s.CombineBagsDuringSalvage = v, @@ -1554,7 +1627,7 @@ internal static class SettingsSchema { Section("AutoVendor"), Bool("Enabled", s => s.AutoVendorEnabled, (s, v) => s.AutoVendorEnabled = v, - "Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\nProfile: <Vendor Name>.utl, else default.utl, in the AutoVendor folder."), + "Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\nProfile: <Vendor Name>.utl, else default.utl, from your character's AutoVendor folder,\nthen the server's (RynthAi\\AutoVendor\\<server>), then RynthAi\\AutoVendor."), Bool("Test Mode (only print what it would do)", s => s.AutoVendorTestMode, (s, v) => s.AutoVendorTestMode = v, "Lists what would be bought and sold without trading. Leave this on until the lists look right."), Bool("Buy", s => s.AutoVendorEnableBuying, (s, v) => s.AutoVendorEnableBuying = v), diff --git a/src/RynthCore.Engine/UI/PanelLayout.cs b/src/RynthCore.Engine/UI/PanelLayout.cs index a7a2c3a..807c748 100644 --- a/src/RynthCore.Engine/UI/PanelLayout.cs +++ b/src/RynthCore.Engine/UI/PanelLayout.cs @@ -7,7 +7,9 @@ // Switching. Tick (EndScene, AC's render thread, every frame) works out the // layout the client should use: the PC-wide default until a character is in // the world, then that character's (SessionStateRegistry's server and name, -// known straight after LoginComplete, which a hot reload marks at engine init). +// known straight after LoginComplete, which a hot reload marks at engine init; +// a client launched with no character picked has no name there, so the +// player's own name from the object snapshot, 2026-11-05). // A switch then runs in three steps: // 1. render thread: snapshot the ImGui windows of the layout being left; // 2. UI writer (UiBackgroundWriter, in order with every other UI save): write @@ -28,10 +30,13 @@ // the render thread and atomically, always to the file of the layout the // context holds. // -// The default pair is written by clients that use it in the world as before -// (setting off, no character name) and by /rc layout default; not by a switch, -// not at character select with the setting on, and never with the windows of a -// character that logged out (PanelLayoutPolicy.MayAutoSaveIni). +// The default pair is written by clients that use it with the setting off (as +// before) and by /rc layout default. With the setting on nothing else writes +// it (2026-11-05; PanelLayoutPolicy.MaySaveLayoutInUse, PanelStateStore +// .ReadOnlyPath): not a switch, not character select, not a client in the +// world that doesn't know its character yet, not Save Layout Now. Before, a +// client with no character name saved its places there all session, every +// such client overwrote the others', and a reload read back whoever won. // ============================================================================ using System; @@ -56,17 +61,25 @@ internal static class PanelLayout // and the ImGui windows' text for it. private static Loaded? _applied; private static string? _activeIniText; - private static bool _contextHeldCharacter; // the ImGui context has had a character's windows in it private static LayoutOwner? _placedFor; // the layout the open panels were last placed from private static bool _placedForSet; /// <summary>The character whose layout is applied; null = the default (or none yet).</summary> private static LayoutOwner? Active => Volatile.Read(ref _applied)?.Switch.To; - // The identity Tick last read (SessionStateRegistry's strings), so it isn't rebuilt every frame. - private static string? _idServer, _idCharacter; + // The identity Tick last read (SessionStateRegistry's strings and the player's own name), so it + // isn't rebuilt every frame. + private static string? _idServer, _idCharacter, _idLive; private static LayoutOwner? _idOwner; + // The player's own name for the login it was read in (render thread): the launch context has + // none when the client was launched to character select (2026-11-05). + private static string _liveName = string.Empty; + private static long _liveNameLogin = -1; + + // The setting the default's read-only mark (PanelStateStore.ReadOnlyPath) was set for. + private static bool? _readOnlyFor; + /// <summary>An /rc layout default or reset waiting for the render thread (one at a time).</summary> private sealed record PendingOp(LayoutCommand Kind, Action<string, bool> Reply); private static PendingOp? _pendingOp; @@ -88,23 +101,57 @@ internal static class PanelLayout { if (_initialized) return; _initialized = true; + MarkDefaultReadOnly(EngineSettings.PanelLayoutPerCharacter); RynthLog.UI($"PanelLayout: per character {(EngineSettings.PanelLayoutPerCharacter ? "on" : "off")}; layouts under {Path.Combine(LocalRoot, PanelLayoutPolicy.LayoutsFolder)}."); } + /// <summary>With the setting on, no save writes the default's panel_state.txt (PanelLayoutPolicy.MaySaveLayoutInUse).</summary> + private static void MarkDefaultReadOnly(bool perCharacter) + { + if (_readOnlyFor == perCharacter) return; + _readOnlyFor = perCharacter; + PanelStateStore.ReadOnlyPath = perCharacter ? FilesFor(null).PanelState : null; + } + private static bool InWorld => LoginLifecycleHooks.HasObservedLoginComplete; private static LayoutOwner? Identity() { string server = SessionStateRegistry.LastServerName, character = SessionStateRegistry.LastCharacterName; - if (!ReferenceEquals(server, _idServer) || !ReferenceEquals(character, _idCharacter)) + string live = string.IsNullOrWhiteSpace(character) && InWorld ? LiveName() : string.Empty; + if (!ReferenceEquals(server, _idServer) || !ReferenceEquals(character, _idCharacter) || !ReferenceEquals(live, _idLive)) { _idServer = server; _idCharacter = character; - _idOwner = PanelLayoutPolicy.Owner(server, character); + _idLive = live; + _idOwner = PanelLayoutPolicy.Identity(server, character, live); } return _idOwner; } + /// <summary> + /// The name of the player in the world, read once per login from the object snapshot (no native + /// call: the main-thread walk fills it every half second; the live name lookup at LoginComplete + /// stays off in SessionStateRegistry). Empty until the snapshot has the player. Render thread. + /// </summary> + private static string LiveName() + { + long login = LoginLifecycleHooks.LoginCompleteAtMs; + if (login != _liveNameLogin) + { + _liveNameLogin = login; + _liveName = string.Empty; + } + if (_liveName.Length > 0 || login == 0) return _liveName; + uint me = ClientHelperHooks.CachedPlayerId; + if (me != 0 && ClientObjectHooks.TryGetSnapshotName(me, out string name) && !string.IsNullOrWhiteSpace(name)) + { + _liveName = name.Trim(); + RynthLog.UI($"PanelLayout: the launch context names no character; the player in the world is {_liveName}."); + } + return _liveName; + } + /// <summary> /// True when panels may draw (EngineFrameController.PanelsLive): after a login, only once that /// login's layout is in place. Always true before Initialize. Render thread. @@ -129,6 +176,7 @@ internal static class PanelLayout if (!Session.InFlight && Volatile.Read(ref _pendingOp) != null && Interlocked.Exchange(ref _pendingOp, null) is { } op) RunOp(op, imguiReady ? snapshotIni : null); + MarkDefaultReadOnly(EngineSettings.PanelLayoutPerCharacter); // the setting can change in Settings > Display LayoutSwitch? sw = Session.Tick(Environment.TickCount64, EngineSettings.PanelLayoutPerCharacter, InWorld, LoginLifecycleHooks.LoginCompleteAtMs, SessionStateRegistry.LoginRecorded, Identity()); if (sw is { } s) @@ -223,7 +271,6 @@ internal static class PanelLayout } Volatile.Write(ref _applied, l); _activeIniText = l.IniText; - if (l.Switch.To != null) _contextHeldCharacter = true; Session.MarkApplied(l.Switch.Gen); // A reset places the panels again even though the layout's owner is the same. @@ -293,12 +340,29 @@ internal static class PanelLayout path = string.Empty; // Nothing applied yet: the context holds no file's windows, and saving it would empty one. if (Volatile.Read(ref _applied) is not { } applied) return false; - if (!explicitSave && !PanelLayoutPolicy.MayAutoSaveIni(applied.Switch.To != null, EngineSettings.PanelLayoutPerCharacter, InWorld, _contextHeldCharacter)) + // The default with the setting on: only read, even by Save Layout Now (2026-11-05). + if (!PanelLayoutPolicy.MaySaveLayoutInUse(applied.Switch.To != null, EngineSettings.PanelLayoutPerCharacter)) + { + if (explicitSave) RynthLog.UI($"PanelLayout: Save Layout Now didn't write {applied.Files.ImGuiIni}: {SaveBlockedReason()}."); return false; + } path = applied.Files.ImGuiIni; return true; } + private static string SaveBlockedReason() => PanelLayoutPolicy.DefaultReadOnlyText(InWorld); + + /// <summary> + /// Save Layout Now (Settings > Display): null when the window places go to the layout in use, else + /// why they don't (the PC-wide default with the setting on is only read). Any thread (racy read). + /// </summary> + public static string? SavePlacesProblem() + { + if (!_initialized || Volatile.Read(ref _applied) is not { } applied) return null; + return PanelLayoutPolicy.MaySaveLayoutInUse(applied.Switch.To != null, EngineSettings.PanelLayoutPerCharacter) + ? null : SaveBlockedReason(); + } + // ── /rc layout and Settings ─────────────────────────────────────────── /// <summary>/rc layout: the layout in use, its files, and the default's. Any thread (racy reads).</summary> diff --git a/src/RynthCore.Engine/UI/PanelLayoutPolicy.cs b/src/RynthCore.Engine/UI/PanelLayoutPolicy.cs index 062e94d..f5077dd 100644 --- a/src/RynthCore.Engine/UI/PanelLayoutPolicy.cs +++ b/src/RynthCore.Engine/UI/PanelLayoutPolicy.cs @@ -20,6 +20,17 @@ // time. The key is the one the engine's other per-character files use: the // server and character of the launch context (SessionStateRegistry). // +// A client launched with no character picked (2026-11-05: the owner's client +// that stops at character select) has no name in its launch context, so it +// sat on the PC-wide default for the whole session, at every login and after +// every hot reload, and saved its window places into the shared files that +// seed new characters. The name is now the launch context's or, when that has +// none, the player's own name read in the world (Identity). While no name is +// known the default is only read: nothing writes it automatically, and Save +// Layout Now doesn't either, with the setting on (MaySaveLayoutInUse); only +// /rc layout default does. The client switches to its character's layout as +// soon as the name is known, however late. +// // Here: who owns a layout and its file names, which layout a client uses, // what a new character's layout is seeded from, the session bookkeeping that // decides when to switch and when panels may draw (PanelLayoutSession), and @@ -55,6 +66,13 @@ internal readonly record struct LayoutFiles(string PanelState, string ImGuiIni) /// <summary>What /rc layout asks for.</summary> internal enum LayoutCommand { Invalid, Status, MakeDefault, ResetAsk, ResetConfirm } +/// <summary>The kinds of windows the engine hosts (ImGuiPanelHost): its own panels, plugins' manifest windows, script windows.</summary> +internal enum WindowKind { EnginePanel, PluginWindow, ScriptWindow } + +/// <summary>What a layout switch does to one window: nothing, open it, close it (not saved), place it +/// from the layout, or place it and save it there (new to that layout).</summary> +internal enum SwitchStep { Leave, Open, Close, Place, PlaceAndSave } + /// <summary>Why a client in the world uses the PC-wide default (the status line says it).</summary> internal enum DefaultReason { None, SettingOff, NotInWorld, NoCharacterName, WaitingForName, NotRunning } @@ -80,6 +98,15 @@ internal static class PanelLayoutPolicy return new LayoutOwner((server ?? string.Empty).Trim(), c); } + /// <summary> + /// The layout's owner from what the client knows (2026-11-05): the launch context's character, or + /// when it has none (a client launched to character select) the name of the player in the world. + /// The launch context comes first: it is the key the other per-character files use. Null while + /// neither is known. + /// </summary> + public static LayoutOwner? Identity(string? server, string? launchCharacter, string? liveCharacter) => + Owner(server, string.IsNullOrWhiteSpace(launchCharacter) ? liveCharacter : launchCharacter); + /// <summary>"Name on Server" (just the name when the server isn't known), for replies and the log.</summary> public static string Describe(LayoutOwner who) => who.Server.Length > 0 ? who.Character + " on " + who.Server : who.Character; @@ -147,16 +174,40 @@ internal static class PanelLayoutPolicy (!characterPanelState && defaultPanelState, !characterIni && defaultIni); /// <summary> - /// Whether an automatic save of the ImGui windows (the dirty timer, shutdown) may write the file in - /// use. Always for a character's layout. The default: with the setting off (the shared file, as - /// before), or in the world by a client whose context never held a character's windows (one with - /// no character name, which uses the default as before). Not at character select: the default - /// there is this client's copy from when it loaded it, and writing it back could undo another - /// client's /rc layout default; nor with the windows of a character that just logged out. An - /// explicit save (Save Layout Now) writes whatever is in use. + /// Whether a save (imgui.ini or panel_state.txt; Dear ImGui's dirty timer, a moved window, shutdown, + /// a hot reload, Save Layout Now) may write the layout in use. Always a character's layout. The + /// PC-wide default only with the setting off (the shared files, as before). With the setting on + /// the default is only read (2026-11-05): a client on it is at character select or doesn't know + /// its character yet, and every such client saving its places there made them overwrite each + /// other and seeded new characters with them. /rc layout default writes it (PanelLayoutFiles). /// </summary> - public static bool MayAutoSaveIni(bool characterLayout, bool perCharacter, bool inWorld, bool contextHeldCharacter) => - characterLayout || !perCharacter || (inWorld && !contextHeldCharacter); + public static bool MaySaveLayoutInUse(bool characterLayout, bool perCharacter) => + characterLayout || !perCharacter; + + /// <summary>Engine panels and plugin windows open and close with the layout; script windows when their owner says (2026-11-05).</summary> + public static bool FollowsSavedOpenState(WindowKind kind) => kind != WindowKind.ScriptWindow; + + /// <summary> + /// What a layout switch does to one window (ImGuiPanelHost.ApplyLayoutSwitch): <paramref name="shown"/> + /// now; <paramref name="saved"/> the new layout has a row for it, <paramref name="savedOpen"/> saved + /// open; <paramref name="remember"/> Remember Open Windows. A plugin window follows the layout like an + /// engine panel (2026-11-05): it registers from its plugin's manifest seconds after a login, so one + /// registered while another layout was in use (a name that came late, a relogin) had that layout's + /// open state and kept it. + /// </summary> + public static SwitchStep StepAtSwitch(WindowKind kind, bool shown, bool remember, bool saved, bool savedOpen) + { + bool follows = FollowsSavedOpenState(kind) && remember && saved; + if (!shown) return follows && savedOpen ? SwitchStep.Open : SwitchStep.Leave; + if (follows && !savedOpen) return SwitchStep.Close; + return saved ? SwitchStep.Place : SwitchStep.PlaceAndSave; + } + + /// <summary>Why the window places weren't saved (the default with the setting on): Save Layout Now's reply and the log.</summary> + public static string DefaultReadOnlyText(bool inWorld) => + "with Panel Layout Per Character on, the PC-wide default layout is only read (" + + ReasonText(inWorld ? DefaultReason.NoCharacterName : DefaultReason.NotInWorld) + + "); /rc layout default makes a character's layout the default"; // ── /rc layout ─────────────────────────────────────────────────────── @@ -180,7 +231,7 @@ internal static class PanelLayoutPolicy { DefaultReason.SettingOff => "Panel layout per character is off (Settings > Display)", DefaultReason.NotInWorld => "no character is in the world", - DefaultReason.NoCharacterName => "no character name is known for this client (it wasn't started by the RynthCore launcher)", + DefaultReason.NoCharacterName => "this client doesn't know its character's name yet, so window places aren't saved until it does", DefaultReason.WaitingForName => "still waiting for the character's name", DefaultReason.NotRunning => "panel layouts aren't running in this client", _ => "the layout is still switching", @@ -291,7 +342,8 @@ internal sealed class PanelLayoutSession /// <summary> /// Once a frame. <paramref name="identityRecorded"/>: the login's identity is recorded - /// (SessionStateRegistry); <paramref name="identity"/> is it (null: no character name). + /// (SessionStateRegistry); <paramref name="identity"/> is who the client is now (PanelLayoutPolicy.Identity: + /// the recorded name, else the player's own; null: no character name yet). /// Returns a switch to start, or null. /// </summary> public LayoutSwitch? Tick(long nowMs, bool perCharacter, bool inWorld, long loginAtMs, bool identityRecorded, LayoutOwner? identity) @@ -302,7 +354,10 @@ internal sealed class PanelLayoutSession Wanted = null; } // (A login time of 0 in the world: the flag is set, its time not yet; wait for it.) - else if (loginAtMs != 0 && (identityRecorded || nowMs - loginAtMs >= PanelLayoutPolicy.IdentityWaitMs)) + // Recorded without a name (a client launched to character select, 2026-11-05): the player's + // own name is on its way too, so that waits as long as an unrecorded one. After the wait the + // default is used (read only) and the next Tick that has a name switches to its layout. + else if (loginAtMs != 0 && ((identityRecorded && identity is not null) || nowMs - loginAtMs >= PanelLayoutPolicy.IdentityWaitMs)) { Decided = true; Wanted = PanelLayoutPolicy.Choose(perCharacter, inWorld, identity); diff --git a/src/RynthCore.Engine/UI/PanelStateStore.cs b/src/RynthCore.Engine/UI/PanelStateStore.cs index c6ed10f..dc2f5ef 100644 --- a/src/RynthCore.Engine/UI/PanelStateStore.cs +++ b/src/RynthCore.Engine/UI/PanelStateStore.cs @@ -22,6 +22,11 @@ // PC-wide default; in the world a client uses its character's own copy, // layouts\<server>\<character>\panel_state.txt (PanelLayout switches the file // with SwitchTo). Saves are atomic: a temp file, then a replace. +// +// ReadOnlyPath (2026-11-05): with Panel Layout Per Character on, PanelLayout +// names the PC-wide default here and no save writes it (a change stays in +// memory): a client on the default is at character select or doesn't know its +// character yet, and such clients saving there overwrote each other. // ============================================================================ using System; @@ -66,6 +71,23 @@ internal static class PanelStateStore private static string FilePath => _path ?? DefaultPath; + private static volatile string? _readOnlyPath; + private static bool _readOnlyLogged; // under Sync: the skipped save is logged once per file switch + + /// <summary> + /// A file no save writes (PanelLayout: the PC-wide default while Panel Layout Per Character is + /// on); null = none. Changes made while it is in use stay in memory. Any thread. + /// </summary> + internal static string? ReadOnlyPath + { + get => _readOnlyPath; + set => _readOnlyPath = value; + } + + /// <summary>The file in use is <see cref="ReadOnlyPath"/> (under Sync).</summary> + private static bool InUseIsReadOnly => + _readOnlyPath is { } p && string.Equals(Path.GetFullPath(p), Path.GetFullPath(FilePath), StringComparison.OrdinalIgnoreCase); + /// <summary>The file in use now (the default, or the character's). Any thread.</summary> internal static string CurrentPath { @@ -92,6 +114,7 @@ internal static class PanelStateStore _barMaxPerRow = BarLayout.NoLimit; _path = path; _loaded = false; + _readOnlyLogged = false; Load(); } } @@ -316,6 +339,17 @@ internal static class PanelStateStore // file; do not overwrite it while the user is rearranging. if (!force && !EngineSettings.RememberWindowLayout) return; + // The PC-wide default with the setting on: not even Save Layout Now writes it (/rc layout + // default does, PanelLayoutFiles.MakeDefault). + if (InUseIsReadOnly) + { + if (!_readOnlyLogged) + { + _readOnlyLogged = true; + try { RynthLog.UI($"PanelStateStore: not saving {FilePath} - with Panel Layout Per Character on, the PC-wide default is only read (at character select, or until this client knows its character); changes stay in memory."); } catch { } + } + return; + } try { diff --git a/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs b/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs index fae56c5..d3f7d86 100644 --- a/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs @@ -82,8 +82,18 @@ internal static class ItemsPanel // Melee, Missile, "War Magic", "Void Magic", Shield, Ammo, or "" (not known). Set by RynthAi for // display (the Items face groups by it); sent back untouched and ignored there. [JsonPropertyName("kind")] public string Kind { get; set; } = string.Empty; + // True = "No buff" (RynthAi ItemRule.KeepBuffed off), sent for every entry by RynthAi and + // applied back by it for shield entries only. Null = the plugin predates it: no toggle is + // drawn, and none is written back (RynthAi keeps its saved value). + [JsonPropertyName("noBuff")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? NoBuff { get; set; } public bool IsShield => string.Equals(Action, ItemsCommands.ShieldAction, StringComparison.OrdinalIgnoreCase); + + /// <summary>The faces draw their "No buff" toggle: a shield entry (Action "Shield", the only + /// kind RynthAi applies it to) from a plugin that sends the field.</summary> + [JsonIgnore] public bool ShowsNoBuff => IsShield && NoBuff.HasValue; } internal sealed class ConsumableEntry @@ -874,7 +884,8 @@ internal static class ItemsPanel if (a.Count != b.Count) return true; for (int i = 0; i < a.Count; i++) if (a[i].Id != b[i].Id || a[i].Name != b[i].Name || a[i].Element != b[i].Element - || !string.Equals(a[i].Action, b[i].Action, StringComparison.OrdinalIgnoreCase)) return true; + || !string.Equals(a[i].Action, b[i].Action, StringComparison.OrdinalIgnoreCase) + || a[i].NoBuff != b[i].NoBuff) return true; // so this panel never saves back a stale noBuff return false; } diff --git a/src/RynthCore.Engine/UI/Panels/RadarSettingsStore.cs b/src/RynthCore.Engine/UI/Panels/RadarSettingsStore.cs index 1cbc415..db3cddb 100644 --- a/src/RynthCore.Engine/UI/Panels/RadarSettingsStore.cs +++ b/src/RynthCore.Engine/UI/Panels/RadarSettingsStore.cs @@ -64,6 +64,12 @@ internal static class RadarSettingsStore /// <summary>How strongly that picture shows (the radar's own Opacity applies on top).</summary> public static float WorldMapOpacity = 0.8f; + /// <summary>ImGui face: a ring round you at RynthAi's Monster Range, the distance the bot attacks + /// from (2026-11-06). On by default; nothing is drawn until RynthAi has sent its settings.</summary> + public static bool ShowMonsterRangeRing = true; + /// <summary>...and one at its Ring Range (ring spells). Off by default.</summary> + public static bool ShowRingRangeRing; + // Text sizes of the compass letters and the coordinate strip (px at 100% UI scale). public const float DefaultCompassSize = 14f, DefaultCoordSize = 11f, MinText = 8f, MaxText = 28f; public static float CompassSize = DefaultCompassSize; @@ -226,6 +232,8 @@ internal static class RadarSettingsStore SelectedColor = sc; break; case "worldMap": ShowWorldMap = val == "1"; break; + case "monsterRangeRing": ShowMonsterRangeRing = val == "1"; break; + case "ringRangeRing": ShowRingRangeRing = val == "1"; break; case "worldMapOpacity": if (float.TryParse(val, NumberStyles.Float, CultureInfo.InvariantCulture, out float wo) && float.IsFinite(wo)) WorldMapOpacity = Math.Clamp(wo, 0.1f, 1.0f); @@ -295,6 +303,8 @@ internal static class RadarSettingsStore sw.WriteLine(FormattableString.Invariant($"selectedColor={SelectedColor:X8}")); sw.WriteLine($"worldMap={(ShowWorldMap ? "1" : "0")}"); sw.WriteLine(FormattableString.Invariant($"worldMapOpacity={WorldMapOpacity:0.##}")); + sw.WriteLine($"monsterRangeRing={(ShowMonsterRangeRing ? "1" : "0")}"); + sw.WriteLine($"ringRangeRing={(ShowRingRangeRing ? "1" : "0")}"); sw.WriteLine(FormattableString.Invariant($"compassSize={CompassSize:0.##}")); sw.WriteLine(FormattableString.Invariant($"coordSize={CoordSize:0.##}")); var styleLines = new System.Collections.Generic.List<string>(); diff --git a/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs b/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs index a3a03d9..b81e236 100644 --- a/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs +++ b/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs @@ -203,6 +203,8 @@ internal static class AcIconDecoder public const int MaxSide = 128; /// <summary>The largest side a retail UI picture (a window background, a title bar) may have.</summary> public const int MaxUiSide = 512; + /// <summary>The widest retail font glyph sheet (Palatino_Linotype_24's is 2048 x 279).</summary> + public const int MaxFontSheetSide = 2048; private const int MaxTextureFile = 1024 * 1024; private const int MaxPaletteFile = 256 * 1024; @@ -383,6 +385,43 @@ internal static class AcIconDecoder } } + /// <summary> + /// A retail font's glyph sheet (the Font file's foreground or background surface: an A8 texture, + /// one coverage byte a pixel, sides up to <see cref="MaxFontSheetSide"/>) as RGBA white with the + /// coverage as alpha, so a tint colours the glyphs. Null for anything else (2026-11-07). + /// </summary> + public static AcIconImage? DecodeFontSheet(AcDatFile dat, uint textureId) + { + if (!IsTextureId(textureId)) return null; + try + { + byte[]? data = dat.Read(textureId, MaxTextureFile); + return data == null ? null : DecodeFontSheetFile(data); + } + catch + { + return null; + } + } + + /// <summary>The pure half of <see cref="DecodeFontSheet"/>: a Texture file's bytes.</summary> + internal static AcIconImage? DecodeFontSheetFile(byte[] data) + { + if (data.Length < 24) return null; + var file = new ReadOnlySpan<byte>(data); + int w = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(8)); + int h = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(12)); + uint format = BinaryPrimitives.ReadUInt32LittleEndian(file.Slice(16)); + int length = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(20)); + if (format != FmtA8 || w <= 0 || h <= 0 || w > MaxFontSheetSide || h > MaxFontSheetSide) return null; + int n = w * h; + if (length < n || 24L + length > data.Length) return null; + var src = file.Slice(24, n); + var px = new byte[n * 4]; + for (int i = 0; i < n; i++) Set(px, i, 255, 255, 255, src[i]); + return new AcIconImage { Width = w, Height = h, Pixels = px }; + } + private const uint FmtR8G8B8 = 0x14, FmtA8R8G8B8 = 0x15, FmtR5G6B5 = 0x17, FmtA4R4G4B4 = 0x1A, FmtA8 = 0x1C, FmtP8 = 0x29, FmtIndex16 = 0x65, FmtLscapeR8G8B8 = 0xF3, FmtLscapeAlpha = 0xF4, FmtDxt1 = 0x31545844, FmtDxt3 = 0x33545844, FmtDxt5 = 0x35545844; diff --git a/src/RynthCore.Engine/UI/Sections/PluginWindows.cs b/src/RynthCore.Engine/UI/Sections/PluginWindows.cs index fbcd86c..651c82c 100644 --- a/src/RynthCore.Engine/UI/Sections/PluginWindows.cs +++ b/src/RynthCore.Engine/UI/Sections/PluginWindows.cs @@ -19,7 +19,12 @@ // the plugin shipping first and the engine face deleted a release later. // A window seen for the first time this session opens if it was open when the // game last closed (Remember Open Windows); one that went with a plugin reload -// opens again when the plugin comes back. +// opens again when the plugin comes back. Both read the panel layout in use +// when the window registers; when the layout changes later (UI/PanelLayout: a +// hot reload that registered windows before the character's layout was in, +// a character name that came late, a relogin) ImGuiPanelHost's layout switch +// opens, closes and places the hosted windows from the new layout, like the +// engine's panels (2026-11-05). // // WindowPlan.cs is the pure part (which windows, which are refused and why, // which take over an engine panel). @@ -152,7 +157,9 @@ internal static class PluginWindows // 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) + Background: 0, Rounding: 0f, EdgeToEdge: true, GripOnHover: true, OpenCorner: Corner(w.Corner), DrawScale: w.DrawScale, + // A frameless window that sizes itself (fitHeight) needs no grip of the host's: its own edges resize it. + NoResize: w.FitHeight && w.UnderUi, UnderUi: w.UnderUi) : 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); diff --git a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs index 9ecf103..20b8c27 100644 --- a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs +++ b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs @@ -118,7 +118,10 @@ internal sealed record SectionWindowDecl( // 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) + bool DrawScale = false, + // 2026-11-07 (no version bump: older engines ignore the key): drawn under AC's own UI, like a native + // AC window ("layer": "underUi"; frameless windows only). AC's windows cover it and take the clicks there. + bool UnderUi = false) { /// <summary>For every world, not one server.</summary> public bool IsUniversal => Server.Length == 0; @@ -240,7 +243,8 @@ internal static class SectionManifestParser 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))); + DrawScale: Str(e, "scale").Trim().Equals("draw", StringComparison.OrdinalIgnoreCase), + UnderUi: Str(e, "layer").Trim().Equals("underUi", StringComparison.OrdinalIgnoreCase))); } return new SectionManifest(plugin, servers.ToArray(), sections.ToArray(), contributions.ToArray()) diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 71a3869..7a81114 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -202,6 +202,8 @@ public struct RynthCoreApiNative // v91: a floor under the world's ambient light (drawing only, this client) public IntPtr SetAmbientLightFloorFn; // int SetAmbientLightFloor(uint rgb) -> 1 hook live, 0 not; 0x00RRGGBB, 0 = none public IntPtr GetAmbientLightFn; // int GetAmbientLight(uint* client, uint* applied) -> 1 hook live, 0 not + // v93: the monster plates' last server health reading per object + public IntPtr GetMonsterHealthFn; // int GetMonsterHealth(uint id, float* ratio, uint* ageMs) -> 1 reading, 0 none } /// <summary> diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 9b23c06..00fc926 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -1848,6 +1848,35 @@ public readonly unsafe struct RynthCoreHost return r == 1; } + /// <summary> + /// v93: <see cref="TryGetMonsterHealth"/> (the monster plates' last server health reading per object). + /// </summary> + public bool HasMonsterHealth => _api.Version >= 93 && _api.GetMonsterHealthFn != IntPtr.Zero; + + /// <summary> + /// v93: the last health ratio (0..1) the server sent for <paramref name="id"/>, as the engine's monster + /// plates keep it, and how many ms ago (<paramref name="ageMs"/>). The plates ask the server for the + /// monsters around the player round-robin (about one a second; ones in a fight every 2 s, quiet ones + /// every 12 s), so this covers monsters whose health the server streams to nobody else here. Those + /// probe replies never arrive as UpdateHealth events (a plugin must not count someone else's hit as + /// its own): use this for ranking, not for kill or damage tracking. Never the plates' estimates from + /// the player's hits. False when the server never sent this object's health, or on an older engine. + /// Read-only, any thread. + /// </summary> + public bool TryGetMonsterHealth(uint id, out float ratio, out uint ageMs) + { + ratio = -1f; + ageMs = uint.MaxValue; + if (!HasMonsterHealth || id == 0) return false; + float r = -1f; + uint age = uint.MaxValue; + int ok = ((delegate* unmanaged[Cdecl]<uint, float*, uint*, int>)_api.GetMonsterHealthFn)(id, &r, &age); + if (ok != 1 || float.IsNaN(r) || r < 0f) return false; + ratio = Math.Min(r, 1f); + ageMs = age; + return true; + } + private int CallSetActionKey(string action, string key, int op, out string message) { message = string.Empty; diff --git a/src/RynthCore.PluginSdk/UiKitTypes.cs b/src/RynthCore.PluginSdk/UiKitTypes.cs index 7821ed1..64d1308 100644 --- a/src/RynthCore.PluginSdk/UiKitTypes.cs +++ b/src/RynthCore.PluginSdk/UiKitTypes.cs @@ -75,6 +75,18 @@ public enum RynthIconKind Object = 1, /// <summary>A spell id: the spell's icon.</summary> Spell = 2, + /// <summary> + /// A retail UI picture (any 0x06 texture up to 512 x 512: window backgrounds, banners, frame + /// pieces), at its own size. Engines from 2026-11-07; older ones answer IntPtr.Zero for it, so + /// draw a stand-in while it stays zero. + /// </summary> + UiSprite = 3, + /// <summary> + /// A retail font's glyph sheet (the Font file's foreground or background surface, an A8 0x06 + /// texture up to 2048 wide) as white with the sheet's level as alpha: draw glyphs from it with a + /// tint, from the Font file's glyph table. Engines from 2026-11-07; older ones answer IntPtr.Zero. + /// </summary> + FontSheet = 4, } /// <summary>Where RynthCoreHost.PollKeyCapture is (v90).</summary> diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index 952ac84..ecae5c1 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -36,7 +36,7 @@ <PropertyGroup> <!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. --> - <RynthCoreSdkApiVersion>92</RynthCoreSdkApiVersion> + <RynthCoreSdkApiVersion>93</RynthCoreSdkApiVersion> <!-- The first engine API that loads managed plugins and gives them Runtime\PluginShared (2026.10.19.1). --> <RynthCoreManagedPluginApi>88</RynthCoreManagedPluginApi> <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn> diff --git a/tools/ChatCommandReplyTests/Program.cs b/tools/ChatCommandReplyTests/Program.cs index 15b736d..d2efaca 100644 --- a/tools/ChatCommandReplyTests/Program.cs +++ b/tools/ChatCommandReplyTests/Program.cs @@ -94,6 +94,8 @@ internal static class Program ("panels", "panels open 0x1F", "panels open"), ("panels", "panels toggle 12", "panels open twelve"), ("panels", "panels", "panels open 1 2"), + ("title", "title 42", "title banana"), + ("title", "title 7", "title"), ("rl", "rl", "rl now"), ("rl", "reload", "reload now"), ("inventory", "inv", "inv now"), diff --git a/tools/ChatFilterTests/ChatFilterTests.csproj b/tools/ChatFilterTests/ChatFilterTests.csproj index e8952a4..e870212 100644 --- a/tools/ChatFilterTests/ChatFilterTests.csproj +++ b/tools/ChatFilterTests/ChatFilterTests.csproj @@ -34,6 +34,8 @@ <Compile Include="..\..\src\RynthCore.Engine\UI\Panels\RynthChatPresets.cs" Link="Engine\RynthChatPresets.cs" /> <!-- 2026-10-19: re-reading the shared rynthchat_settings.json when another client saved it. --> <Compile Include="..\..\src\RynthCore.Engine\UI\Data\SharedFileWatch.cs" Link="Engine\SharedFileWatch.cs" /> + <!-- 2026-11-05: a plugin's own colour for a line it writes (RynthAi's Info text colour). --> + <Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatOwnColors.cs" Link="Engine\ChatOwnColors.cs" /> </ItemGroup> </Project> diff --git a/tools/ChatFilterTests/EngineStubs.cs b/tools/ChatFilterTests/EngineStubs.cs index 779ed30..64017f2 100644 --- a/tools/ChatFilterTests/EngineStubs.cs +++ b/tools/ChatFilterTests/EngineStubs.cs @@ -7,6 +7,8 @@ namespace RynthCore.Engine.Compatibility { public static int Lines; public static void UI(string message) { Lines++; } + public static readonly System.Collections.Generic.List<string> InfoLines = new(); + public static void Info(string message) { Lines++; InfoLines.Add(message); } } } diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 3f9392a..9b0f084 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -65,6 +65,10 @@ internal static class Program HighlightBand(); HighlightJson(); HighlightOldReader(); + OwnColorPrecedence(); + OwnColorQueue(); + OwnColorCommand(); + SlowRulesNeedStrikes(); Console.WriteLine(); Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); @@ -86,6 +90,47 @@ internal static class Program Console.WriteLine($" FAIL [{_case}] {what}"); } + // The owner, 2026-11-07: "chat filter too slow and getting skipped all the time", with eight + // plain-text rules. The clock timed them, so a busy PC (several game clients) made any rule + // "too slow". Now rules that can run non-backtracking (linear time) have no timeout and are + // never skipped; the rest need SlowStrikesToSkip slow readings within the window. + private static void SlowRulesNeedStrikes() + { + Case("plain text and simple regex rules run linear and are never too slow; others need 3 strikes"); + foreach (var (mode, pattern) in new[] { (ChatMatchMode.Regex, "In portal Space"), (ChatMatchMode.Regex, "You've earned"), + (ChatMatchMode.Contains, "Keep (really)"), (ChatMatchMode.Regex, "^You (evade|evaded) .*!$") }) + { + var r = new ChatFilterRule { Pattern = pattern, Mode = mode }; + r.Recompile(); + Check(r.Compiled != null && r.Linear, $"'{pattern}' ({mode}) compiles linear"); + Check(r.Compiled?.MatchTimeout == Regex.InfiniteMatchTimeout, $"'{pattern}': no match timeout to trip"); + } + var plain = new ChatFilterRule { Pattern = "In portal Space", Tab = "Junk" }; + plain.Recompile(); + var router = new ChatRouter(new[] { plain }, null, "", countHits: false); + Check(router.Evaluate("In portal Space", "Chat", 0, null).InHome == false, "the linear rule still routes the line"); + + // A backreference needs backtracking: the timed compile, exactly as before. + var back = new ChatFilterRule { Pattern = @"^(\w)(a+)+\1$", Action = ChatRuleAction.Hide }; + back.Recompile(); + Check(back.Compiled != null && !back.Linear, "a backreference compiles with backtracking"); + Check(back.Compiled?.MatchTimeout == TimeSpan.FromMilliseconds(ChatFilterRule.TimeoutMs), "...with the 15 ms timeout"); + + string evil = "b" + new string('a', 40) + "!"; // (a+)+ backtracks exponentially before failing + var r2 = new ChatRouter(new[] { back }, null, "", countHits: false); + int bumps = ChatModel.FilterBumps; + r2.Evaluate(evil, "Chat", 0, null); + Check(!back.Slow, "one timeout: a strike, still used"); + r2.Evaluate(evil, "Chat", 0, null); + Check(!back.Slow, "two: still used"); + Check(RynthCore.Engine.Compatibility.RynthLog.InfoLines.Any(l => l.Contains("2 of 3 before it is skipped")), "each strike is logged"); + r2.Evaluate(evil, "Chat", 0, null); + Check(back.Slow, "three within the window: skipped until edited"); + Check(ChatModel.FilterBumps == bumps + 1, "the kept lines are re-routed once, when it is skipped"); + back.Recompile(); + Check(!back.Slow && back.SlowStrikes == 0, "an edit (recompile) clears it and its strikes"); + } + /// <summary>What a rule compiled to before match modes (ChatFilterRule.Recompile, 2026-09-29).</summary> private static Regex? Before(string pattern, out string? error) { @@ -435,6 +480,95 @@ internal static class Program Check(!ChatLineColors.AnySet && ChatLineColors.Resolve(null, "fellowship", "Chat") == OldChannelArgb("Chat"), "reset all: as before"); } + // 2026-11-05: a plugin's own colour for a line (RynthAi's Info text colour, ChatOwnColors.cs): + // the line keeps its chat type and tab; only its colour changes. + private const string ItemLine = "[RynthAi Item] Blunt Crossbow (Pierce Crossbow), Gold, Craft 6"; + private const uint Orange = 0xFFEE921E; + + private static void OwnColorPrecedence() + { + Case("own colour: below a rule's, above kind, tab, retail and built-in"); + ChatLineColors.ResetAll(); + bool retail = ChatLineColors.RetailColors; + ChatLineColors.RetailColors = true; + const uint Rule = 0xFFABCDEF, Mine = 0xFF102030; + Check(ChatLineColors.ResolveLine(null, null, null, "Items", 0x12) == OldChannelArgb("Items"), "none: an Items line keeps its teal (as before)"); + Check(ChatLineColors.ResolveLine(null, null, "tell", "Chat", 0x03) == ChatLineColors.Resolve(null, "tell", "Chat", 0x03), "none: exactly Resolve"); + Check(ChatLineColors.ResolveLine(null, Orange, null, "Items", 0x01) == Orange, "own colour beats the Items tab's built-in"); + Check(ChatLineColors.ResolveLine(null, Orange, null, "System", 0x05) == Orange, "and AC's own colour for the type"); + ChatLineColors.Set("tab:Items", Mine); + ChatLineColors.Set("allegiance", Mine); + Check(ChatLineColors.ResolveLine(null, Orange, null, "Items", 0x01) == Orange, "and a tab colour the user set"); + Check(ChatLineColors.ResolveLine(null, Orange, "allegiance", "Chat", 0x12) == Orange, "and a kind colour the user set"); + Check(ChatLineColors.ResolveLine(Rule, Orange, null, "Items", 0x01) == Rule, "a rule's line colour still wins"); + ChatLineColors.ResetAll(); + ChatLineColors.RetailColors = retail; + } + + private static void OwnColorQueue() + { + Case("own colour: matched by text and type, once, oldest first; refused and stale lines forgotten"); + var q = new ChatOwnColorQueue(); + Check(q.Take(ItemLine, 0x12, 0) == null, "nothing waiting: null"); + q.Expect(ItemLine + "\r\n", 0x12, 0x00EE921E, 1000); + Check(q.Count == 1, "one waiting"); + Check(q.Take(ItemLine, 0x01, 1100) == null, "another chat type: not it"); + Check(q.Take(ItemLine + " more", 0x12, 1100) == null, "other text: not it"); + Check(q.Take(ItemLine, 0x12, 1100) == Orange, "CR/LF trimmed like WriteToChat; made opaque"); + Check(q.Take(ItemLine, 0x12, 1200) == null, "used up: the same text again is drawn as usual"); + + q.Expect(ItemLine, 0x12, 0xFF111111, 2000); + q.Expect(ItemLine, 0x12, 0xFF222222, 2001); + Check(q.Take(ItemLine, 0x12, 2100) == 0xFF111111 && q.Take(ItemLine, 0x12, 2100) == 0xFF222222, "two of the same line: in order"); + + q.Expect(ItemLine, 0x12, Orange, 3000); + q.Forget(ItemLine, 0x12); + Check(q.Count == 0 && q.Take(ItemLine, 0x12, 3100) == null, "a line WriteToChat refused colours nothing"); + + q.Expect(ItemLine, 0x12, Orange, 4000); + Check(q.Take(ItemLine, -1, 4100) == Orange, "a RynthChat without chat types (-1) matches by text"); + + q.Expect(ItemLine, 0x12, Orange, 5000); + Check(q.Take(ItemLine, 0x12, 5000 + ChatOwnColorQueue.LineTtlMs + 1) == null && q.Count == 0, "a line nobody picked up in time is forgotten"); + + for (int i = 0; i < ChatOwnColorQueue.MaxLines + 10; i++) q.Expect("line " + i, 0x01, Orange, 6000); + Check(q.Count == ChatOwnColorQueue.MaxLines, $"at most {ChatOwnColorQueue.MaxLines} wait"); + Check(q.Take("line 0", 0x01, 6001) == null && q.Take("line 10", 0x01, 6001) == Orange, "the oldest went first"); + + var q2 = new ChatOwnColorQueue(); + string longLine = new string('x', 1500); + q2.Expect(longLine, 0x01, Orange, 0); + Check(q2.Take(longLine[..ChatOwnColorQueue.MaxArrivingChars], 0x01, 1) == Orange, "a line AC cut at 1,024 characters matches by its start"); + q2.Expect(ItemLine, 0x01, Orange, 0); + Check(q2.Take(ItemLine[..20], 0x01, 1) == null, "a short line never matches by its start"); + var q3 = new ChatOwnColorQueue(); + q3.Expect("\r\n", 0x01, Orange, 0); + q3.Expect("", 0x01, Orange, 0); + Check(q3.Count == 0, "an empty line is never noted"); + } + + private static void OwnColorCommand() + { + Case("own colour: SendPluginCommand(\"RynthCore.Chat\", \"nextcolor\", ...) arms the next WriteToChat"); + Check(ChatOwnColors.CommandTarget == "RynthCore.Chat" && ChatOwnColors.NextColorAction == "nextcolor", "the names RynthAi sends"); + Check(ChatOwnColors.TakeArmed(0) == null, "nothing armed: null"); + Check(ChatOwnColors.HandlePluginCommand("nextcolor", "#EE921E", 100), "understood"); + Check(ChatOwnColors.TakeArmed(150) == Orange, "the next WriteToChat takes it"); + Check(ChatOwnColors.TakeArmed(160) == null, "only the next one"); + Check(ChatOwnColors.HandlePluginCommand("NEXTCOLOR", " ee921e ", 200) && ChatOwnColors.TakeArmed(200) == Orange, "any case, no #, spaces"); + Check(ChatOwnColors.HandlePluginCommand("nextcolor", "#EE921E", 300) && ChatOwnColors.TakeArmed(300 + ChatOwnColors.ArmWindowMs + 1) == null, + "armed too long ago: dropped"); + Check(ChatOwnColors.HandlePluginCommand("nextcolor", "#EE921E", 400) && ChatOwnColors.HandlePluginCommand("nextcolor", "none", 401) + && ChatOwnColors.TakeArmed(402) == null, "\"none\" disarms"); + Check(!ChatOwnColors.HandlePluginCommand("nextcolor", "orange", 500) && ChatOwnColors.TakeArmed(500) == null, "a bad colour: refused, nothing armed"); + Check(!ChatOwnColors.HandlePluginCommand("colour", "#EE921E", 600), "an unknown action: refused"); + ChatOwnColors.HandlePluginCommand("nextcolor", "#EE921E", 700); + uint? other = null; + var t = new Thread(() => other = ChatOwnColors.TakeArmed(700)); + t.Start(); t.Join(); + Check(other == null && ChatOwnColors.TakeArmed(700) == Orange, "armed per thread: another plugin thread's line isn't coloured"); + } + private static void LineColorJson() { Case("line colours: lineColors in rynthchat_settings.json"); diff --git a/tools/ChatHistoryBench/Stubs.cs b/tools/ChatHistoryBench/Stubs.cs index 85f7c4c..52391ec 100644 --- a/tools/ChatHistoryBench/Stubs.cs +++ b/tools/ChatHistoryBench/Stubs.cs @@ -8,6 +8,7 @@ namespace RynthCore.Engine.Compatibility { public static int Lines; public static void UI(string message) { Lines++; } + public static void Info(string message) { Lines++; } } } diff --git a/tools/CleaveGhostTests/CleaveGhostTests.csproj b/tools/CleaveGhostTests/CleaveGhostTests.csproj index 8306b03..b955501 100644 --- a/tools/CleaveGhostTests/CleaveGhostTests.csproj +++ b/tools/CleaveGhostTests/CleaveGhostTests.csproj @@ -11,6 +11,9 @@ Also (2026-10-31) src\RynthCore.Engine\ImGui\MonsterHud\HealthProbe.cs: which unselected plate the HUD asks the server's health for next (the server streams only the queried target), and which 0x01C0 replies are the probe's (kept from plugins) versus the selection's / a plugin's. + And (2026-11-07) src\RynthCore.Engine\ImGui\MonsterHud\MonsterHudData.cs: the server reading plugin API v93 + GetMonsterHealth hands out (probe replies included, estimates never) and its age, read from other threads; + HudFeedStub.cs stands in for the combat text's feed. All compiled in; no game, no engine. Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> @@ -26,6 +29,7 @@ <ItemGroup> <Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\CleaveHealth.cs" Link="Engine\CleaveHealth.cs" /> <Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\HealthProbe.cs" Link="Engine\HealthProbe.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\MonsterHudData.cs" Link="Engine\MonsterHudData.cs" /> <Compile Include="..\..\src\RynthCore.Engine\Compatibility\ObjectFreshness.cs" Link="Engine\ObjectFreshness.cs" /> </ItemGroup> diff --git a/tools/CleaveGhostTests/HudFeedStub.cs b/tools/CleaveGhostTests/HudFeedStub.cs new file mode 100644 index 0000000..a2c50ac --- /dev/null +++ b/tools/CleaveGhostTests/HudFeedStub.cs @@ -0,0 +1,10 @@ +// A stand-in for src\RynthCore.Engine\ImGui\MonsterHud\HudFeed.cs, the combat text's feed, so +// MonsterHudData.cs compiles here without the ImGui HUD. It only counts what it is told. +namespace RynthCore.Engine.ImGuiBackend.Hud; + +internal static class HudFeed +{ + public static int HealthCalls; + + public static void OnHealth(uint id, float prev, float ratio, uint max) => HealthCalls++; +} diff --git a/tools/CleaveGhostTests/Program.cs b/tools/CleaveGhostTests/Program.cs index 9720271..b76cef9 100644 --- a/tools/CleaveGhostTests/Program.cs +++ b/tools/CleaveGhostTests/Program.cs @@ -20,6 +20,9 @@ internal static class Program Run("health probe: the stalest fight plate first, never-read plates nearest first", ProbeStalestAndNearest); Run("health probe: nothing due (fresh, dead, no id) sends nothing", ProbeNothingDue); Run("health probe: a probe's replies are the HUD's; the owner's and plugins' are theirs", ProbeReplies); + Run("plugin reading (v93): the server's last ratio and its age; never an estimate", PluginReadingServerOnly); + Run("plugin reading (v93): a probe reply is recorded for plugins to read, while it still isn't theirs as an event", PluginReadingProbeReply); + Run("plugin reading (v93): safe to read from another thread while the game thread records", PluginReadingThreads); Console.WriteLine($"{_checks} check(s), {_failed} failed."); return _failed == 0 ? 0 : 1; } @@ -209,4 +212,93 @@ internal static class Program HealthProbe.Reset(); Check(!HealthProbe.IsProbeReply(0x114, 5100) && !HealthProbe.TryGetOwner(out _), "reset (logout) forgets everything"); } + + // ── Plugin API v93 GetMonsterHealth (MonsterHudData.TryGetServerHealth) ── + + private static long Ms(double ms) => (long)(ms * System.Diagnostics.Stopwatch.Frequency / 1000.0); + + private static void PluginReadingServerOnly() + { + MonsterHudData.Clear(); + long t0 = System.Diagnostics.Stopwatch.GetTimestamp(); + Check(!MonsterHudData.TryGetServerHealth(0x40, t0, out float r, out uint age) && r == -1f && age == uint.MaxValue, + "never read: false, -1, max age"); + Check(!MonsterHudData.TryGetServerHealth(0, t0, out _, out _), "id 0: false"); + + MonsterHudData.RecordHealth(0x40, 0.6f, 0, 0); + long recorded = System.Diagnostics.Stopwatch.GetTimestamp(); + Check(MonsterHudData.TryGetServerHealth(0x40, recorded + Ms(2500), out r, out age) && Near(r, 0.6f), + $"the server's 60% (got {r:0.000})"); + Check(age >= 2500 && age < 2600, $"2.5 s old (got {age} ms)"); + + // The plates' estimate from the player's own hit shows on the plate, not in the plugin reading. + MonsterHudData.RecordHealth(0x40, 0.3f, 0, 0, estimated: true); + Check(MonsterHudData.TryGetHealth(0x40, out HealthObservation h) && Near(h.Ratio, 0.3f) && h.Estimated, "the plate shows the estimate"); + Check(MonsterHudData.TryGetServerHealth(0x40, recorded + Ms(3000), out r, out age) && Near(r, 0.6f) && age >= 3000, + $"the reading stays the server's 60% and keeps its age (got {r:0.000}, {age} ms)"); + + // An estimate on a plate the server never read: nothing for plugins. + MonsterHudData.RecordHealth(0x41, 0.8f, 0, 0, estimated: true); + Check(!MonsterHudData.TryGetServerHealth(0x41, recorded, out _, out _), "estimate only: false"); + + // The next server reading replaces it. + MonsterHudData.RecordHealth(0x41, 0.45f, 450, 1000); + Check(MonsterHudData.TryGetServerHealth(0x41, System.Diagnostics.Stopwatch.GetTimestamp(), out r, out age) && Near(r, 0.45f) && age < 100, + $"server 45%, fresh (got {r:0.000}, {age} ms)"); + + // A dead monster reads 0 (the plugin decides what that means for it). + MonsterHudData.RecordHealth(0x42, 0f, 0, 0); + Check(MonsterHudData.TryGetServerHealth(0x42, System.Diagnostics.Stopwatch.GetTimestamp(), out r, out _) && r == 0f, "dead: 0"); + + // A clock behind the reading never gives a negative or wrapped age; a very old one saturates. + Check(MonsterHudData.TryGetServerHealth(0x41, 0, out _, out age) && age == 0, $"now before the reading: 0 ms (got {age})"); + Check(MonsterHudData.TryGetServerHealth(0x41, recorded + Ms(60.0 * 24 * 3600 * 1000), out _, out age) && age == uint.MaxValue, + $"60 days: saturates (got {age})"); + + MonsterHudData.Clear(); + Check(!MonsterHudData.TryGetServerHealth(0x41, recorded, out _, out _), "logout clears it"); + } + + private static void PluginReadingProbeReply() + { + // PluginManager.QueueUpdateHealth records every 0x01C0 in MonsterHudData first, then drops a probe's + // reply from the plugins' UpdateHealth queue: the reading is there, the event is not. + MonsterHudData.Clear(); + HealthProbe.Reset(); + HealthProbe.NoteQuery(0x10); // the fight target owns the stream + HealthProbe.NoteProbe(0x20, 1000); // the plates probe a monster someone else is fighting + MonsterHudData.RecordHealth(0x20, 0.25f, 0, 0); + Check(HealthProbe.IsProbeReply(0x20, 1100), "the reply is the probe's (kept from plugins as an event)"); + Check(MonsterHudData.TryGetServerHealth(0x20, System.Diagnostics.Stopwatch.GetTimestamp(), out float r, out _) && Near(r, 0.25f), + $"... and its 25% is readable by id (got {r:0.000})"); + HealthProbe.Reset(); + MonsterHudData.Clear(); + } + + private static void PluginReadingThreads() + { + MonsterHudData.Clear(); + int bad = 0; + long reads = 0; + using var stop = new CancellationTokenSource(); + var reader = Task.Run(() => + { + while (!stop.IsCancellationRequested) + for (uint id = 1; id <= 64; id++) + { + if (MonsterHudData.TryGetServerHealth(id, out float r, out _) && (r < 0f || r > 1f || float.IsNaN(r))) + Interlocked.Increment(ref bad); + Interlocked.Increment(ref reads); + } + }); + // The game thread's side, including a full table's wholesale clear (2048 entries). + for (int round = 0; round < 40; round++) + for (uint id = 1; id <= 2100; id++) + MonsterHudData.RecordHealth(id, (id % 100) / 100f, 0, 0, estimated: (id & 3) == 0); + stop.Cancel(); + reader.Wait(); + Check(bad == 0, $"every reading in range ({bad} bad)"); + Check(Interlocked.Read(ref reads) > 0, "the reader ran"); + MonsterHudData.Clear(); + } } diff --git a/tools/DamageRowStatsTests/Program.cs b/tools/DamageRowStatsTests/Program.cs index 3b47335..21cb3d3 100644 --- a/tools/DamageRowStatsTests/Program.cs +++ b/tools/DamageRowStatsTests/Program.cs @@ -35,6 +35,9 @@ internal static class Program Missing(); Words(); Percents(); + XpPerKill(); + CorpseTime(); + ShieldTaken(); Console.WriteLine($"DamageRowStatsTests: {_checks} checks, {_failed} failed."); return _failed == 0 ? 0 : 1; } @@ -99,4 +102,113 @@ internal static class Program Eq(DamageRowStats.Percent(9, 200), "4.5%", "one decimal below 10%"); Eq(DamageRowStats.Percent(7, 3), "100%", "clamped"); } + + private static void XpPerKill() + { + // An older RynthAi sends no xp/xk: nothing new on the line or in the tip. + DamageRowStats old = Row(Full)!; + Eq((old.Xp, old.XpKills, old.XpPerKill), (0L, 0, 0L), "no xp/xk: 0"); + Check(!old.Line().Contains("XP/kill"), "no xp/xk: no XP/kill on the line"); + Check(!old.Tip().Contains("XP:"), "no xp/xk: no XP in the tip"); + + DamageRowStats s = Row("{\"mstats\":{\"sw\":61,\"ev\":14,\"k\":3,\"xp\":3703701,\"xk\":3}}")!; + Eq((s.Xp, s.XpKills, s.XpPerKill), (3703701L, 3, 1234567L), "xp and xk read"); + Eq(s.Line(), "XP/kill 1,234,567 · It evades 23% (14/61)", "XP/kill leads the line, thousands"); + Check(s.Tip().Contains("XP: 3,703,701 from 3 kills, 1,234,567 per kill."), "tip: XP " + s.Tip()); + + Eq(Row("{\"mstats\":{\"xp\":5,\"xk\":2}}")!.XpPerKill, 3L, "rounded (2.5 up)"); + Eq(Row("{\"mstats\":{\"xp\":10,\"xk\":3}}")!.XpPerKill, 3L, "rounded (3.33 down)"); + Eq(Row("{\"mstats\":{\"k\":1,\"xp\":900,\"xk\":1}}")!.Line(), "XP/kill 900", "a kill with XP alone: the line shows XP/kill"); + Check(Row("{\"mstats\":{\"k\":1,\"xp\":900,\"xk\":1}}")!.Tip().Contains("from 1 kill,"), "one kill"); + Eq(Row("{\"mstats\":{\"k\":2,\"xp\":900,\"xk\":0}}")!.Line(), "", "xk 0: no XP/kill"); + Eq(Row("{\"mstats\":{\"k\":2,\"xp\":-50,\"xk\":-1}}")!.Line(), "", "negative xp/xk read as 0"); + Check(Row("{\"mstats\":{\"xp\":0,\"xk\":0}}") == null, "xp/xk all zero: no line"); + Eq(Row("{\"mstats\":{\"xp\":50000000000,\"xk\":2}}")!.Line(), "XP/kill 25,000,000,000", "XP past an int"); + } + + private static void CorpseTime() + { + // An older RynthAi sends no cd/cn: nothing new. + DamageRowStats old = Row(Full)!; + Eq((old.CorpseMs, old.CorpseKills), (0, 0), "no cd/cn: 0"); + Check(!old.Line().Contains("Death animation"), "no cd/cn: no death animation on the line"); + Check(!old.Tip().Contains("Corpse appears"), "no cd/cn: no corpse in the tip"); + + DamageRowStats s = Row("{\"mstats\":{\"sw\":61,\"ev\":14,\"k\":3,\"xp\":3703701,\"xk\":3,\"cd\":2140,\"cn\":3}}")!; + Eq((s.CorpseMs, s.CorpseKills), (2140, 3), "cd and cn read"); + Eq(s.Line(), "XP/kill 1,234,567 · It evades 23% (14/61) · Death animation 2.1 s", "death animation last, after the rates"); + Eq(Row("{\"mstats\":{\"sw\":61,\"ev\":14,\"at\":120,\"yev\":50,\"ysp\":8,\"yrs\":1,\"k\":3,\"cd\":2140,\"cn\":3}}")!.Line(), + "It evades 23% (14/61) · You evade 42% (50/120) · You resist 13% (1/8) · Death animation 2.1 s", "far right, after You evade / You resist"); + Check(s.Tip().Contains("Corpse appears 2.1 s after the kill (over 3 kills)."), "tip: corpse " + s.Tip()); + Eq(Row("{\"mstats\":{\"k\":1,\"cd\":2140,\"cn\":1}}")!.Line(), "Death animation 2.1 s", "death animation alone (no XP sent)"); + Check(Row("{\"mstats\":{\"k\":1,\"cd\":900,\"cn\":1}}")!.Tip().Contains("(over 1 kill)."), "one kill"); + Check(Row("{\"mstats\":{\"cd\":1500,\"cn\":2}}") != null, "a timed corpse alone is something"); + + // Rounding to one decimal. + Eq(Row("{\"mstats\":{\"cd\":2150,\"cn\":1}}")!.CorpseSeconds, "2.2", "2.15 s rounds up"); + Eq(Row("{\"mstats\":{\"cd\":2149,\"cn\":1}}")!.CorpseSeconds, "2.1", "2.149 s rounds down"); + Eq(Row("{\"mstats\":{\"cd\":3000,\"cn\":1}}")!.CorpseSeconds, "3.0", "whole seconds keep the decimal"); + Eq(Row("{\"mstats\":{\"cd\":40,\"cn\":1}}")!.CorpseSeconds, "0.0", "under 50 ms"); + Eq(Row("{\"mstats\":{\"cd\":12345,\"cn\":1}}")!.Line(), "Death animation 12.3 s", "over ten seconds"); + + // Bad values. + Eq(Row("{\"mstats\":{\"k\":2,\"cd\":2000,\"cn\":0}}")!.Line(), "", "cn 0: no corpse"); + Eq(Row("{\"mstats\":{\"k\":2,\"cd\":2000}}")!.Line(), "", "cd without cn: no corpse"); + Eq(Row("{\"mstats\":{\"k\":2,\"cd\":2000,\"cn\":-4}}")!.Line(), "", "negative cn read as 0"); + Eq(Row("{\"mstats\":{\"cd\":-500,\"cn\":2}}")!.Line(), "Death animation 0.0 s", "negative cd read as 0"); + Eq(Row("{\"mstats\":{\"cd\":\"2000\",\"cn\":2}}")!.Line(), "Death animation 0.0 s", "text cd read as 0"); + Eq(Row("{\"mstats\":{\"k\":1,\"cd\":2000,\"cn\":1.5}}")!.Line(), "", "fractional cn read as 0"); + Check(Row("{\"mstats\":{\"cd\":0,\"cn\":0}}") == null, "cd/cn all zero: no line"); + } + + // RynthAi 2026-11-08: the hits it landed by shield and facing (learned across logins). + private const string Split = + "{\"mstats\":{\"hsf\":19,\"dsf\":209,\"msf\":11,\"hsb\":1,\"dsb\":274,\"msb\":274,\"hnf\":54,\"dnf\":2916,\"mnf\":80}}"; + + private static void ShieldTaken() + { + // An older RynthAi sends no cells: nothing new. + DamageRowStats old = Row(Full)!; + Check(!old.HasShieldTaken, "no cells: none"); + Check(!old.Line().Contains("Hits taken"), "no cells: nothing on the line"); + Check(!old.Tip().Contains("Shield up"), "no cells: nothing in the tip"); + + // Cells alone (nothing since login): a row of its own, the session's numbers left out. + DamageRowStats? s = Row(Split); + Check(s != null, "the cells alone are something"); + if (s == null) return; + Check(!s.HasSession, "no session numbers"); + Eq((s.ShieldCells[0].Hits, s.ShieldCells[0].Total, s.ShieldCells[0].Max), (19, 209L, 11L), "shield front read"); + Eq(s.ShieldCells[1].Hits, 1, "shield behind read"); + Eq(s.ShieldCells[2].Hits, 0, "a missing cell is 0"); + Eq((s.ShieldHits(true), s.ShieldHits(false)), (20, 54), "hits each way"); + Eq(Math.Round(s.ShieldAvg(true), 2), 24.15, "shield mean over every facing ((209 + 274) / 20)"); + Eq(s.Line(), "Hits taken: shield 24 avg (front 95%), no shield 54 avg", "the line"); + string tip = s.Tip(); + Check(!tip.Contains("Since you logged in"), "no session block: " + tip); + Check(tip.Contains("Shield up: 20 hits, avg 24 - front 19 hits, avg 11, max 11; behind 1 hit, avg 274, max 274; facing unknown -."), + "tip: shield cells: " + tip); + Check(tip.Contains("No shield: 54 hits, avg 54 - front 54 hits, avg 54, max 80; behind -; facing unknown -."), "tip: no shield cells"); + Check(tip.Contains("within 90 degrees of your facing"), "tip: ACE's rule"); + + // With the session's numbers: the cells after XP/kill, the death animation last. + DamageRowStats both = Row("{\"mstats\":{\"sw\":61,\"ev\":14,\"k\":3,\"xp\":3703701,\"xk\":3,\"cd\":2140,\"cn\":3," + + "\"hsf\":2,\"dsf\":20,\"msf\":12,\"hnb\":1,\"dnb\":60,\"mnb\":60}}")!; + Eq(both.Line(), "XP/kill 1,234,567 · Hits taken: shield 10 avg (front 100%), no shield 60 avg · It evades 23% (14/61) · Death animation 2.1 s", + "after XP/kill, before the rates; death animation last"); + Check(both.Tip().StartsWith("Since you logged in") && both.Tip().Contains("\n\nDamage it did to you, learned across logins:"), + "tip: the session first, then the cells"); + + // One side only, and facing never measured. + Eq(Row("{\"mstats\":{\"hnf\":3,\"dnf\":150,\"mnf\":60}}")!.Line(), "Hits taken: no shield 50 avg", "no shield only"); + Eq(Row("{\"mstats\":{\"hsu\":4,\"dsu\":40,\"msu\":12}}")!.Line(), "Hits taken: shield 10 avg (facing unknown)", "facing never measured"); + Eq(Row("{\"mstats\":{\"hsf\":1,\"dsf\":5,\"hsu\":3,\"dsu\":15}}")!.Line(), "Hits taken: shield 5 avg (front 100%)", + "front share over the measured ones only"); + + // Bad values. + Check(Row("{\"mstats\":{\"hsf\":0,\"dsf\":50}}") == null, "damage without hits: nothing"); + Check(Row("{\"mstats\":{\"hsf\":-3,\"dsf\":50}}") == null, "negative hits read as 0"); + Eq(Row("{\"mstats\":{\"hsf\":2,\"dsf\":-50}}")!.Line(), "Hits taken: shield 0 avg (front 100%)", "negative damage read as 0"); + Check(Row("{\"mstats\":{\"hsf\":1.5,\"dsf\":50}}") == null, "fractional hits read as 0"); + } } diff --git a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj index 25a5c88..337e790 100644 --- a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj +++ b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj @@ -25,6 +25,9 @@ report names the plugin call the pump is inside; PluginShutdownGate: plugins are shut down only once the pump stopped (plus source scans of EngineLifecycle's step order and ShutdownAll's gate) + NativeAttackRearm.cs the native attack clears a stuck attack-in-progress flag (after a stance + change, or 2 s with no swing) and only goes out in Melee/Missile (plus + a source scan of ClientCombatHooks / CombatModeHooks using it) Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> <PropertyGroup> @@ -56,6 +59,7 @@ <Compile Include="..\..\src\RynthCore.Engine\ImGui\FontPixels.cs" Link="Engine\FontPixels.cs" /> <Compile Include="..\..\src\RynthCore.Engine\Net\IdRequester.cs" Link="Engine\IdRequester.cs" /> <Compile Include="..\..\src\RynthCore.Engine\Plugins\PumpGuards.cs" Link="Engine\PumpGuards.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\NativeAttackRearm.cs" Link="Engine\NativeAttackRearm.cs" /> </ItemGroup> </Project> diff --git a/tools/EngineRobustnessTests/NativeAttackRearmTests.cs b/tools/EngineRobustnessTests/NativeAttackRearmTests.cs new file mode 100644 index 0000000..8ea0466 --- /dev/null +++ b/tools/EngineRobustnessTests/NativeAttackRearmTests.cs @@ -0,0 +1,119 @@ +using RynthCore.Engine.Compatibility; + +namespace EngineRobustnessTests; + +/// <summary> +/// The native attack's stuck attack-in-progress flag (Compatibility/NativeAttackRearm.cs), from +/// the 2026-11-06 wedge: a buff-wand swap mid-fight, then 37 minutes of native attacks the client +/// queued behind a flag no AttackDone would ever clear (the regular attack fought at once). Plus a +/// source scan that ClientCombatHooks and CombatModeHooks use the rule where it matters. +/// </summary> +internal static partial class Program +{ + private static void RunNativeAttackRearmTests() + { + RearmAfterStanceChange(); + RearmWhenStale(); + RearmLeavesASwingAlone(); + RearmWithoutTheAttackingFlag(); + RearmModes(); + RearmSourceScan(); + } + + private static void RearmAfterStanceChange() + { + _case = "native re-arm: after a stance change"; + long since = 0; + // Back in Melee after the Staff: the flag set, no swing, the mode changed since the last native attack. + var v = NativeAttackRearm.Judge(inProgress: true, serverSwinging: false, stanceChangedSinceLastSend: true, 1000, ref since); + Check(v == NativeAttackRearm.Verdict.AfterStanceChange, $"cleared at the first native attack, got {v}"); + Check(since == 0, "no stuck clock left running"); + + // The same with the flag clear: nothing to do. + v = NativeAttackRearm.Judge(false, false, true, 1000, ref since); + Check(v == NativeAttackRearm.Verdict.Leave, "flag clear: left alone"); + } + + private static void RearmWhenStale() + { + _case = "native re-arm: stale"; + long since = 0; + var v = NativeAttackRearm.Judge(true, false, false, 10_000, ref since); + Check(v == NativeAttackRearm.Verdict.Leave && since == 10_000, "first sight: the clock starts, no clear (a request can be on its way)"); + v = NativeAttackRearm.Judge(true, false, false, 10_000 + NativeAttackRearm.StuckMs - 1, ref since); + Check(v == NativeAttackRearm.Verdict.Leave, "under 2 s: still left"); + v = NativeAttackRearm.Judge(true, false, false, 10_000 + NativeAttackRearm.StuckMs, ref since); + Check(v == NativeAttackRearm.Verdict.Stale, $"2 s with no swing: cleared, got {v}"); + Check(since == 0, "the clock starts over"); + + // The answer comes in between: the clock resets. + since = 0; + NativeAttackRearm.Judge(true, false, false, 20_000, ref since); + NativeAttackRearm.Judge(false, false, false, 20_500, ref since); // AttackDone cleared it + Check(since == 0, "the flag cleared by the server: clock reset"); + v = NativeAttackRearm.Judge(true, false, false, 22_100, ref since); + Check(v == NativeAttackRearm.Verdict.Leave, "set again later: a fresh 2 s"); + } + + private static void RearmLeavesASwingAlone() + { + _case = "native re-arm: a swing in progress"; + long since = 0; + for (long t = 0; t <= 10_000; t += 500) + { + var v = NativeAttackRearm.Judge(true, serverSwinging: true, stanceChangedSinceLastSend: t == 0, t, ref since); + Check(v == NativeAttackRearm.Verdict.Leave, $"the server swinging (CommenceAttack, no AttackDone yet) at {t} ms: left alone"); + } + Check(since == 0, "no stuck clock while it swings"); + } + + private static void RearmWithoutTheAttackingFlag() + { + _case = "native re-arm: attacking flag unknown"; + long since = 0; + var v = NativeAttackRearm.Judge(true, serverSwinging: null, stanceChangedSinceLastSend: true, 0, ref since); + Check(v == NativeAttackRearm.Verdict.AfterStanceChange, "the stance rule still applies"); + for (long t = 0; t <= 20_000; t += 1000) + { + v = NativeAttackRearm.Judge(true, null, false, t, ref since); + Check(v == NativeAttackRearm.Verdict.Leave, $"no stale clear at {t} ms: a swing can't be told from a stuck flag"); + } + } + + private static void RearmModes() + { + _case = "native re-arm: modes"; + Check(NativeAttackRearm.AttackMode(2) && NativeAttackRearm.AttackMode(4), "Melee and Missile attack"); + Check(!NativeAttackRearm.AttackMode(1) && !NativeAttackRearm.AttackMode(8), "Peace and Magic don't (the native attack is refused there)"); + Check(NativeAttackRearm.DisarmFor(1) && NativeAttackRearm.DisarmFor(8), "Peace and Magic disarm a left-over attack"); + Check(!NativeAttackRearm.DisarmFor(2) && !NativeAttackRearm.DisarmFor(4), "Melee and Missile keep it"); + } + + private static void RearmSourceScan() + { + _case = "native re-arm: source scan"; + string? compat = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Compatibility")); + Check(compat != null, "found src\\RynthCore.Engine\\Compatibility by walking up"); + if (compat == null) return; + + string hooks = File.ReadAllText(Path.Combine(compat, "ClientCombatHooks.cs")); + int body = hooks.IndexOf("public static bool NativeAttack(", StringComparison.Ordinal); + int guard = hooks.IndexOf("NativeAttackRearm.AttackMode(mode)", body, StringComparison.Ordinal); + int rearm = hooks.IndexOf("RearmIfStuck(cs);", body, StringComparison.Ordinal); + int start = hooks.IndexOf("_startAttackRequest(cs);", body, StringComparison.Ordinal); + int stamp = hooks.IndexOf("_modeChangesAtLastSend = CombatModeHooks.ModeChanges;", body, StringComparison.Ordinal); + Check(body >= 0 && guard > body && rearm > guard && start > rearm, + "NativeAttack: the mode guard, then the re-arm, then StartAttackRequest"); + Check(stamp > start, "the mode-change count is taken after the attack went out"); + + string mode = File.ReadAllText(Path.Combine(compat, "CombatModeHooks.cs")); + int detour = mode.IndexOf("private static void SetCombatModeDetour(", StringComparison.Ordinal); + int request = mode.IndexOf("public static unsafe bool RequestCombatMode(", StringComparison.Ordinal); + Check(detour >= 0 && mode.IndexOf("ClientCombatHooks.DisarmOutOfAttackStance(", detour, StringComparison.Ordinal) > detour, + "the SetCombatMode detour disarms a left-over attack"); + int trampoline = request >= 0 ? mode.IndexOf("_originalSetCombatMode(combatSystem, combatMode, 1);", request, StringComparison.Ordinal) : -1; + int disarm = trampoline >= 0 ? mode.IndexOf("ClientCombatHooks.DisarmOutOfAttackStance(", trampoline, StringComparison.Ordinal) : -1; + Check(trampoline > request && disarm > trampoline && disarm < detour, + "RequestCombatMode (the trampoline skips the detour) disarms too"); + } +} diff --git a/tools/EngineRobustnessTests/Program.cs b/tools/EngineRobustnessTests/Program.cs index 0ff6401..4235f54 100644 --- a/tools/EngineRobustnessTests/Program.cs +++ b/tools/EngineRobustnessTests/Program.cs @@ -53,6 +53,8 @@ internal static partial class Program RunShutdownOrderTests(); RunReloadStallTests(); + RunNativeAttackRearmTests(); + Console.WriteLine($"{_checks} check(s), {_failed} failed."); return _failed == 0 ? 0 : 1; } diff --git a/tools/HotkeyTests/Program.cs b/tools/HotkeyTests/Program.cs index d7db410..54f8112 100644 --- a/tools/HotkeyTests/Program.cs +++ b/tools/HotkeyTests/Program.cs @@ -219,8 +219,15 @@ internal static class Program Check(HotkeyRules.Check(ok with { InWorld = false }, f1) == HotkeyGate.NotInWorld, "character select: no"); Check(HotkeyRules.Check(ok with { GameFocused = false }, f1) == HotkeyGate.NotFocused, "another app in front: no"); Check(HotkeyRules.Check(ok with { RynthTextFocus = true }, ctrlW) == HotkeyGate.RynthTyping, "RynthCore text box: no, even Ctrl combos"); - Check(HotkeyRules.Check(ok with { AcTextFocus = true }, f1) == HotkeyGate.AcTyping, "AC chat typing: no, even F keys"); - Check(HotkeyRules.Check(ok with { AcTextFocus = true, RynthTextFocus = true }, f1) == HotkeyGate.RynthTyping, "ours first"); + // 2026-11-06 (owner): an F key types nothing, so it fires while a chat entry has the keys. + Check(HotkeyRules.Check(ok with { AcTextFocus = true }, f1) == HotkeyGate.Fire, "AC chat typing: an F key still fires"); + Check(HotkeyRules.Check(ok with { AcTextFocus = true }, new KeyCombo(VK_F12, HotkeyMods.Shift | HotkeyMods.Ctrl)) == HotkeyGate.Fire, + "AC chat typing: an F key with modifiers still fires"); + Check(HotkeyRules.Check(ok with { RynthTextFocus = true }, f1) == HotkeyGate.Fire, "RynthCore text box: an F key still fires"); + Check(HotkeyRules.Check(ok with { AcTextFocus = true }, w) == HotkeyGate.AcTyping, "AC chat typing: a letter is held"); + Check(HotkeyRules.Check(ok with { AcTextFocus = true }, ctrlW) == HotkeyGate.AcTyping, "AC chat typing: Ctrl combos are held (copy, paste)"); + Check(HotkeyRules.Check(ok with { AcTextFocus = true }, altNum) == HotkeyGate.AcTyping, "AC chat typing: Alt combos are held"); + Check(HotkeyRules.Check(ok with { AcTextFocus = true, RynthTextFocus = true }, w) == HotkeyGate.RynthTyping, "ours first"); var unknown = ok with { AcTextFocus = null }; Check(HotkeyRules.Check(unknown, w) == HotkeyGate.AcUnknownTextKey, "AC focus unknown: a letter could be typing"); diff --git a/tools/ItemsNoBuffTests/ItemsNoBuffTests.csproj b/tools/ItemsNoBuffTests/ItemsNoBuffTests.csproj new file mode 100644 index 0000000..7fd2b2a --- /dev/null +++ b/tools/ItemsNoBuffTests/ItemsNoBuffTests.csproj @@ -0,0 +1,27 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the Items faces' "No buff" shield toggle: ItemsPanel.WeaponEntry must read + RynthAi's "noBuff" (sent for every entry; null from an older RynthAi), show the toggle on shield + entries only, and write the field back only when it holds a value. Reaches the internal types by + reflection (the engine has no test seam). x86, like the engine: needs the x86 .NET runtime. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0-windows</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <RuntimeIdentifier>win-x86</RuntimeIdentifier> + <SelfContained>false</SelfContained> + <Platforms>x86</Platforms> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>ItemsNoBuffTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <ProjectReference Include="..\..\src\RynthCore.Engine\RynthCore.Engine.csproj" /> + </ItemGroup> + +</Project> diff --git a/tools/ItemsNoBuffTests/Program.cs b/tools/ItemsNoBuffTests/Program.cs new file mode 100644 index 0000000..2b02f74 --- /dev/null +++ b/tools/ItemsNoBuffTests/Program.cs @@ -0,0 +1,79 @@ +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; +using System.Text.RegularExpressions; + +namespace ItemsNoBuffTests +{ + // The engine half of the shield "No buff" toggle, against what RynthAi's Items bridge writes + // (ItemsBridgePayload: PascalCase names, "noBuff" on every weapon entry) and reads + // (case-insensitive; noBuff applied for Action "Shield" entries only, absent = unchanged). + internal static class Program + { + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + + private const string Ns = "RynthCore.Engine.UI.Panels."; + private const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; + + private static int Main() + { + Assembly engine = Assembly.Load("RynthCore.Engine"); + Type ctxType = engine.GetType(Ns + "ItemsPanelJsonContext", throwOnError: true)!; + object ctx = ctxType.GetProperty("Default", All)!.GetValue(null)!; + var info = (JsonTypeInfo)ctxType.GetProperty("Payload", All)!.GetValue(ctx)!; + Type payloadType = engine.GetType(Ns + "ItemsPanel+Payload", throwOnError: true)!; + Type entryType = engine.GetType(Ns + "ItemsPanel+WeaponEntry", throwOnError: true)!; + + List<object> Weapons(object payload) => + ((System.Collections.IEnumerable)payloadType.GetProperty("Weapons", All)!.GetValue(payload)!).Cast<object>().ToList(); + bool? NoBuff(object e) => (bool?)entryType.GetProperty("NoBuff", All)!.GetValue(e); + bool Shows(object e) => (bool)entryType.GetProperty("ShowsNoBuff", All)!.GetValue(e)!; + string Name(object e) => (string)entryType.GetProperty("Name", All)!.GetValue(e)!; + + // --- RynthAi -> engine (the shape RynthAi's BuildItemsJson writes) + const string fromPlugin = "{\n \"Weapons\": [\n" + + " { \"Id\": 1, \"Name\": \"Sword\", \"Action\": \"Weapon\", \"Element\": \"Slash\", \"Kind\": \"Melee\", \"KeepBuffed\": false, \"noBuff\": true },\n" + + " { \"Id\": 2, \"Name\": \"Kite Shield\", \"Action\": \"Shield\", \"Element\": \"Shield\", \"Kind\": \"Shield\", \"KeepBuffed\": true, \"noBuff\": false },\n" + + " { \"Id\": 3, \"Name\": \"Rose Shield\", \"Action\": \"Shield\", \"Element\": \"Shield\", \"Kind\": \"Shield\", \"KeepBuffed\": false, \"noBuff\": true },\n" + + " { \"Id\": 4, \"Name\": \"Buckler\", \"Action\": \"Weapon\", \"Element\": \"Shield\", \"Kind\": \"Shield\", \"noBuff\": true }\n" + + " ],\n \"MissingIds\": []\n}"; + object p = JsonSerializer.Deserialize(fromPlugin, info)!; + var w = Weapons(p); + Check(w.Count == 4, "four entries read"); + Check(NoBuff(w[0]) == true && NoBuff(w[1]) == false && NoBuff(w[2]) == true, "noBuff is read per entry"); + Check(!Shows(w[0]), "a weapon row: no toggle (RynthAi ignores noBuff on weapons)"); + Check(Shows(w[1]) && Shows(w[2]), "a shield row (Action Shield): the toggle"); + Check(!Shows(w[3]), "a shield filed as a Weapon (Kind Shield, Action Weapon): no toggle (RynthAi ignores it there)"); + + // --- An older RynthAi: no field -> no toggle, nothing written back + object old = JsonSerializer.Deserialize("{\"Weapons\":[{\"Id\":2,\"Name\":\"Kite Shield\",\"Action\":\"Shield\",\"Element\":\"Shield\"}]}", info)!; + object oldShield = Weapons(old)[0]; + Check(NoBuff(oldShield) == null, "an older RynthAi: noBuff is null"); + Check(!Shows(oldShield), "and the shield row has no toggle"); + string oldBack = JsonSerializer.Serialize(old, info); + Check(!oldBack.Contains("noBuff"), "and the save carries no noBuff (RynthAi keeps its saved value): " + oldBack); + Check(!oldBack.Contains("ShowsNoBuff"), "the face-only ShowsNoBuff is not on the wire"); + + // --- Engine -> RynthAi: the toggle flipped and saved + entryType.GetProperty("NoBuff", All)!.SetValue(w[1], true); // what the faces' click does + entryType.GetProperty("NoBuff", All)!.SetValue(w[2], false); + string back = JsonSerializer.Serialize(p, info); + Check(Regex.IsMatch(back, "\"id\":2,[^}]*\"noBuff\":true"), "the Kite Shield goes back noBuff true: " + back); + Check(Regex.IsMatch(back, "\"id\":3,[^}]*\"noBuff\":false"), "the Rose Shield goes back noBuff false"); + Check(Regex.IsMatch(back, "\"id\":1,[^}]*\"noBuff\":true"), "a weapon's value is round-tripped untouched (RynthAi ignores it)"); + Check(Regex.Matches(back, "\"action\":\"Shield\"").Count == 2 && Name(w[1]) == "Kite Shield", "names and actions round-trip"); + + // The field name is exactly what RynthAi's ItemRule.NoBuff ([JsonPropertyName("noBuff")]) reads. + var attr = entryType.GetProperty("NoBuff", All)!.GetCustomAttribute<System.Text.Json.Serialization.JsonPropertyNameAttribute>(); + Check(attr?.Name == "noBuff", "the wire name is noBuff"); + + Console.WriteLine(_fails == 0 ? $"All {_asserts} checks passed." : $"{_fails} of {_asserts} checks FAILED."); + return _fails == 0 ? 0 : 1; + } + } +} diff --git a/tools/OutdoorHuntPickTests/OutdoorHuntPickTests.csproj b/tools/OutdoorHuntPickTests/OutdoorHuntPickTests.csproj new file mode 100644 index 0000000..081b3c8 --- /dev/null +++ b/tools/OutdoorHuntPickTests/OutdoorHuntPickTests.csproj @@ -0,0 +1,31 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the Settings > Navigation > Outdoor Hunt "Go for" row (2026-11-08): the mirror + of RynthAi's OutdoorHuntPick (0 = Nearest monster, 1 = Biggest pack, 2 = Most XP) in + UI\Data\SettingsData.cs. Nothing is claimed until RynthAi sends the value (an older RynthAi omits + it: the row stays hidden and a save sends null, which RynthAi leaves alone); the row edits only + that property and keeps it within the three choices. + The engine has no test seam for SettingsData.cs (it pulls in the whole ImGui layer), so this + references the built engine assembly and reaches the internal types by reflection. x86, like + the engine: needs the x86 .NET runtime (C:\Program Files (x86)\dotnet). + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0-windows</TargetFramework> + <PlatformTarget>x86</PlatformTarget> + <RuntimeIdentifier>win-x86</RuntimeIdentifier> + <SelfContained>false</SelfContained> + <Platforms>x86</Platforms> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>OutdoorHuntPickTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <ProjectReference Include="..\..\src\RynthCore.Engine\RynthCore.Engine.csproj" /> + </ItemGroup> + +</Project> diff --git a/tools/OutdoorHuntPickTests/Program.cs b/tools/OutdoorHuntPickTests/Program.cs new file mode 100644 index 0000000..ecf1f29 --- /dev/null +++ b/tools/OutdoorHuntPickTests/Program.cs @@ -0,0 +1,110 @@ +using System.Collections; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; + +namespace OutdoorHuntPickTests +{ + // Reaches RynthCore.Engine's internal settings mirror by reflection. See the csproj. + internal static class Program + { + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + + private const string Ns = "RynthCore.Engine.UI.Data."; + private const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; + + private static int Main() + { + Assembly engine = Assembly.Load("RynthCore.Engine"); + Type settingsType = engine.GetType(Ns + "RynthAiSettings", throwOnError: true)!; + Type ctxType = engine.GetType(Ns + "RynthAiSettingsJsonContext", throwOnError: true)!; + Type schemaType = engine.GetType(Ns + "SettingsSchema", throwOnError: true)!; + PropertyInfo? prop = settingsType.GetProperty("OutdoorHuntPick", All); + Check(prop != null && prop.PropertyType == typeof(int?), "the mirror has a nullable int OutdoorHuntPick (RynthAi's payload name)"); + if (prop == null) return Finish(); + + object ctx = ctxType.GetProperty("Default", All)!.GetValue(null)!; + var info = (JsonTypeInfo)ctxType.GetProperty("RynthAiSettings", All)!.GetValue(ctx)!; + object Parse(string json) => JsonSerializer.Deserialize(json, info)!; + + // What a payload carries: nothing from an older RynthAi, the value from a newer one. + object fresh = Activator.CreateInstance(settingsType, nonPublic: true)!; + Check(prop.GetValue(fresh) == null, "a fresh mirror holds no value"); + Check(prop.GetValue(Parse("{\"OutdoorHuntRange\":60,\"OutdoorHuntRadius\":0}")) == null, "a RynthAi without it: absent (null)"); + for (int v = 0; v <= 2; v++) + Check((int?)prop.GetValue(Parse("{\"OutdoorHuntPick\":" + v + "}")) == v, $"RynthAi sends {v}"); + + // A save sends exactly what the mirror holds: unset stays null (RynthAi leaves its setting alone). + Check(JsonSerializer.Serialize(fresh, info).Contains("\"OutdoorHuntPick\":null"), "an unset mirror saves null"); + Check(JsonSerializer.Serialize(Parse("{\"OutdoorHuntPick\":2}"), info).Contains("\"OutdoorHuntPick\":2"), "Most XP saves 2"); + + // The schema row, under Navigation, beside Hunt Range / Hunt Radius. + object? nav = null; + foreach (object t in (IEnumerable)schemaType.GetField("Tabs", All)!.GetValue(null)!) + if ((string)t.GetType().GetProperty("Name")!.GetValue(t)! == "Navigation") nav = t; + Check(nav != null, "a Navigation tab"); + if (nav == null) return Finish(); + + var labels = new List<string>(); + object? row = null; + int matches = 0; + foreach (object r in (IEnumerable)nav.GetType().GetProperty("Rows")!.GetValue(nav)!) + { + string label = (string?)r.GetType().GetProperty("Label")!.GetValue(r) ?? ""; + labels.Add(label); + if (label == "Go for") { row = r; matches++; } + } + Check(matches == 1, "exactly one Go for row, under Navigation"); + int radius = labels.IndexOf("Hunt Radius (yd)"), goFor = labels.IndexOf("Go for"); + Check(radius >= 0 && goFor == radius + 1, "right after Hunt Radius"); + if (row == null) return Finish(); + + Type rt = row.GetType(); + Check(rt.GetProperty("Kind")!.GetValue(row)!.ToString() == "Combo", "a combo"); + var items = (string[])rt.GetProperty("CurrentItems")!.GetValue(row)!; + Check(items.SequenceEqual(new[] { "Nearest monster", "Biggest pack", "Most XP" }), "the three choices, in RynthAi's order"); + string tip = (string?)rt.GetProperty("Tooltip")!.GetValue(row) ?? ""; + Check(tip.Contains("Nearest monster: the closest one, as before."), "tooltip: nearest"); + Check(tip.Contains("Biggest pack: the most monsters together"), "tooltip: biggest pack"); + Check(tip.Contains("Most XP: the pack worth the most experience, learned from your kills"), "tooltip: most XP"); + + var get = (Delegate)rt.GetProperty("Get")!.GetValue(row)!; + var set = (Delegate)rt.GetProperty("Set")!.GetValue(row)!; + MethodInfo visible = rt.GetMethod("IsVisible")!; + + Check(!(bool)visible.Invoke(row, new[] { fresh })!, "hidden while RynthAi hasn't sent the value"); + Check(!(bool)visible.Invoke(row, new[] { Parse("{\"OutdoorHuntRange\":60,\"OutdoorHuntRadius\":0}") })!, + "hidden for a RynthAi with Hunt Range but no Go for"); + object near = Parse("{\"OutdoorHuntRange\":60,\"OutdoorHuntPick\":0}"); + Check((bool)visible.Invoke(row, new[] { near })!, "shown once RynthAi sends it"); + Check((double)get.DynamicInvoke(near)! == 0, "Nearest monster reads 0"); + set.DynamicInvoke(near, 2.0); + Check((int?)prop.GetValue(near) == 2, "choosing Most XP sets 2"); + set.DynamicInvoke(near, 1.0); + Check((int?)prop.GetValue(near) == 1, "choosing Biggest pack sets 1"); + set.DynamicInvoke(near, 7.0); + Check((int?)prop.GetValue(near) == 2, "an out-of-range pick is kept within the choices"); + Check((double)get.DynamicInvoke(Parse("{\"OutdoorHuntPick\":9}"))! == 2, "an unknown value from a newer RynthAi reads as the last choice"); + Check((double)get.DynamicInvoke(Parse("{\"OutdoorHuntPick\":-3}"))! == 0, "a negative value reads Nearest monster"); + + // Picking changes nothing else in the payload. + object before = Parse("{\"OutdoorHuntRange\":60,\"OutdoorHuntRadius\":150,\"OutdoorHuntPick\":0}"); + set.DynamicInvoke(before, 1.0); + string after = JsonSerializer.Serialize(before, info); + Check(after.Contains("\"OutdoorHuntRange\":60") && after.Contains("\"OutdoorHuntRadius\":150") && after.Contains("\"OutdoorHuntPick\":1"), + "Hunt Range and Hunt Radius ride along unchanged"); + return Finish(); + } + + private static int Finish() + { + Console.WriteLine(_fails == 0 ? $"All {_asserts} checks passed." : $"{_fails} of {_asserts} checks FAILED."); + return _fails == 0 ? 0 : 1; + } + } +} diff --git a/tools/PanelLayoutTests/Program.cs b/tools/PanelLayoutTests/Program.cs index 2555c12..8c2780d 100644 --- a/tools/PanelLayoutTests/Program.cs +++ b/tools/PanelLayoutTests/Program.cs @@ -62,6 +62,9 @@ namespace PanelLayoutTests Run(TwoSessionsNeverShareAFile); Run(TwoClientsNeverWriteEachOthersFiles); Run(AutoSaveRules); + Run(IdentityFromThePlayerWhenTheLaunchHasNone); + Run(HotReloadWithTheNameNotKnownYet); + Run(TheDefaultIsOnlyReadInUse); Run(CommandReplies); } finally @@ -617,16 +620,139 @@ namespace PanelLayoutTests private static void AutoSaveRules() { - Case("automatic imgui.ini saves"); - Check(PanelLayoutPolicy.MayAutoSaveIni(characterLayout: true, perCharacter: true, inWorld: true, contextHeldCharacter: true), "a character's layout: always saved"); - Check(PanelLayoutPolicy.MayAutoSaveIni(true, true, inWorld: false, contextHeldCharacter: true), "...also at a logout's last save"); - Check(PanelLayoutPolicy.MayAutoSaveIni(false, perCharacter: false, inWorld: true, contextHeldCharacter: true), "the setting off: the shared default is saved, as before"); - Check(PanelLayoutPolicy.MayAutoSaveIni(false, perCharacter: false, inWorld: false, contextHeldCharacter: false), "the setting off, at character select: saved, as before"); - Check(PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: true, contextHeldCharacter: false), "in the world with no character name (the default in use): saved, as before"); - Check(!PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: false, contextHeldCharacter: false), - "character select with the setting on: the default isn't written (it could undo another client's /rc layout default)"); - Check(!PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: false, contextHeldCharacter: true), "the default after a character logged out: not saved (its windows would leak into it)"); - Check(!PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: true, contextHeldCharacter: true), "the default in the world after a character's layout was used: not saved"); + Case("saves of the layout in use (imgui.ini and panel_state.txt)"); + Check(PanelLayoutPolicy.MaySaveLayoutInUse(characterLayout: true, perCharacter: true), "a character's layout: always saved"); + Check(PanelLayoutPolicy.MaySaveLayoutInUse(false, perCharacter: false), "the setting off: the shared default is saved, as before"); + Check(!PanelLayoutPolicy.MaySaveLayoutInUse(false, perCharacter: true), + "the setting on: the default is never saved (character select, a client that doesn't know its character yet, Save Layout Now)"); + string why = PanelLayoutPolicy.DefaultReadOnlyText(inWorld: true); + Check(why.Contains(PanelLayoutPolicy.ReasonText(DefaultReason.NoCharacterName), StringComparison.Ordinal) && why.Contains("/rc layout default", StringComparison.Ordinal), + "Save Layout Now on the default says why and what writes it"); + Check(PanelLayoutPolicy.DefaultReadOnlyText(false).Contains(PanelLayoutPolicy.ReasonText(DefaultReason.NotInWorld), StringComparison.Ordinal), "...at character select too"); + } + + // ── 2026-11-05: a client launched with no character picked ───────────── + + private static void IdentityFromThePlayerWhenTheLaunchHasNone() + { + Case("the key: the launch context's name, else the player's own"); + Eq(PanelLayoutPolicy.Identity(ServerOne, CharA, CharB), WhoA, "the launch context names one: that one (the key the other per-character files use)"); + Eq(PanelLayoutPolicy.Identity(ServerOne, "", CharB), WhoB, "the launch context names none: the player in the world"); + Eq(PanelLayoutPolicy.Identity(ServerOne, " ", " " + CharB + " "), WhoB, "a blank launch name is none; the player's name is trimmed"); + Check(PanelLayoutPolicy.Identity(ServerOne, "", "") == null, "neither known: no owner"); + Check(PanelLayoutPolicy.Identity(ServerOne, null, null) == null, "nothing at all: no owner"); + } + + private static void HotReloadWithTheNameNotKnownYet() + { + // The live log (2026-11-05): "SessionState: recorded login session ... character=''" at the hot + // reload, then "switched to the PC-wide default layout" and nothing later; that client saved + // its places into the shared files all session. + Case("hot reload, recorded with no name: waits for the player's name, never the default first"); + var s = new PanelLayoutSession(); + const long login = 70_000; + Check(s.Tick(login, true, true, login, identityRecorded: true, null) == null, "recorded without a name: no switch yet (the player's name is on its way)"); + Check(!s.ReadyToDraw(login + 16, true, login), "...and the panels wait"); + Check(s.Tick(login + 500, true, true, login, true, null) == null, "still waiting half a second in"); + LayoutSwitch? sw = s.Tick(login + 800, true, true, login, true, WhoA); + Check(sw is { } a && Equals(a.To, WhoA) && !a.FlushFrom, "the player's name read: straight to the character's layout, nothing written out"); + s.MarkApplied(sw!.Value.Gen); + Check(s.ReadyToDraw(login + 816, true, login), "applied: the panels draw, in the character's places"); + + Case("hot reload, the name later than the wait: the default only read, then the character's"); + var late = new PanelLayoutSession(); + Check(late.Tick(login, true, true, login, true, null) == null, "recorded without a name: waiting"); + sw = late.Tick(login + PanelLayoutPolicy.IdentityWaitMs, true, true, login, true, null); + Check(sw is { } d && d.To == null && !d.FlushFrom, "the wait over, no name: the default, so the panels can draw"); + Check(!PanelLayoutPolicy.MaySaveLayoutInUse(characterLayout: sw!.Value.To != null, perCharacter: true), + "...but nothing auto-saves into it (no default auto-save from a client in the world)"); + late.MarkApplied(sw.Value.Gen); + Check(late.ReadyToDraw(login + PanelLayoutPolicy.IdentityWaitMs + 1, true, login), "the panels draw with it meanwhile"); + Check(late.Tick(login + PanelLayoutPolicy.IdentityWaitMs + 16, true, true, login, true, null) == null, "no name yet: nothing more"); + sw = late.Tick(login + PanelLayoutPolicy.IdentityWaitMs + 2000, true, true, login, true, WhoA); + Check(sw is { } c && Equals(c.To, WhoA) && c.From == null && !c.FlushFrom, + "the name known later: the switch to the character's layout, the default not written out"); + Check(late.ReadyToDraw(login + PanelLayoutPolicy.IdentityWaitMs + 2001, true, login), "the panels keep drawing while it loads"); + late.MarkApplied(sw!.Value.Gen); + Eq(late.AppliedLayout, WhoA, "the character's layout is in use for the rest of the session"); + Check(PanelLayoutPolicy.MaySaveLayoutInUse(late.AppliedLayout != null, true), "...and its saves go to the character's files"); + Check(late.Tick(login + PanelLayoutPolicy.IdentityWaitMs + 3000, true, true, login, true, WhoA) == null, "no switch back"); + + Case("a relogin in the same client: the new login waits for its own name again"); + sw = late.Tick(200_000, true, false, 0, true, null); + Check(sw is { } o && o.To == null && o.FlushFrom, "logout: the character's written out, the default (read only) at character select"); + late.MarkApplied(sw!.Value.Gen); + const long relogin = 300_000; + Check(late.Tick(relogin, true, true, relogin, true, null) == null, "the new login, no name yet: waiting"); + sw = late.Tick(relogin + 400, true, true, relogin, true, WhoB); + Check(sw is { } r && Equals(r.To, WhoB), "the other character's name: its layout"); + } + + private static void TheDefaultIsOnlyReadInUse() + { + Case("PanelStateStore: the PC-wide default is only read with the setting on"); + string root = NewDir("readonly"); + string def = Path.Combine(root, "panel_state.txt"); + File.WriteAllText(def, "# default\r\nbar=1,2\r\npanel.Shortcuts=open,10,20,300,120,docked,0,0\r\n"); + byte[] defBytes = File.ReadAllBytes(def); + string a = Path.Combine(root, "layouts", "s", "a", "panel_state.txt"); + Directory.CreateDirectory(Path.GetDirectoryName(a)!); + File.WriteAllText(a, "# A\r\npanel.Shortcuts=open,900,700,300,120,docked,0,0\r\n"); + PanelStateStore.ReadOnlyPath = def; + try + { + PanelStateStore.SwitchTo(def, flushCurrent: false); + PanelStateStore.SetPanel("Shortcuts", new PanelStateStore.PanelEntry(true, 55, 66, 300, 120)); + PanelStateStore.SetBarPosition(3, 4); + Eq(File.ReadAllBytes(def), defBytes, "a moved window and the bar on the default: not written"); + Check(PanelStateStore.TryGetPanel("Shortcuts", out var moved) && moved.Left == 55, "...kept in memory while it is in use"); + PanelStateStore.Flush(); + Eq(File.ReadAllBytes(def), defBytes, "Save Layout Now doesn't write it either"); + PanelStateStore.SwitchTo(a, flushCurrent: true); + Eq(File.ReadAllBytes(def), defBytes, "switching away (even asked to write out what it leaves) doesn't write it"); + Check(PanelStateStore.TryGetPanel("Shortcuts", out var mine) && mine.Left == 900, "the character's layout: its own place, not the moves made on the default"); + + Case("a plugin window registered after the switch gets its saved place, and its moves are saved"); + // PluginWindows registers its windows seconds after the login (the manifests); the store + // holds every row of the file whether a window is registered or not. + Check(PanelStateStore.TryGetPanel("Late Window", out _) == false, "not in the file: nothing saved yet"); + File.WriteAllText(a, "# A\r\npanel.Shortcuts=open,900,700,300,120,docked,0,0\r\npanel.Toolbar=open,400,10,500,40,docked,0,0\r\n"); + PanelStateStore.SwitchTo(a, flushCurrent: false); + Check(PanelStateStore.TryGetPanel("Toolbar", out var tb) && tb.Open && tb.Left == 400 && tb.Top == 10, + "a window registered after the switch reads its saved place and open state from the character's layout"); + PanelStateStore.SetPanel("Toolbar", tb with { Left = 420, Top = 12 }); + Check(File.ReadAllText(a).Contains("panel.Toolbar=open,420,12,", StringComparison.Ordinal), "its move is saved to the character's file"); + Check(File.ReadAllText(a).Contains("panel.Shortcuts=open,900,700,", StringComparison.Ordinal), "...with the other windows' rows kept"); + Eq(File.ReadAllBytes(def), defBytes, "...and the default untouched"); + + Case("a layout switch and plugin windows: they follow the new layout like engine panels"); + const WindowKind plugin = WindowKind.PluginWindow, engine = WindowKind.EnginePanel, script = WindowKind.ScriptWindow; + Eq(PanelLayoutPolicy.StepAtSwitch(plugin, shown: false, remember: true, saved: true, savedOpen: true), SwitchStep.Open, + "registered (on the old layout) but not open, the new layout has it open: it opens there"); + Eq(PanelLayoutPolicy.StepAtSwitch(plugin, shown: true, remember: true, saved: true, savedOpen: false), SwitchStep.Close, + "opened from the old layout, the new one has it closed: it closes (not saved over)"); + Eq(PanelLayoutPolicy.StepAtSwitch(plugin, true, true, saved: true, savedOpen: true), SwitchStep.Place, "open in both: it moves to the new layout's place"); + Eq(PanelLayoutPolicy.StepAtSwitch(plugin, true, true, saved: false, savedOpen: false), SwitchStep.PlaceAndSave, + "new to the layout: placed, and saved there so it comes back there"); + Eq(PanelLayoutPolicy.StepAtSwitch(plugin, false, true, saved: false, savedOpen: false), SwitchStep.Leave, "not open, not in the layout: left alone"); + Eq(PanelLayoutPolicy.StepAtSwitch(plugin, false, remember: false, true, true), SwitchStep.Leave, "Remember Open Windows off: not opened"); + Eq(PanelLayoutPolicy.StepAtSwitch(plugin, true, remember: false, true, false), SwitchStep.Place, "...nor closed"); + Eq(PanelLayoutPolicy.StepAtSwitch(engine, false, true, true, true), SwitchStep.Open, "an engine panel: the same"); + Eq(PanelLayoutPolicy.StepAtSwitch(engine, true, true, true, false), SwitchStep.Close, "...both ways"); + Eq(PanelLayoutPolicy.StepAtSwitch(script, false, true, true, true), SwitchStep.Leave, "a script window opens when its script says, not from the layout"); + Eq(PanelLayoutPolicy.StepAtSwitch(script, true, true, true, false), SwitchStep.Place, "...and stays open (it moves)"); + + Case("the setting off: the default is saved, as before"); + PanelStateStore.ReadOnlyPath = null; + PanelStateStore.SwitchTo(def, flushCurrent: false); + PanelStateStore.SetBarPosition(5, 6); + Check(File.ReadAllText(def).Contains("bar=5,6", StringComparison.Ordinal), "no read-only mark: the shared file is written"); + } + finally + { + PanelStateStore.ReadOnlyPath = null; + } + NoTempFiles(root); } private static void CommandReplies() diff --git a/tools/PlateSightTests/PlateSightTests.csproj b/tools/PlateSightTests/PlateSightTests.csproj new file mode 100644 index 0000000..8cafd78 --- /dev/null +++ b/tools/PlateSightTests/PlateSightTests.csproj @@ -0,0 +1,25 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for src\RynthCore.Engine\ImGui\MonsterHud\PlateSightRules.cs (2026-11-04, problem + report R-20261105-020337-67aa: nameplates and NPC labels drew, and took clicks, through walls): + given the camera's cell, the player's cell, the visible-cell list, "sees outside", AC's draw + stamp on the object's room and the doorways, does a plate or label show? Anything unknown shows + (today's behaviour). The AC-side facts (offsets, the stamp, the pattern) are checked against + acclient.exe by tools\plate_sight_check.py. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>PlateSightTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\PlateSightRules.cs" Link="Engine\PlateSightRules.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/PlateSightTests/Program.cs b/tools/PlateSightTests/Program.cs new file mode 100644 index 0000000..4eb023f --- /dev/null +++ b/tools/PlateSightTests/Program.cs @@ -0,0 +1,274 @@ +using RynthCore.Engine.ImGuiBackend.Hud; + +namespace PlateSightTests; + +/// <summary> +/// PlateSightRules: does a nameplate or name label show for an object, given what AC's cells say +/// (2026-11-04, report R-20261105-020337-67aa: labels drew, and took clicks, through walls)? +/// </summary> +internal static class Program +{ + // One landblock (0xC6A9: the town of the report) with a shop and its neighbours. + private const uint Shop = 0xC6A90161; // the viewer's room (the report's cell): sees outside + private const uint ShopBack = 0xC6A90162; // another room of the shop, in its visible list + private const uint ShopUpstairs = 0xC6A90163; // in the visible list too + private const uint NextDoor = 0xC6A90170; // another building's room: not visible from the shop + private const uint Street = 0xC6A90029; // an outdoor land cell + private const uint Street2 = 0xC6A9002A; + private const uint Dungeon = 0x01D90105; // a dungeon room: doesn't see outside + private const uint DungeonNear = 0x01D90106; + private const uint DungeonFar = 0x01D90140; + + private static readonly uint[] ShopVisible = { Shop, ShopBack, ShopUpstairs }; + private static readonly uint[] DungeonVisible = { Dungeon, DungeonNear }; + + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + CellIds(); + Stamps(); + Rects(); + NothingKnownShows(); + OwnRoomsAlwaysShow(); + BothOutdoorsUnchanged(); + IndoorsTheCellList(); + IndoorsTheDrawStamp(); + IndoorsOutdoorObjects(); + DungeonsSeeNothingOutside(); + OutdoorsLookingIntoBuildings(); + CoarseIsTheCellListsOnly(); + TheReport(); + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL PLATE SIGHT TESTS PASSED." : $"{_failed} FAILED."); + return _failed == 0 ? 0 : 1; + } + + private static SightQuery InShop(uint obj, bool onScreen = true) => new() + { + ViewerCell = Shop, PlayerCell = Shop, ViewerSeesOutside = SightFact.Yes, + ViewerVisible = ShopVisible, VisibleKnown = true, ObjectCell = obj, OnScreen = onScreen, + }; + + private static SightQuery InDungeon(uint obj, bool onScreen = true) => new() + { + ViewerCell = Dungeon, PlayerCell = Dungeon, ViewerSeesOutside = SightFact.No, + ViewerVisible = DungeonVisible, VisibleKnown = true, ObjectCell = obj, OnScreen = onScreen, + }; + + private static SightQuery OnStreet(uint obj, bool onScreen = true) => new() + { + ViewerCell = Street, PlayerCell = Street, ViewerSeesOutside = SightFact.Yes, + ViewerVisible = ReadOnlySpan<uint>.Empty, VisibleKnown = true, ObjectCell = obj, OnScreen = onScreen, + }; + + private static void CellIds() + { + Case("cell ids: land cells are outdoors, 0x0100 and up are EnvCells"); + Check(!PlateSightRules.IsIndoor(Street) && !PlateSightRules.IsIndoor(0xC6A90001) && !PlateSightRules.IsIndoor(0xC6A90040), "0x0001-0x0040 outdoors"); + Check(!PlateSightRules.IsIndoor(0xC6A900FF), "0x00FF outdoors"); + Check(PlateSightRules.IsIndoor(0xC6A90100) && PlateSightRules.IsIndoor(Shop) && PlateSightRules.IsIndoor(0x01D9FFFD), "0x0100.. indoors"); + } + + private static void Stamps() + { + Case("draw stamps: drawn since the sample, wrapping at 2^32"); + Check(PlateSightRules.DrawnSince(101, 100), "one newer"); + Check(PlateSightRules.DrawnSince(5000, 100), "many newer (several DrawCells passes a frame)"); + Check(!PlateSightRules.DrawnSince(100, 100), "the sample itself is not newer"); + Check(!PlateSightRules.DrawnSince(99, 100), "older"); + Check(!PlateSightRules.DrawnSince(0, 100), "never drawn (a new cell starts at 0)"); + Check(PlateSightRules.DrawnSince(0x10, 0xFFFFFFF0), "across the wrap"); + Check(!PlateSightRules.DrawnSince(0xFFFFFFF0, 0x10), "older across the wrap"); + } + + private static void Rects() + { + Case("screen rects: overlap, touching, the margin"); + Check(PlateSightRules.Overlaps(10, 10, 20, 20, 15, 15, 30, 30, 0), "overlapping"); + Check(PlateSightRules.Overlaps(10, 10, 20, 20, 20, 0, 30, 30, 0), "touching edges count"); + Check(!PlateSightRules.Overlaps(10, 10, 20, 20, 25, 10, 30, 20, 0), "apart"); + Check(PlateSightRules.Overlaps(10, 10, 20, 20, 25, 10, 30, 20, 6), "apart by less than the margin"); + Check(PlateSightRules.Overlaps(15, 0, 15, 40, 10, 10, 20, 20, 0), "a head-to-feet line through the rect"); + } + + private static void NothingKnownShows() + { + Case("nothing known: today's behaviour (the plate shows)"); + var q = new SightQuery { ObjectCell = NextDoor, OnScreen = true, ObjectCellDrawn = SightFact.No }; + Check(PlateSightRules.Show(in q), "no viewer cell"); + q = InShop(0); + Check(PlateSightRules.Show(in q), "no object cell"); + q = InShop(0x00000161); + Check(PlateSightRules.Show(in q), "an object cell without a landblock"); + q = InShop(NextDoor); + q.VisibleKnown = false; + q.ViewerVisible = ReadOnlySpan<uint>.Empty; + Check(PlateSightRules.Show(in q), "visible list unreadable, no stamp: shows"); + q = InShop(Street); + q.ViewerSeesOutside = SightFact.Unknown; + Check(PlateSightRules.Show(in q), "viewer's sees-outside unreadable: an outdoor object shows"); + } + + private static void OwnRoomsAlwaysShow() + { + Case("the viewer's and the player's own cells always show"); + SightQuery q = InShop(Shop); + q.ObjectCellDrawn = SightFact.No; // even a stale "not drawn" + Check(PlateSightRules.Show(in q), "the viewer's room"); + q = InShop(NextDoor); + q.PlayerCell = NextDoor; // third person: the camera is in another room + q.ObjectCellDrawn = SightFact.No; + Check(PlateSightRules.Show(in q), "the player's room"); + q = InDungeon(Dungeon, onScreen: false); + Check(PlateSightRules.Show(in q), "the dungeon room you stand in"); + } + + private static void BothOutdoorsUnchanged() + { + Case("viewer and object outdoors: no change (no terrain or building occlusion)"); + SightQuery q = OnStreet(Street2); + Check(PlateSightRules.Show(in q), "on screen"); + q = OnStreet(Street2, onScreen: false); + Check(PlateSightRules.Show(in q), "pinned to the edge"); + q = OnStreet(0xC7A90001); + Check(PlateSightRules.Show(in q), "the next landblock"); + } + + private static void IndoorsTheCellList() + { + Case("indoors, no draw stamp: only the cells in the viewer's visible list"); + SightQuery q = InShop(ShopBack); + Check(PlateSightRules.Show(in q), "a room in the list"); + q = InShop(ShopUpstairs, onScreen: false); + Check(PlateSightRules.Show(in q), "a room in the list, off screen"); + q = InShop(NextDoor); + Check(!PlateSightRules.Show(in q), "another building's room: hidden"); + q = InShop(NextDoor, onScreen: false); + Check(!PlateSightRules.Show(in q), "another building's room, pinned to the edge: hidden"); + q = InDungeon(DungeonFar); + Check(!PlateSightRules.Show(in q), "a dungeon room not visible from here: hidden"); + q = InDungeon(DungeonNear); + Check(PlateSightRules.Show(in q), "a dungeon room visible from here: shows"); + } + + private static void IndoorsTheDrawStamp() + { + Case("on screen: AC's draw stamp on the object's room decides"); + SightQuery q = InShop(ShopBack); + q.ObjectCellDrawn = SightFact.No; + Check(!PlateSightRules.Show(in q), "in the list but AC didn't draw it (behind the wall): hidden"); + q.ObjectCellDrawn = SightFact.Yes; + Check(PlateSightRules.Show(in q), "drawn: shows"); + q = InShop(NextDoor); + q.ObjectCellDrawn = SightFact.Yes; + Check(PlateSightRules.Show(in q), "drawn wins over the list (seen out the door and through another)"); + q = InDungeon(DungeonNear); + q.ObjectCellDrawn = SightFact.No; + Check(!PlateSightRules.Show(in q), "the next dungeon room around the corner: hidden"); + + Case("off screen (pinned by Keep on screen): the stamp is ignored, the list decides"); + q = InShop(ShopBack, onScreen: false); + q.ObjectCellDrawn = SightFact.No; // AC skips rooms outside the view + Check(PlateSightRules.Show(in q), "a visible room off to the side keeps its pinned plate"); + q = InShop(NextDoor, onScreen: false); + q.ObjectCellDrawn = SightFact.Yes; + Check(!PlateSightRules.Show(in q), "off screen, not in the list: hidden"); + } + + private static void IndoorsOutdoorObjects() + { + Case("from inside a building that sees outside: outdoor objects need a drawn doorway on screen"); + SightQuery q = InShop(Street); + q.InDoorway = SightFact.Yes; + Check(PlateSightRules.Show(in q), "seen through the door: shows"); + q.InDoorway = SightFact.No; + Check(!PlateSightRules.Show(in q), "behind the shop's wall: hidden"); + q.InDoorway = SightFact.Unknown; + Check(PlateSightRules.Show(in q), "doorways not worked out: shows"); + q = InShop(Street, onScreen: false); + q.InDoorway = SightFact.No; + Check(PlateSightRules.Show(in q), "pinned to the edge: the cell rule (sees outside) shows it"); + } + + private static void DungeonsSeeNothingOutside() + { + Case("from a cell that doesn't see outside, nothing outdoors shows"); + SightQuery q = InDungeon(Street); + Check(!PlateSightRules.Show(in q), "on screen"); + q.InDoorway = SightFact.Yes; + Check(!PlateSightRules.Show(in q), "even with a (stale) doorway answer"); + q = InDungeon(Street, onScreen: false); + Check(!PlateSightRules.Show(in q), "pinned to the edge"); + } + + private static void OutdoorsLookingIntoBuildings() + { + Case("from outdoors, objects inside buildings and dungeons"); + SightQuery q = OnStreet(Shop); + q.ObjectCellDrawn = SightFact.Yes; + Check(PlateSightRules.Show(in q), "the shop's room drawn through its doorway: shows"); + q.ObjectCellDrawn = SightFact.No; + Check(!PlateSightRules.Show(in q), "not drawn (door out of view, walls): hidden"); + q = OnStreet(Shop, onScreen: false); + q.ObjectSeesOutside = SightFact.Yes; + Check(PlateSightRules.Show(in q), "off screen, a room that sees outside: shows"); + q.ObjectSeesOutside = SightFact.No; + Check(!PlateSightRules.Show(in q), "off screen, a sealed room / dungeon: hidden"); + q.ObjectSeesOutside = SightFact.Unknown; + Check(PlateSightRules.Show(in q), "off screen, unknown: shows"); + q = OnStreet(Dungeon); + q.ObjectSeesOutside = SightFact.No; + Check(!PlateSightRules.Show(in q), "a dungeon room below the town, no stamp: hidden"); + } + + private static void CoarseIsTheCellListsOnly() + { + Case("the 4 Hz scan: the cell lists only (no stamp, no doorway)"); + Check(PlateSightRules.ShowCoarse(Shop, Shop, SightFact.Yes, ShopVisible, true, ShopBack), "a visible room"); + Check(!PlateSightRules.ShowCoarse(Shop, Shop, SightFact.Yes, ShopVisible, true, NextDoor), "another building's room"); + Check(PlateSightRules.ShowCoarse(Shop, Shop, SightFact.Yes, ShopVisible, true, Street), "outdoors from a shop that sees outside"); + Check(!PlateSightRules.ShowCoarse(Dungeon, Dungeon, SightFact.No, DungeonVisible, true, Street), "outdoors from a dungeon"); + Check(!PlateSightRules.ShowCoarse(Dungeon, Dungeon, SightFact.No, DungeonVisible, true, DungeonFar), "a dungeon room out of sight"); + Check(PlateSightRules.ShowCoarse(Dungeon, Dungeon, SightFact.No, ReadOnlySpan<uint>.Empty, false, DungeonFar), "list unreadable: shows"); + Check(PlateSightRules.ShowCoarse(Street, Street, SightFact.Yes, ReadOnlySpan<uint>.Empty, true, Shop), "outdoors: a building's room is left to the frame check"); + Check(PlateSightRules.ShowCoarse(0, 0, SightFact.Unknown, ReadOnlySpan<uint>.Empty, false, NextDoor), "no viewer: shows"); + } + + private static void TheReport() + { + // R-20261105-020337-67aa: indoors in cell 0xC6A90161 buying components; NPC and monster labels through walls. + Case("the report: in a town shop, only what can be seen keeps a label"); + SightQuery vendor = InShop(Shop); + Check(PlateSightRules.Show(in vendor), "the vendor in your room"); + SightQuery backRoom = InShop(ShopBack); + backRoom.ObjectCellDrawn = SightFact.Yes; + Check(PlateSightRules.Show(in backRoom), "an NPC in the back room, seen through the inner door"); + SightQuery nextDoor = InShop(NextDoor); + nextDoor.ObjectCellDrawn = SightFact.No; + Check(!PlateSightRules.Show(in nextDoor), "an NPC in the building next door"); + SightQuery behindWall = InShop(Street); + behindWall.InDoorway = SightFact.No; + Check(!PlateSightRules.Show(in behindWall), "a monster in the street behind the shop's wall"); + SightQuery outTheDoor = InShop(Street2); + outTheDoor.InDoorway = SightFact.Yes; + Check(PlateSightRules.Show(in outTheDoor), "an NPC in the street, seen out of the open door"); + } + + private static void Case(string name) + { + _case = name; + Console.WriteLine($"- {name}"); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}"); + } +} diff --git a/tools/PlateSizingTests/Program.cs b/tools/PlateSizingTests/Program.cs index f7d70a6..120ee4c 100644 --- a/tools/PlateSizingTests/Program.cs +++ b/tools/PlateSizingTests/Program.cs @@ -59,6 +59,8 @@ namespace PlateSizingTests HealthRefreshDefaultsOn(); HealthRefreshRoundTripAndClamp(); + HideBehindWallsDefaultsOnAndRoundTrips(); + Console.WriteLine(); Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); Console.WriteLine(_failed == 0 ? "ALL PLATE SIZING TESTS PASSED." : $"{_failed} FAILED."); @@ -588,6 +590,35 @@ namespace PlateSizingTests // ── refresh others' health (HealthProbe) ──────────────────────────── + // ── hide behind walls (2026-11-04, report R-20261105-020337-67aa) ───── + + private static void HideBehindWallsDefaultsOnAndRoundTrips() + { + Case("hide behind walls: on by default and from a file before it; off round-trips; Reset all restores it"); + S.ResetToDefaults(); + Check(S.HideBehindWalls, "on by default (the fixed behaviour)"); + string[] lines = Written(); + Check(lines.Contains("hideBehindWalls=1"), "hideBehindWalls=1 written"); + Check(S.Describe().Contains("hide behind walls on"), "the status line names it"); + string[] old = lines.Where(l => !l.StartsWith("hideBehindWalls=", StringComparison.Ordinal)).ToArray(); + Check(old.Length == lines.Length - 1, "the old file lacks exactly the one key"); + S.HideBehindWalls = false; + S.ResetToDefaults(); // the loader starts from the defaults + S.ApplyLines(old); + Check(S.HideBehindWalls, "on after loading the old file"); + + S.HideBehindWalls = false; + string[] off = Written(); + Check(off.Contains("hideBehindWalls=0"), "hideBehindWalls=0 written"); + S.ResetToDefaults(); + S.ApplyLines(off); + Check(!S.HideBehindWalls, "off after reload"); + Check(off.SequenceEqual(Written()), "identical text after a reload"); + Check(S.Describe().Contains("hide behind walls off"), "the status line says off"); + S.ResetToDefaults(); + Check(S.HideBehindWalls, "Reset all: on"); + } + private static void HealthRefreshDefaultsOn() { Case("refresh others' health: on at 1 s by default, and after loading a file from before it"); diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index 75d8a1c..93b6dc3 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -603,11 +603,11 @@ internal static class Program Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v91 follow: - // eleven slots to v89, then v90's thirteen and v91's two). - var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(26).TakeLast(6).ToArray(); + // eleven slots to v89, then v90's thirteen, v91's two and v93's one). + var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(27).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(26).TakeLast(6).ToArray(); + var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(27).TakeLast(6).ToArray(); Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order"); } @@ -618,6 +618,15 @@ internal static class Program { var all = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray(); var sdkAll = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray(); + // v93: the monster plates' health readings end the table (2026-11-07), right after v91's two. + Check(all.Last() == "GetMonsterHealthFn", "v93 slot last: " + all.Last()); + Check(sdkAll.Last() == "GetMonsterHealthFn", "SDK v93 slot last: " + sdkAll.Last()); + Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("GetMonsterHealthFn"), + (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetMonsterHealthFn"), "GetMonsterHealthFn offset"); + Eq((int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetMonsterHealthFn"), + (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetAmbientLightFn") + IntPtr.Size, "GetMonsterHealthFn right after GetAmbientLightFn"); + all = all.SkipLast(1).ToArray(); + sdkAll = sdkAll.SkipLast(1).ToArray(); // v91: the ambient light floor's two slots end the table (2026-10-27); the checks after these are // on the table before them. string[] v91 = { "SetAmbientLightFloorFn", "GetAmbientLightFn" }; diff --git a/tools/ProblemReportTests/ProblemReportTests.csproj b/tools/ProblemReportTests/ProblemReportTests.csproj index 0c3b7b9..b26c86a 100644 --- a/tools/ProblemReportTests/ProblemReportTests.csproj +++ b/tools/ProblemReportTests/ProblemReportTests.csproj @@ -9,6 +9,9 @@ - the log tail: last N lines, the byte cap (keeps the end, starts at a line), a last line still being written, CRLF, an empty / missing file, the rotated .old topping up a short current log, and reading while another thread keeps appending (as the engine does); + - the per-client log's rotation chain (src\RynthCore.Engine\LogRotation.cs, compiled in): .old is + always the newest, older copies shift to .old.1 ... .old.N-1, the cap and a smaller cap, held + handles (share-delete readers vs an editor without it), and the 7-day pruner's rule; - hiding the account (login) name, the Windows user name (profile paths) and the PC name; - the cooldown arithmetic, the endpoint override rules, and reading the server's answers. Optional: (double dash) server http://127.0.0.1:18097/report posts real bodies to a local copy @@ -27,6 +30,7 @@ <ItemGroup> <Compile Include="..\..\src\RynthCore.Engine\Report\ProblemReportCore.cs" Link="Engine\ProblemReportCore.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\LogRotation.cs" Link="Engine\LogRotation.cs" /> </ItemGroup> </Project> diff --git a/tools/ProblemReportTests/Program.cs b/tools/ProblemReportTests/Program.cs index f8e3baa..9d46032 100644 --- a/tools/ProblemReportTests/Program.cs +++ b/tools/ProblemReportTests/Program.cs @@ -2,6 +2,7 @@ using System.IO.Compression; using System.Net.Http.Headers; using System.Text; using System.Text.Json; +using RynthCore.Engine; using RynthCore.Engine.Report; namespace ProblemReportTests; @@ -30,6 +31,10 @@ internal static class Program TailCrlfAndEdges(); TailTopsUpFromOld(); TailWhileWriting(); + RotationShifts(); + RotationCap(); + RotationHeldHandles(); + RotationPruneRule(); AccountHidden(); Cooldown(); Endpoint(); @@ -292,6 +297,156 @@ internal static class Program Check(!full.IncludesOld, "a full current log doesn't touch .old"); } + // ── Log rotation chain (src\RynthCore.Engine\LogRotation.cs) ──────────── + + private static string RotDir(string name) + { + string dir = Path.Combine(_tmp, name); + Directory.CreateDirectory(dir); + return dir; + } + + private static string? ReadOrNull(string path) => File.Exists(path) ? File.ReadAllText(path) : null; + + private static void RotationShifts() + { + Case("rotation: copies shift down, .old is always the newest"); + string active = Path.Combine(RotDir("rot-shift"), "RynthCore.4242.log"); + for (int gen = 1; gen <= 5; gen++) + { + File.WriteAllText(active, "gen " + gen); + Eq(LogRotation.Rotate(active, 8), LogRotation.Outcome.Moved, $"rotation {gen} moves the live file"); + Check(!File.Exists(active), $"rotation {gen}: the live file is gone (the next line starts a new one)"); + Eq(ReadOrNull(active + ".old"), "gen " + gen, $"rotation {gen}: .old is the newest"); + } + Eq(ReadOrNull(active + ".old.1"), "gen 4", ".old.1 = the one before"); + Eq(ReadOrNull(active + ".old.4"), "gen 1", ".old.4 = the oldest so far"); + Check(!File.Exists(active + ".old.5"), "nothing past what was rotated"); + Eq(LogRotation.CopyPath(active, 0), active + ".old", "copy 0 is .old"); + Eq(LogRotation.CopyPath(active, 3), active + ".old.3", "copy 3 is .old.3"); + + Case("rotation: mtimes stay oldest-last (soak_scorecard sorts by them)"); + DateTime prev = DateTime.MaxValue; + bool ordered = true; + for (int i = 0; i <= 4; i++) + { + string p = LogRotation.CopyPath(active, i); + File.SetLastWriteTime(p, DateTime.Now.AddMinutes(-10 * i)); // as a real run would leave them + } + File.WriteAllText(active, "gen 6"); + LogRotation.Rotate(active, 8); + for (int i = 0; i <= 5; i++) + { + DateTime t = File.GetLastWriteTime(LogRotation.CopyPath(active, i)); + if (t > prev) ordered = false; + prev = t; + } + Check(ordered, "each older copy keeps its older last-write time"); + } + + private static void RotationCap() + { + Case("rotation: the cap drops the oldest"); + string active = Path.Combine(RotDir("rot-cap"), "RynthCore.77.log"); + for (int gen = 1; gen <= 12; gen++) + { + File.WriteAllText(active, "gen " + gen); + LogRotation.Rotate(active, 8); + } + Eq(ReadOrNull(active + ".old"), "gen 12", ".old = newest"); + Eq(ReadOrNull(active + ".old.7"), "gen 5", ".old.7 = oldest kept"); + Check(!File.Exists(active + ".old.8"), "no .old.8 (8 copies: .old + .old.1-.old.7)"); + Eq(Directory.GetFiles(Path.GetDirectoryName(active)!, "RynthCore.77.log.old*").Length, 8, "exactly 8 copies on disk"); + + Case("rotation: a smaller cap trims leftovers from a larger one"); + LogRotation.Rotate(active, 8); // no live file: nothing happens + File.WriteAllText(active, "gen 13"); + Eq(LogRotation.Rotate(active, 3), LogRotation.Outcome.Moved, "rotates"); + Eq(ReadOrNull(active + ".old"), "gen 13", ".old = newest"); + Eq(ReadOrNull(active + ".old.1"), "gen 12", ".old.1"); + Eq(ReadOrNull(active + ".old.2"), "gen 11", ".old.2 = oldest kept"); + Check(!File.Exists(active + ".old.3") && !File.Exists(active + ".old.7"), "everything past .old.2 deleted"); + + Case("rotation: keep 1 is the old behaviour (only .old)"); + File.WriteAllText(active, "gen 14"); + LogRotation.Rotate(active, 1); + Eq(ReadOrNull(active + ".old"), "gen 14", ".old replaced by the newest"); + Eq(Directory.GetFiles(Path.GetDirectoryName(active)!, "RynthCore.77.log.old*").Length, 1, "one copy"); + + Case("rotation: clamps and gaps"); + Eq(LogRotation.ClampKeepCopies(0), 1, "0 -> 1"); + Eq(LogRotation.ClampKeepCopies(-5), 1, "negative -> 1"); + Eq(LogRotation.ClampKeepCopies(500), LogRotation.MaxKeepCopies, "huge -> max"); + Eq(LogRotation.DefaultKeepCopies, 8, "default 8"); + string g = Path.Combine(RotDir("rot-gap"), "RynthCore.5.log"); + File.WriteAllText(g + ".old", "a"); + File.WriteAllText(g + ".old.3", "c"); // .old.1 / .old.2 missing (deleted by hand) + File.WriteAllText(g + ".old.x", "keep me"); // not a numbered copy + File.WriteAllText(g, "live"); + LogRotation.Rotate(g, 8); + Eq(ReadOrNull(g + ".old"), "live", "gap: .old newest"); + Eq(ReadOrNull(g + ".old.1"), "a", "gap: .old -> .old.1"); + Eq(ReadOrNull(g + ".old.4"), "c", "gap: .old.3 -> .old.4"); + Eq(ReadOrNull(g + ".old.x"), "keep me", "a non-numbered name is left alone"); + Eq(LogRotation.Rotate(Path.Combine(_tmp, "rot-gap", "nope.log"), 8), LogRotation.Outcome.Missing, "no live file: Missing"); + } + + private static void RotationHeldHandles() + { + Case("rotation: handles readers hold (share delete) don't stop it"); + string active = Path.Combine(RotDir("rot-held"), "RynthCore.9.log"); + File.WriteAllText(active + ".old", "previous"); + File.WriteAllText(active, "current"); + // The launcher's wedge check and the problem report hold the log open with ReadWrite | Delete. + using (var launcher = new FileStream(active, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + using (var report = new FileStream(active + ".old", FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + { + Eq(LogRotation.Rotate(active, 8), LogRotation.Outcome.Moved, "moved with both held"); + } + Eq(ReadOrNull(active + ".old"), "current", ".old = newest"); + Eq(ReadOrNull(active + ".old.1"), "previous", "the held .old shifted to .old.1"); + + Case("rotation: a .old held without delete sharing falls back like before"); + File.WriteAllText(active, "next"); + using (var editor = new FileStream(active + ".old", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + LogRotation.Outcome o = LogRotation.Rotate(active, 8); + // .old can be neither moved nor deleted, so the live file can't take its name: it is emptied. + Eq(o, LogRotation.Outcome.Truncated, "live file emptied, as the old code did"); + Eq(ReadOrNull(active), "", "live log is empty, not growing"); + } + Eq(ReadOrNull(active + ".old"), "current", "the held .old is untouched"); + Eq(ReadOrNull(active + ".old.2"), "previous", "older copies still shifted"); + } + + private static void RotationPruneRule() + { + Case("prune: names and pids"); + Eq(LogRotation.PidOf("RynthCore.1234.log"), (int?)1234, "live log"); + Eq(LogRotation.PidOf("RynthCore.1234.log.old"), (int?)1234, ".old"); + Eq(LogRotation.PidOf("RynthCore.1234.log.old.7"), (int?)1234, ".old.7"); + Eq(LogRotation.PidOf("RynthCore.log"), (int?)null, "shared log"); + Eq(LogRotation.PidOf("RynthCore.1234.log.bak"), (int?)null, "other suffix"); + Eq(LogRotation.PidOf("RynthCore.abc.log"), (int?)null, "not a pid"); + Eq(LogRotation.PidOf("RynthCore.1234.log.old.x"), (int?)null, "non-numbered copy"); + + Case("prune: what the 7-day pruner deletes"); + DateTime cutoff = new DateTime(2026, 11, 1); + DateTime old = cutoff.AddDays(-1), fresh = cutoff.AddDays(1); + Func<int, bool> live = pid => pid == 500; + const string self = "RynthCore.100.log", shared = "RynthCore.log"; + Check(LogRotation.ShouldPrune("RynthCore.300.log.old.5", self, shared, old, cutoff, live), "a dead client's old .old.5 goes"); + Check(LogRotation.ShouldPrune("RynthCore.300.log", self, shared, old, cutoff, live), "a dead client's old .log goes"); + Check(!LogRotation.ShouldPrune("RynthCore.300.log.old.5", self, shared, fresh, cutoff, live), "a recent copy stays"); + Check(!LogRotation.ShouldPrune("RynthCore.500.log.old.7", self, shared, old, cutoff, live), "a running client's old copy stays"); + Check(!LogRotation.ShouldPrune("RynthCore.500.log", self, shared, old, cutoff, live), "a running client's live log stays"); + Check(!LogRotation.ShouldPrune("RynthCore.100.log", self, shared, old, cutoff, live), "our own live log stays"); + Check(!LogRotation.ShouldPrune("RynthCore.100.log.old.3", self, shared, old, cutoff, live), "our own copies stay"); + Check(LogRotation.ShouldPrune("RynthCore.1000.log.old", self, shared, old, cutoff, live), "pid 1000 isn't pid 100's file"); + Check(!LogRotation.ShouldPrune("RynthCore.log", self, shared, old, cutoff, live), "the shared log stays"); + Check(LogRotation.ShouldPrune("RynthCore.300.log.bak", self, shared, old, cutoff, live), "other names: age alone, as before"); + } + private static void TailWhileWriting() { Case("tail: file being appended to"); diff --git a/tools/RadarSettingsTests/Program.cs b/tools/RadarSettingsTests/Program.cs index 0b8c2e8..7a64b5d 100644 --- a/tools/RadarSettingsTests/Program.cs +++ b/tools/RadarSettingsTests/Program.cs @@ -46,12 +46,14 @@ namespace RadarSettingsTests Run("NameAndSizeFileRoundTrip", () => NameAndSizeFileRoundTrip(root)); Run("StyleKeysClampAndIgnore", StyleKeysClampAndIgnore); Run("WorldMapBackdropSettings", () => WorldMapBackdropSettings(root)); + Run("RangeRings", () => RangeRings(root)); // after FileRoundTrip: a file from before keeps the defaults Run("RoundRadarAndClipping", () => RoundRadarAndClipping(root)); Run("ClickThroughWheelZoom", () => ClickThroughWheelZoom(root)); Run("SelectionSettingsSave", () => SelectionSettingsSave(root)); Run("WhichMarkerIsSelected", WhichMarkerIsSelected); Run("SelectionEdgeArrow", SelectionEdgeArrow); Run("SelectionLabelPlacement", SelectionLabelPlacement); + Run("ClickThroughDotPressNeverMoves", ClickThroughDotPressNeverMoves); } finally { @@ -248,6 +250,47 @@ namespace RadarSettingsTests Check(!st.TryLoad("color.monster", "FFFF0000"), "colour keys are not ours"); Check(!st.TryLoad("zoom", "2"), "plain keys are not ours"); } + // The range rings (2026-11-06): Monster Range on and Ring Range off by default, a settings file + // from before (FileRoundTrip's, no ring lines) leaves them so, both save under their keys, and + // the ring is range x zoom pixels round you, drawn only while some of it is on the picture. + private static void RangeRings(string root) + { + Check(RadarSettingsStore.ShowMonsterRangeRing, "Monster Range ring on by default (and after loading an older file)"); + Check(!RadarSettingsStore.ShowRingRangeRing, "Ring Range ring off by default"); + string saved = Path.Combine(root, "rings.txt"); + Environment.SetEnvironmentVariable("RYNTHCORE_RADAR_SETTINGS", saved); + RadarSettingsStore.ShowMonsterRangeRing = false; + RadarSettingsStore.ShowRingRangeRing = true; + RadarSettingsStore.Save(); + string text = File.ReadAllText(saved).Replace("\r\n", "\n"); + Check(text.Contains("monsterRangeRing=0\n"), "saved monsterRangeRing=0"); + Check(text.Contains("ringRangeRing=1\n"), "saved ringRangeRing=1"); + RadarSettingsStore.ShowMonsterRangeRing = true; + RadarSettingsStore.ShowRingRangeRing = false; + RadarSettingsStore.Save(); + text = File.ReadAllText(saved).Replace("\r\n", "\n"); + Check(text.Contains("monsterRangeRing=1\n") && text.Contains("ringRangeRing=0\n"), "saved the defaults back"); + + Check(RadarRangeRing.RadiusPx(50, 1.5f) == 75f, "50 yd at 1.5 px/yd: 75 px"); + Check(RadarRangeRing.RadiusPx(5, 6f) == 30f, "5 yd at the closest zoom: 30 px"); + Check(RadarRangeRing.RadiusPx(50, 0.1f) == 25f, "zoom under 0.5 counts as 0.5, as the projection"); + Check(RadarRangeRing.RadiusPx(50, float.NaN) == 25f, "a NaN zoom counts as 0.5"); + Check(RadarRangeRing.RadiusPx(0, 2f) == 0f && RadarRangeRing.RadiusPx(-3, 2f) == 0f, "no range: no ring"); + Check(RadarRangeRing.RadiusPx(double.NaN, 2f) == 0f, "a NaN range: no ring"); + + var min = new System.Numerics.Vector2(100, 100); + var max = new System.Numerics.Vector2(300, 300); + var mid = new System.Numerics.Vector2(200, 200); + Check(RadarRangeRing.Shows(75f, mid, min, max, null), "inside the square"); + Check(RadarRangeRing.Shows(120f, mid, min, max, null), "past the sides, the corners still cross it"); + Check(!RadarRangeRing.Shows(142f, mid, min, max, null), "past the corners (141.4 px): nothing to draw"); + Check(!RadarRangeRing.Shows(3f, mid, min, max, null), "too small to draw"); + Check(!RadarRangeRing.Shows(float.NaN, mid, min, max, null), "NaN radius: nothing"); + var circle = new RoundMask(mid, 100); + Check(RadarRangeRing.Shows(100f, mid, min, max, circle), "round: on the edge"); + Check(!RadarRangeRing.Shows(101f, mid, min, max, circle), "round: past the circle, nothing to draw"); + } + // The world map backdrop: off by default, and its switch and strength save under their keys. private static void WorldMapBackdropSettings(string root) { @@ -270,6 +313,25 @@ namespace RadarSettingsTests // The round radar: the setting saves, and the geometry cuts shapes to the circle. // Docked click-through with "Mouse wheel still zooms" (2026-10-29): the wheel over the radar is // the radar's, everywhere else and in every other case it stays the game's. + // 2026-11-04 (Discord): with click-through on, holding on a dot moved the radar. A press may move + // it only with click-through off, Ctrl held when it began, or popped out; decided at the press. + private static void ClickThroughDotPressNeverMoves() + { + Check(RadarDrag.PressMoves(false, false, false), "click-through off: a press drags"); + Check(!RadarDrag.PressMoves(true, false, false), "click-through on, no Ctrl (a dot press): stays put"); + Check(RadarDrag.PressMoves(true, true, false), "click-through on, Ctrl held: drags"); + Check(RadarDrag.PressMoves(true, false, true), "popped out: always interactive, drags"); + + var d = new RadarDrag(); + Check(d.Update(false, true, false, false), "no press yet: nothing to stop (the item isn't active)"); + Check(!d.Update(true, true, false, false), "dot press under click-through: no move"); + Check(!d.Update(false, true, true, false), "Ctrl pressed mid-hold: still no move"); + Check(!d.Update(false, false, false, false), "click-through switched off mid-hold: still no move"); + Check(d.Update(true, true, true, false), "next press with Ctrl: moves"); + Check(d.Update(false, true, false, false), "Ctrl let go mid-drag: keeps moving"); + Check(d.Update(true, false, false, false), "click-through off: moves"); + } + private static void ClickThroughWheelZoom(string root) { Check(!RadarSettingsStore.ClickThroughWheelZoom, "off by default"); diff --git a/tools/RadarSettingsTests/RadarSettingsTests.csproj b/tools/RadarSettingsTests/RadarSettingsTests.csproj index a0b45ff..d841018 100644 --- a/tools/RadarSettingsTests/RadarSettingsTests.csproj +++ b/tools/RadarSettingsTests/RadarSettingsTests.csproj @@ -1,14 +1,16 @@ <Project Sdk="Microsoft.NET.Sdk"> <!-- - Offline checks for the radar's per-kind show boxes (RadarSettingsStore.ShowFlag / ShowKind) + Offline checks for the radar's range rings (RadarRangeRing.cs: their boxes, defaults, file keys, + and the ring's radius, range x zoom, and when it shows), and for the radar's per-kind show boxes (RadarSettingsStore.ShowFlag / ShowKind) the marker kinds (RadarKind) the RynthAi snapshot sends, and the per-kind marker size / name label settings (MarkerStyleSettings). src\RynthCore.Engine\UI\Panels\ RadarSettingsStore.cs and UI\Data\RadarSnapshotJson.cs are compiled in, with a synchronous UiBackgroundWriter stub. Every kind must have its own box, Corpses off must hide your corpses too, unknown kinds stay hidden, a plugin-shaped snapshot filters per box, and every box must round-trip through the settings file. The selected-object highlight (RadarSelection.cs): which - marker is the selected one, when it clears, the edge arrow and label maths, and its settings. Uses RYNTHCORE_RADAR_SETTINGS (temp files); never + marker is the selected one, when it clears, the edge arrow and label maths, and its settings. Which + presses may move the radar (RadarDrag.cs: never a dot press under click-through without Ctrl). Uses RYNTHCORE_RADAR_SETTINGS (temp files); never touches %LOCALAPPDATA%\RynthCore. Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> @@ -25,9 +27,11 @@ <Compile Include="..\..\src\RynthCore.Engine\UI\Panels\RadarSettingsStore.cs" Link="Engine\RadarSettingsStore.cs" /> <Compile Include="..\..\src\RynthCore.Engine\UI\Data\RadarSnapshotJson.cs" Link="Engine\RadarSnapshotJson.cs" /> <Compile Include="..\..\src\RynthCore.Engine\UI\Panels\MarkerStyleSettings.cs" Link="Engine\MarkerStyleSettings.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\RadarRangeRing.cs" Link="Engine\RadarRangeRing.cs" /> <Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\CircleClip.cs" Link="Engine\CircleClip.cs" /> <Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\RadarWheel.cs" Link="Engine\RadarWheel.cs" /> <Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\RadarSelection.cs" Link="Engine\RadarSelection.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\RadarDrag.cs" Link="Engine\RadarDrag.cs" /> </ItemGroup> </Project> diff --git a/tools/SelfPlateTests/Program.cs b/tools/SelfPlateTests/Program.cs index 62cf066..0dac8b5 100644 --- a/tools/SelfPlateTests/Program.cs +++ b/tools/SelfPlateTests/Program.cs @@ -42,6 +42,9 @@ namespace SelfPlateTests TicksAndDuration(); CategoryZeroStandsAlone(); ShortArraysAndHugeExpiry(); + IconsCarryTheirSpells(); + AddSpellLimits(); + TooltipText(); SelfIconSizeSetting(); SelfPlateAt100IsTheOldPlate(); @@ -338,6 +341,61 @@ namespace SelfPlateTests Check(c == 2, "an empty destination still counts"); } + // ── Hover tooltip (2026-11-07) ─────────────────────────────────────── + + private static uint[] Spells(DebuffIcon ic) + { + var s = new uint[ic.SpellCount]; + for (int i = 0; i < s.Length; i++) s[i] = ic.SpellAt(i); + return s; + } + + private static void IconsCarryTheirSpells() + { + Case("each icon carries the spell heading each category it merges (the tooltip names them)"); + int c = Run(new[] { new E(3, 80, 2), new E(4, 25, 4), new E(2, 30, 110) }, out var ic); + Check(c == 2, $"two icons (got {c})"); + Check(ic[0].Kind == DebuffKind.VulnFire && Spells(ic[0]).SequenceEqual(new uint[] { 2 }), "fire vuln: spell 2 (" + string.Join(",", Spells(ic[0])) + ")"); + Check(ic[1].Kind == DebuffKind.Attributes && Spells(ic[1]).OrderBy(x => x).SequenceEqual(new uint[] { 3, 4 }), + "attributes: spells 3 and 4 (" + string.Join(",", Spells(ic[1])) + ")"); + c = Run(new[] { new E(1, 20, 116), new E(10, 50, 116) }, out ic); + Check(c == 1 && Spells(ic[0]).SequenceEqual(new uint[] { 10 }), "one category: the spell that lasts longest (10)"); + Run(new[] { new E(100, 600, 50), new E(0x8001, 30, 0) }, out ic); + Check(ic[0].SpellCount == 0, "no icon, no spells"); + } + + private static void AddSpellLimits() + { + Case("AddSpell: skips 0 and repeats, holds at most MaxSpells"); + var ic = new DebuffIcon(); + ic.AddSpell(0); ic.AddSpell(7); ic.AddSpell(7); + Check(ic.SpellCount == 1 && ic.SpellAt(0) == 7, "0 and the repeat skipped"); + for (uint s = 20; s < 30; s++) ic.AddSpell(s); + Check(ic.SpellCount == DebuffIcon.MaxSpells, $"capped at {DebuffIcon.MaxSpells} (got {ic.SpellCount})"); + Check(Spells(ic).SequenceEqual(new uint[] { 7, 20, 21, 22 }), "first ones kept: " + string.Join(",", Spells(ic))); + Check(ic.SpellAt(-1) == 0 && ic.SpellAt(9) == 0, "out of range reads 0"); + } + + private static void TooltipText() + { + Case("tooltip wording: kind, what it does, the spells, when the first ends"); + string t = DebuffTip.Text(DebuffKind.VulnFire, new[] { "Fire Vulnerability Other VII" }, 1, 83, estimated: true, self: false); + Check(t == "Fire vulnerability\nTakes more fire damage.\n Fire Vulnerability Other VII\nEnds in about 1:23", "monster fire vuln:\n" + t); + t = DebuffTip.Text(DebuffKind.VulnFire, new[] { "Fire Vulnerability Other VII" }, 1, 42, estimated: false, self: true); + Check(t.Contains("You take more fire damage.") && t.EndsWith("Ends in 42 s"), "yours: 'You take', exact time:\n" + t); + t = DebuffTip.Text(DebuffKind.Attributes, new[] { "Weakness Other VII", "Feeblemind Other VII" }, 6, 30, true, false); + Check(t.Contains("\n Weakness Other VII\n Feeblemind Other VII\n and 4 more\n") && t.EndsWith("First one ends in about 30 s"), + "stack of 6, two names known:\n" + t); + t = DebuffTip.Text(DebuffKind.Imperil, Array.Empty<string>(), 1, 0, true, false); + Check(t == "Imperil\nArmor lowered: physical hits land harder.", "no names (spell table not loaded), no time:\n" + t); + foreach (DebuffKind k in Enum.GetValues<DebuffKind>()) + Check(DebuffTip.Title(k).Length > 0 && DebuffTip.Effect(k, false).Length > 0 && DebuffTip.Effect(k, true).Length > 0, $"{k} has words"); + Check(DebuffTip.Time(0.2) == "1 s" && DebuffTip.Time(58.5) == "59 s" && DebuffTip.Time(59.5) == "1:00" && DebuffTip.Time(3725) == "1:02:05", + $"times: {DebuffTip.Time(0.2)} {DebuffTip.Time(58.5)} {DebuffTip.Time(59.5)} {DebuffTip.Time(3725)}"); + Check(DebuffTip.More(1) == "1 more debuff than fits in the row." && DebuffTip.More(3) == "3 more debuffs than fit in the row.", "+N wording"); + Check(DebuffTip.Others.StartsWith("Debuffed by someone else\n"), "others marker wording"); + } + // ── Your debuff icon size (2026-10-28) ────────────────────────────── private static void SelfIconSizeSetting() diff --git a/tools/SelfPlateTests/SelfPlateTests.csproj b/tools/SelfPlateTests/SelfPlateTests.csproj index 4efdf4c..ad409ad 100644 --- a/tools/SelfPlateTests/SelfPlateTests.csproj +++ b/tools/SelfPlateTests/SelfPlateTests.csproj @@ -31,6 +31,7 @@ <Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\HealthProbe.cs" Link="Engine\HealthProbe.cs" /> <Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\DebuffIcon.cs" Link="Engine\DebuffIcon.cs" /> <Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\SelfDebuffs.cs" Link="Engine\SelfDebuffs.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\DebuffTip.cs" Link="Engine\DebuffTip.cs" /> <Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\PlateMetrics.cs" Link="Engine\PlateMetrics.cs" /> <Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\VitalLoss.cs" Link="Engine\VitalLoss.cs" /> </ItemGroup> diff --git a/tools/plate_sight_check.py b/tools/plate_sight_check.py new file mode 100644 index 0000000..39c1e78 --- /dev/null +++ b/tools/plate_sight_check.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +""" +Offline check of the AC facts behind the nameplates' "behind walls" rule +(src/RynthCore.Engine/Compatibility/AcCellSight.cs, 2026-11-04, problem report +R-20261105-020337-67aa) against an acclient.exe. Read-only: maps the file, runs nothing. + +pe_pattern.py CHECK already proves the embedded CEnvCell::GetDrawnThisFrame pattern is +unique and lands on its VA. This checks the layout the engine reads, so a different +client build fails here instead of hiding plates in game: + + * CEnvCell::GetDrawnThisFrame compares cell+0x130 with [device global]+0xB0, and + SetDrawnThisFrame writes that stamp to cell+0x130 (the same global); + * PView::DrawCells adds 1 to [global]+0xB0 before it draws, RenderDeviceD3D::Flip + adds 1 to its own +0xB0, and DrawEnvCell marks the cell before drawing it; + * CPhysicsObj::enter_cell stores the cell at +0x90 and the cell's +0x28 id at +0x4C; + * SmartBox::RenderNormalMode reads the viewer cell id at +0x0C and the viewer cell's + seen_outside through [+0x50]+0xE8; + * PView::DrawInside hands the cell's +0xE0 / +0xE4 (visible-cell list) to add_views; + * PView::ClipPortals walks the portal count at +0x108 and the array at +0x10C; + * D3DPolyRender::DrawPortalPolyInternal reads the polygon's point count at +0x0E; + * CCellPortal::UnPack stores 0xFFFFFFFF as the other cell of a doorway to outside; + * CEnvCell::UnPack stores seen_outside (flags & 1) at +0xE8 (this-0x30 frame: +0xB8). + +Usage: python tools/plate_sight_check.py ["<path-to-acclient.exe>"] +Exit 0 = every check passed. +""" +import os +import struct +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from pe_pattern import read_window, matches # noqa: E402 + +DEFAULT_CLIENT = r"C:\Turbine\Asheron's Call\acclient.exe" +N = None + +fails = 0 + + +def check(ok, msg): + global fails + print(("ok " if ok else "FAIL ") + msg) + if not ok: + fails += 1 + + +def main(): + path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_CLIENT + if not os.path.exists(path): + print(f"acclient.exe not found: {path}") + return 2 + W, BASE = read_window(path) + + def at(va, n): + o = va - BASE + return W[o:o + n] + + def body_has(va, needle, span=0x200): + return W.find(bytes(needle), va - BASE, va - BASE + span) >= 0 + + # CEnvCell::GetDrawnThisFrame: mov eax,[ecx+130h]; mov ecx,[global]; cmp eax,[ecx+0B0h]; sete al; ret + pat = [0x8B, 0x81, 0x30, 0x01, 0x00, 0x00, 0x8B, 0x0D, N, N, N, N, + 0x3B, 0x81, 0xB0, 0x00, 0x00, 0x00, 0x0F, 0x94, 0xC0, 0xC3] + ms = matches(W, pat, limit=4) + check(len(ms) == 1, f"GetDrawnThisFrame pattern unique ({len(ms)} match)") + if len(ms) != 1: + return 1 + get_drawn = BASE + ms[0] + g = struct.unpack_from("<I", W, ms[0] + 8)[0] + print(f" GetDrawnThisFrame @ 0x{get_drawn:08X}, render device global 0x{g:08X}") + gb = list(struct.pack("<I", g)) + + # SetDrawnThisFrame (right after it): mov eax,[global]; mov edx,[eax+0B0h]; mov [ecx+130h],edx; ret + set_drawn = get_drawn + 0x20 + check(at(set_drawn, 18) == bytes([0xA1] + gb + [0x8B, 0x90, 0xB0, 0, 0, 0, 0x89, 0x91, 0x30, 0x01, 0, 0, 0xC3]), + f"SetDrawnThisFrame @ 0x{set_drawn:08X} writes [global]+0xB0 to cell+0x130") + + # CPhysicsPart's twin reads +0DCh from the same global (proves the stamp is the device's, shared). + twin = [0x8B, 0x81, 0xDC, 0x00, 0x00, 0x00, 0x8B, 0x0D] + gb + [0x3B, 0x81, 0xB0, 0, 0, 0, 0x0F, 0x94, 0xC0, 0xC3] + check(len(matches(W, twin, limit=4)) == 1, "CPhysicsPart::GetDrawnThisFrame compares the same device stamp") + + # PView::DrawCells: mov eax,[global]; mov ecx,[eax+0B0h]; add esp,4; inc ecx; mov [eax+0B0h],ecx + draw_cells = 0x005A5950 + check(body_has(draw_cells, [0xA1] + gb + [0x8B, 0x88, 0xB0, 0, 0, 0, 0x83, 0xC4, 0x04, 0x41, 0x89, 0x88, 0xB0, 0, 0, 0], 0x80), + "PView::DrawCells adds 1 to the device stamp before drawing") + # DrawEnvCell: mov esi,[esp+8]; mov ecx,esi; call GetDrawnThisFrame; test al,al; jnz; mov ecx,esi; call SetDrawnThisFrame + dec = 0x005A0280 + ok = at(dec, 7) == bytes([0x56, 0x8B, 0x74, 0x24, 0x08, 0x8B, 0xCE]) and at(dec + 7, 1) == b"\xE8" + rel1 = struct.unpack_from("<i", W, dec + 8 - BASE)[0] + rel2 = struct.unpack_from("<i", W, dec + 0x17 - BASE)[0] + check(ok and dec + 12 + rel1 == get_drawn and dec + 0x1B + rel2 == set_drawn, + "DrawEnvCell tests GetDrawnThisFrame and calls SetDrawnThisFrame before drawing") + # Flip, after Present: mov eax,[esi+0B0h]; inc eax; pop edi; mov [esi+0B0h],eax (the device's own stamp) + flip = 0x005A0F60 + check(body_has(flip, [0x8B, 0x86, 0xB0, 0, 0, 0, 0x40, 0x5F, 0x89, 0x86, 0xB0, 0, 0, 0], 0x100), + "RenderDeviceD3D::Flip adds 1 to +0xB0") + + # CPhysicsObj::enter_cell: mov eax,[ebx+28h]; mov [esi+4Ch],eax ... mov [esi+90h],ebx + ec = 0x005119A0 + check(body_has(ec, [0x8B, 0x43, 0x28, 0x89, 0x46, 0x4C], 0x80) and body_has(ec, [0x89, 0x9E, 0x90, 0x00, 0x00, 0x00], 0x90), + "CPhysicsObj::enter_cell: cell id from cell+0x28 to +0x4C, cell pointer to +0x90") + + # SmartBox::RenderNormalMode: mov ecx,[esi+0Ch] (viewer cell id) ... mov edx,[esi+50h]; mov ecx,[edx+0E8h] + rnm = 0x00453B40 + check(body_has(rnm, [0x8B, 0x4E, 0x0C], 0x40) and body_has(rnm, [0x8B, 0x56, 0x50, 0x8B, 0x8A, 0xE8, 0, 0, 0], 0x60), + "SmartBox::RenderNormalMode: viewer cell id +0x0C, viewer cell +0x50, its seen_outside +0xE8") + + # PView::DrawInside: mov eax,[esi+0E4h]; xor ecx,ecx; mov cx,[esi+0E0h] (add_views' arguments) + di = 0x005A6970 + check(body_has(di, [0x8B, 0x86, 0xE4, 0, 0, 0, 0x33, 0xC9, 0x66, 0x8B, 0x8E, 0xE0, 0, 0, 0], 0x80), + "PView::DrawInside hands the visible-cell list (+0xE0 count, +0xE4 ids) to add_views") + + # PView::ClipPortals: mov ecx,[ebp+108h] (portal count) ... mov esi,[ebp+10Ch] (portal array) + cp = 0x005A6630 + check(body_has(cp, [0x8B, 0x8D, 0x08, 0x01, 0, 0], 0x40) and body_has(cp, [0x8B, 0xB5, 0x0C, 0x01, 0, 0], 0x80), + "PView::ClipPortals: portal count +0x108, CCellPortal array +0x10C") + + # D3DPolyRender::DrawPortalPolyInternal: mov al,[ebp+0Eh] (point count); mov eax,[ebp+0]; mov ecx,[eax+esi*4] + dp = 0x0059CCA0 + check(body_has(dp, [0x8A, 0x45, 0x0E], 0x40) and body_has(dp, [0x8B, 0x45, 0x00, 0x8B, 0x0C, 0xB0, 0xD9, 0x01], 0x60), + "DrawPortalPolyInternal: CPolygon point count byte +0x0E, CVertex* array at +0, x first") + + # CCellPortal::UnPack: test dl,4; ... mov dword [esi],0FFFFFFFFh (a doorway to the outside) + cu = 0x0053C810 + check(body_has(cu, [0xF6, 0xC2, 0x04], 0x60) and body_has(cu, [0xC7, 0x06, 0xFF, 0xFF, 0xFF, 0xFF], 0x60), + "CCellPortal::UnPack: a doorway to outside has other cell 0xFFFFFFFF") + + # CEnvCell::UnPack: and ecx,1; mov [esi+0B8h],ecx (this-0x30: +0xE8 seen_outside) + eu = 0x0052E0D0 + check(body_has(eu, [0x83, 0xE1, 0x01, 0x89, 0x8E, 0xB8, 0, 0, 0], 0x40), + "CEnvCell::UnPack stores seen_outside (flags & 1) at +0xE8") + + print() + print("PASS" if fails == 0 else f"{fails} FAILED") + return 0 if fails == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/soak_scorecard.py b/tools/soak_scorecard.py index 331071d..1eaf65f 100644 --- a/tools/soak_scorecard.py +++ b/tools/soak_scorecard.py @@ -62,9 +62,11 @@ def _secs(line: str): def pid_log_groups(): """Map pid -> [its log files sorted oldest-first], covering rotations - (RynthCore.<pid>.log plus .log.old / .log.N). The engine rotates at ~5 MB: - right after a rotation the live .log is a tiny fragment and the soak's - history is in .log.old, so scoring only .log would miss the whole run. + (RynthCore.<pid>.log plus .log.old and the older .log.old.1 ... .log.old.N, + LogRotation.cs). The engine rotates at ~5 MB: right after a rotation the + live .log is a tiny fragment and the soak's history is in the .old copies, + so scoring only .log would miss the whole run. Rotation keeps each copy's + last-write time, so sorting by mtime puts them in order. Each pid is analyzed over its concatenated files in chronological order.""" groups = {} for f in glob.glob(os.path.join(LOG_DIR, "RynthCore.*.log*")):