RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:27 -04:00
commit a24ed6df7c
322 changed files with 83009 additions and 7504 deletions

View file

@ -0,0 +1,296 @@
// ============================================================================
// RynthCore.Engine - ImGui/CodeEditor.cs
// A syntax-coloured source editor for ImGui faces: ImGuiColorTextEdit
// compiled into our cimgui.dll (native/cimgui/rynth_textedit_ext.cpp),
// called through function pointers resolved from that module.
//
// AC's render thread only, inside the ImGui frame. The native editor is
// created on the first Render (it reads the ImGui style) and destroyed by
// Dispose. Text crosses the boundary only on SetText/GetText, never per
// frame: IsDirty compares the editor's change counter, so a 50 KB meta costs
// nothing while it is being typed in.
// ============================================================================
using System;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
namespace RynthCore.Engine.ImGuiBackend;
internal enum CodeLanguage { None = 0, Meta = 1, Lua = 2 }
internal sealed unsafe class CodeEditor : IDisposable
{
// ── Exports ────────────────────────────────────────────────────────────
private static bool _resolved, _available;
private static delegate* unmanaged[Cdecl]<IntPtr> _create;
private static delegate* unmanaged[Cdecl]<IntPtr, void> _destroy;
private static delegate* unmanaged[Cdecl]<byte*, byte*, byte*, void> _setMetaVocabulary;
private static delegate* unmanaged[Cdecl]<IntPtr, int, void> _setLanguage;
private static delegate* unmanaged[Cdecl]<IntPtr, uint*, int, void> _setPalette;
private static delegate* unmanaged[Cdecl]<IntPtr, int, int, int, int, void> _setOptions;
private static delegate* unmanaged[Cdecl]<IntPtr, byte*, void> _setText;
private static delegate* unmanaged[Cdecl]<IntPtr, int*, byte*> _getText;
private static delegate* unmanaged[Cdecl]<IntPtr, uint> _getChangeCount;
private static delegate* unmanaged[Cdecl]<IntPtr, byte*, float, float, int, int> _render;
private static delegate* unmanaged[Cdecl]<IntPtr, int*, int*, void> _getCursor;
private static delegate* unmanaged[Cdecl]<IntPtr, int, int, void> _setCursor;
private static delegate* unmanaged[Cdecl]<IntPtr, float*, float*, void> _getCursorScreenPos;
private static delegate* unmanaged[Cdecl]<IntPtr, int*, byte*> _getLinePrefix;
private static delegate* unmanaged[Cdecl]<IntPtr, int, byte*, void> _replaceBeforeCursor;
private static delegate* unmanaged[Cdecl]<IntPtr, int, void> _setCompletionKeysHeld;
private static delegate* unmanaged[Cdecl]<IntPtr, void> _requestFocus;
/// <summary>False when the loaded cimgui.dll was built without the editor.</summary>
public static bool Available
{
get
{
if (!_resolved) Resolve();
return _available;
}
}
private static void Resolve()
{
_resolved = true;
IntPtr module = EntryPoint.ImGuiNativeHandle;
if (module == IntPtr.Zero) return;
IntPtr Get(string name) => NativeLibrary.TryGetExport(module, name, out IntPtr p) ? p : IntPtr.Zero;
_create = (delegate* unmanaged[Cdecl]<IntPtr>)Get("RynthTE_Create");
_destroy = (delegate* unmanaged[Cdecl]<IntPtr, void>)Get("RynthTE_Destroy");
_setMetaVocabulary = (delegate* unmanaged[Cdecl]<byte*, byte*, byte*, void>)Get("RynthTE_SetMetaVocabulary");
_setLanguage = (delegate* unmanaged[Cdecl]<IntPtr, int, void>)Get("RynthTE_SetLanguage");
_setPalette = (delegate* unmanaged[Cdecl]<IntPtr, uint*, int, void>)Get("RynthTE_SetPalette");
_setOptions = (delegate* unmanaged[Cdecl]<IntPtr, int, int, int, int, void>)Get("RynthTE_SetOptions");
_setText = (delegate* unmanaged[Cdecl]<IntPtr, byte*, void>)Get("RynthTE_SetText");
_getText = (delegate* unmanaged[Cdecl]<IntPtr, int*, byte*>)Get("RynthTE_GetText");
_getChangeCount = (delegate* unmanaged[Cdecl]<IntPtr, uint>)Get("RynthTE_GetChangeCount");
_render = (delegate* unmanaged[Cdecl]<IntPtr, byte*, float, float, int, int>)Get("RynthTE_Render");
_getCursor = (delegate* unmanaged[Cdecl]<IntPtr, int*, int*, void>)Get("RynthTE_GetCursor");
_setCursor = (delegate* unmanaged[Cdecl]<IntPtr, int, int, void>)Get("RynthTE_SetCursor");
_getCursorScreenPos = (delegate* unmanaged[Cdecl]<IntPtr, float*, float*, void>)Get("RynthTE_GetCursorScreenPos");
_getLinePrefix = (delegate* unmanaged[Cdecl]<IntPtr, int*, byte*>)Get("RynthTE_GetLinePrefix");
_replaceBeforeCursor = (delegate* unmanaged[Cdecl]<IntPtr, int, byte*, void>)Get("RynthTE_ReplaceBeforeCursor");
_setCompletionKeysHeld = (delegate* unmanaged[Cdecl]<IntPtr, int, void>)Get("RynthTE_SetCompletionKeysHeld");
_requestFocus = (delegate* unmanaged[Cdecl]<IntPtr, void>)Get("RynthTE_RequestFocus");
_available = _create != null && _destroy != null && _setMetaVocabulary != null && _setLanguage != null
&& _setPalette != null && _setOptions != null && _setText != null && _getText != null
&& _getChangeCount != null && _render != null && _getCursor != null && _setCursor != null
&& _getCursorScreenPos != null && _getLinePrefix != null && _replaceBeforeCursor != null
&& _setCompletionKeysHeld != null && _requestFocus != null;
if (!_available)
RynthLog.UI("CodeEditor: this cimgui.dll has no RynthTE_* exports; ImGui source editors are unavailable.");
}
private static bool _vocabularySet;
/// <summary>The Meta language's keywords (all Meta editors share them). Set once.</summary>
public static void SetMetaVocabulary(string[] structWords, string[] conditionWords, string[] actionWords)
{
if (_vocabularySet || !Available) return;
_vocabularySet = true;
byte[] s = Utf8Z(string.Join('\n', structWords));
byte[] c = Utf8Z(string.Join('\n', conditionWords));
byte[] a = Utf8Z(string.Join('\n', actionWords));
fixed (byte* ps = s, pc = c, pa = a)
_setMetaVocabulary(ps, pc, pa);
}
// ── Instance ───────────────────────────────────────────────────────────
private IntPtr _handle;
private readonly byte[] _id;
private readonly CodeLanguage _language;
private readonly uint[] _palette;
private string? _pendingText;
private uint _cleanCount;
private bool _held;
/// <param name="palette">ImGui colours (ABGR) in ImGuiColorTextEdit's PaletteIndex order.</param>
public CodeEditor(string id, CodeLanguage language, uint[] palette)
{
_id = Utf8Z(id);
_language = language;
_palette = palette;
}
public bool Created => _handle != IntPtr.Zero;
private bool Ensure()
{
if (_handle != IntPtr.Zero) return true;
if (!Available) return false;
_handle = _create();
if (_handle == IntPtr.Zero) return false;
_setLanguage(_handle, (int)_language);
fixed (uint* p = _palette)
_setPalette(_handle, p, _palette.Length);
_setOptions(_handle, 0, 0, 1, 4);
SetTextNow(_pendingText ?? string.Empty);
_pendingText = null;
return true;
}
/// <summary>Replaces the text (and the undo history); the editor is clean afterwards.</summary>
public void SetText(string text)
{
if (_handle == IntPtr.Zero) { _pendingText = text; return; }
SetTextNow(text);
}
private void SetTextNow(string text)
{
byte[] bytes = Utf8Z(text);
fixed (byte* p = bytes)
_setText(_handle, p);
_cleanCount = _getChangeCount(_handle);
}
public string GetText()
{
if (_handle == IntPtr.Zero) return _pendingText ?? string.Empty;
int len;
byte* p = _getText(_handle, &len);
return len <= 0 ? string.Empty : Encoding.UTF8.GetString(p, len);
}
/// <summary>Counts text changes (edits, undo, redo, SetText).</summary>
public uint ChangeCount => _handle == IntPtr.Zero ? 0 : _getChangeCount(_handle);
/// <summary>Edited since the last SetText or MarkClean.</summary>
public bool IsDirty => _handle != IntPtr.Zero && _getChangeCount(_handle) != _cleanCount;
public void MarkClean()
{
if (_handle != IntPtr.Zero) _cleanCount = _getChangeCount(_handle);
}
/// <summary>Draws the editor as a child window of <paramref name="size"/>; returns whether it has keyboard focus.</summary>
public bool Render(Vector2 size)
{
if (!Ensure()) return false;
fixed (byte* id = _id)
return _render(_handle, id, size.X, size.Y, 1) != 0;
}
/// <summary>Zero-based line and (tab-expanded) column of the cursor.</summary>
public (int Line, int Column) Cursor
{
get
{
if (_handle == IntPtr.Zero) return (0, 0);
int line, column;
_getCursor(_handle, &line, &column);
return (line, column);
}
}
public void SetCursor(int line, int charIndex)
{
if (_handle != IntPtr.Zero) _setCursor(_handle, line, charIndex);
}
/// <summary>Screen position of the bottom-left corner of the cursor's cell (after Render).</summary>
public Vector2 CursorScreenPos
{
get
{
if (_handle == IntPtr.Zero) return Vector2.Zero;
float x, y;
_getCursorScreenPos(_handle, &x, &y);
return new Vector2(x, y);
}
}
/// <summary>The cursor's line up to the cursor.</summary>
public string LinePrefix()
{
if (_handle == IntPtr.Zero) return string.Empty;
int len;
byte* p = _getLinePrefix(_handle, &len);
return len <= 0 ? string.Empty : Encoding.UTF8.GetString(p, len);
}
/// <summary>Replaces the <paramref name="bytes"/> UTF-8 bytes before the cursor with <paramref name="text"/> (one undo step).</summary>
public void ReplaceBeforeCursor(int bytes, string text)
{
if (_handle == IntPtr.Zero) return;
byte[] t = Utf8Z(text);
fixed (byte* p = t)
_replaceBeforeCursor(_handle, bytes, p);
}
/// <summary>While true the editor leaves Up/Down/PageUp/PageDown/Enter/Tab/Escape to a completion list.</summary>
public bool CompletionKeysHeld
{
get => _held;
set
{
if (_held == value || _handle == IntPtr.Zero) return;
_held = value;
_setCompletionKeysHeld(_handle, value ? 1 : 0);
}
}
public void RequestFocus()
{
if (_handle != IntPtr.Zero) _requestFocus(_handle);
}
public void Dispose()
{
if (_handle == IntPtr.Zero) return;
_pendingText = GetText();
_destroy(_handle);
_handle = IntPtr.Zero;
_held = false;
}
private static byte[] Utf8Z(string s)
{
byte[] bytes = new byte[Encoding.UTF8.GetByteCount(s) + 1];
Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0);
return bytes;
}
// ── Palettes ───────────────────────────────────────────────────────────
/// <summary>
/// The Meta editor's colours (MetaSourceEditor's): STATE:/IF:/DO:/NAV: teal
/// (Keyword), conditions amber (KnownIdentifier), actions blue
/// (PreprocIdentifier), braces violet, numbers green, "~~" comments grey.
/// Lua uses the same slots (keywords teal, built-ins amber).
/// </summary>
public static uint[] RynthPalette()
{
static uint C(uint argb) => RynthTheme.Argb(argb);
return new[]
{
C(0xFFD9E6F2), // Default
C(0xFF26D9E6), // Keyword
C(0xFF99E699), // Number
C(0xFFE6C07B), // String
C(0xFFE6C07B), // CharLiteral
C(0xFFCC88CC), // Punctuation
C(0xFF8CA6BF), // Preprocessor
C(0xFFD9E6F2), // Identifier
C(0xFFE8B333), // KnownIdentifier
C(0xFF7BB8FF), // PreprocIdentifier
C(0xFF6A7A8A), // Comment
C(0xFF6A7A8A), // MultiLineComment
C(0xFF141F29), // Background
C(0xFFE6F2FF), // Cursor
C(0x80305A80), // Selection
C(0x80B02020), // ErrorMarker
C(0xFF3A4A5A), // ControlCharacter
C(0x40F08000), // Breakpoint
C(0xFF4F6478), // LineNumber
C(0x40263A50), // CurrentLineFill
C(0x20263A50), // CurrentLineFillInactive
C(0x40264059), // CurrentLineEdge
};
}
}

View file

@ -6,7 +6,6 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.D3D9;
@ -17,30 +16,36 @@ internal static unsafe class DX9Backend
{
private static readonly Guid IID_IUnknown = new("00000000-0000-0000-C000-000000000046");
// ─── Native ImDrawData layout (pre-1.90 cimgui, x86) ─────────────
// Our cimgui.dll uses the old layout where CmdLists is a raw pointer (4 bytes)
// rather than ImVector (12 bytes). All offsets confirmed by memory dump.
private static Vector2 GetDisplayPos(IntPtr drawDataNative)
// Draw data is read through ImGui.NET's native structs (ImDrawData,
// ImDrawList, ImDrawCmd). That is only valid because Native\cimgui.dll is
// the exact 1.91.6 build ImGui.NET 1.91.6.1 was generated against;
// ImGuiSelfTest refuses to start ImGui if the loaded DLL is anything else.
// Converted-vertex scratch buffer, grown on demand and reused every frame
// (no per-frame native allocation on AC's thread). Freed in Shutdown.
private static CustomVertex* _vtxScratch;
private static int _vtxScratchCapacity;
private static CustomVertex* EnsureVertexScratch(int needed)
{
float x = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 20));
float y = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 24));
return new Vector2(x, y);
}
private static Vector2 GetDisplaySize(IntPtr drawDataNative)
{
float x = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 28));
float y = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 32));
return new Vector2(x, y);
}
private static int GetCmdListsCount(IntPtr drawDataNative)
{
return Marshal.ReadInt32(drawDataNative, 4);
}
private static IntPtr GetCmdListsArray(IntPtr drawDataNative)
{
return Marshal.ReadIntPtr(drawDataNative, 16);
if (needed > _vtxScratchCapacity)
{
int cap = _vtxScratchCapacity == 0 ? 8192 : _vtxScratchCapacity;
while (cap < needed) cap *= 2;
if (_vtxScratch != null) NativeMemory.Free(_vtxScratch);
_vtxScratch = (CustomVertex*)NativeMemory.Alloc((nuint)cap, (nuint)sizeof(CustomVertex));
_vtxScratchCapacity = cap;
}
return _vtxScratch;
}
// ── Diagnostics (/rc imgui diag): what the last RenderDrawData did ──
private static int _diagLists, _diagVtx, _diagCmds, _diagDraws, _diagSkipped, _diagFailed, _diagLastHr;
private static long _diagFrames;
public static string DescribeLastFrame() =>
$"render: initialized={_initialized} frames={_diagFrames} lastFrame lists={_diagLists} vtx={_diagVtx} cmds={_diagCmds} draws={_diagDraws} skipped={_diagSkipped} failedDraws={_diagFailed} lastFailHr=0x{_diagLastHr:X8} fontTex=0x{_fontTexture:X8}";
// ─── D3D9 constants ───────────────────────────────────────────────
private const uint D3DPT_TRIANGLELIST = 4;
private const uint D3DFMT_INDEX16 = 101;
@ -125,6 +130,12 @@ internal static unsafe class DX9Backend
// D3DSAMPLERSTATETYPE
private const uint D3DSAMP_MINFILTER = 5;
private const uint D3DSAMP_MAGFILTER = 6;
private const uint D3DSAMP_ADDRESSU = 1;
private const uint D3DSAMP_ADDRESSV = 2;
private const uint D3DSAMP_MIPFILTER = 7;
private const uint D3DTADDRESS_CLAMP = 3;
private const uint D3DTEXF_NONE = 0;
private const uint D3DRS_WRAP0 = 128;
// D3DTEXTUREFILTERTYPE
private const uint D3DTEXF_LINEAR = 2;
@ -133,16 +144,24 @@ internal static unsafe class DX9Backend
private const uint D3DFVF_XYZ = 0x002;
private const uint D3DFVF_DIFFUSE = 0x040;
private const uint D3DFVF_TEX1 = 0x100;
private const uint D3DFVF_CUSTOM = D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1;
private const uint D3DFVF_XYZRHW = 0x004;
private const uint D3DFVF_CUSTOM = D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1;
private const uint D3DRS_VERTEXBLEND = 151;
private const uint D3DRS_CLIPPLANEENABLE = 152;
// D3DBLENDOP
private const uint D3DBLENDOP_ADD = 1;
// ─── Vertex structure (D3D9 layout) ───────────────────────────────
[StructLayout(LayoutKind.Sequential)]
// Pre-transformed (screen-space) vertices, like VitalHud and the Avalonia
// quad. The first in-game test drew ImGui with XYZ vertices through the
// fixed-function transform stage and nothing appeared, although every
// draw call succeeded: state AC leaves in that stage (user clip planes,
// vertex blending) can discard the geometry. XYZRHW skips it entirely.
private struct CustomVertex
{
public float X, Y, Z;
public float X, Y, Z, Rhw;
public uint Col; // ARGB
public float U, V;
}
@ -358,6 +377,11 @@ internal static unsafe class DX9Backend
if (!CreateFontTexture(pDevice))
return false;
// Draw lists may exceed 64K vertices (radar walls); with this flag ImGui
// splits them into commands that carry a VtxOffset, which
// RenderDrawData applies, so 16-bit indices stay valid.
ImGuiNET.ImGui.GetIO().BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset;
_initialized = true;
RynthLog.Render("DX9Backend: ImGui resources initialized.");
return true;
@ -372,12 +396,19 @@ internal static unsafe class DX9Backend
public static void Shutdown()
{
ReleaseRetiredFontTexture();
if (_fontTexture != IntPtr.Zero)
{
var release = GetTexMethod<ReleaseD>(_fontTexture, TextureVTableIndex.Release);
release(_fontTexture);
_fontTexture = IntPtr.Zero;
}
if (_vtxScratch != null)
{
NativeMemory.Free(_vtxScratch);
_vtxScratch = null;
_vtxScratchCapacity = 0;
}
_initialized = false;
_coreInitialized = false;
}
@ -466,21 +497,54 @@ internal static unsafe class DX9Backend
public static void RenderDrawData(ImDrawDataPtr drawData, IntPtr pDevice)
{
if (!_initialized) return;
if (drawData.NativePtr == null) 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);
}
IntPtr ddNative = (IntPtr)drawData.NativePtr;
int cmdListsCount = GetCmdListsCount(ddNative);
Vector2 displaySize = GetDisplaySize(ddNative);
Vector2 displayPos = GetDisplayPos(ddNative);
/// <summary>
/// Renders one draw list built outside ImGui's draw data (UnderUiLayer: the
/// world overlays drawn at AC's 3D→UI transition, in the middle of AC's frame).
/// Same state save/restore as <see cref="RenderDrawData"/>, plus the few
/// states a 3D pass can leave that the UI pass at EndScene never does.
/// Doesn't count in /rc imgui diag. AC's render thread.
/// </summary>
public static void RenderDrawList(ImDrawList* list, Vector2 displaySize, IntPtr pDevice)
{
if (!_initialized || list == null || pDevice == IntPtr.Zero) return;
RenderLists(&list, 1, -1, Vector2.Zero, displaySize, pDevice, midFrame: true);
}
/// <param name="totalVtx">For the diagnostics; -1: not a frame of ImGui's own (not counted).</param>
private static void RenderLists(ImDrawList** cmdLists, int cmdListsCount, int totalVtx, Vector2 displayPos, Vector2 displaySize,
IntPtr pDevice, bool midFrame)
{
if (cmdListsCount == 0) return;
if (displaySize.X <= 0 || displaySize.Y <= 0) return;
if (cmdLists == null) return;
IntPtr cmdListsArray = GetCmdListsArray(ddNative);
if (cmdListsArray == IntPtr.Zero) return;
if (totalVtx >= 0)
{
_diagFrames++;
_diagLists = cmdListsCount; _diagVtx = totalVtx;
_diagCmds = 0; _diagDraws = 0; _diagSkipped = 0; _diagFailed = 0;
}
if (false && _logCount < 3)
RynthLog.Render($"DX9: Rendering {cmdListsCount} lists, display={displaySize.X}x{displaySize.Y}");
// Mid-frame only (the 3D pass's leftovers): texture-coordinate wrapping,
// and sampler 0's addressing and mip filter.
uint oldWrap0 = 0, oldSamp0AddrU = 0, oldSamp0AddrV = 0, oldSamp0Mip = 0;
if (midFrame)
{
_getRenderState!(pDevice, D3DRS_WRAP0, out oldWrap0);
_getSamplerState!(pDevice, 0, D3DSAMP_ADDRESSU, out oldSamp0AddrU);
_getSamplerState!(pDevice, 0, D3DSAMP_ADDRESSV, out oldSamp0AddrV);
_getSamplerState!(pDevice, 0, D3DSAMP_MIPFILTER, out oldSamp0Mip);
_setRenderState!(pDevice, D3DRS_WRAP0, 0);
_setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
_setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
_setSamplerState!(pDevice, 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
}
// ── Manual state save ────────────────────────────────────────
D3DVIEWPORT9 oldVp = default;
@ -500,6 +564,7 @@ internal static unsafe class DX9Backend
uint oldFillMode = 0, oldZWriteEnable = 0, oldAlphaTestEnable = 0;
uint oldClipping = 0, oldRangeFog = 0, oldSpecular = 0;
uint oldSrcBlendAlpha = 0, oldDestBlendAlpha = 0;
uint oldVertexBlend = 0, oldClipPlanes = 0;
uint oldTss0TexCoordIdx = 0, oldTss0TexTransFlags = 0;
// Stream source and index buffer — DrawIndexedPrimitiveUP sets these to NULL internally
IntPtr oldStreamData = IntPtr.Zero;
@ -548,6 +613,8 @@ internal static unsafe class DX9Backend
_getRenderState!(pDevice, D3DRS_SPECULARENABLE, out oldSpecular);
_getRenderState!(pDevice, D3DRS_SRCBLENDALPHA, out oldSrcBlendAlpha);
_getRenderState!(pDevice, D3DRS_DESTBLENDALPHA, out oldDestBlendAlpha);
_getRenderState!(pDevice, D3DRS_VERTEXBLEND, out oldVertexBlend);
_getRenderState!(pDevice, D3DRS_CLIPPLANEENABLE, out oldClipPlanes);
_getTexStageState!(pDevice, 0, D3DTSS_TEXCOORDINDEX, out oldTss0TexCoordIdx);
_getTexStageState!(pDevice, 0, D3DTSS_TEXTURETRANSFORMFLAGS, out oldTss0TexTransFlags);
_getStreamSource!(pDevice, 0, out oldStreamData, out oldStreamOffset, out oldStreamStride);
@ -555,153 +622,89 @@ internal static unsafe class DX9Backend
try
{
// Set up render state with correct display size
if (false && _logCount < 3) RynthLog.Render("DX9: step SetupRenderState");
SetupRenderStateNative(pDevice, displayPos, displaySize);
if (false && _logCount < 3) RynthLog.Render("DX9: step SetupRenderState done");
// ── Native ImDrawCmd offsets (imgui.h 1.91.6, x86) ──────────
// +0 ClipRect (4 floats, 16 bytes)
// +16 TextureId (ptr, 4 bytes)
// +20 VtxOffset (uint32)
// +24 IdxOffset (uint32)
// +28 ElemCount (uint32)
// +32 UserCallback (ptr, 4 bytes)
// +36 UserCallbackData (ptr, 4 bytes)
// Total = 40 bytes. The C# ImDrawCmd wrapper adds UserCallbackDataSize
// and UserCallbackDataOffset (8 more bytes = 48), but the native cimgui.dll
// does NOT have those fields. We read at stride 40 to match the native layout.
const int CmdStride = 40;
const int ResetRenderStateSentinel = -8; // ImDrawCallback_ResetRenderState
for (int n = 0; n < cmdListsCount; n++)
{
IntPtr listPtr = Marshal.ReadIntPtr(cmdListsArray, n * IntPtr.Size);
if (listPtr == IntPtr.Zero) continue;
ImDrawList* list = cmdLists[n];
if (list == null) continue;
// Read ImDrawList fields directly from native memory.
// ImDrawList starts with three ImVectors (each 12 bytes: Size/Capacity/Data).
// [0] CmdBuffer — ImVector<ImDrawCmd>
// [12] IdxBuffer — ImVector<ImDrawIdx>
// [24] VtxBuffer — ImVector<ImDrawVert>
int cmdCount = Marshal.ReadInt32(listPtr, 0); // CmdBuffer.Size
IntPtr cmdData = Marshal.ReadIntPtr(listPtr, 8); // CmdBuffer.Data
int idxCount = Marshal.ReadInt32(listPtr, 12); // IdxBuffer.Size
IntPtr idxBase = Marshal.ReadIntPtr(listPtr, 20); // IdxBuffer.Data
int vtxCount = Marshal.ReadInt32(listPtr, 24); // VtxBuffer.Size
IntPtr vtxBase = Marshal.ReadIntPtr(listPtr, 32); // VtxBuffer.Data
if (false && _logCount < 3)
RynthLog.Render($"DX9: list[{n}] vtx={vtxCount} idx={idxCount} cmds={cmdCount}");
int vtxCount = list->VtxBuffer.Size;
int cmdCount = list->CmdBuffer.Size;
if (vtxCount == 0 || cmdCount == 0) continue;
// One-time stride diagnostic — log what each cmd stride gives for cmd[1]
if (false && _logCount == 0 && n == 0 && cmdCount >= 2)
{
RynthLog.Render($"DX9: C# ImDrawCmd size = {Unsafe.SizeOf<ImDrawCmd>()}");
for (int ts = 32; ts <= 64; ts += 4)
{
IntPtr tp = cmdData + ts;
uint te = (uint)Marshal.ReadInt32(tp, 28);
float tx = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(tp, 0));
float tz = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(tp, 8));
uint tcb = (uint)Marshal.ReadInt32(tp, 32);
RynthLog.Render($"DX9: stride={ts}: elems={te} clipX={tx} clipZ={tz} cb=0x{tcb:X8}");
}
}
// One-time vertex diagnostic — verify ImDrawVert layout
if (false && _logCount == 0 && n == 0)
{
RynthLog.Render($"DX9: C# ImDrawVert size = {Unsafe.SizeOf<ImDrawVert>()}");
// Read first 3 vertices as raw bytes to verify layout
for (int vi = 0; vi < Math.Min(3, vtxCount); vi++)
{
IntPtr vp = vtxBase + vi * Unsafe.SizeOf<ImDrawVert>();
float px = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 0));
float py = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 4));
float ux = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 8));
float uy = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 12));
uint col = (uint)Marshal.ReadInt32(vp, 16);
RynthLog.Render($"DX9: vtx[{vi}] pos=({px},{py}) uv=({ux},{uy}) col=0x{col:X8}");
}
}
CustomVertex* vtxBuf = (CustomVertex*)NativeMemory.Alloc((nuint)(vtxCount * sizeof(CustomVertex)));
ImDrawVert* srcVtx = (ImDrawVert*)vtxBase;
ImDrawVert* srcVtx = (ImDrawVert*)list->VtxBuffer.Data;
ushort* idxBase = (ushort*)list->IdxBuffer.Data;
ImDrawCmd* cmds = (ImDrawCmd*)list->CmdBuffer.Data;
// ImGui vertices are pos/uv/RGBA; D3D9's FVF wants xyz/ARGB/uv.
CustomVertex* vtxBuf = EnsureVertexScratch(vtxCount);
for (int i = 0; i < vtxCount; i++)
{
vtxBuf[i].X = srcVtx[i].pos.X;
vtxBuf[i].Y = srcVtx[i].pos.Y;
// Screen pixels relative to the viewport; -0.5 is D3D9's
// half-pixel offset (the XYZ path put it in the projection).
vtxBuf[i].X = srcVtx[i].pos.X - displayPos.X - 0.5f;
vtxBuf[i].Y = srcVtx[i].pos.Y - displayPos.Y - 0.5f;
vtxBuf[i].Z = 0f;
vtxBuf[i].Rhw = 1f;
uint c = srcVtx[i].col;
vtxBuf[i].Col = (c & 0xFF00FF00) | ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16);
vtxBuf[i].U = srcVtx[i].uv.X;
vtxBuf[i].V = srcVtx[i].uv.Y;
}
if (false && _logCount < 3) RynthLog.Render($"DX9: list[{n}] vertex copy done");
for (int cmdI = 0; cmdI < cmdCount; cmdI++)
{
IntPtr cmdPtr = cmdData + cmdI * CmdStride;
ImDrawCmd* cmd = &cmds[cmdI];
// Read fields at known native offsets
float clipX = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 0));
float clipY = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 4));
float clipZ = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 8));
float clipW = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 12));
IntPtr textureId = Marshal.ReadIntPtr(cmdPtr, 16);
uint nativeIdxOff = (uint)Marshal.ReadInt32(cmdPtr, 24);
uint elemCount = (uint)Marshal.ReadInt32(cmdPtr, 28);
IntPtr userCallback = Marshal.ReadIntPtr(cmdPtr, 32);
if (userCallback != IntPtr.Zero)
if (cmd->UserCallback != IntPtr.Zero)
{
if (false && _logCount < 3)
RynthLog.Render($"DX9: cmd[{cmdI}] CALLBACK elems={elemCount} cb=0x{userCallback:X}");
if ((int)userCallback == ResetRenderStateSentinel)
if ((int)cmd->UserCallback == ResetRenderStateSentinel)
SetupRenderStateNative(pDevice, displayPos, displaySize);
// Non-sentinel callbacks: skip (no draw data, ElemCount expected 0)
// Other callbacks are not supported (no managed callbacks
// from inside the render path); they carry no geometry.
continue;
}
if (elemCount == 0)
{
if (false && _logCount < 3)
RynthLog.Render($"DX9: cmd[{cmdI}] ZERO-ELEM skip tex=0x{textureId:X}");
continue;
}
if (false && _logCount < 3)
RynthLog.Render($"DX9: cmd[{cmdI}] tex=0x{textureId:X} elems={elemCount} clip={clipX},{clipY},{clipZ},{clipW}");
uint elemCount = cmd->ElemCount;
_diagCmds++;
if (elemCount == 0) continue;
Vector4 clip = cmd->ClipRect;
RECT sr;
sr.Left = (int)(clipX - displayPos.X);
sr.Top = (int)(clipY - displayPos.Y);
sr.Right = (int)(clipZ - displayPos.X);
sr.Bottom = (int)(clipW - displayPos.Y);
sr.Left = (int)(clip.X - displayPos.X);
sr.Top = (int)(clip.Y - displayPos.Y);
sr.Right = (int)(clip.Z - displayPos.X);
sr.Bottom = (int)(clip.W - displayPos.Y);
// Inside the viewport (0,0,displaySize; set above): a pop-out's picture is
// only part of its ImGui display, so a full-display clip rect reaches past
// it on every side. Nothing outside the viewport is drawn anyway.
if (sr.Left < 0) sr.Left = 0;
if (sr.Top < 0) sr.Top = 0;
if (sr.Right > (int)displaySize.X) sr.Right = (int)displaySize.X;
if (sr.Bottom > (int)displaySize.Y) sr.Bottom = (int)displaySize.Y;
if (sr.Right <= sr.Left || sr.Bottom <= sr.Top) { _diagSkipped++; continue; }
_setScissorRect!(pDevice, &sr);
_setTexture!(pDevice, 0, textureId);
_setTexture!(pDevice, 0, cmd->TextureId);
ushort* pIdxData = (ushort*)idxBase + nativeIdxOff;
if (false && _logCount < 3)
RynthLog.Render($"DX9: cmd[{cmdI}] DrawIndexedPrimUP primCount={elemCount / 3}");
_drawIndexedPrimUP!(pDevice,
D3DPT_TRIANGLELIST, 0, (uint)vtxCount,
// DrawIndexedPrimitiveUP has no base-vertex argument, so the
// command's VtxOffset is applied by offsetting the vertex pointer.
uint vtxOffset = cmd->VtxOffset;
if (vtxOffset >= (uint)vtxCount) { _diagSkipped++; continue; }
int hr = _drawIndexedPrimUP!(pDevice,
D3DPT_TRIANGLELIST, 0, (uint)vtxCount - vtxOffset,
elemCount / 3,
(IntPtr)pIdxData, D3DFMT_INDEX16,
(IntPtr)vtxBuf, (uint)sizeof(CustomVertex));
if (false && _logCount < 3) RynthLog.Render($"DX9: cmd[{cmdI}] draw done");
(IntPtr)(idxBase + cmd->IdxOffset), D3DFMT_INDEX16,
(IntPtr)(vtxBuf + vtxOffset), (uint)sizeof(CustomVertex));
_diagDraws++;
if (hr < 0) { _diagFailed++; _diagLastHr = hr; }
}
NativeMemory.Free(vtxBuf);
}
}
finally
{
_logCount++;
// ── Manual state restore ─────────────────────────────────
_setRenderState!(pDevice, D3DRS_CULLMODE, oldCull);
_setRenderState!(pDevice, D3DRS_LIGHTING, oldLighting);
@ -745,10 +748,19 @@ internal static unsafe class DX9Backend
_setRenderState!(pDevice, D3DRS_SPECULARENABLE, oldSpecular);
_setRenderState!(pDevice, D3DRS_SRCBLENDALPHA, oldSrcBlendAlpha);
_setRenderState!(pDevice, D3DRS_DESTBLENDALPHA, oldDestBlendAlpha);
_setRenderState!(pDevice, D3DRS_VERTEXBLEND, oldVertexBlend);
_setRenderState!(pDevice, D3DRS_CLIPPLANEENABLE, oldClipPlanes);
_setTexStageState!(pDevice, 0, D3DTSS_TEXCOORDINDEX, oldTss0TexCoordIdx);
_setTexStageState!(pDevice, 0, D3DTSS_TEXTURETRANSFORMFLAGS, oldTss0TexTransFlags);
_setStreamSource!(pDevice, 0, oldStreamData, oldStreamOffset, oldStreamStride);
_setIndices!(pDevice, oldIndexBuffer);
if (midFrame)
{
_setRenderState!(pDevice, D3DRS_WRAP0, oldWrap0);
_setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSU, oldSamp0AddrU);
_setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSV, oldSamp0AddrV);
_setSamplerState!(pDevice, 0, D3DSAMP_MIPFILTER, oldSamp0Mip);
}
// Release COM refs we obtained
if (oldTexture != IntPtr.Zero)
@ -842,28 +854,35 @@ internal static unsafe class DX9Backend
// FVF — SetStreamSource is NOT called here; DrawIndexedPrimitiveUP uses user-memory
// pointers directly and does not require a bound vertex stream.
_setFVF!(dev, D3DFVF_CUSTOM);
_setRenderState!(dev, D3DRS_VERTEXBLEND, 0); // D3DVBF_DISABLE
_setRenderState!(dev, D3DRS_CLIPPLANEENABLE, 0); // no user clip planes
// Orthographic projection — D3D9 pixel centers are at +0.5 (not +0.0 like D3D10+)
float L = displayPos.X + 0.5f;
float R = displayPos.X + displaySize.X + 0.5f;
float T = displayPos.Y + 0.5f;
float B = displayPos.Y + displaySize.Y + 0.5f;
// No transforms: XYZRHW vertices are already in viewport pixels (see CustomVertex).
}
D3DMATRIX identity;
identity.M11 = 1; identity.M12 = 0; identity.M13 = 0; identity.M14 = 0;
identity.M21 = 0; identity.M22 = 1; identity.M23 = 0; identity.M24 = 0;
identity.M31 = 0; identity.M32 = 0; identity.M33 = 1; identity.M34 = 0;
identity.M41 = 0; identity.M42 = 0; identity.M43 = 0; identity.M44 = 1;
/// <summary>
/// After the font atlas was rebuilt: replace the font texture. Render thread.
/// The old texture is kept one more frame: UnderUiLayer's list from the frame
/// before may still be drawn by this frame's fallback, and it names the old one.
/// </summary>
public static bool RebuildFontTexture(IntPtr pDevice)
{
ReleaseRetiredFontTexture();
_retiredFontTexture = _fontTexture;
_fontTexture = IntPtr.Zero;
return CreateFontTexture(pDevice);
}
D3DMATRIX projection;
projection.M11 = 2f / (R - L); projection.M12 = 0f; projection.M13 = 0f; projection.M14 = 0f;
projection.M21 = 0f; projection.M22 = 2f / (T - B); projection.M23 = 0f; projection.M24 = 0f;
projection.M31 = 0f; projection.M32 = 0f; projection.M33 = 0.5f; projection.M34 = 0f;
projection.M41 = (L + R) / (L - R); projection.M42 = (T + B) / (B - T); projection.M43 = 0.5f; projection.M44 = 1f;
// The font texture a rebuild replaced; released at the next frame's build.
private static IntPtr _retiredFontTexture;
_setTransform!(dev, D3DTS_WORLD, &identity);
_setTransform!(dev, D3DTS_VIEW, &identity);
_setTransform!(dev, D3DTS_PROJECTION, &projection);
/// <summary>Releases the texture the last rebuild replaced. Render thread, at the start of a frame's build.</summary>
public static void ReleaseRetiredFontTexture()
{
if (_retiredFontTexture == IntPtr.Zero) return;
var release = GetTexMethod<ReleaseD>(_retiredFontTexture, TextureVTableIndex.Release);
release(_retiredFontTexture);
_retiredFontTexture = IntPtr.Zero;
}
private static bool CreateFontTexture(IntPtr pDevice)
@ -921,27 +940,52 @@ internal static unsafe class DX9Backend
// Store texture ID for ImGui
io.Fonts.SetTexID(_fontTexture);
// Force native TexID write — managed wrapper can mismatch on x86
nint texId = io.Fonts.TexID;
unsafe
{
byte* ioPtr = (byte*)ImGuiNET.ImGui.GetIO().NativePtr;
IntPtr fontsPtr = *(IntPtr*)(ioPtr + 36);
*(IntPtr*)(fontsPtr + 4) = _fontTexture;
}
if (texId == 0)
{
unsafe
{
byte* ioPtr = (byte*)ImGuiNET.ImGui.GetIO().NativePtr;
IntPtr fontsPtr = *(IntPtr*)(ioPtr + 36);
*(IntPtr*)(fontsPtr + 4) = _fontTexture;
}
}
return true;
}
/// <summary>
/// A managed-pool A8R8G8B8 texture (it survives a device reset) holding RGBA pixels
/// (script window icons). Zero on failure. AC's render thread, after <see cref="InitCore"/>.
/// </summary>
public static IntPtr CreateTextureRgba(IntPtr pDevice, int width, int height, ReadOnlySpan<byte> rgba)
{
if (_createTexture == null || pDevice == IntPtr.Zero || width <= 0 || height <= 0
|| rgba.Length < width * height * 4)
return IntPtr.Zero;
int hr = _createTexture(pDevice, (uint)width, (uint)height, 1, 0,
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out IntPtr tex, IntPtr.Zero);
if (hr < 0 || tex == IntPtr.Zero)
return IntPtr.Zero;
var lockRect = GetTexMethod<TexLockRectD>(tex, TextureVTableIndex.LockRect);
var unlockRect = GetTexMethod<TexUnlockRectD>(tex, TextureVTableIndex.UnlockRect);
D3DLOCKED_RECT locked;
if (lockRect(tex, 0, &locked, IntPtr.Zero, 0) < 0 || locked.pBits == IntPtr.Zero)
{
ReleaseComObject(tex);
return IntPtr.Zero;
}
byte* dst = (byte*)locked.pBits;
for (int y = 0; y < height; y++)
{
ReadOnlySpan<byte> srcRow = rgba.Slice(y * width * 4, width * 4);
byte* dstRow = dst + y * locked.Pitch;
for (int x = 0; x < width; x++)
{
int i = x * 4;
dstRow[i + 0] = srcRow[i + 2]; // B
dstRow[i + 1] = srcRow[i + 1]; // G
dstRow[i + 2] = srcRow[i + 0]; // R
dstRow[i + 3] = srcRow[i + 3]; // A
}
}
unlockRect(tex, 0);
return tex;
}
/// <summary>Releases a texture made by <see cref="CreateTextureRgba"/>. AC's render thread.</summary>
public static void ReleaseTexture(IntPtr tex) => ReleaseComObject(tex);
private static void CacheDelegates(IntPtr pDevice)
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
@ -1067,7 +1111,11 @@ internal static unsafe class DX9Backend
// core init flag so this path runs even when EnableImGuiBackend=false.
if (!_coreInitialized || pDevice == IntPtr.Zero) return;
if (!D3D9.GameMatrixCapture.HasCapturedFrame) return;
if (D3D9.Nav3DRenderer.RingCount == 0 && D3D9.Nav3DRenderer.LineCount == 0 && D3D9.Nav3DRenderer.TriangleCount == 0) return;
// One snapshot of the committed frame for the whole draw (the pump may
// commit a new one meanwhile; this one stays intact for a tick).
D3D9.Nav3DRenderer.NavBuffer frame = D3D9.Nav3DRenderer.Ready;
int triCount = frame.TriCount, lineCount = frame.LineCount, ringCount = frame.RingCount;
if (ringCount == 0 && lineCount == 0 && triCount == 0) return;
EnsureNavTrig();
@ -1163,39 +1211,33 @@ internal static unsafe class DX9Backend
// vertex buffer and submitted in a single DrawPrimitiveUP — at
// high slope-radius settings we can have 4000+ triangles per
// frame, and one DP-UP per triangle was visibly frame-dropping.
int triCount = D3D9.Nav3DRenderer.TriangleCount;
if (triCount > 0)
{
EnsureNavTriBatch(triCount * 3);
NavVertex* batch = (NavVertex*)_navTriBatch;
for (int i = 0; i < triCount; i++)
{
D3D9.Nav3DRenderer.GetTriangle(i,
out float x1, out float y1, out float z1,
out float x2, out float y2, out float z2,
out float x3, out float y3, out float z3, out uint color);
uint color = frame.TriColor[i];
int b = i * 3;
batch[b ].X = x1; batch[b ].Y = y1; batch[b ].Z = z1; batch[b ].Col = color;
batch[b + 1].X = x2; batch[b + 1].Y = y2; batch[b + 1].Z = z2; batch[b + 1].Col = color;
batch[b + 2].X = x3; batch[b + 2].Y = y3; batch[b + 2].Z = z3; batch[b + 2].Col = color;
batch[b ].X = frame.TriX1[i]; batch[b ].Y = frame.TriY1[i]; batch[b ].Z = frame.TriZ1[i]; batch[b ].Col = color;
batch[b + 1].X = frame.TriX2[i]; batch[b + 1].Y = frame.TriY2[i]; batch[b + 1].Z = frame.TriZ2[i]; batch[b + 1].Col = color;
batch[b + 2].X = frame.TriX3[i]; batch[b + 2].Y = frame.TriY3[i]; batch[b + 2].Z = frame.TriZ3[i]; batch[b + 2].Col = color;
}
_drawPrimUP!(pDevice, D3DPT_TRIANGLELIST, (uint)triCount, (IntPtr)batch, (uint)sizeof(NavVertex));
}
// Draw lines (extruded XZ-plane quads — for edges/strips)
for (int i = 0; i < D3D9.Nav3DRenderer.LineCount; i++)
for (int i = 0; i < lineCount; i++)
{
D3D9.Nav3DRenderer.GetLine(i, out float x1, out float y1, out float z1,
out float x2, out float y2, out float z2, out float thick, out uint color);
DrawNavLine(pDevice, x1, y1, z1, x2, y2, z2, thick, color);
DrawNavLine(pDevice, frame.LineX1[i], frame.LineY1[i], frame.LineZ1[i],
frame.LineX2[i], frame.LineY2[i], frame.LineZ2[i], frame.LineThick[i], frame.LineColor[i]);
}
// Draw rings
for (int i = 0; i < D3D9.Nav3DRenderer.RingCount; i++)
for (int i = 0; i < ringCount; i++)
{
D3D9.Nav3DRenderer.GetRing(i, out float x, out float y, out float z,
out float radius, out float thick, out float height, out uint color);
DrawNavRing(pDevice, x, y, z, radius, thick, height, color);
DrawNavRing(pDevice, frame.RingX[i], frame.RingY[i], frame.RingZ[i],
frame.RingRadius[i], frame.RingThick[i], frame.RingHeight[i], frame.RingColor[i]);
}
if (_nav3DLogCount == 0)

View file

@ -11,7 +11,7 @@
// * ImGui-gated (only when EngineSettings.EnableImGuiBackend is true):
// Win32Backend.NewFrame / DX9Backend.NewFrame, ImGui.NewFrame/EndFrame/
// Render, RynthCoreShell + plugin RenderAll, DX9Backend.RenderDrawData,
// mouse/keyboard capture flag updates, multi-viewport platform pump.
// mouse/keyboard capture flag updates.
//
// Renamed 2026-05-10 from ImGuiController — the type now owns more than
// ImGui's frame; the ImGui block is just one branch of its work.
@ -42,17 +42,6 @@ internal static class EngineFrameController
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool GetClientRect(IntPtr hWnd, out ClientRect lpRect);
[DllImport("user32.dll")]
private static extern bool ClientToScreen(IntPtr hWnd, ref ClientPoint lpPoint);
[StructLayout(LayoutKind.Sequential)]
private struct ClientRect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
private struct ClientPoint { public int X, Y; }
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
private static bool _imguiInitialized;
@ -103,6 +92,8 @@ internal static class EngineFrameController
RynthLog.Render($"EngineFrameController: Game HWND = 0x{_gameHwnd:X8}");
EntryPoint.GameHwnd = _gameHwnd;
_coreResolved = true;
// Pop-outs hold D3DPOOL_DEFAULT render targets: release them before AC resets a lost device.
D3D9.DeviceResetHook.InstallFromDevice(pDevice);
return true;
}
@ -114,6 +105,11 @@ internal static class EngineFrameController
if (!EnsureCore(pDevice))
return false;
// Before any context exists: the loaded cimgui.dll must be the exact
// build ImGui.NET wraps, or every struct read below is at wrong offsets.
if (!ImGuiSelfTest.Run(EntryPoint.ImGuiNativeHandle))
return false;
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
if (previousContext != IntPtr.Zero)
RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context.");
@ -143,23 +139,20 @@ internal static class EngineFrameController
}
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
// ViewportsEnable was enabling ImGui multi-viewport platform/renderer
// callbacks against a cimgui.dll that is NOT built with
// IMGUI_ENABLE_VIEWPORTS. The platform/renderer callback chain then
// recursed (Platform → Renderer → Platform → ...) on AC's render
// thread, eating the 1MB stack in ~17s and AV'ing in ntdll mid-push.
// CLAUDE.md flags this: Multi-viewport "requires cimgui built with
// IMGUI_ENABLE_VIEWPORTS" — flag re-introduced this in the engine
// and triggered the silent stack-overflow on every login.
// io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;
// Popped-out plugin windows use WS_EX_TOOLWINDOW so they don't show
// up as extra "Asheron's Call" entries in the taskbar — critical for
// users running many clients side by side.
io.ConfigViewportsNoTaskBarIcon = true;
ImGuiNET.ImGui.StyleColorsDark();
// Multi-viewport (ViewportsEnable) is deliberately never enabled: it
// runs many native->managed platform/renderer callbacks per frame on
// AC's thread and creates HWNDs from inside EndScene. Pop-out panels,
// if built, are driven explicitly by the engine instead
// (docs/IMGUI_PARITY_PLAN.md section 4.2).
// One-shot offset probe for diagnostics — safe to keep installed.
ViewportProbe.Run();
// DPI scale for fonts and style metrics. Logged next to Avalonia's
// scale: docked positions are stored in Avalonia logical units, so
// the two must agree for a panel to land in the same place in
// either face (plan section 4.4).
_uiScale = UiScale.ForWindow(_gameHwnd);
RynthLog.UI($"EngineFrameController: ImGui scale {_uiScale:0.##} (Avalonia input scale {UI.AvaloniaOverlay.InputScale:0.##}).");
RynthTheme.Apply(ImGuiNET.ImGui.GetStyle(), _uiScale);
ImGuiFonts.Build(io, _uiScale);
if (!Win32Backend.Init(_gameHwnd))
return false;
@ -167,26 +160,11 @@ internal static class EngineFrameController
if (!DX9Backend.InitImGui(pDevice))
return false;
// Viewport backends only run when ViewportsEnable is on. Installing
// their callbacks on PlatformIO without the flag has no upside and
// just expands the crash surface.
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
bool platformOk = ViewportPlatformBackend.Init(_gameHwnd);
bool rendererOk = platformOk && ViewportRendererBackend.Init(pDevice);
if (!platformOk || !rendererOk)
{
RynthLog.Render($"EngineFrameController: viewport init failed (platform={platformOk}, renderer={rendererOk}) — disabling ViewportsEnable.");
io.ConfigFlags &= ~ImGuiConfigFlags.ViewportsEnable;
}
ViewportPlatformBackend.ImGuiContext = _context;
}
_lastFrameTicks = Stopwatch.GetTimestamp();
_imguiInitialized = true;
initSucceeded = true;
RynthLog.Render("EngineFrameController: Fully initialized - RynthCore shell active.");
RynthLog.UI("EngineFrameController: ImGui initialized.");
return true;
}
finally
@ -213,14 +191,16 @@ internal static class EngineFrameController
{
ImGuiNET.ImGui.SetCurrentContext(contextToDestroy);
// Zero the WndProc context guard BEFORE DestroyContext so any
// deferred OS messages that arrive at viewport HWNDs during or
// after teardown don't try to call into freed ImGui memory.
ViewportPlatformBackend.ImGuiContext = IntPtr.Zero;
PluginManager.ShutdownAll();
// No context may be destroyed while a font worker runs (ImGuiFonts, re-bake note).
ImGuiFonts.WaitForWorkers();
// Pop-outs share the main font atlas: their contexts go before the main one.
ImGuiPopOuts.Shutdown();
OverlayTextureRenderer.Shutdown();
ViewportRendererBackend.Shutdown();
ViewportPlatformBackend.Shutdown();
// Its lists are drawn by DX9Backend from the DIP hook, which is still live.
UnderUiLayer.Shutdown();
ScriptIcons.Shutdown(); // script window icon textures, before the backend goes
RetailSprites.Shutdown(); // retail UI pictures (Inventory Classic view), likewise
DX9Backend.Shutdown();
// Do NOT call Win32Backend.Shutdown() here. EngineLifecycle.Shutdown
// owns that step explicitly, AFTER AvaloniaOverlay.Stop — floating
@ -230,6 +210,7 @@ internal static class EngineFrameController
// those destroys to AC's proc, which ignores them, and the orphaned
// panel HWND outlives the engine load.
ImGuiNET.ImGui.DestroyContext(contextToDestroy);
ImGuiFonts.Free(); // the atlas referenced these buffers; the context is gone now
_imguiInitialized = false;
_coreResolved = false;
@ -299,6 +280,11 @@ internal static class EngineFrameController
// is the dump-verified 0x0067E779 READ-AV when done on the pump thread.
// Sampled every frame (positions are volatile), zero-alloc.
Compatibility.ClientObjectHooks.PrefetchPositions();
// Refresh the cached player id every frame (unthrottled: the native leaf is
// two loads) and the other small main-thread snapshots (cast gate, pose,
// ...). Off-thread callers are served from these instead of reading AC
// memory from the pump thread. Also runs from the Client::UseTime drain.
Compatibility.MainThreadSnapshots.Tick();
// Same main-thread guard: snapshot XP/luminance/deaths/vitae (main-thread-only
// Inq* reads) so the GetEngineStatusJson host bridge can serve them off-thread (throttled).
Compatibility.ClientObjectHooks.PrefetchPlayerStats();
@ -363,8 +349,21 @@ internal static class EngineFrameController
// calls it at all.
// ── ImGui-gated work ─────────────────────────────────────────
if (Plugins.EngineSettings.EnableImGuiBackend)
RunImGuiFrame(pDevice);
// The frame is BUILT here and SUBMITTED after the Nav3D fallback and
// the vital HUD, so ImGui windows sit above both. The Avalonia quad
// (EndSceneHook, after this returns) stays topmost while both stacks
// run, matching input order: Avalonia gets the first hit test.
bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend;
bool imguiBuilt = false;
long uiTicks = 0;
if (!imguiEnabled)
_imguiIdle = true; // switched off in game: input state resets when it comes back
else
{
long t0 = Stopwatch.GetTimestamp();
imguiBuilt = BuildImGuiFrame(pDevice);
uiTicks = Stopwatch.GetTimestamp() - t0;
}
// Fallback render — only fires when the injector missed this
// frame's 3D→UI transition. _coreInitialized is enough — this
@ -372,13 +371,22 @@ internal static class EngineFrameController
if (!nav3DAlreadyRendered)
DX9Backend.RenderNav3D(pDevice);
// Custom D3D9 vital HUD (Health/Stamina/Mana). Always-on (independent
// of EnableImGuiBackend) so it shows even in Avalonia-only mode; drawn
// last so it sits on top of the world + AC UI. Reads the vitals
// snapshot maintained on this same (AC main) thread and does its own
// device state save/restore. No-op until vitals are seeded.
if (Plugins.EngineSettings.DrawCustomVitalBars)
D3D9.VitalHud.Draw(pDevice);
// The world overlays built last frame (nameplates, combat text) normally
// drew at this frame's 3D->UI transition, under AC's UI. If that wasn't
// seen, they draw here - still under the ImGui panels. No-op when they
// already drew (UnderUiLayer presents a list once).
UnderUiLayer.PresentFallback(pDevice);
if (imguiEnabled)
{
long t0 = Stopwatch.GetTimestamp();
if (imguiBuilt)
SubmitImGuiFrame(pDevice);
// Popped-out panels: their own contexts, windows and render targets.
if (_imguiInitialized)
ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive);
UiFrameStats.Record(uiTicks + (Stopwatch.GetTimestamp() - t0));
}
}
catch (Exception ex)
{
@ -392,9 +400,30 @@ internal static class EngineFrameController
// never fires again — every subsequent frame falls back to the
// end-of-frame draw (which paints over the UI).
D3D9.Nav3DRenderInjector.ResetFrame();
// What this frame built for the world overlays is presented next frame.
UnderUiLayer.EndFrame();
}
}
/// <summary>
/// The main-thread prefetches of the always-on pipeline above, for a client without
/// the EndScene hook (Decal in the process): called from the Client::UseTime detour
/// (AC's main thread) once GameTickHooks.HeadlessPrefetch is set. Same calls, same
/// order, each throttled and main-thread-gated internally. The EndScene path doesn't
/// use this (it runs the calls inline, unchanged).
/// </summary>
internal static void RunHeadlessPrefetch()
{
Compatibility.ClientObjectHooks.PrefetchPlayerSkills();
Compatibility.ClientObjectHooks.PrefetchKnownSpells();
Compatibility.ClientObjectHooks.PrefetchAttackable();
Compatibility.ClientObjectHooks.PrefetchObjectIdentity();
Compatibility.ClientObjectHooks.PrefetchPositions();
Compatibility.ClientObjectHooks.PrefetchPlayerStats();
try { Plugins.PluginManager.TrySeedLiveObjectsFromCObjectMaintOnce(); }
catch (Exception ex) { RynthLog.Plugin($"CObjectMaint seed threw {ex.GetType().Name}: {ex.Message}"); }
}
/// <summary>
/// The plugin lifecycle/tick work that used to run inline in
/// <see cref="OnEndScene"/>. Driven by the dedicated managed plugin pump
@ -419,15 +448,28 @@ internal static class EngineFrameController
return; // never re-enter PluginManager from two stacks
try
{
// Plugins only get the ImGui context when they may draw with it
// (EnableImGuiShell, FORCE-gated). The engine's own ImGui panels
// don't need plugins to see it, and handing it over switched
// RynthAi into its legacy-ImGui setup (first ImGui-on test,
// 2026-09-28) - plugins must behave exactly as in Avalonia-only mode.
IntPtr pluginContext = Plugins.EngineSettings.EnableImGuiShell ? _context : IntPtr.Zero;
if (!_pluginsInitialized)
{
_pluginsInitialized = true;
PluginManager.InitPlugins(_context, device, _gameHwnd);
PluginManager.InitPlugins(pluginContext, device, _gameHwnd);
}
PluginManager.ProcessPendingActions(_context, device, _gameHwnd);
// Decal bridge mode with the in-game renderer (DecalInGameImGui): chat and
// chat-bar lines come from the bridge. One flag check in every other client.
if (Compatibility.DecalBridgeHost.Active)
Compatibility.DecalBridgeHost.Drain();
PluginManager.ProcessPendingActions(pluginContext, device, _gameHwnd);
PluginManager.FlushPendingDeletes(); // closes the create→delete race window
PluginManager.TickAll();
// Panel data: plugin exports for the UI are called here, on the same
// thread as the plugin tick, and published as immutable snapshots.
UI.Data.UiDataHub.Step();
}
catch (Exception ex)
{
@ -439,26 +481,97 @@ internal static class EngineFrameController
}
}
/// <summary>
/// Runs the ImGui-specific portion of the per-frame pipeline:
/// backend NewFrame plumbing, ImGui frame open/close, RynthCore shell +
/// plugin RenderAll, draw-data submission, capture flag update, and the
/// multi-viewport platform pump. Bypassed entirely when
/// EngineSettings.EnableImGuiBackend is false.
/// </summary>
private static void RunImGuiFrame(IntPtr pDevice)
/// <summary>True when anything ImGui should be drawn this frame.</summary>
private static bool HasImGuiContent()
{
if (_imguiInitFailed) return;
if (Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled) return true;
if (!PanelsLive) return false;
ImGuiPanelHost.RestoreOnce();
return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame;
}
/// <summary>
/// Panel faces show only in the world, like the Avalonia overlay (hidden
/// between characters, not closed).
/// </summary>
private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete;
/// <summary>DPI scale the fonts and style were built for (see Init).</summary>
private static float _uiScale = 1f;
/// <summary>The scale the fonts and style were built for.</summary>
internal static float FontScale => _uiScale;
/// <summary>A popped-out panel was clicked: the main context's text edit ends next frame. AC thread.</summary>
internal static void DropMainTextFocus() => _dropImGuiTextFocus = true;
// ── Diagnostics (/rc imgui diag) ─────────────────────────────────
private static long _framesBuilt;
private static System.Numerics.Vector2 _lastDisplaySize;
/// <summary>One line per fact about the ImGui layer's state. Game thread (reads plain fields).</summary>
internal static System.Collections.Generic.List<string> DescribeState()
{
var lines = new System.Collections.Generic.List<string>
{
$"layer={(Plugins.EngineSettings.EnableImGuiBackend ? "on" : "off")} initialized={_imguiInitialized} initFailed={_imguiInitFailed} selfTest={ImGuiSelfTest.LastResult}",
$"inWorld={PanelsLive} content={HasImGuiContentNoRestore()} idle={_imguiIdle} framesBuilt={_framesBuilt} uiScale={_uiScale:0.##} avaloniaScale={UI.AvaloniaOverlay.InputScale:0.##} display={_lastDisplaySize.X:0}x{_lastDisplaySize.Y:0}",
DX9Backend.DescribeLastFrame(),
UnderUiLayer.Describe(),
$"capture: {Win32Backend.DescribeCapture()}",
};
lines.AddRange(ImGuiPopOuts.Describe());
return lines;
}
private static bool HasImGuiContentNoRestore() =>
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame));
// Keyboard owner between the stacks (plan §3.2 d): whichever side started
// text entry most recently keeps the keyboard.
private static bool _prevImGuiText, _prevAvaloniaText, _dropImGuiTextFocus;
/// <summary>True while frames are being skipped because nothing ImGui is open.</summary>
private static bool _imguiIdle = true;
/// <summary>
/// Builds the ImGui frame (NewFrame ... Render) and publishes the capture
/// flags. Returns true when there is draw data for <see cref="SubmitImGuiFrame"/>.
/// Only called while EngineSettings.EnableImGuiBackend is true.
///
/// Early-out: with no ImGui content there is no ImGui frame at all. Queued
/// input is dropped (nothing would drain it) and capture flags are cleared,
/// so the idle cost is one GetClientRect.
/// </summary>
private static bool BuildImGuiFrame(IntPtr pDevice)
{
if (_imguiInitFailed) return false;
if (!_imguiInitialized)
{
// Initialised as soon as the backend is enabled (not lazily on first
// content), so the cimgui self-test result is in the log at startup.
if (!Init(pDevice))
{
_imguiInitFailed = true;
return;
return false;
}
}
Win32Backend.UpdateClientMetrics(out int clientW, out int clientH);
// Monster nameplates: pick the monsters (throttled) before deciding
// whether there is a frame to build, so plates alone can ask for one.
Hud.MonsterHud.Update(PanelsLive);
if (!HasImGuiContent())
{
_imguiIdle = true;
Win32Backend.DiscardQueuedInput();
Win32Backend.ClearCaptureFlags();
return false;
}
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
ImGuiNET.ImGui.SetCurrentContext(_context);
bool frameStarted = false;
@ -466,11 +579,36 @@ internal static class EngineFrameController
try
{
_frameCount++;
DX9Backend.NewFrame();
Win32Backend.NewFrame();
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
long now = Stopwatch.GetTimestamp();
if (_imguiIdle)
{
// Resuming: keys/buttons released while idle must not read as held,
// and the idle gap must not become one huge DeltaTime.
_imguiIdle = false;
Win32Backend.ResetImGuiInputState(io);
_lastFrameTicks = now;
}
_frameCount++;
// A panel's text size changed: re-bake the fonts (only the sizes in
// use) and replace the font texture, between frames.
// The new atlas is baked on a worker (ImGuiFonts.PumpRebuild), once per run of
// changes (RequestRebuild debounces); here it is swapped in and its texture made.
DX9Backend.ReleaseRetiredFontTexture(); // the texture a rebuild replaced last frame
long rebuildStart = Stopwatch.GetTimestamp();
if (ImGuiFonts.PumpRebuild(io, _uiScale, out string rebuilt))
{
DX9Backend.RebuildFontTexture(pDevice);
double rebuildMs = (Stopwatch.GetTimestamp() - rebuildStart) * 1000.0 / Stopwatch.Frequency;
RynthLog.UI($"ImGuiFonts: text size change: {rebuilt}; render thread {rebuildMs:0.0} ms (swap + texture).");
}
// Script window icons decoded since the last frame become textures, and the least
// recently drawn go, before anything draws (no draw list points at them any more).
ScriptIcons.BeginFrame(pDevice);
RetailSprites.BeginFrame(pDevice); // retail UI pictures decoded since the last frame (kept, never evicted)
DX9Backend.NewFrame();
Win32Backend.NewFrame(clientW, clientH);
// Fallback: if Win32Backend could not determine display size, read from the D3D9 viewport.
if (io.DisplaySize.X <= 1 || io.DisplaySize.Y <= 1)
@ -480,65 +618,52 @@ internal static class EngineFrameController
io.DisplaySize = new System.Numerics.Vector2(vpW, vpH);
}
long now = Stopwatch.GetTimestamp();
float dt = (float)(now - _lastFrameTicks) / Stopwatch.Frequency;
_lastFrameTicks = now;
io.DeltaTime = dt > 0f ? dt : 1f / 60f;
// With ViewportsEnable on, ImGui routes mouse and window positions in
// absolute screen coords. The main viewport's Pos must equal the game
// client's screen origin so clicks over the main viewport map to the
// correct windows, and popped-out viewports share a coord system with
// the main one.
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
int screenX = 0, screenY = 0;
if (_gameHwnd != IntPtr.Zero)
{
ClientPoint p = new ClientPoint { X = 0, Y = 0 };
if (ClientToScreen(_gameHwnd, ref p)) { screenX = p.X; screenY = p.Y; }
}
ImGuiViewportPtr mainVp = ImGuiNET.ImGui.GetMainViewport();
mainVp.Pos = new System.Numerics.Vector2(screenX, screenY);
mainVp.Size = io.DisplaySize;
mainVp.WorkPos = new System.Numerics.Vector2(screenX, screenY);
mainVp.WorkSize = io.DisplaySize;
}
ImGuiNET.ImGui.NewFrame();
frameStarted = true;
// EnableImGuiShell gates the in-AC ImGui surface as a whole: both the
// RynthCore overlay bar and any plugin-drawn ImGui windows. Plugins
// still load, init, and tick when this is off — they just don't
// draw, so Avalonia panels can drive them via the plugin's C exports.
if (_dropImGuiTextFocus)
{
// An Avalonia TextBox took the keyboard: end ImGui's text edit.
_dropImGuiTextFocus = false;
ImGuiNET.ImGui.SetWindowFocus(null);
}
// EnableImGuiShell gates the old diagnostic shell and plugin-drawn
// ImGui windows (plugin code on AC's thread: FORCE-gated, stays off).
if (Plugins.EngineSettings.EnableImGuiShell)
{
RynthCoreShell.Render(_frameCount);
PluginManager.RenderAll();
}
bool captureMouse =
ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow) ||
ImGuiNET.ImGui.IsAnyItemActive();
bool captureKeyboard = ImGuiNET.ImGui.IsAnyItemActive();
if (PanelsLive)
{
// World overlays: built into UnderUiLayer's list, drawn next frame at
// AC's 3D->UI transition (under AC's UI and every panel), no input.
Hud.MonsterHud.Draw(_uiScale);
if (ImGuiBar.Visible)
ImGuiBar.Draw(_uiScale);
ImGuiPanelHost.DrawAll(_uiScale);
ImGuiBar.SyncPopOut(_uiScale);
}
if (ImGuiFontTest.Enabled)
ImGuiFontTest.Draw(_uiScale);
ImGuiNET.ImGui.EndFrame();
frameEnded = true;
ImGuiNET.ImGui.Render();
Win32Backend.UpdateCaptureFlags(captureMouse, captureKeyboard);
ImGuiAssertLog.Poll();
_framesBuilt++;
_lastDisplaySize = io.DisplaySize;
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
DX9Backend.RenderDrawData(drawData, pDevice);
// OverlayTextureRenderer.Render is now driven from EndSceneHook.EndSceneDetour
// directly so the Avalonia compositor runs even when EnableImGuiBackend=false.
// Leaving it out of this call site avoids double-blit when ImGui is also active.
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
ImGuiNET.ImGui.UpdatePlatformWindows();
ImGuiNET.ImGui.RenderPlatformWindowsDefault();
}
// io.WantCaptureMouse already applies ImGui's own button-ownership
// rule; io.WantTextInput is true only while a text field is edited.
// MonsterHud.WantsMouse: the cursor is on a clickable nameplate (or a
// press that began on one is held), so that click is the plate's.
Win32Backend.UpdateCaptureFlags(io.WantCaptureMouse || Hud.MonsterHud.WantsMouse, io.WantTextInput);
ArbitrateTextFocus(io.WantTextInput);
return true;
}
catch (Exception ex)
{
@ -552,7 +677,46 @@ internal static class EngineFrameController
{
}
Win32Backend.ClearCaptureFlags();
RynthLog.Info($"EngineFrameController: frame {_frameCount} ImGui error: {ex.GetType().Name}: {ex.Message}");
return false;
}
finally
{
ImGuiNET.ImGui.SetCurrentContext(previousContext);
}
}
private static void ArbitrateTextFocus(bool imguiText)
{
bool avaloniaText = Win32Backend.AvaloniaTextInputActive;
if (imguiText && !_prevImGuiText && avaloniaText)
{
// An ImGui field just started typing: Avalonia gives up the keyboard.
Win32Backend.AvaloniaTextInputActive = false;
UI.AvaloniaOverlay.ClearTextFocus();
avaloniaText = false;
}
else if (avaloniaText && !_prevAvaloniaText && imguiText)
{
_dropImGuiTextFocus = true;
}
_prevImGuiText = imguiText;
_prevAvaloniaText = avaloniaText;
}
/// <summary>Draws the frame <see cref="BuildImGuiFrame"/> produced.</summary>
private static void SubmitImGuiFrame(IntPtr pDevice)
{
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
ImGuiNET.ImGui.SetCurrentContext(_context);
try
{
DX9Backend.RenderDrawData(ImGuiNET.ImGui.GetDrawData(), pDevice);
}
catch (Exception ex)
{
RynthLog.Info($"EngineFrameController: frame {_frameCount} ImGui submit error: {ex.GetType().Name}: {ex.Message}");
}
finally
{

View file

@ -0,0 +1,74 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiAssertLog.cs
// Surfaces Dear ImGui's soft asserts in the engine log.
//
// Our cimgui build routes IM_ASSERT into a native ring buffer instead of
// aborting (native/cimgui/rynth_imconfig.h). Poll() runs on AC's thread after
// each ImGui frame: it reads one int, and only formats and logs when new
// failures appeared. The first MaxLoggedInFull are logged individually; after
// that a count is logged at most once a minute so a per-frame assert can't
// flood the log.
// ============================================================================
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ImGuiAssertLog
{
private const int MaxLoggedInFull = 50;
private const int RingSlots = 16; // kAssertSlots in rynth_cimgui_ext.cpp
private static delegate* unmanaged[Cdecl]<int> _getCount;
private static delegate* unmanaged[Cdecl]<int, byte*, int, int> _getText;
private static int _seen;
private static int _loggedInFull;
private static int _suppressed;
private static long _lastSummaryTicks;
/// <summary>Resolves the ring-buffer exports. Called by ImGuiSelfTest once the build is verified.</summary>
public static void Bind(IntPtr cimguiModule)
{
if (NativeLibrary.TryGetExport(cimguiModule, "RynthImGui_GetAssertCount", out IntPtr count) &&
NativeLibrary.TryGetExport(cimguiModule, "RynthImGui_GetAssertText", out IntPtr text))
{
_getCount = (delegate* unmanaged[Cdecl]<int>)count;
_getText = (delegate* unmanaged[Cdecl]<int, byte*, int, int>)text;
// Asserts from an earlier engine generation (the DLL outlives RL) are not ours to report.
_seen = _getCount();
}
}
public static void Poll()
{
if (_getCount == null) return;
int count = _getCount();
if (count == _seen) return;
int first = Math.Max(_seen, count - RingSlots);
_suppressed += first - _seen; // overwritten before we could read them
byte* buf = stackalloc byte[256];
for (int i = first; i < count; i++)
{
if (_loggedInFull >= MaxLoggedInFull) { _suppressed++; continue; }
int len = _getText(i, buf, 256);
if (len < 0) { _suppressed++; continue; }
_loggedInFull++;
RynthLog.UI($"ImGui assert #{i + 1}: {Marshal.PtrToStringAnsi((IntPtr)buf, len)}");
}
_seen = count;
if (_suppressed > 0)
{
long now = Stopwatch.GetTimestamp();
if (now - _lastSummaryTicks >= Stopwatch.Frequency * 60)
{
RynthLog.UI($"ImGui asserts: {_suppressed} more not logged individually ({count} total this load).");
_suppressed = 0;
_lastSummaryTicks = now;
}
}
}
}

View file

@ -0,0 +1,448 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiBar.cs
// The overlay bar's ImGui face (docs/IMGUI_PARITY_PLAN.md §2.0).
//
// Same content as the Avalonia bar, as square Phosphor icon buttons with
// the names in tooltips: the grip (RC: build stamp tooltip), one button per
// registered panel except the ones the RynthAi launcher opens (PanelIcons;
// an unknown panel shows its first letter), reload (RL) and pop out.
// Dragging the grip moves the bar; the position is the shared bar= row in
// panel_state.txt. Right-click a panel button (or the grip for the bar
// itself) to choose which face shows it docked. Pop out moves the ImGui bar
// into its own window (ImGuiPopOuts, sized to its content; dock back
// returns it); a bar whose face is Avalonia/Both still pops out as the
// Avalonia bar.
//
// Face key "__bar" in panel_faces.txt; code default Avalonia. While the ImGui
// bar shows, the docked Avalonia bar is hidden and takes no clicks
// (AvaloniaOverlay.DockedBarSuppressed). AC thread except where noted.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using ImGuiNET;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.ScriptWindows;
namespace RynthCore.Engine.ImGuiBackend;
internal static class ImGuiBar
{
public const string FaceKey = "__bar";
// Opened from the RynthAi launcher, not the bar (AvaloniaOverlay.BuildRoot). Lua has
// its own bar button since it became the RynthLua plugin. "Monsters" (retired 2026-10-01,
// still registered by EntryPoint) must never get a button: PanelRouter sends it to Damage.
private static readonly HashSet<string> LauncherOnly = new(StringComparer.OrdinalIgnoreCase)
{ "Monsters", "Damage", "Settings", "Nav", "Meta", "Items" };
private static readonly PanelFace[] Faces = { PanelFace.Avalonia, PanelFace.ImGui, PanelFace.Both };
private static readonly string[] FaceNames = { "Avalonia", "ImGui", "Both (side by side)" };
private sealed record ButtonInfo(string Title, string Id, string PopupId, string Icon, bool Letter, string Tooltip,
bool ImGuiOnly = false);
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
private static readonly string[] ImGuiOnlyBarPanels = { Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title };
// Known panels' icons (DrakBot's where the same window exists); others show their first letter.
private static readonly Dictionary<string, string> PanelIcons = new(StringComparer.OrdinalIgnoreCase)
{
["RynthAi"] = PhosphorIcons.Robot,
["Chat"] = PhosphorIcons.ChatCircleText,
["ChatFilters"] = PhosphorIcons.Funnel,
["Radar"] = PhosphorIcons.Compass,
["Vision"] = PhosphorIcons.Eye,
["Nav"] = PhosphorIcons.MapTrifold,
["RynthNav"] = PhosphorIcons.NavigationArrow,
["Tracker"] = PhosphorIcons.ChartLineUp,
["Lua"] = PhosphorIcons.FileCode,
["Settings"] = PhosphorIcons.Gear,
["Damage"] = PhosphorIcons.ChartBar,
["Meta"] = PhosphorIcons.ListChecks,
["Items"] = PhosphorIcons.Backpack,
["Loot Editor"] = PhosphorIcons.TreasureChest,
["Skills"] = PhosphorIcons.GraduationCap,
["Sense"] = PhosphorIcons.Binoculars,
["Status"] = PhosphorIcons.Info,
["Inventory"] = PhosphorIcons.Package, // not Backpack: the dashboard's Items launcher has that
["Log"] = PhosphorIcons.TerminalWindow,
};
/// <summary>A panel's bar icon: its Phosphor icon, else its first letter (letter = true).</summary>
internal static string IconFor(string title, out bool letter)
{
letter = !PanelIcons.TryGetValue(title, out string? icon);
if (!letter) return icon!;
foreach (char c in title)
if (char.IsLetterOrDigit(c)) return char.ToUpperInvariant(c).ToString();
return "?";
}
// Square buttons, logical px (x the DPI scale).
private const float ButtonSize = 20f, ButtonGap = 3f;
private static ButtonInfo[]? _buttons;
private static string _tooltip = "";
private static bool _placed;
private static Vector2 _pos, _persistedPos;
private const string PopOutTitle = "__bar";
// Popped out (the ImGui bar in its own window). Read from panel_state once,
// then kept here so a switch shows at once (the file is written in the background).
private static bool? _floating;
private static bool Floating => _floating ??= PanelStateStore.BarFloating;
/// <summary>True when the ImGui bar is popped out into its own window.</summary>
public static bool PoppedOut => ResolveFace() == PanelFace.ImGui && Floating;
/// <summary>The bar's docked face. Any thread.</summary>
public static PanelFace ResolveFace()
{
if (!Plugins.EngineSettings.EnableImGuiBackend) return PanelFace.Avalonia;
if (!Plugins.EngineSettings.EnableAvaloniaOverlay) return PanelFace.ImGui;
return PanelFaceStore.TryGet(FaceKey, out PanelFace f) ? f : PanelFace.ImGui;
}
/// <summary>
/// Shows/hides the docked Avalonia bar to match the bar's face. Call at
/// init and whenever the face or the ImGui layer changes. Any thread.
/// </summary>
public static void ApplyFace()
{
AvaloniaOverlay.SetDockedBarSuppressed(ResolveFace() == PanelFace.ImGui);
_placed = false; // re-read the shared position next frame
}
/// <summary>True when the ImGui bar should draw (docked face ImGui/Both, not popped out).</summary>
public static bool Visible => ResolveFace() != PanelFace.Avalonia && !Floating;
/// <summary>
/// Opens or closes the bar's own window to match <see cref="PoppedOut"/>. AC
/// thread, in the world, with the main context current (after the panels).
/// </summary>
public static void SyncPopOut(float s)
{
bool have = ImGuiPopOuts.IsPopped(PopOutTitle);
if (PoppedOut && !have)
{
EnsureButtons();
var saved = PanelStateStore.BarFloatingPosition;
Vector2 at = saved.HasValue
? new Vector2((float)saved.Value.Left, (float)saved.Value.Top)
: ImGuiPopOuts.ClientOriginOnScreen() + _pos;
ImGuiPopOuts.Open(PopOutTitle, (int)at.X, (int)at.Y, (int)(400 * s), (int)(28 * s), 0, 0, s,
draw: DrawPopped,
onMoved: static (x, y) => UiBackgroundWriter.Enqueue("persist bar", () => PanelStateStore.SetBarFloatingState(true, x, y)),
sizeToContent: true);
}
else if (!PoppedOut && have)
{
ImGuiPopOuts.Close(PopOutTitle);
}
}
/// <summary>
/// Pops the ImGui bar out into its own window (at the docked bar's screen
/// spot) or docks it back where it was docked. The window opens/closes on
/// the next frame (SyncPopOut). Any thread.
/// </summary>
public static void SetPoppedOut(bool popped)
{
if (popped == Floating) return;
_floating = popped;
if (popped)
{
Vector2 screen = ImGuiPopOuts.ClientOriginOnScreen() + _pos;
UiBackgroundWriter.Enqueue("pop out bar", () => PanelStateStore.SetBarFloatingState(true, screen.X, screen.Y));
}
else
{
_placed = false; // back where it was docked (bar= row); the popped-out spot is kept
var at = PanelStateStore.BarFloatingPosition ?? (0, 0);
UiBackgroundWriter.Enqueue("dock bar", () => PanelStateStore.SetBarFloatingState(false, at.Item1, at.Item2));
}
}
/// <summary>The bar in its own window: the same content at the pop-out's panel origin, sized to fit. AC thread.</summary>
private static void DrawPopped(float s, Vector2 display)
{
EnsureButtons();
float place = AvaloniaOverlay.InputScale > 0 ? AvaloniaOverlay.InputScale : 1f;
ImGuiNET.ImGui.SetNextWindowPos(ImGuiPopOuts.PanelOrigin, ImGuiCond.Always);
PushBarWindowStyle(s);
ImGuiNET.ImGui.Begin("##rc_bar", BarFlags);
try
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
DrawContent(s, place, popped: true);
ImGuiNET.ImGui.PopFont();
// Not on its first frame: an auto-resizing window has no content size yet
// and reports just its padding (8x6), which would shrink the window to it.
if (!ImGuiNET.ImGui.IsWindowAppearing())
ImGuiPopOuts.ReportContentSize(ImGuiNET.ImGui.GetWindowSize());
}
finally
{
ImGuiNET.ImGui.End();
PopBarWindowStyle();
}
}
private const ImGuiWindowFlags BarFlags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize
| ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoMove
| ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoFocusOnAppearing
| ImGuiWindowFlags.NoBringToFrontOnFocus | ImGuiWindowFlags.NoNav;
private static void PushBarWindowStyle(float s)
{
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 3) * s);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(ButtonGap, ButtonGap) * s);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, RynthTheme.BarRounding);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowMinSize, Vector2.One);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, RynthTheme.BarBackground);
}
private static void PopBarWindowStyle()
{
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.PopStyleVar(5);
}
public static void Draw(float s)
{
EnsureButtons();
float place = AvaloniaOverlay.InputScale > 0 ? AvaloniaOverlay.InputScale : 1f;
bool both = ResolveFace() == PanelFace.Both;
if (!_placed)
{
var saved = PanelStateStore.BarPosition;
Vector2 logical = saved.HasValue ? new Vector2((float)saved.Value.Left, (float)saved.Value.Top) : new Vector2(50, 5);
if (both) logical += new Vector2(24, 24);
_pos = _persistedPos = logical * place;
ImGuiNET.ImGui.SetNextWindowPos(_pos, ImGuiCond.Always);
_placed = true;
}
PushBarWindowStyle(s);
ImGuiNET.ImGui.Begin("##rc_bar", BarFlags);
try
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
DrawContent(s, place, popped: false);
ImGuiNET.ImGui.PopFont();
}
finally
{
_pos = ImGuiNET.ImGui.GetWindowPos();
ImGuiNET.ImGui.End();
PopBarWindowStyle();
}
if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && _pos != _persistedPos)
{
_persistedPos = _pos;
Vector2 logical = _pos / place - (both ? new Vector2(24, 24) : Vector2.Zero);
double left = logical.X, top = logical.Y;
UiBackgroundWriter.Enqueue("persist bar", () => PanelStateStore.SetBarPosition(left, top));
if (!both) AvaloniaOverlay.SyncDockedBarPosition(left, top);
}
}
private static void DrawContent(float s, float place, bool popped)
{
var square = new Vector2(ButtonSize, ButtonSize) * s;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Ui14);
// Grip (the RC label's place, in its light green): the bar's drag handle
// (the Avalonia bar drags from its left edge, over the same spot).
Vector2 rcPos = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.InvisibleButton("##bardrag", new Vector2(square.X * 0.8f, square.Y));
if (popped)
{
// Popped out, the window itself moves (it follows the cursor from here on).
if (ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 2f))
ImGuiPopOuts.BeginMoveCurrent();
}
else if (ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 0f))
{
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
Vector2 size = ImGuiNET.ImGui.GetWindowSize();
Vector2 next = ImGuiNET.ImGui.GetWindowPos() + ImGuiNET.ImGui.GetIO().MouseDelta;
if (display.X > 1)
next = Vector2.Clamp(next, Vector2.Zero, Vector2.Max(Vector2.Zero, display - size));
ImGuiNET.ImGui.SetWindowPos(next);
}
ImGuiNET.ImGui.SetItemTooltip(_tooltip);
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
ImGuiNET.ImGui.OpenPopup("##face_bar");
PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.DotsSixVertical, rcPos, new Vector2(square.X * 0.8f, square.Y), RynthTheme.RcLabel);
FacePopup("##face_bar", FaceKey, hasImGuiFace: true);
// Collapse: the bar folds to its grip and this caret.
bool collapsed = RynthAiDashboardState.BarCollapsed;
ImGuiNET.ImGui.SameLine(0, 0);
Vector2 cPos = ImGuiNET.ImGui.GetCursorScreenPos();
var caretSize = new Vector2(square.X * 0.6f, square.Y);
if (ImGuiNET.ImGui.InvisibleButton("##barcollapse", caretSize))
RynthAiDashboardState.SetBarCollapsed(!collapsed);
bool caretHot = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.SetItemTooltip(collapsed ? "Show the bar" : "Fold the bar to this button");
PhosphorIcons.DrawCentered(dl, iconFont, collapsed ? PhosphorIcons.CaretRight : PhosphorIcons.CaretLeft, cPos, caretSize,
caretHot ? RynthTheme.RcLabel : 0xFF9A9A9Au);
if (collapsed) return;
PushBarButtonStyle(s);
ImFontPtr letterFont = ImGuiFonts.Get(UiFont.UiBold11);
foreach (ButtonInfo b in _buttons!)
{
ImGuiNET.ImGui.SameLine();
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText))
PanelRouter.Toggle(b.Title);
ImGuiNET.ImGui.SetItemTooltip(b.Tooltip);
if (b.ImGuiOnly) continue; // no Avalonia face: no face to choose
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
ImGuiNET.ImGui.OpenPopup(b.PopupId);
FacePopup(b.PopupId, b.Title, ImGuiPanelHost.HasFace(b.Title));
}
// Script windows (decision 2): one button with a menu, only while a ShowInBar
// script window exists. They never get buttons of their own (EnsureButtons
// lists OverlayHost's engine panels only; script windows are dynamic entries).
ScriptBarItem[] scripts = ScriptWindowRegistry.BarItems;
if (scripts.Length > 0)
{
ImGuiNET.ImGui.SameLine();
if (IconButton("##scripts", iconFont, PhosphorIcons.AppWindow, square, RynthTheme.BarText))
ImGuiNET.ImGui.OpenPopup("##scripts_menu");
ImGuiNET.ImGui.SetItemTooltip("Script windows");
}
ImGuiNET.ImGui.SameLine(0, 6 * s);
if (IconButton("##reload", iconFont, PhosphorIcons.ArrowsClockwise, square, RynthTheme.ReloadLabel))
ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null);
ImGuiNET.ImGui.SetItemTooltip("Engine reload (RL) — shut down, FreeLibrary, reload from disk, re-init.");
if (ResolveFace() == PanelFace.ImGui)
{
ImGuiNET.ImGui.SameLine();
if (IconButton("##popout", iconFont, popped ? PhosphorIcons.ArrowSquareIn : PhosphorIcons.ArrowSquareOut, square, RynthTheme.PopOutLabel))
SetPoppedOut(!popped);
ImGuiNET.ImGui.SetItemTooltip(popped ? "Dock the bar back into the game window." : "Pop the bar out into its own floating window.");
}
else if (Plugins.EngineSettings.EnableAvaloniaOverlay) // Avalonia/Both bar: pops out as the Avalonia bar
{
ImGuiNET.ImGui.SameLine();
if (IconButton("##popout", iconFont, PhosphorIcons.ArrowSquareOut, square, RynthTheme.PopOutLabel))
{
Vector2 logical = ImGuiNET.ImGui.GetWindowPos() / place;
AvaloniaOverlay.PopOutBarFrom(logical.X, logical.Y);
}
ImGuiNET.ImGui.SetItemTooltip("Pop the bar out into its own floating window.");
}
PopBarButtonStyle();
// Drawn after the bar buttons' style is popped, so the menu has the normal look.
ScriptsMenu(scripts);
}
/// <summary>
/// The Scripts button's popup: the ShowInBar script windows grouped by script, a
/// checkbox item each for open. Toggling tells the owner (Visibility, reason 2).
/// </summary>
private static void ScriptsMenu(ScriptBarItem[] items)
{
if (!ImGuiNET.ImGui.BeginPopup("##scripts_menu")) return;
try
{
if (items.Length == 0) ImGuiNET.ImGui.CloseCurrentPopup();
uint disabled = ImGuiNET.ImGui.GetColorU32(ImGuiCol.TextDisabled);
foreach (ScriptBarItem item in items)
{
if (item.GroupStart)
{
// A script's own text: never a format string.
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, disabled);
ImGuiNET.ImGui.TextUnformatted(item.Group);
ImGuiNET.ImGui.PopStyleColor();
}
bool open = ImGuiPanelHost.IsOpen(item.PanelKey);
if (ImGuiNET.ImGui.MenuItem(item.MenuLabel, "", open))
ScriptWindowRegistry.PlayerSetVisible(item.Window, !open);
}
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
/// <summary>A square bar button (the bar's button style) with an icon, or a letter, centred on it.</summary>
private static bool IconButton(string id, ImFontPtr font, string icon, Vector2 size, uint color)
{
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos();
bool clicked = ImGuiNET.ImGui.Button(id, size);
PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), font, icon, at, size, color);
return clicked;
}
private static void FacePopup(string popupId, string title, bool hasImGuiFace)
{
if (!ImGuiNET.ImGui.BeginPopup(popupId)) return;
ImGuiNET.ImGui.TextDisabled(title == FaceKey ? "Bar, docked, shows as" : "Docked, shows as");
PanelFace current = title == FaceKey ? ResolveFace() : PanelRouter.ResolveDockedFace(title);
for (int i = 0; i < Faces.Length; i++)
{
bool enabled = Faces[i] == PanelFace.Avalonia || hasImGuiFace;
if (ImGuiNET.ImGui.MenuItem(FaceNames[i], "", current == Faces[i], enabled))
PanelRouter.SetDockedFace(title, Faces[i]);
}
if (!hasImGuiFace)
ImGuiNET.ImGui.TextDisabled("(no ImGui version yet)");
ImGuiNET.ImGui.EndPopup();
}
private static void PushBarButtonStyle(float s)
{
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 2f);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, RynthTheme.BarButton);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, RynthTheme.Argb(0xFF2A3850));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonActive, RynthTheme.Argb(0xFF34466A));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, RynthTheme.BarButtonBorder);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, RynthTheme.BarText);
}
private static void PopBarButtonStyle()
{
ImGuiNET.ImGui.PopStyleColor(5);
ImGuiNET.ImGui.PopStyleVar(3);
}
private static void EnsureButtons()
{
if (_buttons != null) return;
var list = new List<ButtonInfo>();
foreach (var (title, _) in OverlayHost.GetPanels())
if (!LauncherOnly.Contains(title))
{
string icon = IconFor(title, out bool letter);
list.Add(new ButtonInfo(title, "##bar_" + title, "##face_" + title, icon, letter,
title + "\nRight-click: which face shows it docked."));
}
foreach (string title in ImGuiOnlyBarPanels)
if (ImGuiPanelHost.HasFace(title) && !LauncherOnly.Contains(title))
{
string icon = IconFor(title, out bool letter);
list.Add(new ButtonInfo(title, "##bar_" + title, "##face_" + title, icon, letter, title, ImGuiOnly: true));
}
_buttons = list.ToArray();
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar face.";
}
}

View file

@ -0,0 +1,72 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiFontTest.cs
// Developer check for the atlas and theme (docs/IMGUI_PARITY_PLAN.md P0
// acceptance): every baked font with sample text, every merged symbol and
// icons inline with text (to judge their size and baseline), then every
// baked Phosphor icon, plus the theme swatches. Only with RYNTHCORE_IMGUI_FONTTEST=1 in the
// client's environment or after /rc imgui fonttest; never shown otherwise.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal static class ImGuiFontTest
{
/// <summary>Shown when RYNTHCORE_IMGUI_FONTTEST=1, or toggled with /rc imgui fonttest.</summary>
public static volatile bool Enabled =
Environment.GetEnvironmentVariable("RYNTHCORE_IMGUI_FONTTEST") == "1";
private const string Sample = "The quick brown fox 0123456789 — …";
private const string Symbols = "● • → ←";
private const string Icons = PhosphorIcons.Gear + " Settings " + PhosphorIcons.Play + " Run " + PhosphorIcons.Trash
+ " Delete " + PhosphorIcons.Sword + PhosphorIcons.Sparkle + PhosphorIcons.SneakerMove + PhosphorIcons.Bag + " Hxg";
public static void Draw(float scale)
{
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(560, 520) * scale, ImGuiCond.FirstUseEver);
if (ImGuiNET.ImGui.Begin("RynthCore font test##fonttest"))
{
ImGuiNET.ImGui.TextDisabled($"scale {scale:0.##} atlas {ImGuiNET.ImGui.GetIO().Fonts.TexWidth}x{ImGuiNET.ImGui.GetIO().Fonts.TexHeight}");
for (UiFont f = 0; f < UiFont.Count; f++)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(f));
ImGuiNET.ImGui.TextUnformatted($"{f,-9} {Sample} {Symbols} {Icons}");
ImGuiNET.ImGui.PopFont();
}
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui14));
ImGuiNET.ImGui.PushTextWrapPos(0);
ImGuiNET.ImGui.TextUnformatted(PhosphorIcons.Baked);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.Separator();
Swatch("bar", RynthTheme.BarBackground); Swatch("button", RynthTheme.BarButton);
Swatch("glass", RynthTheme.PanelGlass); Swatch("teal", RynthTheme.PanelBorder);
Swatch("header", RynthTheme.PanelHeader); Swatch("rynthai", RynthTheme.RynthAiBackground);
Swatch("gold", RynthTheme.RadarGold);
ImGuiNET.ImGui.NewLine();
ImGuiNET.ImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.RcLabel), "RC");
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.ReloadLabel), "RL");
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.PopOutLabel), PhosphorIcons.ArrowSquareOut);
}
ImGuiNET.ImGui.End();
}
private static void Swatch(string label, uint color)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float h = ImGuiNET.ImGui.GetTextLineHeight();
ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(p, p + new Vector2(h * 2, h), color);
ImGuiNET.ImGui.Dummy(new Vector2(h * 2, h));
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.TextUnformatted(label);
ImGuiNET.ImGui.SameLine();
}
}

View file

@ -0,0 +1,627 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiFonts.cs
// The ImGui font atlas (docs/IMGUI_PARITY_PLAN.md §4.4).
//
// ImGui 1.91 has no dynamic font sizes, so every size a panel face uses is
// baked once, at the DPI scale the context is created with:
// Segoe UI 9/10/11/14 and Bold 11/14 (panel text, headers, radar compass),
// Consolas 9/10/12 (Tracker, Log, Meta rows), Cascadia Mono 12 (Meta
// source; Consolas if missing), and the chat monospace at 8-18 in steps
// of 2 (the chat font slider snaps to the nearest).
// The few symbol glyphs still drawn as text (SymbolCodepoints) are merged in
// from Segoe UI Symbol wherever the main font lacks them.
//
// Icons: the Phosphor icon font (MIT, Assets/Fonts/Phosphor.ttf, embedded in
// this assembly) is merged into every baked font, the scaled sets included,
// at the web font's code points (U+E000 up), so an icon is text
// (PhosphorIcons). Only PhosphorIcons.Baked is merged, not the whole set.
// Each font gets the icons at about 1.2x its em (Phosphor's em is its pixel
// size; Segoe UI's is 0.75 of it), shifted down so the icon's centre sits on
// the text's cap-height centre, on a fixed advance so icon columns line up.
//
// Font files are read by Preload() on the engine's init worker, so AC's
// render thread only copies bytes into the atlas. The native TTF buffers and
// glyph ranges stay alive until Free() (after the context is destroyed).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal enum UiFont
{
Ui10, Ui11, Ui14,
UiBold11, UiBold14,
Mono9, Mono10, Mono12,
Code12,
Chat8, Chat10, Chat12, Chat14, Chat16, Chat18,
Ui9,
// RynthAi dashboard: Cascadia Mono (Consolas if missing), like the Avalonia face.
Dash9, Dash10, Dash11, Dash14,
// RynthVision combat numbers: baked big so they stay sharp.
NumBold24,
// Scaled-up nameplate text and big combat numbers: picked by Sharp() so text is
// shrunk from a bigger bake, never stretched from a smaller one.
Ui18, NumBold48,
Count,
}
internal static unsafe class ImGuiFonts
{
private static readonly string FontsDir = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
// Main text: Basic Latin + Latin-1, general punctuation (— – … • ‘ ’ “ ”), arrows.
private static readonly ushort[] MainRanges = { 0x0020, 0x00FF, 0x2010, 0x2027, 0x2190, 0x21FF, 0 };
// Symbols still drawn as text, merged from Segoe UI Symbol where the main font
// lacks them. The panels' other symbols (⚔ ✦ ➤ ◫ ♥ ◆ ⚙ ▾ ▴ ↗ ↙ ◢ ✕ ☑ ☐ ▶ ▼ ▲ ◀ ■
// ❏ ↺ ✎ − ⬡ ◎ ⚒ ...) are Phosphor icons now (PhosphorIcons). Arrows, bullets and
// dashes are in MainRanges.
private static readonly ushort[] SymbolCodepoints =
{
0x25CF, // ● (Meta source: unapplied edits)
};
private static byte[]? _segoe, _segoeBold, _consolas, _cascadia, _symbol, _phosphor;
private const string PhosphorResource = "RynthCore.Engine.Assets.Fonts.Phosphor.ttf";
// Icon size relative to the text's em, capped at the line height (x0.95) for
// fonts whose em fills the line (Consolas): bigger icons climb out of the line.
private const float IconScale = 1.2f, IconMaxOfLine = 0.95f;
// Where a Phosphor icon's box centre sits above the baseline, in its em
// (the 1024-unit box runs from -64 to 960).
private const float IconCentreEm = 448f / 1024f;
// Phosphor's regular strokes are 1/16 em: at 9-13 px they rasterize thin and grey.
private const float IconRasterizerMultiply = 1.2f;
private static volatile bool _preloaded;
private static readonly List<IntPtr> NativeBuffers = new();
private static readonly ImFontPtr[] Fonts = new ImFontPtr[(int)UiFont.Count];
// Per-panel text size (UI.PanelTextScale): the same fonts baked bigger, one
// set per size in use. Get() returns the set for CurrentStep, which the panel
// host sets while it draws a panel, so every face's text grows without any
// face code changing. Baked (not stretched), so the big text stays sharp.
private static readonly Dictionary<int, ImFontPtr[]> ScaledFonts = new();
/// <summary>Text size step of the panel being drawn (0 = normal). Render thread.</summary>
public static int CurrentStep;
// Stopwatch timestamp the requested rebuild is due at; 0 = none requested.
private static long _rebuildDue;
/// <summary>
/// A panel's text size changed: rebuild the font atlas before a frame at least
/// <paramref name="delayMs"/> from now. Each request moves the time out, so a run
/// of changes (clicks, wheel notches) re-bakes once, after the last. Any thread.
/// </summary>
public static void RequestRebuild(int delayMs = 0)
{
long due = Stopwatch.GetTimestamp() + Math.Max(0, delayMs) * Stopwatch.Frequency / 1000;
if (due == 0) due = 1;
System.Threading.Volatile.Write(ref _rebuildDue, due);
}
/// <summary>True once per request, when it is due. Render thread, before NewFrame.</summary>
public static bool TakeRebuildRequest()
{
long due = System.Threading.Volatile.Read(ref _rebuildDue);
if (due == 0 || Stopwatch.GetTimestamp() < due) return false;
// A newer request made meanwhile keeps its own (later) time.
return System.Threading.Interlocked.CompareExchange(ref _rebuildDue, 0, due) == due;
}
/// <summary>
/// The baked size step closest to <paramref name="step"/> (0 = normal): the step
/// itself once baked. Between a size change and the re-bake it lands on, a panel
/// keeps drawing at a nearby baked size instead of dropping to normal. Render thread.
/// </summary>
public static int BakedStepNear(int step)
{
if (step <= 0 || ScaledFonts.ContainsKey(step)) return Math.Max(0, step);
int best = 0;
foreach (int baked in ScaledFonts.Keys)
if (Math.Abs(baked - step) < Math.Abs(best - step)) best = baked;
return best;
}
// Native copies of the font files and glyph ranges, made once: rebuilds reuse them.
private static IntPtr _nSegoe, _nSegoeBold, _nMono, _nCode, _nSymbol, _nPhosphor;
private static ushort* _mainRanges, _symbolRanges, _iconRanges;
/// <summary>Reads the font files. Engine init worker thread; safe to skip (Build reads them itself).</summary>
public static void Preload()
{
if (_preloaded) return;
_segoe = TryRead("segoeui.ttf");
_segoeBold = TryRead("segoeuib.ttf");
_consolas = TryRead("consola.ttf");
_cascadia = TryRead("CascadiaMono.ttf");
_symbol = TryRead("seguisym.ttf");
_phosphor = TryReadResource(PhosphorResource);
_preloaded = true;
}
/// <summary>A baked font. Before Build (or if it failed) this is ImGui's default font.</summary>
public static ImFontPtr Get(UiFont font)
{
if (CurrentStep > 0 && ScaledFonts.TryGetValue(CurrentStep, out ImFontPtr[]? set))
{
ImFontPtr s = set[(int)font];
if (s.NativePtr != null) return s;
}
ImFontPtr f = Fonts[(int)font];
return f.NativePtr != null ? f : ImGuiNET.ImGui.GetIO().FontDefault;
}
private static readonly UiFont[] SharpRegular = { UiFont.Ui9, UiFont.Ui10, UiFont.Ui11, UiFont.Ui14, UiFont.Ui18 };
private static readonly UiFont[] SharpBold = { UiFont.UiBold11, UiFont.UiBold14, UiFont.NumBold24, UiFont.NumBold48 };
/// <summary>
/// The smallest baked font at least <paramref name="px"/> tall (else the biggest), for text
/// drawn at a scaled size: shrinking a bigger bake stays sharp, stretching a smaller one blurs.
/// Draw with the returned font at <paramref name="px"/>.
/// </summary>
public static ImFontPtr Sharp(float px, bool bold)
{
UiFont[] set = bold ? SharpBold : SharpRegular;
ImFontPtr best = Get(set[0]);
for (int i = 0; i < set.Length; i++)
{
ImFontPtr f = Fonts[(int)set[i]];
if (f.NativePtr == null) continue;
best = f;
if (f.FontSize >= px - 0.5f) break;
}
return best;
}
/// <summary>The baked chat font nearest to <paramref name="points"/> (8-18).</summary>
public static ImFontPtr Chat(float points)
{
int step = Math.Clamp((int)MathF.Round((points - 8f) / 2f), 0, 5);
return Get(UiFont.Chat8 + step);
}
/// <summary>
/// Adds every font to the current context's atlas at <paramref name="scale"/>
/// (DPI / 96). AC thread, before the atlas texture is first built.
/// </summary>
public static void Build(ImGuiIOPtr io, float scale)
{
long t0 = Stopwatch.GetTimestamp();
PrepareNativeData();
ScaledFonts.Clear();
AddAll(io.Fonts, scale, RynthCore.Engine.UI.PanelTextScale.StepsInUse(), Fonts, ScaledFonts);
if (Fonts[(int)UiFont.Ui11].NativePtr != null)
io.NativePtr->FontDefault = Fonts[(int)UiFont.Ui11].NativePtr;
else
io.Fonts.AddFontDefault(); // no Segoe UI: ImGui's built-in font keeps text readable
double ms = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency;
RynthLog.UI($"ImGuiFonts: {CountBaked()} fonts queued at scale {scale:0.##} in {ms:0.0} ms " +
$"(Cascadia Mono {(_cascadia != null ? "found" : "missing, using Consolas")}, symbols {(_symbol != null ? "merged" : "missing")}, " +
$"icons {(_phosphor != null ? $"{IconCount()} merged" : "missing")}).");
}
/// <summary>The font files and glyph ranges as native memory, made once (rebuilds reuse them). AC thread.</summary>
private static void PrepareNativeData()
{
if (!_preloaded) Preload();
if (_mainRanges != null) return;
byte[]? mono = _consolas;
byte[]? code = _cascadia ?? _consolas;
_mainRanges = PinRanges(MainRanges);
_symbolRanges = PinRanges(SymbolRanges());
_iconRanges = PinRanges(IconRanges());
_nSegoe = ToNative(_segoe); _nSegoeBold = ToNative(_segoeBold); _nMono = ToNative(mono);
_nCode = ToNative(code); _nSymbol = ToNative(_symbol); _nPhosphor = ToNative(_phosphor);
}
/// <summary>
/// Queues every font into <paramref name="atlas"/>: the normal set into
/// <paramref name="baseSet"/>, a bigger copy per text size step into
/// <paramref name="scaled"/>. Touches no ImGui context and no static font
/// table, so the off-thread re-bake runs it too (after PrepareNativeData).
/// </summary>
private static void AddAll(ImFontAtlasPtr atlas, float scale, List<int> steps, ImFontPtr[] baseSet,
Dictionary<int, ImFontPtr[]> scaled)
{
byte[]? mono = _consolas;
byte[]? code = _cascadia ?? _consolas;
ushort* mainRanges = _mainRanges;
ushort* symbolRanges = _symbolRanges;
ushort* iconRanges = _iconRanges;
IntPtr segoe = _nSegoe, segoeBold = _nSegoeBold, consolas = _nMono, codeFont = _nCode, symbol = _nSymbol,
phosphor = _nPhosphor;
// Each base font's em and cap height, to size and place the icons merged into it.
FaceMetrics mSegoe = FaceMetrics.Read(_segoe), mSegoeBold = FaceMetrics.Read(_segoeBold),
mMono = FaceMetrics.Read(mono), mCode = FaceMetrics.Read(code);
ImFontPtr[] target = baseSet;
float factor = 1f;
void Add(UiFont id, IntPtr data, byte[]? bytes, FaceMetrics metrics, float px)
{
if (data == IntPtr.Zero || bytes == null) return;
float size = MathF.Round(px * scale * factor);
ImFontConfigPtr cfg = ImGuiNative.ImFontConfig_ImFontConfig();
try
{
cfg.FontDataOwnedByAtlas = false;
target[(int)id] = atlas.AddFontFromMemoryTTF(data, bytes.Length, size, cfg, (IntPtr)mainRanges);
if (symbol != IntPtr.Zero && _symbol != null)
{
cfg.MergeMode = true;
cfg.GlyphMinAdvanceX = 0;
atlas.AddFontFromMemoryTTF(symbol, _symbol.Length, size, cfg, (IntPtr)symbolRanges);
}
if (phosphor != IntPtr.Zero && _phosphor != null)
{
// Phosphor's em is its pixel size (ascent + descent = 1 em).
float em = size * metrics.EmPerPx;
float iconPx = MathF.Max(1f, MathF.Round(MathF.Min(em * IconScale, size * IconMaxOfLine)));
cfg.MergeMode = true;
// Whole-pixel advances, so horizontal oversampling buys nothing: 1 halves the icons' atlas space.
cfg.PixelSnapH = true;
cfg.OversampleH = 1;
cfg.GlyphMinAdvanceX = iconPx;
// Down (+y) from the shared baseline: the icon's centre onto the cap-height centre.
cfg.GlyphOffset = new Vector2(0, MathF.Round(IconCentreEm * iconPx - metrics.CapHalfEm * em));
cfg.RasterizerMultiply = IconRasterizerMultiply;
atlas.AddFontFromMemoryTTF(phosphor, _phosphor.Length, iconPx, cfg, (IntPtr)iconRanges);
}
}
finally
{
ImGuiNative.ImFontConfig_destroy(cfg.NativePtr);
}
}
Add(UiFont.Ui11, segoe, _segoe, mSegoe, 11); // first added = io.FontDefault unless set below
Add(UiFont.Ui10, segoe, _segoe, mSegoe, 10);
Add(UiFont.Ui14, segoe, _segoe, mSegoe, 14);
Add(UiFont.Ui9, segoe, _segoe, mSegoe, 9);
Add(UiFont.UiBold11, segoeBold, _segoeBold, mSegoeBold, 11);
Add(UiFont.UiBold14, segoeBold, _segoeBold, mSegoeBold, 14);
Add(UiFont.Mono9, consolas, mono, mMono, 9);
Add(UiFont.Mono10, consolas, mono, mMono, 10);
Add(UiFont.Mono12, consolas, mono, mMono, 12);
Add(UiFont.Code12, codeFont, code, mCode, 12);
Add(UiFont.Dash9, codeFont, code, mCode, 9);
Add(UiFont.Dash10, codeFont, code, mCode, 10);
Add(UiFont.Dash11, codeFont, code, mCode, 11);
Add(UiFont.Dash14, codeFont, code, mCode, 14);
Add(UiFont.NumBold24, segoeBold, _segoeBold, mSegoeBold, 24);
Add(UiFont.Ui18, segoe, _segoe, mSegoe, 18);
Add(UiFont.NumBold48, segoeBold, _segoeBold, mSegoeBold, 48);
for (int i = 0; i < 6; i++)
Add(UiFont.Chat8 + i, consolas, mono, mMono, 8 + i * 2);
// Bigger copies for each panel text size in use (chat keeps its own size setting).
foreach (int step in steps)
{
target = new ImFontPtr[(int)UiFont.Count];
factor = RynthCore.Engine.UI.PanelTextScale.Factor(step);
Add(UiFont.Ui11, segoe, _segoe, mSegoe, 11);
Add(UiFont.Ui10, segoe, _segoe, mSegoe, 10);
Add(UiFont.Ui14, segoe, _segoe, mSegoe, 14);
Add(UiFont.Ui9, segoe, _segoe, mSegoe, 9);
Add(UiFont.UiBold11, segoeBold, _segoeBold, mSegoeBold, 11);
Add(UiFont.UiBold14, segoeBold, _segoeBold, mSegoeBold, 14);
Add(UiFont.Mono9, consolas, mono, mMono, 9);
Add(UiFont.Mono10, consolas, mono, mMono, 10);
Add(UiFont.Mono12, consolas, mono, mMono, 12);
Add(UiFont.Code12, codeFont, code, mCode, 12);
Add(UiFont.Dash9, codeFont, code, mCode, 9);
Add(UiFont.Dash10, codeFont, code, mCode, 10);
Add(UiFont.Dash11, codeFont, code, mCode, 11);
Add(UiFont.Dash14, codeFont, code, mCode, 14);
scaled[step] = target;
}
}
// ── Re-bake off AC's thread ─────────────────────────────────────────
// A text size change needs a new atlas. Rasterizing it took 180-300 ms with one
// or two enlarged sizes (about 1 s with all ten), which froze the game for that
// long when it ran on the render thread. Instead a worker queues and builds a
// NEW atlas (no ImGui context involved) while frames go on with the old one;
// then, between frames, the main context and every pop-out are pointed at the
// new atlas, its texture is made, and the old atlas is destroyed on another
// worker. AC's thread only pays for the swap and the texture upload.
//
// ImGui's allocator hook writes to the current context's debug counters from
// any thread, so no context may be destroyed while a worker allocates or frees:
// WaitForWorkers() runs first (ImGuiPopOuts.Close, EngineFrameController.Shutdown).
private sealed class Bake
{
public IntPtr Atlas; // ImFontAtlas*, in no context yet; 0 = the bake failed
public readonly ImFontPtr[] Base = new ImFontPtr[(int)UiFont.Count];
public readonly Dictionary<int, ImFontPtr[]> Scaled = new();
public int Steps;
public double Ms;
public string? Error;
}
private static System.Threading.Thread? _bakeThread;
private static Bake? _bakeDone; // set by the worker as it ends
private static readonly List<System.Threading.Thread> FreeThreads = new();
/// <summary>
/// Render thread, before NewFrame, with the main context current. Starts a re-bake
/// when one is due, and swaps a finished one in. True when <paramref name="io"/>'s
/// atlas changed: the caller makes its texture. <paramref name="what"/> says what happened.
/// </summary>
public static bool PumpRebuild(ImGuiIOPtr io, float scale, out string what)
{
what = "";
if (_bakeThread != null)
{
Bake? done = System.Threading.Volatile.Read(ref _bakeDone);
if (done == null) return false; // still baking: frames go on with the old atlas
_bakeThread.Join();
_bakeThread = null;
_bakeDone = null;
if (done.Atlas == IntPtr.Zero)
{
// Failed off-thread: the old way, here.
io.Fonts.Clear();
Build(io, scale);
what = $"off-thread bake failed ({done.Error}); re-baked on the render thread";
return true;
}
SwapIn(io, done);
what = $"baked off-thread in {done.Ms:0.0} ms ({done.Steps} enlarged size(s) in use)";
return true;
}
if (!TakeRebuildRequest()) return false;
PrepareNativeData();
List<int> steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse();
try
{
_bakeDone = null;
_bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps));
return false;
}
catch (Exception ex)
{
_bakeThread = null;
io.Fonts.Clear();
Build(io, scale);
what = $"no bake thread ({ex.GetType().Name}); re-baked on the render thread";
return true;
}
}
private static void BakeWorker(float scale, List<int> steps)
{
var bake = new Bake { Steps = steps.Count };
long t0 = Stopwatch.GetTimestamp();
ImFontAtlas* atlas = null;
try
{
atlas = ImGuiNative.ImFontAtlas_ImFontAtlas();
var ptr = new ImFontAtlasPtr(atlas);
AddAll(ptr, scale, steps, bake.Base, bake.Scaled);
if (bake.Base[(int)UiFont.Ui11].NativePtr == null)
ptr.AddFontDefault(); // no Segoe UI: ImGui's built-in font keeps text readable
ptr.Build();
// The RGBA copy the texture is made from, here too: the swap then only uploads it.
ptr.GetTexDataAsRGBA32(out IntPtr _, out int _, out int _);
bake.Atlas = (IntPtr)atlas;
atlas = null;
}
catch (Exception ex)
{
bake.Error = $"{ex.GetType().Name}: {ex.Message}";
}
finally
{
if (atlas != null) ImGuiNative.ImFontAtlas_destroy(atlas);
bake.Ms = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency;
System.Threading.Volatile.Write(ref _bakeDone, bake);
}
}
/// <summary>Points the main context and every pop-out at the baked atlas; the old one is freed off-thread.</summary>
private static void SwapIn(ImGuiIOPtr io, Bake bake)
{
ImFontAtlas* old = io.NativePtr->Fonts;
ImFontAtlas* fresh = (ImFontAtlas*)bake.Atlas;
io.NativePtr->Fonts = fresh; // the main context owns (and at shutdown deletes) whatever atlas it holds
io.NativePtr->FontDefault = bake.Base[(int)UiFont.Ui11].NativePtr; // null: the atlas's first font
Array.Copy(bake.Base, Fonts, Fonts.Length);
ScaledFonts.Clear();
foreach (KeyValuePair<int, ImFontPtr[]> kv in bake.Scaled) ScaledFonts[kv.Key] = kv.Value;
ImGuiPopOuts.ReplaceFontAtlas((IntPtr)old, (IntPtr)fresh);
if (old == null || old == fresh) return;
IntPtr oldPtr = (IntPtr)old;
try
{
lock (FreeThreads)
{
FreeThreads.RemoveAll(t => !t.IsAlive);
FreeThreads.Add(EngineThreads.Start("ImGuiFonts.Free",
() => ImGuiNative.ImFontAtlas_destroy((ImFontAtlas*)oldPtr)));
}
}
catch
{
ImGuiNative.ImFontAtlas_destroy(old); // no thread: free it here
}
}
/// <summary>
/// Waits for a running re-bake and atlas frees. Before destroying any ImGui
/// context (see the note above). AC thread. A finished bake stays to be swapped in.
/// </summary>
public static void WaitForWorkers()
{
_bakeThread?.Join();
System.Threading.Thread[] frees;
lock (FreeThreads) { frees = FreeThreads.ToArray(); FreeThreads.Clear(); }
foreach (System.Threading.Thread t in frees) t.Join();
}
/// <summary>Frees the native font buffers. Only after the ImGui context is destroyed.</summary>
public static void Free()
{
// A worker may still read the buffers below (a bake) or free an atlas.
WaitForWorkers();
if (_bakeThread != null || _bakeDone != null)
{
_bakeThread = null;
Bake? pending = _bakeDone;
_bakeDone = null;
if (pending != null && pending.Atlas != IntPtr.Zero)
ImGuiNative.ImFontAtlas_destroy((ImFontAtlas*)pending.Atlas); // baked, never swapped in
}
foreach (IntPtr p in NativeBuffers)
NativeMemory.Free((void*)p);
NativeBuffers.Clear();
Array.Clear(Fonts);
ScaledFonts.Clear();
_mainRanges = _symbolRanges = _iconRanges = null;
_nSegoe = _nSegoeBold = _nMono = _nCode = _nSymbol = _nPhosphor = IntPtr.Zero;
}
private static int CountBaked()
{
int n = 0;
foreach (ImFontPtr f in Fonts) if (f.NativePtr != null) n++;
return n;
}
private static ushort[] SymbolRanges()
{
var ranges = new ushort[SymbolCodepoints.Length * 2 + 1];
for (int i = 0; i < SymbolCodepoints.Length; i++)
{
ranges[i * 2] = SymbolCodepoints[i];
ranges[i * 2 + 1] = SymbolCodepoints[i];
}
return ranges; // trailing 0 terminator
}
/// <summary>PhosphorIcons.Baked as glyph ranges: sorted, runs of neighbours joined, 0-terminated.</summary>
private static ushort[] IconRanges()
{
var points = new SortedSet<ushort>();
foreach (char c in PhosphorIcons.Baked) points.Add(c);
var ranges = new List<ushort>();
int start = -1, prev = -1;
foreach (ushort cp in points)
{
if (start < 0) start = cp;
else if (cp != prev + 1) { ranges.Add((ushort)start); ranges.Add((ushort)prev); start = cp; }
prev = cp;
}
if (start >= 0) { ranges.Add((ushort)start); ranges.Add((ushort)prev); }
ranges.Add(0);
return ranges.ToArray();
}
private static int IconCount() => new HashSet<char>(PhosphorIcons.Baked).Count;
/// <summary>
/// A TrueType font's em as a fraction of the ImGui pixel size (ImGui sizes a
/// font so hhea ascent - descent = the size) and half its cap height in em.
/// Read from the head, hhea and OS/2 tables; Segoe UI's values when unreadable.
/// </summary>
private readonly record struct FaceMetrics(float EmPerPx, float CapHalfEm)
{
private static readonly FaceMetrics Fallback = new(2048f / 2724f, 1434f / 2048f * 0.5f);
public static FaceMetrics Read(byte[]? ttf)
{
if (ttf == null || ttf.Length < 12) return Fallback;
try
{
int upm = 0, ascent = 0, descent = 0, cap = 0;
int tables = U16(ttf, 4);
for (int i = 0; i < tables; i++)
{
int rec = 12 + i * 16;
uint tag = (uint)(ttf[rec] << 24 | ttf[rec + 1] << 16 | ttf[rec + 2] << 8 | ttf[rec + 3]);
int off = ttf[rec + 8] << 24 | ttf[rec + 9] << 16 | ttf[rec + 10] << 8 | ttf[rec + 11];
if (tag == 0x68656164) upm = U16(ttf, off + 18); // head
else if (tag == 0x68686561) { ascent = S16(ttf, off + 4); descent = S16(ttf, off + 6); } // hhea
else if (tag == 0x4F532F32 && U16(ttf, off) >= 2) cap = S16(ttf, off + 88); // OS/2
}
if (upm <= 0 || ascent - descent <= 0) return Fallback;
if (cap <= 0) cap = (int)(upm * 0.7f);
return new FaceMetrics((float)upm / (ascent - descent), cap * 0.5f / upm);
}
catch (IndexOutOfRangeException)
{
return Fallback;
}
}
private static int U16(byte[] b, int at) => b[at] << 8 | b[at + 1];
private static int S16(byte[] b, int at) => (short)(b[at] << 8 | b[at + 1]);
}
private static ushort* PinRanges(ushort[] ranges)
{
var p = (ushort*)NativeMemory.Alloc((nuint)ranges.Length, sizeof(ushort));
ranges.AsSpan().CopyTo(new Span<ushort>(p, ranges.Length));
NativeBuffers.Add((IntPtr)p);
return p;
}
private static IntPtr ToNative(byte[]? bytes)
{
if (bytes == null || bytes.Length == 0) return IntPtr.Zero;
void* p = NativeMemory.Alloc((nuint)bytes.Length);
bytes.AsSpan().CopyTo(new Span<byte>(p, bytes.Length));
NativeBuffers.Add((IntPtr)p);
return (IntPtr)p;
}
/// <summary>A font embedded in this assembly (the Phosphor icons); null when missing.</summary>
private static byte[]? TryReadResource(string name)
{
try
{
using Stream? stream = typeof(ImGuiFonts).Assembly.GetManifestResourceStream(name);
if (stream == null)
{
RynthLog.UI($"ImGuiFonts: embedded font {name} missing; icons will not draw.");
return null;
}
var bytes = new byte[stream.Length];
stream.ReadExactly(bytes);
return bytes;
}
catch (Exception ex)
{
RynthLog.UI($"ImGuiFonts: could not read {name} - {ex.GetType().Name}: {ex.Message}");
return null;
}
}
private static byte[]? TryRead(string file)
{
try
{
string path = Path.Combine(FontsDir, file);
return File.Exists(path) ? File.ReadAllBytes(path) : null;
}
catch (Exception ex)
{
RynthLog.UI($"ImGuiFonts: could not read {file} - {ex.GetType().Name}: {ex.Message}");
return null;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,701 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiPopOuts.cs
// Popped-out ImGui panels (docs/IMGUI_PARITY_PLAN.md §4.2, P5): a panel
// popped out of the client is still its ImGui face, drawn by the engine into
// its own window. No ImGui multi-viewport.
//
// Per pop-out:
// • a LayeredWindow owned by AC's window (non-activating, hidden from
// Alt-Tab, moves and resizes without the OS modal loop), created on the
// game thread by a posted message, never inline in EndScene;
// • a secondary ImGui context sharing the main font atlas, fed from that
// window's mouse messages, plus keys and the wheel routed from the game
// window (the pop-out never takes focus, so AC keeps rendering);
// • a PopOutSurface: render target → readback → UpdateLayeredWindow.
// A pop-out renders at up to 30 Hz, and on every frame for a few frames after
// input so clicks and typing feel immediate.
//
// Tooltips and popups: the context's display is the monitor's work area, with
// the panel drawn where it really is on it, so ImGui places a tooltip or menu
// as it would in the client (flipping at the screen's edges). The picture is
// the panel plus a transparent margin holding whatever reaches past it; with
// nothing out there the margin is 0 and the picture is just the panel. The
// window grows by the margin and moves so the panel stays put (LayeredWindow
// .Present). Before this, the window was the panel and a tooltip below the
// one-button-high popped-out bar was cut off at its edge.
//
// Threads: everything here runs on AC's main thread, which both renders
// (EndScene) and dispatches the game and pop-out WndProcs. No locks.
// Shutdown releases every window, context and D3D surface; nothing survives
// an engine reload.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.UI;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ImGuiPopOuts
{
private const uint WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105;
private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205, WM_MBUTTONDOWN = 0x0207, WM_MBUTTONUP = 0x0208, WM_MOUSEWHEEL = 0x020A, WM_MOUSEHWHEEL = 0x020E;
private const int VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12;
private const int HotFramesAfterInput = 4;
private const int MaxContentSide = 4096; // a size-to-content pop-out's largest size (px)
private const int MarginStep = 32; // margins grow in steps, so a tooltip that follows the mouse doesn't resize the window every frame
private const float OverflowSlack = 2f; // anti-aliased edges reach ~1 px past the panel: not a tooltip
// A margin's largest size (px). Room for any tooltip or menu; it bounds the readback
// if something follows the mouse far off the panel (the inventory's drag ghost).
private const int MaxMargin = 640;
private static readonly long FrameInterval = Stopwatch.Frequency / 30; // hovered or just used
// Otherwise the face's own idle rate (IImGuiPanel.PopOutIdleHz, default 10 Hz).
[StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; }
[DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT p);
[DllImport("user32.dll")] private static extern IntPtr WindowFromPoint(POINT p);
[DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr hWnd, ref POINT p);
[DllImport("user32.dll")] private static extern short GetKeyState(int vk);
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
private readonly record struct InputMessage(uint Msg, IntPtr WParam, IntPtr LParam);
private sealed class PopOut
{
public required string Title;
public required IntPtr Context;
public int Left, Top, Width, Height; // requested geometry (screen px)
public int CaptionHeight, CaptionRightInset; // native drag band (px)
public LayeredWindow? Window;
public bool Visible;
public readonly PopOutSurface Surface = new();
public readonly List<InputMessage> Input = new(32);
public readonly bool[] Buttons = new bool[3];
public long LastFrameTicks;
public int HotFrames = HotFramesAfterInput;
public bool WantTextInput, DropTextFocus;
public bool Hovered;
// A pop-out that isn't a panel (the bar): its own draw, sized to its content.
public Action<float, Vector2>? Draw;
public Action<int, int>? OnMoved;
public bool SizeToContent, ResizeGrip = true;
public Vector2 ContentSize;
public int ShownWidth, ShownHeight; // the picture size last pushed
public long IdleInterval = Stopwatch.Frequency / 10;
public ulong LastHash;
// The context's display (the work area around the panel) and the panel's place on it.
public int OriginX, OriginY, DisplayW, DisplayH;
// The picture's margins around the panel (px): room for tooltips and popups.
public int MarginL, MarginT, MarginR, MarginB;
// Cost, for /rc imgui diag: frames built / pictures pushed, and the time spent.
public long Built, Pushed, BuildTicks, PushTicks;
}
private static readonly Dictionary<string, PopOut> Pops = new(StringComparer.OrdinalIgnoreCase);
private static readonly List<PopOut> Order = new();
private static PopOut? _current; // the pop-out whose frame is being built
private static PopOut? _keyboard; // the pop-out typing into a text box
private static int _loggedErrors;
/// <summary>True while a pop-out's ImGui frame is being built (inside a face's Draw). AC thread.</summary>
public static bool InPopOutFrame => _current != null;
/// <summary>
/// Where a popped-out face puts its window (its top-left in the pop-out's ImGui
/// coordinates): the panel's place on the work area. (0,0) outside a pop-out frame.
/// AC thread, in the draw.
/// </summary>
public static Vector2 PanelOrigin => _current is { } pop ? new Vector2(pop.OriginX, pop.OriginY) : Vector2.Zero;
public static bool IsPopped(string title) => Pops.ContainsKey(title);
/// <summary>The screen position of the game window's client origin (to place a pop-out where the docked panel was).</summary>
public static Vector2 ClientOriginOnScreen()
{
var p = new POINT();
IntPtr game = Win32Backend.GameHwnd;
if (game != IntPtr.Zero) ClientToScreen(game, ref p);
return new Vector2(p.X, p.Y);
}
/// <summary>
/// Pops a panel out at the given screen geometry. Call with the main context
/// current (its font atlas is shared). AC thread.
/// </summary>
public static void Open(string title, int left, int top, int width, int height, int captionHeight, int captionRightInset, float uiScale,
Action<float, Vector2>? draw = null, Action<int, int>? onMoved = null, bool sizeToContent = false)
{
if (Pops.ContainsKey(title)) return;
IntPtr main = ImGuiNET.ImGui.GetCurrentContext();
if (main == IntPtr.Zero) return;
IntPtr ctx = ImGuiNET.ImGui.CreateContext(ImGuiNET.ImGui.GetIO().Fonts);
ImGuiNET.ImGui.SetCurrentContext(ctx);
try
{
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
io.NativePtr->IniFilename = null;
io.BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset;
RynthTheme.Apply(ImGuiNET.ImGui.GetStyle(), uiScale);
}
finally
{
ImGuiNET.ImGui.SetCurrentContext(main);
}
var pop = new PopOut
{
Title = title, Context = ctx,
Left = left, Top = top, Width = Math.Max(80, width), Height = Math.Max(40, height),
CaptionHeight = captionHeight, CaptionRightInset = captionRightInset,
Draw = draw, OnMoved = onMoved, SizeToContent = sizeToContent, ResizeGrip = !sizeToContent,
};
Pops[title] = pop;
Order.Add(pop);
// Creating an HWND from inside EndScene isn't safe: the game WndProc does it.
if (!Win32Backend.PostToGameThread(() => CreateWindow(pop)))
RynthLog.UI($"ImGuiPopOuts: {title}: no game window to create the pop-out from.");
}
private static void CreateWindow(PopOut pop)
{
if (!Pops.TryGetValue(pop.Title, out PopOut? live) || live != pop || pop.Window != null) return;
try
{
// A saved spot off the screen (a monitor since unplugged, a bad save) comes back on it.
if (LayeredWindow.ClampToWorkArea(ref pop.Left, ref pop.Top, pop.Width, pop.Height))
RynthLog.UI($"ImGuiPopOuts: {pop.Title}: saved spot was off the screen; moved to ({pop.Left},{pop.Top}).");
var window = new LayeredWindow(pop.Width, pop.Height, pop.Left, pop.Top, Win32Backend.GameHwnd)
{
CaptionHeight = pop.CaptionHeight,
CaptionRightInset = pop.CaptionRightInset,
ResizeGripEnabled = pop.ResizeGrip,
};
window.OnInput = (msg, wParam, lParam, _, _) => OnWindowInput(pop, msg, wParam, lParam);
window.OnResized = (_, _) => pop.HotFrames = Math.Max(pop.HotFrames, 2);
window.OnMoved = (x, y) => NotifyMoved(pop, window, x, y);
window.OnResizeEnd = (w, h) => ImGuiPanelHost.OnPopOutGeometry(pop.Title, window.ScreenLeft, window.ScreenTop, w, h);
LayeredWindow.ClaimTitle(pop.Title, window.Hwnd);
pop.Window = window;
pop.HotFrames = HotFramesAfterInput;
RynthLog.UI($"ImGuiPopOuts: {pop.Title} popped out at ({pop.Left},{pop.Top}) {pop.Width}x{pop.Height}.");
}
catch (Exception ex)
{
RynthLog.UI($"ImGuiPopOuts: {pop.Title}: window creation failed ({ex.GetType().Name}: {ex.Message}).");
}
}
/// <summary>The window moved (a drag ended, or it was pulled back onto the screen): save the spot. AC thread.</summary>
private static void NotifyMoved(PopOut pop, LayeredWindow window, int x, int y)
{
if (pop.OnMoved != null) pop.OnMoved(x, y);
else ImGuiPanelHost.OnPopOutGeometry(pop.Title, x, y, window.Width, window.Height);
}
/// <summary>Closes a pop-out: its window, surfaces and context. AC thread.</summary>
public static void Close(string title)
{
if (!Pops.Remove(title, out PopOut? pop)) return;
Order.Remove(pop);
if (_keyboard == pop) _keyboard = null;
try { pop.Window?.Dispose(); } catch (Exception ex) { RynthLog.UI($"ImGuiPopOuts: {title} window dispose threw {ex.Message}"); }
pop.Window = null;
pop.Surface.Dispose();
ImGuiFonts.WaitForWorkers(); // no context goes while a font worker runs (ImGuiFonts, re-bake note)
ImGuiNET.ImGui.DestroyContext(pop.Context); // restores the current context
RynthLog.UI($"ImGuiPopOuts: {title} closed.");
}
/// <summary>
/// The main context's font atlas was replaced (ImGuiFonts re-bake): every pop-out
/// shares it, so each one's context is pointed at the new atlas too. AC thread,
/// between frames.
/// </summary>
public static void ReplaceFontAtlas(IntPtr oldAtlas, IntPtr newAtlas)
{
if (Order.Count == 0) return;
IntPtr previous = ImGuiNET.ImGui.GetCurrentContext();
try
{
foreach (PopOut pop in Order)
{
ImGuiNET.ImGui.SetCurrentContext(pop.Context);
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
if ((IntPtr)io.NativePtr->Fonts == oldAtlas)
io.NativePtr->Fonts = (ImFontAtlas*)newAtlas;
pop.LastHash = 0; // redraw with the new glyphs even if the lists hash the same
}
}
finally
{
ImGuiNET.ImGui.SetCurrentContext(previous);
}
}
/// <summary>Engine shutdown / reload: every pop-out goes. Any thread that may touch the device.</summary>
/// <summary>
/// The device is about to be Reset (D3D9.DeviceResetHook): release every
/// pop-out's D3DPOOL_DEFAULT surfaces, or the Reset fails and AC stops with
/// "Could not initialize Direct3D". They are recreated on the next frame;
/// the windows keep their last picture meanwhile. AC thread. Returns the
/// number of pop-outs released.
/// </summary>
public static int ReleaseDeviceResources()
{
int released = 0;
foreach (PopOut pop in Order)
{
pop.Surface.Dispose();
pop.LastHash = 0; // draw the next frame even if nothing changed
released++;
}
return released;
}
public static void Shutdown()
{
var titles = new List<string>(Pops.Keys);
foreach (string title in titles) Close(title);
}
/// <summary>
/// A size-to-content pop-out's draw reports how big its content came out;
/// the window takes that size on the next frame. AC thread, in the draw.
/// </summary>
public static void ReportContentSize(Vector2 size)
{
PopOut? pop = _current;
if (pop == null || !pop.SizeToContent || size == pop.ContentSize) return;
pop.ContentSize = size;
pop.HotFrames = Math.Max(pop.HotFrames, 2);
}
/// <summary>Starts moving the current pop-out's window (a chromeless face dragged by its own surface). AC thread, in a face's Draw.</summary>
public static void BeginMoveCurrent() => _current?.Window?.BeginContentMove();
// ── Input ──────────────────────────────────────────────────────────
private static void OnWindowInput(PopOut pop, uint msg, IntPtr wParam, IntPtr lParam)
{
pop.Input.Add(new InputMessage(msg, wParam, lParam));
pop.HotFrames = HotFramesAfterInput;
if (msg is WM_LBUTTONDOWN or WM_RBUTTONDOWN or WM_MBUTTONDOWN)
{
// A click in this pop-out ends text entry everywhere else.
EngineFrameController.DropMainTextFocus();
foreach (PopOut other in Order)
if (other != pop && other.WantTextInput) { other.DropTextFocus = true; other.HotFrames = 2; }
}
}
/// <summary>
/// Called by the game WndProc for every message. True when a pop-out took it:
/// keys while a pop-out's text box is being edited, and the wheel over a
/// pop-out. A click on the game ends a pop-out's text edit. AC thread.
/// </summary>
public static bool RouteInput(uint msg, IntPtr wParam, IntPtr lParam)
{
if (Order.Count == 0) return false;
switch (msg)
{
case WM_LBUTTONDOWN or WM_RBUTTONDOWN or WM_MBUTTONDOWN:
foreach (PopOut pop in Order)
if (pop.WantTextInput) { pop.DropTextFocus = true; pop.HotFrames = 2; }
return false;
case WM_MOUSEWHEEL or WM_MOUSEHWHEEL:
{
var p = new POINT { X = (short)((long)lParam & 0xFFFF), Y = (short)(((long)lParam >> 16) & 0xFFFF) };
IntPtr under = WindowFromPoint(p);
foreach (PopOut pop in Order)
{
if (pop.Window == null || pop.Window.Hwnd != under) continue;
OnWindowInput(pop, msg, wParam, lParam);
return true;
}
return false;
}
case WM_KEYDOWN or WM_KEYUP or WM_CHAR or WM_SYSKEYDOWN or WM_SYSKEYUP:
{
PopOut? sink = _keyboard;
if (sink == null || !sink.WantTextInput) return false;
sink.Input.Add(new InputMessage(msg, wParam, lParam));
sink.HotFrames = HotFramesAfterInput;
return true;
}
}
return false;
}
/// <param name="offsetX">Added to a message's client x to make it ImGui's (the window's origin in ImGui coordinates).</param>
private static void FeedInput(PopOut pop, ImGuiIOPtr io, int offsetX, int offsetY)
{
foreach (InputMessage m in pop.Input)
{
// Mouse messages from the window carry the position (client coords). It has to
// reach ImGui before the button: a press is applied where ImGui last saw the
// mouse, and an idle pop-out may last have seen it outside the window, so a
// quick grab of a drag surface pressed nothing (Tom, 2026-09-29: the popped-out
// dashboard wouldn't move). Wheel lParams are screen coordinates: skipped.
if (m.Msg is WM_MOUSEMOVE or WM_LBUTTONDOWN or WM_LBUTTONUP or WM_RBUTTONDOWN or WM_RBUTTONUP or WM_MBUTTONDOWN or WM_MBUTTONUP)
io.AddMousePosEvent((short)((long)m.LParam & 0xFFFF) + offsetX, (short)(((long)m.LParam >> 16) & 0xFFFF) + offsetY);
switch (m.Msg)
{
case WM_LBUTTONDOWN: SetButton(pop, io, 0, true); break;
case WM_LBUTTONUP: SetButton(pop, io, 0, false); break;
case WM_RBUTTONDOWN: SetButton(pop, io, 1, true); break;
case WM_RBUTTONUP: SetButton(pop, io, 1, false); break;
case WM_MBUTTONDOWN: SetButton(pop, io, 2, true); break;
case WM_MBUTTONUP: SetButton(pop, io, 2, false); break;
case WM_MOUSEWHEEL: io.AddMouseWheelEvent(0f, (short)((long)m.WParam >> 16) / 120f); break;
case WM_MOUSEHWHEEL: io.AddMouseWheelEvent((short)((long)m.WParam >> 16) / 120f, 0f); break;
case WM_KEYDOWN or WM_SYSKEYDOWN or WM_KEYUP or WM_SYSKEYUP:
{
ImGuiKey key = Win32Backend.VkToImGuiKey((int)(long)m.WParam);
if (key != ImGuiKey.None) io.AddKeyEvent(key, m.Msg is WM_KEYDOWN or WM_SYSKEYDOWN);
break;
}
case WM_CHAR:
{
uint ch = (uint)(long)m.WParam;
if (ch > 0 && ch < 0x10000) io.AddInputCharacter(ch);
break;
}
}
}
pop.Input.Clear();
}
private static void SetButton(PopOut pop, ImGuiIOPtr io, int button, bool down)
{
if (pop.Buttons[button] == down) return;
pop.Buttons[button] = down;
io.AddMouseButtonEvent(button, down);
}
// ── Frames ─────────────────────────────────────────────────────────
/// <summary>
/// Draws and presents every pop-out that is due. <paramref name="live"/> is
/// false between characters: pop-outs hide, like the in-client panels.
/// AC thread, inside EndScene, after the main frame.
/// </summary>
public static void RenderAll(IntPtr device, float uiScale, bool live)
{
if (Order.Count == 0) return;
if (!live)
{
foreach (PopOut pop in Order)
if (pop.Visible) { pop.Window?.Hide(); pop.Visible = false; }
return;
}
IntPtr previous = ImGuiNET.ImGui.GetCurrentContext();
long now = Stopwatch.GetTimestamp();
try
{
for (int i = 0; i < Order.Count; i++)
{
PopOut pop = Order[i];
if (pop.Window == null || pop.Window.Hwnd == IntPtr.Zero) continue;
long interval = pop.HotFrames > 0 || pop.Hovered || pop.WantTextInput ? 0 : pop.IdleInterval;
if (pop.HotFrames <= 0 && now - pop.LastFrameTicks < Math.Max(interval, FrameInterval)) continue;
RenderOne(device, pop, uiScale, now);
}
}
finally
{
_current = null;
ImGuiNET.ImGui.SetCurrentContext(previous);
}
}
private static void RenderOne(IntPtr device, PopOut pop, float uiScale, long now)
{
LayeredWindow window = pop.Window!;
int w = Math.Max(1, window.Width), h = Math.Max(1, window.Height);
if (pop.SizeToContent && pop.ContentSize.X >= 1 && pop.ContentSize.Y >= 1)
{
// The window follows the content (Present resizes it to the picture).
w = Math.Min(MaxContentSide, (int)MathF.Ceiling(pop.ContentSize.X));
h = Math.Min(MaxContentSide, (int)MathF.Ceiling(pop.ContentSize.Y));
}
PlaceOnDisplay(pop, window, w, h);
// The screen spot of ImGui's (0,0).
int anchorX = window.ScreenLeft - pop.OriginX, anchorY = window.ScreenTop - pop.OriginY;
ImGuiNET.ImGui.SetCurrentContext(pop.Context);
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
bool started = false;
try
{
// The display is the work area, not the window: a size-to-content face must
// lay out against a large display (ImGui clamps an auto-resizing window to the
// display; when the display was the window, each shrank the other, 400x40 ->
// 8x6 -> 4x4, and the popped-out bar was a 4 px speck), and tooltips and
// popups get room around the panel.
io.DisplaySize = new Vector2(pop.DisplayW, pop.DisplayH);
float dt = pop.LastFrameTicks == 0 ? 1f / 30f : (float)(now - pop.LastFrameTicks) / Stopwatch.Frequency;
io.DeltaTime = Math.Clamp(dt, 1f / 240f, 0.5f);
pop.LastFrameTicks = now;
FeedInput(pop, io, window.SurfaceLeft - anchorX, window.SurfaceTop - anchorY);
// The cursor, from the screen: over this window (or dragging from it) it's in
// ImGui's coordinates, otherwise nowhere, so hover highlights clear.
GetCursorPos(out POINT cursor);
bool held = pop.Buttons[0] || pop.Buttons[1] || pop.Buttons[2];
pop.Hovered = WindowFromPoint(cursor) == window.Hwnd;
if (held || pop.Hovered)
io.AddMousePosEvent(cursor.X - anchorX, cursor.Y - anchorY);
else
io.AddMousePosEvent(-float.MaxValue, -float.MaxValue);
bool gameFocused = GetForegroundWindow() == Win32Backend.GameHwnd;
io.AddFocusEvent(gameFocused || held);
io.AddKeyEvent(ImGuiKey.ModCtrl, (GetKeyState(VK_CONTROL) & 0x8000) != 0);
io.AddKeyEvent(ImGuiKey.ModShift, (GetKeyState(VK_SHIFT) & 0x8000) != 0);
io.AddKeyEvent(ImGuiKey.ModAlt, (GetKeyState(VK_MENU) & 0x8000) != 0);
_current = pop;
ImGuiNET.ImGui.NewFrame();
started = true;
if (pop.DropTextFocus)
{
pop.DropTextFocus = false;
ImGuiNET.ImGui.SetWindowFocus(null);
}
if (pop.Draw != null) pop.Draw(uiScale, new Vector2(w, h));
else ImGuiPanelHost.DrawPopped(pop.Title, uiScale, new Vector2(w, h));
ImGuiNET.ImGui.EndFrame();
started = false;
ImGuiNET.ImGui.Render();
_current = null;
long built = Stopwatch.GetTimestamp();
pop.Built++;
pop.BuildTicks += built - now;
// The picture: the panel, plus a margin for anything drawn past it (a tooltip,
// a menu). Only a menu there takes clicks; a tooltip lets them through.
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
UpdateMargins(pop, drawData.NativePtr, w, h);
window.MarginsClickThrough = !ImGuiNET.ImGui.IsPopupOpen("", ImGuiPopupFlags.AnyPopupId | ImGuiPopupFlags.AnyPopupLevel);
int sx = pop.OriginX - pop.MarginL, sy = pop.OriginY - pop.MarginT;
int sw = w + pop.MarginL + pop.MarginR, sh = h + pop.MarginT + pop.MarginB;
if (drawData.NativePtr != null)
{
drawData.NativePtr->DisplayPos = new Vector2(sx, sy); // render into the sw x sh picture
drawData.NativePtr->DisplaySize = new Vector2(sw, sh);
}
// Nothing changed since the last picture: skip the render, readback and
// window update (most panels are still most of the time).
ulong hash = HashDrawData(drawData, sw, sh) ^ Mix(sx, sy, w, h);
if (hash == pop.LastHash && pop.Visible && pop.Surface.SnapshotPath == null)
{
pop.Surface.Flush(device, window);
}
else
{
pop.LastHash = hash;
if (pop.Surface.Render(device, drawData, sw, sh, new PopOutSurface.Placement(pop.MarginL, pop.MarginT, w, h), window))
{
// Shown, or its picture changed size (the bar grows to its content):
// none of it may hang off the screen.
if ((!pop.Visible || w != pop.ShownWidth || h != pop.ShownHeight) && window.EnsureOnScreen())
NotifyMoved(pop, window, window.ScreenLeft, window.ScreenTop);
pop.ShownWidth = w;
pop.ShownHeight = h;
if (!pop.Visible)
{
window.Show();
pop.Visible = true;
}
}
pop.Pushed++;
pop.PushTicks += Stopwatch.GetTimestamp() - built;
}
pop.WantTextInput = io.WantTextInput;
pop.IdleInterval = Stopwatch.Frequency / ImGuiPanelHost.PopOutIdleHz(pop.Title);
if (pop.WantTextInput) _keyboard = pop;
else if (_keyboard == pop) _keyboard = null;
if (pop.HotFrames > 0) pop.HotFrames--;
}
catch (Exception ex)
{
try { if (started) ImGuiNET.ImGui.EndFrame(); } catch { }
_current = null;
pop.HotFrames = 0;
if (_loggedErrors++ < 10)
RynthLog.UI($"ImGuiPopOuts: {pop.Title} frame threw {ex.GetType().Name}: {ex.Message}");
}
}
// ── Tooltips and popups: the display and the margins ───────────────
/// <summary>
/// Sets the context's display to the work area of the panel's monitor (and the
/// panel, where it hangs off it), and the panel's place on it. ImGui then keeps
/// tooltips and popups on the screen and flips them at its edges, as in the client.
/// </summary>
private static void PlaceOnDisplay(PopOut pop, LayeredWindow window, int w, int h)
{
if (window.IsDragging && pop.DisplayW > 0)
{
// Mid-drag the display travels with the panel: the panel keeps its ImGui
// position, so a moved picture is the same picture (not redrawn every step).
// It is placed afresh once the drag ends.
pop.DisplayW = Math.Max(pop.DisplayW, pop.OriginX + w);
pop.DisplayH = Math.Max(pop.DisplayH, pop.OriginY + h);
return;
}
int left = window.ScreenLeft, top = window.ScreenTop;
int l = left, t = top, r = left + w, b = top + h;
if (LayeredWindow.TryGetWorkArea(left, top, w, h, out int wl, out int wt, out int wr, out int wb))
{
l = Math.Min(l, wl); t = Math.Min(t, wt);
r = Math.Max(r, wr); b = Math.Max(b, wb);
}
pop.OriginX = left - l;
pop.OriginY = top - t;
pop.DisplayW = r - l;
pop.DisplayH = b - t;
}
/// <summary>
/// The picture's margins: room for everything drawn past the panel, in steps, held
/// while something is out there (a tooltip following the mouse doesn't resize the
/// window on every frame) and dropped to 0 when nothing is. Never past the display.
/// </summary>
private static void UpdateMargins(PopOut pop, ImDrawData* dd, int w, int h)
{
float px0 = pop.OriginX, py0 = pop.OriginY, px1 = px0 + w, py1 = py0 + h;
if (!OverflowBounds(dd, px0, py0, px1, py1, pop.DisplayW, pop.DisplayH, out float x0, out float y0, out float x1, out float y1))
{
pop.MarginL = pop.MarginT = pop.MarginR = pop.MarginB = 0;
return;
}
pop.MarginL = Math.Clamp(Math.Max(Step(px0 - x0), pop.MarginL), 0, pop.OriginX);
pop.MarginT = Math.Clamp(Math.Max(Step(py0 - y0), pop.MarginT), 0, pop.OriginY);
pop.MarginR = Math.Clamp(Math.Max(Step(x1 - px1), pop.MarginR), 0, Math.Max(0, pop.DisplayW - pop.OriginX - w));
pop.MarginB = Math.Clamp(Math.Max(Step(y1 - py1), pop.MarginB), 0, Math.Max(0, pop.DisplayH - pop.OriginY - h));
}
private static int Step(float overflow)
=> overflow <= OverflowSlack ? 0 : Math.Min(MaxMargin, ((int)MathF.Ceiling(overflow) + MarginStep - 1) / MarginStep * MarginStep);
/// <summary>
/// The bounds of what is drawn outside the panel rect (tooltips, popups), as it will
/// show: each draw command's triangles, cut to its clip rect and the display. False
/// when nothing reaches more than <see cref="OverflowSlack"/> px past the panel.
/// Only commands whose clip rect reaches past the panel are walked (a window's
/// background, tooltips and popups); the panel's own content is clipped inside it.
/// </summary>
private static bool OverflowBounds(ImDrawData* dd, float px0, float py0, float px1, float py1, float displayW, float displayH,
out float x0, out float y0, out float x1, out float y1)
{
x0 = px0; y0 = py0; x1 = px1; y1 = py1;
if (dd == null) return false;
ImDrawList** lists = (ImDrawList**)dd->CmdLists.Data;
for (int n = 0; n < dd->CmdListsCount; n++)
{
ImDrawList* list = lists[n];
if (list == null) continue;
int vtxCount = list->VtxBuffer.Size, idxCount = list->IdxBuffer.Size;
ImDrawVert* vtx = (ImDrawVert*)list->VtxBuffer.Data;
ushort* idx = (ushort*)list->IdxBuffer.Data;
ImDrawCmd* cmds = (ImDrawCmd*)list->CmdBuffer.Data;
for (int c = 0; c < list->CmdBuffer.Size; c++)
{
ImDrawCmd* cmd = &cmds[c];
if (cmd->UserCallback != IntPtr.Zero || cmd->ElemCount == 0) continue;
float cx0 = Math.Max(cmd->ClipRect.X, 0f), cy0 = Math.Max(cmd->ClipRect.Y, 0f);
float cx1 = Math.Min(cmd->ClipRect.Z, displayW), cy1 = Math.Min(cmd->ClipRect.W, displayH);
if (cx1 <= cx0 || cy1 <= cy0) continue;
if (cx0 >= px0 && cy0 >= py0 && cx1 <= px1 && cy1 <= py1) continue; // can't draw outside the panel
float vx0 = float.MaxValue, vy0 = float.MaxValue, vx1 = float.MinValue, vy1 = float.MinValue;
long start = cmd->IdxOffset, end = Math.Min((long)idxCount, start + cmd->ElemCount);
long vbase = cmd->VtxOffset;
for (long i = start; i < end; i++)
{
long v = vbase + idx[i];
if (v >= vtxCount) continue;
Vector2 pos = vtx[v].pos;
if (pos.X < vx0) vx0 = pos.X;
if (pos.Y < vy0) vy0 = pos.Y;
if (pos.X > vx1) vx1 = pos.X;
if (pos.Y > vy1) vy1 = pos.Y;
}
vx0 = Math.Max(vx0, cx0); vy0 = Math.Max(vy0, cy0);
vx1 = Math.Min(vx1, cx1); vy1 = Math.Min(vy1, cy1);
if (vx1 <= vx0 || vy1 <= vy0) continue;
x0 = Math.Min(x0, vx0); y0 = Math.Min(y0, vy0);
x1 = Math.Max(x1, vx1); y1 = Math.Max(y1, vy1);
}
}
return px0 - x0 > OverflowSlack || py0 - y0 > OverflowSlack || x1 - px1 > OverflowSlack || y1 - py1 > OverflowSlack;
}
/// <summary>Folds the picture's placement into the draw-data hash.</summary>
private static ulong Mix(int a, int b, int c, int d)
=> ((ulong)(uint)a * 0x9E3779B97F4A7C15UL) ^ ((ulong)(uint)b * 0xC2B2AE3D27D4EB4FUL)
^ ((ulong)(uint)c * 0x165667B19E3779F9UL) ^ ((ulong)(uint)d * 0x27D4EB2F165667C5UL);
/// <summary>Diagnostics: the pop-out's next frame is also saved as a BMP in the log folder. AC thread.</summary>
public static string? RequestSnapshot(string title)
{
if (!Pops.TryGetValue(title, out PopOut? pop)) return null;
string path = System.IO.Path.Combine(@"C:\Games\RynthCore\Logs", $"popout_{title.Replace(' ', '_')}.bmp");
pop.Surface.SnapshotPath = path;
pop.HotFrames = Math.Max(pop.HotFrames, 2);
return path;
}
/// <summary>One line per pop-out for /rc imgui diag.</summary>
public static List<string> Describe()
{
var lines = new List<string>();
double ms = 1000.0 / Stopwatch.Frequency;
foreach (PopOut pop in Order)
lines.Add($"popout {pop.Title}: window={(pop.Window == null ? "pending" : $"0x{pop.Window.Hwnd.ToInt64():X} at ({pop.Window.ScreenLeft},{pop.Window.ScreenTop}) {pop.Window.Width}x{pop.Window.Height}")} visible={pop.Visible} text={pop.WantTextInput}"
+ $" margins=({pop.MarginL},{pop.MarginT},{pop.MarginR},{pop.MarginB}) display={pop.DisplayW}x{pop.DisplayH}"
+ $" built={pop.Built} ({(pop.Built > 0 ? pop.BuildTicks * ms / pop.Built : 0):0.00} ms) pushed={pop.Pushed} ({(pop.Pushed > 0 ? pop.PushTicks * ms / pop.Pushed : 0):0.00} ms)");
return lines;
}
/// <summary>A 64-bit hash of everything that affects the picture: vertices, indices, commands and the size.</summary>
private static ulong HashDrawData(ImDrawDataPtr drawData, int w, int h)
{
ImDrawData* dd = drawData.NativePtr;
ulong hash = 0xcbf29ce484222325UL ^ (ulong)(uint)w ^ ((ulong)(uint)h << 32);
if (dd == null) return hash;
ImDrawList** lists = (ImDrawList**)dd->CmdLists.Data;
for (int n = 0; n < dd->CmdListsCount; n++)
{
ImDrawList* list = lists[n];
if (list == null) continue;
hash = HashBytes(hash, (byte*)list->VtxBuffer.Data, list->VtxBuffer.Size * sizeof(ImDrawVert));
hash = HashBytes(hash, (byte*)list->IdxBuffer.Data, list->IdxBuffer.Size * sizeof(ushort));
hash = HashBytes(hash, (byte*)list->CmdBuffer.Data, list->CmdBuffer.Size * sizeof(ImDrawCmd));
}
return hash;
}
private static ulong HashBytes(ulong hash, byte* data, int length)
{
if (data == null || length <= 0) return hash;
ulong* p = (ulong*)data;
int words = length >> 3;
for (int i = 0; i < words; i++)
hash = (hash ^ p[i]) * 0x100000001B3UL + (hash >> 29);
for (int i = words << 3; i < length; i++)
hash = (hash ^ data[i]) * 0x100000001B3UL;
return hash ^ (ulong)length;
}
}

View file

@ -0,0 +1,166 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiSelfTest.cs
// Refuses to start ImGui unless the loaded cimgui.dll is RynthCore's own
// build (native/cimgui, scripts/Build-Cimgui.ps1) and its struct layout
// matches ImGui.NET 1.91.6.1.
//
// Every managed ImGui struct accessor (ImDrawData, ImGuiIO, ImFontAtlas, ...)
// reads native memory at ImGui.NET's compiled offsets, and every enum value
// is passed straight through. A different native build silently shifts both:
// the DLL bundled until 2026-09 was 1.89.7, and even the stock NuGet 1.91.6
// x86 DLL disagrees with its own wrapper (64-bit ImTextureID). This check
// turns a mismatch into a logged refusal instead of memory corruption on
// AC's thread.
// ============================================================================
using System;
using System.Numerics;
using System.Runtime.InteropServices;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ImGuiSelfTest
{
/// <summary>IMGUI_VERSION of the native build ImGui.NET 1.91.6.1 wraps.</summary>
internal const string ExpectedVersion = "1.91.6";
/// <summary>Must equal RynthImGui_BuildTag() in native/cimgui/rynth_cimgui_ext.cpp.</summary>
/// <summary>Outcome of the last Run, for /rc imgui diag ("not run" before the first).</summary>
public static string LastResult { get; private set; } = "not run";
internal const string ExpectedBuildTag = "rynth-cimgui 1.91.6dock ImTextureID=void* soft-assert layout-1 textedit-264bee4";
/// <summary>
/// True when <paramref name="cimguiModule"/> is our cimgui build and its
/// layout matches the managed wrapper. Safe to call before any context
/// exists. On a mismatch it logs why and returns false; the caller must
/// not create an ImGui context.
/// </summary>
public static bool Run(IntPtr cimguiModule)
{
try
{
// igGetVersion exists in every cimgui and has no side effects, so
// it goes first: older builds compile IM_ASSERT in as a hard abort,
// and the layout calls below would trip it on a mismatch.
string version = ImGuiNET.ImGui.GetVersion() ?? "";
if (version != ExpectedVersion)
return Fail($"cimgui.dll reports ImGui {version}, ImGui.NET expects {ExpectedVersion}");
if (cimguiModule == IntPtr.Zero
|| !NativeLibrary.TryGetExport(cimguiModule, "RynthImGui_BuildTag", out IntPtr buildTagFn)
|| !NativeLibrary.TryGetExport(cimguiModule, "RynthImGui_GetLayout", out IntPtr getLayoutFn))
return Fail("cimgui.dll is not the RynthCore build (no RynthImGui_* exports); rebuild with scripts/Build-Cimgui.ps1");
string tag = Marshal.PtrToStringAnsi(((delegate* unmanaged[Cdecl]<IntPtr>)buildTagFn)()) ?? "";
if (tag != ExpectedBuildTag)
return Fail($"cimgui build tag '{tag}', expected '{ExpectedBuildTag}'");
(string Name, int Value)[] expected = ExpectedLayout();
var getLayout = (delegate* unmanaged[Cdecl]<int*, int, int>)getLayoutFn;
int nativeCount = getLayout(null, 0);
if (nativeCount < expected.Length)
return Fail($"layout table has {nativeCount} entries, expected {expected.Length}");
int* native = stackalloc int[nativeCount];
getLayout(native, nativeCount);
int mismatches = 0;
for (int i = 0; i < expected.Length; i++)
{
if (native[i] == expected[i].Value) continue;
mismatches++;
RynthLog.UI($"ImGuiSelfTest: layout[{i}] {expected[i].Name}: native={native[i]} managed={expected[i].Value}");
}
if (mismatches > 0)
return Fail($"{mismatches} layout mismatch(es) between cimgui.dll and ImGui.NET");
// Dear ImGui's own check (asserts are soft in our build).
if (!ImGuiNET.ImGui.DebugCheckVersionAndDataLayout(ExpectedVersion,
(uint)sizeof(ImGuiIO), (uint)sizeof(ImGuiStyle), (uint)sizeof(Vector2),
(uint)sizeof(Vector4), (uint)sizeof(ImDrawVert), sizeof(ushort)))
return Fail("DebugCheckVersionAndDataLayout reported a mismatch");
ImGuiAssertLog.Bind(cimguiModule);
LastResult = $"OK - {tag}";
RynthLog.UI($"ImGuiSelfTest: OK - {tag}, {expected.Length} layout checks passed.");
return true;
}
catch (Exception ex)
{
return Fail($"{ex.GetType().Name}: {ex.Message}");
}
}
private static bool Fail(string why)
{
LastResult = "FAILED - " + why;
RynthLog.UI($"ImGuiSelfTest: FAILED - {why}. ImGui disabled.");
return false;
}
private static int Off(void* structBase, void* field) => (int)((byte*)field - (byte*)structBase);
/// <summary>
/// The managed side of the layout table, in the index order of
/// RynthImGui_GetLayout (native/cimgui/rynth_cimgui_ext.cpp). Append only.
/// </summary>
internal static (string Name, int Value)[] ExpectedLayout()
{
// Offsets are taken from zeroed stack locals (&((T*)null)->Field
// null-checks in .NET).
ImDrawCmd cmd = default;
ImDrawList list = default;
ImDrawData data = default;
ImFontAtlas atlas = default;
ImGuiIO io = default;
return new (string, int)[]
{
("table version", 1),
("sizeof(ImTextureID)", sizeof(IntPtr)),
("sizeof(ImWchar)", sizeof(ushort)),
("sizeof(ImDrawIdx)", sizeof(ushort)),
("sizeof(ImDrawVert)", sizeof(ImDrawVert)),
("sizeof(ImDrawCmd)", sizeof(ImDrawCmd)),
("ImDrawCmd.TextureId", Off(&cmd, &cmd.TextureId)),
("ImDrawCmd.VtxOffset", Off(&cmd, &cmd.VtxOffset)),
("ImDrawCmd.IdxOffset", Off(&cmd, &cmd.IdxOffset)),
("ImDrawCmd.ElemCount", Off(&cmd, &cmd.ElemCount)),
("ImDrawCmd.UserCallback", Off(&cmd, &cmd.UserCallback)),
("sizeof(ImDrawList)", sizeof(ImDrawList)),
("ImDrawList.VtxBuffer", Off(&list, &list.VtxBuffer)),
("sizeof(ImDrawData)", sizeof(ImDrawData)),
("ImDrawData.CmdLists", Off(&data, &data.CmdLists)),
("ImDrawData.DisplayPos", Off(&data, &data.DisplayPos)),
("ImDrawData.DisplaySize", Off(&data, &data.DisplaySize)),
("sizeof(ImFontAtlas)", sizeof(ImFontAtlas)),
("ImFontAtlas.TexID", Off(&atlas, &atlas.TexID)),
("sizeof(ImFont)", sizeof(ImFont)),
// Pinned to the native size: ImGui.NET's generator expands the
// Colored:1/Visible:1/Codepoint:30 bitfield into three uints, so
// its ImFontGlyph is 48 bytes and wrong under ANY native build.
// Never read glyphs through ImGui.NET's ImFontGlyph/ImFontGlyphPtr.
("sizeof(ImFontGlyph) [native]", 40),
("sizeof(ImFontConfig)", sizeof(ImFontConfig)),
("sizeof(ImGuiIO)", sizeof(ImGuiIO)),
("ImGuiIO.Fonts", Off(&io, &io.Fonts)),
("ImGuiIO.WantCaptureMouse", Off(&io, &io.WantCaptureMouse)),
("ImGuiIO.WantTextInput", Off(&io, &io.WantTextInput)),
("sizeof(ImGuiStyle)", sizeof(ImGuiStyle)),
("sizeof(ImGuiViewport)", sizeof(ImGuiViewport)),
("sizeof(ImGuiPlatformIO)", sizeof(ImGuiPlatformIO)),
("sizeof(ImGuiInputTextCallbackData)", sizeof(ImGuiInputTextCallbackData)),
("sizeof(ImGuiListClipper)", sizeof(ImGuiListClipper)),
("sizeof(ImGuiPayload)", sizeof(ImGuiPayload)),
("sizeof(ImGuiTableSortSpecs)", sizeof(ImGuiTableSortSpecs)),
("sizeof(ImGuiTableColumnSortSpecs)", sizeof(ImGuiTableColumnSortSpecs)),
("sizeof(ImGuiStorage)", sizeof(ImGuiStorage)),
("sizeof(ImGuiWindowClass)", sizeof(ImGuiWindowClass)),
("sizeof(ImGuiSizeCallbackData)", sizeof(ImGuiSizeCallbackData)),
("ImGuiCol.COUNT", (int)ImGuiCol.COUNT),
("ImGuiKey.NamedKey_END", (int)ImGuiKey.NamedKey_END),
("ImGuiStyleVar.COUNT", (int)ImGuiStyleVar.COUNT),
("ImGuiMouseCursor.COUNT", (int)ImGuiMouseCursor.COUNT),
};
}
}

View file

@ -0,0 +1,832 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/CombatText.cs
// RynthVision combat text, the ImGui port of the RynthJuice plugin (so it
// also works in dungeons), plus the gain text:
// - damage you deal: a number over the monster, white -> yellow -> orange
// -> red by size, GOLD, bigger and with "!" on a crit;
// - damage you take: red numbers over your head;
// - heals: green "+N" over you or a monster;
// - kill burst: expanding rings where a monster you damaged dies;
// - gains: "+12,345 XP", "+500 Lum", "+10 Radiance" rising over your head.
// Numbers pop from the head with a little sideways jitter, drift up and fade
// (~1.2 s; crits pop larger). At most MaxNumbers live at once.
//
// Sources (engine-side events, no polling of monsters):
// AttackerNotification / DefenderNotification (SmartBoxHooks, exact melee
// and missile damage + crit; the target is named, not id'd);
// ACE's spell lines "[Critical hit! ]You <verb> <target> for N points
// with <spell>." and "<source> <verbs> you for N points with <spell>.",
// and damage over time ("You <verb> <target> for N points of periodic
// ... damage!", "You receive N points of periodic harm.");
// health observations (MonsterHudData): a monster reaching 0 (kill) or
// rising (heal); the player's own vitals snapshot for heals;
// KillerNotification (the death message names the victim) and object
// deletes after a recent hit (kill fallback);
// XP / Luminance: TotalExperience (Int64 1) and AvailableLuminance
// (Int64 6) read at 4 Hz on AC's thread, rises only (spending never
// shows); Radiance (Aelrynth): "You gain N Radiance." in chat.
// ACE sends no damage notification for a killing blow, so the last hit's
// number is estimated from the last health ratio x max HP when the max is
// known (appraised), else only the burst shows.
//
// Hooks run on AC's main thread and only queue (a lock, a struct); the
// render thread resolves names to monsters and draws. 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;
internal static class CombatText
{
private const int MaxNumbers = 30;
private const int MaxBursts = 8;
private const int MaxGains = 6;
private const int MaxEvents = 64;
// Base lifetimes; MonsterHudSettings.NumTime scales them.
private const float NumberLife = 2.0f, CritLife = 2.5f, HealLife = 1.8f;
private const float GainLife = 1.8f, GainMergeSec = 0.3f;
private const float BurstLife = 1.1f;
private const double KillAfterHitSec = 10.0; // a death counts as "yours" this long after your last hit
private const double DeleteKillSec = 8.0; // a delete counts as a death this soon after your last hit
private static uint C(uint argb) => MonsterHud.C(argb);
private static readonly uint StaminaAmber = C(0xFFFFC040), ManaBlue = C(0xFF5AA8FF);
private static readonly uint Gold = C(0xFFFFD700), HealGreen = C(0xFF50FF50), TakenRed = C(0xFFFF2828),
White = C(0xFFFFFFFF), PaleYellow = C(0xFFFFF080), Orange = C(0xFFFFA030), Red = C(0xFFFF3828),
BurstCyan = C(0xFF60FFFF), BurstGold = C(0xFFFFD24A),
XpGold = C(0xFFFFC83C), LumViolet = C(0xFFC08CFF), RadianceTeal = C(0xFF7FF0E0);
// ── Events (AC's main thread -> render thread) ──────────────────────
private enum EvKind : byte { Dealt, Taken, Health, KillMsg, Deleted, Radiance, Test, ChatXp, ChatLum }
private readonly record struct Ev(EvKind Kind, uint Id, string? Text, int Amount, bool Crit, float Prev, float Ratio, uint Max);
private static readonly object Sync = new();
private static readonly List<Ev> Pending = new(MaxEvents);
private static readonly List<Ev> Work = new(MaxEvents);
// ── Live effects (render thread) ────────────────────────────────────
private enum NumKind : byte { Dealt, Taken, Heal, Stamina, Mana }
private sealed class Number
{
public bool Active;
public NumKind Kind;
public string Text = "";
public uint Color;
public bool Crit;
public long Born;
public float Life;
public bool OnPlayer;
public uint Cell;
public float X, Y, Z;
public float Jitter;
public uint Target;
}
private sealed class Burst
{
public bool Active;
public bool Crit;
public long Born;
public uint Cell;
public float X, Y, Z; // feet
}
private enum GainKind : byte { Xp, Lum, Radiance }
private sealed class Gain
{
public GainKind Kind;
public long Amount;
public long Born;
public long Merged;
public string Text = "";
}
private sealed class Hit
{
public long Ticks;
public uint Cell;
public float X, Y, Z; // head
public float FeetZ;
public long BurstAt;
}
private static readonly Number[] Numbers = CreatePool<Number>(MaxNumbers);
private static readonly Burst[] Bursts = CreatePool<Burst>(MaxBursts);
private static readonly List<Gain> Gains = new(MaxGains);
private static readonly Dictionary<uint, Hit> Hits = new(64);
private static readonly List<uint> HitEvict = new(16);
private static int _liveNumbers, _liveBursts;
private static uint _rng = 0x9E3779B9u;
private static long _nextHitPrune;
// Player vitals (heals) and the gain baselines.
private static uint _prevHealth, _prevMaxHealth, _prevStamina, _prevMaxStamina, _prevMana, _prevMaxMana;
private static uint _gainOwner;
private static long _xpBase = -1, _lumBase = -1;
// A chat line already showed this rise (Aelrynth's kill summary): the property poll skips it.
private static long _chatXpUntil, _chatLumUntil;
private static string _lastRadianceLine = "";
private static long _lastRadianceTicks;
private static int _statNumbers, _statBursts, _statGains;
private static T[] CreatePool<T>(int n) where T : new()
{
var a = new T[n];
for (int i = 0; i < n; i++) a[i] = new T();
return a;
}
/// <summary>True while anything is on screen or waiting to be drawn.</summary>
public static bool HasContent
{
get
{
if (_liveNumbers > 0 || _liveBursts > 0 || Gains.Count > 0) return true;
lock (Sync) return Pending.Count > 0;
}
}
public static void Clear()
{
lock (Sync) Pending.Clear();
foreach (Number n in Numbers) n.Active = false;
foreach (Burst b in Bursts) b.Active = false;
Gains.Clear();
Hits.Clear();
_liveNumbers = _liveBursts = 0;
_prevHealth = _prevMaxHealth = 0;
_gainOwner = 0;
_xpBase = _lumBase = -1;
}
/// <summary>When the player last hit this monster (Stopwatch ticks), long.MinValue if never. Render thread.</summary>
public static long LastHitTicks(uint id) => Hits.TryGetValue(id, out Hit? h) ? h.Ticks : long.MinValue;
// ════════════════════════════════════════════════════════════════════
// Feeds (AC's main thread; queue only)
// ════════════════════════════════════════════════════════════════════
private static void Push(in Ev e)
{
lock (Sync)
{
if (Pending.Count >= MaxEvents) Pending.RemoveAt(0);
Pending.Add(e);
}
}
private static bool NumbersOn => MonsterHudSettings.Numbers;
private static long _lastDamageKey, _lastDamageTicks;
private static string? _lastDamageName;
/// <summary>AttackerNotification (you hit <paramref name="name"/>) / DefenderNotification (you were hit).</summary>
public static void OnDamageEvent(bool attacker, string? name, uint damage, bool crit)
{
if (!NumbersOn || damage == 0) return;
// The same event seen by both of SmartBoxHooks' paths within 50 ms is one hit.
long key = ((long)damage << 2) | (attacker ? 2L : 0L) | (crit ? 1L : 0L);
long now = Stopwatch.GetTimestamp();
if (key == _lastDamageKey && name == _lastDamageName && now - _lastDamageTicks < Stopwatch.Frequency / 20) return;
_lastDamageKey = key; _lastDamageName = name; _lastDamageTicks = now;
if (attacker)
{
if (!string.IsNullOrEmpty(name)) Push(new Ev(EvKind.Dealt, 0, name, (int)damage, crit, 0, 0, 0));
}
else if (MonsterHudSettings.NumTaken)
{
Push(new Ev(EvKind.Taken, 0, null, (int)damage, crit, 0, 0, 0));
}
}
/// <summary>A health observation for a creature (not the player): kills and heals.</summary>
public static void OnHealth(uint id, float prev, float ratio, uint max)
{
if (!NumbersOn || prev < 0f) return;
if (ratio <= 0.001f && prev > 0.001f)
Push(new Ev(EvKind.Health, id, null, 0, false, prev, ratio, max));
else if (ratio > prev + 0.001f && MonsterHudSettings.NumHeals)
Push(new Ev(EvKind.Health, id, null, 0, false, prev, ratio, max));
}
/// <summary>KillerNotification: the player killed something; the message names it.</summary>
public static void OnKillMessage(string? message)
{
if (!NumbersOn || string.IsNullOrEmpty(message)) return;
Push(new Ev(EvKind.KillMsg, 0, message, 0, false, 0, 0, 0));
}
/// <summary>"/rv plates test": a spread of sample numbers, a burst and gains around the player.</summary>
public static void SpawnTest() => Push(new Ev(EvKind.Test, 0, null, 0, false, 0, 0, 0));
public static void OnDeleted(uint id)
{
if (!NumbersOn || !MonsterHudSettings.NumKills) return;
// Only creatures can be kill-burst candidates; items and corpses come and go all the time.
if (!ClientObjectHooks.TryGetSnapshotItemType(id, out uint type) || (type & 0x10) == 0) return;
Push(new Ev(EvKind.Deleted, id, null, 0, false, 0, 0, 0));
}
private static int _radianceDiag, _gainDiag;
private static readonly string[] AttackPrefixes = { "Critical hit! ", "Overpower! ", "Sneak Attack! " };
/// <summary>A chat line: spell damage (dealt / taken) and Radiance gains. Cheap for anything else.</summary>
public static void OnChat(string line)
{
if (line.Length < 14) return;
// Diagnostics: the first lines mentioning Radiance (every kill line), and whether they parse.
if (_radianceDiag < 60 && line.Contains("Radiance", StringComparison.Ordinal))
{
_radianceDiag++;
bool shape = line.StartsWith("You gain ", StringComparison.Ordinal) && line.EndsWith(" Radiance.", StringComparison.Ordinal);
RynthLog.Compat($"Nameplates: radiance line '{line}' (len {line.Length}, matches {shape}, gains {MonsterHudSettings.Gains}/{MonsterHudSettings.GainRadiance})");
}
// Aelrynth's kill summary: "Kill: +5,000 experience, +50 Radiance." (parts optional,
// "Luminance" too). It reports XP even at max level, where TotalExperience no longer rises.
if (line.StartsWith("Kill: +", StringComparison.Ordinal))
{
if (!MonsterHudSettings.Gains) return;
long now = Stopwatch.GetTimestamp();
if (line == _lastRadianceLine && now - _lastRadianceTicks < Stopwatch.Frequency / 10) return;
_lastRadianceLine = line;
_lastRadianceTicks = now;
// Parts are separated by ", "; a bare ',' is a thousands separator ("+10,500 experience"),
// which the old Split(',') cut in two, dropping every XP amount of 1,000 or more.
foreach (string raw in line.Substring(6).TrimEnd('.').Split(", "))
{
string part = raw.Trim();
if (part.Length < 3 || part[0] != '+') continue;
int sp = part.IndexOf(' ');
if (sp < 2 || !TryParseNumber(part.AsSpan(1, sp - 1), out long amount) || amount <= 0) continue;
string what = part.Substring(sp + 1);
int amt = (int)Math.Min(amount, int.MaxValue);
if (what.StartsWith("experience", StringComparison.OrdinalIgnoreCase))
{
if (!MonsterHudSettings.GainXp) continue;
_chatXpUntil = now + Stopwatch.Frequency * 2; // the property poll skips this rise
Push(new Ev(EvKind.ChatXp, 0, null, amt, false, 0, 0, 0));
}
else if (what.StartsWith("Luminance", StringComparison.OrdinalIgnoreCase))
{
if (!MonsterHudSettings.GainLum) continue;
_chatLumUntil = now + Stopwatch.Frequency * 2;
Push(new Ev(EvKind.ChatLum, 0, null, amt, false, 0, 0, 0));
}
else if (what.StartsWith("Radiance", StringComparison.OrdinalIgnoreCase))
{
if (MonsterHudSettings.GainRadiance) Push(new Ev(EvKind.Radiance, 0, null, amt, false, 0, 0, 0));
}
}
return;
}
// "You gain 1,234 Radiance." (Aelrynth; may be batched)
if (line.StartsWith("You gain ", StringComparison.Ordinal) && line.EndsWith(" Radiance.", StringComparison.Ordinal))
{
if (!MonsterHudSettings.Gains || !MonsterHudSettings.GainRadiance) return;
long now = Stopwatch.GetTimestamp();
// The same line twice within 100 ms is one line seen by two chat paths.
if (line == _lastRadianceLine && now - _lastRadianceTicks < Stopwatch.Frequency / 10) return;
_lastRadianceLine = line;
_lastRadianceTicks = now;
if (TryParseNumber(line.AsSpan(9, line.Length - 9 - " Radiance.".Length), out long amount) && amount > 0)
Push(new Ev(EvKind.Radiance, 0, null, (int)Math.Min(amount, int.MaxValue), false, 0, 0, 0));
return;
}
if (!NumbersOn) return;
// Damage over time on you: "You receive N points of periodic harm."
if (line.StartsWith("You receive ", StringComparison.Ordinal) && line.EndsWith(" points of periodic harm.", StringComparison.Ordinal))
{
if (MonsterHudSettings.NumTaken &&
TryParseNumber(line.AsSpan(12, line.Length - 12 - " points of periodic harm.".Length), out long harm) && harm > 0 && harm < 1_000_000)
Push(new Ev(EvKind.Taken, 0, null, (int)harm, false, 0, 0, 0));
return;
}
// Spells: "... for N points with <spell>."; your damage over time: "You <verb> <target> for N points of periodic <type> damage!"
int ptsWith = line.IndexOf(" points with ", StringComparison.Ordinal);
if (ptsWith < 0) ptsWith = line.IndexOf(" points of periodic ", StringComparison.Ordinal);
if (ptsWith < 0) return;
bool crit = false;
int start = 0;
for (bool again = true; again;)
{
again = false;
foreach (string pre in AttackPrefixes)
if (string.CompareOrdinal(line, start, pre, 0, pre.Length) == 0)
{
if (pre[0] == 'C') crit = true;
start += pre.Length;
again = true;
}
}
int forAt = line.LastIndexOf(" for ", ptsWith, StringComparison.Ordinal);
if (forAt <= start || !TryParseNumber(line.AsSpan(forAt + 5, ptsWith - forAt - 5), out long n) || n <= 0 || n > 1_000_000)
return;
if (string.CompareOrdinal(line, start, "You ", 0, 4) == 0)
{
// "You <verb> <target> for N points with <spell>."
int verbEnd = line.IndexOf(' ', start + 4);
if (verbEnd < 0 || verbEnd >= forAt) return;
string target = line[(verbEnd + 1)..forAt];
if (target.Length > 0) Push(new Ev(EvKind.Dealt, 0, target, (int)n, crit, 0, 0, 0));
}
else if (MonsterHudSettings.NumTaken && forAt >= 4 && string.CompareOrdinal(line, forAt - 4, " you", 0, 4) == 0)
{
// "<source> <verbs> you for N points with <spell>."
Push(new Ev(EvKind.Taken, 0, null, (int)n, crit, 0, 0, 0));
}
}
/// <summary>Digits with thousands separators ("12,345").</summary>
private static bool TryParseNumber(ReadOnlySpan<char> s, out long value)
{
value = 0;
bool any = false;
foreach (char ch in s)
{
if (ch == ',' || ch == '.' || ch == ' ') continue;
if (ch < '0' || ch > '9') return false;
value = value * 10 + (ch - '0');
any = true;
if (value > 1_000_000_000_000L) return false;
}
return any;
}
/// <summary>XP / Luminance rises since the last poll (4 Hz, AC's thread, from MonsterHud.Update).</summary>
public static void PollGains(uint playerId)
{
if (playerId == 0) return;
if (playerId != _gainOwner) { _gainOwner = playerId; _xpBase = _lumBase = -1; }
bool gains = MonsterHudSettings.Gains;
if (!ClientObjectHooks.TryGetObjectQuadProperty(playerId, 1u, out long xp) || xp <= 0) return; // TotalExperience
long nowTicks = Stopwatch.GetTimestamp();
if (_xpBase >= 0 && xp > _xpBase && gains && MonsterHudSettings.GainXp && nowTicks > _chatXpUntil) AddGain(GainKind.Xp, xp - _xpBase);
_xpBase = xp;
// AvailableLuminance: absent means 0 once the player's qualities are readable (the XP read was).
long lum = ClientObjectHooks.TryGetObjectQuadProperty(playerId, 6u, out long l) ? l : 0;
if (_lumBase >= 0 && lum > _lumBase && gains && MonsterHudSettings.GainLum && nowTicks > _chatLumUntil) AddGain(GainKind.Lum, lum - _lumBase);
_lumBase = lum;
}
// ════════════════════════════════════════════════════════════════════
// Draw (render thread, inside the ImGui frame)
// ════════════════════════════════════════════════════════════════════
public static void Draw(ref MonsterHud.Frame f)
{
ProcessEvents(ref f);
if (NumbersOn && MonsterHudSettings.NumHeals) WatchPlayerHeals();
PruneHits(f.Now);
float k = MonsterHudSettings.Scale * f.UiScale;
if (_liveBursts > 0) DrawBursts(ref f, k);
if (_liveNumbers > 0) DrawNumbers(ref f, k);
if (Gains.Count > 0) DrawGains(ref f, k);
}
private static void ProcessEvents(ref MonsterHud.Frame f)
{
Work.Clear();
lock (Sync)
{
if (Pending.Count == 0) return;
Work.AddRange(Pending);
Pending.Clear();
}
uint player = ClientHelperHooks.GetPlayerId();
foreach (Ev e in Work)
{
switch (e.Kind)
{
case EvKind.Dealt:
{
uint id = MonsterHud.FindPlateByName(e.Text!);
if (id == 0) id = PlateDebuffs.UniqueNearby(e.Text!);
if (id == 0 || !NoteHit(id, f.Now, out Hit h)) break;
if (MonsterHudSettings.NumDealt)
SpawnNumber(NumKind.Dealt, e.Amount, e.Crit, false, h.Cell, h.X, h.Y, h.Z, id, f.Now);
break;
}
case EvKind.Taken:
SpawnNumber(NumKind.Taken, e.Amount, e.Crit, true, 0, 0, 0, 0, 0, f.Now);
break;
case EvKind.Health:
if (e.Id == player) break;
if (e.Ratio <= 0.001f)
{
Kill(e.Id, e.Prev, e.Max, f.Now, requireHit: true);
}
else
{
uint max = e.Max;
if (max == 0 && ObjectQualityCache.TryGetCreatureVitals(e.Id, out CreatureVitals v)) max = v.MaxHealth;
int delta = max > 0 ? (int)MathF.Round((e.Ratio - e.Prev) * max) : 0;
if (delta >= Math.Max(8, (int)(max * 0.05f)) && MonsterHud.TryGetHead(e.Id, out uint c, out float x, out float y, out float z, out _))
SpawnNumber(NumKind.Heal, delta, false, false, c, x, y, z, e.Id, f.Now);
}
break;
case EvKind.KillMsg:
{
uint id = MonsterHud.FindPlateNamedIn(e.Text!);
if (id == 0) break;
float prev = MonsterHudData.TryGetHealth(id, out HealthObservation ho) ? ho.Ratio : 0f;
uint max = ho.Max;
Kill(id, prev, max, f.Now, requireHit: false);
break;
}
case EvKind.Deleted:
if (Hits.TryGetValue(e.Id, out Hit? dh))
{
if (dh.BurstAt == 0 && f.Now - dh.Ticks < (long)(DeleteKillSec * Stopwatch.Frequency) &&
MonsterHudSettings.NumKills)
SpawnBurst(dh.Cell, dh.X, dh.Y, dh.FeetZ, false, f.Now);
Hits.Remove(e.Id);
}
break;
// Chat-reported gains show one-for-one with the chat line: merging two kills
// inside GainMergeSec showed a sum that matched no line in chat (2026-09-30).
case EvKind.Radiance:
AddGain(GainKind.Radiance, e.Amount, merge: false);
break;
case EvKind.ChatXp:
AddGain(GainKind.Xp, e.Amount, merge: false);
break;
case EvKind.ChatLum:
AddGain(GainKind.Lum, e.Amount, merge: false);
break;
case EvKind.Test:
{
uint c = f.PlayerCell;
float x = f.Px, y = f.Py, z = f.Pz + 2f;
SpawnNumber(NumKind.Dealt, 18, false, false, c, x + 2f, y + 2f, z, 0, f.Now);
SpawnNumber(NumKind.Dealt, 73, false, false, c, x - 2f, y + 1f, z, 0, f.Now);
SpawnNumber(NumKind.Dealt, 142, false, false, c, x + 1f, y - 2f, z, 0, f.Now);
SpawnNumber(NumKind.Dealt, 891, true, false, c, x - 1f, y - 1f, z, 0, f.Now);
SpawnNumber(NumKind.Heal, 64, false, false, c, x + 3f, y, z, 0, f.Now);
SpawnNumber(NumKind.Taken, 37, false, true, 0, 0, 0, 0, 0, f.Now);
SpawnBurst(c, x, y + 3f, f.Pz, false, f.Now);
AddGain(GainKind.Xp, 12345);
AddGain(GainKind.Lum, 500);
AddGain(GainKind.Radiance, 10);
break;
}
}
}
Work.Clear();
}
/// <summary>Records a hit on a monster (for kill attribution) with its head position. False without a position.</summary>
private static bool NoteHit(uint id, long now, out Hit hit)
{
if (!Hits.TryGetValue(id, out Hit? h))
{
if (Hits.Count >= 128) Hits.Clear();
h = new Hit();
Hits[id] = h;
}
hit = h;
h.Ticks = now;
if (MonsterHud.TryGetHead(id, out uint cell, out float x, out float y, out float z, out float feet))
{
h.Cell = cell; h.X = x; h.Y = y; h.Z = z; h.FeetZ = feet;
}
return h.Cell != 0;
}
/// <summary>A monster died: the burst, the estimated killing blow, and its debuffs go.</summary>
private static void Kill(uint id, float prevRatio, uint max, long now, bool requireHit)
{
PlateDebuffs.Remove(id);
Hits.TryGetValue(id, out Hit? h);
bool recent = h != null && now - h.Ticks < (long)(KillAfterHitSec * Stopwatch.Frequency);
if (requireHit && !recent) return;
if (h != null && h.BurstAt != 0 && now - h.BurstAt < 5 * Stopwatch.Frequency) return; // already shown
if (!MonsterHud.TryGetHead(id, out uint cell, out float x, out float y, out float z, out float feet))
{
if (h == null || h.Cell == 0) return;
cell = h.Cell; x = h.X; y = h.Y; z = h.Z; feet = h.FeetZ;
}
if (h == null)
{
if (Hits.Count >= 128) Hits.Clear();
h = new Hit { Ticks = long.MinValue / 2, Cell = cell, X = x, Y = y, Z = z, FeetZ = feet };
Hits[id] = h;
}
h.BurstAt = now;
// ACE sends no notification for the killing blow: estimate it from the last health seen.
if (MonsterHudSettings.NumDealt && recent)
{
if (max == 0 && ObjectQualityCache.TryGetCreatureVitals(id, out CreatureVitals v)) max = v.MaxHealth;
int est = max > 0 ? (int)MathF.Round(Math.Clamp(prevRatio, 0f, 1f) * max) : 0;
if (est > 0 && !RecentNumberOn(id, now)) SpawnNumber(NumKind.Dealt, est, false, false, cell, x, y, z, id, now);
}
if (MonsterHudSettings.NumKills)
SpawnBurst(cell, x, y, feet, false, now);
}
private static bool RecentNumberOn(uint id, long now)
{
foreach (Number n in Numbers)
if (n.Active && n.Target == id && now - n.Born < Stopwatch.Frequency * 3 / 10) return true;
return false;
}
private static void PruneHits(long now)
{
if (now < _nextHitPrune) return;
_nextHitPrune = now + Stopwatch.Frequency * 5;
HitEvict.Clear();
foreach (KeyValuePair<uint, Hit> kv in Hits)
if (now - kv.Value.Ticks > 60 * Stopwatch.Frequency && (kv.Value.BurstAt == 0 || now - kv.Value.BurstAt > 60 * Stopwatch.Frequency))
HitEvict.Add(kv.Key);
foreach (uint id in HitEvict) Hits.Remove(id);
}
/// <summary>The player's health rising past regen size: a green number over the head.</summary>
private static void WatchPlayerHeals()
{
if (!PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot v) || v.MaxHealth == 0) return;
long now = Stopwatch.GetTimestamp();
Restore(NumKind.Heal, v.Health, v.MaxHealth, ref _prevHealth, ref _prevMaxHealth, now);
if (MonsterHudSettings.NumRestores)
{
Restore(NumKind.Stamina, v.Stamina, v.MaxStamina, ref _prevStamina, ref _prevMaxStamina, now);
Restore(NumKind.Mana, v.Mana, v.MaxMana, ref _prevMana, ref _prevMaxMana, now);
}
}
/// <summary>A rise bigger than a regen tick (spells, potions, kits): a number over the player.</summary>
private static void Restore(NumKind kind, uint cur, uint max, ref uint prevCur, ref uint prevMax, long now)
{
uint prev = prevCur, pm = prevMax;
prevCur = cur;
prevMax = max;
if (max == 0 || prev == 0 || pm != max || cur <= prev) return;
int delta = (int)(cur - prev);
if (delta >= Math.Max(10, (int)(max * 0.05f)))
SpawnNumber(kind, delta, false, true, 0, 0, 0, 0, 0, now);
}
// ── Spawning ─────────────────────────────────────────────────────────
private static void SpawnNumber(NumKind kind, int amount, bool crit, bool onPlayer, uint cell, float x, float y, float z, uint target, long now)
{
if (amount <= 0) return;
Number? n = null;
foreach (Number c in Numbers)
if (!c.Active) { n = c; break; }
if (n == null)
{
// Full: reuse the oldest.
n = Numbers[0];
foreach (Number c in Numbers) if (c.Born < n.Born) n = c;
_liveNumbers--;
}
n.Active = true;
n.Kind = kind;
n.Crit = crit;
n.Born = now;
n.OnPlayer = onPlayer;
n.Cell = cell; n.X = x; n.Y = y; n.Z = z;
n.Target = target;
n.Jitter = (NextRandom() * 2f - 1f) * 14f;
string s = amount.ToString(CultureInfo.InvariantCulture);
switch (kind)
{
case NumKind.Heal:
n.Text = "+" + s; n.Color = HealGreen; n.Life = HealLife;
break;
case NumKind.Stamina:
n.Text = "+" + s + " stam"; n.Color = StaminaAmber; n.Life = HealLife;
break;
case NumKind.Mana:
n.Text = "+" + s + " mana"; n.Color = ManaBlue; n.Life = HealLife;
break;
case NumKind.Taken:
n.Text = crit ? s + "!" : s; n.Color = crit ? Gold : TakenRed; n.Life = crit ? CritLife : NumberLife;
break;
default:
n.Text = crit ? s + "!" : s; n.Color = crit ? Gold : DamageColor(amount); n.Life = crit ? CritLife : NumberLife;
break;
}
_liveNumbers++;
_statNumbers++;
}
private static void SpawnBurst(uint cell, float x, float y, float z, bool crit, long now)
{
Burst? b = null;
foreach (Burst c in Bursts)
if (!c.Active) { b = c; break; }
if (b == null)
{
b = Bursts[0];
foreach (Burst c in Bursts) if (c.Born < b.Born) b = c;
_liveBursts--;
}
b.Active = true;
b.Crit = crit;
b.Born = now;
b.Cell = cell; b.X = x; b.Y = y; b.Z = z;
_liveBursts++;
_statBursts++;
}
/// <summary>A gain; with <paramref name="merge"/>, the same kind within GainMergeSec adds to the newest one.</summary>
private static void AddGain(GainKind kind, long amount, bool merge = true)
{
if (amount <= 0) return;
// Diagnostics (2026-09-30: popups read half the chat's "Kill:" XP): the first 60 gains
// with their source, beside the kill lines logged in OnChat.
if (_gainDiag < 60)
{
_gainDiag++;
RynthLog.Compat($"Nameplates: gain {kind} +{amount} ({(merge ? "property rise" : "chat line")})");
}
long now = Stopwatch.GetTimestamp();
for (int i = merge ? Gains.Count - 1 : -1; i >= 0; i--)
{
Gain g = Gains[i];
if (g.Kind != kind) continue;
if (now - g.Born < (long)(GainMergeSec * Stopwatch.Frequency))
{
g.Amount += amount;
g.Merged = now;
g.Text = GainText(kind, g.Amount);
return;
}
break;
}
if (Gains.Count >= MaxGains) Gains.RemoveAt(0);
Gains.Add(new Gain { Kind = kind, Amount = amount, Born = now, Merged = now, Text = GainText(kind, amount) });
_statGains++;
}
private static string GainText(GainKind kind, long amount)
{
string n = amount.ToString("N0", CultureInfo.InvariantCulture);
return kind switch
{
GainKind.Xp => "+" + n + " XP",
GainKind.Lum => "+" + n + " Lum",
_ => "+" + n + " Radiance",
};
}
private static float NextRandom()
{
_rng ^= _rng << 13; _rng ^= _rng >> 17; _rng ^= _rng << 5;
return (_rng & 0xFFFFFF) / (float)0x1000000;
}
private static uint DamageColor(int amount) =>
amount < 25 ? White : amount < 60 ? PaleYellow : amount < 120 ? Orange : Red;
// ── Painting ─────────────────────────────────────────────────────────
private static float EaseOut(float t) => 1f - (1f - t) * (1f - t);
/// <summary>Where "over the player" is on screen: the head, or the upper middle in first person.</summary>
private static Vector2 PlayerAnchor(ref MonsterHud.Frame f, bool aboveplate, float k)
{
if (PlayerPlate.HeadOnScreen && !PlayerPlate.FirstPerson)
return new Vector2(PlayerPlate.HeadScreen.X, (aboveplate ? PlayerPlate.PlateTop : PlayerPlate.HeadScreen.Y) - 6f * k);
return new Vector2(MathF.Round(f.Display.X * 0.5f), MathF.Round(f.Display.Y * (aboveplate ? 0.28f : 0.42f)));
}
private static void DrawNumbers(ref MonsterHud.Frame f, float k)
{
float baseSize = ImGuiFonts.Get(UiFont.NumBold24).FontSize * MonsterHudSettings.NumSize * MonsterHudSettings.Scale;
float timeScale = MonsterHudSettings.NumTime;
Vector2 playerAt = PlayerAnchor(ref f, false, k);
int live = 0;
foreach (Number n in Numbers)
{
if (!n.Active) continue;
float age = (f.Now - n.Born) / (float)Stopwatch.Frequency / timeScale;
if (age >= n.Life) { n.Active = false; continue; }
live++;
Vector2 at;
if (n.OnPlayer) at = playerAt;
else if (!MonsterHud.Project(ref f, n.Cell, n.X, n.Y, n.Z, out at, keepOnScreen: true)) continue;
float t = age / n.Life;
float rise = 70f * k * MonsterHudSettings.NumSize * EaseOut(t);
float pop = 1f + (n.Crit ? 0.7f : 0.35f) * MathF.Max(0f, 1f - age / (n.Crit ? 0.16f : 0.12f));
float size = MathF.Round(baseSize * pop * (n.Crit ? 1.35f : 1f) * (n.Kind == NumKind.Taken ? 1.1f : 1f));
ImFontPtr font = ImGuiFonts.Sharp(size, bold: true); // shrink a bigger bake, never stretch
float alpha = MathF.Min(1f, age / 0.06f);
float fadeStart = 0.55f * n.Life;
if (age > fadeStart) alpha *= MathF.Max(0f, 1f - (age - fadeStart) / (n.Life - fadeStart));
float w = MonsterHud.TextWidth(font, size, n.Text);
var pos = new Vector2(MathF.Round(at.X + n.Jitter * k - w * 0.5f), MathF.Round(at.Y - 10f * k - rise - size));
MonsterHud.OutlinedText(f.Dl, font, size, pos, alpha, n.Text);
if (n.Crit) MonsterHud.OutlinedText(f.Dl, font, size, pos + new Vector2(1, 0), alpha * 0.6f, n.Text);
f.Dl.AddText(font, size, pos, MonsterHud.Mul(n.Color, alpha), n.Text);
}
_liveNumbers = live;
}
private static void DrawGains(ref MonsterHud.Frame f, float k)
{
// 24 px bake at GainSize 1 would be big; 0.75 keeps the old look at the default.
float baseSize = MathF.Round(ImGuiFonts.Get(UiFont.NumBold24).FontSize * 0.75f * MonsterHudSettings.GainSize * MonsterHudSettings.Scale);
float life = GainLife * MonsterHudSettings.GainTime;
Vector2 at = PlayerAnchor(ref f, true, k);
float lineH = baseSize + 3f * k;
int slot = 0;
for (int i = Gains.Count - 1; i >= 0; i--)
{
Gain g = Gains[i];
float age = (f.Now - g.Born) / (float)Stopwatch.Frequency;
if (age >= life) { Gains.RemoveAt(i); continue; }
float t = age / life;
float drift = 34f * k * MonsterHudSettings.GainSize * EaseOut(t);
float sinceMerge = (f.Now - g.Merged) / (float)Stopwatch.Frequency;
float pop = 1f + 0.25f * MathF.Max(0f, 1f - sinceMerge / 0.15f);
float size = MathF.Round(baseSize * pop);
ImFontPtr font = ImGuiFonts.Sharp(size, bold: true);
float alpha = MathF.Min(1f, age / 0.08f);
if (t > 0.6f) alpha *= MathF.Max(0f, 1f - (t - 0.6f) / 0.4f);
uint col = g.Kind == GainKind.Xp ? XpGold : g.Kind == GainKind.Lum ? LumViolet : RadianceTeal;
float w = MonsterHud.TextWidth(font, size, g.Text);
// Newest at the bottom; each older line sits one line higher.
var pos = new Vector2(MathF.Round(at.X - w * 0.5f), MathF.Round(at.Y - size - drift - slot * lineH));
MonsterHud.OutlinedText(f.Dl, font, size, pos, alpha, g.Text);
f.Dl.AddText(font, size, pos, MonsterHud.Mul(col, alpha), g.Text);
slot++;
}
}
/// <summary>Expanding ground rings plus a short fading pillar of rings where the monster fell.</summary>
private static void DrawBursts(ref MonsterHud.Frame f, float k)
{
int live = 0;
foreach (Burst b in Bursts)
{
if (!b.Active) continue;
float age = (f.Now - b.Born) / (float)Stopwatch.Frequency;
if (age >= BurstLife) { b.Active = false; continue; }
live++;
float t = age / BurstLife;
float fade = 1f - t;
uint main = b.Crit ? BurstGold : BurstCyan;
float thick = MathF.Max(1f, 3f * k * fade + 1f);
Ring(ref f, b, 0.5f + 5.5f * EaseOut(t), 0.15f, MonsterHud.Mul(main, fade), thick);
float t2 = Math.Clamp((age - 0.12f) / (BurstLife - 0.12f), 0f, 1f);
if (t2 > 0f) Ring(ref f, b, 0.3f + 3.2f * EaseOut(t2), 0.15f, MonsterHud.Mul(White, (1f - t2) * 0.8f), MathF.Max(1f, thick * 0.7f));
for (int i = 0; i < 4; i++)
{
float h = 0.6f + i * 0.7f + 1.2f * t;
float r = (1.3f - i * 0.22f) * (0.6f + 0.6f * EaseOut(t));
Ring(ref f, b, r, h, MonsterHud.Mul(main, fade * (0.75f - i * 0.12f)), MathF.Max(1f, thick * 0.6f));
}
}
_liveBursts = live;
}
private static void Ring(ref MonsterHud.Frame f, Burst b, float radius, float height, uint col, float thick)
{
const int Segs = 28;
bool havePrev = false;
Vector2 prev = default;
for (int i = 0; i <= Segs; i++)
{
float ang = i * (MathF.PI * 2f / Segs);
bool ok = MonsterHud.Project(ref f, b.Cell, b.X + radius * MathF.Cos(ang), b.Y + radius * MathF.Sin(ang), b.Z + height, out Vector2 p);
if (ok && havePrev) f.Dl.AddLine(prev, p, col, thick);
havePrev = ok;
prev = p;
}
}
public static string Describe() =>
$"Combat text {(MonsterHudSettings.Numbers ? "on" : "off")}, gains {(MonsterHudSettings.Gains ? "on" : "off")}: " +
$"{_liveNumbers} number(s), {_liveBursts} burst(s), {Gains.Count} gain(s) live; " +
$"{_statNumbers} numbers, {_statBursts} kill bursts, {_statGains} gains this session.";
}

View file

@ -0,0 +1,145 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/HudFeed.cs
// The one-line entry points the engine's existing hooks call for the
// RynthVision overlays (nameplates, debuffs, self plate, combat text), and
// the gate that keeps them off unless RynthVision is installed.
//
// Callers (all existing chokepoints, no new hooks):
// PluginManager.QueueChatWindowText -> OnChat
// PluginManager.QueueSelectedTargetChange -> OnSelection
// PluginManager.QueueDeleteObject -> OnDeleted
// CombatActionHooks.CastSpell -> OnCast
// SmartBoxHooks (0x01B1 / 0x01B2 / 0x01AD) -> OnDamageEvent, OnKillMessage
// AppraisalHooks (0xC9 CreatureProfile) -> OnAppraisal
// MonsterHudData.RecordHealth -> OnHealth
// All on AC's main thread; each call is a few compares when the line or
// event isn't one of ours, and never throws into the hook.
//
// Gate: the overlays belong to RynthVision, so they run only when
// RynthCore.Plugin.RynthVision.dll is in engine.json's PluginPaths (the list
// EntryPoint gates the Vision panel on), re-read every few seconds.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace RynthCore.Engine.ImGuiBackend.Hud;
internal static class HudFeed
{
private const string VisionDll = "RynthCore.Plugin.RynthVision.dll";
private static volatile bool _visionInstalled;
private static long _nextGateCheck;
/// <summary>True when the RynthVision plugin is in the plugin list. Any thread; re-checked every 5 s.</summary>
public static bool VisionInstalled
{
get
{
long now = Stopwatch.GetTimestamp();
if (now >= Volatile.Read(ref _nextGateCheck))
{
Volatile.Write(ref _nextGateCheck, now + Stopwatch.Frequency * 5);
_visionInstalled = HasVision();
}
return _visionInstalled;
}
}
private static bool HasVision()
{
try
{
IReadOnlyList<string> paths = Plugins.EngineSettings.PluginPaths;
for (int i = 0; i < paths.Count; i++)
if (string.Equals(Path.GetFileName(paths[i]), VisionDll, StringComparison.OrdinalIgnoreCase))
return true;
}
catch { }
return false;
}
/// <summary>Cheap gate for the feeds: the cached flag only (Update refreshes it).</summary>
private static bool On => _visionInstalled && MonsterHudSettings.Loaded;
public static void OnChat(string? line)
{
if (!On || string.IsNullOrEmpty(line)) return;
try
{
line = line.TrimEnd('\r', '\n'); // same instance when there is nothing to trim
if (MonsterHudSettings.Enabled && MonsterHudSettings.ShowDebuffs) PlateDebuffs.OnChat(line);
CombatText.OnChat(line);
}
catch (Exception ex) { Log("chat", ex); }
}
public static void OnCast(uint targetId, int spellId)
{
if (!On || !MonsterHudSettings.ShowDebuffs) return;
try { PlateDebuffs.NoteCast(targetId, spellId); }
catch (Exception ex) { Log("cast", ex); }
}
public static void OnSelection(uint id)
{
if (!On) return;
try { PlateDebuffs.NoteSelection(id); }
catch (Exception ex) { Log("selection", ex); }
}
public static void OnDeleted(uint id)
{
if (!On) return;
try
{
PlateDebuffs.Remove(id);
CombatText.OnDeleted(id);
}
catch (Exception ex) { Log("delete", ex); }
}
public static void OnDamageEvent(bool attacker, string? name, uint damage, bool crit)
{
if (!On) return;
try { CombatText.OnDamageEvent(attacker, name, damage, crit); }
catch (Exception ex) { Log("damage", ex); }
}
public static void OnKillMessage(string? message)
{
if (!On) return;
try { CombatText.OnKillMessage(message); }
catch (Exception ex) { Log("kill", ex); }
}
public static void OnAppraisal(uint id, uint enchantmentBitfield)
{
if (!On || !MonsterHudSettings.ShowDebuffs) return;
try { PlateDebuffs.OnAppraisal(id, enchantmentBitfield); }
catch (Exception ex) { Log("appraisal", ex); }
}
/// <summary><paramref name="prev"/> is -1 when this is the first observation.</summary>
public static void OnHealth(uint id, float prev, float ratio, uint max)
{
if (!On) return;
try
{
if (ratio <= 0.001f && prev > 0.001f) PlateDebuffs.Remove(id); // died
CombatText.OnHealth(id, prev, ratio, max);
}
catch (Exception ex) { Log("health", ex); }
}
private static int _errors;
private static void Log(string what, Exception ex)
{
if (++_errors <= 10)
RynthLog.UI($"Nameplates: {what} feed failed - {ex.GetType().Name}: {ex.Message}");
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,102 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/MonsterHudData.cs
// What the nameplates know about a monster beyond the client's object
// tables: its last health ratio (and absolute HP when a max is known) and
// whether it hit the player recently.
//
// Fed by two existing chokepoints (one line each, no new hooks); each health
// change is passed on to HudFeed (combat text kills / heals):
// PluginManager.QueueUpdateHealth - every health observation the engine
// makes (0x01C0 UpdateHealth, QueryHealthResponse, 0xC9 appraisal
// CreatureProfile, player vitals); runs whether or not plugins load.
// SmartBoxHooks.ParseGameEventDamage - DefenderNotification (0x01B2,
// "X hits you"), which names the attacker (no id on the wire).
// 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).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace RynthCore.Engine.ImGuiBackend.Hud;
/// <summary>Last health observation for one object.</summary>
internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks);
internal static class MonsterHudData
{
private static readonly object Sync = new();
private static readonly Dictionary<uint, HealthObservation> Health = new(256);
private static readonly Dictionary<string, long> Attackers = new(StringComparer.OrdinalIgnoreCase);
private const int MaxHealthEntries = 2048;
private const int MaxAttackerEntries = 64;
/// <summary>
/// A health update for <paramref name="id"/>. A max of 0 (ratio-only update)
/// keeps the last known max. Any thread; never blocks for long.
/// </summary>
public static void RecordHealth(uint id, float ratio, uint current, uint max)
{
if (id == 0 || float.IsNaN(ratio)) return;
ratio = Math.Clamp(ratio, 0f, 1f);
long now = Stopwatch.GetTimestamp();
float before = -1f;
lock (Sync)
{
bool had = Health.TryGetValue(id, out HealthObservation prev);
if (had) before = prev.Ratio;
if (max == 0 && had && prev.Max > 0)
{
max = prev.Max;
current = (uint)Math.Round(max * ratio);
}
if (Health.Count >= MaxHealthEntries && !Health.ContainsKey(id))
Health.Clear();
Health[id] = new HealthObservation(ratio, current, max, now);
}
// Kills and heals for the combat text; a death also drops the monster's debuffs.
HudFeed.OnHealth(id, before, ratio, max);
}
public static bool TryGetHealth(uint id, out HealthObservation h)
{
lock (Sync)
return Health.TryGetValue(id, out h);
}
/// <summary>A monster named <paramref name="name"/> hit the player. Any thread.</summary>
public static void RecordAttacker(string? name)
{
if (string.IsNullOrWhiteSpace(name)) return;
long now = Stopwatch.GetTimestamp();
lock (Sync)
{
if (Attackers.Count >= MaxAttackerEntries && !Attackers.ContainsKey(name))
Attackers.Clear();
Attackers[name] = now;
}
}
/// <summary>True when a monster with this name hit the player within <paramref name="seconds"/>.</summary>
public static bool AttackedRecently(string name, double seconds)
{
if (name.Length == 0) return false;
lock (Sync)
{
if (!Attackers.TryGetValue(name, out long t)) return false;
return (Stopwatch.GetTimestamp() - t) < (long)(seconds * Stopwatch.Frequency);
}
}
/// <summary>Logout / character switch: ids don't survive the session.</summary>
public static void Clear()
{
lock (Sync)
{
Health.Clear();
Attackers.Clear();
}
}
}

View file

@ -0,0 +1,294 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/MonsterHudSettings.cs
// Persisted settings of the monster nameplates (MonsterHud.cs), in the same
// hand-editable key=value style as RadarSettingsStore:
// %LocalAppData%\RynthCore\nameplate_settings.txt.
//
// Threads: fields are read on AC's render thread every frame and written by
// the Settings face (render thread) and /rc plates (AC's chat hook, the same
// thread). File I/O never runs on the render thread: Load and Save both go
// through UiBackgroundWriter, and the HUD draws nothing until Loaded is set,
// so a player who turned it off never sees a frame of plates at startup.
// ============================================================================
using System;
using System.Globalization;
using System.IO;
using RynthCore.Engine.UI;
namespace RynthCore.Engine.ImGuiBackend.Hud;
/// <summary>Which monsters get a plate.</summary>
internal enum PlateFilter
{
/// <summary>Every attackable monster in range (nearest first, up to MaxPlates).</summary>
All = 0,
/// <summary>The selected target, monsters that hit you recently, and monsters that are hurt.</summary>
Engaged = 1,
}
internal static class MonsterHudSettings
{
private static readonly object Sync = new();
private static volatile bool _loaded;
private static bool _loadQueued;
// ── Values (conservative defaults) ──────────────────────────────────
public static bool Enabled = true;
public static float MaxDistance = 35f; // yards (AC units)
public static int MaxPlates = 20;
public static PlateFilter Filter = PlateFilter.All;
public static bool ShowNames = true;
public static bool ShowHpNumbers = true;
public static bool ShowDistance = false;
public static bool ShowLevel = true;
public static bool ShowWeakness = true; // "Weak to" pill (RynthAi's learned damage data)
public static bool FadeWithDistance = true;
public static float Scale = 1.0f;
public static float Opacity = 0.9f;
public static float HeightLift = 0.0f; // extra metres above the estimated head height
/// <summary>A left-click on a monster plate selects that monster in game.</summary>
public static bool ClickToSelect = true;
// Name-only labels over NPCs (vendors in gold) and, optionally, other players.
// Counted apart from MaxPlates so they never push a monster plate out.
public static bool NpcNames = true;
public static float NpcMaxDistance = 30f; // yards; short so a town isn't a wall of text
public static int MaxNpcLabels = 15;
public static bool PlayerNames = false;
// Debuff icons on the monster plates (PlateDebuffs).
public static bool ShowDebuffs = true;
public static bool ShowOthersDebuff = true; // "debuffed by others" marker (appraisal highlights)
// The player's own plate (PlayerPlate): health / stamina / mana over your head.
public static bool SelfPlate = true;
public static bool SelfNumbers = false; // "cur/max" beside each bar
public static bool SelfName = false;
public static bool SelfHideFirstPerson = true;
// Combat text (CombatText): floating numbers and the kill burst.
public static bool Numbers = true;
public static bool NumDealt = true;
public static bool NumTaken = true;
public static bool NumHeals = true;
public static bool NumKills = true;
/// <summary>Plates, numbers and your plate stay inside the screen when the camera closes in (walls).</summary>
public static bool KeepOnScreen = true;
/// <summary>"+N stam" / "+N mana" over you when a spell, potion or kit restores them.</summary>
public static bool NumRestores = true;
/// <summary>Combat number size (1 = the 24 px bake) and how long they stay (1 = default).</summary>
public static float NumSize = 1.0f, NumTime = 1.0f;
/// <summary>XP / Lum / Radiance gain text: size and how long it stays (1 = default).</summary>
public static float GainSize = 1.0f, GainTime = 1.0f;
/// <summary>Where the player plate sits relative to the character.</summary>
public static SelfPlatePosition SelfPosition = SelfPlatePosition.Above;
public const float MinNumSize = 0.5f, MaxNumSize = 2.5f, MinNumTime = 0.5f, MaxNumTime = 3.0f;
// Gain text over the player: XP, Luminance, Radiance.
public static bool Gains = true;
public static bool GainXp = true;
public static bool GainLum = true;
public static bool GainRadiance = true;
// ── Ranges (shared by the Settings face, the command and Load) ──────
public const float MinDistance = 5f, MaxDistanceLimit = 120f;
public const int MinPlates = 1, MaxPlatesLimit = 60;
public const float MinNpcDistance = 5f, MaxNpcDistanceLimit = 80f;
public const int MinNpcLabels = 1, MaxNpcLabelsLimit = 40;
public const float MinScale = 0.6f, MaxScale = 2.0f;
public const float MinOpacity = 0.2f, MaxOpacity = 1.0f;
public const float MinLift = -1.5f, MaxLift = 3.0f;
/// <summary>True once the file has been read (or found missing). Any thread.</summary>
public static bool Loaded => _loaded;
private static string FilePath =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "nameplate_settings.txt");
/// <summary>Queues the one-time read off the calling thread. Any thread; cheap after the first call.</summary>
public static void EnsureLoadQueued()
{
if (_loaded) return;
lock (Sync)
{
if (_loadQueued) return;
_loadQueued = true;
}
UiBackgroundWriter.Enqueue("nameplate settings (load)", LoadNow);
}
private static void LoadNow()
{
lock (Sync)
{
try
{
string path = FilePath;
if (!File.Exists(path)) return;
foreach (string raw in File.ReadAllLines(path))
{
string line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#')) continue;
int eq = line.IndexOf('=');
if (eq <= 0) continue;
string key = line[..eq].Trim();
string val = line[(eq + 1)..].Trim();
switch (key)
{
case "enabled": Enabled = val == "1"; break;
case "maxDistance": if (TryF(val, out float d)) MaxDistance = Math.Clamp(d, MinDistance, MaxDistanceLimit); break;
case "maxPlates":
if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
MaxPlates = Math.Clamp(n, MinPlates, MaxPlatesLimit);
break;
case "filter": Filter = val.Equals("engaged", StringComparison.OrdinalIgnoreCase) ? PlateFilter.Engaged : PlateFilter.All; break;
case "showNames": ShowNames = val == "1"; break;
case "showHp": ShowHpNumbers = val == "1"; break;
case "showDistance": ShowDistance = val == "1"; break;
case "showLevel": ShowLevel = val == "1"; break;
case "showWeakness": ShowWeakness = val == "1"; break;
case "fade": FadeWithDistance = val == "1"; break;
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 "heightLift": if (TryF(val, out float h)) HeightLift = Math.Clamp(h, MinLift, MaxLift); break;
case "npcNames": NpcNames = val == "1"; break;
case "npcDistance": if (TryF(val, out float nd)) NpcMaxDistance = Math.Clamp(nd, MinNpcDistance, MaxNpcDistanceLimit); break;
case "npcMax":
if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int nm))
MaxNpcLabels = Math.Clamp(nm, MinNpcLabels, MaxNpcLabelsLimit);
break;
case "playerNames": PlayerNames = val == "1"; break;
case "showDebuffs": ShowDebuffs = val == "1"; break;
case "showOthersDebuff": ShowOthersDebuff = val == "1"; break;
case "selfPlate": SelfPlate = val == "1"; break;
case "selfNumbers": SelfNumbers = val == "1"; break;
case "selfName": SelfName = val == "1"; break;
case "selfHideFirstPerson": SelfHideFirstPerson = val == "1"; break;
case "numbers": Numbers = val == "1"; break;
case "numDealt": NumDealt = val == "1"; break;
case "numTaken": NumTaken = val == "1"; break;
case "numHeals": NumHeals = val == "1"; break;
case "numKills": NumKills = val == "1"; break;
case "keepOnScreen": KeepOnScreen = val == "1"; break;
case "numRestores": NumRestores = val == "1"; break;
case "numSize": if (TryF(val, out float ns)) NumSize = Math.Clamp(ns, MinNumSize, MaxNumSize); break;
case "numTime": if (TryF(val, out float nt)) NumTime = Math.Clamp(nt, MinNumTime, MaxNumTime); break;
case "selfPosition": if (Enum.TryParse(val, true, out SelfPlatePosition sp)) SelfPosition = sp; break;
case "gainSize": if (TryF(val, out float gs)) GainSize = Math.Clamp(gs, MinNumSize, MaxNumSize); break;
case "gainTime": if (TryF(val, out float gt)) GainTime = Math.Clamp(gt, MinNumTime, MaxNumTime); break;
case "gains": Gains = val == "1"; break;
case "gainXp": GainXp = val == "1"; break;
case "gainLum": GainLum = val == "1"; break;
case "gainRadiance": GainRadiance = val == "1"; break;
}
}
}
catch { /* best-effort: defaults stay */ }
finally { _loaded = true; }
}
}
private static bool TryF(string s, out float v) => float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out v);
/// <summary>Writes the settings in the background. Any thread.</summary>
public static void Save() => UiBackgroundWriter.Enqueue("nameplate settings", SaveNow);
private static void SaveNow()
{
lock (Sync)
{
try
{
string path = FilePath;
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
using var sw = new StreamWriter(path, append: false);
sw.WriteLine("# RynthCore monster nameplates - auto-generated, hand-edits OK. /rc plates in game.");
sw.WriteLine($"enabled={B(Enabled)}");
sw.WriteLine(FormattableString.Invariant($"maxDistance={MaxDistance:0.#}"));
sw.WriteLine(FormattableString.Invariant($"maxPlates={MaxPlates}"));
sw.WriteLine($"filter={(Filter == PlateFilter.Engaged ? "engaged" : "all")}");
sw.WriteLine($"showNames={B(ShowNames)}");
sw.WriteLine($"showHp={B(ShowHpNumbers)}");
sw.WriteLine($"showDistance={B(ShowDistance)}");
sw.WriteLine($"showLevel={B(ShowLevel)}");
sw.WriteLine($"showWeakness={B(ShowWeakness)}");
sw.WriteLine($"fade={B(FadeWithDistance)}");
sw.WriteLine(FormattableString.Invariant($"scale={Scale:0.##}"));
sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}"));
sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}"));
sw.WriteLine($"clickSelect={B(ClickToSelect)}");
sw.WriteLine($"npcNames={B(NpcNames)}");
sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}"));
sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}"));
sw.WriteLine($"playerNames={B(PlayerNames)}");
sw.WriteLine($"showDebuffs={B(ShowDebuffs)}");
sw.WriteLine($"showOthersDebuff={B(ShowOthersDebuff)}");
sw.WriteLine($"selfPlate={B(SelfPlate)}");
sw.WriteLine($"selfNumbers={B(SelfNumbers)}");
sw.WriteLine($"selfName={B(SelfName)}");
sw.WriteLine($"selfHideFirstPerson={B(SelfHideFirstPerson)}");
sw.WriteLine($"numbers={B(Numbers)}");
sw.WriteLine($"numDealt={B(NumDealt)}");
sw.WriteLine($"numTaken={B(NumTaken)}");
sw.WriteLine($"numHeals={B(NumHeals)}");
sw.WriteLine($"numKills={B(NumKills)}");
sw.WriteLine($"keepOnScreen={B(KeepOnScreen)}");
sw.WriteLine($"numRestores={B(NumRestores)}");
sw.WriteLine(FormattableString.Invariant($"numSize={NumSize:0.##}"));
sw.WriteLine(FormattableString.Invariant($"numTime={NumTime:0.##}"));
sw.WriteLine(FormattableString.Invariant($"gainSize={GainSize:0.##}"));
sw.WriteLine($"selfPosition={SelfPosition}");
sw.WriteLine(FormattableString.Invariant($"gainTime={GainTime:0.##}"));
sw.WriteLine($"gains={B(Gains)}");
sw.WriteLine($"gainXp={B(GainXp)}");
sw.WriteLine($"gainLum={B(GainLum)}");
sw.WriteLine($"gainRadiance={B(GainRadiance)}");
}
catch { /* non-fatal */ }
}
}
private static string B(bool v) => v ? "1" : "0";
/// <summary>Back to the defaults (and saved). Render / chat thread.</summary>
public static void ResetToDefaults()
{
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;
ShowDebuffs = true; ShowOthersDebuff = true;
NpcNames = true; NpcMaxDistance = 30f; MaxNpcLabels = 15; PlayerNames = false;
SelfPlate = true; SelfNumbers = false; SelfName = false; SelfHideFirstPerson = true;
Numbers = true; NumDealt = true; NumTaken = true; NumHeals = true; NumKills = true;
NumSize = 1.0f; NumTime = 1.0f; NumRestores = true; KeepOnScreen = true;
GainSize = 1.0f; GainTime = 1.0f; SelfPosition = SelfPlatePosition.Above;
Gains = true; GainXp = true; GainLum = true; GainRadiance = true;
Save();
}
/// <summary>Every master switch at once ("/rv plates all on|off").</summary>
public static void SetAll(bool on)
{
Enabled = on; ShowDebuffs = on; SelfPlate = on; Numbers = on; Gains = on; NpcNames = on;
if (!on) PlayerNames = false; // "all on" leaves player names as chosen (off by default)
}
/// <summary>One line for chat: the current state.</summary>
public static string Describe() => string.Create(CultureInfo.InvariantCulture,
$"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)}), debuffs {OnOff(ShowDebuffs)} (others {OnOff(ShowOthersDebuff)}); " +
$"NPC names {OnOff(NpcNames)} ({NpcMaxDistance:0}yd, max {MaxNpcLabels}), player names {OnOff(PlayerNames)}; " +
$"self {OnOff(SelfPlate)} (numbers {OnOff(SelfNumbers)}, name {OnOff(SelfName)}, hide in first person {OnOff(SelfHideFirstPerson)}); " +
$"combat text {OnOff(Numbers)} (dealt {OnOff(NumDealt)}, taken {OnOff(NumTaken)}, heals {OnOff(NumHeals)}, kills {OnOff(NumKills)}); " +
$"gains {OnOff(Gains)} (xp {OnOff(GainXp)}, lum {OnOff(GainLum)}, radiance {OnOff(GainRadiance)}).");
private static string OnOff(bool v) => v ? "on" : "off";
}
/// <summary>Player plate placement: over the head, under the feet, or beside the character.</summary>
internal enum SelfPlatePosition { Above, Below, Left, Right }

View file

@ -0,0 +1,261 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/MonsterHudSettingsUi.cs
// The RynthVision overlay settings, drawn as two tabs of the Vision panel
// (Panels/VisionFace.cs): "Nameplates" (monster plates, NPC / player names,
// debuff icons, your plate, look) and "Combat text" (numbers, kill burst, gains). Square toggle
// dots and amber section headers; sliders save when the drag ends. Values
// live engine-side in MonsterHudSettings. AC's render thread, inside the
// face's content child.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend.Hud;
internal static class MonsterHudSettingsUi
{
private static readonly uint Amber = C(0xFFE8B333), TextDim = C(0xFFF2F7FC), Mute = C(0xFFB8C8D8),
ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455), BtnBord = C(0xFF34587A), BtnFill = C(0xFF16283A);
private static uint C(uint argb) => RynthTheme.Argb(argb);
private static bool Loading(float w)
{
if (MonsterHudSettings.Loaded) return false;
MonsterHudSettings.EnsureLoadQueued();
Note("Loading...", w);
return true;
}
/// <summary>The "Nameplates" tab body at the cursor, <paramref name="w"/> wide.</summary>
public static void DrawNameplates(float w)
{
if (Loading(w)) return;
bool changed = false;
Section("Monster plates", w);
changed |= Toggle("Show monster nameplates", ref MonsterHudSettings.Enabled,
"Health bars and names over monsters in the world. Chat: /rv plates on|off.");
changed |= Toggle("Click a plate to select", ref MonsterHudSettings.ClickToSelect,
"Left-click a monster's plate (name or health bar) to select that monster, as clicking it in the world does. " +
"Off: plates never take a click. Chat: /rv plates click.", sub: true);
Note("Plates sit under every panel; a click on a plate selects its monster, every other click goes to the game.", w);
bool all = MonsterHudSettings.Filter == PlateFilter.All;
if (Toggle("All monsters in range", ref all, "Every attackable monster within the distance, nearest first.", radio: true))
{
MonsterHudSettings.Filter = PlateFilter.All;
changed = true;
}
bool engaged = MonsterHudSettings.Filter == PlateFilter.Engaged;
if (Toggle("Only target + attackers", ref engaged,
"Your selected target, monsters that hit you in the last 20 s, and monsters that are hurt.", radio: true))
{
MonsterHudSettings.Filter = PlateFilter.Engaged;
changed = true;
}
changed |= SliderF("Max distance (yd)", ref MonsterHudSettings.MaxDistance,
MonsterHudSettings.MinDistance, MonsterHudSettings.MaxDistanceLimit, "%.0f", w);
changed |= SliderI("Max plates", ref MonsterHudSettings.MaxPlates,
MonsterHudSettings.MinPlates, MonsterHudSettings.MaxPlatesLimit, w);
Section("On the plate", w);
changed |= Toggle("Name", ref MonsterHudSettings.ShowNames, null);
changed |= Toggle("HP numbers", ref MonsterHudSettings.ShowHpNumbers,
"\"142 / 190\" when the monster's max HP is known (appraised), else a percentage. Hidden until its health has been seen.");
changed |= Toggle("Level badge", ref MonsterHudSettings.ShowLevel,
"Coloured against your level: grey, green, white, orange, red. Needs an appraisal.");
changed |= Toggle("Weak-to element", ref MonsterHudSettings.ShowWeakness,
"What the monster takes most damage from, from RynthAi's Damage data (needs RynthAi).");
changed |= Toggle("Distance", ref MonsterHudSettings.ShowDistance, null);
Section("Names over NPCs and players", w);
changed |= Toggle("NPC names", ref MonsterHudSettings.NpcNames,
"The name over vendors, quest givers, town criers and other NPCs: yellow, vendors gold (the radar's colours). " +
"Name only, no health bar; click one to select it. Chat: /rv plates npcs.");
changed |= SliderF("NPC name distance (yd)", ref MonsterHudSettings.NpcMaxDistance,
MonsterHudSettings.MinNpcDistance, MonsterHudSettings.MaxNpcDistanceLimit, "%.0f", w);
changed |= SliderI("Max names", ref MonsterHudSettings.MaxNpcLabels,
MonsterHudSettings.MinNpcLabels, MonsterHudSettings.MaxNpcLabelsLimit, w);
changed |= Toggle("Player names", ref MonsterHudSettings.PlayerNames,
"The name over other players too (blue), within the same distance and count. Chat: /rv plates players.");
Note("Names count apart from the monster plates, so they never push one out; the nearest win.", w);
Section("Debuffs", w);
changed |= Toggle("Debuff icons", ref MonsterHudSettings.ShowDebuffs,
"Your own debuffs on each monster (vulnerabilities, Imperil, Magic Yield, attribute and skill debuffs...), " +
"one icon per kind with a line that runs out with the spell. From your \"You cast ... on ...\" lines. Chat: /rv plates debuffs.");
changed |= Toggle("Debuffed by others", ref MonsterHudSettings.ShowOthersDebuff,
"A small marker when an appraisal shows a lowered attribute or vital that none of your own debuffs explains. " +
"It only updates when the monster is appraised (your combat target is appraised often).", sub: true);
Section("Your plate", w);
changed |= Toggle("Show your plate", ref MonsterHudSettings.SelfPlate,
"Health, stamina and mana bars over your own head. Chat: /rv plates self.");
changed |= Toggle("Numbers on your bars", ref MonsterHudSettings.SelfNumbers, "\"cur / max\" inside each bar (taller bars).", sub: true);
changed |= Toggle("Your name", ref MonsterHudSettings.SelfName, null, sub: true);
changed |= Toggle("Hide in first person", ref MonsterHudSettings.SelfHideFirstPerson,
"When the camera is at your head the plate would sit mid-screen; hide it then.", sub: true);
changed |= SelfPositionPick("Over your head", SelfPlatePosition.Above);
changed |= SelfPositionPick("Under your feet", SelfPlatePosition.Below);
changed |= SelfPositionPick("Beside you, left", SelfPlatePosition.Left);
changed |= SelfPositionPick("Beside you, right", SelfPlatePosition.Right);
Section("Look", w);
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 |= 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);
ImGuiNET.ImGui.Dummy(new Vector2(0, 8));
if (SmallButton("Reset all to defaults"))
{
MonsterHudSettings.ResetToDefaults();
changed = false; // ResetToDefaults saved already
}
if (changed)
MonsterHudSettings.Save();
}
/// <summary>The "Combat text" tab body at the cursor, <paramref name="w"/> wide.</summary>
public static void DrawCombatText(float w)
{
if (Loading(w)) return;
bool changed = false;
Section("Combat numbers", w);
changed |= Toggle("Show combat numbers", ref MonsterHudSettings.Numbers,
"Floating numbers over monsters and over you. Chat: /rv plates numbers.");
changed |= Toggle("Damage you deal", ref MonsterHudSettings.NumDealt,
"White to red by size; gold and bigger with \"!\" on a crit. A killing blow is estimated from the last health seen.", sub: true);
changed |= Toggle("Damage you take", ref MonsterHudSettings.NumTaken, "Red numbers over your head.", sub: true);
changed |= Toggle("Heals", ref MonsterHudSettings.NumHeals,
"Green \"+N\" when you or a monster gains more health than a regen tick.", sub: true);
changed |= Toggle("Kill burst", ref MonsterHudSettings.NumKills, "Expanding rings where a monster you damaged dies.", sub: true);
changed |= Toggle("Stamina and mana restores", ref MonsterHudSettings.NumRestores,
"\"+N stam\" (amber) and \"+N mana\" (blue) over you when a spell, potion or kit restores more than a regen tick.", sub: true);
changed |= SliderF("Number size", ref MonsterHudSettings.NumSize, MonsterHudSettings.MinNumSize, MonsterHudSettings.MaxNumSize, "%.2f", w);
changed |= SliderF("Number duration", ref MonsterHudSettings.NumTime, MonsterHudSettings.MinNumTime, MonsterHudSettings.MaxNumTime, "%.2fx", w);
Section("Gains", w);
changed |= Toggle("Show gains", ref MonsterHudSettings.Gains,
"Rising text over your head when you earn. Chat: /rv plates gains.");
changed |= Toggle("Experience", ref MonsterHudSettings.GainXp, "\"+12,345 XP\"", sub: true);
changed |= Toggle("Luminance", ref MonsterHudSettings.GainLum, "\"+500 Lum\"", sub: true);
changed |= Toggle("Radiance", ref MonsterHudSettings.GainRadiance,
"\"+10 Radiance\", from Aelrynth's \"You gain N Radiance.\" lines.", sub: true);
changed |= SliderF("Gain text size", ref MonsterHudSettings.GainSize, MonsterHudSettings.MinNumSize, MonsterHudSettings.MaxNumSize, "%.2f", w);
changed |= SliderF("Gain text duration", ref MonsterHudSettings.GainTime, MonsterHudSettings.MinNumTime, MonsterHudSettings.MaxNumTime, "%.2fx", w);
Note("Spending experience or luminance never shows.", w);
if (changed)
MonsterHudSettings.Save();
}
// ── Rows ─────────────────────────────────────────────────────────────
/// <summary>A square dot + label; the row toggles (a radio row only ever turns on; a sub row is indented).</summary>
private static bool SelfPositionPick(string label, SelfPlatePosition pos)
{
bool on = MonsterHudSettings.SelfPosition == pos;
if (!Toggle(label, ref on, "Where your plate sits. Chat: /rv plates self position above|below|left|right.", radio: true, sub: true))
return false;
MonsterHudSettings.SelfPosition = pos;
return true;
}
private static bool Toggle(string label, ref bool value, string? tip, bool radio = false, bool sub = false)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
if (sub) ImGuiNET.ImGui.SetCursorScreenPos(ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(16, 0));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float labelW = ImGuiNET.ImGui.CalcTextSize(label).X;
ImGuiNET.ImGui.PushID(label);
bool clicked = ImGuiNET.ImGui.InvisibleButton("##t", new Vector2(18 + labelW, 16));
ImGuiNET.ImGui.PopID();
if (ImGuiNET.ImGui.IsItemHovered())
{
ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
if (tip != null) ImGuiNET.ImGui.SetTooltip(tip);
}
if (clicked) value = radio || !value;
dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), value ? ToggleOn : ToggleOff, 2);
dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
return clicked;
}
private static bool SliderF(string label, ref float value, float min, float max, string fmt, float w)
{
BeginSliderRow(label, w);
bool changed = ImGuiNET.ImGui.SliderFloat("##v", ref value, min, max, fmt, ImGuiSliderFlags.AlwaysClamp);
return EndSliderRow(changed);
}
private static bool SliderI(string label, ref int value, int min, int max, float w)
{
BeginSliderRow(label, w);
bool changed = ImGuiNET.ImGui.SliderInt("##v", ref value, min, max, "%d", ImGuiSliderFlags.AlwaysClamp);
return EndSliderRow(changed);
}
private static void BeginSliderRow(string label, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.GetWindowDrawList().AddText(p + new Vector2(0, 2), TextDim, label);
float labelCol = Math.Min(130, w * 0.45f);
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + labelCol, p.Y));
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(60, w - labelCol));
ImGuiNET.ImGui.PushID(label);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
}
/// <summary>True once the edit is finished (drag released or value typed), so saves aren't per-step.</summary>
private static bool EndSliderRow(bool changed)
{
bool done = changed && !ImGuiNET.ImGui.IsItemActive() || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(2);
ImGuiNET.ImGui.PopID();
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
return done;
}
private static void Section(string text, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.GetWindowDrawList().AddText(p, Amber, text);
ImGuiNET.ImGui.Dummy(new Vector2(w, ImGuiNET.ImGui.GetFontSize() + 2));
ImGuiNET.ImGui.PopFont();
}
private static void Note(string text, float w)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopStyleColor();
}
private static bool SmallButton(string label)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(8, 3));
bool clicked = ImGuiNET.ImGui.Button(label);
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(2);
return clicked;
}
}

View file

@ -0,0 +1,519 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/PlateDebuffs.cs
// Which debuffs are on which monster, for the icon row on each nameplate.
//
// Source 1, the player's own casts (primary). ACE tells the caster
// "You cast {spell} on {target}{suffix}" (ChatMessageType.Magic)
// with suffix ", surpassing X" | ", refreshing X" | ", but it is surpassed by X"
// (WorldObject_Magic.cs, from AddEnchantmentResult.StackType), and
// "{target} resists your spell", "You fail to affect {target} with {spell}".
// The line names the target, not its id, and several monsters share names,
// so the line is matched to an object id:
// 1. a pending engine cast (CombatActionHooks.CastSpell: RynthAi and every
// other engine-issued cast) of the same spell on a monster of that name,
// within PendingCastSec;
// 2. else the selected target, or a target selected within PendingCastSec,
// with that name (manual casts go at the selection);
// 3. else the only creature of that name within FallbackRangeM;
// 4. else nothing is recorded (ambiguous).
// The spell name gives id / category / power / duration through the client's
// spell table (PortalSpellTable). Stacking follows AC: one entry per spell
// category; a surpassing or refreshing cast replaces it; a surpassed cast
// leaves the stronger one and at least extends how long the category lasts.
// Duration: the table's, times 1 + 0.2 x the player's
// AugmentationIncreasedSpellDuration (PropertyInt 238), not for DoTs (ACE
// EnchantmentManager.BuildEntry).
//
// Source 2, appraisal highlights (secondary, generic). The 0xC9 appraisal's
// CreatureAppraisalProfile keeps enchantment_bitfield: low 9 bits = attribute
// or vital modified, bits 16..24 = modified upward (green). Red bits that none
// of the player's own debuffs explained at that moment raise one "debuffed by
// others" marker, kept for OthersMemorySec or until the next appraisal. It
// only refreshes on appraisal (the combat target is re-appraised often).
//
// Entries drop at expiry, when the monster dies or is released (delete), and
// on logout. Fed on AC's main thread (chat, cast, selection, appraisal,
// delete hooks); read by the plates on the render thread. A lock keeps it
// safe if a caller moves. Bounded. Engine-owned statics only.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.ImGuiBackend.Hud;
/// <summary>What an icon on the plate stands for (one icon per kind).</summary>
internal enum DebuffKind : byte
{
VulnFire, VulnCold, VulnLightning, VulnAcid, VulnSlash, VulnPierce, VulnBludgeon,
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>
internal struct DebuffIcon
{
public DebuffKind Kind;
public long Expiry; // Stopwatch ticks
public float Duration; // seconds, of the entry expiring first
public int Stack;
}
internal static class PlateDebuffs
{
private const double PendingCastSec = 8.0;
private const float FallbackRangeM = 60f;
private const double OthersMemorySec = 180.0;
private const int MaxMonsters = 512;
private const int MaxPending = 16;
private const uint TypeCreature = 0x10;
private sealed class Entry
{
public uint Category;
public DebuffKind Kind;
public uint SpellId;
public uint Power;
public long Expiry;
public float Duration;
}
private readonly record struct PendingCast(uint Target, uint SpellId, long Ticks);
private readonly record struct Selection(uint Id, long Ticks);
private readonly record struct OthersMark(ushort Mask, long Ticks);
private static readonly object Sync = new();
private static readonly Dictionary<uint, List<Entry>> ByMonster = new(64);
private static readonly Dictionary<uint, OthersMark> Others = new(64);
private static readonly List<PendingCast> Pending = new(MaxPending);
private static readonly List<Selection> Selections = new(8);
private static float _durationMult = 1f;
private static int _recorded, _ambiguous, _resisted;
private static string _lastEvent = "none yet";
/// <summary>Caster duration multiplier from AugmentationIncreasedSpellDuration (MonsterHud refreshes it).</summary>
public static void SetDurationAugmentation(int augs) =>
_durationMult = 1f + Math.Clamp(augs, 0, 5) * 0.2f;
// ── Feeds (AC's main thread) ─────────────────────────────────────────
/// <summary>
/// An engine-issued cast (targetId 0 = self: ignored). A repeat of the same
/// spell on the same target (a retry, or the off-thread enqueue and its
/// main-thread run) refreshes the one entry instead of adding another.
/// </summary>
public static void NoteCast(uint targetId, int spellId)
{
if (targetId == 0 || spellId <= 0) return;
long now = Stopwatch.GetTimestamp();
lock (Sync)
{
for (int i = 0; i < Pending.Count; i++)
if (Pending[i].Target == targetId && Pending[i].SpellId == (uint)spellId)
{
Pending.RemoveAt(i);
break;
}
if (Pending.Count >= MaxPending) Pending.RemoveAt(0);
Pending.Add(new PendingCast(targetId, (uint)spellId, now));
}
}
/// <summary>The client's selection changed.</summary>
public static void NoteSelection(uint id)
{
if (id == 0) return;
long now = Stopwatch.GetTimestamp();
lock (Sync)
{
if (Selections.Count >= 8) Selections.RemoveAt(0);
Selections.Add(new Selection(id, now));
}
}
/// <summary>A monster left the client (died, despawned, out of range): its debuffs go with it.</summary>
public static void Remove(uint id)
{
lock (Sync)
{
ByMonster.Remove(id);
Others.Remove(id);
}
}
public static void Clear()
{
lock (Sync)
{
ByMonster.Clear();
Others.Clear();
Pending.Clear();
Selections.Clear();
}
}
/// <summary>
/// The appraisal's enchantment bitfield for a creature (successful roll only).
/// Keeps the red bits that the player's own tracked debuffs don't explain.
/// </summary>
public static void OnAppraisal(uint id, uint bitfield)
{
if (id == 0 || (bitfield & 0xFE00FE00u) != 0) return; // bits outside the 9 + 9 known: not trusted
ushort red = (ushort)((bitfield & 0x1FF) & ~((bitfield >> 16) & 0x1FF));
long now = Stopwatch.GetTimestamp();
lock (Sync)
{
ushort explained = 0;
if (ByMonster.TryGetValue(id, out List<Entry>? list))
foreach (Entry e in list)
if (e.Expiry > now) explained |= ExplainedBits(e.Category);
ushort unexplained = (ushort)(red & ~explained);
if (unexplained == 0) { Others.Remove(id); return; }
if (Others.Count >= MaxMonsters && !Others.ContainsKey(id)) Others.Clear();
Others[id] = new OthersMark(unexplained, now);
}
}
/// <summary>
/// A chat line. Cheap unless it is one of the caster's magic lines. Needs
/// the spell table; before it has loaded, cast lines are ignored.
/// </summary>
public static void OnChat(string line)
{
if (line.Length < 12) return;
if (line.StartsWith("You cast ", StringComparison.Ordinal))
{
if (!PortalSpellTable.Ready) { PortalSpellTable.EnsureLoadQueued(); return; }
OnYouCast(line);
return;
}
if (line.EndsWith(" resists your spell", StringComparison.Ordinal))
{
string name = line[..^" resists your spell".Length];
Consume(name, 0);
lock (Sync) { _resisted++; _lastEvent = $"{name} resisted"; }
return;
}
if (line.StartsWith("You fail to affect ", StringComparison.Ordinal))
{
int with = line.LastIndexOf(" with ", StringComparison.Ordinal);
if (with > 19) Consume(line[19..with], 0);
return;
}
if (line.StartsWith("Your spell fizzled", StringComparison.Ordinal))
{
lock (Sync) if (Pending.Count > 0) Pending.RemoveAt(Pending.Count - 1);
}
}
private static readonly string[] SuffixMarks = { ", surpassing ", ", refreshing ", ", but it is surpassed by " };
private static void OnYouCast(string line)
{
// "You cast <spell> on <target>[<suffix>]"
string body = line[9..].TrimEnd('.', ' ', '\r', '\n');
int suffixAt = -1, suffixKind = -1;
for (int k = 0; k < SuffixMarks.Length; k++)
{
int i = body.IndexOf(SuffixMarks[k], StringComparison.Ordinal);
if (i > 0 && (suffixAt < 0 || i < suffixAt)) { suffixAt = i; suffixKind = k; }
}
string surpassedBy = suffixKind == 2 ? body[(suffixAt + SuffixMarks[2].Length)..] : "";
if (suffixAt > 0) body = body[..suffixAt];
// The spell name may itself contain " on ": try each split, left to right.
DebuffSpell? spell = null;
string target = "";
for (int at = body.IndexOf(" on ", StringComparison.Ordinal); at > 0; at = body.IndexOf(" on ", at + 1, StringComparison.Ordinal))
{
if (PortalSpellTable.TryGetByName(body[..at], out DebuffSpell s))
{
spell = s;
target = body[(at + 4)..];
break;
}
}
if (spell == null || target.Length == 0 || target == "yourself" || target == "you") return; // a buff, or not ours
long now = Stopwatch.GetTimestamp();
uint id = ResolveTarget(spell, target, now, out string how);
lock (Sync)
{
if (id == 0)
{
_ambiguous++;
_lastEvent = $"{spell.Name} on {target}: target ambiguous, not shown";
return;
}
Apply(id, spell, suffixKind, surpassedBy, now);
_recorded++;
_lastEvent = $"{spell.Name} on {target} (0x{id:X8}, {how})";
}
}
/// <summary>Pending engine cast, then the selection, then a unique name nearby; 0 if ambiguous.</summary>
private static uint ResolveTarget(DebuffSpell spell, string name, long now, out string how)
{
long window = (long)(PendingCastSec * Stopwatch.Frequency);
lock (Sync)
{
// 1. The newest engine cast of this spell on a monster so named.
int best = -1;
for (int i = Pending.Count - 1; i >= 0; i--)
{
PendingCast p = Pending[i];
if (now - p.Ticks > window) continue;
if (p.SpellId != spell.Id && !SameName(p.SpellId, spell.Name)) continue;
if (!NameIs(p.Target, name)) continue;
best = i;
break;
}
if (best >= 0)
{
uint t = Pending[best].Target;
Pending.RemoveAt(best);
how = "engine cast";
return t;
}
}
// 2. The selection (manual casts go at the selected target).
uint sel = ClientHelperHooks.GetSelectedItemId();
if (sel != 0 && NameIs(sel, name)) { how = "selected"; return sel; }
lock (Sync)
{
for (int i = Selections.Count - 1; i >= 0; i--)
{
Selection s = Selections[i];
if (now - s.Ticks > window) break;
if (NameIs(s.Id, name)) { how = "recent selection"; return s.Id; }
}
}
// 3. The only creature of that name nearby.
uint only = UniqueNearby(name);
how = only != 0 ? "unique name" : "ambiguous";
return only;
}
private static bool SameName(uint spellId, string name) =>
PortalSpellTable.TryGetById(spellId, out DebuffSpell s) && s.Name.Equals(name, StringComparison.OrdinalIgnoreCase);
private static bool NameIs(uint id, string name) =>
ClientObjectHooks.TryGetSnapshotName(id, out string n) && n.Equals(name, StringComparison.Ordinal);
/// <summary>The only creature so named within FallbackRangeM of the player; 0 when none or several.</summary>
internal static uint UniqueNearby(string name)
{
if (!PlayerPhysicsHooks.TryGetPlayerPose(out uint pCell, out float px, out float py, out float pz, out _, out _, out _, out _))
return 0;
uint found = 0;
uint[] ids = ClientObjectHooks.LiveObjectIds;
for (int i = 0; i < ids.Length; i++)
{
uint id = ids[i];
if (!NameIs(id, name)) continue;
if (!ClientObjectHooks.TryGetSnapshotItemType(id, out uint type) || (type & TypeCreature) == 0) continue;
if (!ClientObjectHooks.TryGetSnapshotPosition(id, out uint cell, out float x, out float y, out float z)) continue;
int dx = (int)((cell >> 24) & 0xFF) - (int)((pCell >> 24) & 0xFF);
int dy = (int)((cell >> 16) & 0xFF) - (int)((pCell >> 16) & 0xFF);
if (Math.Abs(dx) > 1 || Math.Abs(dy) > 1) continue;
float ex = x + dx * 192f - px, ey = y + dy * 192f - py, ez = z - pz;
if (ex * ex + ey * ey + ez * ez > FallbackRangeM * FallbackRangeM) continue;
if (found != 0) return 0; // two of them: ambiguous
found = id;
}
return found;
}
/// <summary>A resist or failure: drop the newest pending cast on a monster so named.</summary>
private static void Consume(string name, uint spellId)
{
lock (Sync)
{
for (int i = Pending.Count - 1; i >= 0; i--)
{
if ((spellId == 0 || Pending[i].SpellId == spellId) && NameIs(Pending[i].Target, name))
{
Pending.RemoveAt(i);
return;
}
}
}
}
/// <summary>AC-style stacking, one entry per category. Caller holds Sync.</summary>
private static void Apply(uint id, DebuffSpell spell, int suffixKind, string surpassedBy, long now)
{
float dur = (float)spell.Duration * (spell.IsDot ? 1f : _durationMult);
if (dur <= 0) return;
long expiry = now + (long)(dur * Stopwatch.Frequency);
if (!ByMonster.TryGetValue(id, out List<Entry>? list))
{
if (ByMonster.Count >= MaxMonsters) ByMonster.Clear();
list = new List<Entry>(4);
ByMonster[id] = list;
}
Entry? e = null;
foreach (Entry x in list)
if (x.Category == spell.Category) { e = x; break; }
if (suffixKind == 2)
{
// Surpassed: the stronger spell stays; ours sits under it, so the category lasts at least as long as ours.
if (e != null)
{
if (expiry > e.Expiry) { e.Expiry = expiry; e.Duration = dur; }
return;
}
DebuffSpell shown = PortalSpellTable.TryGetByName(surpassedBy, out DebuffSpell y) && y.Category == spell.Category ? y : spell;
list.Add(new Entry { Category = spell.Category, Kind = KindOf(shown), SpellId = shown.Id, Power = shown.Power, Expiry = expiry, Duration = dur });
return;
}
// Initial, surpassing, refreshing: this spell now heads the category.
if (e == null)
{
e = new Entry { Category = spell.Category };
list.Add(e);
}
e.Kind = KindOf(spell);
e.SpellId = spell.Id;
e.Power = spell.Power;
e.Expiry = expiry;
e.Duration = dur;
}
// ── Read (render thread) ─────────────────────────────────────────────
/// <summary>
/// The icons for one monster, merged by kind, soonest expiry first within a
/// kind; expired entries are dropped here. Returns the icon count (may
/// exceed dst.Length: the rest are the overflow).
/// </summary>
public static int GetIcons(uint id, DebuffIcon[] dst, out bool others)
{
others = false;
long now = Stopwatch.GetTimestamp();
lock (Sync)
{
if (Others.TryGetValue(id, out OthersMark m))
{
if (now - m.Ticks < (long)(OthersMemorySec * Stopwatch.Frequency)) others = true;
else Others.Remove(id);
}
if (!ByMonster.TryGetValue(id, out List<Entry>? list)) return 0;
for (int i = list.Count - 1; i >= 0; i--)
if (list[i].Expiry <= now) list.RemoveAt(i);
if (list.Count == 0) { ByMonster.Remove(id); return 0; }
int n = 0;
ulong seen = 0;
foreach (Entry e in list)
{
int k = (int)e.Kind;
if ((seen & (1UL << k)) != 0)
{
for (int i = 0; i < Math.Min(n, dst.Length); i++)
{
if (dst[i].Kind != e.Kind) continue;
dst[i].Stack++;
if (e.Expiry < dst[i].Expiry) { dst[i].Expiry = e.Expiry; dst[i].Duration = e.Duration; }
break;
}
continue;
}
seen |= 1UL << k;
if (n < dst.Length)
dst[n] = new DebuffIcon { Kind = e.Kind, Expiry = e.Expiry, Duration = e.Duration, Stack = 1 };
n++;
}
// Stable order on the plate: by kind.
int shown = Math.Min(n, dst.Length);
for (int i = 1; i < shown; i++)
{
DebuffIcon t = dst[i];
int j = i - 1;
while (j >= 0 && dst[j].Kind > t.Kind) { dst[j + 1] = dst[j]; j--; }
dst[j + 1] = t;
}
return n;
}
}
/// <summary>Tracked debuff entries (all monsters) and monsters carrying the "others" marker.</summary>
public static void Count(out int entries, out int monsters, out int othersMarked)
{
long now = Stopwatch.GetTimestamp();
entries = monsters = 0;
lock (Sync)
{
foreach (List<Entry> list in ByMonster.Values)
{
int live = 0;
foreach (Entry e in list) if (e.Expiry > now) live++;
entries += live;
if (live > 0) monsters++;
}
othersMarked = Others.Count;
}
}
public static string Describe()
{
Count(out int entries, out int monsters, out int others);
lock (Sync)
return $"Debuffs: {entries} tracked on {monsters} monster(s), {others} with others' marker; " +
$"{_recorded} recorded, {_resisted} resisted, {_ambiguous} ambiguous this session; last: {_lastEvent}. " +
$"Spell table: {PortalSpellTable.Status}.";
}
// ── Categories ───────────────────────────────────────────────────────
/// <summary>AC spell category (ACE SpellCategory) to the icon it shows.</summary>
internal static DebuffKind KindOf(DebuffSpell s)
{
switch (s.Category)
{
case 110: return DebuffKind.VulnFire;
case 106: return DebuffKind.VulnCold;
case 108: return DebuffKind.VulnLightning;
case 102: return DebuffKind.VulnAcid;
case 114: return DebuffKind.VulnSlash;
case 112: return DebuffKind.VulnPierce;
case 104: return DebuffKind.VulnBludgeon;
case 116: return DebuffKind.Imperil; // ArmorLowering (Imperil)
case 42: return DebuffKind.MagicYield; // MagicDefenseLowering (Magic Yield)
case 38: case 40: return DebuffKind.Defense; // Melee / Missile defense (Vulnerability, Defenselessness)
case 2: case 4: case 6: case 8: case 10: case 12: return DebuffKind.Attributes;
case 80: case 82: case 84: case 94: case 96: case 98: return DebuffKind.Vitals; // max vitals, regen (Fester...)
case 78: return DebuffKind.Movement; // RunLowering (Leaden Feet)
}
if (s.IsDot) return DebuffKind.Dot;
uint c = s.Category;
bool skill = (c >= 18 && c <= 76 && (c & 1) == 0) || c == 206 || c == 217 || c == 219 || c == 220 || c == 594 ||
c == 644 || c == 664 || c == 667 || c == 670 || c == 673 || c == 676 || c == 697;
if (skill) return DebuffKind.Skills;
if (c == 636 || c == 637 || c == 642 || c == 643 || (c >= 410 && c <= 412) || c == 530 || c == 536 || c == 537 ||
c == 618 || c == 619 || c == 631 || (c >= 684 && c <= 687))
return DebuffKind.Dot;
return DebuffKind.Other;
}
/// <summary>Appraisal bits (attribute / vital highlight) a category of the player's own would turn red.</summary>
private static ushort ExplainedBits(uint category) => category switch
{
2 => 0x001, // Strength
4 => 0x002 | 0x040 | 0x080, // Endurance (and the max health / stamina it feeds)
6 => 0x004, // Quickness
8 => 0x008, // Coordination
10 => 0x010, // Focus
12 => 0x020 | 0x100, // Self (and max mana)
80 => 0x040,
82 => 0x080,
84 => 0x100,
_ => 0,
};
}

View file

@ -0,0 +1,232 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/PlayerPlate.cs
// The player's own plate: three thin stacked bars over your head (health red,
// stamina amber, mana blue) in the monster plates' style (edge, shine, the
// chip that drains after a drop); optional "cur/max" in each bar and the
// name above. No name and no numbers by default, to stay compact.
//
// Data: PlayerVitalsHooks.TryGetSnapshot, the buffed values AC's own vital
// bars show, kept on AC's main thread (a lock and a struct copy per frame).
// Position: the player's live pose, projected like the monster plates
// (MonsterHud.Project handles the landblock frame).
//
// First person: when the camera is inside or right at the head, the plate
// would sit in the middle of the screen, so it hides (setting; on by
// default). The head point is still published for the gain text.
//
// Render thread only. Engine-owned statics.
// ============================================================================
using System;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.D3D9;
namespace RynthCore.Engine.ImGuiBackend.Hud;
internal static class PlayerPlate
{
private const float HeadHeight = 2.05f; // metres above the feet (human-sized characters)
private const float FirstPersonDistance = 1.3f; // camera this close to the head = first person
private static readonly uint HealthCol = MonsterHud.C(0xFFE04A4A), StaminaCol = MonsterHud.C(0xFFE8B333),
ManaCol = MonsterHud.C(0xFF3F8FE8), NameCol = MonsterHud.C(0xFFF2E8DC), NumCol = MonsterHud.C(0xFFFFFFFF);
private struct BarState
{
public float Shown, Trail;
public long Hold;
public bool Init;
public uint Cur, Max;
public string? Text;
public long TextKey;
}
private static BarState _hp, _st, _mn;
private static float _alpha;
/// <summary>Where the head is on screen this frame (valid when <see cref="HeadOnScreen"/>).</summary>
public static Vector2 HeadScreen { get; private set; }
public static bool HeadOnScreen { get; private set; }
/// <summary>Top of the drawn plate (or the head point when it isn't drawn): where the gain text starts.</summary>
public static float PlateTop { get; private set; }
/// <summary>The camera is at the head (first person) this frame.</summary>
public static bool FirstPerson { get; private set; }
public static void Reset()
{
_hp = default; _st = default; _mn = default;
_alpha = 0f;
HeadOnScreen = false;
FirstPerson = false;
}
public static void Draw(ref MonsterHud.Frame f)
{
// Head point (AC landblock-local), used by the gain text even when the plate is off.
float hz = f.Pz + HeadHeight + MonsterHudSettings.HeightLift;
FirstPerson = IsFirstPerson(ref f);
HeadOnScreen = MonsterHud.Project(ref f, f.PlayerCell, f.Px, f.Py, hz, out Vector2 head, keepOnScreen: true) &&
head.X > -40 && head.X < f.Display.X + 40 && head.Y > -40 && head.Y < f.Display.Y + 40;
HeadScreen = head;
PlateTop = head.Y;
bool show = MonsterHudSettings.SelfPlate && HeadOnScreen && !(FirstPerson && MonsterHudSettings.SelfHideFirstPerson) &&
PlayerVitalsHooks.TryGetSnapshot(out _);
float kAlpha = 1f - MathF.Exp(-f.Dt * 12f);
_alpha += ((show ? MonsterHudSettings.Opacity : 0f) - _alpha) * kAlpha;
if (!show) { if (_alpha < 0.02f) _alpha = 0f; return; }
if (_alpha < 0.01f) return;
PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot v);
float kBar = 1f - MathF.Exp(-f.Dt * 14f);
Step(ref _hp, v.Health, v.MaxHealth, f.Now, kBar, f.Dt);
Step(ref _st, v.Stamina, v.MaxStamina, f.Now, kBar, f.Dt);
Step(ref _mn, v.Mana, v.MaxMana, f.Now, kBar, f.Dt);
float a = Math.Clamp(_alpha, 0f, 1f);
float k = MonsterHudSettings.Scale * f.UiScale;
bool numbers = MonsterHudSettings.SelfNumbers;
// With numbers on, the bars grow to fit bold, outlined text that reads over any fill.
float barW = MathF.Round((numbers ? 124f : 96f) * k);
float barH = MathF.Round((numbers ? 15f : 5f) * k);
float gap = MathF.Max(2f, MathF.Round(2f * k));
float round = MathF.Max(1f, 1.5f * k);
// Sized from the 11 px bold bake, drawn from the smallest bake at least that big (no blur when scaled up).
float smallSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale);
ImFontPtr small = ImGuiFonts.Sharp(smallSize, bold: true);
ImDrawListPtr dl = f.Dl;
float blockH = 3 * barH + 2 * gap;
float nameH = 0f;
float nameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale);
ImFontPtr nameFont = ImGuiFonts.Sharp(nameSize, bold: true);
if (MonsterHudSettings.SelfName) nameH = nameSize + 3f * k;
// Where the block goes: above the head (default), under the feet, or beside the character.
float left, y;
SelfPlatePosition where = MonsterHudSettings.SelfPosition;
if (where == SelfPlatePosition.Above)
{
left = head.X - barW * 0.5f;
y = head.Y - 4f * k - blockH;
}
else
{
bool feetOk = MonsterHud.Project(ref f, f.PlayerCell, f.Px, f.Py, f.Pz, out Vector2 feet, keepOnScreen: true);
if (!feetOk) feet = new Vector2(head.X, head.Y + 90f * k);
float charH = MathF.Max(20f * k, feet.Y - head.Y);
float midY = head.Y + charH * 0.5f;
float side = MathF.Max(22f * k, charH * 0.28f);
switch (where)
{
case SelfPlatePosition.Below:
left = feet.X - barW * 0.5f;
y = feet.Y + 6f * k + nameH;
break;
case SelfPlatePosition.Left:
left = head.X - side - barW;
y = midY - blockH * 0.5f;
break;
default: // Right
left = head.X + side;
y = midY - blockH * 0.5f;
break;
}
}
if (MonsterHudSettings.KeepOnScreen)
{
left = Math.Clamp(left, 4f, MathF.Max(4f, f.Display.X - barW - 4f));
y = Math.Clamp(y, 4f + nameH, MathF.Max(4f + nameH, f.Display.Y - blockH - 4f));
}
left = MathF.Round(left);
y = MathF.Round(y);
PaintOne(dl, ref _hp, left, y, barW, barH, round, a, HealthCol, numbers, small, smallSize);
PaintOne(dl, ref _st, left, y + barH + gap, barW, barH, round, a, StaminaCol, numbers, small, smallSize);
PaintOne(dl, ref _mn, left, y + 2 * (barH + gap), barW, barH, round, a, ManaCol, numbers, small, smallSize);
float top = y - 1f;
if (MonsterHudSettings.SelfName)
{
string name = PlayerName();
if (name.Length > 0)
{
ImFontPtr font = nameFont;
float size = nameSize;
float w = MonsterHud.TextWidth(font, size, name);
var pos = new Vector2(MathF.Round(left + (barW - w) * 0.5f), MathF.Round(y - 3f * k - size));
MonsterHud.OutlinedText(dl, font, size, pos, a, name);
dl.AddText(font, size, pos, MonsterHud.Mul(NameCol, a), name);
top = pos.Y;
}
}
// Gain text floats above the plate when it's over the head, else above the head itself.
PlateTop = where == SelfPlatePosition.Above ? top : head.Y;
}
/// <summary>The camera at (or inside) the head: AC's first-person view.</summary>
private static bool IsFirstPerson(ref MonsterHud.Frame f)
{
if (!GameMatrixCapture.TryGetCameraPosition(out float cx, out float cy, out float cz)) return false;
if (!MonsterHud.TryOffset(f.FrameCell, f.PlayerCell, out float ox, out float oy)) return false;
// Camera is in D3D axes (x east, y up, z north); the eyes sit about 1.6 m up.
float dx = cx - (f.Px + ox), dy = cy - (f.Pz + 1.6f), dz = cz - (f.Py + oy);
return dx * dx + dy * dy + dz * dz < FirstPersonDistance * FirstPersonDistance;
}
private static void Step(ref BarState b, uint cur, uint max, long now, float kBar, float dt)
{
float ratio = max > 0 ? Math.Clamp((float)cur / max, 0f, 1f) : 0f;
b.Cur = cur; b.Max = max;
if (!b.Init || _alpha <= 0.02f)
{
b.Shown = b.Trail = ratio;
b.Hold = 0;
b.Init = true;
return;
}
MonsterHud.StepBar(ref b.Shown, ref b.Trail, ref b.Hold, ratio, now, kBar, dt);
}
private static void PaintOne(ImDrawListPtr dl, ref BarState b, float left, float top, float w, float h, float round, float a,
uint col, bool numbers, ImFontPtr font, float size)
{
var b0 = new Vector2(left, top);
var b1 = new Vector2(left + w, top + h);
MonsterHud.PaintBar(dl, b0, b1, round, a, b.Shown, b.Trail, col, ticks: false);
if (!numbers || h < 8f || b.Max == 0) return;
long key = ((long)b.Max << 32) | b.Cur;
string? text = b.Text;
if (key != b.TextKey || text == null)
{
b.TextKey = key;
text = b.Text = b.Cur.ToString(CultureInfo.InvariantCulture) + " / " + b.Max.ToString(CultureInfo.InvariantCulture);
}
float tw = MonsterHud.TextWidth(font, size, text);
var pos = new Vector2(MathF.Round(left + (w - tw) * 0.5f), MathF.Round(top + (h - size) * 0.5f));
// A dark band behind the text, then an outline, so it reads over bright and dark fills alike.
dl.AddRectFilled(new Vector2(pos.X - 3f, top + 1f), new Vector2(pos.X + tw + 3f, top + h - 1f), MonsterHud.Mul(0x70000000u, a), 2f);
MonsterHud.OutlinedText(dl, font, size, pos, a, text);
dl.AddText(font, size, pos, MonsterHud.Mul(NumCol, a), text);
}
private static string _name = "";
private static uint _nameOwner;
private static string PlayerName()
{
uint id = ClientHelperHooks.GetPlayerId();
if (id != _nameOwner && ClientObjectHooks.TryGetSnapshotName(id, out string n) && n.Length > 0)
{
_nameOwner = id;
_name = n;
}
return _name;
}
public static string Describe() =>
$"Self plate {(MonsterHudSettings.SelfPlate ? "on" : "off")}" +
(FirstPerson ? " (first person" + (MonsterHudSettings.SelfHideFirstPerson ? ", hidden)." : ").") : ".");
}

View file

@ -0,0 +1,348 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/PortalSpellTable.cs
// The client's spell table (portal dat file 0x0E00000E), read once in the
// background so the nameplates can turn "You cast <spell> on <monster>" into
// a spell id, category, power and duration.
//
// Layout (ACE.DatLoader SpellTable / SpellBase): file id u32, then a
// PackedHashTable (u16 count, u16 buckets) of u32 spell id + SpellBase:
// name, desc: u16 length + nibble-swapped bytes, each padded to 4
// school, icon, category, bitfield, baseMana u32; rangeConst, rangeMod f32;
// power u32; economyMod f32; formulaVersion u32; componentLoss f32;
// metaSpellType u32, metaSpellId u32;
// Enchantment (1) / FellowEnchantment (12): duration f64, degradeMod f32,
// degradeLimit f32; PortalSummon (7): portalLifetime f64;
// 8 x u32 components, casterEffect, targetEffect, fizzleEffect u32,
// recoveryInterval f64, recoveryAmount f32, displayOrder,
// nonComponentTargetType, manaMod u32.
// Bitfield 0x4 = Beneficial, 0x10000 = DamageOverTime (ACE SpellFlags).
//
// Only debuffs are kept (non-beneficial enchantments, ~1,500 of ~6,300),
// plus every spell's icon id (script windows draw spell icons) and name
// (the Inventory panel's item tooltips and the Skills panel's buff lists).
// The dat reader is a minimal port of the on-demand reader in
// RynthSuite/Shared/RynthCore.TerrainData/DatDatabase.cs (header at 0x140,
// B-tree search by id, block chain whose first dword is the next block).
//
// Threads: the load runs on UiBackgroundWriter (never AC's thread); readers
// take a published immutable snapshot. Engine-owned statics only.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using RynthCore.Engine.UI;
namespace RynthCore.Engine.ImGuiBackend.Hud;
/// <summary>One debuff spell from the client's spell table.</summary>
internal sealed class DebuffSpell
{
public uint Id;
public string Name = "";
public uint Category;
public uint Power;
public uint Flags;
public double Duration; // seconds, before caster augmentations
public bool IsDot => (Flags & 0x10000) != 0;
}
internal static class PortalSpellTable
{
private const uint SpellTableFileId = 0x0E00000E;
private const uint FlagBeneficial = 0x4;
private const uint MetaEnchantment = 1, MetaPortalSummon = 7, MetaFellowEnchantment = 12;
private sealed class Table
{
public readonly Dictionary<uint, DebuffSpell> ById = new();
public readonly Dictionary<string, DebuffSpell> ByName = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Every spell's icon (0x06 texture id), for script windows' spell icons.</summary>
public readonly Dictionary<uint, uint> IconById = new();
/// <summary>Every spell's name, for item tooltips (Inventory panel) and buff lists (Skills panel).</summary>
public readonly Dictionary<uint, string> NameById = new();
}
private static readonly object Sync = new();
private static volatile Table? _table;
private static bool _queued;
private static volatile string _status = "not loaded";
/// <summary>True once the table is readable.</summary>
public static bool Ready => _table != null;
public static int Count => _table?.ById.Count ?? 0;
/// <summary>"1,512 debuffs from client_portal.dat" or why not. Any thread.</summary>
public static string Status => _status;
/// <summary>Queues the one-time read off the calling thread. Cheap after the first call.</summary>
public static void EnsureLoadQueued()
{
if (_table != null) return;
lock (Sync)
{
if (_queued) return;
_queued = true;
}
_status = "loading";
UiBackgroundWriter.Enqueue("portal spell table", LoadNow);
}
public static bool TryGetById(uint id, out DebuffSpell spell)
{
Table? t = _table;
if (t != null && t.ById.TryGetValue(id, out DebuffSpell? s)) { spell = s; return true; }
spell = null!;
return false;
}
/// <summary>Any spell's icon (0x06 texture id) once the table is loaded. Any thread.</summary>
public static bool TryGetIcon(uint spellId, out uint icon)
{
Table? t = _table;
if (t != null && t.IconById.TryGetValue(spellId, out icon)) return true;
icon = 0;
return false;
}
/// <summary>Any spell's name once the table is loaded. Any thread.</summary>
public static bool TryGetName(uint spellId, out string name)
{
Table? t = _table;
if (t != null && t.NameById.TryGetValue(spellId, out string? n)) { name = n; return true; }
name = string.Empty;
return false;
}
/// <summary>
/// A debuff by its exact name. Several spells can share a name (monster
/// versions of "Poison", "Slowness"...): the strongest non-self one wins.
/// </summary>
public static bool TryGetByName(string name, out DebuffSpell spell)
{
Table? t = _table;
if (t != null && t.ByName.TryGetValue(name, out DebuffSpell? s)) { spell = s; return true; }
spell = null!;
return false;
}
// ── Load (background) ────────────────────────────────────────────────
private static void LoadNow()
{
try
{
string? path = FindPortalDat();
if (path == null) { _status = "client_portal.dat not found next to acclient.exe"; return; }
byte[]? raw = DatReader.ReadFile(path, SpellTableFileId, out string why);
if (raw == null) { _status = $"{Path.GetFileName(path)}: {why}"; return; }
Table t = Parse(raw, out int total);
_table = t;
_status = $"{t.ById.Count:N0} debuffs of {total:N0} spells from {Path.GetFileName(path)}";
RynthLog.UI($"Nameplates: spell table - {_status}");
}
catch (Exception ex)
{
_status = $"spell table read failed: {ex.GetType().Name}: {ex.Message}";
RynthLog.UI($"Nameplates: {_status}");
}
}
private static string? FindPortalDat()
{
var dirs = new List<string>(2);
try
{
string? exe = Environment.ProcessPath;
string? dir = string.IsNullOrEmpty(exe) ? null : Path.GetDirectoryName(exe);
if (!string.IsNullOrEmpty(dir)) dirs.Add(dir);
}
catch { }
try { dirs.Add(Environment.CurrentDirectory); } catch { }
foreach (string dir in dirs)
foreach (string name in new[] { "client_portal.dat", "portal.dat" })
{
string full = Path.Combine(dir, name);
if (File.Exists(full)) return full;
}
return null;
}
private static Table Parse(byte[] raw, out int total)
{
var t = new Table();
var r = new SpanReader(raw);
r.U32(); // file id
total = r.U16();
r.U16(); // bucket count
for (int i = 0; i < total && r.Ok; i++)
{
uint id = r.U32();
string name = r.ObfuscatedString();
r.ObfuscatedString(); // description
r.U32(); // school
uint icon = r.U32();
uint category = r.U32();
uint flags = r.U32();
r.U32(); // base mana
r.Skip(8); // range constant, range mod
uint power = r.U32();
r.Skip(12); // economy mod, formula version, component loss
uint meta = r.U32();
r.U32(); // meta spell id
double duration = 0;
if (meta == MetaEnchantment || meta == MetaFellowEnchantment)
{
duration = r.F64();
r.Skip(8); // degrade modifier, degrade limit
}
else if (meta == MetaPortalSummon)
{
r.Skip(8);
}
r.Skip(8 * 4 + 12 + 8 + 4 + 12); // components, effects, recovery, display order, target type, mana mod
if (!r.Ok) break;
if (icon != 0) t.IconById[id] = icon;
if (name.Length > 0) t.NameById[id] = name;
if (meta != MetaEnchantment || (flags & FlagBeneficial) != 0 || name.Length == 0) continue;
var s = new DebuffSpell { Id = id, Name = name, Category = category, Power = power, Flags = flags, Duration = duration };
t.ById[id] = s;
if (!t.ByName.TryGetValue(name, out DebuffSpell? prev) || Better(s, prev))
t.ByName[name] = s;
}
return t;
}
/// <summary>Name collisions: prefer a spell cast on others (not SelfTargeted 0x8), then the stronger.</summary>
private static bool Better(DebuffSpell a, DebuffSpell b)
{
bool aSelf = (a.Flags & 0x8) != 0, bSelf = (b.Flags & 0x8) != 0;
if (aSelf != bSelf) return !aSelf;
return a.Power > b.Power;
}
/// <summary>Bounds-checked little-endian reader; Ok turns false on overrun.</summary>
private ref struct SpanReader
{
private readonly ReadOnlySpan<byte> _b;
private int _p;
public bool Ok;
public SpanReader(byte[] b) { _b = b; _p = 0; Ok = true; }
private bool Has(int n)
{
if (Ok && _p + n <= _b.Length) return true;
Ok = false;
return false;
}
public uint U32() { if (!Has(4)) return 0; uint v = BitConverter.ToUInt32(_b.Slice(_p, 4)); _p += 4; return v; }
public ushort U16() { if (!Has(2)) return 0; ushort v = BitConverter.ToUInt16(_b.Slice(_p, 2)); _p += 2; return v; }
public double F64() { if (!Has(8)) return 0; double v = BitConverter.ToDouble(_b.Slice(_p, 8)); _p += 8; return v; }
public void Skip(int n) { if (Has(n)) _p += n; }
/// <summary>u16 length + bytes with nibbles swapped, then aligned to 4 (from the file start, as ACE does).</summary>
public string ObfuscatedString()
{
int n = U16();
if (!Has(n)) return "";
Span<char> chars = n <= 256 ? stackalloc char[n] : new char[n];
for (int i = 0; i < n; i++)
{
byte x = _b[_p + i];
chars[i] = (char)(byte)((x >> 4) | (x << 4)); // Latin-1: byte == code point
}
_p += n;
_p = (_p + 3) & ~3;
return new string(chars);
}
}
/// <summary>Just enough of the dat format to read one file by id.</summary>
private static class DatReader
{
private const int HeaderOffset = 0x140;
private const int Branches = 62, MaxEntries = 61, EntrySize = 24;
private const int NodeSize = 4 * Branches + 4 + EntrySize * MaxEntries; // 1716
private const int MaxDepth = 16;
public static byte[]? ReadFile(string path, uint fileId, out string why)
{
// Read-only, and share everything: AC holds its own handles on the dats.
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess);
Span<byte> hdr = stackalloc byte[36];
fs.Seek(HeaderOffset, SeekOrigin.Begin);
if (!ReadFully(fs, hdr)) { why = "short header"; return null; }
uint blockSize = BitConverter.ToUInt32(hdr.Slice(4, 4));
uint root = BitConverter.ToUInt32(hdr.Slice(32, 4));
if (blockSize <= 4 || blockSize > 65536 || root == 0 || root >= fs.Length) { why = "bad header"; return null; }
uint offset = root;
for (int depth = 0; depth < MaxDepth && offset != 0; depth++)
{
byte[]? node = ReadChain(fs, blockSize, offset, NodeSize);
if (node == null) { why = "unreadable B-tree node"; return null; }
uint count = BitConverter.ToUInt32(node, 4 * Branches);
if (count > MaxEntries) { why = "corrupt B-tree node"; return null; }
int i = 0;
while (i < count && BitConverter.ToUInt32(node, 4 * Branches + 4 + i * EntrySize + 4) < fileId) i++;
if (i < count && BitConverter.ToUInt32(node, 4 * Branches + 4 + i * EntrySize + 4) == fileId)
{
int e = 4 * Branches + 4 + i * EntrySize;
uint fileOffset = BitConverter.ToUInt32(node, e + 8);
uint fileSize = BitConverter.ToUInt32(node, e + 12);
if (fileSize == 0 || fileSize > 64 * 1024 * 1024) { why = "implausible file size"; return null; }
byte[]? data = ReadChain(fs, blockSize, fileOffset, (int)fileSize);
why = data == null ? "unreadable file blocks" : "";
return data;
}
bool leaf = BitConverter.ToUInt32(node, 0) == 0;
if (leaf || i >= Branches) break;
offset = BitConverter.ToUInt32(node, i * 4);
}
why = $"file 0x{fileId:X8} not in the dat";
return null;
}
/// <summary>A block chain: each block starts with the next block's offset (0 = last).</summary>
private static byte[]? ReadChain(FileStream fs, uint blockSize, uint offset, int size)
{
if ((long)offset + 4 > fs.Length) return null;
var buffer = new byte[size];
Span<byte> next = stackalloc byte[4];
fs.Seek(offset, SeekOrigin.Begin);
if (!ReadFully(fs, next)) return null;
uint nextAddr = BitConverter.ToUInt32(next);
int done = 0;
int guard = 0;
while (done < size)
{
int take = Math.Min((int)blockSize - 4, size - done);
if (!ReadFully(fs, buffer.AsSpan(done, take))) return null;
done += take;
if (done >= size) break;
if (nextAddr == 0 || nextAddr >= fs.Length || ++guard > 1_000_000) return null;
fs.Seek(nextAddr, SeekOrigin.Begin);
if (!ReadFully(fs, next)) return null;
nextAddr = BitConverter.ToUInt32(next);
}
return buffer;
}
private static bool ReadFully(FileStream fs, Span<byte> dest)
{
while (dest.Length > 0)
{
int n = fs.Read(dest);
if (n <= 0) return false;
dest = dest.Slice(n);
}
return true;
}
}
}

View file

@ -0,0 +1,951 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/ChatFace.cs
// ImGui face of RynthChat (docked or popped out; the old Avalonia face is
// UI/Panels/RynthChatPanel.cs): channel and custom tabs with unread counts
// (right-click a tab: mark read, rename, delete), Filters (the ChatFilters
// rule editor), the settings gear, search, the coloured scrollback, and the
// input line with Tell and the panel's resize grip beside it.
//
// Scrollback: wrapped lines, heights cached per wrap width and font; only
// the lines in view are drawn. The timestamp is dimmed and the text wraps
// under itself. Lines keep the colour and highlights the rules gave them
// (ChatLine.Route, worked out on the pump - no regex runs here); a line with
// highlights is laid out by hand (LayoutSpans) so each run can take its own
// colour. Drag across lines to copy them (the keyboard stays with the game,
// so copy is mouse-driven). Right-click a line to copy it or to make a rule
// from it: move / copy lines like it to a tab, hide them, colour them. A line
// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go
// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them).
// Follows the newest line until you scroll up.
//
// The input line belongs to ChatModel (UI/Data/ChatData.cs): Win32Backend
// turns the chat keys into ChatModel edits on AC's thread, which is also
// this face's thread. Clicking the box starts typing, like Enter.
//
// The panel has no strip under the body for the resize grip (PanelSpec.
// GripInBody): the input row stops short of the bottom-right corner by
// ImGuiPanelHost.BodyGripReserve and the host draws the grip there.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class ChatFace : IImGuiPanel
{
public const string Title = "Chat";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(460, 300), new Vector2(260, 140), Background: 0, EdgeToEdge: true, GripInBody: true),
() => new ChatFace());
private static readonly uint TabActive = RynthTheme.Argb(0xFF264C59), TabAdd = RynthTheme.Argb(0xFF7AE09A),
InputBg = RynthTheme.Argb(0xFF0A121A), InputBorder = RynthTheme.Argb(0xFF264C59), InputActive = RynthTheme.Argb(0xFFFFD700),
SelBg = RynthTheme.Argb(0x663A6EA5), FlashBg = RynthTheme.Argb(0xE0264C59), TellBg = RynthTheme.Argb(0xFF0E2E3A),
TsColor = RynthTheme.Argb(0xFF6F8397), MentionBg = RynthTheme.Argb(0x33FFC857),
BadgeBg = RynthTheme.Argb(0xFF1F6F7A), BadgeMention = RynthTheme.Argb(0xFFB8860B);
private const float StickThreshold = 24f;
// Visible lines for the current tab + search, with wrapped heights; _lay
// holds the hand layout of lines with highlights (null for plain lines).
private readonly List<ChatLine> _vis = new(512);
private readonly List<float> _h = new(512);
private readonly List<SpanLayout?> _lay = new(512);
private float[] _tops = new float[1];
private int _heightsFrom; // first line whose height needs measuring
private bool _topsDirty = true;
private long _seenLinesVersion = -1, _seenRoutes = -1, _lastId;
private string _seenTab = "", _seenSearch = "";
private float _seenWrap = -1, _seenFont = -1;
private bool _seenTs;
private readonly byte[] _search = new byte[128], _newTab = new byte[64], _mentionWords = new byte[256];
private bool _stick = true;
private float _lastScrollY;
// Height of lines dropped off the top (the buffer is full) while not following the
// tail: the view is moved up by as much, so the lines being read stay put instead of
// sliding away.
private float _droppedAbove;
private float _inputScroll;
// Selection: indices into _vis.
private int _selAnchor = -1, _selEnd = -1;
private bool _selDragging, _selMoved;
private Vector2 _selDown;
private string? _flash;
private double _flashUntil;
// Unread lines per tab since it was last on screen (Id of the newest line seen there).
private readonly Dictionary<string, long> _seenId = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, (int Count, bool Mention)> _unread = new(StringComparer.OrdinalIgnoreCase);
private long _unreadLines = -1, _unreadRoutes = -1, _unreadTabsVersion = -1;
private string _unreadTab = "";
private bool _openSettings, _openNewTab, _focusNewTab, _openTabMenu, _openLineMenu, _openRename;
private string? _ctxTab, _renameFrom;
private ChatLine? _ctxLine;
private string _ctxPattern = "";
// Map coordinates in the right-clicked line (ChatCoords, found when the menu opens):
// its menu offers "Arrow to" / "Go to" them, through RynthNav.
private List<ChatCoord> _ctxCoords = new();
/// <summary>A Move/Copy rule waiting for the New tab popup to name its tab.</summary>
private ChatFilterRule? _pendingRule;
public bool ClickThrough => ChatModel.CtrlGatedClickThrough && !ImGuiNET.ImGui.GetIO().KeyCtrl;
/// <summary>New lines arrive a few times a second at most; popped out and idle, 5 Hz is plenty.</summary>
public int PopOutIdleHz => 5;
public void OnShown()
{
ChatModel.EnsureSettingsLoaded();
UiSources.Chat.Subscribe();
UiSources.Chat.RequestRefresh();
ChatModel.SetShown(true);
_stick = true;
_seenRoutes = -1; // full rebuild on the first frame
_seenId.Clear(); // every tab starts read
_unreadLines = -1;
}
public void OnHidden()
{
ChatModel.SetShown(false);
UiSources.Chat.Unsubscribe();
}
public void Draw()
{
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
uint bg = RynthTheme.Argb(((uint)Math.Clamp(ChatModel.BackgroundAlpha, 0, 255) << 24) | 0x0A121A);
dl.AddRectFilled(origin, origin + size, bg, 4);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4));
float x0 = origin.X + 4, w = size.X - 8;
var snap = UiSources.Chat.Current;
ChatLine[] lines = snap?.Value ?? Array.Empty<ChatLine>();
string tab = ChatModel.CurrentTab();
UpdateUnread(lines, snap?.Version ?? -1, tab);
float y = DrawTabStrip(new Vector2(x0, origin.Y + 4), w);
DrawSearch(new Vector2(x0, y), w);
y += 26;
SyncLines(snap, lines, tab);
// Scrollback, then the input row along the bottom; the grip takes its
// bottom-right corner (ImGuiPanelHost.BodyGripReserve).
const float inputH = 22, bottomPad = 2;
float reserve = ImGuiPanelHost.BodyGripReserve;
float inputY = origin.Y + size.Y - bottomPad - inputH;
float listH = Math.Max(20, inputY - 4 - y);
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y));
DrawLines(new Vector2(w, listH));
float inputRight = reserve > 0 ? origin.X + size.X - reserve - 3 : x0 + w;
DrawInput(new Vector2(x0, inputY), inputRight - x0, inputH);
ImGuiNET.ImGui.PopStyleVar();
DrawPopups();
ImGuiNET.ImGui.PopFont();
}
// ── Tabs ─────────────────────────────────────────────────────────────
private const string SearchHint = PhosphorIcons.MagnifyingGlass + " Search…";
private const string FiltersLabel = PhosphorIcons.Funnel + " Filters";
/// <summary>Tabs wrap left of Filters and the settings gear. Returns the y below the strip.</summary>
private float DrawTabStrip(Vector2 start, float w)
{
const float h = 20;
float gearW = 22, filtW = ButtonWidth(FiltersLabel) - 4;
float right = start.X + w;
if (IconButton("##chat_gear", PhosphorIcons.Gear, new Vector2(right - gearW, start.Y), new Vector2(gearW, h), Text, BtnFill))
_openSettings = true;
ImGuiNET.ImGui.SetItemTooltip("Chat settings");
if (Button("##chat_filters", FiltersLabel, new Vector2(right - gearW - 3 - filtW, start.Y), new Vector2(filtW, h), Text, BtnFill))
PanelRouter.Toggle("ChatFilters");
ImGuiNET.ImGui.SetItemTooltip("Rules: move, copy or hide lines by regex, and colour them");
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float stripRight = right - gearW - filtW - 8;
float x = start.X, y = start.Y;
string current = ChatModel.CurrentTab();
foreach (string tab in ChatModel.AllTabs())
{
bool custom = !ChatModel.IsBaseTab(tab);
bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase);
_unread.TryGetValue(tab, out var unread);
string? badge = !active && unread.Count > 0 ? (unread.Count > 99 ? "99+" : unread.Count.ToString()) : null;
float badgeW = 0;
if (badge != null)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
badgeW = ImGuiNET.ImGui.CalcTextSize(badge).X + 8;
ImGuiNET.ImGui.PopFont();
}
float textW = ImGuiNET.ImGui.CalcTextSize(tab).X;
// No inline delete button on custom tabs: right-click → Delete tab does it and
// the red X cost a tab's worth of strip width (2026-09-30).
float bw = textW + 12 + (badge != null ? badgeW + 3 : 0), extra = 0;
if (x > start.X && x + bw + extra > stripRight) { x = start.X; y += h + 2; }
ImGuiNET.ImGui.PushID(tab);
var p = new Vector2(x, y);
if (Button("##tab", "", p, new Vector2(bw, h), Text, active ? TabActive : BtnFill))
ChatModel.SelectTab(tab);
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _ctxTab = tab; _openTabMenu = true; }
if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here");
else if (custom) ImGuiNET.ImGui.SetItemTooltip("Right-click to rename or delete this tab");
float ty = y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.AddText(new Vector2(x + 6, ty), Text, tab);
if (badge != null)
{
var b0 = new Vector2(x + 6 + textW + 3, y + 4);
dl.AddRectFilled(b0, b0 + new Vector2(badgeW, h - 8), unread.Mention ? BadgeMention : BadgeBg, (h - 8) * 0.5f);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
dl.AddText(b0 + new Vector2(4, (h - 8 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, badge);
ImGuiNET.ImGui.PopFont();
}
ImGuiNET.ImGui.PopID();
x += bw + extra + 2;
}
if (x > start.X && x + 18 > stripRight) { x = start.X; y += h + 2; }
if (IconButton("##chat_addtab", PhosphorIcons.Plus, new Vector2(x, y), new Vector2(18, h), TabAdd, BtnFill, font: UiFont.Ui11))
{
_pendingRule = null;
WriteUtf8(_newTab, "");
_openNewTab = _focusNewTab = true;
}
ImGuiNET.ImGui.SetItemTooltip("New tab (fill it with a rule: right-click a line, or Filters)");
return y + h + 4;
}
/// <summary>
/// Unread counts per tab: lines shown there that arrived after it was last on
/// screen. Recounted only when the lines, the routes or the tabs change.
/// </summary>
private void UpdateUnread(ChatLine[] lines, long linesVersion, string current)
{
long newest = lines.Length > 0 ? lines[^1].Id : 0;
_seenId[current] = newest;
long routes = ChatModel.RoutesVersion, tabsVersion = ChatModel.FiltersVersion;
if (linesVersion == _unreadLines && routes == _unreadRoutes && tabsVersion == _unreadTabsVersion
&& string.Equals(current, _unreadTab, StringComparison.Ordinal)) return;
_unreadLines = linesVersion;
_unreadRoutes = routes;
_unreadTabsVersion = tabsVersion;
_unreadTab = current;
_unread.Clear();
foreach (string tab in ChatModel.AllTabs())
{
if (!_seenId.TryGetValue(tab, out long seen)) { _seenId[tab] = newest; continue; } // a new tab starts read
int count = 0;
bool mention = false;
for (int i = lines.Length - 1; i >= 0 && lines[i].Id > seen; i--)
if (ChatModel.LineInTab(lines[i], tab)) { count++; mention |= lines[i].Route.Mention; }
if (count > 0) _unread[tab] = (count, mention);
}
}
private void DrawSearch(Vector2 p, float w)
{
bool hasText = _search[0] != 0;
TextBox("##chat_search", _search, p, hasText ? w - 24 : w, SearchHint, out _);
if (hasText)
{
if (IconButton("##chat_search_x", PhosphorIcons.X, new Vector2(p.X + w - 22, p.Y), new Vector2(22, 22), Mute, BtnFill, font: UiFont.Ui10))
WriteUtf8(_search, "");
ImGuiNET.ImGui.SetItemTooltip("Clear the search");
}
}
// ── Lines ────────────────────────────────────────────────────────────
/// <summary>Brings _vis up to date with the snapshot, tab, search and routes.</summary>
private void SyncLines(UiSnapshot<ChatLine[]>? snap, ChatLine[] lines, string tab)
{
string search = Utf8(_search);
long routes = ChatModel.RoutesVersion;
if (routes != _seenRoutes || tab != _seenTab || search != _seenSearch)
{
_seenRoutes = routes;
_seenTab = tab;
_seenSearch = search;
_seenLinesVersion = snap?.Version ?? -1;
_vis.Clear();
_h.Clear();
_lay.Clear();
foreach (ChatLine line in lines)
if (ChatModel.LineVisible(line, tab, search)) { _vis.Add(line); _h.Add(0); _lay.Add(null); }
_lastId = lines.Length > 0 ? lines[^1].Id : _lastId;
_heightsFrom = 0;
_topsDirty = true;
ClearSelection();
_stick = true; // a rebuild re-pins to the newest line
_droppedAbove = 0f;
return;
}
if (snap == null || snap.Version == _seenLinesVersion) return;
_seenLinesVersion = snap.Version;
// Drop lines the source no longer keeps, then add the new ones.
long oldest = lines.Length > 0 ? lines[0].Id : long.MaxValue;
int drop = 0;
while (drop < _vis.Count && _vis[drop].Id < oldest) drop++;
if (drop > 0 && !_selDragging)
{
if (!Following)
for (int i = 0; i < drop; i++) _droppedAbove += _h[i];
_vis.RemoveRange(0, drop);
_h.RemoveRange(0, drop);
_lay.RemoveRange(0, drop);
_heightsFrom = Math.Max(0, _heightsFrom - drop);
if (_selAnchor >= 0) { _selAnchor -= drop; _selEnd -= drop; if (_selAnchor < 0 || _selEnd < 0) ClearSelection(); }
_topsDirty = true;
}
foreach (ChatLine line in lines)
{
if (line.Id <= _lastId) continue;
_lastId = line.Id;
if (!ChatModel.LineVisible(line, tab, search)) continue;
if (_heightsFrom > _vis.Count) _heightsFrom = _vis.Count;
_vis.Add(line);
_h.Add(0);
_lay.Add(null);
_topsDirty = true;
}
}
/// <summary>The view follows the newest line (auto-scroll on and not scrolled away).</summary>
private bool Following => ChatModel.AutoScroll && _stick;
private void DrawLines(Vector2 size)
{
// Lines left the top of a full buffer while not following: scroll up by as much
// in THIS frame's BeginChild. (SetScrollY only lands in the next frame's Begin,
// after this frame has drawn the shortened list at the old scroll - the text
// jumped up for a frame and a strip at the bottom went blank, several times a
// second in busy chat.) A frame with wheel input waits a frame: this would
// override the wheel's own scroll.
bool compensated = false;
if (_droppedAbove > 0f)
{
if (Following) _droppedAbove = 0f;
else if (ImGuiNET.ImGui.GetIO().MouseWheel == 0f)
{
ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, Math.Max(0f, _lastScrollY - _droppedAbove)));
_droppedAbove = 0f;
compensated = true;
}
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ScrollbarBg, 0u);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0, 0));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, 10f);
bool open = ImGuiNET.ImGui.BeginChild("##chat_lines", size, ImGuiChildFlags.None, ImGuiWindowFlags.AlwaysVerticalScrollbar);
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) { ImGuiNET.ImGui.EndChild(); return; }
float fontSize = ChatModel.FontSize;
ImFontPtr font = ImGuiFonts.Chat(fontSize);
ImGuiNET.ImGui.PushFont(font);
bool showTs = ChatModel.ShowTimestamps;
float wrapW = Math.Max(20, ImGuiNET.ImGui.GetContentRegionAvail().X - 6);
// The text starts after the timestamp and wraps under itself.
float tsW = showTs ? ImGuiNET.ImGui.CalcTextSize("00:00:00 ").X : 0;
float textW = Math.Max(20, wrapW - tsW);
if (wrapW != _seenWrap || fontSize != _seenFont || showTs != _seenTs)
{
_seenWrap = wrapW;
_seenFont = fontSize;
_seenTs = showTs;
_heightsFrom = 0;
}
if (_heightsFrom < _vis.Count)
{
for (int i = _heightsFrom; i < _vis.Count; i++)
{
ChatLine line = _vis[i];
ChatSpan[]? spans = line.Route.Spans;
if (spans != null)
{
SpanLayout lay = LayoutSpans(font, line.Text, spans, textW);
_lay[i] = lay;
_h[i] = lay.Height;
}
else
{
_lay[i] = null;
_h[i] = ImGuiNET.ImGui.CalcTextSize(line.Text, false, textW).Y;
}
}
_heightsFrom = _vis.Count;
_topsDirty = true;
}
if (_topsDirty)
{
if (_tops.Length < _vis.Count + 1) _tops = new float[Math.Max(_vis.Count + 1, _tops.Length * 2)];
_tops[0] = 0;
for (int i = 0; i < _vis.Count; i++) _tops[i + 1] = _tops[i] + _h[i];
_topsDirty = false;
}
int n = _vis.Count;
float total = _tops[n];
// Following the tail until the user scrolls away from it.
float scrollY = ImGuiNET.ImGui.GetScrollY(), maxY = ImGuiNET.ImGui.GetScrollMaxY();
if (compensated) _lastScrollY = scrollY; // our move, not the user's
// Wheel up over the chat stops following at once; reaching the bottom again resumes it.
// Not while it has nothing to scroll: no scroll change would ever turn following back on.
if (maxY > 0f && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.GetIO().MouseWheel > 0f)
_stick = false;
else if (Math.Abs(scrollY - _lastScrollY) > 0.5f)
_stick = scrollY >= maxY - StickThreshold;
Vector2 basePos = ImGuiNET.ImGui.GetCursorScreenPos();
float viewH = ImGuiNET.ImGui.GetWindowHeight();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
int first = FirstAtOrBelow(scrollY, n);
int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd);
for (int i = first; i < n && _tops[i] < scrollY + viewH; i++)
{
Vector2 p = basePos + new Vector2(0, _tops[i]);
ChatLine line = _vis[i];
ChatRoute route = line.Route;
if (route.Mention)
dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), MentionBg);
if (lo >= 0 && i >= lo && i <= hi)
dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), SelBg);
uint col = RynthTheme.Argb(ChatModel.LineArgb(line));
if (showTs) dl.AddText(font, font.FontSize, p + new Vector2(3, 0), TsColor, line.Timestamp);
Vector2 tp = p + new Vector2(3 + tsW, 0);
SpanLayout? lay = _lay[i];
if (lay == null)
dl.AddText(font, font.FontSize, tp, col, line.Text, textW);
else
foreach (Seg seg in lay.Segs)
dl.AddText(font, font.FontSize, tp + seg.Offset, seg.Argb == 0 ? col : RynthTheme.Argb(seg.Argb), seg.Text);
}
ImGuiNET.ImGui.Dummy(new Vector2(wrapW, Math.Max(1, total)));
HandleSelection(basePos, wrapW, scrollY, viewH, n);
HandleLineMenu(basePos, wrapW, n);
_lastScrollY = scrollY;
if (ChatModel.AutoScroll && _stick && !_selDragging && total > viewH)
ImGuiNET.ImGui.SetScrollHereY(1f);
// "Copied N lines" / "Rule added", top-right, for a moment.
if (_flash != null)
{
if (ImGuiNET.ImGui.GetTime() > _flashUntil) _flash = null;
else
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_flash);
Vector2 wp = ImGuiNET.ImGui.GetWindowPos();
Vector2 fp = new(Math.Max(wp.X + 2, wp.X + wrapW - ts.X - 12), wp.Y + 4);
dl.AddRectFilled(fp, fp + ts + new Vector2(12, 4), FlashBg, 3);
dl.AddText(fp + new Vector2(6, 2), Text, _flash);
ImGuiNET.ImGui.PopFont();
}
}
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.EndChild();
}
private void Flash(string message, double seconds = 2.0)
{
_flash = message;
_flashUntil = ImGuiNET.ImGui.GetTime() + seconds;
}
// ── Highlighted lines: hand layout ───────────────────────────────────
private readonly record struct Seg(string Text, Vector2 Offset, uint Argb); // Argb 0 = the line's colour
private sealed class SpanLayout
{
public required float Height;
public required Seg[] Segs;
}
/// <summary>
/// Word-wraps <paramref name="text"/> to <paramref name="wrapW"/> and cuts each
/// row where a highlight starts or ends, so every run is drawn in its own
/// colour. Called when a line is measured, never per frame.
/// </summary>
private static SpanLayout LayoutSpans(ImFontPtr font, string text, ChatSpan[] spans, float wrapW)
{
float size = font.FontSize;
float Width(int start, int end) => end <= start ? 0 : font.CalcTextSizeA(size, float.MaxValue, 0f, text[start..end]).X;
// Rows as [start, end) character ranges.
var rows = new List<(int Start, int End)>();
int rowStart = 0;
float x = 0;
int i = 0;
while (i < text.Length)
{
if (text[i] == '\n') { rows.Add((rowStart, i)); rowStart = i + 1; x = 0; i++; continue; }
// A word and the spaces after it.
int j = i;
while (j < text.Length && text[j] != ' ' && text[j] != '\n') j++;
while (j < text.Length && text[j] == ' ') j++;
float ww = Width(i, j);
int wordEnd = j;
while (wordEnd > i && text[wordEnd - 1] == ' ') wordEnd--;
float inkW = Width(i, wordEnd);
if (x > 0 && x + inkW > wrapW)
{
rows.Add((rowStart, i));
rowStart = i;
x = 0;
}
if (x == 0 && inkW > wrapW)
{
// A word wider than the row: break it by characters.
int k = i;
while (k < wordEnd)
{
int m = k + 1;
while (m < wordEnd && Width(k, m + 1) <= wrapW) m++;
if (m < wordEnd) { rows.Add((rowStart, m)); rowStart = m; }
else x = Width(k, j);
k = m;
}
i = j;
continue;
}
x += ww;
i = j;
}
rows.Add((rowStart, text.Length));
var segs = new List<Seg>();
for (int r = 0; r < rows.Count; r++)
{
(int a, int b) = rows[r];
float y = r * size, sx = 0;
int c = a;
foreach (ChatSpan span in spans)
{
int s0 = Math.Max(span.Start, a), s1 = Math.Min(span.Start + span.Length, b);
if (s1 <= s0) continue;
if (s0 > c) { segs.Add(new Seg(text[c..s0], new Vector2(sx, y), 0)); sx += Width(c, s0); }
segs.Add(new Seg(text[s0..s1], new Vector2(sx, y), span.Argb));
sx += Width(s0, s1);
c = s1;
}
if (c < b) segs.Add(new Seg(text[c..b], new Vector2(sx, y), 0));
}
return new SpanLayout { Height = Math.Max(1, rows.Count) * size, Segs = segs.ToArray() };
}
/// <summary>Index of the line containing content y (clamped to the list).</summary>
private int FirstAtOrBelow(float y, int n)
{
int lo = 0, hi = n; // first i with _tops[i + 1] > y
while (lo < hi)
{
int mid = (lo + hi) >> 1;
if (_tops[mid + 1] > y) hi = mid; else lo = mid + 1;
}
return Math.Min(lo, Math.Max(0, n - 1));
}
private void HandleSelection(Vector2 basePos, float wrapW, float scrollY, float viewH, int n)
{
if (n == 0) { ClearSelection(); return; }
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
float contentY = mouse.Y - basePos.Y;
if (!_selDragging)
{
if (!ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)
|| !ImGuiNET.ImGui.IsWindowHovered()
|| mouse.X > basePos.X + wrapW + 6) // the scrollbar
return;
ClearSelection();
if (contentY < 0 || contentY >= _tops[n]) return;
_selAnchor = _selEnd = FirstAtOrBelow(contentY, n);
_selDragging = true;
_selMoved = false;
_selDown = mouse;
return;
}
if (Math.Abs(mouse.X - _selDown.X) > 3 || Math.Abs(mouse.Y - _selDown.Y) > 3) _selMoved = true;
_selEnd = FirstAtOrBelow(Math.Clamp(contentY, 0, _tops[n] - 1), n);
// Dragging past the edges scrolls.
Vector2 wp = ImGuiNET.ImGui.GetWindowPos();
if (mouse.Y < wp.Y) ImGuiNET.ImGui.SetScrollY(Math.Max(0, scrollY - 12));
else if (mouse.Y > wp.Y + viewH) ImGuiNET.ImGui.SetScrollY(scrollY + 12);
if (ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) return;
_selDragging = false;
// A drag (even within one line) copies; a plain click just clears.
if (!_selMoved && _selEnd == _selAnchor) { ClearSelection(); return; }
int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd);
var parts = new List<string>(hi - lo + 1);
for (int i = lo; i <= hi && i < _vis.Count; i++) parts.Add(CopyText(_vis[i]));
Flash(ChatModel.CopyLines(parts), 1.5);
}
private static string CopyText(ChatLine line) => ChatModel.ShowTimestamps ? line.FormattedText : line.Text;
/// <summary>Right-click on a line: its menu (drawn in DrawPopups).</summary>
private void HandleLineMenu(Vector2 basePos, float wrapW, int n)
{
if (n == 0 || _selDragging || !ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right) || !ImGuiNET.ImGui.IsWindowHovered())
return;
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
float contentY = mouse.Y - basePos.Y;
if (mouse.X > basePos.X + wrapW + 6 || contentY < 0 || contentY >= _tops[n]) return;
_ctxLine = _vis[FirstAtOrBelow(contentY, n)];
_ctxPattern = ChatModel.PatternFor(_ctxLine);
_ctxCoords = ImGuiPanelHost.HasFace(RynthNavFace.Title) ? ChatCoords.Find(_ctxLine.Text) : new List<ChatCoord>();
_openLineMenu = true;
}
private void ClearSelection()
{
_selAnchor = _selEnd = -1;
_selDragging = _selMoved = false;
}
// ── Input ────────────────────────────────────────────────────────────
private void DrawInput(Vector2 p, float w, float h)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float tellW = ButtonWidth("Tell");
float boxW = Math.Max(20, w - tellW - 4);
bool typing = Win32Backend.ChatCaptureActive;
ImGuiNET.ImGui.SetCursorScreenPos(p);
if (ImGuiNET.ImGui.InvisibleButton("##chat_input", new Vector2(boxW, h)))
ChatModel.BeginTyping();
if (!typing && ChatHooks.RynthChatOwnsChat) ImGuiNET.ImGui.SetItemTooltip("Click or press Enter to chat");
dl.AddRectFilled(p, p + new Vector2(boxW, h), InputBg, 3);
dl.AddRect(p, p + new Vector2(boxW, h), typing ? InputActive : InputBorder, 3);
string text = ChatModel.InputText;
float fh = ImGuiNET.ImGui.GetFontSize();
float ty = p.Y + (h - fh) * 0.5f;
dl.PushClipRect(p + new Vector2(2, 1), p + new Vector2(boxW - 2, h - 1), true);
if (text.Length == 0 && !typing)
{
_inputScroll = 0;
dl.AddText(new Vector2(p.X + 5, ty), Faded(Mute), ChatModel.InputHint ?? "Press Enter to chat…");
}
else
{
int cursor = Math.Clamp(ChatModel.InputCursor, 0, text.Length);
float caretX = cursor == 0 ? 0 : ImGuiNET.ImGui.CalcTextSize(text[..cursor]).X;
float room = boxW - 12;
if (caretX - _inputScroll > room) _inputScroll = caretX - room;
if (caretX < _inputScroll) _inputScroll = caretX;
float tx = p.X + 5 - _inputScroll;
dl.AddText(new Vector2(tx, ty), Text, text);
if (typing && ImGuiNET.ImGui.GetTime() % 1.0 < 0.6)
dl.AddLine(new Vector2(tx + caretX, ty), new Vector2(tx + caretX, ty + fh), Text);
}
dl.PopClipRect();
if (Button("##chat_tell", "Tell", new Vector2(p.X + boxW + 4, p.Y), new Vector2(tellW, h), Text, TellBg))
Win32Backend.RequestTellSelected();
ImGuiNET.ImGui.SetItemTooltip("Select an NPC or player in the game, then click to start /tell <name>, — or type /tell and press Enter.");
}
// ── Rules from a line ────────────────────────────────────────────────
private void RuleFromLine(ChatRuleAction action, string? tab)
{
var rule = new ChatFilterRule { Pattern = _ctxPattern, Action = action, Tab = tab ?? "" };
if (action == ChatRuleAction.Color)
{
rule.ColorMode = ChatColorMode.Line;
ChatModel.AddRule(rule);
if (!ImGuiPanelHost.IsOpen("ChatFilters")) PanelRouter.Toggle("ChatFilters");
Flash("Rule added - pick its colour in Filters");
return;
}
ChatModel.AddRule(rule);
Flash(action switch
{
ChatRuleAction.Move => $"Rule added: lines like this move to {tab}",
ChatRuleAction.Copy => $"Rule added: lines like this also show in {tab}",
_ => "Rule added: lines like this are hidden (undo in Filters)",
}, 3);
}
private void TabMenu(string id, ChatRuleAction action)
{
if (!ImGuiNET.ImGui.BeginMenu(id)) return;
foreach (string t in ChatModel.TargetTabs())
if (ImGuiNET.ImGui.MenuItem(t)) RuleFromLine(action, t);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("New tab…"))
{
_pendingRule = new ChatFilterRule { Pattern = _ctxPattern, Action = action };
WriteUtf8(_newTab, "");
_openNewTab = _focusNewTab = true;
}
ImGuiNET.ImGui.EndMenu();
}
// ── Popups ───────────────────────────────────────────────────────────
private void DrawPopups()
{
if (_openSettings)
{
_openSettings = false;
WriteUtf8(_mentionWords, ChatModel.MentionWords);
ImGuiNET.ImGui.OpenPopup("##chat_settings");
}
if (_openNewTab) { _openNewTab = false; ImGuiNET.ImGui.OpenPopup("##chat_newtab"); }
if (_openTabMenu) { _openTabMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_tabmenu"); }
if (_openLineMenu) { _openLineMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_linemenu"); }
if (_openRename) { _openRename = false; ImGuiNET.ImGui.OpenPopup("##chat_rename"); }
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, RynthTheme.Argb(0xF2060C14));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, TabActive);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrabActive, Amber);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, TabActive);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
DrawSettingsPopup();
DrawNewTabPopup();
DrawTabMenu();
DrawRenamePopup();
DrawLineMenu();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(8);
}
private void DrawSettingsPopup()
{
if (!ImGuiNET.ImGui.BeginPopup("##chat_settings")) return;
ImGuiNET.ImGui.PushItemWidth(150);
int font = (int)MathF.Round(ChatModel.FontSize);
if (ImGuiNET.ImGui.SliderInt("Font size", ref font, 8, 18)) ChatModel.FontSize = font;
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatModel.SaveSettings();
int pct = (int)MathF.Round(ChatModel.BackgroundAlpha / 2.55f);
if (ImGuiNET.ImGui.SliderInt("Background", ref pct, 0, 100, "%d%%"))
ChatModel.BackgroundAlpha = (int)MathF.Round(pct * 2.55f);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatModel.SaveSettings();
ImGuiNET.ImGui.PopItemWidth();
bool ts = ChatModel.ShowTimestamps;
if (ImGuiNET.ImGui.Checkbox("Timestamps", ref ts))
{
ChatModel.ShowTimestamps = ts;
ChatModel.SaveSettings();
}
bool auto = ChatModel.AutoScroll;
if (ImGuiNET.ImGui.Checkbox("Auto-scroll", ref auto))
{
ChatModel.AutoScroll = auto;
if (auto) _stick = true;
ChatModel.SaveSettings();
}
bool hide = ChatHooks.SuppressOriginalChat;
if (ImGuiNET.ImGui.Checkbox("Hide retail chat (Enter types here)", ref hide))
{
ChatHooks.SuppressOriginalChat = hide;
ChatModel.SaveSettings();
}
ImGuiNET.ImGui.SetItemTooltip("On: the retail chatbox is hidden and Enter types in RynthChat.\n" +
"Off: the retail chatbox is shown and Enter types there; RynthChat keeps showing lines and its Tell button still works.");
bool log = ChatModel.LogEnabled;
if (ImGuiNET.ImGui.Checkbox("Log to file", ref log))
{
ChatModel.LogEnabled = log;
ChatModel.SaveSettings();
}
ImGuiNET.ImGui.SetItemTooltip("%AppData%\\RynthCore\\ChatLogs\\<character>.log");
bool through = ChatModel.CtrlGatedClickThrough;
if (ImGuiNET.ImGui.Checkbox("Click-through (hold Ctrl to interact)", ref through))
ChatModel.SetCtrlGatedClickThrough(through);
ImGuiNET.ImGui.SetItemTooltip("Docked chat only; popped out it's always interactive.\n" +
"On: clicks pass through to the game; hold Ctrl to use the chat.");
ImGuiNET.ImGui.Separator();
bool mention = ChatModel.MentionHighlight;
if (ImGuiNET.ImGui.Checkbox("Highlight my name", ref mention))
{
ChatModel.MentionHighlight = mention;
ChatModel.FiltersChanged(); // re-highlights the kept lines
}
ImGuiNET.ImGui.SetItemTooltip("When another player's chat or channel line says your character's name\n" +
"(or a word below), the name is highlighted, the line tinted and the tab's count turns gold.");
if (mention)
{
Label("Also highlight (comma-separated):", Mute);
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
TextBox("##mention_words", _mentionWords, p, 230, "e.g. Drak, buffs", out _);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
ChatModel.MentionWords = Utf8(_mentionWords).Trim();
ChatModel.FiltersChanged();
}
NextLine(p, 26);
bool sound = ChatModel.MentionSound;
if (ImGuiNET.ImGui.Checkbox("Beep when mentioned", ref sound))
{
ChatModel.MentionSound = sound;
ChatModel.SaveSettings();
}
}
if (!ChatModel.PluginBound) Label("Plugin not bound", Mute);
ImGuiNET.ImGui.EndPopup();
}
private void DrawNewTabPopup()
{
if (!ImGuiNET.ImGui.BeginPopup("##chat_newtab"))
{
_pendingRule = null;
return;
}
if (_pendingRule != null)
Label(_pendingRule.Action == ChatRuleAction.Copy ? "New tab for a copy of lines like this:" : "New tab for lines like this:", Mute);
if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; }
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
bool enter = TextBox("##newtab_name", _newTab, p, 120, "tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20);
bool add = Button("##newtab_add", "Add", new Vector2(p.X + 124, p.Y), new Vector2(ButtonWidth("Add"), 20), Text, TabActive);
bool cancel = Button("##newtab_cancel", "Cancel", new Vector2(p.X + 128 + ButtonWidth("Add"), p.Y), new Vector2(ButtonWidth("Cancel"), 20), Text, BtnFill);
NextLine(p, 20);
if (enter || add)
{
ChatFilterRule? pending = _pendingRule;
string? name = ChatModel.AddCustomTab(Utf8(_newTab), select: pending == null);
if (name != null && pending != null)
{
pending.Tab = name;
ChatModel.AddRule(pending);
Flash(pending.Action == ChatRuleAction.Copy
? $"Rule added: lines like this also show in {name}"
: $"Rule added: lines like this move to {name}", 3);
}
_pendingRule = null;
ImGuiNET.ImGui.CloseCurrentPopup();
}
else if (cancel || ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape))
{
_pendingRule = null;
ImGuiNET.ImGui.CloseCurrentPopup();
}
ImGuiNET.ImGui.EndPopup();
}
private void DrawTabMenu()
{
if (!ImGuiNET.ImGui.BeginPopup("##chat_tabmenu")) return;
string tab = _ctxTab ?? "";
Label(tab, Teal);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Mark as read"))
{
var lines = UiSources.Chat.Current?.Value;
_seenId[tab] = lines is { Length: > 0 } ? lines[^1].Id : 0;
_unread.Remove(tab);
}
if (ImGuiNET.ImGui.MenuItem("Mark all tabs read"))
{
var lines = UiSources.Chat.Current?.Value;
long newest = lines is { Length: > 0 } ? lines[^1].Id : 0;
foreach (string t in ChatModel.AllTabs()) _seenId[t] = newest;
_unread.Clear();
}
if (!ChatModel.IsBaseTab(tab))
{
if (ImGuiNET.ImGui.MenuItem("Rename…"))
{
_renameFrom = tab;
WriteUtf8(_newTab, tab);
_openRename = _focusNewTab = true;
}
if (ImGuiNET.ImGui.MenuItem("Delete tab")) ChatModel.DeleteCustomTab(tab);
}
if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters"))
PanelRouter.Toggle("ChatFilters");
ImGuiNET.ImGui.EndPopup();
}
private void DrawRenamePopup()
{
if (!ImGuiNET.ImGui.BeginPopup("##chat_rename")) return;
Label($"Rename \"{_renameFrom}\" (its rules follow):", Mute);
if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; }
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
bool enter = TextBox("##rename_name", _newTab, p, 140, "tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20);
bool ok = Button("##rename_ok", "Rename", new Vector2(p.X + 144, p.Y), new Vector2(ButtonWidth("Rename"), 20), Text, TabActive);
NextLine(p, 20);
if (enter || ok)
{
if (_renameFrom != null && !ChatModel.RenameCustomTab(_renameFrom, Utf8(_newTab)))
Flash("That name is taken (or blank)");
ImGuiNET.ImGui.CloseCurrentPopup();
}
else if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape))
ImGuiNET.ImGui.CloseCurrentPopup();
ImGuiNET.ImGui.EndPopup();
}
private void DrawLineMenu()
{
ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(200, 0), new Vector2(420, float.MaxValue));
if (!ImGuiNET.ImGui.BeginPopup("##chat_linemenu")) return;
ChatLine? line = _ctxLine;
if (line == null) { ImGuiNET.ImGui.EndPopup(); return; }
// Coordinates in the line: point RynthNav's arrow there, or walk there (left-click
// selects lines, so this lives in the right-click menu).
for (int i = 0; i < _ctxCoords.Count && i < 3; i++)
{
ChatCoord c = _ctxCoords[i];
ImGuiNET.ImGui.PushID(i);
if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.NavigationArrow + " Arrow to " + c.Text))
RynthNavCommands.Arrow(c.Text, c.Ns, c.Ew);
if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Play + " Go to " + c.Text))
RynthNavCommands.Go(c.Text, c.Ns, c.Ew);
ImGuiNET.ImGui.PopID();
}
if (_ctxCoords.Count > 0) ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Copy line")) Flash(ChatModel.CopyLines(new[] { CopyText(line) }), 1.5);
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 400);
ImGuiNET.ImGui.TextUnformatted("Lines like this: " + _ctxPattern);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopStyleColor();
TabMenu("Move them to", ChatRuleAction.Move);
TabMenu("Also show them in", ChatRuleAction.Copy);
if (ImGuiNET.ImGui.MenuItem("Hide them")) RuleFromLine(ChatRuleAction.Hide, null);
if (ImGuiNET.ImGui.MenuItem("Colour them…")) RuleFromLine(ChatRuleAction.Color, null);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters"))
PanelRouter.Toggle("ChatFilters");
ImGuiNET.ImGui.EndPopup();
}
}

View file

@ -0,0 +1,527 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/ChatFiltersFace.cs
// ImGui face of the RynthChat rule editor (the old Avalonia face is
// UI/Panels/RynthChatFiltersPanel.cs). One card per rule:
//
// [#] [on] [regex ..........................] [up] [down] [delete]
// When [Any line v] [Move to v] [Junk v] [Colour line v] [swatch]
// (a regex error, a timed-out rule, a missing tab, or its hit count)
//
// The order and what each action does are spelled out in the header lines
// (and in UI/Data/ChatData.cs). Below the rules: Add, Import / Export (the
// clipboard, JSON), and a test box - paste a line, pick where it came from,
// and see which rules match and where it ends up. The test runs on an edit,
// never per frame; the chat itself is routed on the pump.
//
// The rules live in ChatModel. Each edit applies (the pump re-routes the
// kept lines within 100 ms) and saves at once.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class ChatFiltersFace : IImGuiPanel
{
public const string Title = "ChatFilters";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(600, 460), new Vector2(440, 260), EdgeToEdge: true, GripInBody: true),
() => new ChatFiltersFace());
private static readonly uint AddBg = RynthTheme.Argb(0xFF264C59), CardBg = RynthTheme.Argb(0xFF0E1822),
FocusBorder = RynthTheme.Argb(0xFFFFD700);
private sealed class Buffers
{
public readonly byte[] Pattern = new byte[1024];
public bool Active;
}
private readonly Dictionary<ChatFilterRule, Buffers> _bufs = new();
private long _seenVersion = -1;
private readonly Picker _picker = new("##chatrule_pick");
private string? _flash;
private double _flashUntil;
private ChatFilterRule? _focus;
private double _focusUntil;
private bool _scrollToFocus;
private ChatFilterRule? _newTabFor;
private bool _openNewTab, _focusNewTab;
private readonly byte[] _newTab = new byte[64];
// Test box: re-evaluated when the text, its source or the rules change.
private readonly byte[] _test = new byte[512];
private int _testSource = 1; // index into ChatModel.Conditions (not 0, "any")
private string _testSeen = "";
private int _testSourceSeen = -1;
private long _testVersion = -1;
private readonly List<(string Text, uint Color)> _testResult = new();
public void OnShown() => ChatModel.EnsureSettingsLoaded();
private const string AddLabel = PhosphorIcons.Plus + " Add rule";
private const string ImportLabel = PhosphorIcons.ClipboardText + " Import";
private const string ExportLabel = PhosphorIcons.Copy + " Export";
private const string Caret = " " + PhosphorIcons.CaretDown;
private static readonly string[] ActionLabels = { "Move to", "Copy to", "Hide", "Colour only" };
private static readonly string[] ActionHelp =
{
"Move: the line shows ONLY in the chosen tab (it leaves All and its channel tab).",
"Copy: the line also shows in the chosen tab (it stays where it was).",
"Hide: the line is not shown anywhere (the chat log still has it).",
"Colour only: no routing; the rule just colours.",
};
private static readonly string[] ColorLabels = { "No colour", "Colour line", "Colour match" };
public void Draw()
{
float w = Begin(out Vector2 origin, out Vector2 size);
ChatFilterRule[] rules = ChatModel.Filters;
SyncBuffers(rules);
if (ChatModel.FocusRule is { } focus)
{
ChatModel.FocusRule = null;
_focus = focus;
_focusUntil = ImGuiNET.ImGui.GetTime() + 2.5;
_scrollToFocus = true;
}
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
Label("Rules run top to bottom (" + PhosphorIcons.ArrowUp + PhosphorIcons.ArrowDown + " to reorder) on each line's text, as a case-insensitive regex.", Mute);
Label("Where it shows: Copy rules add a tab and go on; the first Move or Hide that matches decides.", Mute);
Label("Colour: the first \"Colour line\" wins; \"Colour match\" colours every match (a higher rule wins an overlap).", Mute);
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
float testH = TestAreaHeight();
Action? edit = null;
float listH = Math.Max(60, Remaining(origin, size) - 30 - testH);
ImGuiNET.ImGui.BeginChild("##filter_rows", new Vector2(w, listH));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal);
float rowW = ImGuiNET.ImGui.GetContentRegionAvail().X - 2;
for (int i = 0; i < rules.Length; i++)
{
ImGuiNET.ImGui.PushID(i);
DrawRule(rules, i, rowW, ref edit);
ImGuiNET.ImGui.PopID();
}
if (rules.Length == 0)
{
Label("No rules yet. Click \"Add rule\", or right-click a line in the chat", Mute);
Label("and pick \"Move them to\", \"Hide them\" or \"Colour them\".", Mute);
}
ImGuiNET.ImGui.PopStyleColor(2);
ImGuiNET.ImGui.EndChild();
// Add / Import / Export
Vector2 ap = ImGuiNET.ImGui.GetCursorScreenPos();
float bx = ap.X;
if (Button("##add", AddLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(AddLabel) + 4, 24), Text, AddBg))
{
// An empty pattern matches nothing until typed; saved now so the row survives a relaunch mid-edit.
var rule = new ChatFilterRule();
edit = () => ChatModel.AddRule(rule);
}
bx += ButtonWidth(AddLabel) + 8;
if (Button("##import", ImportLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(ImportLabel), 24), Text, BtnFill))
Flash(ChatModel.ImportRules(ChatModel.GetClipboardText()));
ImGuiNET.ImGui.SetItemTooltip("Add the rules on the clipboard (an Export, or a rynthchat_settings.json) after these.");
bx += ButtonWidth(ImportLabel) + 4;
if (Button("##export", ExportLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(ExportLabel), 24), Text, BtnFill, rules.Length > 0))
Flash(ChatModel.SetClipboardText(ChatModel.ExportRules())
? $"Copied {rules.Length} rule{(rules.Length == 1 ? "" : "s")} to the clipboard"
: "Clipboard busy - try again");
ImGuiNET.ImGui.SetItemTooltip("Copy every rule and your tabs to the clipboard as JSON, to share or keep.");
bx += ButtonWidth(ExportLabel) + 8;
if (_flash != null)
{
if (ImGuiNET.ImGui.GetTime() > _flashUntil) _flash = null;
else ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(bx, ap.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Amber, _flash);
}
NextLine(ap, 28);
DrawTest(w);
End(origin, size);
_picker.Draw();
DrawNewTabPopup();
edit?.Invoke(); // after drawing: the rows above drew from the old list
}
private void Flash(string message)
{
_flash = message;
_flashUntil = ImGuiNET.ImGui.GetTime() + 3;
}
// ── One rule ─────────────────────────────────────────────────────────
private void DrawRule(ChatFilterRule[] rules, int i, float rowW, ref Action? edit)
{
ChatFilterRule r = rules[i];
Buffers b = _bufs[r];
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 card = ImGuiNET.ImGui.GetCursorScreenPos();
dl.ChannelsSplit(2);
dl.ChannelsSetCurrent(1);
const float rowH = 22;
// Row 1: number, on, pattern, up, down, delete.
Vector2 p = card + new Vector2(4, 4);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
dl.AddText(new Vector2(p.X, p.Y + 5), Faded(Mute), (i + 1).ToString());
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 16, p.Y + 1));
bool on = r.Enabled;
if (ImGuiNET.ImGui.Checkbox("##on", ref on)) { r.Enabled = on; ChatModel.FiltersChanged(); }
ImGuiNET.ImGui.SetItemTooltip(on ? "Rule on (click to turn off)" : "Rule off (click to turn on)");
const float btn = 22;
float x = p.X + 42;
float patW = Math.Max(80, card.X + rowW - 4 - 3 * (btn + 2) - 4 - x);
if (TextBox("##pat", b.Pattern, new Vector2(x, p.Y), patW, "regex, e.g. ^You have been healed", out bool patActive))
{
r.Pattern = Utf8(b.Pattern);
r.Recompile();
ChatModel.FiltersChanged();
}
b.Active = patActive;
if (r.Invalid && r.Pattern.Length > 0)
dl.AddRect(new Vector2(x, p.Y), new Vector2(x + patW, p.Y + rowH), Red, 3);
else if (r.Slow)
dl.AddRect(new Vector2(x, p.Y), new Vector2(x + patW, p.Y + rowH), Amber, 3);
x += patW + 4;
ChatFilterRule rule = r;
if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x, p.Y), new Vector2(btn, rowH), Text, BtnFill, i > 0))
edit = () => ChatModel.MoveFilter(rule, -1);
ImGuiNET.ImGui.SetItemTooltip("Move up (runs earlier)");
x += btn + 2;
if (IconButton("##down", PhosphorIcons.ArrowDown, new Vector2(x, p.Y), new Vector2(btn, rowH), Text, BtnFill, i < rules.Length - 1))
edit = () => ChatModel.MoveFilter(rule, +1);
ImGuiNET.ImGui.SetItemTooltip("Move down (runs later)");
x += btn + 2;
if (IconButton("##del", PhosphorIcons.Trash, new Vector2(x, p.Y), new Vector2(btn, rowH), Red, BtnFill))
edit = () => ChatModel.EditFilters(list => list.Remove(rule));
ImGuiNET.ImGui.SetItemTooltip("Delete this rule");
// Row 2 (wraps when narrow): When, action, tab, colour mode, swatch.
float left = p.X + 42, right = card.X + rowW - 4;
var flow = new Flow(left, p.Y + rowH + 4, right, rowH);
string whenText = "When: " + ChatModel.ConditionLabel(r.When) + Caret;
Vector2 wp = flow.Place(Math.Min(ButtonWidth(whenText), 240));
if (Button("##when", whenText, wp, new Vector2(Math.Min(ButtonWidth(whenText), 240), rowH), Text, BtnFill, leftAlign: true))
OpenWhenPicker(rule, wp);
ImGuiNET.ImGui.SetItemTooltip("Only lines from this channel or chat type (Any line: every line)");
int action = (int)r.Action;
string actText = ActionLabels[action] + Caret;
Vector2 aPos = flow.Place(ButtonWidth(actText));
if (Button("##act", actText, aPos, new Vector2(ButtonWidth(actText), rowH), Text, BtnFill))
_picker.Open(aPos + new Vector2(0, rowH + 2), ActionLabels, action, k =>
{
rule.Action = (ChatRuleAction)k;
if (rule.Action == ChatRuleAction.Color && rule.ColorMode == ChatColorMode.None) rule.ColorMode = ChatColorMode.Line;
ChatModel.FiltersChanged();
}, 140);
ImGuiNET.ImGui.SetItemTooltip(ActionHelp[action]);
if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy)
{
bool noTab = r.Tab.Length == 0;
string tabText = (noTab ? "pick a tab" : r.Tab) + Caret;
Vector2 tPos = flow.Place(ButtonWidth(tabText));
if (Button("##tab", tabText, tPos, new Vector2(ButtonWidth(tabText), rowH), noTab ? Amber : Teal, BtnFill))
OpenTabPicker(rule, tPos);
ImGuiNET.ImGui.SetItemTooltip("The tab it goes to (pick \"New tab…\" to make one)");
}
if (r.Action != ChatRuleAction.Hide)
{
int mode = (int)r.ColorMode;
string colText = ColorLabels[mode] + Caret;
Vector2 cPos = flow.Place(ButtonWidth(colText));
if (Button("##colmode", colText, cPos, new Vector2(ButtonWidth(colText), rowH), Text, BtnFill))
_picker.Open(cPos + new Vector2(0, rowH + 2), ColorLabels, mode, k =>
{
rule.ColorMode = (ChatColorMode)k;
ChatModel.FiltersChanged();
}, 130);
ImGuiNET.ImGui.SetItemTooltip("Colour line: the whole line. Colour match: just the text the regex matched.");
if (r.ColorMode != ChatColorMode.None)
{
Vector2 sPos = flow.Place(rowH);
ImGuiNET.ImGui.SetCursorScreenPos(sPos + new Vector2(2, 2));
Vector4 v = RynthTheme.Vec(r.ColorArgb);
var rgb = new Vector3(v.X, v.Y, v.Z);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 3));
if (ImGuiNET.ImGui.ColorEdit3("##col", ref rgb, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
{
r.ColorArgb = 0xFF000000
| ((uint)Math.Clamp((int)MathF.Round(rgb.X * 255), 0, 255) << 16)
| ((uint)Math.Clamp((int)MathF.Round(rgb.Y * 255), 0, 255) << 8)
| (uint)Math.Clamp((int)MathF.Round(rgb.Z * 255), 0, 255);
ChatModel.FiltersChanged();
}
ImGuiNET.ImGui.PopStyleVar();
}
}
// Row 3: what's wrong, or what it's doing.
float y = flow.Bottom + 3;
(string? note, uint noteColor) = RuleNote(r);
if (note != null)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
ImGuiNET.ImGui.PushClipRect(new Vector2(left, y), new Vector2(right, y + 40), true);
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(left, y));
ImGuiNET.ImGui.PushTextWrapPos(right - ImGuiNET.ImGui.GetWindowPos().X + ImGuiNET.ImGui.GetScrollX());
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, noteColor);
ImGuiNET.ImGui.TextUnformatted(note);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.PopTextWrapPos();
y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
ImGuiNET.ImGui.PopClipRect();
ImGuiNET.ImGui.PopFont();
}
float bottom = Math.Max(y, flow.Bottom + 2) + 4;
// Card background under everything (channel 0), dimmed while off.
dl.ChannelsSetCurrent(0);
bool focused = ReferenceEquals(r, _focus) && ImGuiNET.ImGui.GetTime() < _focusUntil;
dl.AddRectFilled(card, new Vector2(card.X + rowW, bottom), r.Enabled ? CardBg : RowAlt, 4);
dl.AddRect(card, new Vector2(card.X + rowW, bottom), focused ? FocusBorder : BtnBord, 4);
dl.ChannelsMerge();
if (!r.Enabled)
dl.AddRectFilled(card, new Vector2(card.X + rowW, bottom), RynthTheme.Argb(0x55000000), 4);
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(card.X, bottom));
ImGuiNET.ImGui.Dummy(new Vector2(rowW, 4));
if (_scrollToFocus && ReferenceEquals(r, _focus))
{
_scrollToFocus = false;
ImGuiNET.ImGui.SetScrollHereY(1f); // bring the new rule into view
}
}
private static (string? Note, uint Color) RuleNote(ChatFilterRule r)
{
if (r.Pattern.Length == 0) return ("Type a pattern: the rule matches nothing until then.", Faded(Mute));
if (r.Invalid) return ("Regex error: " + (r.Error ?? "doesn't compile"), Red);
if (r.Slow) return ("Too slow: matching it took too long (see the RynthCore log), so the rule is skipped. Edit the pattern to try again.", Amber);
if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy && r.Tab.Length == 0)
return ("Pick a tab: until then it only colours.", Amber);
if (!r.Enabled) return ("Off.", Faded(Mute));
int hits = System.Threading.Volatile.Read(ref r.Hits);
return (hits == 0 ? "No recent line matches." : $"Matches {hits} recent line{(hits == 1 ? "" : "s")}.", Faded(Mute));
}
/// <summary>Left-to-right placement that wraps to a new row when the next item doesn't fit.</summary>
private struct Flow
{
private readonly float _left, _right, _h;
private float _x, _y;
public Flow(float left, float top, float right, float h) { _left = _x = left; _right = right; _y = top; _h = h; }
public float Bottom => _y + _h;
public Vector2 Place(float w)
{
if (_x > _left && _x + w > _right) { _x = _left; _y += _h + 3; }
var at = new Vector2(_x, _y);
_x += w + 4;
return at;
}
}
private void OpenWhenPicker(ChatFilterRule rule, Vector2 at)
{
var labels = new string[ChatModel.Conditions.Length];
int sel = 0;
for (int k = 0; k < labels.Length; k++)
{
labels[k] = ChatModel.Conditions[k].Label;
if (string.Equals(ChatModel.Conditions[k].Value, rule.When, StringComparison.OrdinalIgnoreCase)) sel = k;
}
_picker.Open(at + new Vector2(0, 24), labels, sel, k =>
{
rule.When = ChatModel.Conditions[k].Value;
ChatModel.FiltersChanged();
}, 260);
}
private void OpenTabPicker(ChatFilterRule rule, Vector2 at)
{
string[] tabs = ChatModel.TargetTabs();
var items = new string[tabs.Length + 1];
Array.Copy(tabs, items, tabs.Length);
items[^1] = PhosphorIcons.Plus + " New tab…";
int sel = Array.FindIndex(tabs, t => string.Equals(t, rule.Tab, StringComparison.OrdinalIgnoreCase));
_picker.Open(at + new Vector2(0, 24), items, sel, k =>
{
if (k == tabs.Length)
{
_newTabFor = rule;
WriteUtf8(_newTab, "");
_openNewTab = _focusNewTab = true;
return;
}
rule.Tab = tabs[k];
ChatModel.FiltersChanged();
}, 180);
}
private void DrawNewTabPopup()
{
if (_openNewTab) { _openNewTab = false; ImGuiNET.ImGui.OpenPopup("##chatrule_newtab"); }
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 6));
bool open = ImGuiNET.ImGui.BeginPopup("##chatrule_newtab");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; }
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
bool enter = TextBox("##ruletab_name", _newTab, p, 140, "new tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20);
bool add = Button("##ruletab_add", "Add", new Vector2(p.X + 144, p.Y), new Vector2(ButtonWidth("Add"), 20), Text, AddBg);
NextLine(p, 20);
if (enter || add)
{
string? name = ChatModel.AddCustomTab(Utf8(_newTab), select: false);
if (name != null && _newTabFor != null)
{
_newTabFor.Tab = name;
ChatModel.FiltersChanged();
}
_newTabFor = null;
ImGuiNET.ImGui.CloseCurrentPopup();
}
else if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape))
ImGuiNET.ImGui.CloseCurrentPopup();
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.EndPopup();
}
// ── Test box ─────────────────────────────────────────────────────────
private float TestAreaHeight()
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
float lh = ImGuiNET.ImGui.GetTextLineHeightWithSpacing();
ImGuiNET.ImGui.PopFont();
return 16 + 26 + Math.Max(1, _testResult.Count) * lh + 4;
}
private void DrawTest(float w)
{
Label("Test a line - paste one from the chat (right-click it, Copy line):", Mute);
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
string srcLabel = "from: " + ChatModel.Conditions[_testSource].Label + Caret;
float srcW = Math.Min(ButtonWidth(srcLabel), 230);
TextBox("##test", _test, p, Math.Max(80, w - srcW - 4), "e.g. Bob tells you, \"hi\"", out _);
var sp = new Vector2(p.X + w - srcW, p.Y);
if (Button("##testsrc", srcLabel, sp, new Vector2(srcW, 22), Text, BtnFill, leftAlign: true))
{
var labels = new string[ChatModel.Conditions.Length - 1];
for (int k = 1; k < ChatModel.Conditions.Length; k++) labels[k - 1] = ChatModel.Conditions[k].Label;
_picker.Open(sp + new Vector2(0, 24), labels, _testSource - 1, k => _testSource = k + 1, 260);
}
ImGuiNET.ImGui.SetItemTooltip("Where the test line came from (for rules with a When)");
NextLine(p, 26);
string text = Utf8(_test);
long version = ChatModel.FiltersVersion;
if (text != _testSeen || _testSource != _testSourceSeen || version != _testVersion)
{
_testSeen = text;
_testSourceSeen = _testSource;
_testVersion = version;
RunTest(text);
}
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
// The result lines reach the body's bottom edge: a long one is cut short of
// the resize grip (GripInBody) instead of running under it.
float grip = ImGuiPanelHost.BodyGripReserve;
if (grip > 0)
{
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.PushClipRect(at, new Vector2(at.X + w - grip, at.Y + 4096), true);
}
foreach ((string line, uint color) in _testResult) Label(line, color);
if (grip > 0) ImGuiNET.ImGui.PopClipRect();
ImGuiNET.ImGui.PopFont();
}
/// <summary>Runs the rules over the test line. On an edit only (UI thread; each regex has its timeout).</summary>
private void RunTest(string text)
{
_testResult.Clear();
text = text.Trim();
// A line copied from the chat starts with its timestamp; the rules never see that.
if (text.Length > 9 && text[2] == ':' && text[5] == ':' && text[8] == ' ' && char.IsDigit(text[0])) text = text[9..];
if (text.Length == 0) { _testResult.Add(("Paste a line to see which rules match and where it goes.", Faded(Mute))); return; }
string when = ChatModel.Conditions[_testSource].Value;
string channel = "Chat";
int type = -1;
if (when.StartsWith("chan:", StringComparison.Ordinal)) channel = when[5..];
else if (when.StartsWith("type:", StringComparison.Ordinal) && int.TryParse(when[5..], out int t))
{
type = t;
channel = ChatModel.ChannelForType(t);
}
if (text.StartsWith("[Rynth", StringComparison.OrdinalIgnoreCase)) channel = "Rynth";
var trace = new List<ChatRouter.Step>();
ChatRoute route = ChatModel.TestRouter().Evaluate(text, channel, type, trace);
foreach (ChatRouter.Step step in trace)
_testResult.Add(((step.Rule < 0 ? "Your name" : $"Rule {step.Rule + 1}") + ": " + step.What, Text));
if (trace.Count == 0) _testResult.Add(("No rule matches.", Faded(Mute)));
string where;
if (route.Hidden) where = "Hidden: shown nowhere.";
else
{
var tabs = new List<string>();
if (route.InHome) { tabs.Add("All"); tabs.Add(channel); }
if (route.Tabs != null) tabs.AddRange(route.Tabs);
where = tabs.Count == 0 ? "Shown nowhere." : "Shows in: " + string.Join(", ", tabs) + ".";
}
uint color = RynthTheme.Argb(route.LineArgb ?? ChatModel.ChannelArgb(channel));
_testResult.Add((where + (route.LineArgb != null ? " (this is its colour)" : ""), route.Hidden ? Faded(Mute) : color));
}
/// <summary>Buffers for each rule; refilled from the rules when another face changed them,
/// except the row being typed in.</summary>
private void SyncBuffers(ChatFilterRule[] rules)
{
long version = ChatModel.FiltersVersion;
bool changed = version != _seenVersion;
_seenVersion = version;
foreach (ChatFilterRule r in rules)
{
if (!_bufs.TryGetValue(r, out Buffers? b))
{
_bufs[r] = b = new Buffers();
WriteUtf8(b.Pattern, r.Pattern);
}
else if (changed && !b.Active)
WriteUtf8(b.Pattern, r.Pattern);
}
if (_bufs.Count > rules.Length)
{
var live = new HashSet<ChatFilterRule>(rules);
foreach (ChatFilterRule gone in new List<ChatFilterRule>(_bufs.Keys))
if (!live.Contains(gone)) _bufs.Remove(gone);
}
}
}

View file

@ -0,0 +1,563 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/DamageDetailFace.cs
// "Monster Detail": everything the Damage panel knows about one monster,
// opened by clicking its name there. The Damage panel keeps only what you
// set and sort by; the numbers behind it live here:
// header HP (and where it came from), seconds per kill, hit rate
// Weak to all eight elements as damage taken (1.0 = full) + source
// Accuracy per weapon: hits, misses, hit %, seconds per kill
// Damage per weapon / element / spell tier: avg, crit, non-crit,
// crit rate, casts per kill, kills
// Summons kills and seconds per kill per summon element (and none)
// Damage taken per element: hits, average, biggest
// Rule priority, damage type, extra vuln, match expression, spell
// shapes (debuffs: the Damage panel's caret)
// "Default" shows only Rule: the settings every monster on Default uses.
// A name rule (wcid 0 + a rule name, from the Damage panel's Name rules,
// e.g. "Olthoi") shows only Rule, plus its debuffs, off hand, pet, rename
// and delete: it has no row in the Damage panel to hold them.
//
// Data: UiSources.MonsterDetail (the selected wcid) and MonsterRules; edits
// go through DamageCommands on the pump thread. No Avalonia twin; pops out as ImGui.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Text;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
using Rule = RynthCore.Engine.UI.Panels.MonstersPanel.Rule;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class DamageDetailFace : IImGuiPanel
{
public const string Title = "Monster Detail";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(560, 620), new Vector2(360, 240)),
() => new DamageDetailFace());
private static string _selectedName = "";
/// <summary>
/// Shows <paramref name="wcid"/> in the Monster Detail panel, opening it. wcid 0 shows a
/// rule only: <paramref name="name"/>'s (a name rule, or a monster not met yet), or the
/// Default settings when the name is empty or "Default".
/// </summary>
public static void Show(uint wcid, string name)
{
_selectedName = wcid == 0 && (string.IsNullOrWhiteSpace(name) || IsDefaultName(name)) ? "Default" : name;
MonsterDetailSource.SelectedWcid = wcid;
_showCount++;
UiSources.MonsterDetail.RequestRefresh();
ImGuiPanelHost.Open(Title);
}
private static uint C(uint argb) => RynthTheme.Argb(argb);
private static readonly uint Teal = C(0xFF26D9E6), Gold = C(0xFFFFD16A), Dim = C(0xFFC8D4E0), White = C(0xFFF2F7FC),
EntryBg = C(0xFF16283A), EntryBorder = C(0xFF34587A), ToggleOn = C(0xFF33CC66), ToggleOff = C(0xFF4D4D4D),
BarBg = C(0xFF16222E), Good = C(0xFF33CC66), Mid = C(0xFFE8B333), Bad = C(0xFFE05A5A), DeleteBg = C(0xFF6E1E1E),
DeleteBorder = C(0xFFFF8A8A);
private MonsterDetail? _detail;
private long _seenVersion = -1, _seenRulesVersion = -1;
private MonsterRulesSnapshot? _rules;
private bool _confirmRemove;
private static int _showCount;
private int _seenShow = -1;
// The Rule section's edit boxes: whose rule they hold, the saved values they were
// last loaded from, and whether one is being typed in.
private string _bufFor = "";
private int _prioSeen = int.MinValue;
private string? _exprSeen;
private bool _prioActive, _exprActive;
private readonly byte[] _prioBuf = new byte[12], _exprBuf = new byte[512], _renameBuf = new byte[128];
private string? _renaming; // a rename just sent: "Loading…" until the rule comes back under it
public void OnShown()
{
UiSources.MonsterDetail.Subscribe();
UiSources.MonsterRules.Subscribe();
UiSources.MonsterDetail.RequestRefresh();
UiSources.MonsterRules.RequestRefresh();
}
public void OnHidden()
{
UiSources.MonsterDetail.Unsubscribe();
UiSources.MonsterRules.Unsubscribe();
}
public void Draw()
{
var snap = UiSources.MonsterDetail.Current;
if (snap != null && snap.Version != _seenVersion) { _seenVersion = snap.Version; _detail = snap.Value; }
var rules = UiSources.MonsterRules.Current;
if (rules != null && rules.Version != _seenRulesVersion) { _seenRulesVersion = rules.Version; _rules = rules.Value; }
if (_seenShow != _showCount) { _seenShow = _showCount; _confirmRemove = false; } // another monster: no stale confirm
uint wcid = MonsterDetailSource.SelectedWcid;
bool isDefault = wcid == 0 && IsDefaultName(_selectedName);
bool nameRule = wcid == 0 && !isDefault;
MonsterDetail? d = _detail != null && _detail.Wcid == wcid && wcid != 0 ? _detail : null;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4));
// ── Header ───────────────────────────────────────────────────────
string name = d != null && d.Name.Length > 0 ? d.Name : _selectedName;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
ImGuiNET.ImGui.TextColored(Vec(Teal), isDefault ? "DEFAULT" : name);
ImGuiNET.ImGui.PopFont();
if (isDefault)
{
ImGuiNET.ImGui.TextColored(Vec(Dim), "The spell settings every monster set to Default uses.");
}
else if (nameRule)
{
NameRuleHeader(name);
}
else if (d == null)
{
ImGuiNET.ImGui.TextColored(Vec(Dim), _detail != null && !_detail.Bound ? "Waiting for RynthAi…" : "Loading…");
}
else
{
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.TextColored(Vec(Dim), "wcid " + wcid.ToString(CultureInfo.InvariantCulture));
// Aelrynth only: which difficulty tier these numbers are (the Damage panel's chip picks it).
if (UiSources.Damage.Current?.Value.Tier is { Show: true } tier)
{
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.TextColored(Vec(tier.View == tier.Current ? Teal : Gold),
tier.View <= 0 ? "· Tier 0 (real Dereth)" : "· Tier " + tier.View.ToString(CultureInfo.InvariantCulture));
ImGuiNET.ImGui.SetItemTooltip("HP, casts to kill, seconds per kill, hits and damage taken are this difficulty tier's.\n" +
"Damage per cast and weaknesses are the same at every tier. Change it on the Damage panel.");
}
string hp = d.Hp > 0 ? $"HP {d.Hp:N0} ({d.HpSrc})" : "HP unknown";
string sec = d.SecKill > 0 ? $"{d.SecKill:0.0} s per kill" : "no timed kills yet";
string hit = d.HitRate >= 0 ? $"{d.HitRate * 100:0}% hits" : "no hits yet";
ImGuiNET.ImGui.TextColored(Vec(White), $"{hp} · {sec} · {hit}");
float bw = ImGuiNET.ImGui.CalcTextSize(RemoveLabel).X + 16;
ImGuiNET.ImGui.SameLine();
float room = ImGuiNET.ImGui.GetContentRegionAvail().X;
if (room > bw) ImGuiNET.ImGui.SetCursorPosX(ImGuiNET.ImGui.GetCursorPosX() + room - bw);
Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos();
if (FaceKit.Button("##remove", RemoveLabel, bp, new Vector2(bw, ImGuiNET.ImGui.GetFrameHeight()), White, DeleteBg, border: DeleteBorder))
_confirmRemove = true;
ImGuiNET.ImGui.SetItemTooltip("Take this monster off the Damage panel: its learned numbers and your settings for it. It comes back if you meet it again.");
if (_confirmRemove)
{
ImGuiNET.ImGui.TextColored(Vec(Gold), "Remove " + name + " and everything learned about it?");
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Remove##yes"))
{
DamageCommands.RemoveMonster(wcid);
_confirmRemove = false;
ImGuiPanelHost.Close(Title);
}
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Cancel##no")) _confirmRemove = false;
}
WeakSection(d);
AccuracySection(d);
DamageSection(d);
SummonSection(d);
TakenSection(d);
}
RuleSection(isDefault ? "Default" : name, nameRule);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopFont();
}
private static bool IsDefaultName(string name) => name.Equals("Default", StringComparison.OrdinalIgnoreCase);
// A name rule's header: what it matches, and Delete rule (confirmed).
private void NameRuleHeader(string name)
{
Rule? rule = _rules?.FindRule(name);
if (rule != null) _renaming = null;
ImGuiNET.ImGui.PushTextWrapPos(0);
ImGuiNET.ImGui.TextColored(Vec(Dim), rule == null
? (_rules == null || _renaming == name ? "Loading…" : "There is no rule with this name (deleted?).")
: "A name rule: used for every monster whose name contains \"" + name + "\""
+ (string.IsNullOrWhiteSpace(rule.MatchExpression) ? "" : " and its match expression is true")
+ ", unless a rule higher in the Name rules list matches it first.");
ImGuiNET.ImGui.PopTextWrapPos();
if (rule == null) return;
Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos();
float bw = ImGuiNET.ImGui.CalcTextSize(DeleteRuleLabel).X + 16;
if (FaceKit.Button("##delrule", DeleteRuleLabel, bp, new Vector2(bw, ImGuiNET.ImGui.GetFrameHeight()), White, DeleteBg, border: DeleteBorder))
_confirmRemove = true;
ImGuiNET.ImGui.SetItemTooltip("Delete this rule. Monsters it covered go back to Default (or another rule that matches).");
if (!_confirmRemove) return;
ImGuiNET.ImGui.TextColored(Vec(Gold), "Delete the rule " + name + "?");
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Delete##yes"))
{
DamageCommands.ResetRule(name);
_confirmRemove = false;
ImGuiPanelHost.Close(Title);
}
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Cancel##no")) _confirmRemove = false;
}
// ── Sections ─────────────────────────────────────────────────────────
private static bool Section(string title)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Header, EntryBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, FaceKit.Lighten(EntryBg));
bool open = ImGuiNET.ImGui.CollapsingHeader(title, ImGuiTreeNodeFlags.DefaultOpen);
ImGuiNET.ImGui.PopStyleColor(2);
return open;
}
private static void WeakSection(MonsterDetail d)
{
if (!Section("Weak to")) return;
if (d.Weak.Count == 0)
{
ImGuiNET.ImGui.TextColored(Vec(Dim), "Nothing known yet: not in the server data, no creature type, nothing learned.");
return;
}
ImGuiNET.ImGui.TextColored(Vec(Dim), "Damage it takes from each element (1.0 = full, 0.5 = half), from " + d.WeakSrc + ".");
float labelW = ImGuiNET.ImGui.CalcTextSize("Lightning ").X;
float barW = Math.Max(80, ImGuiNET.ImGui.GetContentRegionAvail().X - labelW - ImGuiNET.ImGui.CalcTextSize(" 0.00x").X - 8);
double top = 1.0;
foreach (var (_, m) in d.Weak) if (m > top) top = m;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float h = ImGuiNET.ImGui.GetTextLineHeight();
foreach (var (e, m) in d.Weak)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
dl.AddText(p, White, e);
Vector2 b0 = p + new Vector2(labelW, 2), b1 = b0 + new Vector2(barW, h - 4);
dl.AddRectFilled(b0, b1, BarBg, 2);
if (m >= 0)
{
float f = (float)Math.Clamp(m / top, 0, 1);
uint col = m >= 1.0 ? Good : m >= 0.6 ? Mid : Bad;
dl.AddRectFilled(b0, b0 + new Vector2(barW * f, h - 4), col, 2);
dl.AddText(new Vector2(b1.X + 6, p.Y), White, m.ToString("0.00", CultureInfo.InvariantCulture) + "x");
}
else
dl.AddText(new Vector2(b1.X + 6, p.Y), Dim, "learned");
ImGuiNET.ImGui.Dummy(new Vector2(labelW + barW + 60, h));
}
}
private static void AccuracySection(MonsterDetail d)
{
if (!Section("Accuracy and speed")) return;
if (d.Weapons.Count == 0) { ImGuiNET.ImGui.TextColored(Vec(Dim), "No attacks recorded yet."); return; }
if (!BeginTable("##acc", "Weapon", "Hit %", "Hits", "Misses", "Sec/Kill", "Timed kills")) return;
foreach (var (w, hits, misses, sec, secN) in d.Weapons)
{
ImGuiNET.ImGui.TableNextRow();
Cell(w);
Cell(hits + misses > 0 ? $"{100.0 * hits / (hits + misses):0}%" : "—");
Cell(hits.ToString(CultureInfo.InvariantCulture));
Cell(misses.ToString(CultureInfo.InvariantCulture));
Cell(sec > 0 ? sec.ToString("0.0", CultureInfo.InvariantCulture) : "—");
Cell(secN.ToString(CultureInfo.InvariantCulture));
}
ImGuiNET.ImGui.EndTable();
}
private static void DamageSection(MonsterDetail d)
{
if (!Section("Damage")) return;
if (d.Casts.Count == 0) { ImGuiNET.ImGui.TextColored(Vec(Dim), "No damage recorded yet."); return; }
if (!BeginTable("##dmg", "Weapon", "Element", "Tier", "Avg", "Crit", "Non-crit", "Crit %", "Casts/Kill", "Kills")) return;
foreach (DetailCast c in d.Casts)
{
ImGuiNET.ImGui.TableNextRow();
Cell(c.Weapon);
Cell(c.Elem);
Cell(DamageSource.FormatTier(c.Tier));
Cell(c.Hits > 0 ? c.Avg.ToString("0", CultureInfo.InvariantCulture) : "—");
Cell(c.CritN > 0 ? c.Crit.ToString("0", CultureInfo.InvariantCulture) : "—");
Cell(c.NonCritN > 0 ? c.NonCrit.ToString("0", CultureInfo.InvariantCulture) : "—");
Cell(c.CritN + c.NonCritN > 0 ? $"{100.0 * c.CritN / (c.CritN + c.NonCritN):0}%" : "—");
Cell(c.Kills > 0 ? c.Casts.ToString("0.00", CultureInfo.InvariantCulture) : "—");
Cell(c.Kills.ToString(CultureInfo.InvariantCulture));
}
ImGuiNET.ImGui.EndTable();
}
private static void SummonSection(MonsterDetail d)
{
if (!Section("Summons")) return;
if (d.Summons.Count == 0)
{
ImGuiNET.ImGui.TextColored(Vec(Dim), "No timed kills yet. (The game doesn't report a summon's own damage, so this compares kill times.)");
return;
}
if (!BeginTable("##pets", "Summon", "Kills", "Sec/Kill")) return;
foreach (var (e, kills, sec) in d.Summons)
{
ImGuiNET.ImGui.TableNextRow();
Cell(e);
Cell(kills.ToString(CultureInfo.InvariantCulture));
Cell(sec > 0 ? sec.ToString("0.0", CultureInfo.InvariantCulture) : "—");
}
ImGuiNET.ImGui.EndTable();
}
private static void TakenSection(MonsterDetail d)
{
if (!Section("Damage taken")) return;
if (d.Taken.Count == 0) { ImGuiNET.ImGui.TextColored(Vec(Dim), "It hasn't hit you yet."); return; }
if (!BeginTable("##taken", "Element", "Hits", "Average", "Biggest")) return;
foreach (var (e, hits, avg, max) in d.Taken)
{
ImGuiNET.ImGui.TableNextRow();
Cell(e);
Cell(hits.ToString(CultureInfo.InvariantCulture));
Cell(avg.ToString("0", CultureInfo.InvariantCulture));
Cell(max.ToString("0", CultureInfo.InvariantCulture));
}
ImGuiNET.ImGui.EndTable();
}
// The rule a monster (or Default, or a name rule) uses: priority, damage type, extra vuln,
// match expression, spell shapes; a name rule also debuffs, off hand, pet and its name.
// A monster following Default gets its own rule (a copy of Default) on the first change.
private void RuleSection(string name, bool nameRule)
{
if (!Section("Rule")) return;
if (_rules == null || _rules.Parsed.Rules.Count == 0)
{
ImGuiNET.ImGui.TextColored(Vec(Dim), "Monster rules not loaded yet.");
return;
}
bool isDefault = IsDefaultName(name);
Rule? exact = isDefault ? null : _rules.FindRule(name);
if (nameRule && exact == null) return; // deleted: editing would make it again
bool custom = exact != null;
Rule view = isDefault ? _rules.DefaultRule() : exact ?? _rules.DefaultRule();
if (!nameRule)
{
ImGuiNET.ImGui.TextColored(Vec(custom || isDefault ? Gold : Dim),
isDefault ? "Applies to every monster set to Default." : custom ? "Custom settings for this monster." : "Following Default (a change here gives it its own settings).");
ImGuiNET.ImGui.TextColored(Vec(Dim), DebuffsHint);
if (custom)
{
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Back to Default")) DamageCommands.ResetRule(name);
}
}
// The edit boxes reload from the rule when its saved value changes (not every frame,
// so a value just entered stays while the plugin saves it).
if (_bufFor != name)
{
_bufFor = name;
_prioSeen = int.MinValue;
_exprSeen = null;
WriteUtf8(_renameBuf, name);
}
// Priority
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextColored(Vec(Dim), "Priority");
ImGuiNET.ImGui.SameLine();
if (!_prioActive && _prioSeen != view.Priority)
{
WriteUtf8(_prioBuf, view.Priority.ToString(CultureInfo.InvariantCulture));
_prioSeen = view.Priority;
}
ImGuiNET.ImGui.SetNextItemWidth(ImGuiNET.ImGui.CalcTextSize("0000").X + 12);
bool enter = ImGuiNET.ImGui.InputText("##prio", _prioBuf, (uint)_prioBuf.Length,
ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.EnterReturnsTrue);
_prioActive = ImGuiNET.ImGui.IsItemActive();
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
if (int.TryParse(Utf8(_prioBuf).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int prio))
{
if (prio != view.Priority) DamageCommands.EditRule(name, r => r.Priority = prio);
}
else _prioSeen = int.MinValue; // not a number: show the saved value again
}
ImGuiNET.ImGui.SetItemTooltip("Target priority: while a higher-priority monster is in range it is attacked first, always (1 = normal). Enter to save.");
// Damage type and Extra vuln
ImGuiNET.ImGui.SameLine(0, 14);
Combo("Damage", "##dtype", DamageCommands.DamageTypes, string.IsNullOrEmpty(view.DamageType) ? "Auto" : view.DamageType,
pick => DamageCommands.EditRule(name, r => r.DamageType = pick),
"Element for spells and weapons against it. Auto = the one it's weakest to.");
ImGuiNET.ImGui.SameLine(0, 14);
Combo("Extra vuln", "##exvuln", DamageCommands.ExVulnTypes, string.IsNullOrEmpty(view.ExVuln) ? "None" : view.ExVuln,
pick => DamageCommands.EditRule(name, r => r.ExVuln = pick),
"A vulnerability of another element, on top of Vuln (which follows the attack's element).");
// Match expression (Default never matches by name, so it has none)
if (!isDefault)
{
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextColored(Vec(Dim), "Match");
ImGuiNET.ImGui.SameLine();
string expr = view.MatchExpression ?? "";
if (!_exprActive && _exprSeen != expr)
{
WriteUtf8(_exprBuf, expr);
_exprSeen = expr;
}
ImGuiNET.ImGui.SetNextItemWidth(-1);
bool exprEnter = ImGuiNET.ImGui.InputText("##expr", _exprBuf, (uint)_exprBuf.Length, ImGuiInputTextFlags.EnterReturnsTrue);
_exprActive = ImGuiNET.ImGui.IsItemActive();
if (exprEnter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
string typed = Utf8(_exprBuf).Trim();
if (typed != expr) DamageCommands.EditRule(name, r => r.MatchExpression = typed);
}
ImGuiNET.ImGui.SetItemTooltip("Only when this is true as well (empty = by name only). Enter to save.\n" +
"Variables: name, range, typeid, maxhp, metastate, true, false\nExamples: range>5, maxhp>1000");
}
ToggleRow("Shapes", DamageCommands.ShapeDefs, view, name);
string casts = DamageCommands.BaseShapeName(view);
if (casts.Length > 0)
{
ImGuiNET.ImGui.SameLine(0, 10);
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextColored(Vec(Dim), "casts " + casts + (view.UseRing ? ", Ring when enough are near" : ""));
ImGuiNET.ImGui.SetItemTooltip("With several shapes on, the first of Arc, Streak, Blast, Bolt is cast.\n" +
"Ring replaces it when at least Min Ring Targets monsters are within Ring Range (Settings).");
}
if (!nameRule) return;
// A name rule has no Damage panel row: its debuffs, off hand and pet are set here.
ToggleRow("Debuffs", DamageCommands.DebuffDefs, view, name);
int off = view.OffhandId;
string offText = off >= 0 && off < DamageCommands.OffhandModeNames.Length ? DamageCommands.OffhandModeNames[off] : "Item " + unchecked((uint)off);
Combo("Off hand", "##offhand", DamageCommands.OffhandModeNames, offText,
pick => DamageCommands.EditRule(name, r => r.OffhandId = Array.IndexOf(DamageCommands.OffhandModeNames, pick)),
"Off hand against the monsters it covers. Default = the DEFAULT line's.\n" +
"Auto = a listed shield; Shield; Dual wield (needs the skill); None = leave the off hand alone.");
ImGuiNET.ImGui.SameLine(0, 14);
string pet = string.IsNullOrEmpty(view.PetDamage) || view.PetDamage.Equals("PAuto", StringComparison.OrdinalIgnoreCase) ? "Auto" : view.PetDamage;
Combo("Pet", "##pet", PetLabels, pet,
pick => DamageCommands.EditRule(name, r => r.PetDamage = pick == "Auto" ? "PAuto" : pick),
"Summon element against the monsters it covers. Auto = its Damage type, else the DEFAULT line's.");
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextColored(Vec(Dim), "Name");
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.SetNextItemWidth(Math.Min(260, ImGuiNET.ImGui.GetContentRegionAvail().X));
bool renamed = ImGuiNET.ImGui.InputText("##rename", _renameBuf, (uint)_renameBuf.Length, ImGuiInputTextFlags.EnterReturnsTrue);
if (renamed || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
string to = Utf8(_renameBuf).Trim();
if (to.Length > 0 && to != name && !IsDefaultName(to) && (_rules.FindRule(to) == null || to.Equals(name, StringComparison.OrdinalIgnoreCase)))
{
DamageCommands.EditRule(name, r => r.Name = to);
_selectedName = to;
_bufFor = to;
_renaming = to;
}
else WriteUtf8(_renameBuf, name);
}
ImGuiNET.ImGui.SetItemTooltip("The part of a monster's name this rule looks for. Enter to rename.");
}
private static readonly string[] PetLabels =
{ "Auto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
/// <summary>A label and a combo of <paramref name="items"/>; <paramref name="onPick"/> runs when another one is chosen.</summary>
private static void Combo(string label, string id, string[] items, string current, Action<string> onPick, string tip)
{
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextColored(Vec(Dim), label);
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.SetNextItemWidth(ImGuiNET.ImGui.CalcTextSize("Dual wield").X + 34);
if (ImGuiNET.ImGui.BeginCombo(id, current))
{
foreach (string v in items)
if (ImGuiNET.ImGui.Selectable(v, v.Equals(current, StringComparison.OrdinalIgnoreCase))
&& !v.Equals(current, StringComparison.OrdinalIgnoreCase))
onPick(v);
ImGuiNET.ImGui.EndCombo();
}
ImGuiNET.ImGui.SetItemTooltip(tip);
}
private const string RemoveLabel = PhosphorIcons.Trash + " Remove monster";
private const string DeleteRuleLabel = PhosphorIcons.Trash + " Delete rule";
private const string DebuffsHint = "Debuffs are set with the " + PhosphorIcons.CaretDown + " in the Damage panel's Debuffs column.";
private static void ToggleRow(string label, (string Field, string Label, string Tip)[] defs, Rule view, string name)
{
ImGuiNET.ImGui.TextColored(Vec(Dim), label);
float h = ImGuiNET.ImGui.GetFrameHeight();
foreach (var (field, text, tip) in defs)
{
ImGuiNET.ImGui.SameLine();
bool on = view.GetToggle(field);
float tw = ImGuiNET.ImGui.CalcTextSize(text).X;
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var size = new Vector2(tw + h + 8, h);
if (ImGuiNET.ImGui.InvisibleButton("##t_" + field, size))
DamageCommands.EditRule(name, rule => DamageCommands.FlipToggle(rule, field));
bool hot = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.SetItemTooltip(tip);
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + size, hot ? FaceKit.Lighten(EntryBg) : EntryBg, 2);
dl.AddRect(p, p + size, EntryBorder, 2);
float box = h - 8;
dl.AddRectFilled(p + new Vector2(4, 4), p + new Vector2(4 + box, 4 + box), on ? ToggleOn : ToggleOff, 2);
dl.AddText(p + new Vector2(box + 8, (h - ImGuiNET.ImGui.GetTextLineHeight()) * 0.5f), White, text);
}
}
// ── Helpers ──────────────────────────────────────────────────────────
private static bool BeginTable(string id, params string[] headers)
{
if (!ImGuiNET.ImGui.BeginTable(id, headers.Length,
ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.PadOuterX))
return false;
foreach (string h in headers) ImGuiNET.ImGui.TableSetupColumn(h);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Teal);
ImGuiNET.ImGui.TableHeadersRow();
ImGuiNET.ImGui.PopStyleColor();
return true;
}
private static void Cell(string text)
{
ImGuiNET.ImGui.TableNextColumn();
ImGuiNET.ImGui.TextColored(Vec(White), text);
}
private static Vector4 Vec(uint abgr) => ImGuiNET.ImGui.ColorConvertU32ToFloat4(abgr);
private static string Utf8(byte[] buffer)
{
int len = Array.IndexOf(buffer, (byte)0);
return Encoding.UTF8.GetString(buffer, 0, len < 0 ? buffer.Length : len);
}
/// <summary>Writes <paramref name="text"/> NUL-terminated, cut at a character boundary if it doesn't fit.</summary>
private static void WriteUtf8(byte[] buffer, string text)
{
byte[] all = Encoding.UTF8.GetBytes(text);
int n = Math.Min(all.Length, buffer.Length - 1);
while (n > 0 && n < all.Length && (all[n] & 0xC0) == 0x80) n--; // don't split a sequence
Array.Copy(all, buffer, n);
buffer[n] = 0;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,659 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/DungeonMapFace.cs
// The Dungeon Map: a large, pannable map of the current dungeon. It replaces
// RynthAi's plugin-drawn DungeonMapUi window (plugin ImGui rendering is no
// longer called; RYNTHCORE_FORCE_IMGUI only) and is opened from the RynthAi
// dashboard's Map launcher.
//
// Data: UiSources.Radar, the same snapshot the Radar face draws
// (RynthPluginGetRadarSnapshot): every floor's walls and fill strips, the
// visited cells, portal / door / creature markers with labels, the player pose.
// The plugin's D3D9 floor textures are not used; floors are strips and walls
// are lines, drawn without anti-aliasing and culled to the canvas.
//
// Like the plugin window it replaces:
// - toolbar: 1U1D (current floor +-1), F1..Fn floor toggles, All, Here, zoom,
// Follow, Rotate, Reset, Doors, Creatures, opacity; it can be hidden;
// - markers: the radar's kinds (RadarKind); the kinds added 2026-10-04 use the
// radar's shapes and colours (RadarMarkerStyle) and its per-kind show boxes;
// - drag pans (and turns Follow off), the wheel zooms;
// - portals always shown with their destination; doors and creatures optional;
// - hidden while you're outdoors or in portal space, back in the next dungeon
// (the panel stays open; ImGuiPanelHost skips drawing it docked).
// Settings are the engine's (dungeon_map_settings.txt beside radar_settings.txt),
// not RynthAi's per-character Map* fields. Zoom, pan and floor picks last for the
// session, as they did.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class DungeonMapFace : IImGuiPanel
{
public const string Title = "Dungeon Map";
public static void Register()
{
DungeonMapSettingsStore.Load(); // engine init thread: the file read stays off AC's thread
ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true),
() => new DungeonMapFace());
}
// ── Palette (the plugin map's colours, ARGB) ──────────────────────────
private const uint CanvasBgArgb = 0xFF0A121F, ToolbarBgArgb = 0xE00A121A;
private static readonly uint CanvasBorder = C(0xFF334D66), Wall = C(0xFF8CCCFF),
PlayerCol = C(0xFF33FF66), Portal = C(0xFFE673FF), PortalRing = C(0xB3FFBFFF), PortalLabel = C(0xFFFFE0FF),
Door = C(0xFFBF8C40), DoorRing = C(0xB3E6BF80), DoorLabel = C(0xFFF2D9A6),
Monster = C(0xFFFF4033), MonsterRing = C(0xB3FF8C80), Npc = C(0xFFFFD933), NpcRing = C(0xB3FFF28C),
CreatureLabel = C(0xFFFFE6E6), Hint = C(0xFF8FA3B8), ButtonBg = C(0xC0141F29), ButtonBorder = C(0xFF34587A),
FloorOn = C(0xFF2673B3), FloorHere = C(0xFF1AA64D);
private const uint FillFlat = 0x662E8C38, FillUp = 0x668C1F14, FillDown = 0x661A8026, FillVisited = 0xB84D6B94;
private static uint C(uint argb) => RynthTheme.Argb(argb);
/// <summary>ARGB colour with its alpha scaled, as an ImGui colour.</summary>
private static uint MulAlpha(uint argb, float k) =>
RynthTheme.Argb((argb & 0x00FFFFFF) | ((uint)Math.Clamp((int)MathF.Round((argb >> 24) * k), 0, 255) << 24));
private const float DimOtherFloors = 0.25f; // the plugin map's DimCol
private const float DefaultZoom = 5f, MinZoom = 1f, MaxZoom = 20f;
// ── Session state (per open) ─────────────────────────────────────────
private float _zoom = DefaultZoom;
private Vector2 _pan;
private bool _follow = true;
private bool _oneUpOneDown = true;
private readonly HashSet<int> _visible = new();
private int _autoLayer = -1;
private uint _landblock;
private int[] _drawOrder = Array.Empty<int>();
public int PopOutIdleHz => 20; // markers move
public bool HiddenWhileDocked
{
get
{
RadarView? view = UiSources.Radar.Current?.Value;
return view != null && !view.Live.IsIndoor;
}
}
public void OnShown()
{
DungeonMapSettingsStore.Load();
UiSources.Radar.Subscribe();
UiSources.Radar.RequestRefresh();
}
public void OnHidden() => UiSources.Radar.Unsubscribe();
public void Draw()
{
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
if (size.X < 16 || size.Y < 16) return;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
RadarView? view = UiSources.Radar.Current?.Value;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
try
{
if (view == null) { Message(dl, origin, size, "Waiting for map data from RynthAi..."); return; }
RadarSnapshot live = view.Live;
if (!live.IsIndoor) { Message(dl, origin, size, "Outdoors: the map shows while you're in a dungeon."); return; }
int layers = live.LayerZs.Count;
TrackLayers(view, live.Player.Landblock, layers);
// ── Toolbar ──
float top = origin.Y;
if (DungeonMapSettingsStore.ShowToolbar)
{
float barH = Toolbar(dl, origin, size.X, view, layers);
top += barH;
}
// ── Canvas ──
var canvasMin = new Vector2(origin.X, top);
var canvasMax = origin + size;
if (canvasMax.Y - canvasMin.Y < 24) return;
dl.AddRectFilled(canvasMin, canvasMax, MulAlpha(CanvasBgArgb, Math.Clamp(DungeonMapSettingsStore.BgOpacity, 0f, 1f)));
dl.AddRect(canvasMin, canvasMax, CanvasBorder);
if (_follow) _pan = Vector2.Zero;
Vector2 centre = (canvasMin + canvasMax) * 0.5f + _pan;
if (layers == 0)
DrawCentredText(dl, (canvasMin + canvasMax) * 0.5f, Hint,
$"Loading dungeon geometry for {live.Player.Landblock:X4}...");
else
{
ImDrawListFlags saved = dl.Flags;
dl.Flags = saved & ~(ImDrawListFlags.AntiAliasedLines | ImDrawListFlags.AntiAliasedLinesUseTex | ImDrawListFlags.AntiAliasedFill);
dl.PushClipRect(canvasMin, canvasMax, true);
var proj = new Projection(centre, live.Player, DungeonMapSettingsStore.RotateWithPlayer, _zoom);
DrawFloors(dl, view, proj, canvasMin, canvasMax);
dl.Flags = saved;
DrawMarkers(dl, live, proj, canvasMin, canvasMax);
DrawPlayer(dl, centre, proj);
dl.PopClipRect();
}
// Show-toolbar button over the canvas corner (submitted before the surface so it wins the hover).
if (!DungeonMapSettingsStore.ShowToolbar)
{
if (IconButton("##dmap_showbar", canvasMin + new Vector2(4, 4), PhosphorIcons.CaretDown))
{
DungeonMapSettingsStore.ShowToolbar = true;
DungeonMapSettingsStore.Save();
}
ImGuiNET.ImGui.SetItemTooltip("Show the map settings");
}
CanvasInput(canvasMin, canvasMax);
}
finally
{
ImGuiNET.ImGui.PopFont();
}
}
// ── Floors ────────────────────────────────────────────────────────────
/// <summary>Follows the player's floor: 1U1D keeps current +-1, Follow alone keeps just the current one.</summary>
private void TrackLayers(RadarView view, uint landblock, int layers)
{
if (landblock != _landblock)
{
_landblock = landblock;
_pan = Vector2.Zero;
_autoLayer = -1;
_visible.Clear();
}
int best = view.CurrentLayer;
if (best < 0 || best == _autoLayer) return;
_autoLayer = best;
if (_oneUpOneDown) SetOneUpOneDown(layers);
else if (_follow || _visible.Count == 0) { _visible.Clear(); _visible.Add(best); }
}
private void SetOneUpOneDown(int layers)
{
_visible.Clear();
if (_autoLayer < 0) return;
if (_autoLayer > 0) _visible.Add(_autoLayer - 1);
_visible.Add(_autoLayer);
if (_autoLayer < layers - 1) _visible.Add(_autoLayer + 1);
}
private void DrawFloors(ImDrawListPtr dl, RadarView view, in Projection proj, Vector2 clipMin, Vector2 clipMax)
{
int layers = view.Live.LayerZs.Count;
int cur = view.CurrentLayer;
// Other floors first, the player's floor on top.
if (_drawOrder.Length < layers) _drawOrder = new int[layers];
int n = 0;
foreach (int i in _visible) if (i >= 0 && i < layers && i != cur) _drawOrder[n++] = i;
bool curVisible = cur >= 0 && _visible.Contains(cur);
if (curVisible) _drawOrder[n++] = cur;
// Fill strips: 5 floats (x0, y0, x1, y1, type).
for (int k = 0; k < n; k++)
{
int layer = _drawOrder[k];
if (view.FillsByLayer[layer] is not float[] strips) continue;
float a = layer == cur ? 1f : DimOtherFloors;
uint flat = MulAlpha(FillFlat, a), up = MulAlpha(FillUp, a), down = MulAlpha(FillDown, a);
for (int i = 0; i + 4 < strips.Length; i += 5)
{
int type = (int)strips[i + 4];
FillRect(dl, proj, strips[i], strips[i + 1], strips[i + 2], strips[i + 3],
type == 1 ? up : type == 2 ? down : flat, clipMin, clipMax);
}
}
// Visited cells, the player's floor only: 4 floats per strip.
if (curVisible && view.VisitedByLayer[cur] is float[] visited)
{
uint fill = RynthTheme.Argb(FillVisited);
for (int i = 0; i + 3 < visited.Length; i += 4)
FillRect(dl, proj, visited[i], visited[i + 1], visited[i + 2], visited[i + 3], fill, clipMin, clipMax);
}
// Walls: 6 floats (ax, ay, bx, by, cell x, cell y).
for (int k = 0; k < n; k++)
{
int layer = _drawOrder[k];
if (view.WallsByLayer[layer] is not float[] segs) continue;
bool current = layer == cur;
uint col = current ? Wall : MulAlpha(0xFF8CCCFF, DimOtherFloors);
float thick = current ? 1.5f : 1f;
for (int i = 0; i + 5 < segs.Length; i += 6)
{
Vector2 pa = proj.P(segs[i], segs[i + 1]);
Vector2 pb = proj.P(segs[i + 2], segs[i + 3]);
if (MathF.Max(pa.X, pb.X) < clipMin.X || MathF.Min(pa.X, pb.X) > clipMax.X ||
MathF.Max(pa.Y, pb.Y) < clipMin.Y || MathF.Min(pa.Y, pb.Y) > clipMax.Y) continue;
dl.AddLine(pa, pb, col, thick);
}
}
}
private static void FillRect(ImDrawListPtr dl, in Projection proj, float x0, float y0, float x1, float y1,
uint col, Vector2 clipMin, Vector2 clipMax)
{
Vector2 p00 = proj.P(x0, y0), p11 = proj.P(x1, y1);
if (proj.Rotated)
{
Vector2 p10 = proj.P(x1, y0), p01 = proj.P(x0, y1);
float minX = MathF.Min(MathF.Min(p00.X, p11.X), MathF.Min(p10.X, p01.X));
float maxX = MathF.Max(MathF.Max(p00.X, p11.X), MathF.Max(p10.X, p01.X));
float minY = MathF.Min(MathF.Min(p00.Y, p11.Y), MathF.Min(p10.Y, p01.Y));
float maxY = MathF.Max(MathF.Max(p00.Y, p11.Y), MathF.Max(p10.Y, p01.Y));
if (maxX < clipMin.X || minX > clipMax.X || maxY < clipMin.Y || minY > clipMax.Y) return;
dl.AddQuadFilled(p00, p10, p11, p01, col);
}
else
{
var a = Vector2.Min(p00, p11);
var b = Vector2.Max(p00, p11);
if (b.X < clipMin.X || a.X > clipMax.X || b.Y < clipMin.Y || a.Y > clipMax.Y) return;
dl.AddRectFilled(a, b, col);
}
}
// ── Markers and player ────────────────────────────────────────────────
private static void DrawMarkers(ImDrawListPtr dl, RadarSnapshot live, in Projection proj, Vector2 clipMin, Vector2 clipMax)
{
const float Margin = 20f;
bool doors = DungeonMapSettingsStore.ShowDoors, creatures = DungeonMapSettingsStore.ShowCreatures;
RadarMarkerStyle.FillColors(KindCols);
foreach (RadarMarker m in live.Markers)
{
if (!ShowOnMap(m.Kind, doors, creatures)) continue;
Vector2 p = proj.P(m.X, m.Y);
if (p.X < clipMin.X - Margin || p.X > clipMax.X + Margin || p.Y < clipMin.Y - Margin || p.Y > clipMax.Y + Margin) continue;
switch (m.Kind)
{
case 0:
dl.AddCircleFilled(p, 4f, Monster, 10);
dl.AddCircle(p, 6f, MonsterRing, 10, 1f);
Label(dl, p + new Vector2(7, -7), CreatureLabel, m.Label, 20);
break;
case 1:
dl.AddCircleFilled(p, 4f, Npc, 10);
dl.AddCircle(p, 6f, NpcRing, 10, 1.2f);
Label(dl, p + new Vector2(7, -7), CreatureLabel, m.Label, 20);
break;
case 2:
dl.AddCircleFilled(p, 5f, Portal, 12);
dl.AddCircle(p, 7f, PortalRing, 12, 1.5f);
Label(dl, p + new Vector2(9, -7), PortalLabel, m.Label, 22);
break;
case 3:
const float r = 5f, o = r + 1.5f;
dl.AddQuadFilled(p + new Vector2(0, -r), p + new Vector2(r, 0), p + new Vector2(0, r), p + new Vector2(-r, 0), Door);
dl.AddQuad(p + new Vector2(0, -o), p + new Vector2(o, 0), p + new Vector2(0, o), p + new Vector2(-o, 0), DoorRing, 1.2f);
Label(dl, p + new Vector2(8, -7), DoorLabel, m.Label, 20);
break;
default:
// The kinds added 2026-10-04: the radar's shape and (user-pickable) colour, a size up.
RadarMarkerStyle.Draw(dl, m.Kind, p, KindCols[m.Kind], 1.35f);
if (m.Kind is not RadarKind.GroundItem)
Label(dl, p + new Vector2(8, -7), CreatureLabel, m.Label, 20);
break;
}
}
}
private static readonly uint[] KindCols = new uint[RadarKind.Count];
/// <summary>
/// Portals always; doors with the map's Doors box; monsters and NPCs with its Creatures box.
/// The kinds added 2026-10-04 also follow the radar's show box for that kind (so items on the
/// ground stay off unless turned on there): players, fellows, pets and vendors with Creatures,
/// corpses, lifestones and ground items on the radar's box alone. Unknown kinds: hidden.
/// </summary>
private static bool ShowOnMap(byte kind, bool doors, bool creatures) => kind switch
{
RadarKind.Portal => true,
RadarKind.Door => doors,
RadarKind.Monster or RadarKind.Npc => creatures,
RadarKind.Player or RadarKind.Fellow or RadarKind.Pet or RadarKind.Vendor =>
creatures && UI.Panels.RadarSettingsStore.ShowKind(kind),
_ => UI.Panels.RadarSettingsStore.ShowKind(kind),
};
private static void Label(ImDrawListPtr dl, Vector2 pos, uint col, string? text, int max)
{
if (string.IsNullOrEmpty(text)) return;
if (text.Length > max) text = text[..max] + "…";
dl.AddText(pos, col, text);
}
private static void DrawPlayer(ImDrawListPtr dl, Vector2 at, in Projection proj)
{
dl.AddCircleFilled(at, 4f, PlayerCol, 10);
// Rotating: facing is always up. North-up: AC heading 0 = east, 90 = north.
Vector2 tip = proj.Rotated ? at + new Vector2(0, -10) : at + new Vector2(proj.Cos * 10, -proj.Sin * 10);
dl.AddLine(at, tip, PlayerCol, 1.5f);
}
/// <summary>World (AC x east, y north) to screen around the player, north-up or rotated so facing is up.</summary>
private readonly struct Projection
{
private readonly float _cx, _cy, _pwx, _pwy, _sin, _cos, _zoom;
public readonly bool Rotated;
public Projection(Vector2 playerAt, RadarPlayer p, bool rotate, float zoom)
{
_cx = playerAt.X; _cy = playerAt.Y; _pwx = p.WorldX; _pwy = p.WorldY;
float h = p.Heading * MathF.PI / 180f;
_sin = MathF.Sin(h); _cos = MathF.Cos(h);
Rotated = rotate; _zoom = zoom;
}
public float Sin => _sin;
public float Cos => _cos;
public Vector2 P(float wx, float wy)
{
float dx = wx - _pwx, dy = wy - _pwy;
if (Rotated)
{
float right = _sin * dx - _cos * dy;
float forward = _cos * dx + _sin * dy;
return new Vector2(_cx + right * _zoom, _cy - forward * _zoom);
}
return new Vector2(_cx + dx * _zoom, _cy - dy * _zoom);
}
}
// ── Canvas input ──────────────────────────────────────────────────────
private void CanvasInput(Vector2 canvasMin, Vector2 canvasMax)
{
ImGuiNET.ImGui.SetCursorScreenPos(canvasMin);
ImGuiNET.ImGui.InvisibleButton("##dmap_canvas", Vector2.Max(canvasMax - canvasMin, new Vector2(1, 1)));
if (ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left))
{
Vector2 delta = ImGuiNET.ImGui.GetIO().MouseDelta;
if (float.IsFinite(delta.X) && float.IsFinite(delta.Y) && delta != Vector2.Zero)
{
_follow = false;
_pan += delta;
}
}
if (ImGuiNET.ImGui.IsItemHovered())
{
float wheel = ImGuiNET.ImGui.GetIO().MouseWheel;
if (float.IsFinite(wheel) && wheel != 0f)
_zoom = Math.Clamp(_zoom + wheel * 0.5f, MinZoom, MaxZoom);
}
}
// ── Toolbar ───────────────────────────────────────────────────────────
/// <summary>Draws the settings rows (they wrap to the width). Returns their height.</summary>
private float Toolbar(ImDrawListPtr dl, Vector2 origin, float width, RadarView view, int layers)
{
const float pad = 4;
// Background first, sized once the rows are laid out: a channel split keeps it underneath.
dl.ChannelsSplit(2);
dl.ChannelsSetCurrent(1);
ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(pad, pad));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 1));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4));
float limit = origin.X + width - pad;
bool changed = false;
if (IconButton("##dmap_hidebar", ImGuiNET.ImGui.GetCursorScreenPos(), PhosphorIcons.CaretUp))
{
DungeonMapSettingsStore.ShowToolbar = false;
changed = true;
}
ImGuiNET.ImGui.SetItemTooltip("Hide the map settings");
// 1U1D and the floors.
SameLineIfFits(40, limit);
if (ToggleButton("1U1D##dmap_1u1d", _oneUpOneDown, FloorOn))
{
_oneUpOneDown = !_oneUpOneDown;
if (_oneUpOneDown) SetOneUpOneDown(layers);
}
ImGuiNET.ImGui.SetItemTooltip("Show your floor and the ones just above and below it");
if (layers > 1)
{
SameLineIfFits(ImGuiNET.ImGui.CalcTextSize("Floors:").X, limit);
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted("Floors:");
for (int i = 0; i < layers; i++)
{
string label = FloorLabel(i);
SameLineIfFits(ImGuiNET.ImGui.CalcTextSize(label).X + 8, limit, 2);
bool on = _visible.Contains(i);
if (ToggleButton(label, on, i == view.CurrentLayer ? FloorHere : FloorOn))
{
_oneUpOneDown = false;
if (on) _visible.Remove(i); else _visible.Add(i);
}
}
SameLineIfFits(24, limit);
if (ImGuiNET.ImGui.SmallButton("All##dmap_all"))
{
_oneUpOneDown = false;
_visible.Clear();
for (int i = 0; i < layers; i++) _visible.Add(i);
}
SameLineIfFits(34, limit, 2);
if (ImGuiNET.ImGui.SmallButton("Here##dmap_here"))
{
_oneUpOneDown = false;
_visible.Clear();
if (view.CurrentLayer >= 0) _visible.Add(view.CurrentLayer);
}
}
// Zoom.
SameLineIfFits(130, limit, 12);
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted("Zoom:");
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.SetNextItemWidth(80);
ImGuiNET.ImGui.SliderFloat("##dmap_zoom", ref _zoom, MinZoom, MaxZoom, "%.1fx");
if (!float.IsFinite(_zoom)) _zoom = DefaultZoom;
// Follow / Rotate / Reset.
SameLineIfFits(190, limit, 12);
ImGuiNET.ImGui.Checkbox("Follow##dmap_follow", ref _follow);
ImGuiNET.ImGui.SetItemTooltip("Keep the map centred on you (dragging the map turns this off)");
ImGuiNET.ImGui.SameLine();
changed |= ImGuiNET.ImGui.Checkbox("Rotate##dmap_rotate", ref DungeonMapSettingsStore.RotateWithPlayer);
ImGuiNET.ImGui.SetItemTooltip("Turn the map so the way you face is up");
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Reset##dmap_reset"))
{
_pan = Vector2.Zero;
_zoom = DefaultZoom;
_follow = true;
_oneUpOneDown = true;
SetOneUpOneDown(layers);
}
// Doors / Creatures.
SameLineIfFits(160, limit, 12);
changed |= ImGuiNET.ImGui.Checkbox("Doors##dmap_doors", ref DungeonMapSettingsStore.ShowDoors);
ImGuiNET.ImGui.SameLine();
changed |= ImGuiNET.ImGui.Checkbox("Creatures##dmap_creatures", ref DungeonMapSettingsStore.ShowCreatures);
ImGuiNET.ImGui.SetItemTooltip("Monsters, NPCs, players, fellows, your pet and vendors. Players, fellows, pets, vendors, corpses, lifestones and ground items also follow their box in the Radar's settings.");
// Opacity (of the map's background).
SameLineIfFits(130, limit, 12);
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted("Opacity:");
ImGuiNET.ImGui.SameLine(0, 4);
ImGuiNET.ImGui.SetNextItemWidth(70);
if (ImGuiNET.ImGui.SliderFloat("##dmap_opacity", ref DungeonMapSettingsStore.BgOpacity, 0f, 1f, "%.2f"))
DungeonMapSettingsStore.BgOpacity = Math.Clamp(DungeonMapSettingsStore.BgOpacity, 0f, 1f);
// Save once the drag ends, not on every step.
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) changed = true;
ImGuiNET.ImGui.PopStyleVar(2);
float bottom = ImGuiNET.ImGui.GetItemRectMax().Y + pad;
dl.ChannelsSetCurrent(0);
dl.AddRectFilled(origin, new Vector2(origin.X + width, bottom), C(ToolbarBgArgb));
dl.ChannelsMerge();
if (changed) DungeonMapSettingsStore.Save();
return bottom - origin.Y;
}
private static readonly List<string> FloorLabels = new();
private static string FloorLabel(int i)
{
while (FloorLabels.Count <= i) FloorLabels.Add("F" + (FloorLabels.Count + 1) + "##dmap_floor" + FloorLabels.Count);
return FloorLabels[i];
}
/// <summary>Keeps the next item on this row when it fits before <paramref name="limit"/>, else starts a new row.</summary>
private static void SameLineIfFits(float nextWidth, float limit, float gap = 8)
{
if (ImGuiNET.ImGui.GetItemRectMax().X + gap + nextWidth <= limit)
ImGuiNET.ImGui.SameLine(0, gap);
}
private static bool ToggleButton(string label, bool on, uint onColour)
{
if (on)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, onColour);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, onColour);
}
bool clicked = ImGuiNET.ImGui.SmallButton(label);
if (on) ImGuiNET.ImGui.PopStyleColor(2);
return clicked;
}
private static bool IconButton(string id, Vector2 pos, string glyph)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
var size = new Vector2(18, 18);
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
uint bg = ImGuiNET.ImGui.IsItemActive() ? C(0xE0101820) : ImGuiNET.ImGui.IsItemHovered() ? C(0xE0243444) : ButtonBg;
dl.AddRectFilled(pos, pos + size, bg, 3);
dl.AddRect(pos, pos + size, ButtonBorder, 3);
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, size, C(0xFFF2F8FF));
return clicked;
}
private static void Message(ImDrawListPtr dl, Vector2 origin, Vector2 size, string text)
{
dl.AddRectFilled(origin, origin + size, MulAlpha(CanvasBgArgb, Math.Clamp(DungeonMapSettingsStore.BgOpacity, 0.6f, 1f)));
DrawCentredText(dl, origin + size * 0.5f, Hint, text);
}
private static void DrawCentredText(ImDrawListPtr dl, Vector2 centre, uint col, string text)
{
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text);
dl.AddText(centre - ts * 0.5f, col, text);
}
}
/// <summary>
/// The Dungeon Map's settings (the plugin map's MapShowDoors / MapShowCreatures /
/// MapShowToolbar / MapBgOpacity / MapRotateWithPlayer, same defaults). Engine-wide,
/// in %LOCALAPPDATA%\RynthCore\dungeon_map_settings.txt, like radar_settings.txt.
/// </summary>
internal static class DungeonMapSettingsStore
{
private static readonly object _sync = new();
private static bool _loaded;
public static bool ShowDoors = true;
public static bool ShowCreatures = true;
public static bool ShowToolbar = true;
public static float BgOpacity = 1.0f;
public static bool RotateWithPlayer;
private static string FilePath
{
get
{
string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(root, "RynthCore", "dungeon_map_settings.txt");
}
}
public static void Load()
{
lock (_sync)
{
if (_loaded) return;
_loaded = true;
try
{
string path = FilePath;
if (!File.Exists(path)) return;
foreach (string raw in File.ReadAllLines(path))
{
string line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#')) continue;
int eq = line.IndexOf('=');
if (eq <= 0) continue;
string key = line[..eq].Trim();
string val = line[(eq + 1)..].Trim();
switch (key)
{
case "showDoors": ShowDoors = val == "1"; break;
case "showCreatures": ShowCreatures = val == "1"; break;
case "showToolbar": ShowToolbar = val == "1"; break;
case "rotate": RotateWithPlayer = val == "1"; break;
case "opacity":
if (float.TryParse(val, NumberStyles.Float, CultureInfo.InvariantCulture, out float o))
BgOpacity = Math.Clamp(o, 0f, 1f);
break;
}
}
}
catch { /* best-effort: defaults already in place */ }
}
}
/// <summary>Writes the settings in the background (the caller is AC's render thread).</summary>
public static void Save()
{
// Snapshot on the caller's thread: the writer runs later.
string text = "# RynthCore dungeon map settings - auto-generated, hand-edits OK.\n"
+ $"showDoors={(ShowDoors ? "1" : "0")}\n"
+ $"showCreatures={(ShowCreatures ? "1" : "0")}\n"
+ $"showToolbar={(ShowToolbar ? "1" : "0")}\n"
+ $"rotate={(RotateWithPlayer ? "1" : "0")}\n"
+ FormattableString.Invariant($"opacity={BgOpacity:0.##}\n");
UiBackgroundWriter.Enqueue("dungeon map settings", () =>
{
lock (_sync)
{
try
{
string path = FilePath;
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
File.WriteAllText(path, text);
}
catch { /* non-fatal */ }
}
});
}
}

View file

@ -0,0 +1,315 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/FaceKit.cs
// Widgets the RynthAi-style ImGui faces share: the flat bordered button (and
// its icon-only form), a text box with a grey hint, a picker (button + popup
// list), wrapped button rows, and UTF-8 text buffers. Colours are the panels' palette (ABGR),
// with text brighter than the Avalonia faces (Tom, 2026-09-28).
//
// Everything runs on AC's render thread inside a face's Draw. No per-frame
// allocation except what callers pass in.
// ============================================================================
using System;
using System.Numerics;
using System.Text;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal static class FaceKit
{
private static uint C(uint argb) => RynthTheme.Argb(argb);
public static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Green = C(0xFF33CC66),
Red = C(0xFFE05A5A), Mute = C(0xFFC8D6E4), Text = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14),
PanelBg = C(0xFF141F29), RowAlt = C(0xFF101822), BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A),
Selected = C(0xFF1A2E42), StartBg = C(0xFF196119), StopBg = C(0xFF801919), DeleteBg = C(0xFF801A1A);
// ── Frame ────────────────────────────────────────────────────────────
/// <summary>
/// Starts an edge-to-edge face body: shell background, Ui10 font, a 6 px
/// inset kept on every line (Indent). Returns the content width. Pair with End.
/// </summary>
public static float Begin(out Vector2 origin, out Vector2 size)
{
origin = ImGuiNET.ImGui.GetCursorScreenPos();
size = ImGuiNET.ImGui.GetContentRegionAvail();
ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(origin, origin + size, ShellBg, 4);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4));
ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(6, 6));
ImGuiNET.ImGui.Indent(6);
return size.X - 12;
}
public static void End(Vector2 origin, Vector2 size)
{
ImGuiNET.ImGui.Unindent(6);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.GetWindowDrawList().AddRect(origin, origin + size, BtnBord, 4);
}
/// <summary>
/// A GripInBody face: how far the resize grip reaches above the 6 px bottom
/// margin (0 for other faces). A scrolling child that runs to the margin ends
/// this much higher so its scrollbar stays clear of the grip.
/// </summary>
public static float GripOverlap() => Math.Max(0f, ImGuiPanelHost.BodyGripReserve - 6f);
/// <summary>Space left below the cursor down to the body's bottom (6 px margin).</summary>
public static float Remaining(Vector2 origin, Vector2 size) =>
origin.Y + size.Y - 6 - ImGuiNET.ImGui.GetCursorScreenPos().Y;
/// <summary>Moves the layout cursor to the start of the line below a row drawn at <paramref name="rowStart"/>.</summary>
public static void NextLine(Vector2 rowStart, float rowHeight)
{
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(rowStart.X, rowStart.Y + rowHeight));
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
}
public static void Separator(float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.GetWindowDrawList().AddLine(p + new Vector2(0, 1), p + new Vector2(w, 1), BtnBord);
ImGuiNET.ImGui.Dummy(new Vector2(w, 2));
}
public static void Label(string text, uint color)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopStyleColor();
}
// ── Buttons ──────────────────────────────────────────────────────────
/// <summary>A flat bordered button at <paramref name="pos"/>.</summary>
public static bool Button(string id, string label, Vector2 pos, Vector2 size, uint fg, uint bg,
bool enabled = true, bool leftAlign = false, uint border = 0)
{
bool clicked = ButtonFrame(id, pos, size, bg, enabled, border);
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(label);
float tx = leftAlign ? pos.X + 6 : pos.X + (size.X - ts.X) * 0.5f;
dl.PushClipRect(pos, pos + size, true);
dl.AddText(new Vector2(tx, pos.Y + (size.Y - ts.Y) * 0.5f), enabled ? fg : Faded(fg), label);
dl.PopClipRect();
return clicked;
}
/// <summary>
/// Button's look with a Phosphor icon centred on it. <paramref name="font"/>
/// sets the icon's size: Ui14 (about 13 px) for 20+ px buttons, Ui11 for smaller.
/// </summary>
public static bool IconButton(string id, string icon, Vector2 pos, Vector2 size, uint fg, uint bg,
bool enabled = true, uint border = 0, UiFont font = UiFont.Ui14)
{
bool clicked = ButtonFrame(id, pos, size, bg, enabled, border);
PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(font), icon, pos, size, enabled ? fg : Faded(fg));
return clicked;
}
private static bool ButtonFrame(string id, Vector2 pos, Vector2 size, uint bg, bool enabled, uint border)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size) && enabled;
bool hot = enabled && ImGuiNET.ImGui.IsItemHovered();
uint fill = enabled && ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : hot ? Lighten(bg) : bg;
dl.AddRectFilled(pos, pos + size, fill, 3);
dl.AddRect(pos, pos + size, border != 0 ? border : BtnBord, 3);
return clicked;
}
/// <summary>Width a button needs for <paramref name="label"/> at the current font.</summary>
public static float ButtonWidth(string label) => ImGuiNET.ImGui.CalcTextSize(label).X + 16;
/// <summary>
/// A draggable column edge at screen x (a 6 px handle, resize cursor on hover).
/// Dragging changes <paramref name="width"/> (never below <paramref name="min"/>);
/// <paramref name="onCommit"/> runs when the drag ends, to save it. Leaves the
/// cursor where it was. Returns true while the width is changing.
/// </summary>
public static bool ColumnDivider(string id, float x, float top, float height, ref float width, float min,
Action<float>? onCommit)
{
Vector2 saved = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x - 3, top));
ImGuiNET.ImGui.SetNextItemAllowOverlap();
ImGuiNET.ImGui.InvisibleButton(id, new Vector2(6, height));
bool active = ImGuiNET.ImGui.IsItemActive();
bool hot = active || ImGuiNET.ImGui.IsItemHovered();
if (hot) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.ResizeEW);
bool changed = false;
if (active)
{
float dx = ImGuiNET.ImGui.GetIO().MouseDelta.X;
if (dx != 0)
{
width = Math.Max(min, width + dx);
changed = true;
}
}
if (ImGuiNET.ImGui.IsItemDeactivated()) onCommit?.Invoke(width);
ImGuiNET.ImGui.GetWindowDrawList().AddLine(new Vector2(x, top + 3), new Vector2(x, top + height - 3),
hot ? Teal : BtnBord, hot ? 2f : 1f);
ImGuiNET.ImGui.SetCursorScreenPos(saved);
return changed;
}
/// <summary>
/// A row of buttons that wraps to the width; returns the index clicked or -1.
/// <paramref name="enabled"/> may be null (all enabled).
/// </summary>
public static int WrapButtons(string idPrefix, string[] labels, float w, float height = 24, bool[]? enabled = null)
{
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
float x = start.X, y = start.Y;
int clicked = -1;
for (int i = 0; i < labels.Length; i++)
{
float bw = ButtonWidth(labels[i]);
if (x > start.X && x + bw > start.X + w) { x = start.X; y += height + 4; }
ImGuiNET.ImGui.PushID(idPrefix + i);
if (Button("##b", labels[i], new Vector2(x, y), new Vector2(bw, height), Text, BtnFill, enabled == null || enabled[i]))
clicked = i;
ImGuiNET.ImGui.PopID();
x += bw + 4;
}
NextLine(start, y - start.Y + height);
return clicked;
}
// ── Text input ───────────────────────────────────────────────────────
/// <summary>
/// A bordered text box with a grey <paramref name="hint"/> while empty.
/// Returns true when Enter was pressed (with EnterReturnsTrue) or the text changed.
/// </summary>
public static bool TextBox(string id, byte[] buffer, Vector2 pos, float width, string hint, out bool active,
ImGuiInputTextFlags flags = ImGuiInputTextFlags.None, float height = 22)
{
ImGuiNET.ImGui.SetCursorScreenPos(pos);
ImGuiNET.ImGui.SetNextItemWidth(width);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 3f);
bool result = ImGuiNET.ImGui.InputText(id, buffer, (uint)buffer.Length, flags);
active = ImGuiNET.ImGui.IsItemActive();
ImGuiNET.ImGui.PopStyleVar(3);
ImGuiNET.ImGui.PopStyleColor(3);
if (buffer[0] == 0 && !active && hint.Length > 0)
ImGuiNET.ImGui.GetWindowDrawList().AddText(pos + new Vector2(5, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute), hint);
return result;
}
// ── Picker ───────────────────────────────────────────────────────────
/// <summary>
/// One popup list per face, opened from any button: call Open from the
/// button's click and Draw once per frame at the end of the face's Draw
/// (outside any child window, so the popup id always matches).
/// </summary>
internal sealed class Picker
{
private readonly string _popupId;
private string[] _items = Array.Empty<string>();
private int _selected = -1;
private Action<int>? _onPick;
private Vector2 _pos;
private float _width = 220;
private bool _openRequested;
public Picker(string popupId) => _popupId = popupId;
public void Open(Vector2 below, string[] items, int selected, Action<int> onPick, float width = 220)
{
_items = items;
_selected = selected;
_onPick = onPick;
_pos = below;
_width = width;
_openRequested = items.Length > 0;
}
public void Draw()
{
if (_openRequested)
{
_openRequested = false;
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Clamp(_pos.X, 0, Math.Max(0, display.X - _width)), _pos.Y));
ImGuiNET.ImGui.OpenPopup(_popupId);
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1));
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(_width, Math.Min(_items.Length * 21 + 4, 340)));
bool open = ImGuiNET.ImGui.BeginPopup(_popupId);
ImGuiNET.ImGui.PopStyleVar(3);
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float iw = ImGuiNET.ImGui.GetContentRegionAvail().X;
for (int i = 0; i < _items.Length; i++)
{
ImGuiNET.ImGui.PushID(i);
Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos();
bool click = ImGuiNET.ImGui.InvisibleButton("##it", new Vector2(iw, 20));
bool hot = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.PopID();
bool sel = i == _selected;
dl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? Selected : hot ? Lighten(BtnFill) : BtnFill);
dl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord);
dl.AddText(ip + new Vector2(6, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), sel ? Teal : Text, _items[i]);
if (click)
{
Action<int>? act = _onPick;
ImGuiNET.ImGui.CloseCurrentPopup();
act?.Invoke(i);
}
}
ImGuiNET.ImGui.EndPopup();
}
}
// ── Text buffers ─────────────────────────────────────────────────────
public static string Utf8(byte[] buffer)
{
int len = Array.IndexOf(buffer, (byte)0);
return Encoding.UTF8.GetString(buffer, 0, len < 0 ? buffer.Length : len);
}
/// <summary>Writes <paramref name="text"/> NUL-terminated, cut at a character boundary if it doesn't fit.</summary>
public static void WriteUtf8(byte[] buffer, string text)
{
byte[] all = Encoding.UTF8.GetBytes(text ?? string.Empty);
int n = Math.Min(all.Length, buffer.Length - 1);
while (n > 0 && n < all.Length && (all[n] & 0xC0) == 0x80) n--;
Array.Copy(all, buffer, n);
buffer[n] = 0;
}
// ── Colour helpers ───────────────────────────────────────────────────
public static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12);
public static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0);
public static uint Faded(uint abgr) => (abgr & 0x00FFFFFF) | ((abgr >> 25) << 24);
private static uint Scale(uint abgr, float k, int add)
{
uint a = abgr & 0xFF000000;
uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add);
uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add);
uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add);
return a | (b << 16) | (g << 8) | r;
}
}

View file

@ -0,0 +1,847 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/InventoryFace.Classic.cs
// The Inventory panel's Classic look (docs/IMGUI_INVENTORY.md, Phase 2): the
// retail inventory window, drawn with the client's own pictures from
// client_portal.dat (RetailSprites) at the retail layout's positions.
//
// Where the numbers come from: the retail window is LayoutDesc 0x21000023 in
// the client's dats. Tom's OpenAC client rebuilds it from the dat
// (src/AcDream.App/UI/Layout: InventoryController, PaperdollController,
// PaperdollSlotBackgrounds, ItemListCellTemplate, UiItemSlot, RetailChromeSprites)
// and pins the resolved layout in tests/AcDream.App.Tests/UI/Layout/fixtures/
// inventory_21000023.json. The element positions, sizes and picture ids below
// are read from that layout (and the empty-cell pictures re-resolved from the
// installed dats the way OpenAC's ItemListCellTemplate does); the resize rules
// (the grid and pack column grow with the window's height, the background's
// 25 px title band isn't stretched) follow AcClientReborn's InventoryGeometry.
// Credit: OpenAC (Tom's project) for the layout and sprite research.
//
// title retail title bar "Inventory of <name>", tool toggles, close
// tools search, sort, category chips (toggle, the funnel in the title)
// paperdoll the 24 equip slots at their retail places (the 3D figure isn't
// drawn, so the retail "Slots" view is always on)
// column burden meter, main pack, then the main pack's pack slots: side
// packs, then the items that take a pack slot (foci), as retail
// lists them; its scrollbar
// contents "Contents of <pack>": the open pack's slots, retail scrollbar;
// with a search or filter on, the matches from every pack
// status the action waiting / last outcome (or the pyreals), Drop, Give
//
// Same behaviours as the Modern look: one action at a time, drag to a pack /
// slot / Drop / Give, double-click to use, right-click menu, split dialog.
// Geometry is in retail pixels times the UI scale (DPI x the panel's text size),
// shrunk only to fit a window narrower than 300.
// ============================================================================
using System;
using System.IO;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed partial class InventoryFace
{
// ── Retail art (0x06 textures in client_portal.dat) ─────────────────
private static class Art
{
public const uint Backdrop = 0x06004D0Au; // 300x362 stone background (element 0x100001D0)
public const uint TitleBar = 0x06004CFAu; // 276x25 title bar (0x100001D3)
public const uint Close = 0x06004D0Cu; // 24x25 close button (0x100001D2); +1 = pressed
public const uint GridEmpty = 0x06004D20u; // empty contents cell (prototype 0x1000033A, ItemSlot_Empty)
public const uint PackEmpty = 0x06000F6Eu; // empty side-pack cell (prototype 0x1000033F > 0x1000033E)
public const uint OpenPack = 0x06005D9Cu; // 36x36 gold arrow on the open pack
public const uint MainPackIcon = 0x0600127Eu; // the main pack's backpack
public const uint Selected = 0x06004D21u; // yellow square on the selected item
public const uint Waiting = 0x0600109Au; // hatch on an item waiting for the server
public const uint AcceptGrid = 0x060011F9u, AcceptPack = 0x060011F7u, Reject = 0x060011F8u;
public const uint BurdenBack = 0x0600121Du, BurdenFill = 0x0600121Cu; // meter 0x100001D9 and its fill
public const uint CapacityBack = 0x06004D22u, CapacityFill = 0x06004D23u; // 5x30 pack fill meter
public const uint Track = 0x06004C5Fu; // 16x32 scrollbar chain, tiled (LayoutDesc 0x2100003E)
public const uint ThumbTop = 0x06004C60u, ThumbMid = 0x06004C63u, ThumbBottom = 0x06004C66u;
public const uint Down = 0x06004C69u, Up = 0x06004C6Cu; // +1 rollover, +2 pressed
}
// Retail geometry (px at scale 1), LayoutDesc 0x21000023.
private const float RetailW = 300, TitleH = 25, FieldY = 23, ContentsY = 237, SideW = 61, CellPx = 32, PackPx = 36;
private const int SideBagSlots = 7;
private static uint Rgb(uint argb) => RynthTheme.Argb(argb);
private static readonly uint StoneFallback = Rgb(0xFF16140F), CellFallback = Rgb(0xFF1C1B18), CellEdge = Rgb(0xFF4A4436),
Gold = Rgb(0xFFCAB06D), White = Rgb(0xFFFFFFFF), Black = Rgb(0xFF000000), SelYellow = Rgb(0xFFF0E040),
AcceptGreen = Rgb(0xFF30D040), RejectRed = Rgb(0xFFE03030);
/// <summary>One paperdoll slot: its equip mask, retail place in the paperdoll field, empty picture.</summary>
private readonly struct DollSlot
{
public readonly uint Mask;
public readonly float X, Y;
public readonly uint Empty;
public readonly string Name;
/// <summary>Aetheria slots: the unlock bit (PropertyInt 322); 0 = always shown.</summary>
public readonly uint Sigil;
public DollSlot(uint mask, float x, float y, uint empty, string name, uint sigil = 0)
{
Mask = mask;
X = x;
Y = y;
Empty = empty;
Name = name;
Sigil = sigil;
}
}
// Element ids, masks and empty pictures: OpenAC's PaperdollSlotBackgrounds (pinned from the
// live dat there, re-checked against the installed dats); places: the layout's elements.
private static readonly DollSlot[] Doll =
{
new(0x00000001u, 84, 28, 0x06006D7Fu, "Head"), // 0x100005AB
new(0x00000200u, 84, 64, 0x06006D7Bu, "Chest"), // 0x100005AC
new(0x00000400u, 84, 100, 0x06006D79u, "Abdomen"), // 0x100005AD
new(0x00000800u, 48, 64, 0x06006D87u, "Upper arms"), // 0x100005AE
new(0x00001000u, 48, 100, 0x06006D81u, "Lower arms"), // 0x100005AF
new(0x00000020u, 48, 136, 0x06006D7Du, "Hands"), // 0x100005B0
new(0x00002000u, 120, 100, 0x06006D89u, "Upper legs"), // 0x100005B1
new(0x00004000u, 120, 136, 0x06006D83u, "Lower legs"), // 0x100005B2
new(0x00000100u, 120, 172, 0x06006D85u, "Feet"), // 0x100005B3
new(0x00000002u, 192, 80, 0x060032C5u, "Shirt"), // 0x100001E2
new(0x00000040u, 192, 116, 0x060032C4u, "Pants"), // 0x100001E3
new(0x00008000u, 8, 8, 0x06000F68u, "Neck"), // 0x100001DA
new(0x04000000u, 8, 44, 0x06006A6Cu, "Trinket"), // 0x1000058E
new(0x00020000u, 8, 80, 0x06000F6Au, "Right wrist"), // 0x100001DD
new(0x00080000u, 8, 116, 0x06000F6Bu, "Right ring"), // 0x100001DE
new(0x00200000u, 8, 172, 0x06000F6Cu, "Shield"), // 0x100001E1
new(0x00010000u, 156, 80, 0x06000F5Du, "Left wrist"), // 0x100001DB
new(0x00040000u, 156, 116, 0x06000F5Au, "Left ring"), // 0x100001DC
new(0x03500000u, 156, 172, 0x06000F66u, "Weapon"), // 0x100001DF: melee, missile, held, two-handed
new(0x00800000u, 190, 172, 0x06000F5Eu, "Ammunition"), // 0x100001E0
new(0x08000000u, 192, 44, 0x0600708Fu, "Cloak"), // 0x100005E9
new(0x10000000u, 126, 8, 0x06006BEFu, "Blue Aetheria", 1), // 0x10000595
new(0x20000000u, 158, 8, 0x06006BF0u, "Yellow Aetheria", 2), // 0x10000596
new(0x40000000u, 190, 8, 0x06006BF1u, "Red Aetheria", 4), // 0x10000597
};
// ── Classic state ───────────────────────────────────────────────────
private int _gridFirstRow, _packFirstRow;
private float _thumbGrab;
private string _captionText = string.Empty;
private string? _hoverLabel, _hoverLabel2;
private string _titleText = "Inventory";
private string? _titleFor;
// =====================================================================
// Body
// =====================================================================
private void ClassicBody(InventoryView view, Vector2 origin, Vector2 size)
{
// Scale: the UI scale (DPI x this panel's text size), shrunk only to fit a narrow window.
float ui = EngineFrameController.FontScale * PanelTextScale.Factor(ImGuiFonts.CurrentStep);
if (!(ui > 0f) || !float.IsFinite(ui)) ui = 1f;
ui *= InventorySettingsStore.SizeFactor; // the panel's own size (the - / + in the title bar)
float s = Math.Max(0.4f, Math.Min(ui, size.X / RetailW));
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float w = size.X;
Vector2 o = origin;
float statusH = MathF.Round(20 * s);
float bottom = o.Y + size.Y - statusH;
// The open pack: a real pack (Classic has no "All" or "Worn" entry; the paperdoll is Worn).
if (_pack == AllPacks || _pack == WornPacks || view.PackOf(_pack) == null)
_pack = view.Packs.Length > 0 ? view.Packs[0].Id : AllPacks;
bool filtered = _category != 0 || _searchText.Length > 0;
RebuildIfNeeded(view, filtered ? AllPacks : _pack);
Backdrop(dl, o, w, bottom - o.Y, s);
TitleBar(view, dl, o, w, s);
// Tools (search, sort, categories): between the title bar and the retail body.
float toolsBottom = o.Y + TitleH * s;
if (InventorySettingsStore.ShowTools)
{
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(o.X + 6, toolsBottom + 4));
Tools(w - 12);
Chips(w - 12);
toolsBottom = ImGuiNET.ImGui.GetCursorScreenPos().Y;
}
float ry = toolsBottom - TitleH * s; // where retail y = 0 lands
float r = Math.Max(ContentsY + 60, (bottom - ry) / s); // the retail window's height (px at scale 1)
float sx = o.X + w - SideW * s; // the side column follows the right edge
Paperdoll(view, dl, new Vector2(o.X, ry + FieldY * s), s);
SideColumn(view, dl, new Vector2(sx, ry + FieldY * s), r, s, filtered);
Contents(view, dl, new Vector2(o.X, ry + ContentsY * s), sx, r, s, filtered);
StatusStrip(view, dl, new Vector2(o.X, bottom), w, statusH, s);
// A press on an item that moves far enough starts a drag.
if (_pressItem != null && _dragItem == null && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)
&& Vector2.DistanceSquared(ImGuiNET.ImGui.GetMousePos(), _pressAt) > 25)
_dragItem = _pressItem;
}
// ── Background and title bar ────────────────────────────────────────
/// <summary>The stone background: its 25 px title band at scale, the rest stretched (AcClientReborn's rule).</summary>
private static void Backdrop(ImDrawListPtr dl, Vector2 o, float w, float h, float s)
{
if (!RetailSprites.TryGet(Art.Backdrop, out IntPtr tex))
{
dl.AddRectFilled(o, o + new Vector2(w, h), StoneFallback);
return;
}
const float ArtH = 362f;
float band = Math.Min(h, TitleH * s);
dl.AddImage(tex, o, o + new Vector2(w, band), Vector2.Zero, new Vector2(1, TitleH / ArtH));
if (h > band)
dl.AddImage(tex, o + new Vector2(0, band), o + new Vector2(w, h), new Vector2(0, TitleH / ArtH), Vector2.One);
}
private void TitleBar(InventoryView view, ImDrawListPtr dl, Vector2 o, float w, float s)
{
float h = TitleH * s, closeW = 24 * s;
float barW = w - closeW;
// The bar: three slices so its bevelled ends keep their shape at any width.
if (RetailSprites.TryGet(Art.TitleBar, out IntPtr tex))
{
const float Src = 276f, Cap = 14f;
float cap = Math.Min(Cap * s, barW * 0.5f);
float u = Cap / Src;
dl.AddImage(tex, o, o + new Vector2(cap, h), Vector2.Zero, new Vector2(u, 1));
dl.AddImage(tex, o + new Vector2(cap, 0), o + new Vector2(barW - cap, h), new Vector2(u, 0), new Vector2(1 - u, 1));
dl.AddImage(tex, o + new Vector2(barW - cap, 0), o + new Vector2(barW, h), new Vector2(1 - u, 0), Vector2.One);
}
else
{
dl.AddRectFilled(o, o + new Vector2(barW, h - 1), Black, 4);
dl.AddRect(o, o + new Vector2(barW, h - 1), Gold, 4);
}
// Two toggles at the bar's right end: the tools row and the Modern look.
float btn = MathF.Round(18 * s);
var b2 = new Vector2(o.X + barW - 8 * s - btn, o.Y + (h - btn) * 0.5f);
var b1 = new Vector2(b2.X - btn - 2 * s, b2.Y);
var bPlus = new Vector2(b1.X - btn - 6 * s, b2.Y);
var bMinus = new Vector2(bPlus.X - btn - 2 * s, b2.Y);
if (TitleToggle("##inv_smaller", PhosphorIcons.Minus, bMinus, btn, false))
InventorySettingsStore.StepSize(-1);
ImGuiNET.ImGui.SetItemTooltip($"Smaller ({InventorySettingsStore.SizePct}%)");
if (TitleToggle("##inv_bigger", PhosphorIcons.Plus, bPlus, btn, false))
InventorySettingsStore.StepSize(+1);
ImGuiNET.ImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)");
if (TitleToggle("##inv_tools", PhosphorIcons.Funnel, b1, btn, InventorySettingsStore.ShowTools))
InventorySettingsStore.SetShowTools(!InventorySettingsStore.ShowTools);
ImGuiNET.ImGui.SetItemTooltip("Search, sort and filter");
if (TitleToggle("##inv_modern", PhosphorIcons.SquaresFour, b2, btn, false))
InventorySettingsStore.SetClassic(false);
ImGuiNET.ImGui.SetItemTooltip("Modern look");
// Drag surface: the bar left of the toggles (moves the panel, like the header).
float dragW = Math.Max(1, bMinus.X - o.X - 2);
ImGuiNET.ImGui.SetCursorScreenPos(o);
ImGuiNET.ImGui.InvisibleButton("##inv_titledrag", new Vector2(dragW, h));
ImGuiPanelHost.DragWindowWithLastItem();
// "Inventory of <name>", centred on the bar (left of the toggles when it's narrow).
if (!ReferenceEquals(_titleFor, view.PlayerName))
{
_titleFor = view.PlayerName;
_titleText = view.PlayerName.Length > 0 ? "Inventory of " + view.PlayerName : "Inventory";
}
ImFontPtr f = ImGuiFonts.Get(UiFont.UiBold11);
ImGuiNET.ImGui.PushFont(f);
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_titleText);
ImGuiNET.ImGui.PopFont();
float tx = o.X + (barW - ts.X) * 0.5f;
if (tx + ts.X > bMinus.X - 4) tx = Math.Max(o.X + 10 * s, bMinus.X - 4 - ts.X);
dl.PushClipRect(o + new Vector2(6 * s, 0), new Vector2(bMinus.X - 2, o.Y + h), true);
dl.AddText(f, f.FontSize * InventorySettingsStore.SizeFactor, new Vector2(tx, o.Y + (h - ts.Y) * 0.5f), White, _titleText);
dl.PopClipRect();
// The retail close button.
var cp = new Vector2(o.X + barW, o.Y);
ImGuiNET.ImGui.SetCursorScreenPos(cp);
if (ImGuiNET.ImGui.InvisibleButton("##inv_close", new Vector2(closeW, h)))
ImGuiPanelHost.Close(Title);
bool down = ImGuiNET.ImGui.IsItemActive();
ImGuiNET.ImGui.SetItemTooltip("Close");
if (!Sprite(dl, down ? Art.Close + 1 : Art.Close, cp, new Vector2(closeW, h)))
{
dl.AddRect(cp + new Vector2(3 * s, 3 * s), cp + new Vector2(closeW - 3 * s, h - 3 * s), Gold, 2);
dl.AddLine(cp + new Vector2(7 * s, h * 0.5f), cp + new Vector2(closeW - 7 * s, h * 0.5f), Gold, 2);
}
}
private static bool TitleToggle(string id, string glyph, Vector2 pos, float size, bool on)
{
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, new Vector2(size, size));
bool hot = ImGuiNET.ImGui.IsItemHovered();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
if (on || hot) dl.AddRect(pos, pos + new Vector2(size, size), on ? Gold : Faded(Gold), 3);
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, new Vector2(size, size), on || hot ? Gold : Faded(Gold));
return clicked;
}
// ── Paperdoll ───────────────────────────────────────────────────────
private void Paperdoll(InventoryView view, ImDrawListPtr dl, Vector2 field, float s)
{
float cell = CellPx * s;
uint pendingId = InventoryModel.Pending?.ItemId ?? 0;
for (int i = 0; i < Doll.Length; i++)
{
DollSlot slot = Doll[i];
InventoryItem? worn = null;
foreach (InventoryItem it in view.Worn)
if ((it.Location & slot.Mask) != 0) { worn = it; break; }
if (slot.Sigil != 0 && worn == null && (view.AetheriaMask & slot.Sigil) == 0) continue; // locked sigil slot
var min = new Vector2(field.X + slot.X * s, field.Y + slot.Y * s);
var max = min + new Vector2(cell, cell);
ImGuiNET.ImGui.SetCursorScreenPos(min);
ImGuiNET.ImGui.PushID(i);
ImGuiNET.ImGui.InvisibleButton("##doll", new Vector2(cell, cell), ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
bool hovered = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.PopID();
if (worn != null)
{
DrawItemIcon(dl, worn.Id, min, cell, ReferenceEquals(worn, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu);
ItemPointer(worn, hovered);
}
else
{
CellPicture(dl, slot.Empty, min, cell);
if (hovered)
{
_hoverLabel = slot.Name;
_hoverLabel2 = "Empty. Drag an item here to wear it.";
}
}
bool over = MouseIn(min, max);
if (_dragItem != null && over)
{
bool fits = _dragItem.Wielder == 0 && (_dragItem.ValidLocations & slot.Mask) != 0;
Overlay(dl, fits ? Art.AcceptGrid : Art.Reject, min, cell, fits ? AcceptGreen : RejectRed);
}
if (worn != null)
{
if (worn.Id == pendingId) Overlay(dl, Art.Waiting, min, cell, Amber);
if (worn.Id == _selected) Overlay(dl, Art.Selected, min, cell, SelYellow);
}
_targets.Add(new Target { Min = min, Max = max, Kind = DropKind.Slot, Id = slot.Mask, Name = slot.Name });
}
}
// ── Side column: burden, main pack, side packs ──────────────────────
private void SideColumn(InventoryView view, ImDrawListPtr dl, Vector2 field, float r, float s, bool filtered)
{
// Burden: caption and percent (36x15 each at y 7 and 18), meter 11x58 at (44, 8).
ImFontPtr f = ImGuiFonts.Get(UiFont.Ui9);
CenterText(dl, f, "Burden", new Vector2(field.X, field.Y + 7 * s), new Vector2(36 * s, 15 * s), White);
CenterText(dl, f, view.BurdenText, new Vector2(field.X, field.Y + 18 * s), new Vector2(36 * s, 15 * s), White);
var mMin = new Vector2(field.X + 44 * s, field.Y + 8 * s);
var mSize = new Vector2(11 * s, 58 * s);
// Retail's meter holds 0-300% of capacity (OpenAC's BurdenMath.LoadToFill: load / 3).
float load = view.BurdenCapacity > 0 && view.Burden >= 0 ? view.Burden / (float)view.BurdenCapacity : 0f;
float fill = Math.Clamp(load / 3f, 0f, 1f);
if (!Sprite(dl, Art.BurdenBack, mMin, mSize)) dl.AddRectFilled(mMin, mMin + mSize, CellFallback);
if (fill > 0f)
{
var fMin = new Vector2(mMin.X, mMin.Y + mSize.Y * (1 - fill));
if (RetailSprites.TryGet(Art.BurdenFill, out IntPtr ft))
dl.AddImage(ft, fMin, mMin + mSize, new Vector2(0, 1 - fill), Vector2.One);
else
dl.AddRectFilled(fMin, mMin + mSize, load > 2f ? Red : load > 1f ? Amber : Green);
}
if (MouseIn(field + new Vector2(0, 7 * s), mMin + mSize) && ImGuiNET.ImGui.IsWindowHovered())
{
_hoverLabel = "Burden";
_hoverLabel2 = view.BurdenTip;
}
// Main pack (36x36 at (6, 32)).
InventoryPack? main = view.Packs.Length > 0 ? view.Packs[0] : null;
PackCell(view, dl, main, new Vector2(field.X + 6 * s, field.Y + 32 * s), s, -1, filtered);
// The main pack's pack slots (36 px pitch at (6, 73)): the side packs, then the items
// that take a pack slot (foci), as retail lists them; retail's seven slots (eight with
// the augmentation) or more. Scrollbar at (41, 73); they scroll together.
float listY = field.Y + 73 * s;
float listH = Math.Max(PackPx * s, (r - FieldY - 87) * s);
int rows = Math.Max(1, (int)(listH / (PackPx * s)));
int sidePacks = Math.Max(0, view.Packs.Length - 1);
int used = sidePacks + view.SlotItems.Length;
int slots = Math.Max(view.ContainerSlots > 0 ? view.ContainerSlots : SideBagSlots, used);
_packFirstRow = Math.Clamp(_packFirstRow, 0, Math.Max(0, slots - rows));
uint pendingId = InventoryModel.Pending?.ItemId ?? 0;
for (int row = 0; row < rows; row++)
{
int i = _packFirstRow + row;
if (i >= slots) break;
var min = new Vector2(field.X + 6 * s, listY + row * PackPx * s);
if (i < sidePacks) PackCell(view, dl, view.Packs[i + 1], min, s, i, filtered);
else if (i < used) SlotItemCell(view, dl, view.SlotItems[i - sidePacks], min, s, i, pendingId);
else
{
PackCell(view, dl, null, min, s, i, filtered);
SlotDropHint(view, dl, min + new Vector2(2 * s, 2 * s), CellPx * s);
}
}
// The column itself (after the pack cells, which win): a pack-slot item dropped here
// moves to the main pack, where it lives. Nothing goes *inside* a pack-slot item.
var colMin = new Vector2(field.X, listY);
var colMax = new Vector2(field.X + 41 * s, listY + Math.Min(listH, rows * PackPx * s));
if (view.PlayerId != 0)
_targets.Add(new Target { Min = colMin, Max = colMax, Kind = DropKind.PackSlots, Id = view.PlayerId, Name = "Main pack" });
if (MouseIn(new Vector2(field.X, listY), new Vector2(field.X + SideW * s, listY + listH))
&& ImGuiNET.ImGui.IsWindowHovered())
Wheel(ref _packFirstRow, slots - rows);
Scrollbar("##inv_packsb", new Vector2(field.X + 41 * s, listY), listH, s, ref _packFirstRow, slots, rows);
}
/// <summary>
/// A pack-slot item (a focus) in the side column: a 36x36 cell with the item at (2, 2),
/// drawn and handled like a grid item (select, double-click use, drag, tooltip, menu).
/// </summary>
private void SlotItemCell(InventoryView view, ImDrawListPtr dl, InventoryItem it, Vector2 min, float s, int index, uint pendingId)
{
float box = PackPx * s, cell = CellPx * s;
var inner = min + new Vector2(2 * s, 2 * s);
ImGuiNET.ImGui.SetCursorScreenPos(min);
ImGuiNET.ImGui.PushID(index + 2);
ImGuiNET.ImGui.InvisibleButton("##slotitem", new Vector2(box, box), ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
bool hovered = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.PopID();
ItemPointer(it, hovered);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts
ItemCell(dl, it, inner, cell, pendingId);
ImGuiNET.ImGui.PopFont();
SlotDropHint(view, dl, inner, cell);
}
/// <summary>While a drag is over a pack-slot cell: accept a pack-slot item headed for the main pack, else refuse.</summary>
private void SlotDropHint(InventoryView view, ImDrawListPtr dl, Vector2 inner, float cell)
{
if (_dragItem == null || !MouseIn(inner, inner + new Vector2(cell, cell))) return;
InventoryPack? main = view.Packs.Length > 0 ? view.Packs[0] : null;
if (_dragItem.RequiresPackSlot && _dragItem.Container == view.PlayerId && _dragItem.Wielder == 0) return; // already here
bool ok = main != null && _dragItem.RequiresPackSlot && !PackRefuses(view, main, _dragItem);
Overlay(dl, ok ? Art.AcceptPack : Art.Reject, inner, cell, ok ? AcceptGreen : RejectRed);
}
/// <summary>One pack cell (36x36, the picture at (2, 2)): click opens it; drop an item on it to move it in.</summary>
private void PackCell(InventoryView view, ImDrawListPtr dl, InventoryPack? pack, Vector2 min, float s, int index, bool filtered)
{
float box = PackPx * s, cell = CellPx * s;
var inner = min + new Vector2(2 * s, 2 * s);
ImGuiNET.ImGui.SetCursorScreenPos(min);
ImGuiNET.ImGui.PushID(index + 2);
bool clicked = ImGuiNET.ImGui.InvisibleButton("##pack", new Vector2(box, box));
bool hovered = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.PopID();
if (pack == null)
{
CellPicture(dl, Art.PackEmpty, inner, cell);
return;
}
if (clicked && _dragItem == null) _pack = pack.Id;
if (pack.IsMain)
{
if (!Sprite(dl, Art.MainPackIcon, inner, new Vector2(cell, cell)))
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Backpack, inner, new Vector2(cell, cell), Amber);
}
else
{
DrawItemIcon(dl, pack.Id, inner, cell);
}
// Fill meter (5x30 at the cell's right edge), hidden while the pack is empty (retail's
// rule). Pack-slot items (foci) don't count against the main pack's 102.
if (pack.Used > 0 && pack.Capacity > 0)
{
float f = Math.Clamp(pack.Used / (float)pack.Capacity, 0f, 1f);
var bMin = inner + new Vector2(cell - 5 * s, 1 * s);
var bSize = new Vector2(5 * s, 30 * s);
if (!Sprite(dl, Art.CapacityBack, bMin, bSize)) dl.AddRectFilled(bMin, bMin + bSize, Black);
var fMin = new Vector2(bMin.X, bMin.Y + bSize.Y * (1 - f));
if (RetailSprites.TryGet(Art.CapacityFill, out IntPtr ft))
dl.AddImage(ft, fMin, bMin + bSize, new Vector2(0, 1 - f), Vector2.One);
else
dl.AddRectFilled(fMin, bMin + bSize, Gold);
}
if (pack.Id == _pack && !filtered)
{
if (!Sprite(dl, Art.OpenPack, min, new Vector2(box, box)))
dl.AddTriangleFilled(new Vector2(min.X, min.Y + box * 0.35f), new Vector2(min.X + 5 * s, min.Y + box * 0.5f),
new Vector2(min.X, min.Y + box * 0.65f), Gold);
}
if (_dragItem != null && MouseIn(min, min + new Vector2(box, box)))
{
bool here = _dragItem.Container == pack.Id && _dragItem.Wielder == 0;
bool full = !here && PackRefuses(view, pack, _dragItem);
if (!here) Overlay(dl, full ? Art.Reject : Art.AcceptPack, inner, cell, full ? RejectRed : AcceptGreen);
}
if (hovered)
{
_hoverLabel = pack.Name;
_hoverLabel2 = pack.FillText;
}
_targets.Add(new Target { Min = min, Max = min + new Vector2(box, box), Kind = DropKind.Pack, Id = pack.Id, Name = pack.Name });
}
// ── Contents: the open pack's slots ─────────────────────────────────
private void Contents(InventoryView view, ImDrawListPtr dl, Vector2 field, float sideX, float r, float s, bool filtered)
{
float cell = CellPx * s;
var gridPos = new Vector2(field.X + 15 * s, field.Y + 20 * s);
float availW = sideX - 32 * s - gridPos.X; // retail: grid 15..207, scrollbar 207..223, column at 239
int cols = Math.Max(1, (int)(availW / cell));
float gridW = cols * cell;
float gridH = Math.Max(cell, (r - ContentsY - 5 - 24) * s);
int rows = Math.Max(1, (int)(gridH / cell + 0.01f));
// "Contents of <pack>" over the grid.
CenterText(dl, ImGuiFonts.Get(UiFont.Ui10), _captionText, new Vector2(gridPos.X, field.Y), new Vector2(gridW, 15 * s), White);
InventoryPack? open = filtered ? null : view.PackOf(_pack);
int cells = open != null ? Math.Max(open.Capacity, _shown.Count) : _shown.Count;
int totalRows = (cells + cols - 1) / cols;
_gridFirstRow = Math.Clamp(_gridFirstRow, 0, Math.Max(0, totalRows - rows));
var area = new Vector2(gridW, rows * cell);
ImGuiNET.ImGui.SetCursorScreenPos(gridPos);
ImGuiNET.ImGui.InvisibleButton("##inv_cells", area, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
bool hovered = ImGuiNET.ImGui.IsItemHovered();
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
int hoverCell = -1;
if (MouseIn(gridPos, gridPos + area))
{
int c = (int)((mouse.X - gridPos.X) / cell), rr = (int)((mouse.Y - gridPos.Y) / cell);
if (c >= 0 && c < cols && rr >= 0 && rr < rows) hoverCell = (_gridFirstRow + rr) * cols + c;
if (ImGuiNET.ImGui.IsWindowHovered()) Wheel(ref _gridFirstRow, totalRows - rows);
}
if (hovered && hoverCell >= 0 && hoverCell < _shown.Count) ItemPointer(_shown[hoverCell], true);
// Only the rows on show; retail draws an item's icon in place of the empty cell.
uint pendingId = InventoryModel.Pending?.ItemId ?? 0;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts
for (int rr = 0; rr < rows; rr++)
{
for (int c = 0; c < cols; c++)
{
int i = (_gridFirstRow + rr) * cols + c;
if (i >= cells) break;
var min = new Vector2(gridPos.X + c * cell, gridPos.Y + rr * cell);
if (i >= _shown.Count)
{
CellPicture(dl, Art.GridEmpty, min, cell);
continue;
}
ItemCell(dl, _shown[i], min, cell, pendingId);
}
}
ImGuiNET.ImGui.PopFont();
if (open != null)
{
// Dropping on the grid moves the item into the open pack.
if (_dragItem != null && hoverCell >= 0 && hoverCell < cells && !(_dragItem.Container == open.Id && _dragItem.Wielder == 0))
{
int c = hoverCell % cols, rr = hoverCell / cols - _gridFirstRow;
var min = new Vector2(gridPos.X + c * cell, gridPos.Y + rr * cell);
bool full = PackRefuses(view, open, _dragItem);
Overlay(dl, full ? Art.Reject : Art.AcceptGrid, min, cell, full ? RejectRed : AcceptGreen);
}
_targets.Add(new Target { Min = gridPos, Max = gridPos + area, Kind = DropKind.Pack, Id = open.Id, Name = open.Name });
}
else if (_shown.Count == 0)
{
dl.AddText(gridPos + new Vector2(4, 4), Mute, "Nothing matches.");
}
Scrollbar("##inv_gridsb", new Vector2(gridPos.X + gridW, gridPos.Y), rows * cell, s, ref _gridFirstRow, totalRows, rows);
}
// ── Status strip: the action / outcome (or pyreals), Drop, Give ─────
private void StatusStrip(InventoryView view, ImDrawListPtr dl, Vector2 p, float w, float h, float s)
{
dl.AddRectFilled(p, p + new Vector2(w, h), Black);
dl.AddLine(p, p + new Vector2(w, 0), Faded(Gold));
InventoryTarget? target = InventoryModel.Target;
InventoryItem? sel = SelectedItem(view);
float zh = h - 4, giveW = Math.Min(128 * s, w * 0.42f), dropW = 62 * s;
var give = new Vector2(p.X + w - giveW - 2, p.Y + 2);
var drop = new Vector2(give.X - dropW - 3, p.Y + 2);
Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, "Drop", drop, new Vector2(dropW, zh), 0, "",
InventoryModel.DropAvailable, sel, "Drop on the ground: drag an item here, or click to drop the selected item.");
Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, target?.ZoneLabel ?? "Give", give, new Vector2(giveW, zh),
target?.Id ?? 0, target?.Name ?? "", InventoryModel.GiveAvailable && target != null, sel,
target?.ZoneTip ?? "Select a creature, NPC or player in the game to give to.");
StatusLine(new Vector2(p.X + 3, p.Y), Math.Max(10, drop.X - p.X - 6), h, view);
}
// ── Pieces ──────────────────────────────────────────────────────────
/// <summary>
/// One item's cell picture (the contents grid and the side column's pack-slot items):
/// its icon (faded while dragged), stack count (in the caller's font), and the waiting
/// and selected overlays.
/// </summary>
private void ItemCell(ImDrawListPtr dl, InventoryItem it, Vector2 min, float cell, uint pendingId)
{
DrawItemIcon(dl, it.Id, min, cell, ReferenceEquals(it, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu);
if (it.StackText.Length > 0)
{
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(it.StackText);
var tp = new Vector2(min.X + cell - ts.X - 1, min.Y + cell - ts.Y);
dl.AddText(tp + Vector2.One, StackShadow, it.StackText);
dl.AddText(tp, StackCol, it.StackText);
}
if (it.Id == pendingId) Overlay(dl, Art.Waiting, min, cell, Amber);
if (it.Id == _selected) Overlay(dl, Art.Selected, min, cell, SelYellow);
}
/// <summary>Hover, click (select, and a press that may become a drag), double-click (use), right-click (menu).</summary>
private void ItemPointer(InventoryItem it, bool hovered)
{
if (!hovered) return;
_hover = it;
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
_selected = it.Id;
_pressItem = it;
_pressAt = ImGuiNET.ImGui.GetMousePos();
}
if (ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
{
_pressItem = null;
Act(InventoryActionKind.Use, it, 0, "", 0);
}
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right))
{
_selected = it.Id;
_ctxItem = it;
_openCtx = true;
}
}
/// <summary>
/// The retail scrollbar (LayoutDesc 0x2100003E's 16 px variant): tiled chain, up and down
/// gems, three-piece thumb. Clicking a gem moves a row; dragging the thumb, or clicking the
/// chain, moves to that point.
/// </summary>
private void Scrollbar(string id, Vector2 pos, float h, float s, ref int first, int total, int visible)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float w = 16 * s, btn = Math.Min(16 * s, h * 0.5f);
int max = Math.Max(0, total - visible);
first = Math.Clamp(first, 0, max);
if (h < 2 || w < 2) return;
// Chain, tiled down the shaft (stretching smears the beads).
if (RetailSprites.TryGet(Art.Track, out IntPtr track))
{
float tile = 32 * s;
for (float y = 0; y < h; y += tile)
{
float th = Math.Min(tile, h - y);
dl.AddImage(track, new Vector2(pos.X, pos.Y + y), new Vector2(pos.X + w, pos.Y + y + th), Vector2.Zero,
new Vector2(1, th / tile));
}
}
else
{
dl.AddRectFilled(pos + new Vector2(w * 0.3f, 0), pos + new Vector2(w * 0.7f, h), Faded(Gold));
}
ImGuiNET.ImGui.PushID(id);
ImGuiNET.ImGui.SetCursorScreenPos(pos);
if (ImGuiNET.ImGui.InvisibleButton("##up", new Vector2(w, btn)) && first > 0) first--;
uint upState = ImGuiNET.ImGui.IsItemActive() ? 2u : ImGuiNET.ImGui.IsItemHovered() ? 1u : 0u;
var downPos = new Vector2(pos.X, pos.Y + h - btn);
ImGuiNET.ImGui.SetCursorScreenPos(downPos);
if (ImGuiNET.ImGui.InvisibleButton("##down", new Vector2(w, btn)) && first < max) first++;
uint downState = ImGuiNET.ImGui.IsItemActive() ? 2u : ImGuiNET.ImGui.IsItemHovered() ? 1u : 0u;
float t0 = pos.Y + btn, span = h - 2 * btn;
if (max > 0 && span > 4)
{
float th = Math.Clamp(span * visible / Math.Max(1, total), Math.Min(16 * s, span), span);
float t = t0 + (span - th) * first / max;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(pos.X, t0));
ImGuiNET.ImGui.InvisibleButton("##track", new Vector2(w, span));
if (ImGuiNET.ImGui.IsItemActive())
{
float my = ImGuiNET.ImGui.GetMousePos().Y;
if (ImGuiNET.ImGui.IsItemActivated()) _thumbGrab = my >= t && my < t + th ? my - t : th * 0.5f;
float rel = (my - _thumbGrab - t0) / Math.Max(1f, span - th);
first = Math.Clamp((int)MathF.Round(rel * max), 0, max);
t = t0 + (span - th) * first / max;
}
// Thumb: 3 px caps, the middle stretched.
float cap = Math.Min(3 * s, th * 0.5f);
var a = new Vector2(pos.X, t);
if (!Sprite(dl, Art.ThumbTop, a, new Vector2(w, cap))
| !Sprite(dl, Art.ThumbMid, a + new Vector2(0, cap), new Vector2(w, th - 2 * cap))
| !Sprite(dl, Art.ThumbBottom, a + new Vector2(0, th - cap), new Vector2(w, cap)))
dl.AddRectFilled(a, a + new Vector2(w, th), Rgb(0xFF203C78), 2);
}
ImGuiNET.ImGui.PopID();
if (!Sprite(dl, Art.Up + upState, pos, new Vector2(w, btn)))
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretUp, pos, new Vector2(w, btn), Gold);
if (!Sprite(dl, Art.Down + downState, downPos, new Vector2(w, btn)))
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown, downPos, new Vector2(w, btn), Gold);
}
private static void Wheel(ref int first, int max)
{
float wheel = ImGuiNET.ImGui.GetIO().MouseWheel;
if (wheel == 0) return;
first = Math.Clamp(first - Math.Sign(wheel), 0, Math.Max(0, max));
}
/// <summary>A retail picture at min..min+size; false (nothing drawn) until it has loaded.</summary>
private static bool Sprite(ImDrawListPtr dl, uint id, Vector2 min, Vector2 size)
{
if (!RetailSprites.TryGet(id, out IntPtr tex)) return false;
dl.AddImage(tex, min, min + size);
return true;
}
/// <summary>An empty cell's picture, or a plain dark cell until it has loaded.</summary>
private static void CellPicture(ImDrawListPtr dl, uint id, Vector2 min, float size)
{
if (Sprite(dl, id, min, new Vector2(size, size))) return;
dl.AddRectFilled(min, min + new Vector2(size, size), CellFallback);
dl.AddRect(min, min + new Vector2(size, size), CellEdge);
}
/// <summary>A retail overlay (selected, waiting, drop accepted / refused), or an outline in <paramref name="fallback"/>.</summary>
private static void Overlay(ImDrawListPtr dl, uint id, Vector2 min, float size, uint fallback)
{
if (Sprite(dl, id, min, new Vector2(size, size))) return;
dl.AddRect(min, min + new Vector2(size, size), fallback, 2, ImDrawFlags.None, 1.5f);
}
private static void CenterText(ImDrawListPtr dl, ImFontPtr f, string text, Vector2 pos, Vector2 size, uint color)
{
if (text.Length == 0) return;
ImGuiNET.ImGui.PushFont(f);
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text);
ImGuiNET.ImGui.PopFont();
dl.PushClipRect(pos, pos + size, true);
dl.AddText(f, f.FontSize * InventorySettingsStore.SizeFactor, new Vector2(pos.X + (size.X - ts.X) * 0.5f, pos.Y + (size.Y - ts.Y) * 0.5f), color, text);
dl.PopClipRect();
}
private static bool MouseIn(Vector2 min, Vector2 max)
{
Vector2 m = ImGuiNET.ImGui.GetMousePos();
return m.X >= min.X && m.Y >= min.Y && m.X < max.X && m.Y < max.Y;
}
}
/// <summary>
/// The Inventory panel's remembered choices: Classic or Modern look, and whether the
/// Classic view shows its tools row. %LOCALAPPDATA%\RynthCore\inventory_settings.txt,
/// read once when the panel opens, written in the background when a choice changes.
/// </summary>
internal static class InventorySettingsStore
{
private static readonly object Sync = new();
private static bool _loaded;
/// <summary>The retail look (default) or the Phase 1 modern layout.</summary>
public static bool Classic { get; private set; } = true;
/// <summary>Classic view: the search / sort / category row under the title bar.</summary>
public static bool ShowTools { get; private set; }
/// <summary>The panel's size in percent of the UI scale (50-150, steps of 10); text follows it.</summary>
public static int SizePct { get; private set; } = 80;
public static float SizeFactor => SizePct / 100f;
private static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "inventory_settings.txt");
public static void Load()
{
lock (Sync)
{
if (_loaded) return;
_loaded = true;
try
{
string path = FilePath;
if (!File.Exists(path)) return;
foreach (string raw in File.ReadAllLines(path))
{
string line = raw.Trim();
int eq = line.IndexOf('=');
if (line.StartsWith('#') || eq <= 0) continue;
string key = line[..eq].Trim(), val = line[(eq + 1)..].Trim();
if (key == "classic") Classic = val == "1";
else if (key == "tools") ShowTools = val == "1";
else if (key == "size" && int.TryParse(val, out int pct)) SizePct = Math.Clamp(pct, 50, 150);
}
}
catch { /* defaults stay */ }
}
}
public static void SetClassic(bool on)
{
if (Classic == on) return;
Classic = on;
Save();
}
public static void StepSize(int dir)
{
int next = Math.Clamp(SizePct + 10 * Math.Sign(dir), 50, 150);
if (next == SizePct) return;
SizePct = next;
Save();
}
public static void SetShowTools(bool on)
{
if (ShowTools == on) return;
ShowTools = on;
Save();
}
/// <summary>Writes the settings in the background (the caller is AC's render thread).</summary>
private static void Save()
{
string text = "# RynthCore inventory panel settings - auto-generated, hand-edits OK.\n"
+ "classic=" + (Classic ? "1" : "0") + "\n"
+ "tools=" + (ShowTools ? "1" : "0") + "\n"
+ "size=" + SizePct + "\n";
UiBackgroundWriter.Enqueue("inventory settings", () =>
{
lock (Sync)
{
try
{
string path = FilePath;
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
File.WriteAllText(path, text);
}
catch { /* non-fatal */ }
}
});
}
}

View file

@ -0,0 +1,990 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/InventoryFace.cs
// The in-game Inventory panel (docs/IMGUI_INVENTORY.md). Engine only.
// Two looks, one set of behaviours (a toggle switches them, remembered):
// Classic the retail inventory window, drawn from the client's own
// pictures (InventoryFace.Classic.cs; Phase 2)
// Modern the Phase 1 layout, below
//
// header burden (percent of capacity) and pyreals; item count
// tools search box, sort picker; category chips
// packs All, Main pack, each side pack (its icon and fill), Worn
// grid the chosen pack's items as icons with stack counts; hover for a
// tooltip (asks the server to identify an unknown item, throttled);
// double-click uses; right-click for Use / Equip / Split / Move to /
// Drop / Give; drag onto a pack to move, onto Equip / Drop / Give
// zones Equip, Drop, Give-to-<selected creature>: drop targets for a drag,
// or buttons for the selected item
// status the one action waiting for the server (with a timer), or how the
// last one ended
//
// Data: InventoryModel (Compatibility), captured and acted on on AC's main
// thread. This face only reads its published objects and posts requests; one
// item action at a time (a click while one waits is refused, never queued).
// Per frame: no allocation except the tooltip of a newly hovered item and the
// filtered list when the view, pack, filter, search or sort change.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI.ScriptWindows;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed partial class InventoryFace : IImGuiPanel
{
public const string Title = "Inventory";
// Default: the Classic view at its retail size (300 x 362 body, plus the status strip).
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(302, 426), new Vector2(240, 300), EdgeToEdge: true),
() => new InventoryFace());
// ── Layout (px, like the other faces) ───────────────────────────────
private const float Cell = 38, Icon = 32, RowH = 24, PackRowH = 38, ZoneH = 30, StatusH = 20;
private const uint AllPacks = 0, WornPacks = 1; // pseudo pack ids (real ids are never 0 or 1)
private static readonly uint CellBg = RynthTheme.Argb(0xFF101822), CellHot = RynthTheme.Argb(0xFF1C3148),
CellSel = RynthTheme.Argb(0xFF26D9E6), StackCol = RynthTheme.Argb(0xFFFFFFFF), StackShadow = RynthTheme.Argb(0xE0000000),
DropHot = RynthTheme.Argb(0xFF1F5A3A), Placeholder = RynthTheme.Argb(0xFF1A2633);
private static readonly string[] SortNames = { "Pack order", "Name", "Value", "Burden", "Type", "Stack" };
private static readonly string[] SortLabels = Array.ConvertAll(SortNames, n => PhosphorIcons.SortAscending + " " + n);
private static readonly string[] CategoryNames = { "All", "Weapons", "Armor", "Jewelry", "Usable", "Comps", "Salvage", "Misc" };
private static readonly InventoryCategory[] CategoryOf =
{
default, InventoryCategory.Weapons, InventoryCategory.Armor, InventoryCategory.Jewelry, InventoryCategory.Usable,
InventoryCategory.Components, InventoryCategory.Salvage, InventoryCategory.Misc,
};
// ── State ───────────────────────────────────────────────────────────
private uint _pack = AllPacks;
private int _sort, _category;
private readonly byte[] _search = new byte[64];
private string _searchText = string.Empty;
private uint _selected;
private readonly Picker _picker = new("##inv_sort");
// Filtered, sorted list (rebuilt only when an input changes).
private readonly List<InventoryItem> _shown = new(256);
private InventoryView? _builtFor;
private uint _builtPack = uint.MaxValue;
private int _builtSort = -1, _builtCategory = -1;
private string _builtSearch = "\0";
private bool _builtClassic;
// Leave pack-slot items (foci) out of this list: the Classic main pack grid (they're in the side column).
private bool _skipSlotItems;
private string _countText = string.Empty;
// Hover and tooltip cache.
private InventoryItem? _hover, _tipItem;
private string[] _tipBase = Array.Empty<string>();
// Drag.
private InventoryItem? _pressItem, _dragItem;
private Vector2 _pressAt;
// Slot: one paperdoll slot (Id = its equip mask, Name = the slot's name).
// PackSlots: the Classic side column's pack slots (Id = the main pack): only a
// pack-slot item (a focus) goes there, which moves it to the main pack.
private enum DropKind : byte { None, Pack, Equip, Drop, Give, Slot, PackSlots }
private struct Target { public Vector2 Min, Max; public DropKind Kind; public uint Id; public string Name; }
private readonly List<Target> _targets = new(16);
// Context menu and split dialog (opened at the end of Draw, outside any child).
private InventoryItem? _ctxItem;
private bool _openCtx, _openSplit;
private InventoryItem? _splitItem;
private int _splitAmount = 1;
private uint _splitTarget;
// Status line cache.
private string _statusText = string.Empty;
private int _statusKey = int.MinValue;
private string _refusal = string.Empty;
private long _refusalAt;
public void OnShown()
{
InventorySettingsStore.Load();
InventoryModel.Subscribe();
}
public void OnHidden()
{
InventoryModel.Hover(0);
InventoryModel.Unsubscribe();
_dragItem = _pressItem = null;
}
// =====================================================================
// Frame
// =====================================================================
public void Draw()
{
InventoryView view = InventoryModel.Current;
_targets.Clear();
_hover = null;
float w = Begin(out Vector2 origin, out Vector2 size);
if (view.PlayerId == 0)
{
Label("Waiting for your character's inventory...", Mute);
End(origin, size);
InventoryModel.Hover(0);
return;
}
_hoverLabel = _hoverLabel2 = null;
// Text follows the panel's size setting (the - / + in the Classic title bar).
ImGuiNET.ImGui.SetWindowFontScale(InventorySettingsStore.SizeFactor);
if (InventorySettingsStore.Classic) ClassicBody(view, origin, size);
else ModernBody(view, origin, size, w);
InventoryModel.Hover(_dragItem == null ? _hover?.Id ?? 0 : 0);
FinishDrag();
End(origin, size);
Tooltip();
DrawDragGhost();
ContextMenu(view);
SplitDialog(view);
_picker.Draw();
}
/// <summary>The Phase 1 layout: header, tools, chips, pack column | grid, zones, status.</summary>
private void ModernBody(InventoryView view, Vector2 origin, Vector2 size, float w)
{
if (_pack != AllPacks && _pack != WornPacks && view.PackOf(_pack) == null) _pack = AllPacks;
RebuildIfNeeded(view, _pack); // the header shows the count
Header(view, w);
Tools(w);
Chips(w);
RebuildIfNeeded(view, _pack);
// Body: pack column | grid, then zones and the status row at the bottom.
float bottomH = ZoneH + StatusH + 8;
Vector2 bodyPos = ImGuiNET.ImGui.GetCursorScreenPos();
float bodyH = Math.Max(60, origin.Y + size.Y - 6 - bottomH - bodyPos.Y);
float colW = w >= 380 ? 128 : 46;
PackColumn(view, bodyPos, colW, bodyH);
Grid(new Vector2(bodyPos.X + colW + 4, bodyPos.Y), new Vector2(w - colW - 4, bodyH));
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bodyPos.X, bodyPos.Y + bodyH + 4));
Zones(view, w);
StatusRow(w);
}
// ── Header: burden, pyreals, count ──────────────────────────────────
private void Header(InventoryView view, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr icons = ImGuiFonts.Get(UiFont.Ui14);
float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
PhosphorIcons.DrawCentered(dl, icons, PhosphorIcons.Scales, p, new Vector2(18, RowH), Amber);
float x = p.X + 20;
dl.AddText(new Vector2(x, ty), BurdenColour(view), view.BurdenText);
float bw = ImGuiNET.ImGui.CalcTextSize(view.BurdenText).X;
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.InvisibleButton("##burden", new Vector2(x + bw - p.X, RowH));
ImGuiNET.ImGui.SetItemTooltip(view.BurdenTip);
x += bw + 16;
PhosphorIcons.DrawCentered(dl, icons, PhosphorIcons.Coins, new Vector2(x, p.Y), new Vector2(18, RowH), Amber);
dl.AddText(new Vector2(x + 20, ty), Text, view.PyrealText);
// Switch to the Classic (retail) look.
var tb = new Vector2(p.X + w - 22, p.Y + 1);
if (IconButton("##inv_classic", PhosphorIcons.AppWindow, tb, new Vector2(22, 22), Amber, BtnFill, font: UiFont.Ui11))
InventorySettingsStore.SetClassic(true);
ImGuiNET.ImGui.SetItemTooltip("Classic look (the retail inventory window)");
float cw = ImGuiNET.ImGui.CalcTextSize(_countText).X;
dl.AddText(new Vector2(tb.X - cw - 6, ty), Mute, _countText);
NextLine(p, RowH + 2);
}
private static uint BurdenColour(InventoryView view)
{
if (view.BurdenCapacity <= 0 || view.Burden < 0) return Text;
return view.Burden > view.BurdenCapacity ? Red : view.Burden * 10 > view.BurdenCapacity * 9 ? Amber : Green;
}
// ── Search, sort, categories ────────────────────────────────────────
private void Tools(float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float sortW = 118;
float boxW = Math.Max(80, w - sortW - 26 - 8);
if (TextBox("##inv_search", _search, p, boxW, PhosphorIcons.MagnifyingGlass + " Search names", out _))
_searchText = Utf8(_search).Trim().ToLowerInvariant();
if (IconButton("##inv_clear", PhosphorIcons.X, new Vector2(p.X + boxW + 2, p.Y), new Vector2(22, 22), Mute, BtnFill,
enabled: _search[0] != 0, font: UiFont.Ui11))
{
Array.Clear(_search);
_searchText = string.Empty;
}
ImGuiNET.ImGui.SetItemTooltip("Clear the search");
Vector2 sp = new(p.X + w - sortW, p.Y);
if (Button("##inv_sortbtn", SortLabels[_sort], sp, new Vector2(sortW, 22), Text, BtnFill,
leftAlign: true))
_picker.Open(new Vector2(sp.X, sp.Y + 24), SortNames, _sort, i => _sort = i, sortW);
ImGuiNET.ImGui.SetItemTooltip("Sort the items");
NextLine(p, 26);
}
private void Chips(float w)
{
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
float x = start.X, y = start.Y;
ImFontPtr f = ImGuiFonts.Get(UiFont.Ui9);
const float h = 18;
for (int i = 0; i < CategoryNames.Length; i++)
{
string label = CategoryNames[i];
float cw = CalcWidth(f, label) + 12;
if (x > start.X && x + cw > start.X + w) { x = start.X; y += h + 3; }
var pos = new Vector2(x, y);
ImGuiNET.ImGui.SetCursorScreenPos(pos);
ImGuiNET.ImGui.PushID(i);
if (ImGuiNET.ImGui.InvisibleButton("##chip", new Vector2(cw, h))) _category = i;
bool hot = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.PopID();
bool on = _category == i;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(pos, pos + new Vector2(cw, h), on ? Selected : hot ? Lighten(BtnFill) : BtnFill, 9);
dl.AddRect(pos, pos + new Vector2(cw, h), on ? Teal : BtnBord, 9);
dl.AddText(f, f.FontSize * InventorySettingsStore.SizeFactor, pos + new Vector2(6, (h - f.FontSize) * 0.5f), on ? Teal : Text, label);
x += cw + 4;
}
NextLine(start, y - start.Y + h + 4);
}
private static float CalcWidth(ImFontPtr font, string text)
{
ImGuiNET.ImGui.PushFont(font);
float w = ImGuiNET.ImGui.CalcTextSize(text).X;
ImGuiNET.ImGui.PopFont();
return w;
}
// ── Filtered list ───────────────────────────────────────────────────
/// <summary>
/// The filtered, sorted list for <paramref name="pack"/> (a real pack id, AllPacks or
/// WornPacks; the caller makes sure a real id is in the view). Rebuilt only on change.
/// </summary>
private void RebuildIfNeeded(InventoryView view, uint pack)
{
bool classic = InventorySettingsStore.Classic;
if (ReferenceEquals(view, _builtFor) && _builtPack == pack && _builtSort == _sort
&& _builtCategory == _category && ReferenceEquals(_builtSearch, _searchText) && _builtClassic == classic)
return;
if (_builtPack != pack || !ReferenceEquals(_builtSearch, _searchText) || _builtCategory != _category)
_gridFirstRow = 0; // another pack or filter: back to the top (Classic grid)
_builtFor = view;
_builtPack = pack;
_builtSort = _sort;
_builtCategory = _category;
_builtSearch = _searchText;
_builtClassic = classic;
_shown.Clear();
InventoryPack? one = pack == WornPacks || pack == AllPacks ? null : view.PackOf(pack);
// Classic, the main pack open: its pack-slot items (foci) are in the side column, not
// the grid (retail). A search or filter (all packs) and the Modern look list them.
_skipSlotItems = classic && one != null && one.IsMain;
if (pack == WornPacks) AddFiltered(view.Worn);
else if (one == null) foreach (InventoryPack p in view.Packs) AddFiltered(p.Items);
else AddFiltered(one.Items);
Comparison<InventoryItem>? cmp = _sort switch
{
1 => ByName,
2 => static (a, b) => b.Value != a.Value ? b.Value.CompareTo(a.Value) : ByName(a, b),
3 => static (a, b) => b.Burden != a.Burden ? b.Burden.CompareTo(a.Burden) : ByName(a, b),
4 => static (a, b) => a.Category != b.Category ? a.Category.CompareTo(b.Category) : ByName(a, b),
5 => static (a, b) => b.Stack != a.Stack ? b.Stack.CompareTo(a.Stack) : ByName(a, b),
_ => null, // pack order: as captured (packs in order, ascending id inside each)
};
if (cmp != null) _shown.Sort(cmp);
int total = pack == WornPacks ? view.Worn.Length : one == null ? view.ItemCount
: _skipSlotItems ? one.Used : one.Items.Length;
_countText = _shown.Count == total
? total.ToString(CultureInfo.InvariantCulture) + " items"
: _shown.Count.ToString(CultureInfo.InvariantCulture) + " of " + total.ToString(CultureInfo.InvariantCulture);
// The Classic grid's caption, retail's "Contents of <pack>".
_captionText = pack == WornPacks ? "Worn"
: one == null ? (_shown.Count == total ? "All packs" : "Matches in all packs: " + _countText)
: one.IsMain ? "Contents of Backpack"
: "Contents of " + one.Name;
}
private static int ByName(InventoryItem a, InventoryItem b)
{
int c = string.CompareOrdinal(a.SearchName, b.SearchName);
return c != 0 ? c : a.Id.CompareTo(b.Id);
}
private void AddFiltered(InventoryItem[] items)
{
InventoryCategory cat = CategoryOf[_category];
foreach (InventoryItem it in items)
{
if (_skipSlotItems && it.RequiresPackSlot) continue;
if (_category != 0 && it.Category != cat) continue;
if (_searchText.Length > 0 && !it.SearchName.Contains(_searchText, StringComparison.Ordinal)) continue;
_shown.Add(it);
}
}
// ── Pack column ─────────────────────────────────────────────────────
private void PackColumn(InventoryView view, Vector2 pos, float colW, float h)
{
ImGuiNET.ImGui.SetCursorScreenPos(pos);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 2));
ImGuiNET.ImGui.BeginChild("##inv_packs", new Vector2(colW, h), ImGuiChildFlags.AlwaysUseWindowPadding);
ImGuiNET.ImGui.PopStyleVar(2);
float iw = ImGuiNET.ImGui.GetContentRegionAvail().X;
bool wide = colW > 60;
PackRow("##p_all", AllPacks, PhosphorIcons.SquaresFour, 0, "All packs", view.ItemCountText, iw, wide, DropKind.None, "");
for (int i = 0; i < view.Packs.Length; i++)
{
InventoryPack p = view.Packs[i];
ImGuiNET.ImGui.PushID(i);
PackRow("##p", p.Id, p.IsMain ? PhosphorIcons.Backpack : string.Empty, p.IsMain ? 0 : p.Id, p.Name, p.FillText,
iw, wide, DropKind.Pack, p.Name);
ImGuiNET.ImGui.PopID();
}
PackRow("##p_worn", WornPacks, PhosphorIcons.Shield, 0, "Worn", view.WornCountText, iw, wide, DropKind.Equip, "Worn");
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleColor();
}
/// <summary>One pack entry: click shows it; it is a drop target (move into it, or equip for Worn).</summary>
private void PackRow(string id, uint packId, string glyph, uint iconObject, string name, string fill, float w, bool wide,
DropKind drop, string dropName)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var sz = new Vector2(w, PackRowH);
if (ImGuiNET.ImGui.InvisibleButton(id, sz)) _pack = packId;
bool hot = ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem);
if (!wide && hot && _dragItem == null && ImGuiNET.ImGui.BeginTooltip())
{
ImGuiNET.ImGui.TextUnformatted(name);
ImGuiNET.ImGui.TextUnformatted(fill);
ImGuiNET.ImGui.EndTooltip();
}
bool on = _pack == packId;
bool dropHot = _dragItem != null && drop != DropKind.None && hot;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + sz, dropHot ? DropHot : on ? Selected : hot ? CellHot : BtnFill, 3);
dl.AddRect(p, p + sz, on || dropHot ? Teal : BtnBord, 3);
var iconMin = new Vector2(p.X + 3, p.Y + (PackRowH - Icon) * 0.5f);
if (iconObject != 0) DrawItemIcon(dl, iconObject, iconMin, Icon);
else PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), glyph, iconMin, new Vector2(Icon, Icon), on ? Teal : Mute);
if (wide)
{
float tx = p.X + Icon + 8;
dl.PushClipRect(new Vector2(tx, p.Y), p + sz, true);
dl.AddText(new Vector2(tx, p.Y + 3), on ? Teal : Text, name);
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
dl.AddText(f9, f9.FontSize * InventorySettingsStore.SizeFactor, new Vector2(tx, p.Y + PackRowH - f9.FontSize - 4), Mute, fill);
dl.PopClipRect();
}
if (drop != DropKind.None)
{
// Only the part inside the (scrolling) pack column counts: a row scrolled out of
// view must not catch a drop over the search box or the zones.
Vector2 wmin = ImGuiNET.ImGui.GetWindowPos(), wmax = wmin + ImGuiNET.ImGui.GetWindowSize();
Vector2 min = Vector2.Max(p, wmin), max = Vector2.Min(p + sz, wmax);
if (max.X > min.X && max.Y > min.Y)
_targets.Add(new Target { Min = min, Max = max, Kind = drop, Id = packId, Name = dropName });
}
}
// ── Grid ────────────────────────────────────────────────────────────
private void Grid(Vector2 pos, Vector2 size)
{
ImGuiNET.ImGui.SetCursorScreenPos(pos);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(3, 3));
ImGuiNET.ImGui.BeginChild("##inv_grid", size, ImGuiChildFlags.AlwaysUseWindowPadding);
ImGuiNET.ImGui.PopStyleVar();
// Showing one pack: dropping on the grid moves the item into that pack.
if (_pack != AllPacks && _pack != WornPacks && _builtFor?.PackOf(_pack) is InventoryPack shownPack)
{
Vector2 wmin = ImGuiNET.ImGui.GetWindowPos();
_targets.Add(new Target { Min = wmin, Max = wmin + ImGuiNET.ImGui.GetWindowSize(), Kind = DropKind.Pack,
Id = shownPack.Id, Name = shownPack.Name });
}
float avail = ImGuiNET.ImGui.GetContentRegionAvail().X;
int cols = Math.Max(1, (int)(avail / Cell));
int rows = (_shown.Count + cols - 1) / cols;
Vector2 o = ImGuiNET.ImGui.GetCursorScreenPos();
var content = new Vector2(cols * Cell, Math.Max(rows * Cell, 1));
var dl = ImGuiNET.ImGui.GetWindowDrawList();
if (_shown.Count == 0)
{
dl.AddText(o + new Vector2(4, 4), Mute, _searchText.Length > 0 || _category != 0 ? "Nothing matches." : "Empty.");
ImGuiNET.ImGui.Dummy(new Vector2(avail, 20));
}
else
{
// One button over the whole grid: hover, click, double-click, right-click and
// drag are worked out from the mouse position (no item per cell).
ImGuiNET.ImGui.InvisibleButton("##cells", content, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
bool hovered = ImGuiNET.ImGui.IsItemHovered();
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
int hoverIdx = -1;
if (hovered)
{
int c = (int)((mouse.X - o.X) / Cell), r = (int)((mouse.Y - o.Y) / Cell);
if (c >= 0 && c < cols && r >= 0 && r < rows)
{
int i = r * cols + c;
if (i < _shown.Count) hoverIdx = i;
}
}
InventoryItem? hot = hoverIdx >= 0 ? _shown[hoverIdx] : null;
_hover = hot;
if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
_selected = hot.Id;
_pressItem = hot;
_pressAt = mouse;
}
if (hot != null && ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
{
_pressItem = null;
Act(InventoryActionKind.Use, hot, 0, "", 0);
}
if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right))
{
_selected = hot.Id;
_ctxItem = hot;
_openCtx = true;
}
if (_pressItem != null && _dragItem == null && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)
&& Vector2.DistanceSquared(mouse, _pressAt) > 25)
_dragItem = _pressItem;
// Visible rows only.
Vector2 clipMin = ImGuiNET.ImGui.GetWindowPos(), clipMax = clipMin + ImGuiNET.ImGui.GetWindowSize();
int firstRow = Math.Max(0, (int)((clipMin.Y - o.Y) / Cell));
int lastRow = Math.Min(rows - 1, (int)((clipMax.Y - o.Y) / Cell));
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts
for (int r = firstRow; r <= lastRow; r++)
{
for (int c = 0; c < cols; c++)
{
int i = r * cols + c;
if (i >= _shown.Count) break;
InventoryItem it = _shown[i];
var cmin = new Vector2(o.X + c * Cell, o.Y + r * Cell);
var cmax = cmin + new Vector2(Cell - 2, Cell - 2);
bool sel = it.Id == _selected;
dl.AddRectFilled(cmin, cmax, i == hoverIdx ? CellHot : CellBg, 3);
DrawItemIcon(dl, it.Id, cmin + new Vector2(2, 2), Icon, ReferenceEquals(it, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu);
if (it.StackText.Length > 0)
{
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(it.StackText);
var tp = new Vector2(cmax.X - ts.X - 2, cmax.Y - ts.Y - 1);
dl.AddText(tp + Vector2.One, StackShadow, it.StackText);
dl.AddText(tp, StackCol, it.StackText);
}
if (sel) dl.AddRect(cmin, cmax, CellSel, 3, ImDrawFlags.None, 1.5f);
else if (it.Wielder != 0) dl.AddRect(cmin, cmax, Amber, 3);
}
}
ImGuiNET.ImGui.PopFont();
}
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleColor();
}
/// <summary>An item's icon (with underlay and overlay) from the shared icon cache, or a placeholder.</summary>
private static void DrawItemIcon(ImDrawListPtr dl, uint objectId, Vector2 min, float size, uint tint = 0xFFFFFFFF)
{
if (ScriptIcons.TryGet(ScriptIconKind.Object, objectId, out IntPtr tex))
dl.AddImage(tex, min, min + new Vector2(size, size), Vector2.Zero, Vector2.One, tint);
else
dl.AddRectFilled(min, min + new Vector2(size, size), Placeholder, 2);
}
// ── Zones: equip, drop, give ────────────────────────────────────────
private void Zones(InventoryView view, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
InventoryTarget? target = InventoryModel.Target;
InventoryItem? sel = SelectedItem(view);
float zw = (w - 8) / 3f;
var sz = new Vector2(zw, ZoneH);
Zone("##z_equip", DropKind.Equip, PhosphorIcons.Shield, "Equip", new Vector2(p.X, p.Y), sz, 0, "",
InventoryModel.WieldAvailable, sel,
"Equip: drag an item here, or click to equip the selected item.");
Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, "Drop", new Vector2(p.X + zw + 4, p.Y), sz, 0, "",
InventoryModel.DropAvailable, sel,
"Drop on the ground: drag an item here, or click to drop the selected item.");
Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, target?.ZoneLabel ?? "Give", new Vector2(p.X + 2 * (zw + 4), p.Y), sz,
target?.Id ?? 0, target?.Name ?? "", InventoryModel.GiveAvailable && target != null, sel,
target?.ZoneTip ?? "Select a creature, NPC or player in the game to give to.");
NextLine(p, ZoneH + 4);
}
private void Zone(string id, DropKind kind, string glyph, string label, Vector2 pos, Vector2 size, uint targetId,
string targetName, bool enabled, InventoryItem? selected, string tip)
{
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
bool hot = ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem);
ImGuiNET.ImGui.SetItemTooltip(tip);
bool dropHot = enabled && _dragItem != null && hot;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
uint fill = dropHot ? DropHot : _dragItem != null && enabled ? Selected : hot && enabled ? Lighten(BtnFill) : BtnFill;
dl.AddRectFilled(pos, pos + size, fill, 3);
dl.AddRect(pos, pos + size, dropHot || (_dragItem != null && enabled) ? Teal : BtnBord, 3);
uint fg = enabled ? Text : Faded(Mute);
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), glyph, pos + new Vector2(4, 0), new Vector2(18, size.Y), fg);
dl.PushClipRect(pos, pos + size, true);
dl.AddText(new Vector2(pos.X + 26, pos.Y + (size.Y - ImGuiNET.ImGui.GetFontSize()) * 0.5f), fg, label);
dl.PopClipRect();
if (enabled)
_targets.Add(new Target { Min = pos, Max = pos + size, Kind = kind, Id = targetId, Name = targetName });
if (clicked && enabled && selected != null)
DropOn(kind, targetId, targetName, selected); // refused with a message while one waits
}
private InventoryItem? SelectedItem(InventoryView view)
{
if (_selected == 0) return null;
foreach (InventoryPack p in view.Packs)
foreach (InventoryItem it in p.Items)
if (it.Id == _selected) return it;
foreach (InventoryItem it in view.Worn)
if (it.Id == _selected) return it;
return null;
}
// ── Status row ──────────────────────────────────────────────────────
private void StatusRow(float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
StatusLine(p, w, StatusH, null);
NextLine(p, StatusH);
}
/// <summary>
/// The one action waiting for the server, a refusal, or how the last action ended; when
/// there is nothing to say, the pyreals (<paramref name="idleView"/>, Classic) or a hint.
/// </summary>
private void StatusLine(Vector2 p, float w, float statusH, InventoryView? idleView)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
long now = Stopwatch.GetTimestamp();
InventoryPending? pending = InventoryModel.Pending;
InventoryResult? result = InventoryModel.LastResult;
float ty = p.Y + (statusH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.PushClipRect(p, p + new Vector2(w, statusH), true);
if (pending != null)
{
int tenths = (int)((now - pending.StartedTicks) * 10 / Stopwatch.Frequency);
int key = (int)(pending.ItemId * 31) ^ tenths ^ ((int)pending.Kind << 24)
^ (pending.WaitingForGame ? (0x40000000 ^ pending.BusyWith.GetHashCode()) : 0);
if (key != _statusKey)
{
_statusKey = key;
string secs = " " + (tenths / 10.0).ToString("0.0", CultureInfo.InvariantCulture) + "s";
// Held until the client's own item gate opens (the bot or another action has it).
_statusText = pending.WaitingForGame
? "Waiting for the game: " + pending.Label + " (busy with " + pending.BusyWith + ")" + secs
: "Waiting for the server: " + pending.Label + secs;
}
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.HourglassMedium, p, new Vector2(16, statusH), Amber);
dl.AddText(new Vector2(p.X + 18, ty), Amber, _statusText);
}
else if (_refusal.Length > 0 && (now - _refusalAt) < Stopwatch.Frequency * 4)
{
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Warning, p, new Vector2(16, statusH), Amber);
dl.AddText(new Vector2(p.X + 18, ty), Amber, _refusal);
}
else if (result != null && (now - result.AtTicks) < Stopwatch.Frequency * 8)
{
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), result.Ok ? PhosphorIcons.Check : PhosphorIcons.Warning,
p, new Vector2(16, statusH), result.Ok ? Green : Red);
dl.AddText(new Vector2(p.X + 18, ty), result.Ok ? Green : Red, result.Text);
}
else if (idleView != null)
{
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Coins, p, new Vector2(16, statusH), Amber);
dl.AddText(new Vector2(p.X + 18, ty), Text, idleView.PyrealText);
float pw = ImGuiNET.ImGui.CalcTextSize(idleView.PyrealText).X;
dl.AddText(new Vector2(p.X + 22 + pw, ty), Mute, "pyreals");
}
else
{
dl.AddText(new Vector2(p.X + 2, ty), Faded(Mute), "Double-click to use. Drag to a pack, Equip, Drop or Give. Right-click for more.");
}
dl.PopClipRect();
}
// ── Actions ─────────────────────────────────────────────────────────
private void Act(InventoryActionKind kind, InventoryItem item, uint target, string targetName, int amount)
{
var req = new InventoryRequest
{
Kind = kind, ItemId = item.Id, TargetId = target, TargetName = targetName, Amount = amount, ItemName = item.Name,
};
if (!InventoryModel.Request(req, out string why))
{
_refusal = why;
_refusalAt = Stopwatch.GetTimestamp();
}
else
{
_refusal = string.Empty;
}
}
private void DropOn(DropKind kind, uint targetId, string targetName, InventoryItem item)
{
switch (kind)
{
case DropKind.Pack:
if (item.Container == targetId && item.Wielder == 0) return; // same pack: nothing to do
if (item.RequiresPackSlot && targetId != InventoryModel.Current.PlayerId)
{
// A side pack has no pack slots (ACE: ContainerCapacity 0); the server would refuse.
Refuse(item.Name + " uses a pack slot: it can only go in the main pack.");
return;
}
Act(InventoryActionKind.Move, item, targetId, targetName, 0);
break;
case DropKind.PackSlots:
if (!item.RequiresPackSlot)
{
Refuse("Only items that use a pack slot (foci) go there. Drop it on a pack to move it.");
return;
}
if (item.Container == targetId && item.Wielder == 0) return; // already in the main pack
Act(InventoryActionKind.Move, item, targetId, targetName, 0);
break;
case DropKind.Equip:
if (item.Wielder != 0) return;
Act(InventoryActionKind.Wield, item, 0, "", 0);
break;
case DropKind.Slot:
if (item.Wielder != 0) return; // already worn (moving between slots isn't supported)
if ((item.ValidLocations & targetId) == 0)
{
Refuse(item.Name + " doesn't go in the " + targetName + " slot.");
return;
}
Act(InventoryActionKind.Wield, item, targetId, targetName, 0);
break;
case DropKind.Drop:
Act(InventoryActionKind.Drop, item, 0, "", 0);
break;
case DropKind.Give:
if (targetId != 0) Act(InventoryActionKind.Give, item, targetId, targetName, 0);
break;
}
}
private void Refuse(string why)
{
_refusal = why;
_refusalAt = Stopwatch.GetTimestamp();
}
/// <summary>
/// Would <paramref name="pack"/> refuse <paramref name="item"/> (full, or no place for it)?
/// ACE's rules (Container.TryAddToInventory): a pack-slot item takes one of the main pack's
/// pack slots (a side pack has none); anything else takes an item slot.
/// </summary>
private static bool PackRefuses(InventoryView view, InventoryPack pack, InventoryItem item)
{
if (item.Container == pack.Id && item.Wielder == 0) return false; // already there
if (item.RequiresPackSlot)
return !pack.IsMain || Math.Max(0, view.Packs.Length - 1) + view.SlotItems.Length >= view.ContainerSlots;
return pack.Used >= pack.Capacity;
}
/// <summary>Mouse released during a drag: act on the target under it (collected this frame).</summary>
private void FinishDrag()
{
if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left))
{
InventoryItem? item = _dragItem;
_dragItem = null;
_pressItem = null;
if (item == null) return;
Vector2 m = ImGuiNET.ImGui.GetMousePos();
foreach (Target t in _targets)
{
if (m.X < t.Min.X || m.Y < t.Min.Y || m.X >= t.Max.X || m.Y >= t.Max.Y) continue;
DropOn(t.Kind, t.Id, t.Name, item);
return;
}
}
}
private void DrawDragGhost()
{
if (_dragItem == null) return;
var fg = ImGuiNET.ImGui.GetForegroundDrawList();
Vector2 m = ImGuiNET.ImGui.GetMousePos() - new Vector2(Icon * 0.5f, Icon * 0.5f);
DrawItemIcon(fg, _dragItem.Id, m, Icon, 0xD0FFFFFF);
ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
}
// ── Tooltip ─────────────────────────────────────────────────────────
private void Tooltip()
{
InventoryItem? it = _hover;
if (_dragItem != null || ImGuiNET.ImGui.IsPopupOpen("", ImGuiPopupFlags.AnyPopupId)) return;
if (it == null)
{
// A pack cell, an empty paperdoll slot, the burden meter (Classic view).
if (_hoverLabel == null) return;
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
if (ImGuiNET.ImGui.BeginTooltip())
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.TextUnformatted(_hoverLabel);
ImGuiNET.ImGui.PopStyleColor();
if (_hoverLabel2 != null)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
ImGuiNET.ImGui.TextUnformatted(_hoverLabel2);
ImGuiNET.ImGui.PopStyleColor();
}
ImGuiNET.ImGui.EndTooltip();
}
ImGuiNET.ImGui.PopStyleColor(2);
return;
}
if (!ReferenceEquals(it, _tipItem))
{
_tipItem = it;
_tipBase = BaseLines(it);
}
InventoryTooltip? extra = InventoryModel.Tooltip;
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
if (ImGuiNET.ImGui.BeginTooltip())
{
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetFontSize() * 24);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.TextUnformatted(it.Name);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
foreach (string line in _tipBase) ImGuiNET.ImGui.TextUnformatted(line);
ImGuiNET.ImGui.PopStyleColor();
if (extra != null && extra.Id == it.Id)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
foreach (string line in extra.Lines) ImGuiNET.ImGui.TextUnformatted(line);
ImGuiNET.ImGui.PopStyleColor();
}
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.EndTooltip();
}
ImGuiNET.ImGui.PopStyleColor(2);
}
private static string[] BaseLines(InventoryItem it)
{
var lines = new List<string>(6);
if (it.Stack > 1)
lines.Add(it.MaxStack > 1 ? $"Stack {it.Stack:N0} of {it.MaxStack:N0}" : $"Stack {it.Stack:N0}");
lines.Add($"Value {it.Value:N0} Burden {it.Burden:N0}");
if (it.Workmanship > 0)
lines.Add("Workmanship " + it.Workmanship.ToString("0.##", CultureInfo.InvariantCulture));
if (it.Wielder != 0) lines.Add("Equipped");
if (it.IsPack) lines.Add($"Pack: {it.ItemsCapacity} slots");
if (it.RequiresPackSlot) lines.Add("Uses a pack slot (main pack only)");
return lines.ToArray();
}
// ── Context menu ────────────────────────────────────────────────────
private void ContextMenu(InventoryView view)
{
if (_openCtx)
{
_openCtx = false;
ImGuiNET.ImGui.OpenPopup("##inv_ctx");
}
PushMenuStyle();
bool open = ImGuiNET.ImGui.BeginPopup("##inv_ctx");
if (!open) { PopMenuStyle(); return; }
try
{
InventoryItem? it = _ctxItem;
if (it == null) { ImGuiNET.ImGui.CloseCurrentPopup(); return; }
bool idle = InventoryModel.Pending == null;
ImGuiNET.ImGui.TextDisabled(it.Name);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Use", "double-click", false, idle))
Act(InventoryActionKind.Use, it, 0, "", 0);
if (it.Wielder == 0 && it.ValidLocations != 0
&& ImGuiNET.ImGui.MenuItem("Equip", "", false, idle && InventoryModel.WieldAvailable))
Act(InventoryActionKind.Wield, it, 0, "", 0);
if (it.Stack > 1 && it.Wielder == 0 && ImGuiNET.ImGui.MenuItem("Split...", "", false, idle))
{
_splitItem = it;
_splitAmount = Math.Max(1, it.Stack / 2);
_splitTarget = it.Container;
_openSplit = true;
}
if (ImGuiNET.ImGui.BeginMenu("Move to", idle))
{
foreach (InventoryPack p in view.Packs)
{
bool here = p.Id == it.Container && it.Wielder == 0;
bool fits = !it.RequiresPackSlot || p.IsMain; // a focus goes in the main pack only
if (ImGuiNET.ImGui.MenuItem(p.Name, p.FillText, here, !here && fits))
Act(InventoryActionKind.Move, it, p.Id, p.Name, 0);
}
ImGuiNET.ImGui.EndMenu();
}
if (it.Wielder == 0 && ImGuiNET.ImGui.MenuItem("Drop", "", false, idle && InventoryModel.DropAvailable))
Act(InventoryActionKind.Drop, it, 0, "", 0);
InventoryTarget? target = InventoryModel.Target;
if (target != null && it.Wielder == 0
&& ImGuiNET.ImGui.MenuItem(target.MenuLabel, "", false, idle && InventoryModel.GiveAvailable))
Act(InventoryActionKind.Give, it, target.Id, target.Name, 0);
if (!idle)
ImGuiNET.ImGui.TextDisabled("(an item action is waiting)");
}
finally
{
ImGuiNET.ImGui.EndPopup();
PopMenuStyle();
}
}
// ── Split dialog ────────────────────────────────────────────────────
private void SplitDialog(InventoryView view)
{
if (_openSplit)
{
_openSplit = false;
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos(), ImGuiCond.Always);
ImGuiNET.ImGui.OpenPopup("##inv_split");
}
PushMenuStyle();
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
bool open = ImGuiNET.ImGui.BeginPopup("##inv_split");
ImGuiNET.ImGui.PopStyleVar();
if (!open) { PopMenuStyle(); return; }
try
{
InventoryItem? it = _splitItem;
// The stack may have changed or gone since the dialog opened: use the live copy.
InventoryItem? live = it == null ? null : FindById(view, it.Id);
if (live == null || live.Stack < 2)
{
ImGuiNET.ImGui.TextUnformatted("That stack is gone.");
if (Button("##sp_close", "Close", ImGuiNET.ImGui.GetCursorScreenPos(), new Vector2(80, 22), Text, BtnFill))
ImGuiNET.ImGui.CloseCurrentPopup();
ImGuiNET.ImGui.Dummy(new Vector2(80, 24));
return;
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.TextUnformatted(live.Name);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.TextUnformatted("Stack of " + live.StackText + ". Split off:");
int max = live.Stack - 1;
_splitAmount = Math.Clamp(_splitAmount, 1, max);
ImGuiNET.ImGui.SetNextItemWidth(200);
ImGuiNET.ImGui.SliderInt("##sp_slider", ref _splitAmount, 1, max);
ImGuiNET.ImGui.SetNextItemWidth(200);
ImGuiNET.ImGui.InputInt("##sp_input", ref _splitAmount, 1, 10);
_splitAmount = Math.Clamp(_splitAmount, 1, max);
ImGuiNET.ImGui.TextUnformatted("Into:");
InventoryPack? into = view.PackOf(_splitTarget);
if (into == null) { _splitTarget = live.Container; into = view.PackOf(_splitTarget); }
foreach (InventoryPack p in view.Packs)
{
if (ImGuiNET.ImGui.Selectable(p.Name + " (" + p.FillText + ")##sp" + p.Id.ToString(CultureInfo.InvariantCulture),
p.Id == _splitTarget))
_splitTarget = p.Id;
}
bool idle = InventoryModel.Pending == null;
Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4);
if (Button("##sp_ok", PhosphorIcons.Scissors + " Split", bp, new Vector2(96, 24), Teal, BtnFill, enabled: idle && into != null))
{
Act(InventoryActionKind.Split, live, _splitTarget, into?.Name ?? "", _splitAmount);
ImGuiNET.ImGui.CloseCurrentPopup();
}
if (Button("##sp_cancel", "Cancel", bp + new Vector2(102, 0), new Vector2(80, 24), Text, BtnFill))
ImGuiNET.ImGui.CloseCurrentPopup();
ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28));
ImGuiNET.ImGui.Dummy(new Vector2(200, 0));
}
finally
{
ImGuiNET.ImGui.EndPopup();
PopMenuStyle();
}
}
private static InventoryItem? FindById(InventoryView view, uint id)
{
foreach (InventoryPack p in view.Packs)
foreach (InventoryItem it in p.Items)
if (it.Id == id) return it;
return null;
}
private static void PushMenuStyle()
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Header, Selected);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, Lighten(BtnFill));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
}
private static void PopMenuStyle()
{
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(7);
}
}

View file

@ -0,0 +1,250 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/ItemsFace.cs
// ImGui face of the Items panel (UI/Panels/ItemsPanel.cs): weapons (name,
// element, Del), consumables (name, type, Del), each with "Add Selected",
// and mana stone tapping (on/off, keep count, min max-mana to tap).
//
// Edits change a private copy and save the whole payload (ItemsCommands,
// pump thread). A newer snapshot replaces the copy; snapshots from before
// the last save are ignored so an edit never flickers back.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
using RynthCore.Engine.UI.Panels;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class ItemsFace : IImGuiPanel
{
public const string Title = "Items";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(420, 520), new Vector2(340, 260), EdgeToEdge: true),
() => new ItemsFace());
private static readonly uint OnBg = RynthTheme.Argb(0xFF104010), OnText = RynthTheme.Argb(0xFF33FF33);
private ItemsPanel.Payload _data = new();
private long _seenVersion = -1, _savedAtVersion = -1;
private readonly Picker _picker = new("##items_pick");
public void OnShown()
{
UiSources.Items.Subscribe();
UiSources.Items.RequestRefresh();
}
public void OnHidden() => UiSources.Items.Unsubscribe();
public void Draw()
{
TakeSnapshot();
float w = Begin(out Vector2 origin, out Vector2 size);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
ImGuiNET.ImGui.BeginChild("##items_body", new Vector2(w, Math.Max(60, Remaining(origin, size))));
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
// Weapons
Section("Weapons", bw);
if (_data.Weapons.Count == 0) Empty("No weapons configured", bw);
else
{
TableHeader("Element", bw);
for (int i = 0; i < _data.Weapons.Count; i++)
{
ItemsPanel.WeaponEntry wpn = _data.Weapons[i];
ImGuiNET.ImGui.PushID("w" + i);
int r = Row(wpn.Name, wpn.Element, i, bw);
ImGuiNET.ImGui.PopID();
if (r == 1)
{
Vector2 at = ImGuiNET.ImGui.GetIO().MousePos;
_picker.Open(at, ItemsCommands.Elements, Array.IndexOf(ItemsCommands.Elements, wpn.Element), e =>
{
wpn.Element = ItemsCommands.Elements[e];
Save();
}, 160);
}
else if (r == 2)
{
_data.Weapons.RemoveAt(i);
Save();
break;
}
}
}
AddSelected("##add_weapon", PhosphorIcons.Plus + " Add Selected Weapon", "(select a weapon in inventory first)", ItemsCommands.AddSelectedWeapon);
Divider(bw);
// Consumables
Section("Consumable Items", bw);
if (_data.Consumables.Count == 0) Empty("No consumables configured", bw);
else
{
TableHeader("Type", bw);
for (int i = 0; i < _data.Consumables.Count; i++)
{
ItemsPanel.ConsumableEntry c = _data.Consumables[i];
ImGuiNET.ImGui.PushID("c" + i);
int r = Row(c.Name, c.Type, i, bw);
ImGuiNET.ImGui.PopID();
if (r == 1)
{
Vector2 at = ImGuiNET.ImGui.GetIO().MousePos;
_picker.Open(at, ItemsCommands.ConsumableTypes, Array.IndexOf(ItemsCommands.ConsumableTypes, c.Type), t =>
{
c.Type = ItemsCommands.ConsumableTypes[t];
Save();
}, 160);
}
else if (r == 2)
{
_data.Consumables.RemoveAt(i);
Save();
break;
}
}
}
AddSelected("##add_consumable", PhosphorIcons.Plus + " Add Selected Consumable", "(select an item in inventory first)", ItemsCommands.AddSelectedConsumable);
Divider(bw);
// Mana stone tapping
Section("Mana Stone Tapping", bw);
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 4);
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float ty = p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.AddText(new Vector2(p.X, ty), Text, "Enable Tapping");
float x = p.X + ImGuiNET.ImGui.CalcTextSize("Enable Tapping").X + 6;
bool on = _data.EnableManaTapping;
if (Button("##tap", on ? "ON" : "OFF", new Vector2(x, p.Y), new Vector2(50, 22), on ? OnText : Mute, on ? OnBg : BtnFill))
{
_data.EnableManaTapping = !on;
Save();
}
x += 66;
dl.AddText(new Vector2(x, ty), Text, "Keep count:");
x += ImGuiNET.ImGui.CalcTextSize("Keep count:").X + 6;
int keep = Spinner("##keep", _data.ManaStoneKeepCount, 1, 999, new Vector2(x, p.Y));
if (keep != _data.ManaStoneKeepCount) { _data.ManaStoneKeepCount = keep; Save(); }
NextLine(new Vector2(p.X - 4, p.Y - 4), 30);
if (_data.EnableManaTapping)
{
p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 0);
dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, "Min MaxMana to tap:");
float sx = p.X + ImGuiNET.ImGui.CalcTextSize("Min MaxMana to tap:").X + 6;
int min = Spinner("##minmana", _data.ManaTapMinMana, 100, 99999, new Vector2(sx, p.Y));
if (min != _data.ManaTapMinMana) { _data.ManaTapMinMana = min; Save(); }
NextLine(new Vector2(p.X - 4, p.Y), 28);
}
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
End(origin, size);
_picker.Draw();
}
private void TakeSnapshot()
{
var snap = UiSources.Items.Current;
if (snap == null || snap.Version == _seenVersion || snap.Version <= _savedAtVersion) return;
_seenVersion = snap.Version;
_data = snap.Value.ParseCopy();
}
private void Save()
{
_savedAtVersion = UiSources.Items.Current?.Version ?? _savedAtVersion;
ItemsCommands.SetJson(ItemsCommands.Serialize(_data));
}
// ── Pieces ───────────────────────────────────────────────────────────
private static void Section(string title, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
float h = bold.FontSize + 8;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + new Vector2(w, h), Selected);
dl.AddText(bold, bold.FontSize, p + new Vector2(8, 4), Amber, title);
ImGuiNET.ImGui.Dummy(new Vector2(w, h));
}
private static void TableHeader(string column, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + new Vector2(w, 22), Selected);
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
float ty = p.Y + (22 - bold.FontSize) * 0.5f;
dl.AddText(bold, bold.FontSize, new Vector2(p.X + 6, ty), Text, "Item Name");
dl.AddText(bold, bold.FontSize, new Vector2(p.X + w - 146 + 6, ty), Text, column);
ImGuiNET.ImGui.Dummy(new Vector2(w, 22));
}
private static void Empty(string message, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(p, p + new Vector2(w, 22), RowAlt);
ImGuiNET.ImGui.GetWindowDrawList().AddText(p + new Vector2(8, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, message);
ImGuiNET.ImGui.Dummy(new Vector2(w, 22));
}
/// <summary>Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0.</summary>
private static int Row(string name, string value, int index, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + new Vector2(w, 24), index % 2 == 0 ? RowAlt : PanelBg);
float nameW = w - 146;
dl.PushClipRect(p, p + new Vector2(nameW, 24), true);
dl.AddText(new Vector2(p.X + 6, p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, name);
dl.PopClipRect();
int result = 0;
if (Button("##pick", value, new Vector2(p.X + nameW + 2, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1;
if (IconButton("##del", PhosphorIcons.Trash, new Vector2(p.X + nameW + 102, p.Y + 2), new Vector2(42, 20), Red, BtnFill)) result = 2;
ImGuiNET.ImGui.SetItemTooltip("Remove");
NextLine(p, 24);
return result;
}
private static void AddSelected(string id, string label, string hint, Action onClick)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 4);
float bw = ButtonWidth(label) + 4;
if (Button(id, label, p, new Vector2(bw, 24), Teal, BtnFill)) onClick();
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
ImGuiNET.ImGui.GetWindowDrawList().AddText(f9, f9.FontSize, new Vector2(p.X + bw + 8, p.Y + (24 - f9.FontSize) * 0.5f), Mute, hint);
NextLine(new Vector2(p.X - 4, p.Y - 4), 32);
}
private static void Divider(float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
Separator(w);
}
/// <summary>[-] value [+]; returns the new value (same when nothing was clicked).</summary>
private static int Spinner(string id, int value, int min, int max, Vector2 pos)
{
int v = value;
ImGuiNET.ImGui.PushID(id);
if (IconButton("##dec", PhosphorIcons.Minus, pos, new Vector2(22, 22), Teal, BtnFill)) v = Math.Max(min, v - 1);
string text = v.ToString(CultureInfo.InvariantCulture);
float tw = ImGuiNET.ImGui.CalcTextSize(text).X;
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(pos.X + 24 + (60 - tw) * 0.5f, pos.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, text);
if (IconButton("##inc", PhosphorIcons.Plus, new Vector2(pos.X + 86, pos.Y), new Vector2(22, 22), Teal, BtnFill)) v = Math.Min(max, v + 1);
ImGuiNET.ImGui.PopID();
return v;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,577 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/LuaFace.cs
// ImGui face of the Lua panel. Two layouts, picked by the payload:
//
// RynthLua v2 (ScriptInfos present), tabs "Scripts" | "Editor", and on the
// right "N running · RynthAi: loaded / not loaded":
// Scripts one row per script: running dot, name, description, autostart
// (Off / global / this character), Run|Stop, Restart. Click a row
// to select it; below, the selected script's state, "Open in
// editor", its console (Copy, Clear) and a line that runs Lua
// inside it (execin).
// Editor status + Run/Stop for the editor's script (the name box, else
// "editor"), name + Save/New/Delete, the coloured editor
// (CodeEditor, Lua) and the selected script's console.
// Old single-script payload (RynthAi's exports) or no plugin: the v1 face,
// status + Run/Stop, script buttons (click to open), name row, editor,
// console; "Lua: RynthLua not connected" until a plugin answers.
//
// Data: UiSources.Lua (hub) and LuaCommands. The editor takes a script when
// the plugin reports a new load (LoadSeq); on first open it restores the
// plugin's last script only if the editor is empty. Text leaves the editor
// only on Run/Save. The payload's Console is the selected script's.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class LuaFace : IImGuiPanel
{
public const string Title = "Lua";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(420, 560), new Vector2(380, 360), EdgeToEdge: true, GripInBody: true),
() => new LuaFace());
private static readonly uint ConsoleBg = RynthTheme.Argb(0xFF05090D), DotOff = RynthTheme.Argb(0xFF4D5A66);
private const string NotConnected = "Lua: RynthLua not connected";
/// <summary>RynthLua's description for a running script that has no file (the editor, /lua exec).</summary>
private const string NotSaved = "(not saved)";
private const float RowH = 26;
private static readonly string[] AutoCodes = { "none", "global", "character" };
private static readonly string[] AutoItems = { "Off", "Every character (global)", "This character" };
private LuaPayload? _data;
private long _seenVersion = -1;
private int _lastLoadSeq = -1, _lastConsoleSeq = -1;
private string _lastSelected = string.Empty;
private bool _firstFetch = true, _scrollConsole;
private string _status = NotConnected;
private bool _running;
private string _note = string.Empty; // local hint ("Type a script name first.")
private bool _editorTab;
private string _editorSelectSent = string.Empty; // Editor tab: last "select" sent for its script
private bool _focusExec;
private readonly byte[] _name = new byte[128];
private readonly byte[] _exec = new byte[1024];
private readonly Picker _picker = new("##lua_pick");
private CodeEditor? _editor;
public void OnShown()
{
UiSources.Lua.Subscribe();
UiSources.Lua.RequestRefresh();
}
public void OnHidden()
{
UiSources.Lua.Unsubscribe();
_editor?.Dispose();
_editor = null;
}
public void Draw()
{
_editor ??= new CodeEditor("##lua_source", CodeLanguage.Lua, CodeEditor.RynthPalette());
TakeSnapshot();
float w = Begin(out Vector2 origin, out Vector2 size);
LuaPayload? d = _data;
if (d?.ScriptInfos is { } infos)
{
Header(w, d);
if (_editorTab) EditorView(w, origin, size, d, infos);
else ScriptsView(w, origin, size, d, infos);
}
else
LegacyView(w, origin, size);
End(origin, size);
_picker.Draw();
}
private void TakeSnapshot()
{
var snap = UiSources.Lua.Current;
if (snap == null)
{
// Plugins unloaded (RL): back to "not connected" until one answers again.
if (_data != null)
{
_data = null;
_seenVersion = -1;
_running = false;
_status = NotConnected;
}
return;
}
if (snap.Version == _seenVersion) return;
_seenVersion = snap.Version;
LuaPayload d = _data = snap.Value;
_running = d.Running;
_status = d.Running
? $"Running: {(d.ScriptName.Length > 0 ? d.ScriptName : "(editor)")}"
: d.Status.Length > 0 ? d.Status : "Lua: idle";
// A newly loaded script goes into the editor; on first open only if it's empty.
if (d.LoadSeq != _lastLoadSeq)
{
bool take = !_firstFetch || _editor!.GetText().Length == 0;
_lastLoadSeq = d.LoadSeq;
if (take)
{
_editor!.SetText(d.LoadedText);
WriteUtf8(_name, d.LoadedName);
}
}
string selected = d.Selected ?? string.Empty;
if (d.ConsoleSeq != _lastConsoleSeq || selected != _lastSelected)
{
_lastConsoleSeq = d.ConsoleSeq;
_lastSelected = selected;
_scrollConsole = true;
_note = string.Empty;
}
_firstFetch = false;
}
private const string ScriptsTab = PhosphorIcons.Files + " Scripts", EditorTab = PhosphorIcons.PencilSimple + " Editor";
private const string RunLabel = PhosphorIcons.Play + " Run", StopLabel = PhosphorIcons.Stop + " Stop",
RestartLabel = PhosphorIcons.ArrowCounterClockwise + " Restart";
// ── v2: header ───────────────────────────────────────────────────────
// [Scripts][Editor] N running · RynthAi: loaded
private void Header(float w, LuaPayload d)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const float h = 24;
float sw = ButtonWidth(ScriptsTab) + 4, ew = ButtonWidth(EditorTab) + 4;
if (Button("##tab_scripts", ScriptsTab, p, new Vector2(sw, h), _editorTab ? Text : Teal, _editorTab ? BtnFill : Selected))
_editorTab = false;
if (Button("##tab_editor", EditorTab, new Vector2(p.X + sw + 2, p.Y), new Vector2(ew, h), _editorTab ? Teal : Text, _editorTab ? Selected : BtnFill))
_editorTab = true;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
bool ai = d.RynthAi == true;
string run = d.RunningCount == 1 ? "1 running" : $"{d.RunningCount} running";
const string sep = " · ";
string aiText = ai ? "RynthAi: loaded" : "RynthAi: not loaded";
float runW = ImGuiNET.ImGui.CalcTextSize(run).X, sepW = ImGuiNET.ImGui.CalcTextSize(sep).X, aiW = ImGuiNET.ImGui.CalcTextSize(aiText).X;
float left = p.X + sw + ew + 10, right = p.X + w;
float x = Math.Max(left, right - runW - sepW - aiW);
float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.PushClipRect(new Vector2(left, p.Y), new Vector2(right, p.Y + h), true);
dl.AddText(new Vector2(x, ty), d.RunningCount > 0 ? Green : Mute, run);
dl.AddText(new Vector2(x + runW, ty), Mute, sep);
dl.AddText(new Vector2(x + runW + sepW, ty), ai ? Green : Amber, aiText);
dl.PopClipRect();
if (ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x + runW + sepW, p.Y), new Vector2(right, p.Y + h)))
ImGuiNET.ImGui.SetTooltip(ai
? "RynthAi's script interface is there: scripts can use its macro, nav and meta features."
: "RynthAi isn't loaded (or is too old): scripts' RynthAi calls won't work.");
NextLine(p, h + 2);
}
// ── v2: Scripts tab ──────────────────────────────────────────────────
private void ScriptsView(float w, Vector2 origin, Vector2 size, LuaPayload d, List<LuaScriptInfo> infos)
{
string sel = d.Selected ?? string.Empty;
ScriptList(w, Remaining(origin, size), infos, sel);
LuaScriptInfo? si = Find(infos, sel);
SelectedRow(w, d, sel, si);
// Console, then the exec line: Dummy+header (30) + child + spacing (4) + line (22).
float consoleH = Math.Max(40, Remaining(origin, size) - 56);
Console(w, consoleH, sel.Length > 0 ? "Console · " + sel : "Console");
ExecRow(w, sel, si?.Running == true);
}
private void ScriptList(float w, float avail, List<LuaScriptInfo> infos, string selected)
{
int n = infos.Count;
float listMax = Math.Max(RowH * 2 + 4, avail * 0.42f);
float listH = Math.Clamp(Math.Max(1, n) * RowH + 4, RowH + 4, listMax);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
ImGuiNET.ImGui.BeginChild("##lua_list", new Vector2(w, listH), ImGuiChildFlags.Borders | ImGuiChildFlags.AlwaysUseWindowPadding);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(2);
float rw = ImGuiNET.ImGui.GetContentRegionAvail().X;
if (n == 0)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.GetWindowDrawList().AddText(p + new Vector2(8, (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute,
"No scripts yet: write one in the Editor tab and Save.");
ImGuiNET.ImGui.Dummy(new Vector2(rw, RowH));
}
for (int i = 0; i < n; i++)
{
ImGuiNET.ImGui.PushID(i);
ScriptRow(infos[i], i, rw, selected);
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
}
// (dot) Name description ........ [Auto: off] [Run] [Restart]
private void ScriptRow(LuaScriptInfo info, int index, float w, string selected)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
bool isSel = info.Name.Equals(selected, StringComparison.OrdinalIgnoreCase);
bool notSaved = IsNotSaved(info);
const float autoW = 74, runW = 50, restartW = 64, gap = 3;
float nameW = Math.Max(40, w - (autoW + runW + restartW + gap * 3 + 2));
dl.AddRectFilled(p, p + new Vector2(w, RowH), isSel ? Selected : index % 2 == 0 ? RowAlt : PanelBg);
ImGuiNET.ImGui.SetCursorScreenPos(p);
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(nameW, RowH)) && !isSel)
LuaCommands.Send("select", info.Name);
if (ImGuiNET.ImGui.IsItemHovered())
{
if (!isSel) dl.AddRectFilled(p, p + new Vector2(nameW, RowH), BtnFill);
ImGuiNET.ImGui.SetTooltip(RowTooltip(info, notSaved));
}
if (isSel) dl.AddRectFilled(p, p + new Vector2(2, RowH), Teal);
float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.AddCircleFilled(new Vector2(p.X + 11, p.Y + RowH * 0.5f), 4, info.Running ? Green : DotOff);
dl.PushClipRect(p, p + new Vector2(nameW - 4, RowH), true);
dl.AddText(new Vector2(p.X + 21, ty), isSel ? Teal : Text, info.Name);
if (info.Description.Length > 0)
dl.AddText(new Vector2(p.X + 21 + ImGuiNET.ImGui.CalcTextSize(info.Name).X + 8, ty), Faded(Mute), info.Description);
dl.PopClipRect();
float x = p.X + nameW, by = p.Y + 3, bh = RowH - 6;
bool auto = info.Autostart is "global" or "character";
if (Button("##auto", AutoLabel(info.Autostart), new Vector2(x, by), new Vector2(autoW, bh), auto ? Teal : Mute, BtnFill, enabled: !notSaved))
{
string name = info.Name;
// Before login there's no character to autostart for: only off / global.
string[] items = _data?.LoggedIn == false ? AutoItems[..2] : AutoItems;
_picker.Open(new Vector2(x, by + bh + 2), items, Array.IndexOf(AutoCodes, info.Autostart),
k => LuaCommands.Send("autostart", name, AutoCodes[k]), 190);
}
ImGuiNET.ImGui.SetItemTooltip(notSaved
? "Save it to a file to autostart it."
: "Start at login: off, on every character (global), or on this character only.");
x += autoW + gap;
if (info.Running)
{
if (Button("##run", StopLabel, new Vector2(x, by), new Vector2(runW, bh), Text, StopBg))
LuaCommands.Send("stopScript", info.Name);
}
else if (Button("##run", RunLabel, new Vector2(x, by), new Vector2(runW, bh), Text, StartBg, enabled: !notSaved))
LuaCommands.Send("start", info.Name);
x += runW + gap;
if (Button("##restart", RestartLabel, new Vector2(x, by), new Vector2(restartW, bh), Text, BtnFill, enabled: info.Running && !notSaved))
LuaCommands.Send("restart", info.Name);
ImGuiNET.ImGui.SetItemTooltip(notSaved ? "Not saved: run it again from the Editor." : "Stop it and start it again from its file.");
NextLine(p, RowH);
}
private static bool IsNotSaved(LuaScriptInfo info) => info.Transient || info.Description == NotSaved;
private static string RowTooltip(LuaScriptInfo info, bool notSaved)
{
string kind = notSaved ? "Not saved (the editor or /lua exec)"
: info.IsFolder ? $"Folder script ({info.Name}\\index.lua)" : $"Single file ({info.Name}.lua)";
string desc = notSaved || info.Description.Length == 0 ? string.Empty : info.Description + "\n";
return $"{info.Name}\n{desc}{kind}\nClick to show its console.";
}
private static string AutoLabel(string autostart) => autostart switch
{
"global" => "Auto: all",
"character" => "Auto: char",
_ => "Auto: off",
};
// name running | stopped (status) [Open in editor]
private void SelectedRow(float w, LuaPayload d, string sel, LuaScriptInfo? si)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const float h = 22;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
if (sel.Length == 0)
{
dl.AddText(p + new Vector2(0, (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "Click a script to see its console.");
NextLine(p, h);
return;
}
const string open = PhosphorIcons.PencilSimple + " Open in editor";
float bw = ButtonWidth(open);
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
ImGuiNET.ImGui.PushFont(bold);
float nameW = ImGuiNET.ImGui.CalcTextSize(sel).X;
ImGuiNET.ImGui.PopFont();
bool running = si?.Running == true;
string state = running ? "running"
: d.ScriptName.Equals(sel, StringComparison.OrdinalIgnoreCase) && d.Status.Length > 0 ? d.Status : "stopped";
dl.PushClipRect(p, p + new Vector2(w - bw - 6, h), true);
dl.AddText(bold, bold.FontSize, p + new Vector2(0, (h - bold.FontSize) * 0.5f), Teal, sel);
dl.AddText(p + new Vector2(nameW + 10, (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), running ? Green : Amber, state);
dl.PopClipRect();
bool canOpen = si != null && !IsNotSaved(si);
if (Button("##open", open, new Vector2(p.X + w - bw, p.Y), new Vector2(bw, h), Text, BtnFill, enabled: canOpen))
{
LuaCommands.Send("load", sel);
_editorTab = true;
}
ImGuiNET.ImGui.SetItemTooltip(canOpen
? (si!.IsFolder ? "Edit its index.lua in the Editor tab." : "Edit it in the Editor tab.")
: "It has no file to open.");
NextLine(p, h);
}
// [Lua to run inside <script>...] [Exec]
private void ExecRow(float w, string sel, bool canExec)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const float bw = 50;
string hint = sel.Length == 0 ? "Select a script to run code in it"
: canExec ? $"Lua to run inside {sel} (Enter)" : $"Start {sel} to run code in it";
if (_focusExec)
{
ImGuiNET.ImGui.SetKeyboardFocusHere();
_focusExec = false;
}
// The row sits on the body's bottom edge: it stops short of the resize grip (GripInBody).
float grip = ImGuiPanelHost.BodyGripReserve;
bool enter = TextBox("##lua_exec", _exec, p, w - bw - 4 - grip, hint, out _, ImGuiInputTextFlags.EnterReturnsTrue);
bool click = Button("##exec", "Exec", new Vector2(p.X + w - bw - grip, p.Y), new Vector2(bw, 22), Text, BtnFill, enabled: canExec);
ImGuiNET.ImGui.SetItemTooltip("Runs the line inside the selected script: its globals, its state.");
if ((enter || click) && canExec)
{
string code = Utf8(_exec).Trim();
if (code.Length > 0)
{
LuaCommands.Send("execin", sel, code);
_exec[0] = 0;
}
_focusExec = enter; // Enter leaves the box; keep typing in it
}
NextLine(p, 22);
}
// ── v2: Editor tab ───────────────────────────────────────────────────
private void EditorView(float w, Vector2 origin, Vector2 size, LuaPayload d, List<LuaScriptInfo> infos)
{
// RynthLua runs the editor text as a script named by the name box, else "editor".
string edName = Utf8(_name).Trim();
string runName = edName.Length > 0 ? edName : "editor";
LuaScriptInfo? ei = Find(infos, runName);
bool running = ei?.Running == true;
// Always say which script the editor holds: the Scripts tab's selection doesn't change it
// (only "Open in editor" does), so the name here is the one Run/Save act on.
string editing = "Editing: " + runName + (_editor?.IsDirty == true ? " (unsaved)" : "");
string status = running ? editing + " · running"
: d.ScriptName.Equals(runName, StringComparison.OrdinalIgnoreCase) && d.Status.Length > 0 ? editing + " · " + d.Status
: editing;
// The console below follows the editor's script, not whatever was last clicked on the
// Scripts tab. Select it once per change of name (selecting also moves the Scripts tab).
if (ei != null && !runName.Equals(d.Selected ?? string.Empty, StringComparison.OrdinalIgnoreCase)
&& !runName.Equals(_editorSelectSent, StringComparison.OrdinalIgnoreCase))
{
LuaCommands.Send("select", ei.Name);
_editorSelectSent = runName;
}
else if (runName.Equals(d.Selected ?? string.Empty, StringComparison.OrdinalIgnoreCase))
_editorSelectSent = string.Empty;
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
const float bw = 64;
float statusW = w - 2 * (bw + 4);
dl.PushClipRect(p, p + new Vector2(statusW, 24), true);
dl.AddText(bold, bold.FontSize, p + new Vector2(0, (24 - bold.FontSize) * 0.5f), running ? Green : Amber, status);
dl.PopClipRect();
if (Button("##run", RunLabel, new Vector2(p.X + statusW + 4, p.Y), new Vector2(bw, 24), Text, StartBg))
LuaCommands.Send("run", edName, _editor?.GetText() ?? string.Empty);
ImGuiNET.ImGui.SetItemTooltip("Run the editor's text as " + runName + " (replaces a running copy).");
if (Button("##stop", StopLabel, new Vector2(p.X + statusW + bw + 8, p.Y), new Vector2(bw, 24), Text, StopBg, enabled: running))
LuaCommands.Send("stopScript", runName);
NextLine(p, 24);
bool folder = ei?.IsFolder == true;
NameRow(w, canDelete: !folder, saveTip: folder ? "Saves its index.lua." : null,
deleteTip: folder ? "Folder scripts are deleted in Explorer." : "Renames it to .lua.bak.");
EditorAndConsole(w, origin, size, 120, ei != null ? "Console · " + ei.Name
: d.Selected is { Length: > 0 } s ? "Console · " + s : "Console");
}
// ── v1: old single-script payload / not connected ────────────────────
private void LegacyView(float w, Vector2 origin, Vector2 size)
{
TopRow(w);
Scripts(w);
NameRow(w, canDelete: true, saveTip: null, deleteTip: null);
EditorAndConsole(w, origin, size, 150, "Console");
}
// Status | Run Stop
private void TopRow(float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
const float bw = 64;
float statusW = w - 2 * (bw + 4);
dl.PushClipRect(p, p + new Vector2(statusW, 24), true);
dl.AddText(bold, bold.FontSize, p + new Vector2(0, (24 - bold.FontSize) * 0.5f), _running ? Green : Amber, _status);
dl.PopClipRect();
if (Button("##run", RunLabel, new Vector2(p.X + statusW + 4, p.Y), new Vector2(bw, 24), Text, StartBg))
LuaCommands.Send("run", Utf8(_name).Trim(), _editor?.GetText() ?? string.Empty);
if (Button("##stop", StopLabel, new Vector2(p.X + statusW + bw + 8, p.Y), new Vector2(bw, 24), Text, StopBg))
LuaCommands.Send("stop");
NextLine(p, 24);
}
// "Scripts (click to open):" then one button per script, wrapping.
private void Scripts(float w)
{
Label("Scripts (click to open):", Mute);
var scripts = _data?.Scripts;
if (scripts == null || scripts.Count == 0)
{
Label("(none yet: write one and Save)", Mute);
return;
}
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
float x = start.X, y = start.Y;
for (int i = 0; i < scripts.Count; i++)
{
string s = scripts[i];
float bw = ButtonWidth(s);
if (x > start.X && x + bw > start.X + w) { x = start.X; y += 26; }
ImGuiNET.ImGui.PushID(i);
if (Button("##s", s, new Vector2(x, y), new Vector2(bw, 22), Text, BtnFill))
LuaCommands.Send("load", s);
ImGuiNET.ImGui.PopID();
x += bw + 4;
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(start.X, y + 22));
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
// ── Shared pieces ────────────────────────────────────────────────────
// [name] Save New Delete
private void NameRow(float w, bool canDelete, string? saveTip, string? deleteTip)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const float bw = 58;
float boxW = w - 3 * (bw + 4);
TextBox("##lua_name", _name, p, boxW, "Script name...", out _);
float x = p.X + boxW + 4;
if (Button("##save", PhosphorIcons.FloppyDisk + " Save", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill))
{
string name = Utf8(_name).Trim();
if (name.Length == 0) _note = "Type a script name first.";
else
{
LuaCommands.Send("save", name, _editor?.GetText() ?? string.Empty);
_editor?.MarkClean();
}
}
if (saveTip != null) ImGuiNET.ImGui.SetItemTooltip(saveTip);
x += bw + 4;
if (Button("##new", PhosphorIcons.FilePlus + " New", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill))
{
_editor?.SetText(string.Empty);
Array.Clear(_name);
}
x += bw + 4;
if (Button("##delete", PhosphorIcons.Trash + " Delete", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill, enabled: canDelete))
{
string name = Utf8(_name).Trim();
if (name.Length > 0) LuaCommands.Send("delete", name);
}
if (deleteTip != null) ImGuiNET.ImGui.SetItemTooltip(deleteTip);
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
// The editor takes what the console leaves.
private void EditorAndConsole(float w, Vector2 origin, Vector2 size, float consoleH, string consoleTitle)
{
// The console below scrolls: the pair ends above the resize grip (GripInBody).
float editorH = Math.Max(80, Remaining(origin, size) - consoleH - 34 - GripOverlap());
if (!CodeEditor.Available)
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE04848), "The script editor needs the new cimgui.dll (a full RynthCore deploy).");
else
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Code12));
_editor!.Render(new Vector2(w, editorH));
ImGuiNET.ImGui.PopFont();
}
Console(w, consoleH, consoleTitle);
}
// Console [Copy] [Clear], then the output (green, wrapped, follows new lines).
private void Console(float w, float height, string title)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.PushClipRect(p, p + new Vector2(w - 122, 22), true);
dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, title);
dl.PopClipRect();
if (Button("##copy", PhosphorIcons.Copy + " Copy", new Vector2(p.X + w - 116, p.Y), new Vector2(56, 22), Text, BtnFill))
ImGuiNET.ImGui.SetClipboardText(_data?.Console ?? string.Empty);
if (Button("##clear", PhosphorIcons.Eraser + " Clear", new Vector2(p.X + w - 56, p.Y), new Vector2(56, 22), Text, BtnFill))
LuaCommands.Send("clearConsole");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 24));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, ConsoleBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4));
ImGuiNET.ImGui.BeginChild("##lua_console", new Vector2(w, height), ImGuiChildFlags.Borders | ImGuiChildFlags.AlwaysUseWindowPadding);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(2);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono10));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Green);
ImGuiNET.ImGui.PushTextWrapPos(0);
string text = _data?.Console ?? string.Empty;
if (text.Length > 0) ImGuiNET.ImGui.TextUnformatted(text);
if (_note.Length > 0) ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "[panel] " + _note);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.PopFont();
if (_scrollConsole)
{
ImGuiNET.ImGui.SetScrollHereY(1f);
_scrollConsole = false;
}
ImGuiNET.ImGui.EndChild();
}
private static LuaScriptInfo? Find(List<LuaScriptInfo> infos, string name)
{
if (name.Length == 0) return null;
foreach (LuaScriptInfo i in infos)
if (i.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return i;
return null;
}
}

View file

@ -0,0 +1,457 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/MetaFace.Schedule.cs
// The Meta panel's Schedule view: RynthAi's Meta Manager, which loads a meta
// when a timer runs out (RynthSuite Docs/META_MANAGER.md).
//
// [x Manager] Poll [5] min [poll now] Wait [60] s Gap [30] s [x While stopped]
// 34 quests, polled 2m ago . last: farm.af (quest x ready)
// # [on] [up][dn] [edit][del] when quest x ready -> farm.af ready | 12m 30s
// ...
// [+ New Rule] first match: amber edge
//
// Data: the "schedule" object of the Meta snapshot (UiSources.Meta). Every
// change is an mm_* MetaCommand, applied by RynthAi on its tick; nothing here
// loads a meta or sends chat. Times are absolute (unix ms) in the snapshot,
// so the countdowns tick here between snapshots.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed partial class MetaFace
{
private const string ScheduleLabel = PhosphorIcons.HourglassMedium + " Schedule##mode_sch";
private static readonly string[] TriggerNames =
{
"Quest ready (/myquests timer)", "After N minutes on the meta", "Every N minutes", "Countdown (you start it)",
};
// Rule editor: -2 closed, -1 new rule, else the rule's index.
private int _schedEdit = -2;
private ScheduleRuleDto _schedRule = new();
private readonly byte[] _schedQuest = new byte[128];
private readonly byte[] _schedMinutes = new byte[16];
private readonly byte[] _schedPoll = new byte[8], _schedWait = new byte[8], _schedGap = new byte[8];
private long _schedFieldsVersion = -1; // snapshot the number boxes were last filled from
private string[] _schedMetaPicks = Array.Empty<string>(), _schedOnlyPicks = Array.Empty<string>();
private void ShowSchedule()
{
_view = View.Schedule;
_schedEdit = -2;
}
private void ScheduleView(Vector2 origin, Vector2 size)
{
float w = size.X;
SchedulePayload? sc = _data.Schedule;
ModeRow(w, source: false, schedule: true);
Separator(w);
if (sc == null)
{
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " This RynthAi has no Meta Manager (update RynthAi).");
return;
}
RefreshScheduleFields(sc);
if (_schedEdit != -2)
{
ScheduleEditor(sc, size.Y - (ImGuiNET.ImGui.GetCursorScreenPos().Y - origin.Y) - FaceKit.GripOverlap());
return;
}
ScheduleSettings(sc, w);
ScheduleStatusLine(sc, w);
Separator(w);
const float bottomH = 24;
float listH = Math.Max(40, origin.Y + size.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - bottomH - 9);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
ImGuiNET.ImGui.BeginChild("##sched_rules", new Vector2(w, listH));
ScheduleRules(sc, ImGuiNET.ImGui.GetContentRegionAvail().X);
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
Separator(w);
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const float newW = 80;
if (Button(PhosphorIcons.Plus + " New Rule##sched_new", new Vector2(p.X, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green))
OpenScheduleEditor(-1, new ScheduleRuleDto { Meta = FirstMetaFile() });
if (sc.Rules.Count > 0)
{
if (Button(PhosphorIcons.ArrowCounterClockwise + " Re-arm all##sched_reset", new Vector2(p.X + newW + 4, p.Y), new Vector2(86, 24),
Mute, BtnFill, BtnBord))
MetaCommands.Simple("mm_reset", -1);
ImGuiNET.ImGui.SetItemTooltip("Clear every rule's fired / error / holding state");
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 24));
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
}
/// <summary>Refill the number boxes from a new snapshot (not while one is being typed in).</summary>
private void RefreshScheduleFields(SchedulePayload sc)
{
long v = UiSources.Meta.Current?.Version ?? 0;
if (v == _schedFieldsVersion || ImGuiNET.ImGui.IsAnyItemActive()) return;
_schedFieldsVersion = v;
WriteUtf8(_schedPoll, sc.PollMinutes.ToString(CultureInfo.InvariantCulture));
WriteUtf8(_schedWait, sc.MaxWaitSeconds.ToString(CultureInfo.InvariantCulture));
WriteUtf8(_schedGap, sc.MinGapSeconds.ToString(CultureInfo.InvariantCulture));
var metas = new List<string>();
foreach (MetaFile f in _data.Files)
if (!string.IsNullOrEmpty(f.Path)) metas.Add(System.IO.Path.GetFileName(f.Path));
_schedMetaPicks = metas.ToArray();
var only = new List<string> { "(any meta)" };
only.AddRange(metas);
_schedOnlyPicks = only.ToArray();
}
private string FirstMetaFile() => _schedMetaPicks.Length > 0 ? _schedMetaPicks[0] : string.Empty;
// [x Manager] Poll [5] min [poll now] | Wait [60] s Gap [30] s [x While stopped]
private void ScheduleSettings(SchedulePayload sc, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float x = p.X;
if (Toggle((sc.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " Manager##sched_on", ref x, p.Y, sc.Enabled))
{
sc.Enabled = !sc.Enabled; // shows at once; the next snapshot confirms
MetaCommands.Simple("mm_enabled", value: sc.Enabled ? "true" : "false");
}
ImGuiNET.ImGui.SetItemTooltip("Off by default. While on, it loads the first due rule's meta (also /ra metamgr on|off).");
x += 4;
NumberField("Poll", "##sched_poll", _schedPoll, "min", ref x, p.Y, 30, "How often it sends /myquests (minimum 1). Only while on and with a quest rule.",
n => { if (n >= 1) MetaCommands.Simple("mm_poll_minutes", value: n.ToString(CultureInfo.InvariantCulture)); });
if (IconButton("##sched_pollnow", PhosphorIcons.ArrowsClockwise, new Vector2(x, p.Y), new Vector2(24, 22), TextDim, BtnFill, BtnBord,
enabled: sc.Enabled))
MetaCommands.Simple("mm_poll_now");
ImGuiNET.ImGui.SetItemTooltip("Check /myquests now");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
Vector2 q = ImGuiNET.ImGui.GetCursorScreenPos();
x = q.X;
NumberField("Wait up to", "##sched_wait", _schedWait, "s", ref x, q.Y, 34,
"A switch waits until the bot is not fighting, looting, buffing or in a portal - at most this long, then it switches anyway.",
n => MetaCommands.Simple("mm_max_wait", value: Math.Max(0, n).ToString(CultureInfo.InvariantCulture)));
NumberField("Gap", "##sched_gap", _schedGap, "s", ref x, q.Y, 34, "At least this long between two switches.",
n => MetaCommands.Simple("mm_min_gap", value: Math.Max(0, n).ToString(CultureInfo.InvariantCulture)));
if (Toggle((sc.AllowWhileStopped ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " While stopped##sched_stopped", ref x, q.Y,
sc.AllowWhileStopped))
{
sc.AllowWhileStopped = !sc.AllowWhileStopped;
MetaCommands.Simple("mm_allow_stopped", value: sc.AllowWhileStopped ? "true" : "false");
}
ImGuiNET.ImGui.SetItemTooltip("Also switch metas while the macro is stopped (off: it waits for the macro to run).");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(q.X, q.Y + 24));
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
}
/// <summary>"Label [box] unit" at (x, y); commits a whole number when the box loses focus after an edit.</summary>
private static void NumberField(string label, string id, byte[] buf, string unit, ref float x, float y, float boxW, string tip, Action<int> commit)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float fy = y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.AddText(new Vector2(x, fy), Mute, label);
x += ImGuiNET.ImGui.CalcTextSize(label).X + 4;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y));
TextBox(id, buf, boxW, "", ImGuiInputTextFlags.CharsDecimal, out _);
bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
ImGuiNET.ImGui.SetItemTooltip(tip);
if (done && int.TryParse(Utf8(buf).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
commit(n);
x += boxW + 3;
dl.AddText(new Vector2(x, fy), Mute, unit);
x += ImGuiNET.ImGui.CalcTextSize(unit).X + 8;
}
private void ScheduleStatusLine(SchedulePayload sc, float w)
{
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
string poll = !sc.Enabled ? "Off - nothing is loaded or polled."
: sc.ServerDisabled ? "The server has /myquests turned off: quest rules can't fire."
: !sc.Polling ? "No quest rules: /myquests is not polled."
: sc.LastPollMs == 0 ? "Waiting for the first /myquests."
: $"{sc.QuestCount} quest timer(s), /myquests {Span(now - sc.LastPollMs)} ago.";
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(sc.ServerDisabled ? 0xFFE8B333 : 0xFFC8D6E4), Fit(poll, w));
if (sc.LastSwitch.Length > 0)
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6),
Fit($"Last: {sc.LastSwitch}{(sc.LastSwitchMs > 0 ? $", {Span(now - sc.LastSwitchMs)} ago" : "")}", w));
ImGuiNET.ImGui.PopFont();
}
private void ScheduleRules(SchedulePayload sc, float w)
{
if (sc.Rules.Count == 0)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " No rules. New Rule: when a timer runs out, load a meta.");
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " The first due rule (top to bottom) wins.");
return;
}
var dl = ImGuiNET.ImGui.GetWindowDrawList();
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
const float h = 20;
for (int i = 0; i < sc.Rules.Count; i++)
{
ScheduleRuleDto r = sc.Rules[i];
bool first = i == sc.FirstMatch && sc.Enabled;
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
dl.AddRectFilled(p, p + new Vector2(w, h), i % 2 == 0 ? PanelBg : RowAlt);
ImGuiNET.ImGui.PushID(1000 + i);
bool changed = false;
float x = p.X + 1;
dl.AddText(new Vector2(x + 2, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, (i + 1).ToString(CultureInfo.InvariantCulture));
x += 16;
if (IconButton("##en", r.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square, new Vector2(x, p.Y + 2), new Vector2(14, 16),
r.Enabled ? Green : Mute, BtnFill, BtnBord))
{
r.Enabled = !r.Enabled;
MetaCommands.Simple("mm_rule_enabled", i, r.Enabled ? "true" : "false");
}
ImGuiNET.ImGui.SetItemTooltip(r.Enabled ? "On - click to turn this rule off" : "Off - click to turn it on");
x += 16;
if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord, enabled: i > 0))
{
MetaCommands.Simple("mm_move", i, "-1");
(sc.Rules[i], sc.Rules[i - 1]) = (sc.Rules[i - 1], sc.Rules[i]);
changed = true;
}
ImGuiNET.ImGui.SetItemTooltip("Higher priority");
x += 18;
if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord,
enabled: i < sc.Rules.Count - 1))
{
MetaCommands.Simple("mm_move", i, "1");
(sc.Rules[i], sc.Rules[i + 1]) = (sc.Rules[i + 1], sc.Rules[i]);
changed = true;
}
ImGuiNET.ImGui.SetItemTooltip("Lower priority");
x += 18;
if (r.Trigger == 3) // countdown: start / stop
{
bool running = r.DueAtMs > 0;
if (IconButton("##cd", running ? PhosphorIcons.Stop : PhosphorIcons.Play, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16),
running ? Amber : Green, BtnFill, BtnBord))
MetaCommands.Simple(running ? "mm_countdown_stop" : "mm_countdown_start", i);
ImGuiNET.ImGui.SetItemTooltip(running ? "Stop the countdown" : $"Start the countdown ({Num(r.Minutes)} min)");
}
else if (r.Fired || (r.State ?? "").StartsWith("error", StringComparison.Ordinal) || (r.State ?? "").Contains("holding"))
{
if (IconButton("##rearm", PhosphorIcons.ArrowCounterClockwise, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Teal, BtnFill, BtnBord))
MetaCommands.Simple("mm_reset", i);
ImGuiNET.ImGui.SetItemTooltip("Re-arm this rule");
}
x += 18;
if (IconButton("##del", PhosphorIcons.Trash, new Vector2(x + 1, p.Y + 2), new Vector2(18, 16), TextDim, DelFill, BtnBord))
{
MetaCommands.Simple("mm_delete", i);
sc.Rules.RemoveAt(i);
changed = true;
}
ImGuiNET.ImGui.SetItemTooltip("Delete rule");
x += 22;
// Text: "when TRIGGER, load META" | time left / state; click to edit.
float textW = p.X + w - x;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y));
bool open = ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(Math.Max(1, textW), h));
if (ImGuiNET.ImGui.IsItemHovered())
{
ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
ImGuiNET.ImGui.SetTooltip(RuleTooltip(r, i, first));
}
ImGuiNET.ImGui.PopID();
if (changed) return; // the list changed: draw it again next frame
if (open)
{
OpenScheduleEditor(i, r);
return;
}
(string when, uint whenCol) = WhenText(r, now);
float whenW = ImGuiNET.ImGui.CalcTextSize(when).X;
float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
uint col = r.Enabled ? TextDim : Faded(TextDim);
dl.AddText(new Vector2(x + 3, ty), col, Fit(RuleText(r), Math.Max(10, textW - whenW - 14)));
dl.AddText(new Vector2(p.X + w - whenW - 4, ty), r.Enabled ? whenCol : Faded(whenCol), when);
if (first) dl.AddRect(p, p + new Vector2(w, h), Amber, 2);
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h));
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
}
}
private static string RuleText(ScheduleRuleDto r)
{
string trig = r.Trigger switch
{
0 => $"quest {(r.Quest.Length > 0 ? r.Quest : "?")} ready",
1 => $"{Num(r.Minutes)} min on the meta",
2 => $"every {Num(r.Minutes)} min",
_ => $"{Num(r.Minutes)} min countdown",
};
string on = r.OnlyOnMeta.Length > 0 ? $" (on {r.OnlyOnMeta})" : "";
return $"{trig}{on} {Arrow} {(r.Meta.Length > 0 ? r.Meta : "?")}{(r.Repeat ? "" : " [once]")}";
}
private const string Arrow = "->";
/// <summary>The right-hand column: the state words, else the time left, "ready" or "never".</summary>
private static (string Text, uint Color) WhenText(ScheduleRuleDto r, long nowMs)
{
string state = r.State ?? string.Empty;
if (state.StartsWith("error", StringComparison.Ordinal)) return ("error", Red);
if (state.StartsWith("waiting", StringComparison.Ordinal)) return (state, Amber);
if (state == "switching") return (state, Amber);
if (r.Fired) return ("fired", Mute);
if (state.Contains("holding")) return ("holding", Teal);
if (state.Length > 0 && r.DueAtMs == 0) return (Short(state), Mute);
if (r.DueAtMs == -1) return ("never", Mute);
if (r.DueAtMs == 0) return ("-", Mute);
long left = r.DueAtMs - nowMs;
return left <= 0 ? ("ready", Green) : (Span(left), TextDim);
}
private static string Short(string state) => state switch
{
"no /myquests yet" => "no data yet",
"/myquests is off on this server" => "no /myquests",
"not started" => "not started",
_ => state.Length > 18 ? state.Substring(0, 18) + "…" : state,
};
private static string RuleTooltip(ScheduleRuleDto r, int i, bool first)
{
var sb = new System.Text.StringBuilder();
sb.Append("Rule ").Append(i + 1).Append(": ").Append(TriggerNames[Math.Clamp(r.Trigger, 0, 3)]).Append('\n');
if (r.Trigger == 0) sb.Append("Quest: ").Append(r.Quest.Length > 0 ? r.Quest : "(none)").Append('\n');
else sb.Append("Minutes: ").Append(Num(r.Minutes)).Append('\n');
sb.Append("Loads: ").Append(r.Meta.Length > 0 ? r.Meta : "(none)").Append('\n');
if (r.OnlyOnMeta.Length > 0) sb.Append("Only while on: ").Append(r.OnlyOnMeta).Append('\n');
sb.Append(r.Repeat ? "Repeats" : "Once (one-shot)");
if (r.FireCount > 0) sb.Append(", fired ").Append(r.FireCount).Append("x this session");
if (!string.IsNullOrEmpty(r.State)) sb.Append('\n').Append(r.State);
if (first) sb.Append("\nFirst match: this rule fires next.");
sb.Append("\nClick to edit.");
return sb.ToString();
}
// ── Rule editor ─────────────────────────────────────────────────────
private void OpenScheduleEditor(int index, ScheduleRuleDto r)
{
_schedEdit = index;
_schedRule = r.CloneSettings();
WriteUtf8(_schedQuest, _schedRule.Quest);
WriteUtf8(_schedMinutes, Num(_schedRule.Minutes));
}
private void ScheduleEditor(SchedulePayload sc, float height)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0);
ImGuiNET.ImGui.BeginChild("##sched_editor", new Vector2(0, Math.Max(60, height)));
ImGuiNET.ImGui.PopStyleColor();
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
ScheduleRuleDto r = _schedRule;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), _schedEdit == -1 ? "New rule" : $"Edit rule {_schedEdit + 1}");
ImGuiNET.ImGui.PopFont();
FieldLabel("When:");
int picked = FlowPicker("##sched_trig", TriggerNames[Math.Clamp(r.Trigger, 0, 3)], TriggerNames, r.Trigger, w);
if (picked >= 0) r.Trigger = picked;
if (r.Trigger == 0)
{
FieldLabel("Quest (as /myquests shows it; case doesn't matter):");
if (TextBox("##sched_quest", _schedQuest, w, "e.g. blightlordlairwait1008", ImGuiInputTextFlags.None, out _))
r.Quest = Utf8(_schedQuest).Trim();
}
else
{
FieldLabel(r.Trigger switch
{
1 => "Minutes on the current meta:",
2 => "Every how many minutes:",
_ => "Countdown minutes (start it with the play button or /ra metamgr start):",
});
if (TextBox("##sched_min", _schedMinutes, 80, "30", ImGuiInputTextFlags.CharsDecimal, out _)
&& double.TryParse(Utf8(_schedMinutes).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out double m) && m >= 0)
r.Minutes = m;
}
FieldLabel("Load meta:");
picked = FlowPicker("##sched_meta", r.Meta.Length > 0 ? r.Meta : "Select a meta...", _schedMetaPicks,
Array.FindIndex(_schedMetaPicks, s => string.Equals(s, r.Meta, StringComparison.OrdinalIgnoreCase)), w);
if (picked >= 0) r.Meta = _schedMetaPicks[picked];
FieldLabel("Only while this meta is loaded:");
int onlyIdx = r.OnlyOnMeta.Length == 0 ? 0
: Array.FindIndex(_schedOnlyPicks, s => string.Equals(s, r.OnlyOnMeta, StringComparison.OrdinalIgnoreCase));
picked = FlowPicker("##sched_only", r.OnlyOnMeta.Length > 0 ? r.OnlyOnMeta : _schedOnlyPicks.Length > 0 ? _schedOnlyPicks[0] : "(any meta)",
_schedOnlyPicks, onlyIdx, w);
if (picked >= 0) r.OnlyOnMeta = picked == 0 ? string.Empty : _schedOnlyPicks[picked];
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float x = p.X;
if (Toggle("Repeat##sched_rep", ref x, p.Y, r.Repeat)) r.Repeat = true;
ImGuiNET.ImGui.SetItemTooltip("Fires every time its timer runs out");
if (Toggle("Once##sched_once", ref x, p.Y, !r.Repeat)) r.Repeat = false;
ImGuiNET.ImGui.SetItemTooltip("Fires once, then waits until you re-arm it");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Separator(w);
bool valid = r.Meta.Length > 0 && (r.Trigger != 0 || r.Quest.Length > 0);
Vector2 b = ImGuiNET.ImGui.GetCursorScreenPos();
string saveLabel = (_schedEdit == -1 ? "Add Rule" : "Save Rule") + "##sched_save";
float sw = ImGuiNET.ImGui.CalcTextSize(saveLabel.Substring(0, saveLabel.IndexOf("##", StringComparison.Ordinal))).X + 20;
if (Button(saveLabel, b, new Vector2(sw, 22), TextDim, NewFill, Green, enabled: valid))
{
var send = r.CloneSettings();
if (_schedEdit == -1) MetaCommands.Send(new MetaCmd { Op = "mm_add", ScheduleRule = send });
else MetaCommands.Send(new MetaCmd { Op = "mm_update", Index = _schedEdit, ScheduleRule = send });
_schedEdit = -2;
}
if (!valid) ImGuiNET.ImGui.SetItemTooltip(r.Meta.Length == 0 ? "Pick a meta to load" : "Name the quest");
if (Button("Cancel##sched_cancel", new Vector2(b.X + sw + 6, b.Y), new Vector2(60, 22), Mute, BtnFill, BtnBord))
_schedEdit = -2;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(b.X, b.Y + 22));
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
if (_schedEdit >= 0)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), "Saving re-arms the rule (clears fired / error).");
ImGuiNET.ImGui.PopFont();
}
ImGuiNET.ImGui.EndChild();
}
private static string Num(double v) => v.ToString("0.##", CultureInfo.InvariantCulture);
/// <summary>12s, 4m 05s, 3h 20m, 2d 4h.</summary>
private static string Span(long ms)
{
if (ms < 0) ms = 0;
var t = TimeSpan.FromMilliseconds(ms);
if (t.TotalHours >= 24) return $"{(int)t.TotalDays}d {t.Hours}h";
if (t.TotalMinutes >= 60) return $"{(int)t.TotalHours}h {t.Minutes:00}m";
if (t.TotalSeconds >= 60) return $"{(int)t.TotalMinutes}m {t.Seconds:00}s";
return $"{(int)t.TotalSeconds}s";
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,25 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/MonstersFace.cs
// The basic Monsters panel's ImGui face, retired 2026-10-01 (Tom). What only
// it could do moved to the Damage panel (DamageFace: Name rules, the
// Offhand modes per monster) and Monster Detail (DamageDetailFace: priority,
// damage type, extra vuln, match expression; a name rule's debuffs, off
// hand, pet and name). Categories were dropped from the UI; Rule.Category
// stays in the model so existing rule files keep it.
//
// Only Register is left, because EntryPoint calls it: it registers no face
// (so "Monsters" never shows) and moves a Monsters panel saved open onto
// Damage. PanelRouter sends every other "Monsters" request to Damage.
// ============================================================================
using RynthCore.Engine.UI;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal static class MonstersFace
{
public const string Title = "Monsters";
/// <summary>Engine init (EntryPoint). Registers nothing: see the file header.</summary>
public static void Register() => PanelRouter.MoveRetiredMonstersPanel();
}

View file

@ -0,0 +1,360 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/NavFace.cs
// ImGui face of the Nav panel (UI/Panels/NavPanel.cs): active nav + status,
// Start/Stop, route type and insert mode, Add Waypoint / Portal (not yet) /
// Recall / Clear / Save / Dungeon Patrol, a chat waypoint, Save As, the nav
// file picker, the nav point reach (RynthAi's FollowNavMin, the same row as
// Settings > Navigation), and the waypoint list (click selects the insert
// point, X deletes, => marks the active one).
//
// Data: UiSources.Nav (hub) and NavCommands. Button actions change a private
// copy at once; the plugin applies commands immediately, so the next
// snapshot (requested right after) replaces the copy. The reach row reads
// UiSources.Settings and saves through SettingsCommands, like the Settings face.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class NavFace : IImGuiPanel
{
public const string Title = "Nav";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(400, 560), new Vector2(360, 380), EdgeToEdge: true),
() => new NavFace());
private static readonly string[] Actions =
{
PhosphorIcons.MapPinPlus + " Add Waypoint", PhosphorIcons.Spiral + " Add Portal", PhosphorIcons.MagicWand + " Add Recall",
PhosphorIcons.Trash + " Clear Route", PhosphorIcons.FloppyDisk + " Save Route", PhosphorIcons.Footprints + " Dungeon Patrol",
};
private const string StartNav = PhosphorIcons.Play + " Start Navigation", StopNav = PhosphorIcons.Stop + " Stop Navigation";
private const string AddChat = PhosphorIcons.Plus + " Add Chat", SaveAs = PhosphorIcons.FloppyDisk + " Save As";
private static readonly bool[] ActionsEnabled = { true, false, true, true, true, true };
private NavPayload _data = new();
private long _seenVersion = -1;
private readonly List<string> _pointText = new();
private int _selected = -1, _addMode;
private bool _typing;
private string _routeLabel = "Route: Once", _insertLabel = "Insert: End", _activeLabel = "Active Nav: None (Unsaved)";
private string _fileLabel = "Select nav file...";
private string[] _navFiles = Array.Empty<string>();
private readonly byte[] _chat = new byte[256];
private int _chatLoadedFor = -1; // waypoint whose command is in _chat (-1: none)
private static void SetUtf8(byte[] buffer, string text)
{
Array.Clear(buffer);
byte[] b = System.Text.Encoding.UTF8.GetBytes(text ?? string.Empty);
Array.Copy(b, buffer, Math.Min(b.Length, buffer.Length - 1));
}
private readonly byte[] _saveName = new byte[128];
private readonly byte[] _reach = new byte[16];
private RynthAiSettings? _settings; // last Settings snapshot (null until fetched)
private long _settingsVersion = -1;
private bool _reachTyping;
private readonly Picker _picker = new("##nav_pick");
public void OnShown()
{
UiSources.Nav.Subscribe();
UiSources.Nav.RequestRefresh();
UiSources.Settings.Subscribe();
UiSources.Settings.RequestRefresh();
}
public void OnHidden()
{
UiSources.Nav.Unsubscribe();
UiSources.Settings.Unsubscribe();
}
public void Draw()
{
TakeSnapshot();
float w = Begin(out Vector2 origin, out Vector2 size);
bool typing = false;
NavPayload d = _data;
bool navActive = d.MacroRunning && d.NavigationEnabled;
// Active nav + status
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
Label(_activeLabel, Amber);
ImGuiNET.ImGui.PopFont();
if (d.NavStatusLine.Length > 0) Label(d.NavStatusLine, d.NavIsStuck ? Amber : Green);
// Start / Stop
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (Button("##startstop", navActive ? StopNav : StartNav, p, new Vector2(w, 28), Text, navActive ? StopBg : StartBg))
{
if (navActive)
{
NavCommands.Send(new NavCmd { Cmd = "stopNav" });
_data.NavigationEnabled = false;
}
else
{
NavCommands.Send(new NavCmd { Cmd = "startNav" });
_data.MacroRunning = true;
_data.NavigationEnabled = true;
}
}
NextLine(p, 32);
Separator(w);
// Route type | Insert mode
p = ImGuiNET.ImGui.GetCursorScreenPos();
float half = (w - 4) / 2;
if (Button("##route", _routeLabel, p, new Vector2(half, 22), Text, BtnFill, leftAlign: true))
_picker.Open(new Vector2(p.X, p.Y + 22), NavCommands.RouteTypes, NavCommands.RouteIndex(_data.RouteType), i =>
{
int routeType = NavCommands.RouteTypeFor(i);
NavCommands.Send(new NavCmd { Cmd = "setRouteType", RouteType = routeType });
_data.RouteType = routeType;
UpdateLabels();
});
if (Button("##insert", _insertLabel, new Vector2(p.X + half + 4, p.Y), new Vector2(half, 22), Text, BtnFill, leftAlign: true))
_picker.Open(new Vector2(p.X + half + 4, p.Y + 22), NavCommands.AddModes, _addMode, i =>
{
_addMode = i;
UpdateLabels();
});
NextLine(p, 26);
typing |= ReachRow(w);
// Actions
int action = WrapButtons("nav_act", Actions, w, 24, ActionsEnabled);
switch (action)
{
case 0: NavCommands.Send(new NavCmd { Cmd = "addWaypoint", AddMode = _addMode, InsertAt = _selected }); break;
case 2:
_picker.Open(ImGuiNET.ImGui.GetIO().MousePos, NavCommands.RecallLabels, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "addRecall", SpellId = NavCommands.RecallIds[i], AddMode = _addMode, InsertAt = _selected }));
break;
case 3:
NavCommands.Send(new NavCmd { Cmd = "clearRoute" });
_data.Points.Clear();
_selected = -1;
RebuildPointText();
break;
case 4: NavCommands.Send(new NavCmd { Cmd = "saveRoute" }); break;
case 5: NavCommands.Send(new NavCmd { Cmd = "dunPatrol" }); break;
}
// Chat waypoint: sent as if typed when the route reaches it. Selecting an
// existing chat waypoint loads its command here; Update saves the edit.
bool chatSelected = _selected >= 0 && _selected < _data.Points.Count
&& _data.Points[_selected].Type == "Chat";
if (_selected != _chatLoadedFor)
{
if (chatSelected) SetUtf8(_chat, _data.Points[_selected].Text);
else if (_chatLoadedFor >= 0) Array.Clear(_chat); // leaving a chat point: don't keep its text
_chatLoadedFor = chatSelected ? _selected : -1;
}
p = ImGuiNET.ImGui.GetCursorScreenPos();
float addW = ButtonWidth(AddChat);
float updW = chatSelected ? ButtonWidth("Update") + 4 : 0;
bool chatEnter = TextBox("##nav_chat", _chat, p, w - addW - updW - 4, "Chat command, e.g. /ub usei Healing Kit",
out bool chatActive, ImGuiInputTextFlags.EnterReturnsTrue);
typing |= chatActive;
bool update = chatSelected
&& Button("##updchat", "Update", new Vector2(p.X + w - addW - updW, p.Y), new Vector2(updW - 4, 22), Text, BtnFill);
bool addChat = Button("##addchat", AddChat, new Vector2(p.X + w - addW, p.Y), new Vector2(addW, 22), Text, BtnFill);
if (update || (chatEnter && chatSelected))
{
string text = Utf8(_chat).Trim();
if (text.Length > 0)
{
NavCommands.Send(new NavCmd { Cmd = "editChat", Index = _selected, Text = text });
_data.Points[_selected].Text = text;
_data.Points[_selected].Desc = "[Chat] " + text;
RebuildPointText();
}
}
else if (chatEnter || addChat)
{
string text = Utf8(_chat).Trim();
if (text.Length > 0)
{
NavCommands.Send(new NavCmd { Cmd = "addChat", Text = text, AddMode = _addMode, InsertAt = _selected });
Array.Clear(_chat);
_chatLoadedFor = -1;
}
}
NextLine(p, 26);
// Save as a named nav
p = ImGuiNET.ImGui.GetCursorScreenPos();
float saveW = ButtonWidth(SaveAs);
bool saveEnter = TextBox("##nav_saveas", _saveName, p, w - saveW - 4, "Nav name...", out bool saveActive, ImGuiInputTextFlags.EnterReturnsTrue);
typing |= saveActive;
bool saveAs = Button("##saveas", SaveAs, new Vector2(p.X + w - saveW, p.Y), new Vector2(saveW, 22), Text, BtnFill);
if (saveEnter || saveAs)
{
string name = Utf8(_saveName).Trim();
if (name.Length > 0)
{
NavCommands.Send(new NavCmd { Cmd = "saveRoute", NavName = name });
Array.Clear(_saveName);
}
}
NextLine(p, 26);
// Nav file picker
if (_navFiles.Length > 0)
{
p = ImGuiNET.ImGui.GetCursorScreenPos();
float lw = ImGuiNET.ImGui.CalcTextSize("Nav:").X + 6;
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "Nav:");
if (Button("##navfile", _fileLabel, new Vector2(p.X + lw, p.Y), new Vector2(w - lw, 22), Text, BtnFill, leftAlign: true))
_picker.Open(new Vector2(p.X + lw, p.Y + 22), _navFiles, Array.IndexOf(_navFiles, _data.ActiveNavName), i =>
NavCommands.Send(new NavCmd { Cmd = "loadNav", NavName = _navFiles[i] }));
NextLine(p, 26);
}
// Waypoints
Separator(w);
Label($"Waypoints ({_data.Points.Count})", Mute);
float listH = Math.Max(60, Remaining(origin, size));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1));
ImGuiNET.ImGui.BeginChild("##nav_points", new Vector2(w, listH));
Waypoints(ImGuiNET.ImGui.GetContentRegionAvail().X);
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
_typing = typing;
End(origin, size);
_picker.Draw();
}
/// <summary>
/// Nav point reach (yd): how close nav gets to each nav point before moving on. Label,
/// [-] value [+]; the typed value commits on Enter or when the box loses focus. Saves the
/// whole settings payload (a copy of the latest snapshot), as the Settings face does.
/// Hidden until RynthAi's settings have been fetched. Returns true while typing.
/// </summary>
private bool ReachRow(float w)
{
var snap = UiSources.Settings.Current;
if (snap != null && snap.Version != _settingsVersion && !_reachTyping)
{
_settingsVersion = snap.Version;
_settings = snap.Value.Clone();
WriteUtf8(_reach, _settings.FollowNavMin.ToString("0.0#", CultureInfo.InvariantCulture));
}
if (_settings == null) return false;
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
string label = SettingsSchema.NavPointReachLabel;
float labelW = ImGuiNET.ImGui.CalcTextSize(label).X;
dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, label);
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.InvisibleButton("##reach_label", new Vector2(Math.Max(1, labelW), 22));
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(SettingsSchema.NavPointReachTip);
const float stepW = 22, boxW = 52;
float right = p.X + w;
float value = _settings.FollowNavMin;
if (Button("##reach_minus", "-", new Vector2(right - stepW * 2 - boxW - 8, p.Y), new Vector2(stepW, 22), Text, BtnFill))
SaveReach(value - 0.1f);
bool enter = TextBox("##reach", _reach, new Vector2(right - stepW - boxW - 4, p.Y), boxW, "",
out bool active, ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.EnterReturnsTrue);
bool commit = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
if (Button("##reach_plus", "+", new Vector2(right - stepW, p.Y), new Vector2(stepW, 22), Text, BtnFill))
SaveReach(value + 0.1f);
if (commit)
{
if (float.TryParse(Utf8(_reach), NumberStyles.Float, CultureInfo.InvariantCulture, out float typed)) SaveReach(typed);
else WriteUtf8(_reach, value.ToString("0.0#", CultureInfo.InvariantCulture)); // bad input reverts
}
_reachTyping = active;
NextLine(p, 26);
return active;
}
private void SaveReach(float yards)
{
if (_settings == null || float.IsNaN(yards)) return;
yards = MathF.Round(Math.Clamp(yards, 0.5f, 20f) * 10f) / 10f;
_settings.FollowNavMin = yards;
WriteUtf8(_reach, yards.ToString("0.0#", CultureInfo.InvariantCulture));
SettingsCommands.Save(_settings.Clone());
}
private void Waypoints(float w)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 clipMin = ImGuiNET.ImGui.GetWindowPos(), clipMax = clipMin + ImGuiNET.ImGui.GetWindowSize();
for (int i = 0; i < _data.Points.Count; i++)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const float h = 22;
if (p.Y + h < clipMin.Y || p.Y > clipMax.Y) { ImGuiNET.ImGui.Dummy(new Vector2(w, h)); continue; }
bool active = i == _data.ActiveNavIndex, selected = i == _selected;
ImGuiNET.ImGui.PushID(i);
// Row click selects (drawn first so the X button on top wins).
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.SetNextItemAllowOverlap(); // the X button on top gets its clicks
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) _selected = i;
dl.AddRectFilled(p, p + new Vector2(w, h), selected ? Selected : i % 2 == 0 ? PanelBg : RowAlt);
if (IconButton("##del", PhosphorIcons.X, new Vector2(p.X + 2, p.Y + 2), new Vector2(18, 18), Text, DeleteBg, font: UiFont.Ui11))
{
NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i });
if (_selected == i) _selected = -1;
else if (_selected > i) _selected--;
_data.Points.RemoveAt(i);
RebuildPointText();
ImGuiNET.ImGui.PopID();
return;
}
float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
if (active) dl.AddText(new Vector2(p.X + 24, ty), Teal, "=>");
dl.PushClipRect(p, p + new Vector2(w - 2, h), true);
dl.AddText(new Vector2(p.X + 44, ty), active ? Teal : Text, i < _pointText.Count ? _pointText[i] : "");
dl.PopClipRect();
ImGuiNET.ImGui.PopID();
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h));
ImGuiNET.ImGui.Dummy(new Vector2(w, 0));
}
}
private void TakeSnapshot()
{
var snap = UiSources.Nav.Current;
if (snap == null || snap.Version == _seenVersion || _typing) return;
_seenVersion = snap.Version;
_data = snap.Value.Clone();
_navFiles = _data.NavFiles.ToArray();
if (_selected >= _data.Points.Count) _selected = -1;
RebuildPointText();
UpdateLabels();
}
private void RebuildPointText()
{
_pointText.Clear();
for (int i = 0; i < _data.Points.Count; i++) _pointText.Add(NavCommands.PointText(_data.Points[i], i));
}
private void UpdateLabels()
{
_activeLabel = "Active Nav: " + (string.IsNullOrEmpty(_data.ActiveNavName) ? "None (Unsaved)" : _data.ActiveNavName);
_routeLabel = "Route: " + NavCommands.RouteTypes[NavCommands.RouteIndex(_data.RouteType)];
_insertLabel = "Insert: " + NavCommands.AddModes[_addMode];
int fileIdx = string.IsNullOrEmpty(_data.ActiveNavName) ? -1 : _data.NavFiles.IndexOf(_data.ActiveNavName);
_fileLabel = fileIdx >= 0 ? _data.NavFiles[fileIdx] : "Select nav file...";
}
}

View file

@ -0,0 +1,286 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/P1Faces.cs
// ImGui faces of the Status, Log and Tracker panels
// (docs/IMGUI_PARITY_PLAN.md §2.11, §2.12). Each mirrors its Avalonia face in
// UI/Panels and reads the same UiDataHub snapshot. AC thread only; strings
// are built when a snapshot changes, not per frame.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Plugins;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal static class P1Faces
{
/// <summary>Registers the P1 faces next to their Avalonia faces (EntryPoint).</summary>
public static void Register(bool trackerPresent)
{
// Status and Log end in a footer of left-aligned buttons: the resize grip
// sits beside it, over the body (GripInBody), instead of in a strip below.
var standard = new PanelSpec(new Vector2(400, 500), new Vector2(320, 240), GripInBody: true);
ImGuiPanelHost.Register("Status", standard, () => new StatusFace());
ImGuiPanelHost.Register("Log", standard, () => new LogFace());
if (trackerPresent)
ImGuiPanelHost.Register("Tracker",
new PanelSpec(new Vector2(165, 190), new Vector2(60, 20), Background: 0, GripInBody: true),
() => new TrackerFace());
// The Skills panel: an engine panel with only an ImGui face, needing no plugin.
// Registered here so engine init needs no new line in EntryPoint; ImGuiBar gives
// it a bar button (ImGuiOnlyPanels).
SkillsFace.Register();
// Sense (watch list of names, anywhere the client knows): ImGui only, like Skills.
SenseFace.Register();
}
}
/// <summary>Status: engine facts, plugin rows, and each panel's face.</summary>
internal sealed class StatusFace : IImGuiPanel
{
private static readonly Vector4 HeaderColor = RynthTheme.Vec(0xC88CC8FF);
private static readonly Vector4 RowColor = RynthTheme.Vec(0xC8D2D2D2);
private static readonly Vector4 ErrorColor = RynthTheme.Vec(0xDCFF6464);
private string[] _engineRows = Array.Empty<string>();
private long _pluginVersion = -1;
private string _pluginHeader = "Plugins";
private readonly List<(string Text, bool Error)> _pluginRows = new();
private List<string> _faceRows = new();
private long _faceRowsTick;
public void OnShown()
{
UiSources.PluginStatus.Subscribe();
UiSources.PluginStatus.RequestRefresh();
BuildEngineRows();
}
private void BuildEngineRows()
{
_engineRows = new[]
{
$"Version: {EntryPoint.BuildStamp}",
$"Game HWND: 0x{EntryPoint.GameHwnd:X8}",
$"Plugin dir: {PluginManager.PluginDirectory}",
};
}
public void OnHidden() => UiSources.PluginStatus.Unsubscribe();
public void Draw()
{
RefreshCaches();
float footer = ImGuiNET.ImGui.GetFrameHeightWithSpacing();
ImGuiNET.ImGui.BeginChild("##status", new Vector2(0, -footer));
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
Header("Engine");
foreach (string row in _engineRows) Row(row, false);
Separator();
Header(_pluginHeader);
if (_pluginRows.Count == 0) Row("None loaded", false);
foreach (var (text, error) in _pluginRows) Row(text, error);
Separator();
Header("UI faces");
foreach (string row in _faceRows) Row(row, false);
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.EndChild();
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowsClockwise + " Refresh"))
{
UiSources.PluginStatus.RequestRefresh();
_faceRowsTick = 0;
BuildEngineRows();
}
}
private void RefreshCaches()
{
var snap = UiSources.PluginStatus.Current;
if (snap != null && snap.Version != _pluginVersion)
{
_pluginVersion = snap.Version;
_pluginHeader = $"Plugins ({snap.Value.Length})";
_pluginRows.Clear();
foreach (PluginStatusRow r in snap.Value)
_pluginRows.Add(($"{r.Label}: {r.State}", r.IsError));
}
long now = Environment.TickCount64;
if (now - _faceRowsTick > 2000)
{
_faceRowsTick = now;
_faceRows = PanelRouter.Describe();
}
}
private static void Header(string text)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
ImGuiNET.ImGui.TextColored(HeaderColor, text);
ImGuiNET.ImGui.PopFont();
}
private static void Row(string text, bool error)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, error ? ErrorColor : RowColor);
ImGuiNET.ImGui.TextWrapped(text);
ImGuiNET.ImGui.PopStyleColor();
}
private static void Separator()
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
ImGuiNET.ImGui.GetWindowDrawList().AddLine(p, p + new Vector2(w, 0), RynthTheme.Argb(0x3CFFFFFF));
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
}
}
/// <summary>Log: the engine's recent-log ring, monospace, with Auto-scroll and Clear.</summary>
internal sealed unsafe class LogFace : IImGuiPanel
{
private ImGuiListClipper* _clipper;
private bool _autoScroll = true;
private long _clearedSeq;
private long _seenVersion = -1;
public void OnShown()
{
UiSources.Log.Subscribe();
UiSources.Log.RequestRefresh();
_clipper = ImGuiNative.ImGuiListClipper_ImGuiListClipper();
}
public void OnHidden()
{
UiSources.Log.Unsubscribe();
if (_clipper != null) ImGuiNative.ImGuiListClipper_destroy(_clipper);
_clipper = null;
}
public void Draw()
{
var snap = UiSources.Log.Current;
bool changed = snap != null && snap.Version != _seenVersion;
if (snap != null) _seenVersion = snap.Version;
float footer = ImGuiNET.ImGui.GetFrameHeightWithSpacing();
ImGuiNET.ImGui.BeginChild("##lines", new Vector2(0, -footer));
if (snap != null && _clipper != null)
{
LogSnapshot log = snap.Value;
// Clear hides everything up to the sequence number it saw, so it keeps
// working after the 256-line ring wraps (Avalonia bug A6).
int start = (int)Math.Clamp(_clearedSeq - log.FirstSeq + 1, 0, log.Lines.Length);
int count = log.Lines.Length - start;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono10));
var clipper = new ImGuiListClipperPtr(_clipper);
clipper.Begin(count);
while (clipper.Step())
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
ImGuiNET.ImGui.TextUnformatted(log.Lines[start + i]);
clipper.End();
ImGuiNET.ImGui.PopFont();
if (changed && _autoScroll)
ImGuiNET.ImGui.SetScrollHereY(1f);
}
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.Checkbox("Auto-scroll", ref _autoScroll);
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button(PhosphorIcons.Eraser + " Clear"))
_clearedSeq = snap?.Value.LastSeq ?? EntryPoint.RecentLogSeq;
}
}
/// <summary>Tracker: nine session-stat rows over an adjustable-opacity background.</summary>
internal sealed class TrackerFace : IImGuiPanel
{
private static readonly Vector4 TitleColor = RynthTheme.Vec(0xFFE6B450);
private static readonly Vector4 LabelColor = RynthTheme.Vec(0xFF999999);
private static readonly uint ResetBg = RynthTheme.Argb(0xFF1A2E40);
private static readonly uint ResetBorder = RynthTheme.Argb(0xFF264C59);
private int _opacity;
public void OnShown()
{
UiSources.Tracker.Subscribe();
UiSources.Tracker.RequestRefresh();
_opacity = (int)Math.Round(TrackerSettings.BgAlpha / 2.55);
}
public void OnHidden() => UiSources.Tracker.Unsubscribe();
public void Draw()
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
// Background behind the content only (like the Avalonia StackPanel), so
// content goes on channel 1 and the rect, sized afterwards, on channel 0.
dl.ChannelsSplit(2);
dl.ChannelsSetCurrent(1);
Vector2 top = ImGuiNET.ImGui.GetCursorScreenPos() - ImGuiNET.ImGui.GetStyle().WindowPadding;
float width = ImGuiNET.ImGui.GetWindowWidth();
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
// Title row: [Tracker] [===slider===] [reset]
ImGuiNET.ImGui.TextColored(TitleColor, "Tracker");
ImGuiNET.ImGui.SameLine();
float resetW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.ArrowCounterClockwise).X + 8;
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(10, ImGuiNET.ImGui.GetContentRegionAvail().X - resetW - 4));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(2, 0));
if (ImGuiNET.ImGui.SliderInt("##opacity", ref _opacity, 0, 100, ""))
TrackerSettings.SetBgAlpha((byte)Math.Round(_opacity * 2.55), save: false);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
TrackerSettings.SetBgAlpha((byte)Math.Round(_opacity * 2.55), save: true);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, ResetBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, ResetBorder);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 1));
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + "##reset"))
UiSources.Tracker.RequestReset();
ImGuiNET.ImGui.SetItemTooltip("Reset the session stats");
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(2);
TrackerSnapshot? snap = UiSources.Tracker.Current?.Value;
string[]? values = snap?.Values;
string[] labels = snap?.Labels ?? TrackerSnapshot.DefaultLabels;
// The resize grip sits over the body's bottom-right corner (GripInBody): a
// row that reaches down into it right-aligns its value short of it.
float grip = ImGuiPanelHost.BodyGripReserve;
float gripTop = grip > 0 ? ImGuiNET.ImGui.GetWindowPos().Y + ImGuiNET.ImGui.GetWindowHeight() - grip : float.MaxValue;
float rowH = ImGuiNET.ImGui.GetTextLineHeight();
for (int i = 0; i < labels.Length; i++)
{
float rowRight = ImGuiNET.ImGui.GetCursorPosX() + ImGuiNET.ImGui.GetContentRegionAvail().X;
if (ImGuiNET.ImGui.GetCursorScreenPos().Y + rowH > gripTop) rowRight -= grip;
ImGuiNET.ImGui.TextColored(LabelColor, labels[i]);
string value = values != null && i < values.Length ? values[i] : "—";
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono9));
float w = ImGuiNET.ImGui.CalcTextSize(value).X;
ImGuiNET.ImGui.SameLine(Math.Max(0, rowRight - w));
ImGuiNET.ImGui.TextUnformatted(value);
ImGuiNET.ImGui.PopFont();
}
ImGuiNET.ImGui.PopFont();
float bottom = ImGuiNET.ImGui.GetCursorScreenPos().Y;
dl.ChannelsSetCurrent(0);
uint bg = RynthTheme.Argb(((uint)TrackerSettings.BgAlpha << 24) | 0x0A121A);
dl.AddRectFilled(top, new Vector2(top.X + width, bottom), bg);
dl.ChannelsMerge();
}
}

View file

@ -0,0 +1,682 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/RadarFace.cs
// ImGui face of the Radar (docs/IMGUI_PARITY_PLAN.md §2.2), drawn the way
// the Avalonia face's RadarSurface.Render does: gold rim, canvas, crosshair,
// floors (current layer full, the one above and below at 30%) with slope
// tints, walls (blue when visited), visited overlay, markers, player arrow,
// outlined compass on the playfield perimeter, coordinate strip. Top-right
// pop-out and settings (gear) buttons, wheel zoom, left-drag moves, left-click on a dot
// selects it in game by object id (hover: name, distance, health), right-click menu, settings
// popup. Settings are shared with the Avalonia face (RadarSettingsStore).
// Marker kinds (RadarKind) each have a shape (RadarMarkerStyle), a show box
// and a colour the user can pick; the settings popup doubles as the legend.
//
// Data: UiSources.Radar (RadarView, lookups precomputed). World geometry is
// drawn without anti-aliasing (crisp tiling like the Avalonia face's aliased
// mode, and far fewer vertices for big dungeons); no per-frame allocation.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
using RynthCore.Engine.UI.Panels;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class RadarFace : IImGuiPanel
{
public const string Title = "Radar";
public static void Register()
{
ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(320, 320), new Vector2(120, 120), PanelChrome.None,
Background: 0, Rounding: 0, EdgeToEdge: true, GoldGrip: true),
() => new RadarFace());
// The Inventory panel (engine data only, like the radar): registered here so
// engine init needs no new line in EntryPoint (as LootEditor / DungeonMap
// register from RynthAiFace). Opened from the bar and /rc inv.
InventoryFace.Register();
}
// ── Palette (RadarPanel's, ARGB) ────────────────────────────────────
private const uint FrameOuterArgb = 0xFF0A0D14, CanvasBgArgb = 0xFF0A121A;
private static readonly uint FrameInner = C(0xFF9E853D), FrameAccent = C(0xFFE6C766),
Crosshair = C(0x994D6680), Cardinal = C(0xFFFFFFFF), CoordText = C(0xFFF2F8FF), Outline = C(0xF2000000),
PlayerCol = C(0xFF33FF66), ButtonBg = C(0xC0141F29), ButtonBorder = C(0xFF34587A);
// Marker colours per kind (RadarSettingsStore.KindColors, user-pickable), refreshed each frame.
private static readonly uint[] KindCols = new uint[RadarKind.Count];
private const uint WallUnseen = 0xFFFFFFFF, WallVisited = 0xFF4099FF, FloorFlat = 0x8C2E8C38,
FloorUp = 0x668C1F14, FloorDown = 0x661A8026, FloorVisited = 0xA64D6B94;
private static uint C(uint argb) => RynthTheme.Argb(argb);
/// <summary>ARGB colour with its alpha scaled, as an ImGui colour.</summary>
private static uint MulAlpha(uint argb, float k) =>
RynthTheme.Argb((argb & 0x00FFFFFF) | ((uint)Math.Clamp((int)MathF.Round((argb >> 24) * k), 0, 255) << 24));
private static readonly (string Label, float WorldX, float WorldY)[] Compass =
{ ("N", 0, 1), ("E", 1, 0), ("S", 0, -1), ("W", -1, 0) };
private bool _settingsOpen;
/// <summary>Markers move: popped out, redraw smoothly even when idle.</summary>
public int PopOutIdleHz => 20;
public bool ClickThrough =>
RadarSettingsStore.CtrlGatedClickThrough && !ImGuiNET.ImGui.GetIO().KeyCtrl;
public void OnShown()
{
RadarSettingsStore.Load();
UiSources.Radar.Subscribe();
UiSources.Radar.RequestRefresh();
}
public void OnHidden() => UiSources.Radar.Unsubscribe();
public void Draw()
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
if (size.X < 16 || size.Y < 16) return;
RadarView? view = UiSources.Radar.Current?.Value;
bool rim = RadarSettingsStore.ShowGoldRim;
float canvasInset = rim ? 5 : 0;
const float coordStrip = 14;
float opacity = Math.Clamp(RadarSettingsStore.Opacity, 0f, 1f);
Vector2 frameMax = origin + size;
// ── Frame: outer black (fades) + gold inner border + accent ──
if (rim)
{
dl.AddRectFilled(origin, frameMax, MulAlpha(FrameOuterArgb, opacity));
dl.AddRect(origin + new Vector2(1, 1), frameMax - new Vector2(1, 1), FrameInner, 0, ImDrawFlags.None, 2);
dl.AddRect(origin + new Vector2(3, 3), frameMax - new Vector2(3, 3), FrameAccent, 0, ImDrawFlags.None, 1);
}
// ── Canvas and world playfield (canvas minus the coord strip) ──
Vector2 canvasMin = origin + new Vector2(canvasInset, canvasInset);
Vector2 canvasMax = frameMax - new Vector2(canvasInset, canvasInset);
dl.AddRectFilled(canvasMin, canvasMax, MulAlpha(CanvasBgArgb, opacity));
var worldMin = canvasMin;
var worldMax = new Vector2(canvasMax.X, canvasMax.Y - coordStrip);
Vector2 centre = (worldMin + worldMax) * 0.5f;
dl.AddLine(new Vector2(centre.X, worldMin.Y), new Vector2(centre.X, worldMax.Y), Crosshair);
dl.AddLine(new Vector2(worldMin.X, centre.Y), new Vector2(worldMax.X, centre.Y), Crosshair);
if (view != null)
{
ImDrawListFlags saved = dl.Flags;
dl.Flags = saved & ~(ImDrawListFlags.AntiAliasedLines | ImDrawListFlags.AntiAliasedLinesUseTex | ImDrawListFlags.AntiAliasedFill);
dl.PushClipRect(worldMin, worldMax, true);
DrawWorld(dl, view, centre, worldMin, worldMax);
dl.PopClipRect();
dl.Flags = saved;
DrawOutlinedText(dl, ImGuiFonts.Get(UiFont.UiBold11), view.CoordText,
new Vector2((canvasMin.X + canvasMax.X) * 0.5f, canvasMax.Y), CoordText, alignBottom: true);
DrawCardinals(dl, view, centre, (worldMax.X - worldMin.X) * 0.5f, (worldMax.Y - worldMin.Y) * 0.5f);
}
// ── Buttons (submitted before the surface so they win the hover) ──
const float btn = 22, gap = 4, inset = 6;
var gearPos = new Vector2(frameMax.X - inset - btn, origin.Y + inset);
var popPos = gearPos - new Vector2(btn + gap, 0);
if (PanelRouter.CanPopOut)
{
if (IconButton("##radar_pop", popPos, ImGuiPanelHost.PopOutGlyph))
ImGuiPanelHost.TogglePopOut(Title);
ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip);
}
bool gear = IconButton("##radar_gear", gearPos, PhosphorIcons.Gear);
ImGuiNET.ImGui.SetItemTooltip("Radar settings");
if (gear)
{
if (_settingsOpen) _settingsOpen = false;
else
{
_settingsOpen = true;
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(gearPos.X + btn, gearPos.Y + btn + 4), ImGuiCond.Always, new Vector2(1, 0));
}
}
// ── 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();
if (view != null && RadarSettingsStore.ClickToSelect)
MarkerInput(dl, view, centre, worldMin, worldMax, surfaceClicked);
if (ImGuiNET.ImGui.IsItemHovered())
{
float wheel = ImGuiNET.ImGui.GetIO().MouseWheel;
if (wheel != 0)
{
float next = Math.Clamp(RadarSettingsStore.Zoom + wheel * 0.15f, 0.5f, 6.0f);
if (next != RadarSettingsStore.Zoom) { RadarSettingsStore.Zoom = next; RadarSettingsStore.Save(); }
}
}
if (ImGuiNET.ImGui.BeginPopupContextItem("##radar_menu"))
{
if (PanelRouter.CanPopOut && ImGuiNET.ImGui.MenuItem(ImGuiPopOuts.InPopOutFrame ? "Dock back" : "Pop out"))
ImGuiPanelHost.TogglePopOut(Title);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Rotate with player", "", RadarSettingsStore.RotateWithPlayer))
{
RadarSettingsStore.RotateWithPlayer = !RadarSettingsStore.RotateWithPlayer;
RadarSettingsStore.Save();
}
ImGuiPanelHost.TextSizeMenu(Title);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Close"))
ImGuiPanelHost.Close(Title);
ImGuiNET.ImGui.EndPopup();
}
SettingsWindow();
}
// ── World ─────────────────────────────────────────────────────────────
/// <summary>World (AC x east, y north) → screen, north-up or rotated so facing is up.</summary>
private readonly struct Projection
{
private readonly float _cx, _cy, _pwx, _pwy, _sin, _cos, _zoom;
private readonly bool _rotate;
public Projection(Vector2 centre, RadarPlayer p, bool rotate, float zoom)
{
_cx = centre.X; _cy = centre.Y; _pwx = p.WorldX; _pwy = p.WorldY;
float h = p.Heading * MathF.PI / 180f; // AC: 0 = east, 90 = north
_sin = MathF.Sin(h); _cos = MathF.Cos(h);
_rotate = rotate; _zoom = zoom;
}
public float Sin => _sin;
public float Cos => _cos;
public Vector2 P(float wx, float wy)
{
float dx = wx - _pwx, dy = wy - _pwy;
if (_rotate)
{
float right = _sin * dx - _cos * dy;
float forward = _cos * dx + _sin * dy;
return new Vector2(_cx + right * _zoom, _cy - forward * _zoom);
}
return new Vector2(_cx + dx * _zoom, _cy - dy * _zoom);
}
}
private static void DrawWorld(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax)
{
RadarSnapshot live = view.Live;
bool rotate = RadarSettingsStore.RotateWithPlayer;
var proj = new Projection(centre, live.Player, rotate, MathF.Max(0.5f, RadarSettingsStore.Zoom));
int cur = view.CurrentLayer, count = live.LayerZs.Count;
// Same order as the Avalonia/ImGui-era radar: below, above (dimmed), current.
if (cur - 1 >= 0) DrawLayer(dl, view, cur - 1, 0.30f, false, proj, rotate, clipMin, clipMax);
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);
// Markers (shapes: RadarMarkerStyle). Corpses and items first, creatures on top.
RadarMarkerStyle.FillColors(KindCols);
for (int pass = 0; pass < 2; pass++)
{
foreach (RadarMarker m in live.Markers)
{
if (!RadarSettingsStore.ShowKind(m.Kind)) continue;
if ((pass == 1) != (RadarKind.IsCreature(m.Kind) || m.Kind is RadarKind.Portal or RadarKind.Door)) continue;
Vector2 pp = proj.P(m.X, m.Y);
if (pp.X < clipMin.X || pp.X > clipMax.X || pp.Y < clipMin.Y || pp.Y > clipMax.Y) continue;
RadarMarkerStyle.Draw(dl, m.Kind, pp, KindCols[m.Kind]);
}
}
// Player dot + 10 px heading arrow (always up when rotating).
dl.AddCircleFilled(centre, 3.5f, PlayerCol, 10);
Vector2 tip = rotate ? centre + new Vector2(0, -10) : centre + new Vector2(proj.Cos * 10, -proj.Sin * 10);
dl.AddLine(centre, tip, PlayerCol, 2);
}
private static void DrawLayer(ImDrawListPtr dl, RadarView view, int layer, float a, bool current,
in Projection proj, bool rotate, Vector2 clipMin, Vector2 clipMax)
{
// Floor strips: 5 floats (x0, y0, x1, y1, type).
if (view.FillsByLayer[layer] is float[] strips)
{
uint flat = MulAlpha(FloorFlat, a), up = MulAlpha(FloorUp, a), down = MulAlpha(FloorDown, a);
for (int i = 0; i + 4 < strips.Length; i += 5)
{
int type = (int)strips[i + 4];
uint col = type == 1 ? up : type == 2 ? down : flat;
FillRect(dl, proj, rotate, strips[i], strips[i + 1], strips[i + 2], strips[i + 3], col, clipMin, clipMax);
}
}
// Walls: 6 floats (ax, ay, bx, by, cell x, cell y); visited tint on the current layer.
if (view.WallsByLayer[layer] is float[] segs)
{
uint unseen = MulAlpha(WallUnseen, a), visited = MulAlpha(WallVisited, a);
float thick = current ? 1.5f : 1.0f;
bool[]? flags = current ? view.CurrentWallVisited : null;
for (int i = 0, w = 0; i + 5 < segs.Length; i += 6, w++)
{
Vector2 pa = proj.P(segs[i], segs[i + 1]);
Vector2 pb = proj.P(segs[i + 2], segs[i + 3]);
if (MathF.Max(pa.X, pb.X) < clipMin.X || MathF.Min(pa.X, pb.X) > clipMax.X ||
MathF.Max(pa.Y, pb.Y) < clipMin.Y || MathF.Min(pa.Y, pb.Y) > clipMax.Y) continue;
bool v = flags != null && w < flags.Length && flags[w];
dl.AddLine(pa, pb, v ? visited : unseen, thick);
}
}
// Visited overlay (current layer only): 4 floats per strip.
if (current && view.VisitedByLayer[layer] is float[] vStrips)
{
uint fill = MulAlpha(FloorVisited, a);
for (int i = 0; i + 3 < vStrips.Length; i += 4)
FillRect(dl, proj, rotate, vStrips[i], vStrips[i + 1], vStrips[i + 2], vStrips[i + 3], fill, clipMin, clipMax);
}
}
private static void FillRect(ImDrawListPtr dl, in Projection proj, bool rotate, float x0, float y0, float x1, float y1,
uint col, Vector2 clipMin, Vector2 clipMax)
{
Vector2 p00 = proj.P(x0, y0), p11 = proj.P(x1, y1);
if (rotate)
{
Vector2 p10 = proj.P(x1, y0), p01 = proj.P(x0, y1);
float minX = MathF.Min(MathF.Min(p00.X, p11.X), MathF.Min(p10.X, p01.X));
float maxX = MathF.Max(MathF.Max(p00.X, p11.X), MathF.Max(p10.X, p01.X));
float minY = MathF.Min(MathF.Min(p00.Y, p11.Y), MathF.Min(p10.Y, p01.Y));
float maxY = MathF.Max(MathF.Max(p00.Y, p11.Y), MathF.Max(p10.Y, p01.Y));
if (maxX < clipMin.X || minX > clipMax.X || maxY < clipMin.Y || minY > clipMax.Y) return;
dl.AddQuadFilled(p00, p10, p11, p01, col);
}
else
{
var a = Vector2.Min(p00, p11);
var b = Vector2.Max(p00, p11);
if (b.X < clipMin.X || a.X > clipMax.X || b.Y < clipMin.Y || a.Y > clipMax.Y) return;
dl.AddRectFilled(a, b, col);
}
}
// ── 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
// 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
// the clicked marker is matched to the client's object list by position
// (the engine's ~0.1 s position snapshot, same landblock, name preferred),
// which can pick the wrong one of two same-name monsters close together.
// The select itself is queued for AC's main thread
// (AcMainThreadQueue.EnqueueOverlaySelect), which re-checks the object
// still exists before selecting.
private const float ClickSlop = 4f; // px a press may move and still be a click
private const float MatchTolerance = 5f; // metres between a marker and its object (snapshot lag)
private const uint TypeCreature = 0x10, TypePortal = 0x10000;
private Vector2 _pressPos;
private float _pressTravel;
private byte _tipKind = byte.MaxValue;
private string? _tipLabel;
private int _tipDistance = int.MinValue;
private int _tipPct = -1;
private string _tipText = "";
private void MarkerInput(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax, bool clicked)
{
Vector2 mouse = ImGuiNET.ImGui.GetIO().MousePos;
if (ImGuiNET.ImGui.IsItemActivated())
{
_pressPos = mouse;
_pressTravel = 0f;
}
if (ImGuiNET.ImGui.IsItemActive())
{
_pressTravel = MathF.Max(_pressTravel, Vector2.Distance(mouse, _pressPos));
// Popped out, a 2 px drag hands the move to the OS window (DragWindowWithLastItem),
// which then follows the cursor: the context's mouse barely moves, so mark it a drag.
if (ImGuiPopOuts.InPopOutFrame && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 2f))
_pressTravel = float.MaxValue;
}
bool hovered = ImGuiNET.ImGui.IsItemHovered();
if (!hovered && !clicked) return;
if (mouse.X < clipMin.X || mouse.X > clipMax.X || mouse.Y < clipMin.Y || mouse.Y > clipMax.Y) return;
float zoom = MathF.Max(0.5f, RadarSettingsStore.Zoom);
var proj = new Projection(centre, view.Live.Player, RadarSettingsStore.RotateWithPlayer, zoom);
// Hit radius: a little more than the dot, growing with zoom, in UI-scaled pixels.
float radius = Math.Clamp(5f + 1.5f * zoom, 6f, 14f) * MathF.Max(1f, EngineFrameController.FontScale);
RadarMarker? hit = MarkerAt(view, proj, mouse, radius, clipMin, clipMax, out Vector2 hitPos);
if (hit == null) return;
if (clicked && _pressTravel <= ClickSlop)
{
uint id = hit.Id != 0 ? hit.Id : ResolveMarker(view, hit);
if (id != 0)
Compatibility.AcMainThreadQueue.EnqueueOverlaySelect(id);
return;
}
if (!hovered || ImGuiNET.ImGui.IsItemActive()) return;
dl.PushClipRect(clipMin, clipMax, true);
dl.AddCircle(hitPos, 6.5f, CoordText, 16, 1.5f);
dl.PopClipRect();
ImGuiNET.ImGui.BeginTooltip();
ImGuiNET.ImGui.TextUnformatted(TipText(view, hit));
ImGuiNET.ImGui.EndTooltip();
}
/// <summary>The shown marker nearest <paramref name="mouse"/> within <paramref name="radius"/> px, or null.</summary>
private static RadarMarker? MarkerAt(RadarView view, in Projection proj, Vector2 mouse, float radius,
Vector2 clipMin, Vector2 clipMax, out Vector2 at)
{
RadarMarker? best = null;
float bestD2 = radius * radius;
at = default;
foreach (RadarMarker m in view.Live.Markers)
{
if (!RadarSettingsStore.ShowKind(m.Kind)) continue;
Vector2 pp = proj.P(m.X, m.Y);
if (pp.X < clipMin.X || pp.X > clipMax.X || pp.Y < clipMin.Y || pp.Y > clipMax.Y) continue;
float d2 = Vector2.DistanceSquared(pp, mouse);
if (d2 > bestD2) continue;
bestD2 = d2;
best = m;
at = pp;
}
return best;
}
/// <summary>
/// The object a marker stands for: the nearest object in the player's landblock
/// (world = landblock-local + 192 m per landblock step, as the radar's markers)
/// of the marker's kind, within <see cref="MatchTolerance"/>; a name match wins
/// over a slightly nearer stranger. 0 when nothing matches. Only for markers
/// without an id (older RynthAi builds).
/// </summary>
private static uint ResolveMarker(RadarView view, RadarMarker m)
{
uint landblock = view.Live.Player.Landblock;
if (landblock == 0) return 0;
uint playerId = Compatibility.ClientHelperHooks.GetPlayerId();
string? label = string.IsNullOrEmpty(m.Label) ? null : m.Label;
const float tol2 = MatchTolerance * MatchTolerance;
uint best = 0;
float bestScore = float.MaxValue;
foreach (uint id in Compatibility.ClientObjectHooks.LiveObjectIds)
{
if (id == 0 || id == playerId) continue;
if (!Compatibility.ClientObjectHooks.TryGetSnapshotPosition(id, out uint cell, out float x, out float y, out float z)) continue;
if ((cell >> 16) != landblock) continue;
float dx = x + ((cell >> 24) & 0xFF) * 192f - m.X;
float dy = y + ((cell >> 16) & 0xFF) * 192f - m.Y;
float dz = z - m.Z;
float d2 = dx * dx + dy * dy + dz * dz;
if (d2 > tol2) continue;
if (m.Kind <= 2)
{
if (!Compatibility.ClientObjectHooks.TryGetSnapshotItemType(id, out uint type)) continue;
uint need = m.Kind == 2 ? TypePortal : TypeCreature;
if ((type & need) == 0) continue;
}
bool named = label != null && Compatibility.ClientObjectHooks.TryGetSnapshotName(id, out string name)
&& name.Equals(label, StringComparison.Ordinal);
float score = named ? d2 : d2 + tol2;
if (score < bestScore) { bestScore = score; best = id; }
}
return best;
}
/// <summary>
/// "Name\n12 yd" for the hovered marker, plus " 75%" when the marker has an id and
/// the engine has a health reading for it (MonsterHudData: one locked lookup, hover
/// only). Rebuilt only when the marker, whole yards or whole percent change.
/// </summary>
private string TipText(RadarView view, RadarMarker m)
{
RadarPlayer p = view.Live.Player;
float dx = m.X - p.WorldX, dy = m.Y - p.WorldY, dz = m.Z - p.Z;
int d = (int)MathF.Round(MathF.Sqrt(dx * dx + dy * dy + dz * dz));
int pct = -1;
if (m.Id != 0 && RadarKind.IsCreature(m.Kind) && Hud.MonsterHudData.TryGetHealth(m.Id, out Hud.HealthObservation h))
pct = (int)MathF.Round(h.Ratio * 100f);
// Markers are rebuilt on every radar poll: key on what the text shows, not the instance.
if (m.Kind == _tipKind && d == _tipDistance && pct == _tipPct
&& string.Equals(m.Label, _tipLabel, StringComparison.Ordinal))
return _tipText;
_tipKind = m.Kind;
_tipLabel = m.Label;
_tipDistance = d;
_tipPct = pct;
// A label is the object's name; the kinds a name alone doesn't tell apart say what they are.
string name = string.IsNullOrEmpty(m.Label) ? RadarKind.Name(m.Kind)
: m.Kind is RadarKind.Fellow or RadarKind.Pet or RadarKind.Vendor or RadarKind.OwnCorpse or RadarKind.Player
? m.Label + " (" + RadarKind.Name(m.Kind) + ")"
: m.Label!;
var inv = System.Globalization.CultureInfo.InvariantCulture;
_tipText = name + "\n" + d.ToString(inv) + " yd"
+ (pct >= 0 ? " " + pct.ToString(inv) + "%" : "");
return _tipText;
}
// ── Compass and text ───────────────────────────────────────────────────
private static void DrawCardinals(ImDrawListPtr dl, RadarView view, Vector2 centre, float halfW, float halfH)
{
const float sz = 14;
bool rotate = RadarSettingsStore.RotateWithPlayer;
float h = view.Live.Player.Heading * MathF.PI / 180f;
float sinH = MathF.Sin(h), cosH = MathF.Cos(h);
float effW = MathF.Max(1, halfW - sz), effH = MathF.Max(1, halfH - sz);
ImFontPtr font = ImGuiFonts.Get(UiFont.UiBold14);
foreach (var c in Compass)
{
float dirX, dirY;
if (rotate)
{
dirX = sinH * c.WorldX - cosH * c.WorldY;
dirY = -(cosH * c.WorldX + sinH * c.WorldY);
}
else
{
dirX = c.WorldX;
dirY = -c.WorldY;
}
// Onto the rectangular perimeter: max(|dx t|/effW, |dy t|/effH) = 1.
float m = MathF.Max(MathF.Abs(dirX) / effW, MathF.Abs(dirY) / effH);
if (m < 1e-4f) continue;
float t = 1 / m;
DrawOutlinedText(dl, font, c.Label, new Vector2(centre.X + dirX * t, centre.Y + dirY * t), Cardinal, alignBottom: false);
}
}
/// <summary>Text with a 1 px 4-way black outline, centred on x; centred or bottom-aligned on y.</summary>
private static void DrawOutlinedText(ImDrawListPtr dl, ImFontPtr font, string text, Vector2 anchor, uint col, bool alignBottom)
{
ImGuiNET.ImGui.PushFont(font);
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text);
ImGuiNET.ImGui.PopFont();
var pos = new Vector2(anchor.X - ts.X * 0.5f, alignBottom ? anchor.Y - ts.Y - 1 : anchor.Y - ts.Y * 0.5f);
float fs = font.FontSize;
dl.AddText(font, fs, pos + new Vector2(-1, 0), Outline, text);
dl.AddText(font, fs, pos + new Vector2(1, 0), Outline, text);
dl.AddText(font, fs, pos + new Vector2(0, -1), Outline, text);
dl.AddText(font, fs, pos + new Vector2(0, 1), Outline, text);
dl.AddText(font, fs, pos, col, text);
}
private static bool IconButton(string id, Vector2 pos, string glyph)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
var size = new Vector2(22, 22);
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
uint bg = ImGuiNET.ImGui.IsItemActive() ? C(0xE0101820) : ImGuiNET.ImGui.IsItemHovered() ? C(0xE0243444) : ButtonBg;
dl.AddRectFilled(pos, pos + size, bg, 3);
dl.AddRect(pos, pos + size, ButtonBorder, 3);
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), glyph, pos, size, CoordText);
return clicked;
}
// ── Settings (gear) ─────────────────────────────────────────────────────
private void SettingsWindow()
{
if (!_settingsOpen) return;
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, C(0xFF0A121A));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, ButtonBorder);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 4f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 10));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 6));
const ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize
| ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoCollapse;
bool visible = ImGuiNET.ImGui.Begin("##radar_settings", ref _settingsOpen, flags);
ImGuiNET.ImGui.PopStyleVar(3);
ImGuiNET.ImGui.PopStyleColor(2);
if (visible)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
ImGuiNET.ImGui.TextUnformatted("Radar Settings");
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.Separator();
bool changed = false;
changed |= Check("Rotate with player", ref RadarSettingsStore.RotateWithPlayer);
changed |= Check("Show gold rim", ref RadarSettingsStore.ShowGoldRim);
changed |= Check("Docked click-through (hold Ctrl to interact)", ref RadarSettingsStore.CtrlGatedClickThrough);
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("On: docked clicks pass through to the game; hold Ctrl to drag, open the gear, or resize.");
changed |= Check("Click a dot to select it", ref RadarSettingsStore.ClickToSelect);
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("Left-click a dot to select that object in game. Hover a dot for its name and distance.");
changed |= Slider("Opacity", ref RadarSettingsStore.Opacity, 0.05f, 1.0f, "%.2f");
changed |= Slider("Zoom", ref RadarSettingsStore.Zoom, 0.5f, 6.0f, "%.1f");
ImGuiNET.ImGui.Separator();
changed |= KindRows();
if (changed)
{
AvaloniaOverlay.RadarCtrlGatedClickThrough = RadarSettingsStore.CtrlGatedClickThrough;
RadarSettingsStore.Save();
}
ImGuiNET.ImGui.PopFont();
}
ImGuiNET.ImGui.End();
}
private static bool Check(string label, ref bool value) => ImGuiNET.ImGui.Checkbox(label, ref value);
// Legend order: creatures, then corpses, then places, then items.
private static readonly (byte Kind, string Label)[] KindRowsOrder =
{
(RadarKind.Monster, "Monsters"), (RadarKind.Player, "Players"), (RadarKind.Fellow, "Fellows"),
(RadarKind.Npc, "NPCs"), (RadarKind.Vendor, "Vendors"), (RadarKind.Pet, "Your pets"),
(RadarKind.Corpse, "Corpses"), (RadarKind.OwnCorpse, "Your corpses"), (RadarKind.Lifestone, "Lifestones"),
(RadarKind.Portal, "Portals"), (RadarKind.Door, "Doors"), (RadarKind.GroundItem, "Items on the ground"),
};
private static readonly string[] KindTips =
{
"Creatures you can attack.",
"Creatures you can't attack (townsfolk, quest givers).",
"Portals, with their destination.",
"Doors, gates and hatches.",
"Other players.",
"Players in your fellowship.",
"Your own combat pet.",
"Shopkeepers.",
"Corpses you can't loot (or not identified yet: selecting one tells).",
"Corpses you may loot: your kills, your fellows' kills and your own corpse. Known once the corpse has been identified (looting or selecting it does that).",
"Lifestones.",
"Items lying on the ground. Off by default: there can be a lot of them.",
};
/// <summary>
/// The legend and per-kind settings: show box, the marker as drawn, its name and a colour
/// swatch (click to pick). One row per kind, then "Reset colours". True when something changed.
/// </summary>
private static bool KindRows()
{
bool changed = false;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
ImGuiNET.ImGui.TextUnformatted("Show (click a swatch to change its colour):");
ImGuiNET.ImGui.PopFont();
RadarMarkerStyle.FillColors(KindCols);
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float scale = MathF.Max(1f, EngineFrameController.FontScale);
const ImGuiColorEditFlags pickFlags = ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel
| ImGuiColorEditFlags.AlphaBar | ImGuiColorEditFlags.AlphaPreviewHalf;
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 3));
foreach (var (kind, label) in KindRowsOrder)
{
ImGuiNET.ImGui.PushID(kind);
changed |= ImGuiNET.ImGui.Checkbox("##show", ref RadarSettingsStore.ShowFlag(kind));
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]);
ImGuiNET.ImGui.SameLine();
// The marker exactly as the radar draws it.
float box = ImGuiNET.ImGui.GetFrameHeight();
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.Dummy(new Vector2(box, box));
RadarMarkerStyle.Draw(dl, kind, at + new Vector2(box, box) * 0.5f, KindCols[kind], 1.3f * scale);
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted(label);
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]);
ImGuiNET.ImGui.SameLine(190 * scale);
Vector4 v = RynthTheme.Vec(RadarSettingsStore.KindColors[kind]);
if (ImGuiNET.ImGui.ColorEdit4("##col", ref v, pickFlags))
{
RadarSettingsStore.KindColors[kind] = ToArgb(v);
_colorDirty = true;
}
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.PopStyleVar();
// The picker reports every drag step: save once no colour edit is in progress.
if (_colorDirty && !ImGuiNET.ImGui.IsAnyItemActive())
{
_colorDirty = false;
changed = true;
}
if (ImGuiNET.ImGui.SmallButton("Reset colours"))
{
RadarSettingsStore.ResetKindColors();
changed = true;
}
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Every kind back to its default colour (show boxes stay as they are).");
return changed;
}
private static bool _colorDirty;
private static uint ToArgb(Vector4 v)
{
static uint B(float f) => (uint)Math.Clamp((int)MathF.Round(f * 255f), 0, 255);
return (B(v.W) << 24) | (B(v.X) << 16) | (B(v.Y) << 8) | B(v.Z);
}
private static bool Slider(string label, ref float value, float min, float max, string fmt)
{
ImGuiNET.ImGui.TextUnformatted(label);
ImGuiNET.ImGui.SameLine(60);
ImGuiNET.ImGui.SetNextItemWidth(170);
ImGuiNET.ImGui.PushID(label);
bool changed = ImGuiNET.ImGui.SliderFloat("##v", ref value, min, max, fmt);
ImGuiNET.ImGui.PopID();
// Save once the drag ends, not on every step.
return changed && !ImGuiNET.ImGui.IsItemActive() || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
}
}

View file

@ -0,0 +1,117 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/RadarMarkerStyle.cs
// One shape per radar marker kind (RadarKind), shared by the Radar face, its
// settings legend and the Dungeon Map. Shapes differ as well as colours, so
// the kinds stay apart for colour-blind players and when a user picks two
// similar colours:
// monster filled dot player dot with a white ring
// NPC filled dot fellow triangle with a white edge
// vendor coin (dot, dark rim) pet small dot, dark edge
// corpse X your corpse bold X with a dark outline
// lifestone ring with a centre item small square
// portal diamond door square with a dark edge
// Colours come in as ImGui colours (RynthTheme.Argb of the ARGB setting).
// ============================================================================
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
using RynthCore.Engine.UI.Panels;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal static class RadarMarkerStyle
{
private static readonly uint White = RynthTheme.Argb(0xF0FFFFFF);
private static readonly uint Black = RynthTheme.Argb(0xE6000000);
/// <summary>
/// Draws a marker of <paramref name="kind"/> centred on <paramref name="p"/>. <paramref name="s"/>
/// scales it (1 = the radar's size; the Dungeon Map draws a little bigger).
/// </summary>
public static void Draw(ImDrawListPtr dl, byte kind, Vector2 p, uint col, float s = 1f)
{
switch (kind)
{
case RadarKind.Monster:
case RadarKind.Npc:
dl.AddCircleFilled(p, 3f * s, col, 8);
break;
case RadarKind.Portal:
{
float r = 4f * s;
dl.AddQuadFilled(p + new Vector2(0, -r), p + new Vector2(r, 0), p + new Vector2(0, r), p + new Vector2(-r, 0), col);
break;
}
case RadarKind.Door:
{
var h = new Vector2(3.5f * s, 3.5f * s);
dl.AddRectFilled(p - h, p + h, col);
dl.AddRect(p - h, p + h, Darken(col, 0.4f));
break;
}
case RadarKind.Player:
dl.AddCircleFilled(p, 3.5f * s, col, 10);
dl.AddCircle(p, 4.5f * s, White, 12, 1.5f);
break;
case RadarKind.Fellow:
{
float r = 4.8f * s;
Vector2 a = p + new Vector2(0, -r), b = p + new Vector2(r * 0.9f, r * 0.65f), c = p + new Vector2(-r * 0.9f, r * 0.65f);
dl.AddTriangleFilled(a, b, c, col);
dl.AddTriangle(a, b, c, White, 1.3f);
break;
}
case RadarKind.Pet:
dl.AddCircleFilled(p, 2.3f * s, col, 8);
dl.AddCircle(p, 2.8f * s, Black, 8, 1f);
break;
case RadarKind.Vendor:
dl.AddCircleFilled(p, 4f * s, col, 12);
dl.AddCircle(p, 4f * s, Darken(col, 0.45f), 12, 1.2f);
dl.AddCircle(p, 2f * s, Darken(col, 0.55f), 8, 1f);
break;
case RadarKind.Corpse:
{
float r = 3f * s;
dl.AddLine(p + new Vector2(-r, -r), p + new Vector2(r, r), col, 1.5f);
dl.AddLine(p + new Vector2(-r, r), p + new Vector2(r, -r), col, 1.5f);
break;
}
case RadarKind.OwnCorpse:
{
float r = 3.6f * s;
dl.AddLine(p + new Vector2(-r, -r), p + new Vector2(r, r), Black, 4f);
dl.AddLine(p + new Vector2(-r, r), p + new Vector2(r, -r), Black, 4f);
dl.AddLine(p + new Vector2(-r, -r), p + new Vector2(r, r), col, 2.2f);
dl.AddLine(p + new Vector2(-r, r), p + new Vector2(r, -r), col, 2.2f);
break;
}
case RadarKind.Lifestone:
dl.AddCircle(p, 3.8f * s, col, 12, 2f);
dl.AddCircleFilled(p, 1.2f * s, col, 6);
break;
case RadarKind.GroundItem:
{
var h = new Vector2(2f * s, 2f * s);
dl.AddRectFilled(p - h, p + h, col);
dl.AddRect(p - h - Vector2.One, p + h + Vector2.One, Black);
break;
}
}
}
/// <summary>An ImGui colour (ABGR) with its RGB scaled by <paramref name="k"/>, alpha kept.</summary>
public static uint Darken(uint col, float k)
{
uint r = (uint)((col & 0xFF) * k), g = (uint)(((col >> 8) & 0xFF) * k), b = (uint)(((col >> 16) & 0xFF) * k);
return (col & 0xFF000000) | (b << 16) | (g << 8) | r;
}
/// <summary>Each kind's ImGui colour from the radar settings, refreshed into <paramref name="into"/> (length RadarKind.Count).</summary>
public static void FillColors(uint[] into)
{
for (int k = 0; k < into.Length; k++)
into[k] = RynthTheme.Argb(RadarSettingsStore.KindColor((byte)k));
}
}

View file

@ -0,0 +1,866 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/RynthAiFace.cs
// ImGui face of the RynthAi dashboard (docs/IMGUI_PARITY_PLAN.md §2.1),
// first laid out from the Avalonia face (UI/Panels/RynthAiPanel.cs), then
// made compact with Phosphor icons, after DrakBot's dashboard. Top to bottom:
// title row RYNTHAI DASHBOARD | target, vitals, lock, opacity -/+,
// minimize, pop out
// header grid macro RUNNING/STOPPED, meta state, bot activity | pickers
// control row (ON/OFF when minimized) combat, buffing, nav, looting and
// meta toggles ... force rebuff
// launchers one row of icon buttons (names in tooltips; labels too
// when the panel is wide enough)
// footer FPS | version | uptime
// bars player vitals, then the target (name + health), each
// toggled from the title row. Last on purpose, like DrakBot's
// target row: what comes and goes with a fight never moves
// the buttons above it.
// Minimized keeps the title row, the control row and the bars. The window's
// minimum height is the content's, and toggling the bars or minimize fits the
// window to the content. Data: UiSources.RynthAi (a RynthAiView with every
// string preformatted); clicks: RynthAiCommands.
//
// Chromeless (like the Avalonia face): the title row is the drag surface.
// AC thread only; no per-frame string building except the FPS/uptime footer,
// which is cached until its value changes.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class RynthAiFace : IImGuiPanel
{
public const string Title = "RynthAi";
public static void Register()
{
ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(296, 200), new Vector2(MinWidth, 54), PanelChrome.None,
Background: RynthTheme.RynthAiBackground, BorderColor: RynthTheme.RynthAiBorder,
Rounding: RynthTheme.RynthAiRounding),
() => new RynthAiFace());
// The Loot Editor edits RynthAi's loot profiles and opens from this dashboard.
LootEditorFace.Register();
// The Map launcher's panel. Registered here (only with RynthAi present, which
// feeds its data) so engine init needs no new line in EntryPoint.
DungeonMapFace.Register();
}
private const float MinWidth = 280;
// ── Palette (RynthAiPanel's, ARGB) ─────────────────────────────────
private static readonly uint Teal = C(0xFF26D9E6), TealSoft = C(0xFF264C59), Amber = C(0xFFE8B333),
Green = C(0xFF40D973), Mute = C(0xFFB8C8D8), TextDim = C(0xFFF2F7FC), White = C(0xFFFFFFFF),
Hp = C(0xFFD93333), Mana = C(0xFF268CF2), ShellBg = C(0xFF0A0F14), BarBg = C(0xFF141F29),
BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A), MacroRun = C(0xFF1A5926), MacroStop = C(0xFF401F1F),
FrFill = C(0xFF47330A), SelectorBg = C(0xFF2D3847);
private static uint C(uint argb) => RynthTheme.Argb(argb);
private static readonly uint[] SegmentColors = BuildSegmentColors();
private string _fpsText = "FPS —", _upText = "Up —";
private int _fpsShown = -1;
private long _upShown = -1;
private bool _patrolOpen;
// Picker toggle: ImGui closes a popup on the press outside it, so remember
// whether it was showing when the selector press began (a second click closes).
private readonly int[] _pickerShownFrame = { -10, -10, -10, -10 };
private readonly bool[] _pressedWhileOpen = new bool[4];
// The content's height (logical units, body padding included), measured each
// frame: the window's minimum height. _fit: resize the window to it once.
private float _contentHeight;
private bool _fit;
// Files folded/open flipped: size the window to that mode's own remembered size.
private bool _modeFlip, _modeFlipApply;
private Vector2 _winLogical; // the window's size in logical units, last frame (docked only)
private const float GripRoom = 12;
public Vector2? MinSize => new Vector2(MinWidth, _contentHeight > 0 ? _contentHeight
: RynthAiDashboardState.Minimized ? 54 : 180);
public void OnShown()
{
UiSources.RynthAi.Subscribe();
UiSources.RynthAi.RequestRefresh();
_fit = true; // drop the empty space a taller saved size leaves under the content
}
public void OnHidden()
{
UiSources.RynthAi.Unsubscribe();
if (_patrolOpen) { UiSources.Patrol.Unsubscribe(); _patrolOpen = false; }
}
public void Draw()
{
RynthAiView? view = UiSources.RynthAi.Current?.Value;
RynthAiSnapshot raw = view?.Raw ?? Empty;
bool minimized = RynthAiDashboardState.Minimized;
uint boxBg = (C(0xFF0A121A) & 0x00FFFFFF) | ((uint)(view?.PanelAlpha ?? 242) << 24);
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
float x0 = start.X;
float width = ImGuiNET.ImGui.GetContentRegionAvail().X;
TitleRow(raw, x0, width, minimized);
Gap(4);
// The Profile/Nav/Loot/Meta pickers only while expanded (the caret on the control row).
if (!minimized && RynthAiDashboardState.ShowFiles)
{
HeaderGrid(view, raw, x0, width);
Gap(4);
}
ControlRow(view, raw, x0, width, minimized, boxBg);
if (!minimized)
{
Gap(4);
Launchers(x0, width);
Gap(6);
Footer(view, x0, width);
}
Bars(view, raw, x0, width, boxBg);
PatrolPopup();
MeasureAndFit(start.Y);
}
/// <summary>
/// Records the content height as the window's minimum (so the bars at the
/// bottom are never cut off) and, after a toggle, fits the window to it.
/// </summary>
private void MeasureAndFit(float startY)
{
float pad = ImGuiNET.ImGui.GetCursorStartPos().Y; // the body's top padding (the bottom's is the same)
float px = ImGuiNET.ImGui.GetCursorScreenPos().Y - startY + 2 * pad;
float place = ImGuiPanelHost.PlacementScale();
// + room for the host's resize grip, which is painted over the body's bottom-right corner.
_contentHeight = MathF.Ceiling(px / place) + GripRoom;
if (!ImGuiPopOuts.InPopOutFrame)
{
if (_modeFlip)
{
// The flip happened mid-frame, so this frame measured the old layout: size next frame.
_modeFlip = false;
_modeFlipApply = true;
}
else if (_modeFlipApply)
{
_modeFlipApply = false;
_fit = false;
bool open = RynthAiDashboardState.ShowFiles;
bool known = RynthAiDashboardState.TryGetFilesModeSize(open, out float mw, out float mh);
float w = known ? mw : ImGuiNET.ImGui.GetWindowWidth() / place;
// Folded always shrinks to its one line; open comes back at the size it last had.
float h = open && known ? MathF.Max(mh, _contentHeight) : _contentHeight;
ImGuiPanelHost.RequestSize(Title, new Vector2(w, h));
return;
}
_winLogical = new Vector2(ImGuiNET.ImGui.GetWindowWidth() / place, ImGuiNET.ImGui.GetWindowHeight() / place);
}
if (_fit && !ImGuiPopOuts.InPopOutFrame)
{
_fit = false;
ImGuiPanelHost.RequestSize(Title, new Vector2(ImGuiNET.ImGui.GetWindowWidth() / place, _contentHeight));
}
}
// ── Title row: "R" + "YNTHAI DASHBOARD" | chips (drag surface) ──────
private void TitleRow(RynthAiSnapshot raw, float x0, float width, bool minimized)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
const int chips = 7;
const float chipW = 18, chipH = 16, chipGap = 2;
float chipsW = chips * chipW + (chips - 1) * chipGap;
float rowH = 20;
// Drag surface: everything left of the chips.
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y));
ImGuiNET.ImGui.InvisibleButton("##dash_drag", new Vector2(Math.Max(1, width - chipsW), rowH));
ImGuiPanelHost.DragWindowWithLastItem();
ImFontPtr title = ImGuiFonts.Get(UiFont.Dash14);
float ty = y + (rowH - title.FontSize) * 0.5f;
dl.PushClipRect(new Vector2(x0, y), new Vector2(x0 + Math.Max(1, width - chipsW - 4), y + rowH), true);
dl.AddText(title, title.FontSize, new Vector2(x0, ty), Teal, "R");
float rw = CalcWidth(title, "R");
dl.AddText(title, title.FontSize, new Vector2(x0 + rw, ty), White, "YNTHAI DASHBOARD");
dl.PopClipRect();
float cx = x0 + width - chipsW;
float cy = y + (rowH - chipH) * 0.5f;
var chip = new Vector2(chipW, chipH);
const UiFont chipFont = UiFont.Dash11;
bool target = RynthAiDashboardState.ShowTargetBar;
if (IconButton("##chip_target", new Vector2(cx, cy), chip, PhosphorIcons.Crosshair, chipFont, BtnFill, target ? Teal : Mute, BtnBord, 2))
{
RynthAiDashboardState.SetShowTargetBar(!target);
_fit = true;
}
ImGuiNET.ImGui.SetItemTooltip(target
? "Target bar on: the target's name and health at the bottom. Click to hide it."
: "Target bar off. Click to show the target's name and health at the bottom.");
cx += chipW + chipGap;
bool vitals = RynthAiDashboardState.ShowVitals;
if (IconButton("##chip_vitals", new Vector2(cx, cy), chip, PhosphorIcons.Heartbeat, chipFont, BtnFill, vitals ? Teal : Mute, BtnBord, 2))
{
RynthAiDashboardState.SetShowVitals(!vitals);
_fit = true;
}
ImGuiNET.ImGui.SetItemTooltip(vitals
? "Player vitals on: your health, stamina and mana at the bottom. Click to hide them."
: "Player vitals off. Click to show your health, stamina and mana at the bottom.");
cx += chipW + chipGap;
if (IconButton("##chip_lock", new Vector2(cx, cy), chip, raw.IsLocked ? PhosphorIcons.Lock : PhosphorIcons.LockOpen,
chipFont, BtnFill, raw.IsLocked ? Amber : Mute, BtnBord, 2))
RynthAiCommands.TogglePanelLock();
ImGuiNET.ImGui.SetItemTooltip(raw.IsLocked ? "Locked. Click to unlock the dashboard." : "Click to lock the dashboard in place.");
cx += chipW + chipGap;
if (IconButton("##chip_minus", new Vector2(cx, cy), chip, PhosphorIcons.Minus, chipFont, BtnFill, Mute, BtnBord, 2))
RynthAiCommands.AdjustOpacity(-0.1f);
ImGuiNET.ImGui.SetItemTooltip("More transparent");
cx += chipW + chipGap;
if (IconButton("##chip_plus", new Vector2(cx, cy), chip, PhosphorIcons.Plus, chipFont, BtnFill, Mute, BtnBord, 2))
RynthAiCommands.AdjustOpacity(0.1f);
ImGuiNET.ImGui.SetItemTooltip("More opaque");
cx += chipW + chipGap;
if (IconButton("##chip_min", new Vector2(cx, cy), chip,
minimized ? PhosphorIcons.ArrowsOutLineVertical : PhosphorIcons.ArrowsInLineVertical, chipFont, BtnFill, Mute, BtnBord, 2))
{
RynthAiDashboardState.SetMinimized(!minimized);
_fit = true; // the window fits the other mode's content next frame
}
ImGuiNET.ImGui.SetItemTooltip(minimized ? "Expand" : "Minimize");
cx += chipW + chipGap;
if (PanelRouter.CanPopOut)
{
if (IconButton("##chip_dock", new Vector2(cx, cy), chip, ImGuiPanelHost.PopOutGlyph, chipFont, BtnFill, Mute, BtnBord, 2))
ImGuiPanelHost.TogglePopOut(Title);
ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip);
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + rowH));
}
// ── Header: macro + state (40%) | Profile/Nav/Loot/Meta pickers (60%) ──
private void HeaderGrid(RynthAiView? view, RynthAiSnapshot raw, float x0, float width)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float y0 = ImGuiNET.ImGui.GetCursorScreenPos().Y + 2;
float leftW = width * 0.4f;
// Left: Meta State / Bot Activity (the macro start/stop is the control row's first square).
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10);
float ly = y0;
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly), Mute, "Meta State:");
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.MetaStateText ?? "Default");
ly += 2 * (f10.FontSize + 1) + 4;
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly), Mute, "Bot Activity:");
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.BotActivityText ?? "Idle");
float leftBottom = ly + 2 * (f10.FontSize + 1);
// Right: four selector rows (label 36 px, picker fills, spacing 3).
float rx = x0 + leftW, rw = width - leftW, ry = y0;
// The fold arrow sits at the end of the Profile row, where it always fits.
const float foldW = 18f;
Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, rx, ry, rw - foldW - 2, null);
if (IconButton("##files_fold", new Vector2(rx + rw - foldW, ry), new Vector2(foldW, 16), PhosphorIcons.CaretUp, UiFont.Dash11, BtnFill, Mute, BtnBord, 2))
{
RynthAiDashboardState.SetFilesModeSize(true, _winLogical.X, _winLogical.Y);
RynthAiDashboardState.SetShowFiles(false);
_modeFlip = true;
}
ImGuiNET.ImGui.SetItemTooltip("Fold the loaded files into one line");
ry += 16 + 3;
Selector(1, "Nav:", view?.NavText ?? "None", raw.NavProfiles, raw.SelectedNavIdx, 0, rx, ry, rw, null);
ry += 16 + 3;
Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, rx, ry, rw, raw);
ry += 16 + 3;
Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, rx, ry, rw, null);
ry += 16;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, Math.Max(leftBottom, ry) + 4));
}
private static readonly string[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta" };
private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta" };
private static readonly string[] NoneItems = { "None" };
private void Selector(int slot, string label, string text, string[] items, int selected, int kind,
float x, float y, float w, RynthAiSnapshot? lootEdit)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10), f9 = ImGuiFonts.Get(UiFont.Dash9);
dl.AddText(f10, f10.FontSize, new Vector2(x, y + (16 - f10.FontSize) * 0.5f), Mute, label);
float editW = 0;
if (lootEdit != null)
{
editW = 18;
var ep = new Vector2(x + w - editW, y);
if (IconButton("##loot_edit", ep, new Vector2(editW, 16), PhosphorIcons.TreasureChest, UiFont.Dash11, SelectorBg, Mute, 0, 2))
{
string path = !string.IsNullOrEmpty(lootEdit.VendorProfilePath) ? lootEdit.VendorProfilePath : lootEdit.CurrentLootPath;
// The in-game Loot Editor panel. The external editor is one click away on the
// panel's toolbar (LootEditorFace.LaunchExternal, an STA thread of its own).
LootEditorFace.ToggleFor(path);
}
ImGuiNET.ImGui.SetItemTooltip("Loot Editor: the loot profile in use, or the open vendor's AutoVendor profile.");
editW += 3;
}
var pos = new Vector2(x + 36, y);
var size = new Vector2(Math.Max(20, w - 36 - editW), 16);
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(SelectorIds[slot], size);
bool hovered = ImGuiNET.ImGui.IsItemHovered();
if (ImGuiNET.ImGui.IsItemActivated())
_pressedWhileOpen[slot] = ImGuiNET.ImGui.GetFrameCount() - _pickerShownFrame[slot] <= 1;
bool open = ImGuiNET.ImGui.IsPopupOpen(PickerIds[slot]);
dl.AddRectFilled(pos, pos + size, hovered ? Lighten(SelectorBg) : SelectorBg, 2);
dl.AddRect(pos, pos + size, BtnBord, 2);
const float arrowW = 12;
dl.PushClipRect(pos, pos + size - new Vector2(arrowW + 4, 0), true);
dl.AddText(f9, f9.FontSize, pos + new Vector2(5, (16 - f9.FontSize) * 0.5f), White, text);
dl.PopClipRect();
PhosphorIcons.DrawCentered(dl, f10, open ? PhosphorIcons.CaretUp : PhosphorIcons.CaretDown,
new Vector2(pos.X + size.X - arrowW - 3, y), new Vector2(arrowW, 16), Mute);
if (clicked && !_pressedWhileOpen[slot] && !open)
{
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(pos.X, pos.Y + size.Y + 2));
ImGuiNET.ImGui.OpenPopup(PickerIds[slot]);
}
Picker(slot, items.Length == 0 ? NoneItems : items, Math.Clamp(selected, 0, Math.Max(0, items.Length - 1)), kind, items.Length > 0);
}
private void Picker(int slot, string[] items, int selected, int kind, bool real)
{
// Same look as the Avalonia picker: 200 wide, teal border, radius 6.
float maxH = Math.Min(items.Length * 26 + 12, Math.Max(60,
ImGuiNET.ImGui.GetIO().DisplaySize.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - 20));
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(200, maxH));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 6f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(2, 2));
bool open = ImGuiNET.ImGui.BeginPopup(PickerIds[slot]);
ImGuiNET.ImGui.PopStyleVar(4);
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return;
_pickerShownFrame[slot] = ImGuiNET.ImGui.GetFrameCount();
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
for (int i = 0; i < items.Length; i++)
{
ImGuiNET.ImGui.PushID(i);
bool isSel = i == selected;
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (ItemButton("##item", p, new Vector2(w, 24), items[i], isSel ? TealSoft : BtnFill, isSel ? Teal : White))
{
if (real) RynthAiCommands.SelectProfile(kind, i);
ImGuiNET.ImGui.CloseCurrentPopup();
}
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.EndPopup();
}
private static bool ItemButton(string id, Vector2 pos, Vector2 size, string text, uint bg, uint fg)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(bg) : bg;
dl.AddRectFilled(pos, pos + size, fill, 3);
dl.AddRect(pos, pos + size, BtnBord, 3);
ImFontPtr f = ImGuiFonts.Get(UiFont.Dash11);
dl.PushClipRect(pos, pos + size, true);
dl.AddText(f, f.FontSize, pos + new Vector2(8, (size.Y - f.FontSize) * 0.5f), fg, text);
dl.PopClipRect();
return clicked;
}
// ── Control row: (ON/OFF) combat, buffing, nav, looting, meta ... force rebuff ──
private const float Square = 24, SquareStep = 27, RowPad = 3;
private void ControlRow(RynthAiView? view, RynthAiSnapshot raw, float x0, float width, bool minimized, uint boxBg)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float top = ImGuiNET.ImGui.GetCursorScreenPos().Y;
float bottom = top + Square + 2 * RowPad;
dl.AddRectFilled(new Vector2(x0, top), new Vector2(x0 + width, bottom), boxBg, 3);
dl.AddRect(new Vector2(x0, top), new Vector2(x0 + width, bottom), BtnBord, 3);
float x = x0 + 5, y = top + RowPad;
// Macro start/stop: a square like the toggles, green with a Stop glyph while running.
{
bool on = raw.MacroRunning;
if (IconButton("##macro", new Vector2(x, y), new Vector2(Square, Square), on ? PhosphorIcons.Stop : PhosphorIcons.Play,
UiFont.Dash14, on ? MacroRun : BarBg, on ? White : Mute, on ? Green : BtnBord, 3))
RynthAiCommands.ToggleMacro();
ImGuiNET.ImGui.SetItemTooltip(on ? "Macro running. Click to stop it." : "Macro stopped. Click to start it.");
x += SquareStep + 6;
}
Toggle("##t_combat", PhosphorIcons.Sword, raw.CombatEnabled, 0, new Vector2(x, y), "Combat");
x += SquareStep;
Toggle("##t_buff", PhosphorIcons.Sparkle, raw.BuffingEnabled, 1, new Vector2(x, y), "Buffing");
x += SquareStep;
Toggle("##t_nav", PhosphorIcons.SneakerMove, raw.NavigationEnabled, 2, new Vector2(x, y), "Navigation");
x += SquareStep;
Toggle("##t_loot", PhosphorIcons.Bag, raw.LootingEnabled, 3, new Vector2(x, y), "Looting");
x += SquareStep;
Toggle("##t_meta", PhosphorIcons.Code, raw.MetaEnabled, 4, new Vector2(x, y), "Meta (the macro rules)");
x += SquareStep;
// The pickers fold out from a caret left of FR (expanded mode, while folded away).
const float caretW = 16f;
bool caret = !minimized && !RynthAiDashboardState.ShowFiles;
float frX = x0 + width - 5 - Square;
if (caret)
{
if (IconButton("##files_open", new Vector2(frX - 4 - caretW, y), new Vector2(caretW, Square), PhosphorIcons.CaretDown,
UiFont.Dash11, BtnFill, Teal, BtnBord, 2))
{
RynthAiDashboardState.SetFilesModeSize(false, _winLogical.X, _winLogical.Y);
RynthAiDashboardState.SetShowFiles(true);
_modeFlip = true;
}
ImGuiNET.ImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") +
"\nLoot: " + (view?.LootText ?? "None") + "\nMeta: " + (view?.MetaText ?? "None") +
"\n\nClick to show the Profile, Nav, Loot and Meta pickers.");
}
// What the bot is doing, always in view (every mode, minimized too): between the toggles and FR.
{
ImFontPtr af = ImGuiFonts.Get(UiFont.Dash10);
float ax = x + 2, aRight = (caret ? frX - 4 - caretW : frX) - 6;
if (aRight - ax > 20)
{
string activity = view?.BotActivityText ?? "Idle";
float ay = y + (Square - af.FontSize) * 0.5f;
dl.PushClipRect(new Vector2(ax, y), new Vector2(aRight, y + Square), true);
dl.AddText(af, af.FontSize, new Vector2(ax, ay), Amber, activity);
dl.PopClipRect();
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(ax, y));
ImGuiNET.ImGui.InvisibleButton("##activity", new Vector2(aRight - ax, Square));
ImGuiNET.ImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + (view?.MetaStateText ?? "Default"));
}
}
// Force rebuff, set apart at the right (DrakBot's place for it).
if (IconButton("##fr", new Vector2(x0 + width - 5 - Square, y), new Vector2(Square, Square), PhosphorIcons.ArrowsClockwise,
UiFont.Dash14, FrFill, Amber, BtnBord, 3))
RynthAiCommands.ForceRebuff();
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
RynthAiCommands.CancelForceRebuff();
ImGuiNET.ImGui.SetItemTooltip("Force rebuff (FR): recast all buffs. Right-click: cancel.");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, bottom));
ImGuiNET.ImGui.Dummy(new Vector2(width, 0));
}
private void Toggle(string id, string icon, bool on, int subsystem, Vector2 pos, string name)
{
if (IconButton(id, pos, new Vector2(Square, Square), icon, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, 3))
RynthAiCommands.SetSubsystemEnabled(subsystem, !on);
ImGuiNET.ImGui.SetItemTooltip(on ? name + " on. Click to turn it off." : name + " off. Click to turn it on.");
}
// ── Launchers: one row of icon buttons ──────────────────────────────
private const float LauncherH = 22, LauncherGap = 2;
private void Launchers(float x0, float width)
{
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
const int buttons = 8;
float bw = MathF.Floor((width - buttons * LauncherGap) / buttons);
// Short labels only when every button has room for its icon and label.
bool labels = bw >= 68;
float x = x0;
Launcher("##l_meta", PhosphorIcons.ListChecks, "Meta", "Meta: the macro rules", x, y, bw, labels, () => PanelRouter.Toggle("Meta"));
x += bw + LauncherGap;
Launcher("##l_lua", PhosphorIcons.FileCode, "Lua", "Lua scripts", x, y, bw, labels, () => PanelRouter.Toggle("Lua"));
x += bw + LauncherGap;
// Monsters opens the Damage panel (the basic Monsters panel and its
// Simple/Advanced chip were retired 2026-10-01).
Launcher("##l_mon", PhosphorIcons.Skull, "Monsters", "Monsters: weapons, spells and rules per monster (the Damage panel)",
x, y, bw, labels, PanelRouter.ToggleMonsters);
x += bw + LauncherGap;
Launcher("##l_set", PhosphorIcons.Gear, "Settings", "Settings", x, y, bw, labels, () => PanelRouter.Toggle("Settings"));
x += bw + LauncherGap;
Launcher("##l_nav", PhosphorIcons.MapTrifold, "Nav", "Nav: routes", x, y, bw, labels, () => PanelRouter.Toggle("Nav"));
x += bw + LauncherGap;
Launcher("##l_map", PhosphorIcons.MapPin, "Map", "Dungeon Map (shows while you're in a dungeon)", x, y, bw, labels,
() => PanelRouter.Toggle(DungeonMapFace.Title));
x += bw + LauncherGap;
Launcher("##l_items", PhosphorIcons.Backpack, "Items", "Items", x, y, bw, labels, () => PanelRouter.Toggle("Items"));
x += bw + LauncherGap;
Launcher("##l_patrol", PhosphorIcons.Footprints, "Patrol",
"Patrol. Left-click: start dungeon patrol. Right-click: routes & recorded hazards.", x, y, bw, labels,
() => RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}"));
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1));
ImGuiNET.ImGui.OpenPopup("##patrol");
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + LauncherH));
}
private void Launcher(string id, string icon, string label, string tooltip, float x, float y, float w, bool showLabel, Action? onClick)
{
var pos = new Vector2(x, y);
var size = new Vector2(Math.Max(10, w), LauncherH);
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
ImGuiNET.ImGui.SetItemTooltip(tooltip);
uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill;
dl.AddRectFilled(pos, pos + size, fill, 3);
dl.AddRect(pos, pos + size, BtnBord, 3);
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Dash14);
if (showLabel)
{
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Dash9);
const float iconBox = 16;
PhosphorIcons.DrawCentered(dl, iconFont, icon, pos + new Vector2(4, 0), new Vector2(iconBox, LauncherH), Mute);
dl.PushClipRect(pos, pos + size, true);
dl.AddText(f9, f9.FontSize, new Vector2(pos.X + 4 + iconBox + 4, pos.Y + (LauncherH - f9.FontSize) * 0.5f), Mute, label);
dl.PopClipRect();
}
else
{
PhosphorIcons.DrawCentered(dl, iconFont, icon, pos, size, Mute);
}
if (clicked && onClick != null)
{
onClick();
}
}
// ── Footer: FPS | version | uptime ─────────────────────────────────────
private void Footer(RynthAiView? view, float x0, float width)
{
int fps = (int)MathF.Round(D3D9.EndSceneHook.MeasuredFps);
if (fps != _fpsShown) { _fpsShown = fps; _fpsText = fps > 0 ? $"FPS {fps}" : "FPS —"; }
DateTime started = EntryPoint.InitStartedUtc;
if (started != DateTime.MinValue)
{
TimeSpan up = DateTime.UtcNow - started;
long secs = (long)up.TotalSeconds;
if (secs != _upShown)
{
_upShown = secs;
_upText = up.TotalHours >= 1 ? $"Up {(int)up.TotalHours}:{up.Minutes:D2}:{up.Seconds:D2}" : $"Up {up.Minutes}:{up.Seconds:D2}";
}
}
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10);
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
float fpsW = CalcWidth(f10, _fpsText), upW = CalcWidth(f10, _upText);
dl.AddText(f10, f10.FontSize, new Vector2(x0, y), Mute, _fpsText);
dl.AddText(f10, f10.FontSize, new Vector2(x0 + width - upW, y), Mute, _upText);
// The version between them: centred when there's room, else after FPS, clipped short of the uptime.
string version = view?.Version ?? string.Empty;
if (version.Length > 0)
{
float left = x0 + fpsW + 8, right = x0 + width - upW - 8;
if (right > left)
{
float vw = CalcWidth(f10, version);
float vx = x0 + (width - vw) * 0.5f;
if (vx < left || vx + vw > right) vx = left;
dl.PushClipRect(new Vector2(left, y), new Vector2(right, y + f10.FontSize + 2), true);
dl.AddText(f10, f10.FontSize, new Vector2(vx, y), Mute, version);
dl.PopClipRect();
}
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + f10.FontSize + 2));
ImGuiNET.ImGui.Dummy(new Vector2(width, 0));
}
// ── Bars (bottom): player vitals, then the target ──────────────────────
private const float VitalsH = 14 + 3 + 14 + 3 + 14;
private void Bars(RynthAiView? view, RynthAiSnapshot raw, float x0, float width, uint boxBg)
{
bool vitals = RynthAiDashboardState.ShowVitals, target = RynthAiDashboardState.ShowTargetBar;
if (!vitals && !target) return;
Gap(4);
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr f11 = ImGuiFonts.Get(UiFont.Dash11), f10 = ImGuiFonts.Get(UiFont.Dash10);
// The target's stamina/mana rows are held while that option is on, so they
// don't grow the box (and the window) as targets come and go.
bool subRows = raw.ShowTargetStaminaMana;
float targetH = f11.FontSize + 2 + 3 + 12 + (subRows ? 2 * (13 + 3) - 3 : 0);
float top = ImGuiNET.ImGui.GetCursorScreenPos().Y;
float height = 5 + (vitals ? VitalsH : 0) + (vitals && target ? 6 : 0) + (target ? targetH : 0) + 4;
var tl = new Vector2(x0, top);
var br = new Vector2(x0 + width, top + height);
dl.AddRectFilled(tl, br, boxBg, 3);
dl.AddRect(tl, br, BtnBord, 3);
float rx = x0 + 5, rw = width - 10, ry = top + 5;
if (vitals)
{
VitalRow(dl, rx, ry, rw, PhosphorIcons.Heart, view?.Health ?? default, Hp, f10); ry += 14 + 3;
VitalRow(dl, rx, ry, rw, PhosphorIcons.Lightning, view?.Stamina ?? default, Green, f10); ry += 14 + 3;
VitalRow(dl, rx, ry, rw, PhosphorIcons.Drop, view?.Mana ?? default, Mana, f10); ry += 14;
if (target) ry += 6;
}
if (target)
{
// Crosshair + name | health, then the 15-segment bar.
string hpText = raw.TargetHealthDisplay;
float hpW = CalcWidth(f11, hpText);
float iconW = CalcWidth(f11, PhosphorIcons.Crosshair);
dl.AddText(f11, f11.FontSize, new Vector2(rx, ry), Mute, PhosphorIcons.Crosshair);
dl.PushClipRect(new Vector2(rx, ry), new Vector2(rx + rw - hpW - 4, ry + f11.FontSize + 2), true);
dl.AddText(f11, f11.FontSize, new Vector2(rx + iconW + 3, ry), TextDim, view?.TargetHeadline ?? "NO TARGET");
dl.PopClipRect();
dl.AddText(f11, f11.FontSize, new Vector2(rx + rw - hpW, ry), White, hpText);
ry += f11.FontSize + 2 + 3;
// 15-segment gradient bar, 10 high, 2 px between segments.
int lit = view?.TargetSegmentsLit ?? 0;
float segW = (rw - 2 * (RynthAiView.Segments - 1)) / RynthAiView.Segments;
for (int i = 0; i < RynthAiView.Segments; i++)
{
float sx = rx + i * (segW + 2);
dl.AddRectFilled(new Vector2(sx, ry + 1), new Vector2(sx + segW, ry + 11), i < lit ? SegmentColors[i] : BarBg, 1);
}
ry += 12;
if (subRows)
{
bool shown = view != null && view.ShowTargetSubBars;
ry += 3;
CompactBar(dl, rx, ry, rw, shown ? view!.TargetStamina : default, Green, f10); ry += 13 + 3;
CompactBar(dl, rx, ry, rw, shown ? view!.TargetMana : default, Mana, f10);
}
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, top + height));
ImGuiNET.ImGui.Dummy(new Vector2(width, 0));
}
private static void CompactBar(ImDrawListPtr dl, float x, float y, float w, VitalView bar, uint color, ImFontPtr font)
{
var a = new Vector2(x, y + 1);
var b = new Vector2(x + w, y + 12);
dl.AddRectFilled(a, b, BarBg, 2);
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, 2);
dl.AddText(font, font.FontSize, new Vector2(x + 4, y + 1 + (11 - font.FontSize) * 0.5f), White, bar.Text ?? "");
}
private static void VitalRow(ImDrawListPtr dl, float x, float y, float w, string icon, VitalView bar, uint color, ImFontPtr font)
{
var a = new Vector2(x, y + 1);
var b = new Vector2(x + w, y + 14);
dl.AddRectFilled(a, b, BarBg, 6);
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, 6);
float ty = y + 1 + (13 - font.FontSize) * 0.5f;
dl.AddText(font, font.FontSize, new Vector2(x + 4, ty), Mute, icon);
dl.AddText(font, font.FontSize, new Vector2(x + 4 + CalcWidth(font, icon) + 3, ty), White, bar.Text ?? "");
}
// ── Patrol flyout (right-click Patrol) ────────────────────────────────
private void PatrolPopup()
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(260, 0), new Vector2(260, 376));
bool open = ImGuiNET.ImGui.BeginPopup("##patrol");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(2);
if (open != _patrolOpen)
{
_patrolOpen = open;
if (open) { UiSources.Patrol.Subscribe(); UiSources.Patrol.RequestRefresh(); }
else UiSources.Patrol.Unsubscribe();
}
if (!open) return;
var snap = UiSources.Patrol.Current;
PatrolInfo info = snap?.Value ?? new PatrolInfo();
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash10));
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash11));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), PhosphorIcons.Footprints + " PATROL & ROUTES");
ImGuiNET.ImGui.PopFont();
Section("THIS DUNGEON");
if (info.InDungeon)
{
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{info.CurrentLandblock} · {info.CurrentHazards} hazard cell(s)");
if (info.CurrentHazards > 0)
{
ImGuiNET.ImGui.SameLine();
if (Mini("Clear##cur"))
RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{info.CurrentLandblock}\"}}", refreshPatrol: true);
}
if (Mini(MarkHazardLabel))
RynthAiCommands.SendNavCommand("{\"Cmd\":\"markHazardHere\"}", refreshPatrol: true);
ImGuiNET.ImGui.SameLine();
if (Mini("Unmark"))
RynthAiCommands.SendNavCommand("{\"Cmd\":\"unmarkHazardHere\"}", refreshPatrol: true);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, RynthTheme.Vec(0xFFB8C8D8));
ImGuiNET.ImGui.TextWrapped("Stand on the lava/acid, click Mark, then re-run Patrol.");
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.PopFont();
}
else
{
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "Not in a dungeon.");
}
Section($"RECORDED HAZARDS ({info.Dungeons.Length})");
if (info.Dungeons.Length == 0)
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "None recorded yet.");
for (int i = 0; i < info.Dungeons.Length; i++)
{
DungeonHazards d = info.Dungeons[i];
ImGuiNET.ImGui.PushID(i);
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{d.Landblock} · {d.Cells} cell(s)");
ImGuiNET.ImGui.SameLine();
if (Mini("Clear"))
RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{d.Landblock}\"}}", refreshPatrol: true);
ImGuiNET.ImGui.PopID();
}
if (info.Dungeons.Length > 0 && Mini("Clear all recorded hazards"))
RynthAiCommands.SendNavCommand("{\"Cmd\":\"clearHazardsAll\"}", refreshPatrol: true);
Section($"SAVED ROUTES ({info.Routes.Length})");
if (info.Routes.Length == 0)
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "No .nav routes saved.");
foreach (string name in info.Routes)
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "• " + name);
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.EndPopup();
}
private const string MarkHazardLabel = PhosphorIcons.Warning + " Mark cell as hazard";
private static void Section(string text)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), text);
ImGuiNET.ImGui.PopFont();
}
private static bool Mini(string label)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, Lighten(BtnFill));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonActive, Darken(BtnFill));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 2f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(6, 1));
bool clicked = ImGuiNET.ImGui.Button(label);
ImGuiNET.ImGui.PopStyleVar(3);
ImGuiNET.ImGui.PopStyleColor(5);
ImGuiNET.ImGui.PopFont();
return clicked;
}
// ── Shared helpers ────────────────────────────────────────────────────
/// <summary>Draws the Avalonia face's flat button frame; returns true on left click.</summary>
private static bool ButtonFrame(string id, Vector2 pos, Vector2 size, uint bg, uint border, float rounding)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight)
&& ImGuiNET.ImGui.IsMouseReleased(ImGuiMouseButton.Left);
uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(bg) : bg;
dl.AddRectFilled(pos, pos + size, fill, rounding);
if (border != 0) dl.AddRect(pos, pos + size, border, rounding);
return clicked;
}
/// <summary>A flat button with centred text; returns true on left click.</summary>
private static bool Button(string id, Vector2 pos, Vector2 size, string text, UiFont font,
uint bg, uint fg, uint border, float rounding)
{
bool clicked = ButtonFrame(id, pos, size, bg, border, rounding);
ImFontPtr f = ImGuiFonts.Get(font);
float tw = CalcWidth(f, text);
ImGuiNET.ImGui.GetWindowDrawList().AddText(f, f.FontSize, pos + new Vector2((size.X - tw) * 0.5f, (size.Y - f.FontSize) * 0.5f), fg, text);
return clicked;
}
/// <summary>A flat button with a Phosphor icon centred on it; returns true on left click.</summary>
private static bool IconButton(string id, Vector2 pos, Vector2 size, string icon, UiFont font,
uint bg, uint fg, uint border, float rounding)
{
bool clicked = ButtonFrame(id, pos, size, bg, border, rounding);
PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(font), icon, pos, size, fg);
return clicked;
}
private static float CalcWidth(ImFontPtr font, string text)
{
ImGuiNET.ImGui.PushFont(font);
float w = ImGuiNET.ImGui.CalcTextSize(text).X;
ImGuiNET.ImGui.PopFont();
return w;
}
private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12);
private static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0);
private static uint Scale(uint abgr, float k, int add)
{
uint a = abgr & 0xFF000000;
uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add);
uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add);
uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add);
return a | (b << 16) | (g << 8) | r;
}
private static void Gap(float h) => ImGuiNET.ImGui.Dummy(new Vector2(0, h));
private static uint[] BuildSegmentColors()
{
var colors = new uint[RynthAiView.Segments];
for (int i = 0; i < colors.Length; i++)
{
float t = (float)i / (colors.Length - 1);
uint r, g, b;
if (t < 0.33f) { float f = t / 0.33f; r = 255; g = (uint)(f * 255); b = 0; }
else if (t < 0.66f) { float f = (t - 0.33f) / 0.33f; r = (uint)((1f - f) * 255); g = 255; b = 0; }
else { float f = (t - 0.66f) / 0.34f; r = 0; g = 255; b = (uint)(f * 255); }
colors[i] = C(0xFF000000 | (r << 16) | (g << 8) | b);
}
return colors;
}
private static readonly RynthAiSnapshot Empty = new();
}

View file

@ -0,0 +1,226 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/RynthNavArrowFace.cs
// RynthNav's arrow: a small draggable overlay that points at RynthNav's arrow
// target relative to the way you face, with the distance, the compass point
// and the target's name (our take on GoArrow's arrow; Digero 2006, Virindi
// 2011, MIT). Shown and hidden from the RynthNav panel's Arrow tab; opens by
// itself when a command sets the arrow (RynthNavArrowWatch). Works popped out.
//
// arrow turns with you every frame (the pose snapshot's heading); green
// within 30 yd, amber while it points at a portal on a route; a
// wand instead of the arrow when the next step is a recall.
// text name, distance and compass point, the route step.
// buttons pop out, hide; Go (RynthNav walks there) and Stop.
//
// The target comes from RynthNav's status (UiSources.RynthNav); RynthNav owns
// it and decides arrival. AC's render thread: snapshots only, no AC calls, and
// strings are rebuilt only when what they show changes.
// ============================================================================
using System;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class RynthNavArrowFace : IImGuiPanel
{
public const string Title = "RynthNav Arrow";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(236, 84), new Vector2(236, 84), PanelChrome.None, Background: 0, Rounding: 6, EdgeToEdge: true),
() => new RynthNavArrowFace());
/// <summary>Shows the overlay (any thread). Only where ImGui faces are drawn.</summary>
public static void Show()
{
if (!ImGuiPanelHost.IsOpen(Title) && PanelRouter.ResolveDockedFace(Title) == PanelFace.ImGui)
ImGuiPanelHost.Open(Title);
}
/// <summary>The arrow turns with you: redraw popped out often enough to look smooth.</summary>
public int PopOutIdleHz => 20;
private static readonly uint Glass = RynthTheme.Argb(0xDC0A0F14), Ring = RynthTheme.Argb(0xFF1A2A39);
private readonly ArrowReadout _read = new();
public void OnShown()
{
UiSources.RynthNav.Subscribe();
UiSources.RynthNav.RequestRefresh();
}
public void OnHidden() => UiSources.RynthNav.Unsubscribe();
public void Draw()
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
if (size.X < 40 || size.Y < 40) return;
RynthNavStatus? st = UiSources.RynthNav.Current?.Value;
_read.Update(st);
dl.AddRectFilled(origin, origin + size, Glass, 6);
dl.AddRect(origin, origin + size, BtnBord, 6);
// The arrow, in a ring on the left.
float d = size.Y - 12;
Vector2 c = origin + new Vector2(6 + d * 0.5f, size.Y * 0.5f);
dl.AddCircleFilled(c, d * 0.5f, ShellBg, 32);
dl.AddCircle(c, d * 0.5f, Ring, 32, 1.5f);
_read.DrawPointer(dl, c, d * 0.5f - 6);
// Text.
float tx = origin.X + d + 14, right = origin.X + size.X - 6;
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), f10 = ImGuiFonts.Get(UiFont.Ui10), f9 = ImGuiFonts.Get(UiFont.Ui9);
dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 46, origin.Y + size.Y), true);
dl.AddText(bold, bold.FontSize, new Vector2(tx, origin.Y + 6), Teal, _read.Line1);
dl.PopClipRect();
dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right, origin.Y + size.Y), true);
dl.AddText(f10, f10.FontSize, new Vector2(tx, origin.Y + 26), Text, _read.Line2);
dl.PopClipRect();
dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 48, origin.Y + size.Y), true);
dl.AddText(f9, f9.FontSize, new Vector2(tx, origin.Y + size.Y - 6 - f9.FontSize - 2), Mute, _read.Line3);
dl.PopClipRect();
// Buttons (before the surface, so they win the hover).
const float b = 20, gap = 3;
var closePos = new Vector2(right - b, origin.Y + 5);
var popPos = closePos - new Vector2(b + gap, 0);
if (PanelRouter.CanPopOut)
{
if (IconButton("##rna_pop", ImGuiPanelHost.PopOutGlyph, popPos, new Vector2(b, b), Mute, BtnFill, font: UiFont.Ui11))
ImGuiPanelHost.TogglePopOut(Title);
ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip);
}
if (IconButton("##rna_close", PhosphorIcons.X, closePos, new Vector2(b, b), Mute, BtnFill, font: UiFont.Ui11))
ImGuiPanelHost.Close(Title);
ImGuiNET.ImGui.SetItemTooltip("Hide the arrow (the RynthNav panel's Arrow tab shows it again)");
var stopPos = new Vector2(right - b, origin.Y + size.Y - b - 5);
var goPos = stopPos - new Vector2(b + gap, 0);
bool canGo = _read.CanGo;
if (IconButton("##rna_go", PhosphorIcons.Play, goPos, new Vector2(b, b), Green, BtnFill, enabled: canGo, font: UiFont.Ui11)
&& st?.Arrow is RynthNavArrow ar)
RynthNavCommands.Go(ar.Final, ar.FinalNs, ar.FinalEw);
ImGuiNET.ImGui.SetItemTooltip("Go: RynthNav walks there (with portals and recalls when its routing is on)");
if (IconButton("##rna_stop", PhosphorIcons.Stop, stopPos, new Vector2(b, b), Red, BtnFill, font: UiFont.Ui11))
RynthNavCommands.Move(5);
ImGuiNET.ImGui.SetItemTooltip("Stop walking");
// Surface: drag moves the overlay (the OS window when popped out).
ImGuiNET.ImGui.SetCursorScreenPos(origin);
ImGuiNET.ImGui.InvisibleButton("##rna_surface", size);
ImGuiPanelHost.DragWindowWithLastItem();
if (ImGuiNET.ImGui.IsItemHovered() && _read.Tooltip.Length > 0) ImGuiNET.ImGui.SetItemTooltip(_read.Tooltip);
}
}
/// <summary>
/// What the arrow shows this frame: the target from RynthNav's status, your position and
/// heading from the pose snapshot. Shared by the overlay and the panel's Arrow tab. AC's
/// render thread; the text is rebuilt only when what it shows changes.
/// </summary>
internal sealed class ArrowReadout
{
public string Line1 = "No arrow", Line2 = "", Line3 = "", Tooltip = "";
public bool HasTarget, CanGo, Pointing;
public float Relative; // degrees clockwise from straight ahead
public double Distance = double.NaN;
public string Kind = "";
private RynthNavArrow? _arrow;
private int _distKey = int.MinValue, _compassKey = -1;
private bool _wasInDungeon, _wasAvailable = true;
private string _compass = "";
private static readonly uint NearCol = RynthTheme.Argb(0xFF40D973);
public void Update(RynthNavStatus? st)
{
RynthNavArrow? a = st?.Arrow;
bool available = st == null || st.Travel;
if (!ReferenceEquals(a, _arrow) || available != _wasAvailable)
{
_arrow = a;
_wasAvailable = available;
_distKey = int.MinValue;
_compassKey = -1;
HasTarget = a != null;
Kind = a?.Kind ?? "";
CanGo = a != null && (a.FinalNs != 0 || a.FinalEw != 0);
Line1 = a == null ? (available ? "No arrow" : "RynthNav is too old for the arrow") : a.Name;
Line3 = a == null ? (available ? "Atlas, chat coords or /rnav arrow" : "")
: a.Kind == "recall" ? (a.StepText.Length > 0 ? a.StepText : "cast the recall")
: a.Kind == "portal" ? "walk into the portal" + (a.Steps > 1 ? $" · step {a.Step}/{a.Steps}" : "")
: a.Steps > 1 ? $"step {a.Step}/{a.Steps}" : a.Type;
Tooltip = a == null ? "" : (a.Kind == "recall" ? "Cast " + a.Name : a.Name + " " + a.CoordText)
+ (a.Steps > 1 ? "\nOn the way to " + a.Final : "");
Line2 = a == null ? "" : a.Kind == "recall" ? "Cast " + a.Name : a.CoordText;
}
Pointing = false;
if (a == null || a.Kind == "recall" || !a.OnMap) return;
if (!RynthNavAtlas.TryPlayerPos(out double ns, out double ew, out bool onMap, out _)) return;
if (!onMap)
{
if (!_wasInDungeon) { Line2 = "in a dungeon: no direction"; _wasInDungeon = true; _distKey = int.MinValue; }
return;
}
_wasInDungeon = false;
Distance = RynthNavAtlas.Distance(ns, ew, a.Ns, a.Ew);
double bearing = RynthNavAtlas.Bearing(ns, ew, a.Ns, a.Ew);
int compassKey = (int)Math.Round(((bearing % 360.0) + 360.0) % 360.0 / 22.5) & 15;
if (compassKey != _compassKey) { _compassKey = compassKey; _compass = RynthNavAtlas.CompassPoint(bearing); _distKey = int.MinValue; }
int key = Distance < 1000 ? (int)Math.Round(Distance) : 100000 + (int)Math.Round(Distance / 100);
if (key != _distKey)
{
_distKey = key;
Line2 = RynthNavStatus.Yards(Distance) + " " + _compass;
}
if (TryHeading(out float heading))
{
Relative = (float)bearing - heading;
Pointing = true;
}
}
/// <summary>The pointer at <paramref name="c"/>: an arrow, a wand for a recall, a dot when there's nothing.</summary>
public void DrawPointer(ImDrawListPtr dl, Vector2 c, float r)
{
if (!HasTarget) { dl.AddCircleFilled(c, 3, FaceKit.Mute); return; }
if (Kind == "recall")
{
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.MagicWand, c - new Vector2(r, r), new Vector2(2 * r, 2 * r), FaceKit.Amber);
return;
}
if (!Pointing) { PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Compass, c - new Vector2(r, r), new Vector2(2 * r, 2 * r), FaceKit.Mute); return; }
uint col = Kind == "portal" ? FaceKit.Amber : Distance <= 30 ? NearCol : FaceKit.Teal;
float rad = Relative * (MathF.PI / 180f);
float s = MathF.Sin(rad), co = MathF.Cos(rad);
Vector2 tip = Rot(c, 0, -r, s, co), left = Rot(c, -0.62f * r, 0.78f * r, s, co),
notch = Rot(c, 0, 0.36f * r, s, co), right = Rot(c, 0.62f * r, 0.78f * r, s, co);
dl.AddTriangleFilled(tip, left, notch, col);
dl.AddTriangleFilled(tip, notch, right, col);
}
private static Vector2 Rot(Vector2 c, float x, float y, float s, float co) =>
new(c.X + x * co - y * s, c.Y + x * s + y * co);
/// <summary>Your heading this frame (compass degrees) from the pose snapshot; no AC call (SenseFace's way).</summary>
private static bool TryHeading(out float heading)
{
heading = 0;
if (!PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out _, out _, out _, out _, out float qw, out float qz, out bool valid, out float h))
return false;
if (valid) { heading = h; return true; }
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
heading = (float)((-yaw % 360.0 + 720.0) % 360.0);
return true;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,103 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/ScriptWindowFace.cs
// Script windows (API v71): the panel face of one window a plugin submitted
// (UI/ScriptWindows). Hosted by ImGuiPanelHost like any panel (frame, saved
// placement, error isolation, input capture); Draw is the replay.
// Design: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §3, §2.5 (Geometry).
//
// Before the replay, inside the host's body child, the face reports the
// window's geometry (position, size, content region, cursor start, focused,
// hovered) in logical units at UI scale 1, as a Geometry event when a value
// moved by more than half a unit or a flag changed.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.ScriptWindows;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed unsafe class ScriptWindowFace : IImGuiPanel
{
private const float GeometryEpsilon = 0.5f;
private readonly ScriptWindow _window;
public ScriptWindowFace(ScriptWindow window) => _window = window;
public bool ClickThrough => (_window.Flags & WindowFlags.ClickThrough) != 0;
/// <summary>
/// Opened. Unless the owner asked for it (ScriptWindow.ExpectOpen), the player
/// opened it (bar, /rc ui open): the owner hears it once so its own visible flag
/// follows, and its flag stays stale until it has seen this event (§3.3). AC thread.
/// </summary>
public void OnShown() => NoteVisibility(visible: true);
/// <summary>Closed: as OnShown; a close the owner didn't ask for is the player's X unless the bar said otherwise.</summary>
public void OnHidden() => NoteVisibility(visible: false);
private void NoteVisibility(bool visible)
{
ScriptWindow w = _window;
bool expected;
if (visible) { expected = w.ExpectOpen; w.ExpectOpen = false; }
else { expected = w.ExpectClose; w.ExpectClose = false; }
int reason = w.PendingReason;
w.PendingReason = 0;
if (w.Removed || expected) return;
byte why = reason != 0 ? (byte)reason
: visible ? VisibilityReason.BarOrCommand : VisibilityReason.PlayerClose;
w.PlayerVisibilitySeq = w.Owner.Events.Visibility(w.Hash, visible, why);
}
public void Draw()
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
try
{
ScriptWindowMetrics.Refresh();
ReportGeometry();
ScriptWindowReplay.Draw(_window);
}
finally
{
ImGuiNET.ImGui.PopFont();
}
}
/// <summary>Queues a Geometry event when the body's geometry or focus/hover changed. AC thread.</summary>
private void ReportGeometry()
{
float s = EngineFrameController.FontScale;
if (!(s > 0f) || !float.IsFinite(s)) s = 1f;
Vector2 pos, size, avail, cursor;
ImGuiNative.igGetWindowPos(&pos);
ImGuiNative.igGetWindowSize(&size);
ImGuiNative.igGetContentRegionAvail(&avail);
ImGuiNative.igGetCursorPos(&cursor);
uint flags = 0;
if (ImGuiNative.igIsWindowFocused(ImGuiFocusedFlags.RootAndChildWindows) != 0) flags |= ScriptGeometry.Focused;
if (ImGuiNative.igIsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows) != 0) flags |= ScriptGeometry.Hovered;
var g = new ScriptGeometry
{
Pos = pos / s,
Size = size / s,
Avail = avail / s,
Cursor = cursor / s,
Flags = flags,
};
ScriptWindow w = _window;
if (w.GeometrySent && g.Flags == w.LastGeometry.Flags
&& !Moved(g.Pos, w.LastGeometry.Pos) && !Moved(g.Size, w.LastGeometry.Size)
&& !Moved(g.Avail, w.LastGeometry.Avail) && !Moved(g.Cursor, w.LastGeometry.Cursor))
return;
w.LastGeometry = g;
w.GeometrySent = true;
w.Owner.Events.Geometry(w.Hash, g);
}
private static bool Moved(Vector2 a, Vector2 b) =>
MathF.Abs(a.X - b.X) > GeometryEpsilon || MathF.Abs(a.Y - b.Y) > GeometryEpsilon;
}

View file

@ -0,0 +1,430 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/SenseFace.cs
// The Sense panel, our take on Virindi Sense: type a name, and every object
// the client knows about anywhere (not just in radar range) whose name
// matches shows up here. Engine only, ImGui only.
//
// add row a text box (Enter adds), Add, the settings gear, the help mark
// terms one chip per term: click it to switch it on/off, X removes it
// status how many matches among how many known objects (or why none)
// rows direction arrow (relative to where you face), name, kind,
// distance, compass point, map coordinates; nearest first; a new
// match flashes. Click selects it in game, hover for details.
// gear a chat line and/or the system beep when a new match appears
// (both off by default; they work with the panel closed).
//
// Data: SenseStore (the list, sense.txt) and UiSources.Sense (the 2 Hz scan on
// the pump thread, snapshots only; UI/Data/SenseData.cs). This face only reads
// the published view and the player pose snapshot (for the arrows, per frame)
// and parks a click's select with AcMainThreadQueue.EnqueueOverlaySelect, the
// path the Radar and the nameplates use. AC's render thread; no AC calls, no
// file I/O, no per-frame allocation except a hovered row's tooltip.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class SenseFace : IImGuiPanel
{
public const string Title = "Sense";
/// <summary>Registers the face (engine init) and queues the list's load so alerts work before it opens.</summary>
public static void Register()
{
ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(470, 360), new Vector2(300, 220), EdgeToEdge: true, GripInBody: true),
() => new SenseFace());
SenseStore.EnsureLoadQueued();
}
/// <summary>Arrows turn with you: 10 Hz idle popped out, 30 Hz while a new match flashes.</summary>
public int PopOutIdleHz => _flashing ? 30 : 10;
// ── Layout (px) and palette ──────────────────────────────────────────
private const float RowH = 20f, ArrowW = 20f, KindW = 58f, DistW = 64f, DirW = 34f, LocW = 116f, ChipH = 20f;
private const long FlashMs = 2500;
private static readonly uint Purple = RynthTheme.Argb(0xFFBF4DFF), ChipOff = RynthTheme.Argb(0xFF0E161E);
private const string HelpText =
"Sense lists every object the client knows about whose name matches a term on your list, however far away it is.\n\n" +
"How far: the client only knows what the server has sent it. That is everything in the landblocks it has loaded " +
"around you (outdoors: your landblock and the ones around it, a few hundred yards, far past the radar), or the whole " +
"dungeon you are in. Nothing beyond that reaches the client, so no plugin can see it.\n\n" +
"Terms ignore case. Without * or ? a name only has to contain the term (drake finds Dragon's Isle Drake). " +
"With them the whole name must match: Drake* starts with Drake, ? is any one letter.\n\n" +
"The distance shows when you and the object are both outdoors (or in surface buildings), or in the same dungeon. " +
"Otherwise the row says elsewhere and gives the landblock.\n\n" +
"Click a row to select it in game. Gear: a chat line or a beep when a new match appears.\n" +
"/rc sense opens and closes this panel.";
// ── State ───────────────────────────────────────────────────────────
private readonly byte[] _input = new byte[SenseStore.MaxTermLength + 1];
private string _message = "";
private uint _messageColor;
private long _messageUntilMs;
private bool _openSettings;
private bool _flashing;
public void OnShown()
{
SenseStore.EnsureLoadQueued();
UiSources.Sense.Subscribe();
UiSources.Sense.RequestRefresh();
}
public void OnHidden() => UiSources.Sense.Unsubscribe();
public void Draw()
{
float w = Begin(out Vector2 origin, out Vector2 size);
DrawAddRow(w);
DrawTerms(w);
SenseView view = UiSources.Sense.Current?.Value ?? SenseView.Empty;
DrawStatus(view);
bool showLoc = w - (ArrowW + KindW + DistW + DirW + LocW) >= 110;
DrawColumnHeader(w, showLoc);
float bodyH = Math.Max(40, Remaining(origin, size) - GripOverlap());
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
ImGuiNET.ImGui.BeginChild("##sense_rows", new Vector2(w, bodyH));
DrawRows(view, showLoc);
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
End(origin, size);
DrawSettingsPopup();
}
// ── Add row ─────────────────────────────────────────────────────────
private void DrawAddRow(float w)
{
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
const float h = 22, iconW = 22;
string addLabel = PhosphorIcons.Plus + " Add";
float addW = ButtonWidth(addLabel);
float boxW = Math.Max(60, w - addW - iconW * 2 - 12);
bool enter = TextBox("##sense_input", _input, start, boxW,
PhosphorIcons.MagnifyingGlass + " Name to watch for (* and ? wildcards)", out _,
ImGuiInputTextFlags.EnterReturnsTrue, h);
bool add = Button("##sense_add", addLabel, new Vector2(start.X + boxW + 4, start.Y), new Vector2(addW, h), Text, BtnFill,
enabled: SenseStore.Loaded);
ImGuiNET.ImGui.SetItemTooltip("Add the name to the watch list (Enter in the box does the same)");
if (enter || add) AddTerm();
float gx = start.X + boxW + 4 + addW + 4;
if (IconButton("##sense_gear", PhosphorIcons.Gear, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill))
_openSettings = true;
ImGuiNET.ImGui.SetItemTooltip("Alerts");
IconButton("##sense_help", PhosphorIcons.Info, new Vector2(gx + iconW + 4, start.Y), new Vector2(iconW, h), Mute, BtnFill);
if (ImGuiNET.ImGui.IsItemHovered())
{
ImGuiNET.ImGui.BeginTooltip();
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetFontSize() * 30);
ImGuiNET.ImGui.TextUnformatted(HelpText);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.EndTooltip();
}
NextLine(start, h + 4);
}
private void AddTerm()
{
string text = Utf8(_input);
bool ok = SenseStore.Add(text, out string message);
if (ok) WriteUtf8(_input, "");
ShowMessage(message, ok ? Mute : Amber);
}
private void ShowMessage(string text, uint color)
{
_message = text;
_messageColor = color;
_messageUntilMs = Environment.TickCount64 + 3000;
}
// ── Terms ───────────────────────────────────────────────────────────
private void DrawTerms(float w)
{
if (!SenseStore.Loaded)
{
Label("Loading the watch list...", Mute);
return;
}
SensePattern[] terms = SenseStore.Terms;
if (terms.Length == 0)
{
Label("No names yet: type one above and press Enter.", Mute);
return;
}
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Ui11);
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
float x = start.X, y = start.Y;
const float iconW = 18, xW = 16;
int toggle = -1, remove = -1;
for (int i = 0; i < terms.Length; i++)
{
SensePattern t = terms[i];
float textW = ImGuiNET.ImGui.CalcTextSize(t.Text).X;
float chipW = Math.Min(w, iconW + textW + 6 + xW);
if (x > start.X && x + chipW > start.X + w) { x = start.X; y += ChipH + 4; }
var p = new Vector2(x, y);
uint fg = t.Enabled ? Text : Faded(Mute);
ImGuiNET.ImGui.PushID(i);
ImGuiNET.ImGui.SetCursorScreenPos(p);
if (ImGuiNET.ImGui.InvisibleButton("##t", new Vector2(chipW - xW, ChipH))) toggle = i;
bool hotT = ImGuiNET.ImGui.IsItemHovered();
if (hotT)
ImGuiNET.ImGui.SetItemTooltip(t.Enabled
? (t.IsGlob ? "On: the whole name must match (wildcards). Click to switch off." : "On: names containing this match. Click to switch off.")
: "Off. Click to switch on.");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x + chipW - xW, y));
if (ImGuiNET.ImGui.InvisibleButton("##x", new Vector2(xW, ChipH))) remove = i;
bool hotX = ImGuiNET.ImGui.IsItemHovered();
if (hotX) ImGuiNET.ImGui.SetItemTooltip("Remove");
ImGuiNET.ImGui.PopID();
uint bg = t.Enabled ? BtnFill : ChipOff;
if (hotT) bg = Lighten(bg);
dl.AddRectFilled(p, p + new Vector2(chipW, ChipH), bg, 3);
dl.AddRect(p, p + new Vector2(chipW, ChipH), t.Enabled ? Teal : BtnBord, 3);
PhosphorIcons.DrawCentered(dl, iconFont, t.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square,
p, new Vector2(iconW, ChipH), t.Enabled ? Teal : fg);
dl.PushClipRect(p, p + new Vector2(chipW - xW, ChipH), true);
dl.AddText(new Vector2(x + iconW, y + (ChipH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), fg, t.Text);
dl.PopClipRect();
PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.X, new Vector2(x + chipW - xW, y), new Vector2(xW, ChipH),
hotX ? Red : Faded(Mute));
x += chipW + 4;
}
NextLine(start, y - start.Y + ChipH + 4);
if (toggle >= 0) SenseStore.SetEnabled(toggle, !terms[toggle].Enabled);
if (remove >= 0)
{
ShowMessage($"Stopped watching for \"{terms[remove].Text}\".", Mute);
SenseStore.Remove(remove);
}
}
// ── Status and header ───────────────────────────────────────────────
private void DrawStatus(SenseView view)
{
bool msg = _message.Length > 0 && Environment.TickCount64 < _messageUntilMs;
Label(msg ? _message : view.Status.Length > 0 ? view.Status : "Scanning...", msg ? _messageColor : Mute);
}
private static void DrawColumnHeader(float w, bool showLoc)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float ty = p.Y + 1;
float nameW = NameWidth(w, showLoc);
float x = p.X + ArrowW;
dl.AddText(new Vector2(x, ty), Mute, "Name");
x += nameW;
dl.AddText(new Vector2(x, ty), Mute, "Kind");
x += KindW;
dl.AddText(new Vector2(x, ty), Mute, "Dist");
x += DistW;
dl.AddText(new Vector2(x, ty), Mute, "Dir");
x += DirW;
if (showLoc) dl.AddText(new Vector2(x, ty), Mute, "Location");
ImGuiNET.ImGui.Dummy(new Vector2(w, ImGuiNET.ImGui.GetFontSize() + 2));
Separator(w);
}
private static float NameWidth(float w, bool showLoc) =>
Math.Max(40, w - ArrowW - KindW - DistW - DirW - (showLoc ? LocW : 0));
// ── Rows ────────────────────────────────────────────────────────────
private void DrawRows(SenseView view, bool showLoc)
{
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
SenseRow[] rows = view.Rows;
_flashing = false;
if (rows.Length == 0)
{
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(6, 6);
ImGuiNET.ImGui.GetWindowDrawList().AddText(at, Faded(Mute),
SenseStore.AnyEnabled ? "Nothing matching is in the client's range right now." : "Switch a term on to start watching.");
return;
}
var dl = ImGuiNET.ImGui.GetWindowDrawList();
long now = Environment.TickCount64;
uint selected = ClientHelperHooks.GetSelectedItemId();
float heading = PlayerHeading(out bool haveHeading);
float nameW = NameWidth(bw, showLoc);
float fontH = ImGuiNET.ImGui.GetFontSize();
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
float scroll = ImGuiNET.ImGui.GetScrollY();
float visible = ImGuiNET.ImGui.GetWindowHeight();
int first = Math.Max(0, (int)(scroll / RowH) - 1);
int last = Math.Min(rows.Length, (int)((scroll + visible) / RowH) + 2);
int clicked = -1, hovered = -1;
for (int i = first; i < last; i++)
{
SenseRow r = rows[i];
var p = new Vector2(start.X, start.Y + i * RowH);
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.PushID(i);
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(bw, RowH))) clicked = i;
bool hot = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.PopID();
if (hot) hovered = i;
bool isSel = r.Id == selected;
uint bg = isSel ? Selected : hot ? Lighten(PanelBg) : (i & 1) == 1 ? RowAlt : 0;
if (bg != 0) dl.AddRectFilled(p, p + new Vector2(bw, RowH), bg);
if (r.FirstSeenMs != 0)
{
long age = now - r.FirstSeenMs;
if (age >= 0 && age < FlashMs)
{
_flashing = true;
float pulse = 0.5f + 0.5f * MathF.Cos(age * 0.0126f);
float a = (1f - age / (float)FlashMs) * (0.2f + 0.35f * pulse);
dl.AddRectFilled(p, p + new Vector2(bw, RowH), WithAlpha(Amber, a));
}
}
if (isSel) dl.AddRect(p, p + new Vector2(bw, RowH), Teal);
Vector2 mid = p + new Vector2(ArrowW * 0.5f, RowH * 0.5f);
if (r.Measured && haveHeading && !float.IsNaN(r.Bearing))
DrawArrow(dl, mid, r.Bearing - heading, KindColor(r.Kind));
else if (r.Measured)
dl.AddCircleFilled(mid, 2.5f, KindColor(r.Kind));
else
dl.AddCircle(mid, 3.5f, Faded(Mute), 12, 1.2f);
float ty = p.Y + (RowH - fontH) * 0.5f;
uint nameCol = r.Measured ? Text : Mute;
float x = p.X + ArrowW;
Cell(dl, r.Name, x, ty, nameW - 4, nameCol);
x += nameW;
Cell(dl, SenseSource.KindName(r.Kind), x, ty, KindW - 4, KindColor(r.Kind));
x += KindW;
Cell(dl, r.DistanceText, x, ty, DistW - 4, r.Measured ? Text : Faded(Mute));
x += DistW;
Cell(dl, r.CompassText, x, ty, DirW - 4, Mute);
x += DirW;
if (showLoc) Cell(dl, r.LocationText, x, ty, bw - (x - p.X) - 4, Mute);
}
ImGuiNET.ImGui.SetCursorScreenPos(start);
ImGuiNET.ImGui.Dummy(new Vector2(bw, rows.Length * RowH));
if (clicked >= 0)
AcMainThreadQueue.EnqueueOverlaySelect(rows[clicked].Id);
if (hovered >= 0)
{
ImGuiNET.ImGui.BeginTooltip();
ImGuiNET.ImGui.TextUnformatted(rows[hovered].Tooltip);
ImGuiNET.ImGui.EndTooltip();
}
}
private static void Cell(ImDrawListPtr dl, string text, float x, float y, float width, uint color)
{
if (text.Length == 0 || width <= 0) return;
dl.PushClipRect(new Vector2(x, y - 2), new Vector2(x + width, y + 40), true);
dl.AddText(new Vector2(x, y), color, text);
dl.PopClipRect();
}
/// <summary>
/// An arrow pointing <paramref name="degrees"/> clockwise from straight up
/// (up = the way you face).
/// </summary>
private static void DrawArrow(ImDrawListPtr dl, Vector2 c, float degrees, uint color)
{
float rad = degrees * (MathF.PI / 180f);
float s = MathF.Sin(rad), co = MathF.Cos(rad);
Vector2 tip = Rot(c, 0, -6.5f, s, co), left = Rot(c, -4.5f, 5f, s, co),
notch = Rot(c, 0, 2.5f, s, co), right = Rot(c, 4.5f, 5f, s, co);
dl.AddTriangleFilled(tip, left, notch, color);
dl.AddTriangleFilled(tip, notch, right, color);
}
private static Vector2 Rot(Vector2 c, float x, float y, float s, float co) =>
new(c.X + x * co - y * s, c.Y + x * s + y * co);
/// <summary>Your heading this frame (compass degrees) from the pose snapshot; no AC call.</summary>
private static float PlayerHeading(out bool ok)
{
ok = PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out _, out _, out _, out _, out float qw, out float qz,
out bool headingValid, out float heading);
if (!ok) return 0;
if (headingValid) return heading;
// AC's get_heading not bound yet: the yaw quaternion (ClientObjectHooks' formula).
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
return (float)((-yaw % 360.0 + 720.0) % 360.0);
}
private static uint KindColor(SenseKind kind) => kind switch
{
SenseKind.Monster => Red,
SenseKind.Npc => Amber,
SenseKind.Player => Green,
SenseKind.Portal => Purple,
SenseKind.Corpse => Mute,
_ => Teal,
};
private static uint WithAlpha(uint abgr, float a) =>
(abgr & 0x00FFFFFF) | ((uint)Math.Clamp((int)(a * 255f), 0, 255) << 24);
// ── Settings (gear) ─────────────────────────────────────────────────
private void DrawSettingsPopup()
{
if (_openSettings)
{
_openSettings = false;
ImGuiNET.ImGui.OpenPopup("##sense_settings");
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
bool open = ImGuiNET.ImGui.BeginPopup("##sense_settings");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(5);
if (!open) return;
Label("When a new match appears:", Mute);
bool chat = SenseStore.AlertChat, beep = SenseStore.AlertBeep;
if (ImGuiNET.ImGui.Checkbox("Chat line", ref chat))
SenseStore.SetAlerts(chat, beep);
ImGuiNET.ImGui.SetItemTooltip("A line in chat such as: Sense: Dragon's Isle Drake 140 yd NE\n" +
"(at most three at once; the same object again only after two minutes).");
if (ImGuiNET.ImGui.Checkbox("System beep", ref beep))
SenseStore.SetAlerts(chat, beep);
ImGuiNET.ImGui.SetItemTooltip("Windows' default sound, at most every 3 seconds.");
Label("Alerts keep working with the panel closed.", Faded(Mute));
Label("Saved in %LocalAppData%\\RynthCore\\sense.txt", Faded(Mute));
ImGuiNET.ImGui.EndPopup();
}
}

View file

@ -0,0 +1,448 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/SettingsFace.cs
// ImGui face of RynthAi's Advanced Settings (docs/IMGUI_PARITY_PLAN.md §2.4).
//
// Draws SettingsSchema (UI/Data/SettingsData.cs), the same list the Avalonia
// face builds from, with that face's look: 150 px tab sidebar, "Advanced
// Settings > Tab" header, square toggle dots, - [value] + steppers (typed
// values commit on Enter or when the field loses focus, then clamp; bad
// input reverts), combo pickers, amber section headers, tooltips.
//
// Edits a private copy of the hub's settings and saves the whole copy
// (SettingsCommands.Save) on each change; a newer fetch replaces the copy
// only while no field here is being typed in. Rows that show or hide other
// rows need nothing special: visibility is re-evaluated every frame.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Text;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class SettingsFace : IImGuiPanel
{
public const string Title = "Settings";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(400, 500), new Vector2(320, 240), EdgeToEdge: true),
() => new SettingsFace());
// ── Palette (SettingsPanel's, ARGB) ─────────────────────────────────
private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Mute = C(0xFFB8C8D8),
TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), PanelBg = C(0xFF141F29), BtnFill = C(0xFF16283A),
BtnBord = C(0xFF34587A), ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455), TabActive = C(0xFF1A2E42);
private static uint C(uint argb) => RynthTheme.Argb(argb);
private static readonly string[] Headers = BuildHeaders();
private RynthAiSettings _data = new();
private long _seenVersion = -1;
private int _tab;
private bool _editing;
// Typed-value buffers, one per numeric row (UTF-8, NUL-terminated).
private sealed class NumberEdit
{
public readonly byte[] Buffer = new byte[24];
public double Shown = double.NaN;
public bool Active; // the box had keyboard focus last frame
}
private readonly Dictionary<SettingRow, NumberEdit> _edits = new();
public void OnShown()
{
UiSources.Settings.Subscribe();
UiSources.Settings.RequestRefresh();
}
public void OnHidden() => UiSources.Settings.Unsubscribe();
public void Draw()
{
// Take a newer fetch unless a value is being typed in.
var snap = UiSources.Settings.Current;
if (snap != null && snap.Version != _seenVersion && !_editing)
{
_seenVersion = snap.Version;
_data = snap.Value.Clone();
}
_editing = false;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
dl.AddRectFilled(origin, origin + size, ShellBg, 4);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
Sidebar(size.Y);
ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(150, 0));
Content(new Vector2(size.X - 150, size.Y));
ImGuiNET.ImGui.PopFont();
dl.AddRect(origin, origin + size, BtnBord, 4);
}
// ── Sidebar: one button per tab ────────────────────────────────────────
private void Sidebar(float height)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
ImGuiNET.ImGui.BeginChild("##settings_tabs", new Vector2(150, height), ImGuiChildFlags.AlwaysUseWindowPadding);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
SettingsTab[] tabs = SettingsSchema.Tabs;
for (int i = 0; i < tabs.Length; i++)
{
string tabName = tabs[i].Name;
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.PushID(i);
if (ImGuiNET.ImGui.InvisibleButton("##tab", new Vector2(w, 26))) _tab = i;
bool hot = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.PopID();
bool sel = i == _tab;
dl.AddRectFilled(p, p + new Vector2(w, 26), sel ? TabActive : hot ? Lighten(BtnFill) : BtnFill);
dl.AddRect(p, p + new Vector2(w, 26), BtnBord);
float ty = p.Y + (26 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.AddText(new Vector2(p.X + 8, ty), sel ? Teal : Mute, TabLabel(tabName));
}
ImGuiNET.ImGui.EndChild();
}
// ── Content: header + the tab's rows ───────────────────────────────────
private void Content(Vector2 size)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 6));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 0));
ImGuiNET.ImGui.BeginChild("##settings_content", size, ImGuiChildFlags.AlwaysUseWindowPadding);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
if (_tab >= SettingsSchema.Tabs.Length) _tab = 0;
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), Headers[_tab]);
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
Vector2 lp = ImGuiNET.ImGui.GetCursorScreenPos();
dl.AddLine(lp, lp + new Vector2(w, 0), BtnBord);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
SettingRow[] rows = SettingsSchema.Tabs[_tab].Rows;
for (int i = 0; i < rows.Length; i++)
{
SettingRow row = rows[i];
if (!row.IsVisible(_data)) continue;
ImGuiNET.ImGui.PushID(i);
DrawRow(row, w);
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.EndChild();
}
private void DrawRow(SettingRow row, float w)
{
switch (row.Kind)
{
case SettingKind.Bool: BoolRow(row, w); break;
case SettingKind.Int:
case SettingKind.Float:
case SettingKind.Double: NumberRow(row, w); break;
case SettingKind.Combo: ComboRow(row, w); break;
case SettingKind.Section: Section(row.Label, w); break;
case SettingKind.Spacer: ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); break;
case SettingKind.Note: Note(row.Label, w); break;
case SettingKind.CraftingStatus: CraftingStatus(row); break;
}
}
private void Changed(SettingRow row, double value)
{
row.Set!(_data, value);
SettingsCommands.Save(_data.Clone());
}
// Square dot + label; the whole row toggles.
private void BoolRow(SettingRow row, float w)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
bool on = row.Get!(_data) != 0;
float labelW = ImGuiNET.ImGui.CalcTextSize(row.Label).X;
if (ImGuiNET.ImGui.InvisibleButton("##b", new Vector2(Math.Min(w, 18 + labelW), 16)))
Changed(row, on ? 0 : 1);
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
Tooltip(row);
dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2);
dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
// Label | [-] [value] [+]; the value commits on Enter or focus loss.
private void NumberRow(SettingRow row, float w)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
bool isInt = row.Kind == SettingKind.Int;
float boxW = isInt ? 52 : 64, boxCol = isInt ? 56 : 68;
double value = Math.Clamp(row.Get!(_data), row.Min, row.Max);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float right = p.X + w;
dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label);
ImGuiNET.ImGui.InvisibleButton("##label", new Vector2(Math.Max(1, w - 40 - boxCol), 22));
Tooltip(row);
float plusX = right - 20, boxX = plusX - boxCol + (boxCol - boxW) * 0.5f, minusX = right - 20 - boxCol - 20;
if (StepButton("##minus", new Vector2(minusX + 1, p.Y + 1), PhosphorIcons.Minus))
Changed(row, Math.Clamp(value - row.Step, row.Min, row.Max));
// Typed value (amber on the panel colour).
NumberEdit edit = EditFor(row);
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(boxX, p.Y + 1));
ImGuiNET.ImGui.SetNextItemWidth(boxW);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f);
if (!edit.Active && edit.Shown != value)
WriteValue(edit, value, isInt);
ImGuiNET.ImGui.InputText("##v", edit.Buffer, (uint)edit.Buffer.Length,
ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.AutoSelectAll);
bool active = ImGuiNET.ImGui.IsItemActive();
edit.Active = active;
_editing |= active;
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
if (TryParse(edit.Buffer, out double typed))
{
double clamped = Math.Clamp(isInt ? Math.Round(typed) : typed, row.Min, row.Max);
Changed(row, clamped);
WriteValue(edit, clamped, isInt);
}
else WriteValue(edit, value, isInt); // bad input reverts
}
ImGuiNET.ImGui.PopStyleVar(3);
ImGuiNET.ImGui.PopStyleColor(3);
if (StepButton("##plus", new Vector2(plusX + 1, p.Y + 1), PhosphorIcons.Plus))
Changed(row, Math.Clamp(value + row.Step, row.Min, row.Max));
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
private NumberEdit EditFor(SettingRow row)
{
if (!_edits.TryGetValue(row, out NumberEdit? e))
_edits[row] = e = new NumberEdit();
return e;
}
private static void WriteValue(NumberEdit edit, double value, bool isInt)
{
string text = isInt ? ((long)Math.Round(value)).ToString(CultureInfo.InvariantCulture)
: value.ToString("G4", CultureInfo.InvariantCulture);
int n = Encoding.UTF8.GetBytes(text, 0, text.Length, edit.Buffer, 0);
edit.Buffer[Math.Min(n, edit.Buffer.Length - 1)] = 0;
edit.Shown = value;
}
private static bool TryParse(byte[] buffer, out double value)
{
int len = Array.IndexOf(buffer, (byte)0);
if (len < 0) len = buffer.Length;
return double.TryParse(Encoding.UTF8.GetString(buffer, 0, len), NumberStyles.Float, CultureInfo.InvariantCulture, out value);
}
// Label | [current item]; click opens a 220 px list with the current item highlighted.
private void ComboRow(SettingRow row, float w)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
string[] items = row.Items!;
int current = Math.Clamp((int)row.Get!(_data), 0, items.Length - 1);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label);
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Ui10);
const float btnW = 160;
var bp = new Vector2(p.X + w - btnW, p.Y + 1);
ImGuiNET.ImGui.SetCursorScreenPos(bp);
if (ImGuiNET.ImGui.InvisibleButton("##combo", new Vector2(btnW, 20)))
{
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Max(bp.X + btnW - 220, 0), bp.Y + 20));
ImGuiNET.ImGui.OpenPopup("##combo_list");
}
bool hot = ImGuiNET.ImGui.IsItemHovered();
Tooltip(row);
dl.AddRectFilled(bp, bp + new Vector2(btnW, 20), hot ? Lighten(BtnFill) : BtnFill);
dl.AddRect(bp, bp + new Vector2(btnW, 20), BtnBord);
dl.PushClipRect(bp, bp + new Vector2(btnW - 16, 20), true);
dl.AddText(f10, f10.FontSize, bp + new Vector2(4, (20 - f10.FontSize) * 0.5f), TextDim, items[current]);
dl.PopClipRect();
PhosphorIcons.DrawCentered(dl, f10, PhosphorIcons.CaretDown, bp + new Vector2(btnW - 16, 0), new Vector2(14, 20), Mute);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(220, items.Length * 21 + 4));
bool open = ImGuiNET.ImGui.BeginPopup("##combo_list");
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(2);
if (open)
{
var pdl = ImGuiNET.ImGui.GetWindowDrawList();
float iw = ImGuiNET.ImGui.GetContentRegionAvail().X;
for (int i = 0; i < items.Length; i++)
{
ImGuiNET.ImGui.PushID(i);
Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos();
bool picked = ImGuiNET.ImGui.InvisibleButton("##item", new Vector2(iw, 20));
bool ih = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.PopID();
bool sel = i == current;
pdl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? TabActive : ih ? Lighten(BtnFill) : BtnFill);
pdl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord);
pdl.AddText(f10, f10.FontSize, ip + new Vector2(6, (20 - f10.FontSize) * 0.5f), sel ? Teal : TextDim, items[i]);
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
if (picked)
{
Changed(row, i);
ImGuiNET.ImGui.CloseCurrentPopup();
}
}
ImGuiNET.ImGui.EndPopup();
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
private static void Section(string text, float w)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
float h = bold.FontSize + 4;
dl.AddRectFilled(p, p + new Vector2(w, h), TabActive);
dl.AddText(bold, bold.FontSize, p + new Vector2(4, 2), Amber, text);
ImGuiNET.ImGui.Dummy(new Vector2(w, h));
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
private static void Note(string text, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
bool small = !text.StartsWith('(');
if (small) ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopStyleColor();
if (small) ImGuiNET.ImGui.PopFont();
}
private void CraftingStatus(SettingRow row)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), row.Label);
ImGuiNET.ImGui.SameLine(0, 6);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(_data.MissileCraftingActive ? 0xFFE8B333 : 0xFFB8C8D8), _data.MissileCraftingState);
ImGuiNET.ImGui.PopFont();
if (!string.IsNullOrEmpty(_data.MissileCraftingStatus))
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
ImGuiNET.ImGui.TextWrapped(_data.MissileCraftingStatus);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.PopFont();
}
}
private static bool StepButton(string id, Vector2 pos, string glyph)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.SetCursorScreenPos(pos);
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, new Vector2(18, 20));
uint bg = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill;
dl.AddRectFilled(pos, pos + new Vector2(18, 20), bg);
dl.AddRect(pos, pos + new Vector2(18, 20), BtnBord);
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, new Vector2(18, 20), TextDim);
return clicked;
}
// Tab icons by tab name (SettingsSchema); a tab not listed shows its name alone.
private static readonly System.Collections.Generic.Dictionary<string, string> TabIcons = new()
{
["Display"] = PhosphorIcons.Monitor,
["UI"] = PhosphorIcons.AppWindow,
["Misc"] = PhosphorIcons.DotsThree,
["Recharge"] = PhosphorIcons.BatteryCharging,
["Melee Combat"] = PhosphorIcons.Sword,
["Spell Combat"] = PhosphorIcons.MagicWand,
["Ranges"] = PhosphorIcons.Ruler,
["Navigation"] = PhosphorIcons.SneakerMove,
["Buffing"] = PhosphorIcons.Sparkle,
["Crafting"] = PhosphorIcons.Hammer,
["Looting"] = PhosphorIcons.Bag,
["Vendoring"] = PhosphorIcons.Storefront,
};
private static readonly System.Collections.Generic.Dictionary<string, string> TabLabels = new();
/// <summary>"icon Name", built once per tab.</summary>
private static string TabLabel(string name)
{
if (TabLabels.TryGetValue(name, out string? label)) return label;
label = TabIcons.TryGetValue(name, out string? icon) ? icon + " " + name : name;
TabLabels[name] = label;
return label;
}
private static void Tooltip(SettingRow row)
{
if (row.Tooltip != null) ImGuiNET.ImGui.SetItemTooltip(row.Tooltip);
}
private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12);
private static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0);
private static uint Scale(uint abgr, float k, int add)
{
uint a = abgr & 0xFF000000;
uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add);
uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add);
uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add);
return a | (b << 16) | (g << 8) | r;
}
private static string[] BuildHeaders()
{
var headers = new string[SettingsSchema.Tabs.Length];
for (int i = 0; i < headers.Length; i++)
headers[i] = "Advanced Settings > " + SettingsSchema.Tabs[i].Name;
return headers;
}
}

View file

@ -0,0 +1,226 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/SkillsData.cs
// The Skills panel's static data from client_portal.dat, read once in the
// background (UiBackgroundWriter, never AC's thread):
//
// SkillTable 0x0E000004 id u32, PackedHashTable (u16 count, u16 buckets) of
// u32 skill id + SkillBase: description, name (u16 length + bytes, each
// padded to 4 from the file start), icon u32, trained cost i32,
// specialized cost i32 (total), category u32, chargen use u32,
// min level u32 (1 usable untrained, 2 needs training), formula
// (W, X, Y, Z, attr1, attr2 u32), upper, lower, learn mod f64.
// XpTable 0x0E000018 id u32, counts (attribute, vital, trained,
// specialized i32, level u32), then count+1 u32 each for attributes,
// vitals, trained and specialized skills, count+1 u64 levels, count+1 u32
// skill credits per level.
//
// Layouts: ACE.DatLoader SkillTable / SkillBase / SkillFormula / XpTable (the
// server raises against the same XpTable). Readers take the published
// immutable tables; any thread.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.ScriptWindows;
namespace RynthCore.Engine.ImGuiBackend.Panels;
/// <summary>One skill from the portal SkillTable.</summary>
internal sealed class SkillDatEntry
{
public uint Id;
public string Name = "";
public string Description = "";
public uint Icon;
public int TrainedCost;
public int SpecializedCost;
public uint Category; // 1 combat, 2 other, 3 magic
public uint MinLevel; // 1 usable untrained, 2 trained or better
public uint Attr1, Attr2, Divisor;
public bool UsableUntrained => MinLevel <= 1;
}
internal sealed class SkillDatTables
{
public readonly Dictionary<uint, SkillDatEntry> Skills = new();
public uint[] AttributeXp = Array.Empty<uint>();
public uint[] VitalXp = Array.Empty<uint>();
public uint[] TrainedXp = Array.Empty<uint>();
public uint[] SpecializedXp = Array.Empty<uint>();
public ulong[] LevelXp = Array.Empty<ulong>();
}
internal static class SkillDat
{
private const uint SkillTableFileId = 0x0E000004;
private const uint XpTableFileId = 0x0E000018;
private const int MaxFile = 1024 * 1024;
private static volatile SkillDatTables? _tables;
private static int _queued;
private static volatile string _status = "not loaded";
public static SkillDatTables? Tables => _tables;
/// <summary>"38 skills, 190 attribute ranks" or why not. Any thread.</summary>
public static string Status => _status;
/// <summary>Queues the one-time read (again after a failure). Cheap once loaded.</summary>
public static void EnsureLoadQueued()
{
if (_tables != null || Interlocked.Exchange(ref _queued, 1) == 1) return;
_status = "loading";
UiBackgroundWriter.Enqueue("skills dat", Load);
}
private static void Load()
{
try
{
string? path = AcDatFile.FindPortalDat();
if (path == null) { Fail("client_portal.dat not found next to acclient.exe"); return; }
using AcDatFile? dat = AcDatFile.Open(path, out string why);
if (dat == null) { Fail($"{Path.GetFileName(path)}: {why}"); return; }
byte[]? skills = dat.Read(SkillTableFileId, MaxFile);
byte[]? xp = dat.Read(XpTableFileId, MaxFile);
if (skills == null || xp == null) { Fail($"{Path.GetFileName(path)}: skill or XP table missing"); return; }
var t = new SkillDatTables();
if (!ParseSkills(skills, t) || !ParseXp(xp, t)) { Fail($"{Path.GetFileName(path)}: skill or XP table unreadable"); return; }
_tables = t;
_status = string.Format(CultureInfo.InvariantCulture, "{0} skills, {1} attribute and {2} skill ranks from {3}",
t.Skills.Count, t.AttributeXp.Length - 1, t.TrainedXp.Length - 1, Path.GetFileName(path));
RynthLog.UI($"Skills: {_status}");
}
catch (Exception ex)
{
Fail($"read failed: {ex.GetType().Name}: {ex.Message}");
}
}
private static void Fail(string why)
{
_status = why;
RynthLog.UI($"Skills: {why}");
Volatile.Write(ref _queued, 0); // the panel's next open tries again
}
private static bool ParseSkills(byte[] raw, SkillDatTables t)
{
var r = new Reader(raw);
r.U32(); // file id
int count = r.U16();
r.U16(); // buckets
for (int i = 0; i < count && r.Ok; i++)
{
var s = new SkillDatEntry { Id = r.U32() };
s.Description = r.PString();
s.Name = r.PString();
s.Icon = r.U32();
s.TrainedCost = (int)r.U32();
s.SpecializedCost = (int)r.U32();
s.Category = r.U32();
r.U32(); // chargen use
s.MinLevel = r.U32();
r.U32(); r.U32(); r.U32(); // formula W, X, Y
s.Divisor = r.U32(); // Z
s.Attr1 = r.U32();
s.Attr2 = r.U32();
r.Skip(24); // upper, lower bound, learn mod
if (!r.Ok) break;
if (s.Name.Length > 0) t.Skills[s.Id] = s;
}
return r.Ok && t.Skills.Count > 0;
}
private static bool ParseXp(byte[] raw, SkillDatTables t)
{
var r = new Reader(raw);
r.U32(); // file id
int attrs = (int)r.U32(), vitals = (int)r.U32(), trained = (int)r.U32(), spec = (int)r.U32();
int levels = (int)r.U32();
if (!r.Ok || attrs < 0 || vitals < 0 || trained < 0 || spec < 0 || levels < 0
|| attrs > 10000 || vitals > 10000 || trained > 10000 || spec > 10000 || levels > 10000)
return false;
t.AttributeXp = r.U32s(attrs + 1);
t.VitalXp = r.U32s(vitals + 1);
t.TrainedXp = r.U32s(trained + 1);
t.SpecializedXp = r.U32s(spec + 1);
var lv = new ulong[levels + 1];
for (int i = 0; i <= levels; i++) lv[i] = r.U64();
t.LevelXp = lv;
return r.Ok;
}
// ── XP arithmetic (the server's: Player.SpendAttributeXp / SpendSkillXp) ──
/// <summary>True when <paramref name="ranks"/> is the table's top rank (nothing left to buy).</summary>
public static bool IsMax(uint[] table, uint ranks) => table.Length == 0 || ranks + 1 >= (uint)table.Length;
/// <summary>XP to buy <paramref name="n"/> more ranks from <paramref name="ranks"/> with <paramref name="spent"/> already spent; -1 past the top.</summary>
public static long CostOf(uint[] table, uint ranks, uint spent, int n)
{
if (n < 1) return 0;
long target = (long)ranks + n;
if (target >= table.Length) return -1;
return Math.Max(0L, (long)table[target] - spent);
}
/// <summary>How many ranks in a row <paramref name="available"/> XP buys (0 when not even one), up to the top rank.</summary>
public static int Affordable(uint[] table, uint ranks, uint spent, long available)
{
int lo = 0, hi = Math.Max(0, table.Length - 1 - (int)Math.Min(ranks, (uint)int.MaxValue));
while (lo < hi)
{
int mid = (lo + hi + 1) / 2;
long c = CostOf(table, ranks, spent, mid);
if (c >= 0 && c <= available) lo = mid; else hi = mid - 1;
}
return lo;
}
/// <summary>Bounds-checked little-endian reader; Ok turns false on overrun.</summary>
private ref struct Reader
{
private readonly ReadOnlySpan<byte> _b;
private int _p;
public bool Ok;
public Reader(byte[] b) { _b = b; _p = 0; Ok = true; }
private bool Has(int n)
{
if (Ok && n >= 0 && _p + n <= _b.Length) return true;
Ok = false;
return false;
}
public uint U32() { if (!Has(4)) return 0; uint v = BitConverter.ToUInt32(_b.Slice(_p, 4)); _p += 4; return v; }
public ushort U16() { if (!Has(2)) return 0; ushort v = BitConverter.ToUInt16(_b.Slice(_p, 2)); _p += 2; return v; }
public ulong U64() { if (!Has(8)) return 0; ulong v = BitConverter.ToUInt64(_b.Slice(_p, 8)); _p += 8; return v; }
public void Skip(int n) { if (Has(n)) _p += n; }
public uint[] U32s(int n)
{
if (!Has(n * 4)) return Array.Empty<uint>();
var a = new uint[n];
for (int i = 0; i < n; i++) a[i] = U32();
return a;
}
/// <summary>u16 length + Latin-1 bytes, then aligned to 4 from the file start (ACE AlignBoundary).</summary>
public string PString()
{
int n = U16();
if (!Has(n)) return "";
string s = Encoding.Latin1.GetString(_b.Slice(_p, n));
_p += n;
_p = (_p + 3) & ~3;
return s;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,250 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/VisionFace.cs
// ImGui face of the RynthVision settings (UI/Panels/RynthVisionPanel.cs),
// in three tabs:
// Terrain the plugin's overlays (radar ring, unclimbable slopes,
// impassable water), colours (AARRGGBB hex + swatch), tuning
// sliders (Ctrl+click to type a value), water terrain types,
// and "Log terrain types here";
// Nameplates the RynthVision nameplates (monster plates, debuff icons,
// your own plate), engine-side (Hud/MonsterHudSettingsUi);
// Combat text floating damage / heal numbers, kill burst and gains.
//
// Terrain edits a private copy and saves just the changed field
// (VisionCommands) when a control finishes changing (a slider on release).
// A newer snapshot replaces the copy unless a control is in use. The other
// two tabs edit MonsterHudSettings directly (saved in the background).
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class VisionFace : IImGuiPanel
{
public const string Title = "Vision";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(320, 560), new Vector2(280, 240), EdgeToEdge: true),
() => new VisionFace());
private static readonly Vector4 HeaderColor = RynthTheme.Vec(0xFF7AB8F5);
private VisionSettings? _s;
private long _seenVersion = -1;
private bool _busy;
private readonly byte[] _slopeHex = new byte[12], _waterHex = new byte[12], _radarHex = new byte[12];
private readonly byte[] _waterTypes = new byte[128];
private int _tab;
private static readonly string[] TabNames = { "Terrain", "Nameplates", "Combat text" };
private static readonly string[] TabIds = { "##vtab0", "##vtab1", "##vtab2" };
public void OnShown()
{
UiSources.Vision.Subscribe();
UiSources.Vision.RequestRefresh();
}
public void OnHidden() => UiSources.Vision.Unsubscribe();
public void Draw()
{
TakeSnapshot();
float w = Begin(out Vector2 origin, out Vector2 size);
TabStrip(w);
if (_tab == 0)
{
_busy = DrawTerrain(w, origin, size);
}
else
{
_busy = false;
ImGuiNET.ImGui.BeginChild("##vision_overlays", new Vector2(w, Math.Max(60, Remaining(origin, size))));
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
float cw = ImGuiNET.ImGui.GetContentRegionAvail().X - 4;
if (_tab == 1) Hud.MonsterHudSettingsUi.DrawNameplates(cw);
else Hud.MonsterHudSettingsUi.DrawCombatText(cw);
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.EndChild();
}
End(origin, size);
}
/// <summary>Terrain | Nameplates | Combat text, as a row of flat buttons.</summary>
private void TabStrip(float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float x = p.X;
float bw = MathF.Floor((w - 8) / TabNames.Length);
for (int i = 0; i < TabNames.Length; i++)
{
bool sel = i == _tab;
if (Button(TabIds[i], TabNames[i], new Vector2(x, p.Y), new Vector2(bw, 24), sel ? Teal : Mute,
sel ? Selected : BtnFill, border: sel ? Teal : 0))
_tab = i;
x += bw + 4;
}
NextLine(p, 30);
}
/// <summary>The plugin's own settings. True while a control is in use.</summary>
private bool DrawTerrain(float w, Vector2 origin, Vector2 size)
{
bool busy = false;
if (_s == null)
{
Label("Waiting for the RynthVision plugin…", Mute);
return false;
}
VisionSettings s = _s;
ImGuiNET.ImGui.BeginChild("##vision_body", new Vector2(w, Math.Max(60, Remaining(origin, size))));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrabActive, Amber);
Header("Overlays");
if (ImGuiNET.ImGui.Checkbox("Radar range ring", ref s.Radar)) Save(VisionKeys.Radar);
if (ImGuiNET.ImGui.Checkbox("Unclimbable slopes", ref s.Slopes)) Save(VisionKeys.Slopes);
if (ImGuiNET.ImGui.Checkbox("Impassable water", ref s.Water)) Save(VisionKeys.Water);
Header("Colors (hex AARRGGBB)");
busy |= ColorRow(SlopeColorF, _slopeHex, ref s.SlopeColor);
busy |= ColorRow(WaterColorF, _waterHex, ref s.WaterColor);
busy |= ColorRow(RadarColorF, _radarHex, ref s.RadarColor);
Header("Tuning");
ImGuiNET.ImGui.PushItemWidth(Math.Max(120, ImGuiNET.ImGui.GetContentRegionAvail().X - 8));
busy |= Slider(RadarRangeF, ref s.RadarRange, 24, 300, "%.0f");
busy |= Slider(RingThickF, ref s.RingThick, 0.5, 6, "%.1f");
busy |= Slider(RingHeightF, ref s.RingHeight, 0.5, 30, "%.1f");
busy |= IntSlider(SlopeRadiusF, ref s.SlopeRadius, 1, 24);
busy |= Slider(SlopeFloorZF, ref s.SlopeFloorZ, 0.30, 0.95, "%.3f");
busy |= Slider(SlopeBiasF, ref s.SlopeBias, 0.00, 1.00, "%.2f");
busy |= IntSlider(WaterRadiusF, ref s.WaterRadius, 1, 24);
ImGuiNET.ImGui.PopItemWidth();
Header("Water terrain types");
if (ImGuiNET.ImGui.Checkbox("Highlight cell if ANY corner is water (else all four)", ref s.WaterAnyCorner)) Save(VisionKeys.WaterAnyCorner);
if (ImGuiNET.ImGui.Checkbox("Only paint water cells with an unwalkable triangle (real impassable)", ref s.WaterImpassableOnly)) Save(VisionKeys.WaterImpassableOnly);
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
bool enter = TextBox("##water_types", _waterTypes, p, 160, "18,19,20", out bool typing, ImGuiInputTextFlags.EnterReturnsTrue);
bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
busy |= typing;
bool apply = Button("##water_apply", "Apply", new Vector2(p.X + 164, p.Y), new Vector2(56, 22), Text, BtnFill);
if (enter || done || apply)
{
// An empty list resets to the defaults in the plugin; the republish
// after the save brings them back here.
s.WaterTypes = VisionSettings.ParseCsv(Utf8(_waterTypes));
WriteUtf8(_waterTypes, string.Join(",", s.WaterTypes));
Save(VisionKeys.WaterTypes);
}
NextLine(p, 26);
p = ImGuiNET.ImGui.GetCursorScreenPos();
if (Button("##inspect", "Log terrain types here", p, new Vector2(ButtonWidth("Log terrain types here") + 8, 24), Text, BtnFill))
VisionCommands.Inspect();
NextLine(p, 28);
ImGuiNET.ImGui.PopStyleColor(5);
ImGuiNET.ImGui.EndChild();
return busy;
}
private void TakeSnapshot()
{
var snap = UiSources.Vision.Current;
if (snap == null || snap.Version == _seenVersion || _busy) return;
_seenVersion = snap.Version;
_s = snap.Value.Settings.Clone();
WriteUtf8(_slopeHex, _s.SlopeColor.ToString("X8"));
WriteUtf8(_waterHex, _s.WaterColor.ToString("X8"));
WriteUtf8(_radarHex, _s.RadarColor.ToString("X8"));
WriteUtf8(_waterTypes, string.Join(",", _s.WaterTypes));
}
private void Save(string key)
{
if (_s != null) VisionCommands.SaveField(_s, key);
}
/// <summary>A control's label, ImGui id and settings key, built once (no per-frame strings).</summary>
private sealed class Field
{
public readonly string Label, Id, Key;
public Field(string label, string id, string key) { Label = label; Id = id; Key = key; }
public static Field Slider(string name, string key) => new(name + ":", "##" + name, key);
public static Field Color(string name, string key) => new(name, "##hex_" + name, key);
}
private static readonly Field SlopeColorF = Field.Color("Slope", VisionKeys.SlopeColor);
private static readonly Field WaterColorF = Field.Color("Water", VisionKeys.WaterColor);
private static readonly Field RadarColorF = Field.Color("Radar", VisionKeys.RadarColor);
private static readonly Field RadarRangeF = Field.Slider("Radar range", VisionKeys.RadarRange);
private static readonly Field RingThickF = Field.Slider("Ring thickness", VisionKeys.RingThick);
private static readonly Field RingHeightF = Field.Slider("Ring height (m)", VisionKeys.RingHeight);
private static readonly Field SlopeRadiusF = Field.Slider("Slope radius (cells)", VisionKeys.SlopeRadius);
private static readonly Field SlopeFloorZF = Field.Slider("Slope floor Z", VisionKeys.SlopeFloorZ);
private static readonly Field SlopeBiasF = Field.Slider("Slope height bias (m)", VisionKeys.SlopeBias);
private static readonly Field WaterRadiusF = Field.Slider("Water radius (cells)", VisionKeys.WaterRadius);
private static void Header(string text)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
ImGuiNET.ImGui.TextColored(HeaderColor, text);
ImGuiNET.ImGui.PopFont();
}
/// <summary>Name | hex box | swatch. Commits on Enter or focus loss; bad input reverts. True while typing.</summary>
private bool ColorRow(Field f, byte[] hex, ref uint argb)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, f.Label);
bool enter = TextBox(f.Id, hex, new Vector2(p.X + 48, p.Y), 92, "", out bool typing,
ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.CharsHexadecimal | ImGuiInputTextFlags.CharsUppercase);
bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
if (enter || done)
{
if (VisionSettings.TryParseHex(Utf8(hex), out uint c)) { argb = c; Save(f.Key); }
WriteUtf8(hex, argb.ToString("X8"));
}
// Swatch: AARRGGBB -> ImGui ABGR.
uint abgr = (argb & 0xFF00FF00) | ((argb >> 16) & 0xFF) | ((argb & 0xFF) << 16);
Vector2 sw = new(p.X + 146, p.Y + 3);
dl.AddRectFilled(sw, sw + new Vector2(22, 16), abgr);
dl.AddRect(sw, sw + new Vector2(22, 16), Mute);
NextLine(p, 26);
return typing;
}
/// <summary>Label, then the slider; saves on release (or after Ctrl+click typing). True while in use.</summary>
private bool Slider(Field f, ref double value, double min, double max, string format)
{
ImGuiNET.ImGui.TextUnformatted(f.Label);
float v = (float)value;
ImGuiNET.ImGui.SliderFloat(f.Id, ref v, (float)min, (float)max, format, ImGuiSliderFlags.AlwaysClamp);
value = v;
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) Save(f.Key);
ImGuiNET.ImGui.SetItemTooltip("Ctrl+click to type a value");
return ImGuiNET.ImGui.IsItemActive();
}
private bool IntSlider(Field f, ref int value, int min, int max)
{
ImGuiNET.ImGui.TextUnformatted(f.Label);
ImGuiNET.ImGui.SliderInt(f.Id, ref value, min, max, "%d", ImGuiSliderFlags.AlwaysClamp);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) Save(f.Key);
ImGuiNET.ImGui.SetItemTooltip("Ctrl+click to type a value");
return ImGuiNET.ImGui.IsItemActive();
}
}

View file

@ -0,0 +1,206 @@
// ============================================================================
// RynthCore.Engine - ImGui/PhosphorIcons.cs
// The Phosphor icons (MIT, Assets/Fonts/Phosphor.ttf; licence in
// THIRD-PARTY-NOTICES.md) as the characters that draw them. ImGuiFonts merges
// the glyphs into every baked font at the web font's code points (the private
// use area), so an icon is just text: put one in a label, or hand it to
// DrawCentered for an icon-only button. The names are Phosphor's.
//
// Only the glyphs in Baked are in the atlas (about 20 fonts plus the scaled
// copies, so the whole 1,500-glyph set would be wasted space). A constant
// that a face uses must be in Baked, or it draws as nothing.
// tools/check_phosphor_icons.py checks the code points against the font and
// that Baked covers every icon the ImGui code uses.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class PhosphorIcons
{
public const string AppWindow = "\uE5DA";
public const string ArrowCircleUp = "\uE030";
public const string ArrowCounterClockwise = "\uE038";
public const string ArrowDown = "\uE03E";
public const string ArrowFatDown = "\uE518";
public const string ArrowFatLinesDown = "\uE524";
public const string ArrowLeft = "\uE058";
public const string ArrowRight = "\uE06C";
public const string ArrowSquareIn = "\uE5DC";
public const string ArrowSquareOut = "\uE5DE";
public const string ArrowUUpLeft = "\uE08A";
public const string ArrowUUpRight = "\uE08C";
public const string ArrowUp = "\uE08E";
public const string ArrowsClockwise = "\uE094";
public const string ArrowsInLineVertical = "\uE532";
public const string ArrowsOutCardinal = "\uE0A4";
public const string ArrowsOutLineVertical = "\uE536";
public const string Backpack = "\uE922";
public const string Bag = "\uE0B0";
public const string Barbell = "\uE0B6";
public const string BatteryCharging = "\uE0BA";
public const string Binoculars = "\uEA64";
public const string Brain = "\uE74E";
public const string CaretDown = "\uE136";
public const string CaretLeft = "\uE138";
public const string CaretRight = "\uE13A";
public const string CaretUp = "\uE13C";
public const string CastleTurret = "\uE9D0";
public const string ChartBar = "\uE150";
public const string ChartLineUp = "\uE156";
public const string ChatCircleText = "\uE16E";
public const string Check = "\uE182";
public const string CheckCircle = "\uE184";
public const string CheckSquare = "\uE186";
public const string ClipboardText = "\uE198";
public const string ClockCounterClockwise = "\uE1A0";
public const string Code = "\uE1BC";
public const string Coins = "\uE78E";
public const string Compass = "\uE1C8";
public const string Copy = "\uE1CA";
public const string Crosshair = "\uE1D6";
public const string CrosshairSimple = "\uE1D8";
public const string Crown = "\uE614";
public const string DotsSixVertical = "\uEAE2";
public const string DotsThree = "\uE1FE";
public const string DotsThreeVertical = "\uE208";
public const string Drop = "\uE210";
public const string Eraser = "\uE21E";
public const string Eye = "\uE220";
public const string FileCode = "\uE914";
public const string FilePlus = "\uE236";
public const string Files = "\uE710";
public const string Fire = "\uE242";
public const string Flask = "\uE79E";
public const string FloppyDisk = "\uE248";
public const string FolderOpen = "\uE256";
public const string Footprints = "\uEA88";
public const string Funnel = "\uE266";
public const string Gear = "\uE270";
public const string Gift = "\uE276";
public const string GlobeHemisphereWest = "\uE28C";
public const string GraduationCap = "\uE62C";
public const string Hammer = "\uE80E";
public const string Heart = "\uE2A8";
public const string HeartBreak = "\uEBE8";
public const string Heartbeat = "\uE2AC";
public const string HourglassMedium = "\uE2B8";
public const string Hourglass = "\uE2B2";
public const string Info = "\uE2CE";
public const string Knife = "\uE636";
public const string Lightning = "\uE2DE";
public const string ListChecks = "\uEADC";
public const string Lock = "\uE2FA";
public const string LockOpen = "\uE306";
public const string MagicWand = "\uE6B6";
public const string MagnifyingGlass = "\uE30C";
public const string MapPin = "\uE316";
public const string MapPinPlus = "\uE314";
public const string MapTrifold = "\uE31A";
public const string Minus = "\uE32A";
public const string Monitor = "\uE32E";
public const string NavigationArrow = "\uEADE";
public const string Path = "\uE39C";
public const string PencilSimple = "\uE3B4";
public const string PersonSimpleRun = "\uE730";
public const string Play = "\uE3D0";
public const string Package = "\uE390";
public const string Plus = "\uE3D4";
public const string Power = "\uE3DA";
public const string Resize = "\uED6E";
public const string Robot = "\uE762";
public const string Ruler = "\uE6B8";
public const string Scales = "\uE750";
public const string Scissors = "\uEAE0";
public const string Scroll = "\uEB7A";
public const string Shield = "\uE40A";
public const string ShieldSlash = "\uE410";
public const string ShieldWarning = "\uE412";
public const string Skull = "\uE916";
public const string SneakerMove = "\uED60";
public const string Snowflake = "\uE5AA";
public const string SortAscending = "\uE444";
public const string SortDescending = "\uE446";
public const string Sparkle = "\uE6A2";
public const string Spiral = "\uE9FA";
public const string Square = "\uE45E";
public const string SquaresFour = "\uE464";
public const string Star = "\uE46A";
public const string Stop = "\uE46C";
public const string Storefront = "\uE470";
public const string Sun = "\uE472";
public const string Sword = "\uE5BA";
public const string Target = "\uE47C";
public const string TerminalWindow = "\uEAE8";
public const string TextAa = "\uE6EE";
public const string Trash = "\uE4A6";
public const string TrendDown = "\uE4AC";
public const string TreasureChest = "\uEDE2";
public const string User = "\uE4C2";
public const string UsersThree = "\uE68E";
public const string Warning = "\uE4E0";
public const string WarningCircle = "\uE4E2";
public const string Wrench = "\uE5D4";
public const string X = "\uE4F6";
public const string XCircle = "\uE4F8";
/// <summary>
/// The icons merged into the atlas: every one the ImGui faces use. Add a
/// constant here when a face starts using it (ImGuiFonts reads this once,
/// at the first atlas build).
/// </summary>
public const string Baked =
AppWindow + ArrowCounterClockwise + ArrowDown + ArrowLeft + ArrowRight + ArrowSquareIn + ArrowSquareOut
+ ArrowUp + ArrowsClockwise + ArrowsInLineVertical + ArrowsOutLineVertical + Backpack + Bag + BatteryCharging
+ CaretDown + CaretLeft + CaretRight + CaretUp + ChartBar + ChartLineUp + ChatCircleText + Check + CheckSquare + ClipboardText + Code
+ Compass + Copy + Crosshair + DotsSixVertical + DotsThree + Drop + Eraser + Eye + FileCode + FilePlus + Files
+ FloppyDisk + Footprints + Funnel + Gear + Hammer + Heart + Heartbeat + Info + Lightning + ListChecks + Lock
+ LockOpen + MagicWand + MagnifyingGlass + MapPin + MapPinPlus + MapTrifold + Minus + Monitor + NavigationArrow
+ PencilSimple + Play + Plus + Resize + Robot + Ruler + Skull + SneakerMove + Sparkle + Spiral + Square
+ Stop + Storefront + Sword + TerminalWindow + Trash + TreasureChest + Warning + X
+ ArrowFatDown + ArrowFatLinesDown + Fire + Flask + HeartBreak + Knife + ShieldSlash + ShieldWarning
+ Snowflake + TrendDown + UsersThree
+ Coins + Gift + HourglassMedium + Scales + Scissors + Shield + SortAscending + SquaresFour
+ ArrowCircleUp + Barbell + Brain + GraduationCap + Hourglass + SortDescending + Package
+ Binoculars + Crown + Sun
+ CastleTurret + ClockCounterClockwise + GlobeHemisphereWest + Path + Star + Target + User
+ TextAa;
/// <summary>
/// Draws <paramref name="glyph"/> (one icon) centred in the box at
/// <paramref name="min"/>, by the glyph's own bounds rather than the line
/// box, so icon-only buttons look centred whatever font carries the icon.
/// Falls back to the text size when the glyph isn't baked.
/// </summary>
public static void DrawCentered(ImDrawListPtr dl, ImFontPtr font, string glyph, Vector2 min, Vector2 size, uint color) =>
DrawCentered(dl, font, font.FontSize, glyph, min, size, color);
/// <summary>
/// DrawCentered at <paramref name="px"/> pixels instead of the font's own size
/// (world overlays that scale with distance); the glyph box scales with it.
/// Never pushes a font, so it also works outside any window.
/// </summary>
public static void DrawCentered(ImDrawListPtr dl, ImFontPtr font, float px, string glyph, Vector2 min, Vector2 size, uint color)
{
if (glyph.Length == 0 || px <= 0) return;
float k = font.FontSize > 0 ? px / font.FontSize : 1f;
Vector2 centre;
// ImFontGlyph (1.91): a 4-byte bitfield, AdvanceX, then X0 Y0 X1 Y1. Read by
// offset: ImGui.NET's generated struct splits the bitfield into three fields.
byte* g = font.NativePtr == null ? null : (byte*)ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]);
if (g != null && glyph.Length == 1)
{
float* box = (float*)(g + 8);
centre = new Vector2((box[0] + box[2]) * 0.5f, (box[1] + box[3]) * 0.5f) * k;
}
else
{
centre = font.CalcTextSizeA(px, float.MaxValue, 0f, glyph) * 0.5f;
}
Vector2 at = min + size * 0.5f - centre;
dl.AddText(font, px, new Vector2(MathF.Round(at.X), MathF.Round(at.Y)), color, glyph);
}
}

View file

@ -0,0 +1,227 @@
// ============================================================================
// RynthCore.Engine - ImGui/PopOutSurface.cs
// The D3D9 side of one popped-out panel (docs/IMGUI_PARITY_PLAN.md §4.2):
// its ImGui draw data is rendered into an off-screen render target, read back
// into system memory and handed to the panel's LayeredWindow
// (UpdateLayeredWindow, per-pixel alpha).
//
// Two render targets alternate: each frame renders into one and reads back
// the other, which the GPU finished a frame ago, so the readback never waits
// on the GPU (a one-frame delay, ~33 ms at 30 Hz). The first frame after a
// (re)size reads its own target once.
//
// A picture can be larger than the panel: a tooltip or popup reaching past it
// is drawn in a margin around it (ImGuiPopOuts). Each target remembers where
// the panel sits in its picture, so the late readback is shown with the
// margins it was drawn with (LayeredWindow.Present keeps the panel in place).
//
// The targets are cleared to transparent black; DX9Backend blends colour with
// SRCALPHA/INVSRCALPHA and alpha with ONE/INVSRCALPHA, which leaves exactly
// the premultiplied BGRA that UpdateLayeredWindow wants.
//
// AC's render thread only (inside EndScene). All resources are released by
// Dispose; nothing is static.
// ============================================================================
using System;
using ImGuiNET;
using RynthCore.Engine.D3D9;
using RynthCore.Engine.UI;
namespace RynthCore.Engine.ImGuiBackend;
internal sealed unsafe class PopOutSurface : IDisposable
{
private const uint D3DFMT_A8R8G8B8 = 21;
private const uint D3DPOOL_SYSTEMMEM = 2;
private const uint D3DCLEAR_TARGET = 1;
private const uint D3DLOCK_READONLY = 0x10;
// IDirect3DDevice9 slots not in DeviceVTableIndex.
private const int CreateRenderTargetSlot = 28;
private const int GetRenderTargetDataSlot = 32;
private const int CreateOffscreenPlainSurfaceSlot = 36;
private const int SetDepthStencilSurfaceSlot = 39;
private const int GetDepthStencilSurfaceSlot = 40;
// IDirect3DSurface9
private const int SurfaceLockRectSlot = 13;
private const int SurfaceUnlockRectSlot = 14;
private struct Viewport { public uint X, Y, Width, Height; public float MinZ, MaxZ; }
private struct LockedRect { public int Pitch; public IntPtr Bits; }
/// <summary>Where the panel sits in a picture: its offset and size (px).</summary>
public readonly record struct Placement(int InsetLeft, int InsetTop, int ContentWidth, int ContentHeight);
private readonly IntPtr[] _targets = new IntPtr[2];
private readonly Placement[] _placements = new Placement[2];
private IntPtr _readback;
private int _width, _height;
private int _current;
private bool _previousValid;
private int _failures;
public int Width => _width;
public int Height => _height;
/// <summary>Diagnostics (/rc ui snap): the next frame pushed is also written here as a 32-bit BMP.</summary>
public string? SnapshotPath;
/// <summary>
/// Renders <paramref name="drawData"/> (sized <paramref name="width"/> ×
/// <paramref name="height"/>, the panel placed in it at <paramref name="placement"/>)
/// and pushes the latest finished frame to <paramref name="window"/>. False when
/// the device refused (logged, retried next frame).
/// </summary>
public bool Render(IntPtr device, ImDrawDataPtr drawData, int width, int height, Placement placement, LayeredWindow window)
{
if (device == IntPtr.Zero || width <= 0 || height <= 0) return false;
if ((width != _width || height != _height || _targets[0] == IntPtr.Zero) && !Create(device, width, height))
return false;
void** vt = *(void***)device;
IntPtr oldTarget = IntPtr.Zero, oldDepth = IntPtr.Zero;
Viewport oldViewport;
((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr*, int>)vt[DeviceVTableIndex.GetRenderTarget])(device, 0, &oldTarget);
((delegate* unmanaged[Stdcall]<IntPtr, IntPtr*, int>)vt[GetDepthStencilSurfaceSlot])(device, &oldDepth);
((delegate* unmanaged[Stdcall]<IntPtr, Viewport*, int>)vt[DeviceVTableIndex.GetViewport])(device, &oldViewport);
try
{
IntPtr target = _targets[_current];
if (((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, int>)vt[DeviceVTableIndex.SetRenderTarget])(device, 0, target) < 0)
return Fail("SetRenderTarget");
// Our target can be larger than AC's depth buffer (a pop-out bigger than
// the game window); nothing here uses depth, so unbind it.
((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int>)vt[SetDepthStencilSurfaceSlot])(device, IntPtr.Zero);
((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, uint, uint, float, uint, int>)vt[DeviceVTableIndex.Clear])(
device, 0, IntPtr.Zero, D3DCLEAR_TARGET, 0x00000000, 1f, 0);
DX9Backend.RenderDrawData(drawData, device);
_placements[_current] = placement;
}
finally
{
// SetRenderTarget resets the viewport to the whole target: put AC's back.
((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, int>)vt[DeviceVTableIndex.SetRenderTarget])(device, 0, oldTarget);
((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int>)vt[SetDepthStencilSurfaceSlot])(device, oldDepth);
((delegate* unmanaged[Stdcall]<IntPtr, Viewport*, int>)vt[DeviceVTableIndex.SetViewport])(device, &oldViewport);
ReleaseCom(oldTarget);
ReleaseCom(oldDepth);
}
// Read back the target the GPU has finished: last frame's, or this one on the first frame.
int read = _previousValid ? 1 - _current : _current;
bool pushed = Push(device, vt, read, window);
_unpushed = read != _current; // this frame's picture is still to be shown
_previousValid = true;
_current = 1 - _current;
return pushed;
}
private bool _unpushed;
/// <summary>
/// Shows the last rendered frame if it hasn't been shown yet (the readback
/// runs a frame behind): called on a frame that was skipped because nothing
/// changed. Cheap no-op otherwise.
/// </summary>
public void Flush(IntPtr device, LayeredWindow window)
{
if (!_unpushed || device == IntPtr.Zero || _targets[0] == IntPtr.Zero) return;
_unpushed = false;
Push(device, *(void***)device, 1 - _current, window);
}
private bool Push(IntPtr device, void** vt, int index, LayeredWindow window)
{
IntPtr target = _targets[index];
Placement at = _placements[index];
if (((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, IntPtr, int>)vt[GetRenderTargetDataSlot])(device, target, _readback) < 0)
return Fail("GetRenderTargetData");
void** svt = *(void***)_readback;
LockedRect locked;
if (((delegate* unmanaged[Stdcall]<IntPtr, LockedRect*, IntPtr, uint, int>)svt[SurfaceLockRectSlot])(_readback, &locked, IntPtr.Zero, D3DLOCK_READONLY) < 0)
return Fail("LockRect");
try
{
window.Present(locked.Bits, locked.Pitch, _width, _height, at.InsetLeft, at.InsetTop, at.ContentWidth, at.ContentHeight);
if (SnapshotPath != null)
{
string path = SnapshotPath;
SnapshotPath = null;
WriteBmp(path, (byte*)locked.Bits, _width, _height, locked.Pitch);
}
}
finally
{
((delegate* unmanaged[Stdcall]<IntPtr, int>)svt[SurfaceUnlockRectSlot])(_readback);
}
_failures = 0;
return true;
}
private static void WriteBmp(string path, byte* bits, int width, int height, int pitch)
{
try
{
int rowBytes = width * 4, imageBytes = rowBytes * height;
using var fs = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
using var bw = new System.IO.BinaryWriter(fs);
bw.Write((ushort)0x4D42); bw.Write(54 + imageBytes); bw.Write(0); bw.Write(54);
bw.Write(40); bw.Write(width); bw.Write(-height); bw.Write((ushort)1); bw.Write((ushort)32);
bw.Write(0); bw.Write(imageBytes); bw.Write(2835); bw.Write(2835); bw.Write(0); bw.Write(0);
for (int y = 0; y < height; y++)
bw.Write(new ReadOnlySpan<byte>(bits + (long)y * pitch, rowBytes));
RynthLog.UI($"PopOutSurface: snapshot {width}x{height} written to {path}.");
}
catch (Exception ex) { RynthLog.UI($"PopOutSurface: snapshot failed: {ex.Message}"); }
}
private bool Create(IntPtr device, int width, int height)
{
Release();
void** vt = *(void***)device;
for (int i = 0; i < 2; i++)
{
IntPtr surface = IntPtr.Zero;
int hr = ((delegate* unmanaged[Stdcall]<IntPtr, uint, uint, uint, uint, uint, int, IntPtr*, IntPtr, int>)vt[CreateRenderTargetSlot])(
device, (uint)width, (uint)height, D3DFMT_A8R8G8B8, 0, 0, 0, &surface, IntPtr.Zero);
if (hr < 0 || surface == IntPtr.Zero) { Release(); return Fail($"CreateRenderTarget {width}x{height} hr=0x{hr:X8}"); }
_targets[i] = surface;
}
IntPtr readback = IntPtr.Zero;
int rhr = ((delegate* unmanaged[Stdcall]<IntPtr, uint, uint, uint, uint, IntPtr*, IntPtr, int>)vt[CreateOffscreenPlainSurfaceSlot])(
device, (uint)width, (uint)height, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &readback, IntPtr.Zero);
if (rhr < 0 || readback == IntPtr.Zero) { Release(); return Fail($"CreateOffscreenPlainSurface {width}x{height} hr=0x{rhr:X8}"); }
_readback = readback;
_width = width;
_height = height;
_current = 0;
_previousValid = false;
return true;
}
private bool Fail(string what)
{
if (_failures++ < 5)
RynthLog.Render($"PopOutSurface: {what} failed; the pop-out keeps its last picture.");
return false;
}
private void Release()
{
for (int i = 0; i < 2; i++) { ReleaseCom(_targets[i]); _targets[i] = IntPtr.Zero; }
ReleaseCom(_readback);
_readback = IntPtr.Zero;
_width = _height = 0;
_previousValid = false;
}
private static void ReleaseCom(IntPtr obj)
{
if (obj == IntPtr.Zero) return;
void** vt = *(void***)obj;
((delegate* unmanaged[Stdcall]<IntPtr, uint>)vt[DeviceVTableIndex.Release])(obj);
}
public void Dispose() => Release();
}

View file

@ -0,0 +1,239 @@
// ============================================================================
// RynthCore.Engine - ImGui/RetailSprites.cs
// The retail UI's own pictures (0x06 textures in client_portal.dat: window
// backgrounds, title bars, slot frames, meters, scrollbar pieces) as ImGui
// textures, for faces that draw the retail look (the Inventory's Classic view).
//
// Unlike ScriptIcons (item icons, many, least recently drawn evicted) this is a
// small fixed set asked for by id: each picture is decoded once, made into a
// texture once and kept until the engine shuts down or ImGui is torn down (hot
// reload). Nothing is decoded or created per frame once a picture is in.
//
// Threads:
// - AC's render thread: TryGet (inside the ImGui frame), BeginFrame (creates
// the textures decoded since the last frame, at most 16 a frame, before
// anything draws) and Shutdown (releases them all). Only it touches D3D.
// - One worker at a time on the thread pool: reads and decodes the pictures
// from client_portal.dat (AcDatFile / AcIconDecoder, pure code, no AC memory).
// 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
// 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).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using RynthCore.Engine.UI.ScriptWindows;
namespace RynthCore.Engine.ImGuiBackend;
internal static class RetailSprites
{
private const int MaxSprites = 192;
private const int MaxCreatesPerFrame = 16;
private static readonly long FailedRetryTicks = Stopwatch.Frequency * 30;
private sealed class Sprite
{
public IntPtr Ptr;
public bool Pending;
public long FailedAt;
}
private readonly struct Result
{
public readonly uint Id;
public readonly AcIconImage? Image;
public readonly int Generation;
public Result(uint id, AcIconImage? image, int generation)
{
Id = id;
Image = image;
Generation = generation;
}
}
// ── AC's render thread only ──────────────────────────────────────────
private static readonly Dictionary<uint, Sprite> Sprites = new(MaxSprites);
private static readonly List<Result> ResultScratch = new(MaxCreatesPerFrame);
// ── Shared with the worker, under Sync ───────────────────────────────
private static readonly object Sync = new();
private static readonly Queue<(uint Id, int Generation)> Requests = new(MaxSprites);
private static readonly Queue<Result> Results = new(MaxSprites);
private static bool _draining;
private static int _generation;
private static bool _datMissingLogged;
/// <summary>Pictures that are textures now (diagnostics).</summary>
public static int LiveTextures { get; private set; }
/// <summary>
/// The texture for a retail UI picture (a 0x06 texture id), once it is in; otherwise
/// false, and the first ask queues its decode. AC's render thread.
/// </summary>
public static bool TryGet(uint textureId, out IntPtr texture)
{
texture = IntPtr.Zero;
if (!AcIconDecoder.IsTextureId(textureId)) return false;
if (!Sprites.TryGetValue(textureId, out Sprite? sprite))
{
if (Sprites.Count >= MaxSprites) return false;
sprite = new Sprite();
Sprites[textureId] = sprite;
}
if (sprite.Ptr != IntPtr.Zero)
{
texture = sprite.Ptr;
return true;
}
if (!sprite.Pending && (sprite.FailedAt == 0 || Stopwatch.GetTimestamp() - sprite.FailedAt >= FailedRetryTicks)
&& Enqueue(textureId))
sprite.Pending = true;
return false;
}
/// <summary>
/// Start of the ImGui frame, before anything draws: turns the pictures decoded since the
/// last frame into textures (at most 16). AC's render thread.
/// </summary>
public static void BeginFrame(IntPtr device)
{
ResultScratch.Clear();
lock (Sync)
{
while (Results.Count > 0 && ResultScratch.Count < MaxCreatesPerFrame)
ResultScratch.Add(Results.Dequeue());
}
if (ResultScratch.Count == 0) return;
long now = Stopwatch.GetTimestamp();
foreach (Result r in ResultScratch)
{
if (r.Generation != _generation || !Sprites.TryGetValue(r.Id, out Sprite? sprite)) continue;
sprite.Pending = false;
if (sprite.Ptr != IntPtr.Zero) continue;
IntPtr ptr = IntPtr.Zero;
if (r.Image != null)
{
try { ptr = DX9Backend.CreateTextureRgba(device, r.Image.Width, r.Image.Height, r.Image.Pixels); }
catch { ptr = IntPtr.Zero; }
}
if (ptr != IntPtr.Zero)
{
sprite.Ptr = ptr;
sprite.FailedAt = 0;
LiveTextures++;
}
else
{
sprite.FailedAt = now;
}
}
ResultScratch.Clear();
}
/// <summary>
/// Engine shutdown or ImGui teardown (hot reload, unload): releases every texture and
/// drops the queues; a worker still running finishes into a generation nobody reads.
/// AC's render thread.
/// </summary>
public static void Shutdown()
{
lock (Sync)
{
_generation++;
Requests.Clear();
Results.Clear();
}
foreach (Sprite s in Sprites.Values)
{
if (s.Ptr == IntPtr.Zero) continue;
try { DX9Backend.ReleaseTexture(s.Ptr); } catch { }
s.Ptr = IntPtr.Zero;
}
Sprites.Clear();
ResultScratch.Clear();
LiveTextures = 0;
}
// ── Worker ───────────────────────────────────────────────────────────
private static bool Enqueue(uint id)
{
lock (Sync)
{
if (Requests.Count + Results.Count >= MaxSprites) return false;
Requests.Enqueue((id, _generation));
if (_draining) return true;
_draining = true;
}
try
{
ThreadPool.UnsafeQueueUserWorkItem(static _ => Drain(), null);
}
catch
{
lock (Sync) _draining = false;
}
return true;
}
/// <summary>The worker: decodes one picture at a time until the queue is empty or the engine stops.</summary>
private static void Drain()
{
AcDatFile? dat = null;
bool datTried = false;
try
{
while (true)
{
(uint Id, int Generation) r;
lock (Sync)
{
if (Requests.Count == 0 || EngineThreads.Stopping)
{
Requests.Clear();
_draining = false;
return;
}
r = Requests.Dequeue();
}
if (!datTried)
{
datTried = true;
string? path = AcDatFile.FindPortalDat();
string why = "client_portal.dat not found next to acclient.exe";
if (path != null) dat = AcDatFile.Open(path, out why);
if (dat == null && !_datMissingLogged)
{
_datMissingLogged = true;
RynthLog.UI($"RetailSprites: no retail UI pictures ({why}); panels draw their own stand-ins.");
}
}
AcIconImage? image = null;
try { image = dat == null ? null : AcIconDecoder.Decode(dat, r.Id, AcIconDecoder.MaxUiSide); }
catch { image = null; }
lock (Sync)
{
if (r.Generation == _generation) Results.Enqueue(new Result(r.Id, image, r.Generation));
}
}
}
catch
{
lock (Sync) { Requests.Clear(); _draining = false; }
}
finally
{
try { dat?.Dispose(); } catch { }
}
}
}

View file

@ -0,0 +1,143 @@
// ============================================================================
// RynthCore.Engine - ImGui/RynthTheme.cs
// Colours and metrics for the ImGui panel faces, taken from the Avalonia
// panels so a docked ImGui face looks like its popped-out Avalonia face
// (docs/IMGUI_PARITY_PLAN.md §4.4). Tokens are ABGR-packed ImGui colours
// (ImGui.GetColorU32 order) built from the Avalonia #AARRGGBB literals.
//
// Apply() sets the base style once at context creation; per-window colours
// (bar, RynthAi, Radar) are pushed around Begin by the panel host.
// ============================================================================
using System;
using System.Numerics;
using System.Runtime.InteropServices;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal static class RynthTheme
{
/// <summary>Avalonia #AARRGGBB → ImGui packed colour (0xAABBGGRR).</summary>
public static uint Argb(uint argb) =>
(argb & 0xFF00FF00) | ((argb & 0x00FF0000) >> 16) | ((argb & 0x000000FF) << 16);
public static Vector4 Vec(uint argb) => new(
((argb >> 16) & 0xFF) / 255f, ((argb >> 8) & 0xFF) / 255f, (argb & 0xFF) / 255f, (argb >> 24) / 255f);
// ── Bar (AvaloniaOverlay.cs BuildRoot) ─────────────────────────────
public static readonly uint BarBackground = Argb(0xE60A0A14);
public const float BarRounding = 4f;
public static readonly uint BarButton = Argb(0xFF1A2230);
public static readonly uint BarButtonBorder = Argb(0xFF3A4A5A);
public static readonly uint BarText = Argb(0xFFFFFFFF);
public static readonly uint RcLabel = Argb(0xFF90EE90); // LightGreen
public static readonly uint ReloadLabel = Argb(0xFFF0E68C); // Khaki
public static readonly uint PopOutLabel = Argb(0xFF87CEFA); // LightSkyBlue
// ── Standard panel frame ───────────────────────────────────────────
public static readonly uint PanelGlass = Argb(0xF212121C); // was D2: the game showed through behind text
public static readonly uint PanelBorder = Argb(0xFF008080); // Teal
public const float PanelRounding = 4f;
public static readonly uint PanelHeader = Argb(0xFF1A1A28);
public static readonly uint DragLabel = Argb(0xFF008080);
public const float HeaderHeight = 24f;
public static readonly uint GripIdle = Argb(0x2026C1A6);
public static readonly uint GripHover = Argb(0x5526C1A6);
public static readonly uint GripGlyph = Argb(0xFF008080);
// ── RynthAi dashboard ──────────────────────────────────────────────
public static readonly uint RynthAiBackground = Argb(0xF20A0F14);
public static readonly uint RynthAiBorder = Argb(0xFF264059);
public const float RynthAiRounding = 3f;
// ── Radar ──────────────────────────────────────────────────────────
public static readonly uint RadarGold = Argb(0xFFE6C766);
public static readonly uint RadarGripIdle = Argb(0x400A121A);
public static readonly uint RadarGripHover = Argb(0xA00A121A);
/// <summary>
/// Base style for every ImGui face, scaled for <paramref name="scale"/>
/// (DPI / 96). AC thread, once, right after the context is created.
/// </summary>
public static void Apply(ImGuiStylePtr style, float scale)
{
ImGuiNET.ImGui.StyleColorsDark();
style.WindowRounding = PanelRounding;
style.ChildRounding = 3f;
style.FrameRounding = 2f;
style.PopupRounding = 3f;
style.GrabRounding = 2f;
style.ScrollbarRounding = 3f;
style.WindowBorderSize = 1f;
style.FrameBorderSize = 0f;
style.WindowPadding = new Vector2(6f, 6f);
style.FramePadding = new Vector2(5f, 2f);
style.ItemSpacing = new Vector2(6f, 4f);
style.ScrollbarSize = 12f;
style.WindowMinSize = new Vector2(20f, 20f);
Set(style, ImGuiCol.Text, 0xFFE6E6E6);
Set(style, ImGuiCol.TextDisabled, 0xFF808080);
Set(style, ImGuiCol.WindowBg, 0xD212121C);
Set(style, ImGuiCol.ChildBg, 0x00000000);
Set(style, ImGuiCol.PopupBg, 0xF214141E);
Set(style, ImGuiCol.Border, 0xFF008080);
Set(style, ImGuiCol.FrameBg, 0xFF1A2230);
Set(style, ImGuiCol.FrameBgHovered, 0xFF243044);
Set(style, ImGuiCol.FrameBgActive, 0xFF2C3A52);
Set(style, ImGuiCol.TitleBg, 0xFF1A1A28);
Set(style, ImGuiCol.TitleBgActive, 0xFF1A1A28);
Set(style, ImGuiCol.Button, 0xFF1A2230);
Set(style, ImGuiCol.ButtonHovered, 0xFF2A3850);
Set(style, ImGuiCol.ButtonActive, 0xFF34466A);
Set(style, ImGuiCol.Header, 0xFF1A2230);
Set(style, ImGuiCol.HeaderHovered, 0xFF2A3850);
Set(style, ImGuiCol.HeaderActive, 0xFF34466A);
Set(style, ImGuiCol.CheckMark, 0xFF26C1A6);
Set(style, ImGuiCol.SliderGrab, 0xFF26A18C);
Set(style, ImGuiCol.SliderGrabActive, 0xFF26C1A6);
Set(style, ImGuiCol.Separator, 0x503A4A5A);
Set(style, ImGuiCol.ResizeGrip, 0x2026C1A6);
Set(style, ImGuiCol.ResizeGripHovered, 0x5526C1A6);
Set(style, ImGuiCol.ResizeGripActive, 0x8026C1A6);
Set(style, ImGuiCol.ScrollbarBg, 0x40000000);
Set(style, ImGuiCol.ScrollbarGrab, 0xFF2A3850);
Set(style, ImGuiCol.TableHeaderBg, 0xFF1A1A28);
Set(style, ImGuiCol.TableBorderStrong, 0xFF3A4A5A);
Set(style, ImGuiCol.TableBorderLight, 0x503A4A5A);
Set(style, ImGuiCol.TableRowBgAlt, 0x10FFFFFF);
Set(style, ImGuiCol.ModalWindowDimBg, 0x00000000);
if (scale != 1f)
style.ScaleAllSizes(scale);
}
private static void Set(ImGuiStylePtr style, ImGuiCol col, uint argb) => style.Colors[(int)col] = Vec(argb);
}
/// <summary>DPI scale for the ImGui faces.</summary>
internal static class UiScale
{
[DllImport("user32.dll")]
private static extern uint GetDpiForWindow(IntPtr hwnd);
/// <summary>
/// GetDpiForWindow(game) / 96, at least 1. For a DPI-unaware acclient this
/// is 1 (Windows scales the whole window); ImGui then works in the same
/// client pixels AC does.
/// </summary>
public static float ForWindow(IntPtr hwnd)
{
try
{
uint dpi = hwnd != IntPtr.Zero ? GetDpiForWindow(hwnd) : 0;
return dpi > 0 ? Math.Max(1f, dpi / 96f) : 1f;
}
catch (EntryPointNotFoundException)
{
return 1f; // pre-1607 Windows 10
}
}
}

View file

@ -0,0 +1,451 @@
// ============================================================================
// RynthCore.Engine - ImGui/ScriptIcons.cs
// Script windows: the D3D9 texture cache behind the Image / ImageButton ops.
// An icon is asked for by kind and id: an icon (0x06 texture) id, an object id
// (the item's icon with its underlay and overlay) or a spell id (the spell's
// icon). Design: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §9 (icons).
//
// Threads:
// - AC's render thread: TryGet (from the replay), BeginFrame (creates the
// textures decoded since the last frame, at most 8 a frame, and evicts the
// least recently drawn ones over the cap) and Shutdown (releases them all).
// Only this thread touches D3D.
// - One worker at a time on the thread pool: resolves an object's icon ids
// from the engine's PWD snapshot (ClientObjectHooks, the off-thread path:
// no AC memory), a spell's icon from the portal spell table, and decodes
// and stacks the pictures from client_portal.dat (AcIconDecoder). Nothing
// it does touches AC or D3D.
// The two meet only in two small queues under one lock.
//
// Bounded: about 256 textures kept (32 x 32 icons: 4 KB each, twice with the
// managed pool's system copy), 8 MB of pixels at most (a picture is at most
// 128 x 128), 2048 remembered ids, 128 requests in flight. What was drawn in
// the last frame is never evicted (so a hud showing more icons than the cap
// doesn't thrash); past the byte budget a new picture stays a placeholder.
// Eviction and creation run at the start of the frame, before anything is
// drawn, so a texture is never released while a draw list still points at it
// (every draw list of the frames before has been rendered by then). Shutdown
// (engine unload, hot reload) releases every texture and drops the queues;
// results of an older generation are thrown away.
//
// A missing, not yet decoded or undecodable icon draws a placeholder (the
// replay's job); nothing here throws into the replay.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.ImGuiBackend.Hud;
using RynthCore.Engine.UI.ScriptWindows;
namespace RynthCore.Engine.ImGuiBackend;
internal static class ScriptIcons
{
public const int MaxTextures = 256;
private const long MaxLiveBytes = 8L * 1024 * 1024;
private const int MaxSlots = 2048;
private const int MaxCreatesPerFrame = 8;
private const int MaxPendingRequests = 128;
private static readonly long ObjectRefreshTicks = Stopwatch.Frequency * 2; // enchantment overlays etc. change
private static readonly long UnresolvedRetryTicks = Stopwatch.Frequency; // an object not seen yet, a spell table still loading
private static readonly long FailedRetryTicks = Stopwatch.Frequency * 30; // an icon that didn't decode
private static readonly long BudgetRetryTicks = Stopwatch.Frequency * 2; // no room in the byte budget
private const uint StypeIcon = 8, StypeIconOverlay = 50, StypeIconUnderlay = 52;
/// <summary>What one picture is made of: icon, underlay and overlay texture ids (0 = none).</summary>
private readonly record struct Layers(uint Icon, uint Underlay, uint Overlay);
/// <summary>One asked-for (kind, id): the layers it resolved to.</summary>
private sealed class Slot
{
public Layers Layers;
public bool Resolved;
public bool Pending;
public long ResolvedAt;
public int LastUsed;
}
/// <summary>One picture's texture (or why it has none yet).</summary>
private sealed class Texture
{
public IntPtr Ptr;
public int Bytes;
public bool Pending;
public long FailedAt;
/// <summary>How long after FailedAt to try again.</summary>
public long RetryTicks;
public int LastUsed;
}
private enum Work : byte { Resolve, Decode }
private readonly struct Request
{
public readonly Work Work;
public readonly ScriptIconKind Kind;
public readonly uint Id;
public readonly Layers Layers;
public readonly int Generation;
public Request(Work work, ScriptIconKind kind, uint id, Layers layers, int generation)
{
Work = work;
Kind = kind;
Id = id;
Layers = layers;
Generation = generation;
}
}
private readonly struct Result
{
public readonly Work Work;
public readonly ulong SlotKey;
public readonly Layers Layers;
public readonly bool Ok;
public readonly AcIconImage? Image;
public readonly int Generation;
public Result(Work work, ulong slotKey, Layers layers, bool ok, AcIconImage? image, int generation)
{
Work = work;
SlotKey = slotKey;
Layers = layers;
Ok = ok;
Image = image;
Generation = generation;
}
}
// ── AC's render thread only ──────────────────────────────────────────
private static readonly Dictionary<ulong, Slot> Slots = new(256);
private static readonly Dictionary<Layers, Texture> Textures = new(MaxTextures);
private static readonly List<(int LastUsed, Layers Key)> EvictScratch = new(MaxTextures);
private static readonly List<ulong> SlotScratch = new();
private static readonly List<Result> ResultScratch = new(MaxCreatesPerFrame);
private static int _frame;
private static int _live;
private static long _liveBytes;
// ── Shared with the worker, under Sync ───────────────────────────────
private static readonly object Sync = new();
private static readonly Queue<Request> Requests = new(MaxPendingRequests);
private static readonly Queue<Result> Results = new(MaxPendingRequests);
private static bool _draining;
private static int _generation;
private static bool _datMissingLogged;
/// <summary>Textures alive now (diagnostics).</summary>
public static int LiveTextures => _live;
private static ulong SlotKey(ScriptIconKind kind, uint id) => ((ulong)kind << 32) | id;
/// <summary>
/// The texture for an icon, if it is ready; otherwise false and, when needed, the work to
/// get it is queued (the replay draws a placeholder meanwhile). AC's render thread.
/// </summary>
public static bool TryGet(ScriptIconKind kind, uint id, out IntPtr texture)
{
texture = IntPtr.Zero;
if (kind > ScriptIconKind.Spell || id == 0) return false;
long now = Stopwatch.GetTimestamp();
ulong key = SlotKey(kind, id);
if (!Slots.TryGetValue(key, out Slot? slot))
{
if (Slots.Count >= MaxSlots) PruneSlots();
slot = new Slot();
if (kind == ScriptIconKind.Icon)
{
slot.Layers = new Layers(AcIconDecoder.NormalizeIconId(id), 0, 0);
slot.Resolved = true;
}
Slots[key] = slot;
}
slot.LastUsed = _frame;
// Objects are looked up again every 2 s (an overlay can change); a spell's icon never
// changes; an id that didn't resolve is tried again after a second.
if (kind != ScriptIconKind.Icon && !slot.Pending)
{
bool due = !slot.Resolved
? slot.ResolvedAt == 0 || now - slot.ResolvedAt >= UnresolvedRetryTicks
: kind == ScriptIconKind.Object && now - slot.ResolvedAt >= ObjectRefreshTicks;
if (due && Enqueue(new Request(Work.Resolve, kind, id, default, _generation)))
slot.Pending = true;
}
if (!slot.Resolved) return false;
if (!Textures.TryGetValue(slot.Layers, out Texture? tex))
{
tex = new Texture();
Textures[slot.Layers] = tex;
}
tex.LastUsed = _frame;
if (tex.Ptr != IntPtr.Zero)
{
texture = tex.Ptr;
return true;
}
if (!tex.Pending && (tex.FailedAt == 0 || now - tex.FailedAt >= tex.RetryTicks)
&& Enqueue(new Request(Work.Decode, kind, id, slot.Layers, _generation)))
tex.Pending = true;
return false;
}
/// <summary>
/// Start of the ImGui frame, before anything draws: creates the textures decoded since
/// the last frame (at most 8) and evicts the least recently drawn ones over the cap.
/// AC's render thread.
/// </summary>
public static void BeginFrame(IntPtr device)
{
_frame++;
ResultScratch.Clear();
lock (Sync)
{
int creates = 0;
while (Results.Count > 0)
{
// Decodes wait their turn once 8 textures were made this frame; lookups don't.
if (Results.Peek().Work == Work.Decode && creates >= MaxCreatesPerFrame) break;
Result r = Results.Dequeue();
if (r.Work == Work.Decode) creates++;
ResultScratch.Add(r);
}
}
if (ResultScratch.Count == 0 && Textures.Count <= MaxTextures) return;
long now = Stopwatch.GetTimestamp();
foreach (Result r in ResultScratch)
{
if (r.Generation != _generation) continue;
if (r.Work == Work.Resolve)
{
if (!Slots.TryGetValue(r.SlotKey, out Slot? slot)) continue;
slot.Pending = false;
slot.ResolvedAt = now;
// A lookup that failed keeps the last picture (an object briefly out of the
// snapshot shouldn't blink); a slot that never resolved stays a placeholder.
if (r.Ok)
{
slot.Layers = r.Layers;
slot.Resolved = true;
}
continue;
}
if (!Textures.TryGetValue(r.Layers, out Texture? tex)) continue; // evicted meanwhile
tex.Pending = false;
if (tex.Ptr != IntPtr.Zero) continue;
IntPtr ptr = IntPtr.Zero;
int bytes = r.Image == null ? 0 : r.Image.Width * r.Image.Height * 4;
bool room = r.Image != null && (_liveBytes + bytes <= MaxLiveBytes || Evict(bytes));
if (room)
{
try { ptr = DX9Backend.CreateTextureRgba(device, r.Image!.Width, r.Image.Height, r.Image.Pixels); }
catch { ptr = IntPtr.Zero; }
}
if (ptr != IntPtr.Zero)
{
tex.Ptr = ptr;
tex.Bytes = bytes;
tex.FailedAt = 0;
_live++;
_liveBytes += bytes;
}
else
{
// Didn't decode (try again much later), or no room yet (soon).
tex.FailedAt = now;
tex.RetryTicks = r.Image != null && !room ? BudgetRetryTicks : FailedRetryTicks;
}
}
ResultScratch.Clear();
if (Textures.Count > MaxTextures) Evict(0);
}
/// <summary>
/// Drops the least recently drawn pictures that weren't drawn in the last frame: until at most
/// MaxTextures remain and, for <paramref name="needBytes"/> &gt; 0, until that many more bytes
/// fit the budget. Returns whether they fit.
/// </summary>
private static bool Evict(int needBytes)
{
EvictScratch.Clear();
foreach (var kv in Textures)
if (!kv.Value.Pending && kv.Value.LastUsed < _frame - 1)
EvictScratch.Add((kv.Value.LastUsed, kv.Key));
EvictScratch.Sort((a, b) => a.LastUsed.CompareTo(b.LastUsed));
for (int i = 0; i < EvictScratch.Count; i++)
{
bool overCount = Textures.Count > MaxTextures;
bool overBytes = needBytes > 0 && _liveBytes + needBytes > MaxLiveBytes;
if (!overCount && !overBytes) break;
if (Textures.Remove(EvictScratch[i].Key, out Texture? tex) && tex.Ptr != IntPtr.Zero)
{
try { DX9Backend.ReleaseTexture(tex.Ptr); } catch { }
_live--;
_liveBytes -= tex.Bytes;
}
}
EvictScratch.Clear();
return _liveBytes + needBytes <= MaxLiveBytes;
}
/// <summary>Forgets the ids not drawn for the longest (their textures stay until evicted).</summary>
private static void PruneSlots()
{
SlotScratch.Clear();
int keepAfter = _frame - 600; // ~10 s at 60 fps
foreach (var kv in Slots)
if (!kv.Value.Pending && kv.Value.LastUsed < keepAfter) SlotScratch.Add(kv.Key);
if (SlotScratch.Count == 0)
foreach (var kv in Slots)
if (!kv.Value.Pending) SlotScratch.Add(kv.Key); // every one is recent: start over
foreach (ulong k in SlotScratch) Slots.Remove(k);
SlotScratch.Clear();
}
/// <summary>
/// Engine shutdown or ImGui teardown (hot reload, unload): releases every texture and drops
/// the queues; a worker still running finishes into a generation nobody reads. AC's render thread.
/// </summary>
public static void Shutdown()
{
lock (Sync)
{
_generation++;
Requests.Clear();
Results.Clear();
}
foreach (Texture t in Textures.Values)
{
if (t.Ptr == IntPtr.Zero) continue;
try { DX9Backend.ReleaseTexture(t.Ptr); } catch { }
t.Ptr = IntPtr.Zero;
}
Textures.Clear();
Slots.Clear();
EvictScratch.Clear();
ResultScratch.Clear();
_live = 0;
_liveBytes = 0;
}
// ── Worker ───────────────────────────────────────────────────────────
/// <summary>Queues work for the worker (starting it when idle). False when too much is in flight.</summary>
private static bool Enqueue(Request r)
{
lock (Sync)
{
if (Requests.Count + Results.Count >= MaxPendingRequests) return false;
Requests.Enqueue(r);
if (_draining) return true;
_draining = true;
}
try
{
ThreadPool.UnsafeQueueUserWorkItem(static _ => Drain(), null);
}
catch
{
lock (Sync) _draining = false;
}
return true;
}
/// <summary>The worker: one request at a time until the queue is empty or the engine stops.</summary>
private static void Drain()
{
AcDatFile? dat = null;
bool datTried = false;
try
{
while (true)
{
Request r;
lock (Sync)
{
if (Requests.Count == 0 || EngineThreads.Stopping)
{
Requests.Clear();
_draining = false;
return;
}
r = Requests.Dequeue();
}
Result result;
try
{
result = r.Work == Work.Resolve ? ResolveNow(r) : DecodeNow(r, ref dat, ref datTried);
}
catch
{
result = new Result(r.Work, SlotKey(r.Kind, r.Id), r.Layers, false, null, r.Generation);
}
lock (Sync)
{
if (r.Generation == _generation) Results.Enqueue(result);
}
}
}
catch
{
lock (Sync) { Requests.Clear(); _draining = false; }
}
finally
{
try { dat?.Dispose(); } catch { }
}
}
/// <summary>An object's icon, underlay and overlay (PWD snapshot, no AC memory), or a spell's icon.</summary>
private static Result ResolveNow(Request r)
{
ulong key = SlotKey(r.Kind, r.Id);
if (r.Kind == ScriptIconKind.Object)
{
// Off AC's main thread these read the 10 Hz main-thread PWD snapshot.
if (!ClientObjectHooks.TryGetObjectDataIdProperty(r.Id, StypeIcon, out uint icon) || icon == 0)
return new Result(Work.Resolve, key, default, false, null, r.Generation);
ClientObjectHooks.TryGetObjectDataIdProperty(r.Id, StypeIconUnderlay, out uint under);
ClientObjectHooks.TryGetObjectDataIdProperty(r.Id, StypeIconOverlay, out uint over);
return new Result(Work.Resolve, key, new Layers(icon, under, over), true, null, r.Generation);
}
if (r.Kind == ScriptIconKind.Spell)
{
PortalSpellTable.EnsureLoadQueued();
bool ok = PortalSpellTable.TryGetIcon(r.Id, out uint icon) && icon != 0;
return new Result(Work.Resolve, key, ok ? new Layers(icon, 0, 0) : default, ok, null, r.Generation);
}
return new Result(Work.Resolve, key, new Layers(AcIconDecoder.NormalizeIconId(r.Id), 0, 0), true, null, r.Generation);
}
private static Result DecodeNow(Request r, ref AcDatFile? dat, ref bool datTried)
{
ulong key = SlotKey(r.Kind, r.Id);
if (!datTried)
{
datTried = true;
string? path = AcDatFile.FindPortalDat();
string why = "client_portal.dat not found next to acclient.exe";
if (path != null) dat = AcDatFile.Open(path, out why);
if (dat == null && !_datMissingLogged)
{
_datMissingLogged = true;
RynthLog.UI($"ScriptIcons: no icons ({why}); script windows draw placeholders.");
}
}
AcIconImage? image = dat == null ? null : AcIconDecoder.Compose(dat, r.Layers.Icon, r.Layers.Underlay, r.Layers.Overlay);
return new Result(Work.Decode, key, r.Layers, image != null, image, r.Generation);
}
}

View file

@ -0,0 +1,836 @@
// ============================================================================
// RynthCore.Engine - ImGui/ScriptWindowReplay.cs
// Script windows (API v71): the op interpreter. Replays a window's latest
// DisplayList with real ImGui calls every frame and turns what ImGui did
// into events for the owner (clicks, new values, text, open states).
// Design: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §2.5-2.7, §4.2, §6.3.
//
// AC's thread only, inside the panel host's window and try/catch. No
// allocation on a frame without input: ops are pre-parsed, strings are pinned
// NUL-terminated UTF-8 handed to cimgui as byte pointers.
//
// Safety:
// - Script text never reaches cimgui as a format string: TextUnformatted
// for every text op (colour / wrap / bullet done with pushes around it),
// LabelText's text was stored with '%' doubled, SeparatorText takes a
// label, slider formats were validated by the parser.
// - The engine owns every Begin/End and Push/Pop. Scopes are an explicit
// stack (no recursion): leftover PushIDs / PushStyleColors are popped at
// the end of their scope, then TreePop / EndChild. An exception mid-list
// unwinds every open scope in a finally before it propagates to
// ImGuiPanelHost.DrawBody, so ImGui's stacks stay balanced.
// - Icons (Image / ImageButton, op level 2) are ids: ScriptIcons turns them
// into cached D3D9 textures; until one is ready, or when it is missing,
// a dim placeholder square of the same size draws (the font atlas's white
// pixel), so a bad id never throws.
// - Sizes and offsets in ops are logical at UI scale 1: multiplied by
// S = EngineFrameController.FontScale here (the sign is kept, so 0 = auto
// and -1 = fill still work).
//
// Measurements (Phase 0): replay cost per frame and the input -> reaction
// latency are logged every ~10 s while a script window is open
// ("ScriptWindows replay:" lines, UI tag).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.ScriptWindows;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ScriptWindowReplay
{
private const byte ScopeRoot = 0, ScopeChild = 1, ScopeTree = 2;
/// <summary>One open scope: the root body, a Child or an open TreeNode.</summary>
private struct Scope
{
public byte Kind;
/// <summary>A CollapsingHeader the player just closed: drawing ops are skipped until the next header.</summary>
public bool Skip;
/// <summary>The op index just past the scope's last child.</summary>
public int End;
public int Ids;
public int Colors;
}
// AC thread only. Root + at most MaxDepth nested blocks.
private static readonly Scope[] Scopes = new Scope[DisplayListParser.MaxDepth + 1];
private static int _frame = int.MinValue;
private static int _frameOps;
private static readonly Vector4 ErrorColor = new(1f, 0.4f, 0.3f, 1f);
/// <summary>Draws <paramref name="w"/>'s latest list into the current window. AC thread.</summary>
public static void Draw(ScriptWindow w)
{
int frame = ImGuiNative.igGetFrameCount();
if (frame != _frame)
{
_frame = frame;
_frameOps = 0;
}
DisplayList list = w.List;
long t0 = Stopwatch.GetTimestamp();
DrawError(w);
int ops = 0;
bool over = false;
int budget = ScriptWindowRegistry.MaxReplayOpsPerFrame - _frameOps;
if (list.OpCount > 0 && budget <= 0)
over = true;
else if (list.OpCount > 0)
{
ops = Replay(w, list, frame, budget, out over);
_frameOps += ops;
}
if (over)
{
// Over the per-frame budget for all script windows together.
ReadOnlySpan<byte> msg = "Too large to draw this frame."u8;
fixed (byte* m = msg) ImGuiNative.igTextUnformatted(m, m + msg.Length);
}
long elapsed = Stopwatch.GetTimestamp() - t0;
// First frame this list is on screen: if it was recorded after the owner applied the
// pending input, that input has had its reaction.
if (!ReferenceEquals(list, w.LastReplayed))
{
w.LastReplayed = list;
w.Locals.PruneIfLarge(frame);
if (w.PendingInputSeq != 0 && list.AckSeq >= w.PendingInputSeq)
{
ScriptWindowStats.Reaction(w, frame - w.PendingInputFrame, Stopwatch.GetTimestamp() - w.PendingInputTicks);
w.PendingInputSeq = 0;
}
}
ScriptWindowStats.Replay(frame, elapsed, ops);
}
/// <summary>The script's error (HasError) in red, wrapped at the window edge, above the list.</summary>
private static void DrawError(ScriptWindow w)
{
if ((w.Flags & WindowFlags.HasError) == 0) return;
byte[]? err = w.ErrorUtf8;
if (err == null || err.Length < 1) return;
ImGuiNative.igPushStyleColor_Vec4(ImGuiCol.Text, ErrorColor);
ImGuiNative.igPushTextWrapPos(0f);
try
{
fixed (byte* e = err) ImGuiNative.igTextUnformatted(e, e + err.Length - 1);
}
finally
{
ImGuiNative.igPopTextWrapPos();
ImGuiNative.igPopStyleColor(1);
}
ImGuiNative.igSeparator();
}
/// <summary>
/// Walks the ops with an explicit scope stack. Returns the ops visited; <paramref name="over"/>
/// is set when the per-frame budget ran out before the list ended (the rest isn't drawn).
/// </summary>
private static int Replay(ScriptWindow w, DisplayList list, int frame, int budget, out bool over)
{
over = false;
int n = list.OpCount;
ReplayOp[] ops = list.Ops;
float s = EngineFrameController.FontScale;
if (!(s > 0f) || !float.IsFinite(s)) s = 1f;
uint ack = list.AckSeq;
ScriptLocals locals = w.Locals;
ScriptEventQueue events = w.Owner.Events;
int visited = 0;
int open = 0; // scopes whose closing calls are still owed
fixed (byte* pool = list.Pool)
{
try
{
Scopes[0] = new Scope { Kind = ScopeRoot, End = n };
open = 1;
int i = 0;
while (open > 0)
{
ref Scope sc = ref Scopes[open - 1];
if (i >= sc.End)
{
open--;
CloseScope(ref sc);
continue;
}
if (visited >= budget) { over = true; break; }
visited++;
ref ReplayOp op = ref ops[i];
if (sc.Skip)
{
if (op.Code == ScriptOp.CollapsingHeader) sc.Skip = false;
else if (op.Code is not (ScriptOp.PushID or ScriptOp.PopID or ScriptOp.PushStyleColor or ScriptOp.PopStyleColor))
{
// IDs and colours still run, so the ID stack after the next header is right.
i = op.EndIndex;
continue;
}
}
int next = i + 1;
byte* str = op.Str >= 0 ? pool + op.Str : null;
switch (op.Code)
{
// ── Text ──────────────────────────────────────────
case ScriptOp.Text:
ImGuiNative.igTextUnformatted(str, str + op.StrLen);
break;
case ScriptOp.TextColored:
ImGuiNative.igPushStyleColor_U32(ImGuiCol.Text, op.Color);
try { ImGuiNative.igTextUnformatted(str, str + op.StrLen); }
finally { ImGuiNative.igPopStyleColor(1); }
break;
case ScriptOp.TextWrapped:
ImGuiNative.igPushTextWrapPos(0f);
try { ImGuiNative.igTextUnformatted(str, str + op.StrLen); }
finally { ImGuiNative.igPopTextWrapPos(); }
break;
case ScriptOp.TextDisabled:
{
Vector4 disabled = *ImGuiNative.igGetStyleColorVec4(ImGuiCol.TextDisabled);
ImGuiNative.igPushStyleColor_Vec4(ImGuiCol.Text, disabled);
try { ImGuiNative.igTextUnformatted(str, str + op.StrLen); }
finally { ImGuiNative.igPopStyleColor(1); }
break;
}
case ScriptOp.BulletText:
ImGuiNative.igBullet();
ImGuiNative.igTextUnformatted(str, str + op.StrLen);
break;
case ScriptOp.SeparatorText:
ImGuiNative.igSeparatorText(str); // a label, not a format
break;
case ScriptOp.LabelText:
ImGuiNative.igLabelText(str, pool + op.Str2); // text stored with '%' doubled
break;
// ── Layout ────────────────────────────────────────
case ScriptOp.Separator:
ImGuiNative.igSeparator();
break;
case ScriptOp.SameLine:
ImGuiNative.igSameLine(op.A * s, op.B < 0f ? -1f : op.B * s);
break;
case ScriptOp.NewLine:
ImGuiNative.igNewLine();
break;
case ScriptOp.Spacing:
ImGuiNative.igSpacing();
break;
case ScriptOp.Dummy:
ImGuiNative.igDummy(new Vector2(op.A * s, op.B * s));
break;
case ScriptOp.Indent:
ImGuiNative.igIndent(op.A * s);
break;
case ScriptOp.Unindent:
ImGuiNative.igUnindent(op.A * s);
break;
// ── Widgets ───────────────────────────────────────
case ScriptOp.Button:
{
byte clicked = op.Flag != 0
? ImGuiNative.igSmallButton(str)
: ImGuiNative.igButton(str, new Vector2(op.A * s, op.B * s));
if (clicked != 0)
w.NoteInput(events.Click(w.Hash, op.Key), frame);
break;
}
case ScriptOp.Checkbox:
{
bool had = locals.Bools.TryGet(op.Key, ack, out bool local);
byte v = had ? (local ? (byte)1 : (byte)0) : op.Flag;
bool changed = ImGuiNative.igCheckbox(str, &v) != 0;
bool active = ImGuiNative.igIsItemActive() != 0;
uint seq = 0;
if (changed)
{
seq = events.Bool(w.Hash, op.Key, v != 0);
w.NoteInput(seq, frame);
}
locals.Bools.After(op.Key, had, changed, v != 0, seq, active, frame);
break;
}
case ScriptOp.SliderInt:
{
bool had = locals.Ints.TryGet(op.Key, ack, out int local);
int v = had ? local : op.I0;
bool changed = ImGuiNative.igSliderInt(str, &v, op.I1, op.I2, pool + op.Str2, ImGuiSliderFlags.AlwaysClamp) != 0;
bool active = ImGuiNative.igIsItemActive() != 0;
uint seq = 0;
if (changed)
{
seq = events.Int(w.Hash, op.Key, v);
w.NoteInput(seq, frame);
}
locals.Ints.After(op.Key, had, changed, v, seq, active, frame);
break;
}
case ScriptOp.SliderFloat:
{
bool had = locals.Floats.TryGet(op.Key, ack, out float local);
float v = had ? local : op.A;
bool changed = ImGuiNative.igSliderFloat(str, &v, op.B, op.C, pool + op.Str2, ImGuiSliderFlags.AlwaysClamp) != 0;
bool active = ImGuiNative.igIsItemActive() != 0;
uint seq = 0;
if (changed && float.IsFinite(v))
{
seq = events.Float(w.Hash, op.Key, v);
w.NoteInput(seq, frame);
}
else changed = false;
locals.Floats.After(op.Key, had, changed, v, seq, active, frame);
break;
}
case ScriptOp.Combo:
{
bool had = locals.Ints.TryGet(op.Key, ack, out int local);
int v = had ? local : op.I0;
bool changed = ImGuiNative.igCombo_Str(str, &v, pool + op.Str2, -1) != 0;
bool active = ImGuiNative.igIsItemActive() != 0;
uint seq = 0;
if (changed)
{
seq = events.Int(w.Hash, op.Key, v);
w.NoteInput(seq, frame);
}
locals.Ints.After(op.Key, had, changed, v, seq, active, frame);
break;
}
case ScriptOp.InputText:
ReplayInputText(w, ref op, str, pool, ack, frame);
break;
case ScriptOp.Selectable:
if (ImGuiNative.igSelectable_Bool(str, op.Flag, (ImGuiSelectableFlags)op.Flags, new Vector2(op.A * s, op.B * s)) != 0)
w.NoteInput(events.Click(w.Hash, op.Key), frame);
break;
case ScriptOp.ProgressBar:
ImGuiNative.igProgressBar(op.A, new Vector2(op.B * s, op.C * s), op.Str2 >= 0 ? pool + op.Str2 : null);
break;
// ── Icons and number inputs (op level 2) ──────────
case ScriptOp.Image:
{
var size = new Vector2(op.A * s, op.B * s);
if (ScriptIcons.TryGet((ScriptIconKind)op.Flag, unchecked((uint)op.I0), out IntPtr tex))
ImGuiNative.igImage(tex, size, new Vector2(op.C, op.D), new Vector2(op.E, op.F), Rgba(op.Color), Rgba(op.Color2));
else
Placeholder(size, Rgba(op.Color2));
break;
}
case ScriptOp.ImageButton:
{
var size = new Vector2(op.A * s, op.B * s);
byte clicked;
if (ScriptIcons.TryGet((ScriptIconKind)op.Flag, unchecked((uint)op.I0), out IntPtr tex))
clicked = ImGuiNative.igImageButton(str, tex, size, new Vector2(op.C, op.D), new Vector2(op.E, op.F), Rgba(op.Color), Rgba(op.Color2));
else
{
// The same button (same ID, size and frame) with the placeholder inside.
WhitePixel(out IntPtr white, out Vector2 uv);
clicked = ImGuiNative.igImageButton(str, white, size, uv, uv, Rgba(op.Color), PlaceholderFill);
}
if (clicked != 0)
w.NoteInput(events.Click(w.Hash, op.Key), frame);
break;
}
case ScriptOp.InputInt:
{
bool had = locals.Ints.TryGet(op.Key, ack, out int local);
int v = had ? local : op.I0;
bool changed = ImGuiNative.igInputInt(str, &v, op.I1, op.I2, (ImGuiInputTextFlags)op.Flags) != 0;
bool active = ImGuiNative.igIsItemActive() != 0;
uint seq = 0;
if (changed)
{
seq = events.Int(w.Hash, op.Key, v);
w.NoteInput(seq, frame);
}
locals.Ints.After(op.Key, had, changed, v, seq, active, frame);
break;
}
case ScriptOp.InputFloat:
{
bool had = locals.Floats.TryGet(op.Key, ack, out float local);
float v = had ? local : op.A;
bool changed = ImGuiNative.igInputFloat(str, &v, op.B, op.C, pool + op.Str2, (ImGuiInputTextFlags)op.Flags) != 0;
bool active = ImGuiNative.igIsItemActive() != 0;
uint seq = 0;
if (changed && float.IsFinite(v))
{
seq = events.Float(w.Hash, op.Key, v);
w.NoteInput(seq, frame);
}
else changed = false;
locals.Floats.After(op.Key, had, changed, v, seq, active, frame);
break;
}
case ScriptOp.DragInt:
{
bool had = locals.Ints.TryGet(op.Key, ack, out int local);
int v = had ? local : op.I0;
bool changed = ImGuiNative.igDragInt(str, &v, op.D, op.I1, op.I2, pool + op.Str2, (ImGuiSliderFlags)op.Flags) != 0;
bool active = ImGuiNative.igIsItemActive() != 0;
uint seq = 0;
if (changed)
{
seq = events.Int(w.Hash, op.Key, v);
w.NoteInput(seq, frame);
}
locals.Ints.After(op.Key, had, changed, v, seq, active, frame);
break;
}
case ScriptOp.DragFloat:
{
bool had = locals.Floats.TryGet(op.Key, ack, out float local);
float v = had ? local : op.A;
bool changed = ImGuiNative.igDragFloat(str, &v, op.D, op.B, op.C, pool + op.Str2, (ImGuiSliderFlags)op.Flags) != 0;
bool active = ImGuiNative.igIsItemActive() != 0;
uint seq = 0;
if (changed && float.IsFinite(v))
{
seq = events.Float(w.Hash, op.Key, v);
w.NoteInput(seq, frame);
}
else changed = false;
locals.Floats.After(op.Key, had, changed, v, seq, active, frame);
break;
}
// ── IDs, style, tooltips ──────────────────────────
case ScriptOp.PushID:
if (op.Flag == 0) ImGuiNative.igPushID_Str(str);
else ImGuiNative.igPushID_Int(op.I0);
sc.Ids++;
break;
case ScriptOp.PopID:
if (sc.Ids > 0)
{
sc.Ids--;
ImGuiNative.igPopID();
}
break;
case ScriptOp.PushStyleColor:
ImGuiNative.igPushStyleColor_U32((ImGuiCol)op.Aux, op.Color);
sc.Colors++;
break;
case ScriptOp.PopStyleColor:
{
int count = Math.Min((int)op.Aux, sc.Colors);
if (count > 0)
{
sc.Colors -= count;
ImGuiNative.igPopStyleColor(count);
}
break;
}
case ScriptOp.SetItemTooltip:
if (ImGuiNative.igIsItemHovered(ImGuiHoveredFlags.ForTooltip) != 0 && ImGuiNative.igBeginTooltip() != 0)
{
try { ImGuiNative.igTextUnformatted(str, str + op.StrLen); }
finally { ImGuiNative.igEndTooltip(); }
}
break;
// ── Containers ────────────────────────────────────
case ScriptOp.Child:
{
ImGuiChildFlags childFlags = op.Flag != 0 ? ImGuiChildFlags.Borders : ImGuiChildFlags.None;
bool visible = ImGuiNative.igBeginChild_Str(str, new Vector2(op.A * s, op.B * s), childFlags, (ImGuiWindowFlags)op.Flags) != 0;
if (visible && open < Scopes.Length)
Scopes[open++] = new Scope { Kind = ScopeChild, End = op.EndIndex };
else
{
ImGuiNative.igEndChild(); // always paired, drawn or not
next = op.EndIndex;
}
break;
}
case ScriptOp.TreeNode:
{
byte live = ImGuiNative.igTreeNodeEx_Str(str, (ImGuiTreeNodeFlags)op.Flags);
ReportOpen(w, ref op, live, frame);
if (live != 0 && op.Flag != 0 && open < Scopes.Length)
Scopes[open++] = new Scope { Kind = ScopeTree, End = op.EndIndex };
else
{
// Closed, or just opened by the player (recorded closed: no children yet).
if (live != 0) ImGuiNative.igTreePop();
next = op.EndIndex;
}
break;
}
case ScriptOp.CollapsingHeader:
{
byte live = ImGuiNative.igCollapsingHeader_TreeNodeFlags(str, (ImGuiTreeNodeFlags)op.Flags);
ReportOpen(w, ref op, live, frame);
// Just closed by the player: the recorded contents follow; hide them until the
// next header or the scope's end (one tick, until the next list arrives).
if (live == 0 && op.Flag != 0) sc.Skip = true;
break;
}
}
i = next;
}
}
finally
{
// Normal end: nothing is open. Over budget or an exception: close every open scope
// (colours, IDs, TreePop, EndChild) so ImGui's stacks stay balanced.
while (open > 0)
{
open--;
CloseScope(ref Scopes[open]);
}
}
}
return visited;
}
/// <summary>The missing-icon placeholder's fill (a dim grey square).</summary>
private static readonly Vector4 PlaceholderFill = new(0.5f, 0.5f, 0.5f, 0.35f);
/// <summary>0xAABBGGRR as ImGui's Vector4 colour.</summary>
private static Vector4 Rgba(uint c) =>
new((c & 0xFF) / 255f, ((c >> 8) & 0xFF) / 255f, ((c >> 16) & 0xFF) / 255f, (c >> 24) / 255f);
/// <summary>The font atlas's white pixel: a plain-colour "image" that needs no texture of its own.</summary>
private static void WhitePixel(out IntPtr texture, out Vector2 uv)
{
ImFontAtlas* atlas = ImGuiNative.igGetIO()->Fonts;
texture = atlas->TexID;
uv = atlas->TexUvWhitePixel;
}
/// <summary>An icon that isn't ready, is missing or didn't decode: a dim square of the same size (and border).</summary>
private static void Placeholder(Vector2 size, Vector4 border)
{
WhitePixel(out IntPtr white, out Vector2 uv);
ImGuiNative.igImage(white, size, uv, uv, PlaceholderFill, border);
}
private static void CloseScope(ref Scope sc)
{
if (sc.Colors > 0)
{
int c = sc.Colors;
sc.Colors = 0;
ImGuiNative.igPopStyleColor(c);
}
while (sc.Ids > 0)
{
sc.Ids--;
ImGuiNative.igPopID();
}
byte kind = sc.Kind;
sc.Kind = ScopeRoot;
if (kind == ScopeTree) ImGuiNative.igTreePop();
else if (kind == ScopeChild) ImGuiNative.igEndChild();
}
/// <summary>
/// A tree node / header whose live state differs from what was last reported for this list
/// (at first, the recorded state) queues an Open event (coalesced per widget).
/// </summary>
private static void ReportOpen(ScriptWindow w, ref ReplayOp op, byte live, int frame)
{
byte v = live != 0 ? (byte)1 : (byte)0;
if (v == op.LastOpen) return;
op.LastOpen = v;
w.NoteInput(w.Owner.Events.Open(w.Hash, op.Key, v != 0), frame);
}
private static void ReplayInputText(ScriptWindow w, ref ReplayOp op, byte* label, byte* pool, uint ack, int frame)
{
int maxLen = op.Aux;
ScriptLocals.TextLocal t = w.Locals.Text(op.Key, maxLen, frame);
byte[] buf = t.Buf;
// No newer local text and not being typed in: show the list's value (copied only when it differs).
if (!(t.Seq > ack || t.Active))
{
t.Seq = 0;
var value = new ReadOnlySpan<byte>(pool + op.Str2, op.Str2Len);
int cur = Array.IndexOf(buf, (byte)0);
if (cur < 0) cur = buf.Length - 1;
if (!value.SequenceEqual(buf.AsSpan(0, cur)))
{
value.CopyTo(buf);
buf[value.Length] = 0;
}
}
var flags = (ImGuiInputTextFlags)op.Flags;
byte ret;
bool edited;
fixed (byte* b = buf)
{
ret = ImGuiNative.igInputText(label, b, (uint)(maxLen + 1), flags, null, null);
edited = ImGuiNative.igIsItemEdited() != 0;
}
t.Active = ImGuiNative.igIsItemActive() != 0;
// EnterReturnsTrue: true = Enter pressed (submitted); edits still send the text, unsubmitted.
// Otherwise true = edited.
bool enterMode = (flags & ImGuiInputTextFlags.EnterReturnsTrue) != 0;
bool submitted = enterMode && ret != 0;
if (submitted || edited || (!enterMode && ret != 0))
{
buf[maxLen] = 0;
int len = Array.IndexOf(buf, (byte)0);
uint seq = w.Owner.Events.Text(w.Hash, op.Key, buf.AsSpan(0, len), submitted);
t.Seq = seq;
w.NoteInput(seq, frame);
}
}
}
/// <summary>
/// A window's local widget values (no snap-back, §2.5). AC thread only. A local value shows
/// while its event seq is newer than the list's AckSeq, or while ImGui reported the item
/// active last frame; otherwise it is dropped and the list's value shows.
/// </summary>
internal sealed class ScriptLocals
{
private const int PruneAbove = 64;
private const int StaleFrames = 600;
public struct Local<T> where T : struct
{
public T Value;
public uint Seq;
public bool Active;
public int Frame;
}
public sealed class LocalMap<T> where T : struct
{
private readonly Dictionary<uint, Local<T>> _map = new();
public int Count => _map.Count;
/// <summary>The local value to show instead of the list's, if any (a stale one is dropped).</summary>
public bool TryGet(uint key, uint ack, out T value)
{
value = default;
if (_map.Count == 0) return false;
ref Local<T> l = ref CollectionsMarshal.GetValueRefOrNullRef(_map, key);
if (Unsafe.IsNullRef(ref l)) return false;
if (l.Seq > ack || l.Active)
{
value = l.Value;
return true;
}
_map.Remove(key);
return false;
}
/// <summary>After the widget call: record a change, or the item's active state.</summary>
public void After(uint key, bool had, bool changed, T value, uint seq, bool active, int frame)
{
if (changed)
{
_map[key] = new Local<T> { Value = value, Seq = seq, Active = active, Frame = frame };
return;
}
if (had)
{
ref Local<T> l = ref CollectionsMarshal.GetValueRefOrNullRef(_map, key);
if (!Unsafe.IsNullRef(ref l))
{
l.Active = active;
l.Frame = frame;
}
}
else if (active)
{
// Grabbed without a change yet: hold the shown value while it is held.
_map[key] = new Local<T> { Value = value, Seq = 0, Active = true, Frame = frame };
}
}
public void Prune(int frame)
{
foreach (var kv in _map)
if (!kv.Value.Active && frame - kv.Value.Frame > StaleFrames)
_map.Remove(kv.Key);
}
}
/// <summary>One InputText's pinned buffer (maxLen + 1 bytes) and its local state.</summary>
public sealed class TextLocal
{
public byte[] Buf;
public int MaxLen;
public uint Seq;
public bool Active;
public int Frame;
public TextLocal(int maxLen)
{
MaxLen = maxLen;
Buf = GC.AllocateArray<byte>(maxLen + 1, pinned: true);
}
}
public readonly LocalMap<bool> Bools = new();
public readonly LocalMap<int> Ints = new();
public readonly LocalMap<float> Floats = new();
private readonly Dictionary<uint, TextLocal> _texts = new();
/// <summary>
/// The InputText buffer for a widget, holding at most <paramref name="maxLen"/> bytes of text
/// (NUL-terminated within maxLen + 1). Allocated when first seen and only ever grown: two
/// InputTexts sharing a key (a duplicate ID the recorder only warns about) with different
/// maxLens would otherwise swap a new pinned buffer in for each of them on every frame.
/// A smaller maxLen cuts the text in place instead.
/// </summary>
public TextLocal Text(uint key, int maxLen, int frame)
{
if (!_texts.TryGetValue(key, out TextLocal? t))
{
t = new TextLocal(maxLen);
_texts[key] = t;
}
else if (t.MaxLen < maxLen)
{
var bigger = new TextLocal(maxLen) { Seq = t.Seq, Active = t.Active };
int len = Array.IndexOf(t.Buf, (byte)0);
if (len < 0) len = t.MaxLen;
t.Buf.AsSpan(0, len).CopyTo(bigger.Buf);
t = bigger;
_texts[key] = t;
}
if (t.MaxLen > maxLen && t.Buf[maxLen] != 0)
{
// ImGui copies strlen(buf) bytes into a buffer of the size it's given: the text must fit.
int len = Array.IndexOf(t.Buf, (byte)0);
if (len < 0 || len > maxLen)
{
len = maxLen;
while (len > 0 && (t.Buf[len] & 0xC0) == 0x80) len--; // don't split a character
t.Buf[len] = 0;
}
}
t.Frame = frame;
return t;
}
/// <summary>On a new list: drop entries for widgets not drawn for a while, once there are many.</summary>
public void PruneIfLarge(int frame)
{
if (Bools.Count > PruneAbove) Bools.Prune(frame);
if (Ints.Count > PruneAbove) Ints.Prune(frame);
if (Floats.Count > PruneAbove) Floats.Prune(frame);
if (_texts.Count > PruneAbove)
foreach (var kv in _texts)
if (!kv.Value.Active && frame - kv.Value.Frame > StaleFrames)
_texts.Remove(kv.Key);
}
}
/// <summary>
/// Phase 0 measurements, AC thread: replay cost per frame (all script windows
/// together) and input -> reaction latency, logged about every 10 s while a
/// script window draws. Lines are written off AC's thread (UiBackgroundWriter).
/// </summary>
internal static class ScriptWindowStats
{
private const double LogEverySeconds = 10.0;
// The frame being summed.
private static int _curFrame = int.MinValue;
private static long _curTicks;
private static int _curOps, _curWindows;
// The current ~10 s period.
private static long _periodStart;
private static int _frames, _maxWindows, _maxOps;
private static long _sumTicks, _maxTicks, _sumOps;
private static int _reactions, _reactionFramesSum, _reactionFramesMax;
private static long _reactionTicksSum, _reactionTicksMax;
public static void Replay(int frame, long ticks, int ops)
{
if (frame != _curFrame)
{
FlushFrame();
_curFrame = frame;
}
_curTicks += ticks;
_curOps += ops;
_curWindows++;
long now = Stopwatch.GetTimestamp();
if (_periodStart == 0) _periodStart = now;
if (now - _periodStart >= (long)(Stopwatch.Frequency * LogEverySeconds))
{
LogPeriod(now);
_periodStart = now;
}
}
public static void Reaction(ScriptWindow w, int frames, long ticks)
{
_reactions++;
_reactionFramesSum += frames;
_reactionFramesMax = Math.Max(_reactionFramesMax, frames);
_reactionTicksSum += ticks;
_reactionTicksMax = Math.Max(_reactionTicksMax, ticks);
string line = $"ScriptWindows input->reaction: {w.PanelKey} {frames} frame(s), {Ms(ticks):0.0} ms";
UiBackgroundWriter.Enqueue("script window latency", () => RynthLog.UI(line));
}
private static void FlushFrame()
{
if (_curWindows == 0) return;
_frames++;
_sumTicks += _curTicks;
_maxTicks = Math.Max(_maxTicks, _curTicks);
_sumOps += _curOps;
_maxOps = Math.Max(_maxOps, _curOps);
_maxWindows = Math.Max(_maxWindows, _curWindows);
_curTicks = 0;
_curOps = 0;
_curWindows = 0;
}
private static void LogPeriod(long now)
{
FlushFrame();
if (_frames > 0)
{
double seconds = (now - _periodStart) / (double)Stopwatch.Frequency;
double avgUs = Ms(_sumTicks) * 1000.0 / _frames;
double maxUs = Ms(_maxTicks) * 1000.0;
double avgOps = _sumOps / (double)_frames;
double usPerOp = _sumOps > 0 ? Ms(_sumTicks) * 1000.0 / _sumOps : 0;
string reaction = _reactions == 0 ? "none"
: $"n={_reactions} avg={_reactionFramesSum / (double)_reactions:0.0} frames/{Ms(_reactionTicksSum) / _reactions:0.0} ms max={_reactionFramesMax} frames/{Ms(_reactionTicksMax):0.0} ms";
string line = $"ScriptWindows replay: {seconds:0.0}s frames={_frames} windows<={_maxWindows} ops/frame avg={avgOps:0} max={_maxOps} "
+ $"us/frame avg={avgUs:0.0} max={maxUs:0.0} us/op={usPerOp:0.000} | input->reaction {reaction}";
UiBackgroundWriter.Enqueue("script window stats", () => RynthLog.UI(line));
}
_frames = _maxWindows = _maxOps = 0;
_sumTicks = _maxTicks = _sumOps = 0;
_reactions = _reactionFramesSum = _reactionFramesMax = 0;
_reactionTicksSum = _reactionTicksMax = 0;
}
private static double Ms(long ticks) => ticks * 1000.0 / Stopwatch.Frequency;
}

View file

@ -0,0 +1,46 @@
// ============================================================================
// RynthCore.Engine - ImGui/UiFrameStats.cs
// Cost of the ImGui work on AC's render thread, for the heartbeat's "ui=".
//
// Record() runs once per EndScene (AC thread) with the ticks spent building
// and submitting the ImGui frame (0-ish on early-out frames). Once a second
// it sorts the window in place and publishes the p95 and max; the heartbeat
// thread only reads the two published floats. No allocation.
// ============================================================================
using System;
using System.Diagnostics;
namespace RynthCore.Engine.ImGuiBackend;
internal static class UiFrameStats
{
private static readonly long[] _samples = new long[1024];
private static int _count;
private static long _windowStart;
private static volatile float _p95Ms;
private static volatile float _maxMs;
/// <summary>95th-percentile ImGui cost per frame over the last full second, in ms.</summary>
public static float P95Ms => _p95Ms;
/// <summary>Worst ImGui frame over the last full second, in ms.</summary>
public static float MaxMs => _maxMs;
public static void Record(long elapsedTicks)
{
long now = Stopwatch.GetTimestamp();
if (_windowStart == 0) _windowStart = now;
if (_count < _samples.Length) _samples[_count++] = elapsedTicks;
if (now - _windowStart < Stopwatch.Frequency) return;
Array.Sort(_samples, 0, _count);
int p95 = Math.Clamp((int)Math.Ceiling(_count * 0.95) - 1, 0, _count - 1);
double toMs = 1000.0 / Stopwatch.Frequency;
_p95Ms = (float)(_samples[p95] * toMs);
_maxMs = (float)(_samples[_count - 1] * toMs);
_count = 0;
_windowStart = now;
}
}

View file

@ -0,0 +1,167 @@
// ============================================================================
// RynthCore.Engine - ImGui/UnderUiLayer.cs
// ImGui geometry that belongs to the 3D world (RynthVision's nameplates, the
// player plate and the combat text): drawn after AC's 3D scene and BEFORE
// AC's own UI, so AC's chat, radar, inventory and other windows cover it the
// way they cover the world. Everything else ImGui draws (the bar, the panels)
// still renders at EndScene, over AC's UI.
//
// How:
// Build inside the main ImGui frame (EndScene), MonsterHud paints into
// one of two ImDrawLists owned here instead of ImGui's background
// list. The lists are created once from the main context's shared
// draw-list data and reset each frame, so their buffers are reused
// (no per-frame allocation once they have grown).
// Commit at the end of EndScene the list just built becomes the one to
// show during the NEXT frame; the other list is built into next.
// Present the next frame, Nav3DRenderInjector's DrawIndexedPrimitive hook
// spots AC's 3D->UI transition (ZENABLE 1->0) and calls
// PresentAtTransition, right after the Nav3D markers: the list goes
// through DX9Backend with a full state save/restore.
// Fallback a frame whose transition wasn't seen (portal space, a loading
// screen, the injector missing it) presents the list at EndScene
// instead, before the ImGui panels - the same place RenderNav3D's
// fallback draws. A list is presented at most once: no double draw.
//
// 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
// that falls back doesn't jump.
//
// Threads: AC's render thread only (EndScene and the DIP detour both run on
// it). Shutdown may run on the lifecycle thread while AC's thread is still in
// the DIP detour: it unpublishes the lists, waits for a present in flight to
// finish, then frees them.
// ============================================================================
using System;
using System.Numerics;
using System.Threading;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class UnderUiLayer
{
private static ImDrawList* _listA, _listB;
private static ImDrawList* _building; // being built this frame (null: nothing built)
private static Vector2 _buildingSize;
private static ImDrawList* _ready; // to present this frame (built last frame)
private static Vector2 _readySize;
private static bool _presented; // _ready already drawn this frame
private static int _presenting; // a present is in flight (Shutdown waits for it)
private static volatile bool _shutDown;
/// <summary>True after <see cref="BeginBuild"/> returned a list this frame. AC's render thread.</summary>
public static bool IsBuilding => _building != null;
/// <summary>Frames presented at the transition / at the EndScene fallback (diagnostics).</summary>
private static long _atTransition, _atFallback;
/// <summary>
/// Inside the main ImGui frame, main context current: a cleared draw list to
/// paint this frame's world overlays into, laid out for <paramref name="display"/>
/// (ImGui display pixels). Null when the layer isn't available. AC's render thread.
/// </summary>
public static ImDrawListPtr BeginBuild(Vector2 display)
{
if (_shutDown) return new ImDrawListPtr(null);
if (_listA == null)
{
IntPtr shared = ImGuiNET.ImGui.GetDrawListSharedData();
if (shared == IntPtr.Zero) return new ImDrawListPtr(null);
_listA = ImGuiNative.ImDrawList_ImDrawList(shared);
_listB = ImGuiNative.ImDrawList_ImDrawList(shared);
}
// Never the list waiting to be shown (the fallback may still present it this frame).
ImDrawList* list = _ready == _listA ? _listB : _listA;
var ptr = new ImDrawListPtr(list);
// What ImGui does for its own background list each frame: reset (keeps the
// buffers), the frame's flags, the font atlas texture, a full-screen clip.
ptr._ResetForNewFrame();
ptr.PushTextureID(ImGuiNET.ImGui.GetIO().Fonts.TexID);
ptr.PushClipRect(Vector2.Zero, display, false);
_building = list;
_buildingSize = display;
return ptr;
}
/// <summary>
/// Called by the DIP hook at AC's 3D->UI transition: draws last frame's world
/// overlays under AC's UI. AC's render thread.
/// </summary>
public static void PresentAtTransition(IntPtr device)
{
if (Present(device)) _atTransition++;
}
/// <summary>
/// EndScene, before the ImGui panels are submitted: when the transition wasn't
/// seen this frame, the overlays are drawn here instead. AC's render thread.
/// </summary>
public static void PresentFallback(IntPtr device)
{
if (Present(device)) _atFallback++;
}
private static bool Present(IntPtr device)
{
if (_presented) return false;
Interlocked.Exchange(ref _presenting, 1);
try
{
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;
}
finally
{
Volatile.Write(ref _presenting, 0);
}
}
/// <summary>
/// End of EndScene (every frame, ImGui on or off): what was built this frame is
/// presented next frame; nothing built means nothing to present. AC's render thread.
/// </summary>
public static void EndFrame()
{
_ready = _shutDown ? null : _building;
_readySize = _buildingSize;
_building = null;
_presented = false;
}
/// <summary>One line for /rc imgui diag.</summary>
public static string Describe() =>
$"under-UI layer: presented at 3D->UI {_atTransition}, at EndScene (fallback) {_atFallback}";
/// <summary>
/// Engine shutdown, before DX9Backend and the ImGui context go. Any thread:
/// unpublishes the lists, waits (briefly) for a present in flight, frees them.
/// </summary>
public static void Shutdown()
{
_shutDown = true;
ImDrawList* a = _listA, b = _listB;
_ready = null;
_building = null;
_listA = _listB = null;
Thread.MemoryBarrier();
var spin = new SpinWait();
long deadline = Environment.TickCount64 + 200;
while (Volatile.Read(ref _presenting) != 0 && Environment.TickCount64 < deadline)
spin.SpinOnce();
if (Volatile.Read(ref _presenting) != 0)
{
// Still drawing after 200 ms: leak the two lists rather than free them under it.
RynthLog.Render("UnderUiLayer: a present was still running at shutdown; its lists are left allocated.");
return;
}
if (a != null) ImGuiNative.ImDrawList_destroy(a);
if (b != null) ImGuiNative.ImDrawList_destroy(b);
}
}

View file

@ -1,53 +0,0 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportOffsets.cs
// Byte offsets of ImGuiPlatformIO callback fields in the cimgui.dll shipped
// with ImGui.NET 1.91.6.1 (docking branch).
//
// WARNING: these do NOT match ImGui.NET's compiled struct layout. ImGui.NET
// prepends 36 bytes of clipboard/IME/OpenInShell fields that this cimgui.dll
// build does not have. Writing via ImGui.NET's ref properties lands 36 bytes
// past the native field, so the native library sees NULL and asserts
// "Platform init didn't install handlers".
//
// Source of truth (disassembled cimgui.dll 1.91.6.1, x86):
// ImGuiPlatformIO_Set_Platform_GetWindowPos → mov [pio+0x10], shim
// ImGuiPlatformIO_Set_Platform_GetWindowSize → mov [pio+0x18], shim
// igUpdatePlatformWindows first callback dispatch → call [g+0x37B8]
// with ImGuiContext PlatformIO offset → pio field 0 = Platform_CreateWindow
//
// Struct size (from constructor memset): 0x74 (116 bytes). Fields 0x00..0x5F
// hold 24 callback pointers; 0x60..0x73 hold Monitors + Viewports ImVectors.
// ═══════════════════════════════════════════════════════════════════════════
namespace RynthCore.Engine.ImGuiBackend;
internal static class ViewportOffsets
{
// Platform_* (18 callbacks — this cimgui.dll build lacks GetWindowWorkAreaInsets)
public const int PlatformCreateWindow = 0;
public const int PlatformDestroyWindow = 4;
public const int PlatformShowWindow = 8;
public const int PlatformSetWindowPos = 12;
public const int PlatformGetWindowPos = 16; // confirmed via _Set_ helper disasm
public const int PlatformSetWindowSize = 20;
public const int PlatformGetWindowSize = 24; // confirmed via _Set_ helper disasm
public const int PlatformSetWindowFocus = 28;
public const int PlatformGetWindowFocus = 32;
public const int PlatformGetWindowMinimized = 36;
public const int PlatformSetWindowTitle = 40;
public const int PlatformSetWindowAlpha = 44;
public const int PlatformUpdateWindow = 48;
public const int PlatformRenderWindow = 52;
public const int PlatformSwapBuffers = 56;
public const int PlatformGetWindowDpiScale = 60;
public const int PlatformOnChangedViewport = 64;
public const int PlatformCreateVkSurface = 68;
// Renderer_* (5 callbacks) — RendererCreateWindow at +72 confirmed by
// igUpdatePlatformWindows disasm: [ebx+0x3800] = [pio + 0x48] = +72.
public const int RendererCreateWindow = 72;
public const int RendererDestroyWindow = 76;
public const int RendererSetWindowSize = 80;
public const int RendererRenderWindow = 84;
public const int RendererSwapBuffers = 88;
}

View file

@ -1,829 +0,0 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportPlatformBackend.cs
// Win32 platform backend for Dear ImGui multi-viewport (equivalent of
// imgui_impl_win32's viewport-capable portion). Installs Platform_* callbacks
// into the native ImGuiPlatformIO struct, registers a window class for
// popped-out ImGui windows, and proxies the required Win32 calls.
//
// Input for viewport HWNDs is forwarded into the existing Dear ImGui IO
// event queue via a dedicated WndProc.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Runtime.InteropServices;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ViewportPlatformBackend
{
// ── Delegate types (cdecl; ImGui callbacks on x86 use the default C ABI) ──
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportVoidDelegate(ImGuiViewport* vp);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportGetVec2Delegate(ImGuiViewport* vp, Vector2* outVec);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSetVec2Delegate(ImGuiViewport* vp, Vector2 value);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte ViewportGetBoolDelegate(ImGuiViewport* vp);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSetStringDelegate(ImGuiViewport* vp, IntPtr str);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSetFloatDelegate(ImGuiViewport* vp, float value);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern ushort RegisterClassExW(ref WNDCLASSEXW lpwcx);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr CreateWindowExW(
uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle,
int X, int Y, int nWidth, int nHeight,
IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
[DllImport("user32.dll")]
private static extern bool DestroyWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int SetWindowTextW(IntPtr hWnd, string lpString);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowLongW(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll")]
private static extern IntPtr GetWindowLongW(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern bool SetLayeredWindowAttributes(IntPtr hWnd, uint crKey, byte bAlpha, uint dwFlags);
[DllImport("user32.dll")]
private static extern IntPtr DefWindowProcW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool AdjustWindowRectEx(ref RECT lpRect, uint dwStyle, bool bMenu, uint dwExStyle);
[DllImport("user32.dll")]
private static extern bool PostMessageW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll")]
private static extern IntPtr SetCapture(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ReleaseCapture();
[StructLayout(LayoutKind.Sequential)]
private struct POINT { public int X, Y; }
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("user32.dll")]
private static extern IntPtr LoadCursorW(IntPtr hInstance, IntPtr lpCursorName);
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int nIndex);
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProc lpfnEnum, IntPtr dwData);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern bool GetMonitorInfoW(IntPtr hMonitor, ref MONITORINFO lpmi);
private delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData);
[StructLayout(LayoutKind.Sequential)]
private struct MONITORINFO
{
public uint cbSize;
public RECT rcMonitor;
public RECT rcWork;
public uint dwFlags;
}
private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private const uint MONITORINFOF_PRIMARY = 0x00000001;
// ImGuiPlatformIO Monitors ImVector (native cimgui.dll layout).
// Native has 18 Platform_* + 5 Renderer_* = 23 callback pointers = 92 bytes,
// then Monitors ImVector{ int Size; int Capacity; void* Data; } at +92..+103,
// then Viewports ImVector at +104..+115. (ImGui.NET's compiled layout adds
// GetWindowWorkAreaInsets and so puts Monitors at +96 — do NOT use that.)
// Confirmed by probe dump showing Viewports.Size=1, Cap=8, Data=ptr at
// +104..+115 when native had just seeded the main viewport.
private const int MonitorsSize = 92;
private const int MonitorsCapacity = 96;
private const int MonitorsData = 100;
// ImGuiPlatformMonitor is 40 bytes (confirmed by cimgui.dll ctor "push 28h"):
// +0 MainPos (ImVec2, 8)
// +8 MainSize (ImVec2, 8)
// +16 WorkPos (ImVec2, 8)
// +24 WorkSize (ImVec2, 8)
// +32 DpiScale (float, 4)
// +36 PlatformHandle (void*, 4)
private const int MonitorStructSize = 40;
private static IntPtr _monitorArrayPtr;
private static int _monitorCount;
private delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct WNDCLASSEXW
{
public uint cbSize;
public uint style;
public IntPtr lpfnWndProc;
public int cbClsExtra;
public int cbWndExtra;
public IntPtr hInstance;
public IntPtr hIcon;
public IntPtr hCursor;
public IntPtr hbrBackground;
[MarshalAs(UnmanagedType.LPWStr)] public string? lpszMenuName;
[MarshalAs(UnmanagedType.LPWStr)] public string? lpszClassName;
public IntPtr hIconSm;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int Left, Top, Right, Bottom; }
// Win32 constants
private const int GWL_STYLE = -16;
private const int GWL_EXSTYLE = -20;
private const int SW_SHOWNA = 8;
private const int SW_HIDE = 0;
private const uint SWP_NOMOVE = 0x0002;
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_NOZORDER = 0x0004;
private const uint SWP_NOACTIVATE = 0x0010;
private const uint WS_POPUP = 0x80000000;
private const uint WS_OVERLAPPEDWINDOW = 0x00CF0000;
private const uint WS_CLIPCHILDREN = 0x02000000;
private const uint WS_CLIPSIBLINGS = 0x04000000;
private const uint WS_EX_TOOLWINDOW = 0x00000080;
private const uint WS_EX_LAYERED = 0x00080000;
private const uint WS_EX_APPWINDOW = 0x00040000;
private const uint WS_EX_TOPMOST = 0x00000008;
private const uint WS_EX_NOACTIVATE = 0x08000000;
private const uint LWA_ALPHA = 0x00000002;
private const uint WM_CLOSE = 0x0010;
private const uint WM_MOVE = 0x0003;
private const uint WM_SIZE = 0x0005;
private const uint WM_MOUSEACTIVATE = 0x0021;
private const uint WM_NCHITTEST = 0x0084;
private const uint WM_MOUSEMOVE = 0x0200;
private const uint WM_LBUTTONDOWN = 0x0201;
private const uint WM_LBUTTONUP = 0x0202;
private const uint WM_LBUTTONDBLCLK = 0x0203;
private const uint WM_RBUTTONDOWN = 0x0204;
private const uint WM_RBUTTONUP = 0x0205;
private const uint WM_RBUTTONDBLCLK = 0x0206;
private const uint WM_MBUTTONDOWN = 0x0207;
private const uint WM_MBUTTONUP = 0x0208;
private const uint WM_MBUTTONDBLCLK = 0x0209;
private const uint WM_MOUSEWHEEL = 0x020A;
private const uint WM_XBUTTONDOWN = 0x020B;
private const uint WM_XBUTTONUP = 0x020C;
private const uint WM_MOUSEHWHEEL = 0x020E;
private const uint WM_KEYDOWN = 0x0100;
private const uint WM_KEYUP = 0x0101;
private const uint WM_CHAR = 0x0102;
private const uint WM_SYSKEYDOWN = 0x0104;
private const uint WM_SYSKEYUP = 0x0105;
private const int MA_NOACTIVATE = 3;
private const int HTCLIENT = 1;
private const IntPtr IDC_ARROW = 0x7F00; // MAKEINTRESOURCE(32512)
private const string WindowClassName = "RynthCoreImGuiViewport";
// Pinned delegate instances — prevent GC while ImGui holds function pointers.
private static readonly List<Delegate> _delegateRoots = new();
private static WndProcDelegate? _viewportWndProc;
private static IntPtr _viewportWndProcPtr;
private static bool _initialized;
private static bool _classRegistered;
private static IntPtr _hInstance;
private static IntPtr _mainHwnd;
// Per-viewport state kept on the managed side.
// Keyed by the native ImGuiViewport* pointer.
private static readonly Dictionary<IntPtr, ViewportState> _viewports = new();
private class ViewportState
{
public IntPtr Hwnd;
public bool HwndOwned;
public uint DwStyle;
public uint DwExStyle;
}
public static bool Init(IntPtr mainHwnd)
{
if (_initialized) return true;
_mainHwnd = mainHwnd;
_hInstance = GetModuleHandleW(null);
if (!EnsureWindowClassRegistered())
{
RynthLog.Info($"ViewportPlatform: RegisterClassEx failed (err {Marshal.GetLastWin32Error()})");
return false;
}
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
InstallCallbacks(pio);
PopulateMonitors(pio);
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
io.BackendFlags |= ImGuiBackendFlags.PlatformHasViewports;
// Do NOT set HasMouseHoveredViewport: that flag tells ImGui the backend
// will route hovered-viewport info via AddMouseViewportEvent each frame.
// We don't call that, so setting the flag causes mouse input to drop on
// the floor (IsWindowHovered returns false for every window).
// The main viewport's PlatformHandle points to the game window; store it
// so the very first frame doesn't try to create a new HWND for viewport 0.
ImGuiViewportPtr mainViewport = ImGuiNET.ImGui.GetMainViewport();
mainViewport.PlatformHandle = _mainHwnd;
mainViewport.PlatformHandleRaw = _mainHwnd;
_viewports[(IntPtr)mainViewport.NativePtr] = new ViewportState
{
Hwnd = _mainHwnd,
HwndOwned = false,
DwStyle = unchecked((uint)(long)GetWindowLongW(_mainHwnd, GWL_STYLE)),
DwExStyle = unchecked((uint)(long)GetWindowLongW(_mainHwnd, GWL_EXSTYLE)),
};
_initialized = true;
RynthLog.Info("ViewportPlatform: initialized.");
return true;
}
public static void Shutdown()
{
if (!_initialized) return;
// Destroy any viewport windows we created.
foreach (var kv in _viewports)
{
if (kv.Value.HwndOwned && kv.Value.Hwnd != IntPtr.Zero)
DestroyWindow(kv.Value.Hwnd);
}
_viewports.Clear();
// Clear the Monitors ImVector pointer in PlatformIO before freeing our
// backing buffer — native ImGui otherwise keeps a stale Data pointer.
if (_monitorArrayPtr != IntPtr.Zero)
{
try
{
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
IntPtr pioNative = (IntPtr)pio.NativePtr;
Marshal.WriteInt32(pioNative, MonitorsSize, 0);
Marshal.WriteInt32(pioNative, MonitorsCapacity, 0);
Marshal.WriteIntPtr(pioNative, MonitorsData, IntPtr.Zero);
}
catch { /* context may already be torn down */ }
Marshal.FreeHGlobal(_monitorArrayPtr);
_monitorArrayPtr = IntPtr.Zero;
_monitorCount = 0;
}
_initialized = false;
}
// Dear ImGui asserts Monitor.Size > 0 before the first UpdatePlatformWindows
// call when ViewportsEnable is on. Populate the Monitors ImVector with the
// primary (and any secondary) displays so windows can pop out correctly.
private static void PopulateMonitors(ImGuiPlatformIOPtr pio)
{
var rects = new List<(RECT mon, RECT work, bool primary)>();
MonitorEnumProc cb = (IntPtr hMon, IntPtr hdc, ref RECT r, IntPtr _) =>
{
MONITORINFO mi = default;
mi.cbSize = (uint)Marshal.SizeOf<MONITORINFO>();
if (GetMonitorInfoW(hMon, ref mi))
rects.Add((mi.rcMonitor, mi.rcWork, (mi.dwFlags & MONITORINFOF_PRIMARY) != 0));
return true;
};
if (!EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, cb, IntPtr.Zero) || rects.Count == 0)
{
// Fallback: single primary display via GetSystemMetrics.
int w = GetSystemMetrics(SM_CXSCREEN);
int h = GetSystemMetrics(SM_CYSCREEN);
RECT r = new RECT { Left = 0, Top = 0, Right = w > 0 ? w : 1920, Bottom = h > 0 ? h : 1080 };
rects.Add((r, r, true));
}
GC.KeepAlive(cb);
_monitorCount = rects.Count;
_monitorArrayPtr = Marshal.AllocHGlobal(_monitorCount * MonitorStructSize);
// Primary monitor must be at index 0 for Dear ImGui's viewport code.
rects.Sort((a, b) => (b.primary ? 1 : 0) - (a.primary ? 1 : 0));
for (int i = 0; i < _monitorCount; i++)
{
var (mon, work, _) = rects[i];
IntPtr mp = _monitorArrayPtr + i * MonitorStructSize;
WriteFloat(mp, 0, mon.Left);
WriteFloat(mp, 4, mon.Top);
WriteFloat(mp, 8, mon.Right - mon.Left);
WriteFloat(mp, 12, mon.Bottom - mon.Top);
WriteFloat(mp, 16, work.Left);
WriteFloat(mp, 20, work.Top);
WriteFloat(mp, 24, work.Right - work.Left);
WriteFloat(mp, 28, work.Bottom - work.Top);
WriteFloat(mp, 32, 1.0f);
Marshal.WriteIntPtr(mp, 36, IntPtr.Zero);
}
IntPtr pioNative = (IntPtr)pio.NativePtr;
Marshal.WriteInt32(pioNative, MonitorsSize, _monitorCount);
Marshal.WriteInt32(pioNative, MonitorsCapacity, _monitorCount);
Marshal.WriteIntPtr(pioNative, MonitorsData, _monitorArrayPtr);
RynthLog.Info($"ViewportPlatform: populated {_monitorCount} monitor(s) at 0x{_monitorArrayPtr.ToInt64():X8}");
}
private static bool EnsureWindowClassRegistered()
{
if (_classRegistered) return true;
_viewportWndProc = ViewportWndProc;
_viewportWndProcPtr = Marshal.GetFunctionPointerForDelegate(_viewportWndProc);
WNDCLASSEXW wc = default;
wc.cbSize = (uint)Marshal.SizeOf<WNDCLASSEXW>();
wc.style = 0x0020 /*CS_OWNDC*/ | 0x0002 /*CS_HREDRAW*/ | 0x0001 /*CS_VREDRAW*/;
wc.lpfnWndProc = _viewportWndProcPtr;
wc.hInstance = _hInstance;
wc.hCursor = LoadCursorW(IntPtr.Zero, IDC_ARROW);
wc.hbrBackground = IntPtr.Zero;
wc.lpszClassName = WindowClassName;
ushort atom = RegisterClassExW(ref wc);
if (atom == 0)
{
int err = Marshal.GetLastWin32Error();
// 1410 = ERROR_CLASS_ALREADY_EXISTS; fine if we were re-initialized.
if (err != 1410) return false;
}
_classRegistered = true;
return true;
}
// ─── Callback installation ────────────────────────────────────────────
private static void InstallCallbacks(ImGuiPlatformIOPtr pio)
{
IntPtr pioNative = (IntPtr)pio.NativePtr;
IntPtr createPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportCreate);
IntPtr destroyPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportDestroy);
IntPtr showPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportShow);
IntPtr setPosPtr = RootAndGetPointer<ViewportSetVec2Delegate>(ViewportSetPos);
IntPtr setSizePtr = RootAndGetPointer<ViewportSetVec2Delegate>(ViewportSetSize);
IntPtr setFocusPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportSetFocus);
IntPtr getFocusPtr = RootAndGetPointer<ViewportGetBoolDelegate>(ViewportGetFocus);
IntPtr getMinPtr = RootAndGetPointer<ViewportGetBoolDelegate>(ViewportGetMinimized);
IntPtr setTitlePtr = RootAndGetPointer<ViewportSetStringDelegate>(ViewportSetTitle);
IntPtr setAlphaPtr = RootAndGetPointer<ViewportSetFloatDelegate>(ViewportSetAlpha);
IntPtr updatePtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportUpdate);
// Direct writes at native cimgui.dll offsets (NOT ImGui.NET's compiled
// layout offsets — those are off by 36 bytes). Void-return and
// small-return callbacks match the cdecl ABI naturally.
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformCreateWindow, createPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformDestroyWindow, destroyPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformShowWindow, showPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowPos, setPosPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowSize, setSizePtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowFocus, setFocusPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformGetWindowFocus, getFocusPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformGetWindowMinimized, getMinPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowTitle, setTitlePtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowAlpha, setAlphaPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformUpdateWindow, updatePtr);
// GetWindowPos / GetWindowSize return ImVec2 by value (x86 cdecl struct
// return — hidden first arg on stack). Our C# delegates take an out-ptr
// instead; cimgui ships a wrapper helper that adapts the ABI and writes
// the wrapper at the right offset for us. Must install via helper, not
// Marshal.WriteIntPtr, or native crashes on the first call.
IntPtr getPosPtr = RootAndGetPointer<ViewportGetVec2Delegate>(ViewportGetPos);
IntPtr getSizePtr = RootAndGetPointer<ViewportGetVec2Delegate>(ViewportGetSize);
ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowPos(pio.NativePtr, getPosPtr);
ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowSize(pio.NativePtr, getSizePtr);
// Read back and log so a silent mismatch surfaces as a log line, not an IM_ASSERT.
IntPtr verifyCreate = Marshal.ReadIntPtr(pioNative, ViewportOffsets.PlatformCreateWindow);
IntPtr verifyGetPos = Marshal.ReadIntPtr(pioNative, ViewportOffsets.PlatformGetWindowPos);
RynthLog.Info($"ViewportPlatform: installed handlers (CreateWindow readback=0x{verifyCreate.ToInt64():X8}, expected=0x{createPtr.ToInt64():X8}, GetWindowPos shim=0x{verifyGetPos.ToInt64():X8})");
}
private static IntPtr RootAndGetPointer<TDelegate>(TDelegate del) where TDelegate : Delegate
{
_delegateRoots.Add(del);
return Marshal.GetFunctionPointerForDelegate<TDelegate>(del);
}
private static void WriteFloat(IntPtr basePtr, int offset, float value)
{
Marshal.WriteInt32(basePtr, offset, BitConverter.SingleToInt32Bits(value));
}
// ─── Callback implementations ─────────────────────────────────────────
private static void ViewportCreate(ImGuiViewport* vp)
{
uint flags = unchecked((uint)vp->Flags);
bool noDecoration = (flags & (uint)ImGuiViewportFlags.NoDecoration) != 0;
bool topMost = (flags & (uint)ImGuiViewportFlags.TopMost) != 0;
uint dwStyle = noDecoration
? WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS
: WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
// Always use WS_EX_TOOLWINDOW so tear-off viewports don't clutter the taskbar / Alt-Tab
// list when users run many clients. Owned by _mainHwnd so it still closes with the game.
uint dwExStyle = WS_EX_TOOLWINDOW;
if (topMost) dwExStyle |= WS_EX_TOPMOST;
dwExStyle |= WS_EX_NOACTIVATE;
// Compute outer window rect that yields the requested client size.
RECT rect;
rect.Left = (int)vp->Pos.X;
rect.Top = (int)vp->Pos.Y;
rect.Right = rect.Left + (int)vp->Size.X;
rect.Bottom = rect.Top + (int)vp->Size.Y;
AdjustWindowRectEx(ref rect, dwStyle, false, dwExStyle);
IntPtr hwnd = CreateWindowExW(
dwExStyle, WindowClassName, "RynthCore Viewport", dwStyle,
rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top,
_mainHwnd, IntPtr.Zero, _hInstance, IntPtr.Zero);
if (hwnd == IntPtr.Zero)
{
RynthLog.Info($"ViewportPlatform: CreateWindowEx failed (err {Marshal.GetLastWin32Error()})");
return;
}
var state = new ViewportState { Hwnd = hwnd, HwndOwned = true, DwStyle = dwStyle, DwExStyle = dwExStyle };
_viewports[(IntPtr)vp] = state;
vp->PlatformHandle = (void*)hwnd;
vp->PlatformHandleRaw = (void*)hwnd;
}
private static void ViewportDestroy(ImGuiViewport* vp)
{
IntPtr key = (IntPtr)vp;
if (_viewports.TryGetValue(key, out var state))
{
if (state.HwndOwned && state.Hwnd != IntPtr.Zero)
DestroyWindow(state.Hwnd);
_viewports.Remove(key);
}
vp->PlatformHandle = (void*)IntPtr.Zero;
vp->PlatformHandleRaw = (void*)IntPtr.Zero;
}
private static void ViewportShow(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return;
ShowWindow(state.Hwnd, SW_SHOWNA);
}
private static void ViewportSetPos(ImGuiViewport* vp, Vector2 pos)
{
if (!TryGetState(vp, out var state)) return;
RECT rect;
rect.Left = (int)pos.X;
rect.Top = (int)pos.Y;
rect.Right = rect.Left;
rect.Bottom = rect.Top;
AdjustWindowRectEx(ref rect, state.DwStyle, false, state.DwExStyle);
SetWindowPos(state.Hwnd, IntPtr.Zero, rect.Left, rect.Top, 0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
private static void ViewportSetSize(ImGuiViewport* vp, Vector2 size)
{
if (!TryGetState(vp, out var state)) return;
RECT rect;
rect.Left = 0; rect.Top = 0;
rect.Right = (int)size.X;
rect.Bottom = (int)size.Y;
AdjustWindowRectEx(ref rect, state.DwStyle, false, state.DwExStyle);
SetWindowPos(state.Hwnd, IntPtr.Zero, 0, 0,
rect.Right - rect.Left, rect.Bottom - rect.Top,
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
}
private static void ViewportGetPos(ImGuiViewport* vp, Vector2* outPos)
{
*outPos = new Vector2(0, 0);
if (!TryGetState(vp, out var state)) return;
// Return the CLIENT-area origin in screen coords, not the outer window
// rect. ImGui's hit-testing uses this as the viewport origin; if we
// include the title-bar height, every click misses by that offset.
POINT p = new POINT { X = 0, Y = 0 };
if (!ClientToScreen(state.Hwnd, ref p)) return;
*outPos = new Vector2(p.X, p.Y);
}
private static void ViewportGetSize(ImGuiViewport* vp, Vector2* outSize)
{
*outSize = new Vector2(0, 0);
if (!TryGetState(vp, out var state)) return;
if (!GetClientRect(state.Hwnd, out RECT r)) return;
*outSize = new Vector2(r.Right - r.Left, r.Bottom - r.Top);
}
private static void ViewportSetFocus(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return;
SetForegroundWindow(state.Hwnd);
}
private static byte ViewportGetFocus(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return 0;
return GetForegroundWindow() == state.Hwnd ? (byte)1 : (byte)0;
}
private static byte ViewportGetMinimized(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return 0;
return IsIconic(state.Hwnd) ? (byte)1 : (byte)0;
}
private static void ViewportSetTitle(ImGuiViewport* vp, IntPtr strPtr)
{
if (!TryGetState(vp, out var state)) return;
string title = Marshal.PtrToStringUTF8(strPtr) ?? "RynthCore Viewport";
SetWindowTextW(state.Hwnd, title);
}
private static void ViewportSetAlpha(ImGuiViewport* vp, float alpha)
{
if (!TryGetState(vp, out var state)) return;
IntPtr exStyle = GetWindowLongW(state.Hwnd, GWL_EXSTYLE);
long exs = (long)exStyle;
if (alpha < 1.0f)
SetWindowLongW(state.Hwnd, GWL_EXSTYLE, (IntPtr)(exs | WS_EX_LAYERED));
byte a = (byte)Math.Clamp((int)(alpha * 255f + 0.5f), 0, 255);
SetLayeredWindowAttributes(state.Hwnd, 0, a, LWA_ALPHA);
}
private static void ViewportUpdate(ImGuiViewport* vp)
{
// No-op on Win32 — imgui_impl_win32 handles monitor updates and other
// housekeeping elsewhere. We refresh monitors from EngineFrameController.
}
private static bool TryGetState(ImGuiViewport* vp, out ViewportState state)
{
return _viewports.TryGetValue((IntPtr)vp, out state!);
}
// ─── WndProc for viewport HWNDs ───────────────────────────────────────
internal static IntPtr ImGuiContext;
private static IntPtr ViewportWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
// If the ImGui context has been torn down (Shutdown already ran), don't
// touch any ImGui API — the context memory is freed and any call into it
// is a use-after-free. Just forward to the default handler.
if (ImGuiContext == IntPtr.Zero)
return DefWindowProcW(hWnd, msg, wParam, lParam);
// OS delivers messages (WM_GETICON, WM_PAINT, etc.) asynchronously outside
// of EndScene. By then our saved context has been restored → GImGui is null,
// and any ImGui call here AVs. Temporarily set our context for the message.
IntPtr saved = ImGuiNET.ImGui.GetCurrentContext();
if (saved != ImGuiContext)
ImGuiNET.ImGui.SetCurrentContext(ImGuiContext);
try
{
ImGuiViewportPtr vp = ImGuiNET.ImGui.FindViewportByPlatformHandle(hWnd);
if (vp.NativePtr == null)
return DefWindowProcW(hWnd, msg, wParam, lParam);
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
// ── Mouse position: forward in screen coords (multi-viewport) ────
if (msg == WM_MOUSEMOVE || msg == WM_LBUTTONDOWN || msg == WM_LBUTTONUP
|| msg == WM_LBUTTONDBLCLK || msg == WM_RBUTTONDOWN || msg == WM_RBUTTONUP
|| msg == WM_RBUTTONDBLCLK || msg == WM_MBUTTONDOWN || msg == WM_MBUTTONUP
|| msg == WM_MBUTTONDBLCLK || msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP)
{
short cx = (short)((long)lParam & 0xFFFF);
short cy = (short)(((long)lParam >> 16) & 0xFFFF);
POINT pt = new POINT { X = cx, Y = cy };
ClientToScreen(hWnd, ref pt);
io.AddMouseSourceEvent(ImGuiMouseSource.Mouse);
io.AddMousePosEvent(pt.X, pt.Y);
}
switch (msg)
{
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
if (SetCapture(hWnd) == IntPtr.Zero) { /* ignore */ }
io.AddMouseButtonEvent(0, true);
return IntPtr.Zero;
case WM_LBUTTONUP:
io.AddMouseButtonEvent(0, false);
ReleaseCapture();
return IntPtr.Zero;
case WM_RBUTTONDOWN:
case WM_RBUTTONDBLCLK:
SetCapture(hWnd);
io.AddMouseButtonEvent(1, true);
return IntPtr.Zero;
case WM_RBUTTONUP:
io.AddMouseButtonEvent(1, false);
ReleaseCapture();
return IntPtr.Zero;
case WM_MBUTTONDOWN:
case WM_MBUTTONDBLCLK:
SetCapture(hWnd);
io.AddMouseButtonEvent(2, true);
return IntPtr.Zero;
case WM_MBUTTONUP:
io.AddMouseButtonEvent(2, false);
ReleaseCapture();
return IntPtr.Zero;
case WM_XBUTTONDOWN:
{
int btn = (((int)(long)wParam >> 16) & 0xFFFF) == 1 ? 3 : 4;
SetCapture(hWnd);
io.AddMouseButtonEvent(btn, true);
return IntPtr.Zero;
}
case WM_XBUTTONUP:
{
int btn = (((int)(long)wParam >> 16) & 0xFFFF) == 1 ? 3 : 4;
io.AddMouseButtonEvent(btn, false);
ReleaseCapture();
return IntPtr.Zero;
}
case WM_MOUSEWHEEL:
io.AddMouseWheelEvent(0f, (short)(((long)wParam >> 16) & 0xFFFF) / 120f);
return IntPtr.Zero;
case WM_MOUSEHWHEEL:
io.AddMouseWheelEvent((short)(((long)wParam >> 16) & 0xFFFF) / 120f, 0f);
return IntPtr.Zero;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
{
ImGuiKey key = VkToImGuiKey((int)(long)wParam);
if (key != ImGuiKey.None) io.AddKeyEvent(key, true);
// Let DefWindowProc run so system keys still function (Alt+F4 etc.).
break;
}
case WM_KEYUP:
case WM_SYSKEYUP:
{
ImGuiKey key = VkToImGuiKey((int)(long)wParam);
if (key != ImGuiKey.None) io.AddKeyEvent(key, false);
break;
}
case WM_CHAR:
{
uint ch = (uint)(long)wParam;
if (ch > 0 && ch < 0x10000) io.AddInputCharacter(ch);
return IntPtr.Zero;
}
case WM_CLOSE:
vp.PlatformRequestClose = true;
return IntPtr.Zero;
case WM_MOVE:
vp.PlatformRequestMove = true;
break;
case WM_SIZE:
vp.PlatformRequestResize = true;
break;
case WM_MOUSEACTIVATE:
{
// If AC is the foreground app, don't steal its focus — just process the click.
// If the user is tabbed out (some other app is foreground), allow Windows to
// activate this viewport so the click actually brings it to the front.
IntPtr fg = GetForegroundWindow();
IntPtr game = Win32Backend.GameHwnd;
if (game != IntPtr.Zero && fg == game)
return new IntPtr(MA_NOACTIVATE);
break;
}
case WM_NCHITTEST:
{
uint flags = unchecked((uint)vp.Flags);
if ((flags & (uint)ImGuiViewportFlags.NoInputs) != 0)
return new IntPtr(-1 /*HTTRANSPARENT*/);
break;
}
}
}
catch (Exception ex)
{
RynthLog.Info($"ViewportPlatform.WndProc: {ex.GetType().Name}: {ex.Message}");
}
finally
{
if (ImGuiContext != IntPtr.Zero && saved != ImGuiContext)
ImGuiNET.ImGui.SetCurrentContext(saved);
}
return DefWindowProcW(hWnd, msg, wParam, lParam);
}
private static ImGuiKey VkToImGuiKey(int vk)
{
return vk switch
{
0x09 => ImGuiKey.Tab,
0x25 => ImGuiKey.LeftArrow,
0x27 => ImGuiKey.RightArrow,
0x26 => ImGuiKey.UpArrow,
0x28 => ImGuiKey.DownArrow,
0x21 => ImGuiKey.PageUp,
0x22 => ImGuiKey.PageDown,
0x24 => ImGuiKey.Home,
0x23 => ImGuiKey.End,
0x2D => ImGuiKey.Insert,
0x2E => ImGuiKey.Delete,
0x08 => ImGuiKey.Backspace,
0x20 => ImGuiKey.Space,
0x0D => ImGuiKey.Enter,
0x1B => ImGuiKey.Escape,
0xBE => ImGuiKey.Period,
0xBC => ImGuiKey.Comma,
0xBD => ImGuiKey.Minus,
0xBB => ImGuiKey.Equal,
0xBA => ImGuiKey.Semicolon,
0xBF => ImGuiKey.Slash,
0xC0 => ImGuiKey.GraveAccent,
0xDB => ImGuiKey.LeftBracket,
0xDC => ImGuiKey.Backslash,
0xDD => ImGuiKey.RightBracket,
0xDE => ImGuiKey.Apostrophe,
>= 0x30 and <= 0x39 => ImGuiKey._0 + (vk - 0x30),
>= 0x41 and <= 0x5A => ImGuiKey.A + (vk - 0x41),
>= 0x60 and <= 0x69 => ImGuiKey.Keypad0 + (vk - 0x60),
>= 0x70 and <= 0x7B => ImGuiKey.F1 + (vk - 0x70),
0x10 => ImGuiKey.LeftShift,
0x11 => ImGuiKey.LeftCtrl,
0x12 => ImGuiKey.LeftAlt,
_ => ImGuiKey.None,
};
}
}

View file

@ -1,200 +0,0 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportProbe.cs
// One-shot diagnostic run at startup. Determines the byte offsets of each
// ImGuiPlatformIO callback field in the running cimgui.dll, so that we can
// install Win32/DX9 platform callbacks by writing IntPtrs directly into
// the native struct (ImGui.NET exposes callback fields as get-only).
//
// Remove/gate this once offsets are documented and wired into a static table.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal static class ViewportProbe
{
// Every Platform_* and Renderer_* callback field ImGui.NET exposes.
// Probing strategy: write a unique sentinel at each 4-byte slot, read
// every getter, record which getter sees the sentinel, restore the slot.
private static readonly string[] FieldsToProbe =
{
"Platform_CreateWindow",
"Platform_DestroyWindow",
"Platform_ShowWindow",
"Platform_SetWindowPos",
"Platform_GetWindowPos",
"Platform_SetWindowSize",
"Platform_GetWindowSize",
"Platform_SetWindowFocus",
"Platform_GetWindowFocus",
"Platform_GetWindowMinimized",
"Platform_SetWindowTitle",
"Platform_SetWindowAlpha",
"Platform_UpdateWindow",
"Platform_RenderWindow",
"Platform_SwapBuffers",
"Platform_GetWindowDpiScale",
"Platform_OnChangedViewport",
"Platform_GetWindowWorkAreaInsets",
"Platform_CreateVkSurface",
"Renderer_CreateWindow",
"Renderer_DestroyWindow",
"Renderer_SetWindowSize",
"Renderer_RenderWindow",
"Renderer_SwapBuffers",
};
// ImGuiViewport fields worth locating so we know where ImGui.NET reads from
// vs the authoritative bytes. These are read-back tests — no writes.
private static readonly string[] ViewportFieldsToLog =
{
"ID",
"Flags",
"Pos",
"Size",
"WorkPos",
"WorkSize",
"DpiScale",
"ParentViewportId",
"DrawData",
"RendererUserData",
"PlatformUserData",
"PlatformHandle",
"PlatformHandleRaw",
"PlatformWindowCreated",
"PlatformRequestMove",
"PlatformRequestResize",
"PlatformRequestClose",
};
private const int ScanBytes = 768;
public static void Run()
{
try
{
RynthLog.Info("ViewportProbe: ---- begin ----");
RunPlatformIOProbe();
RunMainViewportDump();
RynthLog.Info("ViewportProbe: ---- end ----");
}
catch (Exception ex)
{
RynthLog.Info($"ViewportProbe: FAILED {ex.GetType().Name}: {ex.Message}");
}
}
private static unsafe void RunPlatformIOProbe()
{
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
IntPtr pioNative = (IntPtr)pio.NativePtr;
RynthLog.Info($"ViewportProbe: PlatformIO native = 0x{pioNative.ToInt64():X8}");
// Log what each getter returns BEFORE probing, so we can see the stock zero state.
var propertyCache = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
Type ptrType = typeof(ImGuiPlatformIOPtr);
foreach (string name in FieldsToProbe)
{
PropertyInfo? prop = ptrType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
bool intptrLike = prop != null && (
prop.PropertyType == typeof(IntPtr) ||
(prop.PropertyType.IsByRef && prop.PropertyType.GetElementType() == typeof(IntPtr)));
if (intptrLike)
{
propertyCache[name] = prop!;
}
else
{
RynthLog.Info($"ViewportProbe: {name}: NOT FOUND on ImGuiPlatformIOPtr (type={prop?.PropertyType.Name ?? "null"})");
}
}
var discovered = new Dictionary<string, int>(StringComparer.Ordinal);
for (int off = 0; off < ScanBytes; off += 4)
{
IntPtr orig = Marshal.ReadIntPtr(pioNative, off);
IntPtr sentinel = new IntPtr(unchecked((int)0xAB000000) | off);
Marshal.WriteIntPtr(pioNative, off, sentinel);
foreach (var kv in propertyCache)
{
IntPtr read;
try
{
read = (IntPtr)kv.Value.GetValue(pio)!;
}
catch
{
continue;
}
if (read == sentinel && !discovered.ContainsKey(kv.Key))
{
discovered[kv.Key] = off;
}
}
Marshal.WriteIntPtr(pioNative, off, orig);
}
// Emit in ascending offset order so the mapping is obvious in the log.
var sorted = new List<KeyValuePair<string, int>>(discovered);
sorted.Sort((a, b) => a.Value.CompareTo(b.Value));
RynthLog.Info($"ViewportProbe: discovered {sorted.Count}/{propertyCache.Count} offsets:");
foreach (var kv in sorted)
RynthLog.Info($"ViewportProbe: +{kv.Value,4} {kv.Key}");
foreach (string name in FieldsToProbe)
{
if (propertyCache.ContainsKey(name) && !discovered.ContainsKey(name))
RynthLog.Info($"ViewportProbe: MISSING {name} (getter exists but sentinel never matched)");
}
// Hex dump of the first chunk so we can visually scan for anomalies.
DumpRange(pioNative, 0, 256, "PlatformIO");
}
private static unsafe void RunMainViewportDump()
{
ImGuiViewportPtr main = ImGuiNET.ImGui.GetMainViewport();
IntPtr vp = (IntPtr)main.NativePtr;
RynthLog.Info($"ViewportProbe: MainViewport native = 0x{vp.ToInt64():X8}");
Type vptrType = typeof(ImGuiViewportPtr);
foreach (string name in ViewportFieldsToLog)
{
PropertyInfo? prop = vptrType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
if (prop == null)
{
RynthLog.Info($"ViewportProbe: MainViewport.{name}: (no such property)");
continue;
}
object? val;
try { val = prop.GetValue(main); }
catch (Exception ex) { val = $"<throw {ex.GetType().Name}>"; continue; }
RynthLog.Info($"ViewportProbe: MainViewport.{name} ({prop.PropertyType.Name}) = {val}");
}
DumpRange(vp, 0, 160, "MainViewport");
}
private static void DumpRange(IntPtr basePtr, int startOffset, int length, string label)
{
for (int off = startOffset; off < startOffset + length; off += 16)
{
uint w0 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 0));
uint w1 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 4));
uint w2 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 8));
uint w3 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 12));
RynthLog.Info($"ViewportProbe: {label} +{off,4} {w0:X8} {w1:X8} {w2:X8} {w3:X8}");
}
}
}

View file

@ -1,367 +0,0 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportRendererBackend.cs
// Per-viewport D3D9 renderer backend for ImGui multi-viewport.
// Installs Renderer_* callbacks on ImGuiPlatformIO: for each viewport we
// create an additional swap chain on the game's device, render the viewport's
// ImDrawData into that swap chain's back buffer, and Present it so the
// viewport's OS window displays the ImGui content.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.D3D9;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ViewportRendererBackend
{
// ─── D3D9 constants ───────────────────────────────────────────────
private const uint D3DFMT_UNKNOWN = 0;
private const uint D3DFMT_A8R8G8B8 = 21;
private const uint D3DFMT_X8R8G8B8 = 22;
private const uint D3DSWAPEFFECT_DISCARD = 1;
private const uint D3DBACKBUFFER_TYPE_MONO = 0;
private const uint D3DCLEAR_TARGET = 0x00000001;
private const uint D3DPRESENT_INTERVAL_IMMEDIATE = 0x80000000;
[StructLayout(LayoutKind.Sequential)]
private struct D3DPRESENT_PARAMETERS
{
public uint BackBufferWidth;
public uint BackBufferHeight;
public uint BackBufferFormat;
public uint BackBufferCount;
public uint MultiSampleType;
public uint MultiSampleQuality;
public uint SwapEffect;
public IntPtr hDeviceWindow;
public int Windowed; // BOOL
public int EnableAutoDepthStencil; // BOOL
public uint AutoDepthStencilFormat;
public uint Flags;
public uint FullScreen_RefreshRateInHz;
public uint PresentationInterval;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int L, T, R, B; }
// ─── Device method delegates ──────────────────────────────────────
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateAdditionalSwapChainD(IntPtr pDevice, D3DPRESENT_PARAMETERS* pp, out IntPtr ppSwapChain);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetRenderTargetD(IntPtr pDevice, uint rtIndex, IntPtr pSurface);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetRenderTargetD(IntPtr pDevice, uint rtIndex, out IntPtr ppSurface);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int ClearD(IntPtr pDevice, uint count, RECT* pRects, uint flags, uint color, float z, uint stencil);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseD(IntPtr pObj);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SwapChainGetBackBufferD(IntPtr pSwapChain, uint backBufIdx, uint type, out IntPtr ppBackBuffer);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SwapChainPresentD(IntPtr pSwapChain, RECT* src, RECT* dest, IntPtr hDestWnd, IntPtr dirtyRgn, uint flags);
// ─── Callback delegates (must match imgui types) ──────────────────
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportCallbackD(ImGuiViewport* vp);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSizeCallbackD(ImGuiViewport* vp, System.Numerics.Vector2 size);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportRenderD(ImGuiViewport* vp, IntPtr renderArg);
// ─── State ────────────────────────────────────────────────────────
private sealed class ViewportGpuState
{
public IntPtr SwapChain;
public int Width;
public int Height;
}
private static IntPtr _device;
private static CreateAdditionalSwapChainD? _createAdditionalSwapChain;
private static SetRenderTargetD? _setRenderTarget;
private static GetRenderTargetD? _getRenderTarget;
private static ClearD? _clear;
private static readonly Dictionary<IntPtr, ViewportGpuState> _viewports = new();
private static readonly List<Delegate> _delegateRoots = new();
private static bool _initialized;
// Diagnostic one-shot logging counters — limited to a few calls so log doesn't explode.
private static int _logCreate;
private static int _logRender;
private static int _logSwap;
private const int MaxLog = 3;
public static bool Init(IntPtr pDevice)
{
if (_initialized) return true;
if (pDevice == IntPtr.Zero)
{
RynthLog.Info("ViewportRenderer: Init called with null device.");
return false;
}
_device = pDevice;
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
_createAdditionalSwapChain = GetMethod<CreateAdditionalSwapChainD>(vtable, DeviceVTableIndex.CreateAdditionalSwapChain);
_setRenderTarget = GetMethod<SetRenderTargetD>(vtable, DeviceVTableIndex.SetRenderTarget);
_getRenderTarget = GetMethod<GetRenderTargetD>(vtable, DeviceVTableIndex.GetRenderTarget);
_clear = GetMethod<ClearD>(vtable, DeviceVTableIndex.Clear);
InstallCallbacks();
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports;
_initialized = true;
RynthLog.Info("ViewportRenderer: initialized.");
return true;
}
public static void Shutdown()
{
foreach (var kv in _viewports)
{
if (kv.Value.SwapChain != IntPtr.Zero)
ReleaseCom(kv.Value.SwapChain);
}
_viewports.Clear();
_delegateRoots.Clear();
_initialized = false;
}
private static void InstallCallbacks()
{
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
IntPtr pioNative = (IntPtr)pio.NativePtr;
ViewportCallbackD createFn = RendererCreateWindow;
ViewportCallbackD destroyFn = RendererDestroyWindow;
ViewportSizeCallbackD setSizeFn = RendererSetWindowSize;
ViewportRenderD renderFn = RendererRenderWindow;
ViewportRenderD swapFn = RendererSwapBuffers;
_delegateRoots.Add(createFn);
_delegateRoots.Add(destroyFn);
_delegateRoots.Add(setSizeFn);
_delegateRoots.Add(renderFn);
_delegateRoots.Add(swapFn);
IntPtr createPtr = Marshal.GetFunctionPointerForDelegate(createFn);
IntPtr destroyPtr = Marshal.GetFunctionPointerForDelegate(destroyFn);
IntPtr setSizePtr = Marshal.GetFunctionPointerForDelegate(setSizeFn);
IntPtr renderPtr = Marshal.GetFunctionPointerForDelegate(renderFn);
IntPtr swapPtr = Marshal.GetFunctionPointerForDelegate(swapFn);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererCreateWindow, createPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererDestroyWindow, destroyPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererSetWindowSize, setSizePtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererRenderWindow, renderPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererSwapBuffers, swapPtr);
IntPtr verify = Marshal.ReadIntPtr(pioNative, ViewportOffsets.RendererRenderWindow);
RynthLog.Info($"ViewportRenderer: installed handlers (RenderWindow readback=0x{verify.ToInt64():X8}, expected=0x{renderPtr.ToInt64():X8})");
}
// ─── Callback implementations ─────────────────────────────────────
private static void RendererCreateWindow(ImGuiViewport* vp)
{
IntPtr key = (IntPtr)vp;
if (_viewports.ContainsKey(key)) return;
var state = new ViewportGpuState();
_viewports[key] = state;
int w = Math.Max(1, (int)vp->Size.X);
int h = Math.Max(1, (int)vp->Size.Y);
CreateSwapChainForViewport(vp, state, w, h);
if (_logCreate++ < MaxLog)
{
IntPtr hwnd = (IntPtr)vp->PlatformHandleRaw;
if (hwnd == IntPtr.Zero) hwnd = (IntPtr)vp->PlatformHandle;
RynthLog.Info($"ViewportRenderer: CreateWindow vp=0x{key.ToInt64():X8} hwnd=0x{hwnd.ToInt64():X8} size={w}x{h} swapChain=0x{state.SwapChain.ToInt64():X8}");
}
}
private static void RendererDestroyWindow(ImGuiViewport* vp)
{
IntPtr key = (IntPtr)vp;
if (!_viewports.TryGetValue(key, out var state)) return;
if (state.SwapChain != IntPtr.Zero)
{
ReleaseCom(state.SwapChain);
state.SwapChain = IntPtr.Zero;
}
_viewports.Remove(key);
}
private static void RendererSetWindowSize(ImGuiViewport* vp, System.Numerics.Vector2 size)
{
IntPtr key = (IntPtr)vp;
if (!_viewports.TryGetValue(key, out var state)) return;
int w = Math.Max(1, (int)size.X);
int h = Math.Max(1, (int)size.Y);
if (w == state.Width && h == state.Height) return;
if (state.SwapChain != IntPtr.Zero)
{
ReleaseCom(state.SwapChain);
state.SwapChain = IntPtr.Zero;
}
CreateSwapChainForViewport(vp, state, w, h);
}
private static void RendererRenderWindow(ImGuiViewport* vp, IntPtr renderArg)
{
IntPtr key = (IntPtr)vp;
bool diag = _logRender < MaxLog;
if (!_viewports.TryGetValue(key, out var state))
{
if (diag) { RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} NO STATE"); _logRender++; }
return;
}
if (state.SwapChain == IntPtr.Zero)
{
if (diag) { RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} NO SWAPCHAIN"); _logRender++; }
return;
}
if (_setRenderTarget == null || _getRenderTarget == null || _clear == null)
{
if (diag) { RynthLog.Info("ViewportRenderer: RenderWindow device methods null"); _logRender++; }
return;
}
// Get the swap chain's back-buffer surface
var getBB = GetMethodFromObj<SwapChainGetBackBufferD>(state.SwapChain, SwapChain9VTableIndex.GetBackBuffer);
int hrBB = getBB(state.SwapChain, 0, D3DBACKBUFFER_TYPE_MONO, out IntPtr backBuffer);
if (hrBB < 0 || backBuffer == IntPtr.Zero)
{
if (diag) { RynthLog.Info($"ViewportRenderer: GetBackBuffer failed hr=0x{hrBB:X8}"); _logRender++; }
return;
}
IntPtr oldRenderTarget = IntPtr.Zero;
int cmdCount = 0;
float ddW = 0, ddH = 0, ddX = 0, ddY = 0;
try
{
_getRenderTarget(_device, 0, out oldRenderTarget);
int hrSRT = _setRenderTarget(_device, 0, backBuffer);
// Clear unless the ImGui viewport asked us not to.
uint flags = unchecked((uint)vp->Flags);
if ((flags & (uint)ImGuiViewportFlags.NoRendererClear) == 0)
{
_clear(_device, 0, null, D3DCLEAR_TARGET, 0x00000000u, 1.0f, 0);
}
// Render the viewport's own draw data through the main DX9 backend,
// which already handles full state save/restore.
ImDrawDataPtr draw = new ImDrawDataPtr((ImDrawData*)vp->DrawData);
if ((IntPtr)draw.NativePtr != IntPtr.Zero)
{
IntPtr dd = (IntPtr)draw.NativePtr;
cmdCount = Marshal.ReadInt32(dd, 4);
ddX = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 20));
ddY = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 24));
ddW = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 28));
ddH = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 32));
DX9Backend.RenderDrawData(draw, _device);
}
if (diag)
{
RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} setRT=0x{hrSRT:X8} bb=0x{backBuffer.ToInt64():X8} cmds={cmdCount} ddPos=({ddX},{ddY}) ddSize=({ddW},{ddH})");
_logRender++;
}
}
finally
{
if (oldRenderTarget != IntPtr.Zero)
{
_setRenderTarget(_device, 0, oldRenderTarget);
ReleaseCom(oldRenderTarget);
}
ReleaseCom(backBuffer);
}
}
private static void RendererSwapBuffers(ImGuiViewport* vp, IntPtr renderArg)
{
IntPtr key = (IntPtr)vp;
if (!_viewports.TryGetValue(key, out var state)) return;
if (state.SwapChain == IntPtr.Zero) return;
var present = GetMethodFromObj<SwapChainPresentD>(state.SwapChain, SwapChain9VTableIndex.Present);
int hr = present(state.SwapChain, null, null, IntPtr.Zero, IntPtr.Zero, 0);
if (_logSwap++ < MaxLog)
RynthLog.Info($"ViewportRenderer: SwapBuffers vp=0x{key.ToInt64():X8} Present hr=0x{hr:X8}");
}
// ─── Helpers ──────────────────────────────────────────────────────
private static void CreateSwapChainForViewport(ImGuiViewport* vp, ViewportGpuState state, int w, int h)
{
if (_createAdditionalSwapChain == null) return;
IntPtr hwnd = (IntPtr)vp->PlatformHandleRaw;
if (hwnd == IntPtr.Zero) hwnd = (IntPtr)vp->PlatformHandle;
if (hwnd == IntPtr.Zero)
{
RynthLog.Info("ViewportRenderer: viewport has no HWND — cannot create swap chain.");
return;
}
var pp = new D3DPRESENT_PARAMETERS
{
BackBufferWidth = (uint)w,
BackBufferHeight = (uint)h,
BackBufferFormat = D3DFMT_UNKNOWN, // match device default
BackBufferCount = 1,
SwapEffect = D3DSWAPEFFECT_DISCARD,
hDeviceWindow = hwnd,
Windowed = 1,
// Don't wait for vblank — each popped viewport adds another Present
// per frame, and stacking vsyncs cuts the effective frame rate.
PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE,
};
int hr = _createAdditionalSwapChain(_device, &pp, out IntPtr swapChain);
if (hr < 0 || swapChain == IntPtr.Zero)
{
RynthLog.Info($"ViewportRenderer: CreateAdditionalSwapChain failed (hr=0x{hr:X8}) for {w}x{h} hwnd=0x{hwnd:X}");
return;
}
state.SwapChain = swapChain;
state.Width = w;
state.Height = h;
}
private static T GetMethod<T>(IntPtr vtable, int index) where T : Delegate
{
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(addr);
}
private static T GetMethodFromObj<T>(IntPtr pObj, int index) where T : Delegate
{
IntPtr vtable = Marshal.ReadIntPtr(pObj);
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(addr);
}
private static void ReleaseCom(IntPtr pObj)
{
if (pObj == IntPtr.Zero) return;
IntPtr vtable = Marshal.ReadIntPtr(pObj);
IntPtr addr = Marshal.ReadIntPtr(vtable, 2 * IntPtr.Size); // Release is index 2
var release = Marshal.GetDelegateForFunctionPointer<ReleaseD>(addr);
release(pObj);
}
}

View file

@ -6,6 +6,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using ImGuiNET;
@ -41,6 +42,15 @@ internal static unsafe class Win32Backend
private const uint WM_SETCURSOR = 0x0020;
private const uint WM_XBUTTONDOWN = 0x020B;
private const uint WM_XBUTTONUP = 0x020C;
private const uint WM_LBUTTONDBLCLK = 0x0203;
private const uint WM_RBUTTONDBLCLK = 0x0206;
private const uint WM_MBUTTONDBLCLK = 0x0209;
// MK_* button bits (WM_MOUSEMOVE wParam)
private const int MK_LBUTTON = 0x0001;
private const int MK_RBUTTON = 0x0002;
private const int MK_MBUTTON = 0x0010;
private const int MK_XBUTTON1 = 0x0020;
private const int MK_XBUTTON2 = 0x0040;
private const uint WM_CLOSE = 0x0010;
// Set on the first WM_CLOSE so we kick off the engine teardown exactly
@ -84,6 +94,24 @@ internal static unsafe class Win32Backend
/// load left behind (posted by Init). See LayeredWindow.DestroyThreadPanelWindows.</summary>
public const uint WM_RYNTH_SWEEP_PANELS = 0x8004;
/// <summary>Posted by <see cref="PostToGameThread"/>: runs the queued actions on
/// the game thread without the caller waiting (pop-out windows are created this
/// way from inside EndScene, where creating an HWND inline is not safe).</summary>
public const uint WM_RYNTH_POST_ACTION = 0x8005;
private static readonly System.Collections.Concurrent.ConcurrentQueue<Action> _postedActions = new();
/// <summary>
/// Queues <paramref name="action"/> to run on the game thread from the game
/// WndProc, and returns at once. Any thread. False when there is no game window.
/// </summary>
public static bool PostToGameThread(Action action)
{
if (_gameHwnd == IntPtr.Zero) return false;
_postedActions.Enqueue(action);
return PostMessage(_gameHwnd, WM_RYNTH_POST_ACTION, IntPtr.Zero, IntPtr.Zero);
}
private const int VK_CONTROL = 0x11;
private const int VK_SHIFT = 0x10;
private const int VK_MENU = 0x12; // Alt
@ -133,9 +161,6 @@ internal static unsafe class Win32Backend
[DllImport("user32.dll")]
private static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll")]
private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll")]
private static extern bool GetCursorPos(out POINT lpPoint);
@ -260,6 +285,9 @@ internal static unsafe class Win32Backend
/// <summary>The game's main window handle.</summary>
public static IntPtr GameHwnd => _gameHwnd;
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
/// <summary>
/// Populate <see cref="GameHwnd"/> from outside the ImGui Init path.
/// Used by Avalonia-only overlay mode where ImGui is disabled but Avalonia
@ -406,6 +434,32 @@ internal static unsafe class Win32Backend
private static readonly Queue<QueuedInputMessage> _pendingInput = new();
private static volatile bool _wantCaptureMouse;
private static volatile bool _wantCaptureKeyboard;
/// <summary>
/// True while the game window eats mouse input for the ImGui layer: the capture
/// flag the last ImGui frame published (Insert toggle and focus applied). Read
/// during the next frame, it says whether a click that arrived in between went
/// to ImGui (true) or to AC (false). AC thread.
/// </summary>
public static bool MouseCaptured => _wantCaptureMouse;
/// <summary>Stopwatch timestamp of the last ImGui frame that published capture
/// flags. The WndProc ignores (and clears) flags older than CaptureStaleMs, so a
/// frame that stops running (minimized, device lost, detour disabled during RL)
/// can't leave input being eaten with nothing drawn.</summary>
private static long _captureFlagsTicks;
private const int CaptureStaleMs = 250;
/// <summary>Mouse buttons currently held, as MK_* bits, observed on every mouse message.</summary>
private static int _heldMouseButtons;
/// <summary>True when the press that started the current held-button run was not
/// ImGui's (the cursor was not over an ImGui window). Until every button is
/// released, ImGui eats none of the mouse traffic: an RMB camera drag that
/// crosses an ImGui window keeps its moves and its RBUTTONUP.</summary>
private static bool _heldButtonsBelongToGame;
/// <summary>io.WantTextInput from the last ImGui frame: an ImGui text box is
/// being typed in. Vetoes chat Enter-capture the way AvaloniaTextInputActive
/// does for Avalonia TextBoxes.</summary>
public static volatile bool ImGuiTextInputActive;
private static bool _hasMouseCapture;
private static bool _uiCaptureEnabled;
private static bool _hasFocus;
@ -501,7 +555,13 @@ internal static unsafe class Win32Backend
_wndProcDelegate = WndProcHook;
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate);
_installedWndProcPtr = hookPtr;
_originalWndProc = SetWindowLong32(hWnd, GWL_WNDPROC, hookPtr);
// Under the native loader the window keeps the loader's permanent subclass
// (installed once per process); this generation only plugs its handler in.
_viaLoaderSubclass = Hooking.LoaderServices.Available;
if (_viaLoaderSubclass)
_originalWndProc = Hooking.LoaderServices.SubclassInstall(hWnd, hookPtr, out IntPtr previous) ? previous : IntPtr.Zero;
else
_originalWndProc = SetWindowLong32(hWnd, GWL_WNDPROC, hookPtr);
// RynthLog.UI (not .Render — RenderEnabled is false) so chain
// composition across generations is reconstructible from the log.
RynthLog.UI($"Win32Backend: subclass installed — hook=0x{hookPtr:X8}, previous WndProc=0x{_originalWndProc:X8}.");
@ -526,6 +586,7 @@ internal static unsafe class Win32Backend
private static IntPtr _installedWndProcPtr;
private static volatile bool _forwardOnly;
private static bool _viaLoaderSubclass;
public static void Shutdown()
{
@ -551,7 +612,14 @@ internal static unsafe class Win32Backend
// valid because engine module pages are intentionally leaked across
// reloads, and a no-longer-initialized backend just forwards.
IntPtr currentProc = GetWindowLong32(_gameHwnd, GWL_WNDPROC);
if (currentProc == _installedWndProcPtr || currentProc == IntPtr.Zero)
if (_viaLoaderSubclass)
{
// The loader's subclass stays in the chain for good and now passes every
// message straight through: nothing points at this generation any more.
Hooking.LoaderServices.SubclassRelease(_gameHwnd);
RynthLog.UI("Win32Backend: Shutdown — handler removed from the loader's subclass (pass-through).");
}
else if (currentProc == _installedWndProcPtr || currentProc == IntPtr.Zero)
{
SetWindowLong32(_gameHwnd, GWL_WNDPROC, _originalWndProc);
RynthLog.UI("Win32Backend: Shutdown — WndProc restored (we were chain head).");
@ -604,43 +672,43 @@ internal static unsafe class Win32Backend
private static int _newFrameLogCount;
public static void NewFrame()
/// <summary>
/// Reads the game client size and publishes it to the Avalonia overlay.
/// Runs every frame while the ImGui backend is enabled, including frames
/// where no ImGui window is open and NewFrame is skipped.
/// </summary>
public static void UpdateClientMetrics(out int width, out int height)
{
// Deferred focus restore: AvaloniaSubclassWndProc sets this flag when
// WM_SETFOCUS lands on the off-screen Avalonia HWND. We reclaim focus
// here (game thread owns _gameHwnd) so there's no cross-thread wait.
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
// Update display size
GetClientRect(_gameHwnd, out RECT rect);
int w = rect.Right - rect.Left;
int h = rect.Bottom - rect.Top;
width = rect.Right - rect.Left;
height = rect.Bottom - rect.Top;
_newFrameLogCount++;
AvaloniaOverlay.ClientPixelWidth = w;
AvaloniaOverlay.ClientPixelHeight = h;
if ((_lastKnownClientWidth != w || _lastKnownClientHeight != h) && w > 1 && h > 1)
AvaloniaOverlay.ClientPixelWidth = width;
AvaloniaOverlay.ClientPixelHeight = height;
if ((_lastKnownClientWidth != width || _lastKnownClientHeight != height) && width > 1 && height > 1)
{
_lastKnownClientWidth = w;
_lastKnownClientHeight = h;
_lastKnownClientWidth = width;
_lastKnownClientHeight = height;
AvaloniaOverlay.NotifyGameSurfaceMetricsChanged();
AvaloniaOverlay.RequestCapture();
}
}
public static void NewFrame(int clientWidth, int clientHeight)
{
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
_newFrameLogCount++;
// If GetClientRect returns 0x0 or 1x1, the HWND might be wrong.
// DisplaySize will be set from D3D viewport in EngineFrameController instead.
if (w > 1 && h > 1)
io.DisplaySize = new System.Numerics.Vector2(w, h);
if (clientWidth > 1 && clientHeight > 1)
io.DisplaySize = new System.Numerics.Vector2(clientWidth, clientHeight);
FlushQueuedInput(io);
// Refresh the cursor position. With ViewportsEnable, ImGui expects
// absolute screen coords so it can route clicks to the correct viewport.
// Without it, client-relative coords are the simpler contract.
// Refresh the cursor position (client-relative; multi-viewport is not used).
GetCursorPos(out POINT cursorPos);
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) == 0)
ScreenToClient(_gameHwnd, ref cursorPos);
ScreenToClient(_gameHwnd, ref cursorPos);
io.AddMousePosEvent(cursorPos.X, cursorPos.Y);
SyncFocusState(io);
@ -697,7 +765,13 @@ internal static unsafe class Win32Backend
// CreateWindowExW etc. aren't stuck behind unrelated input handling.
if (msg == WM_RYNTH_RUN_ACTION)
{
Action? a = _pendingGameThreadAction;
// Take the action once. A send that timed out is still delivered
// later; without the take, that late delivery ran whatever action
// was pending by then and the action's own send ran it again
// (two LayeredWindows for one popout, one of them orphaned).
#pragma warning disable CS0420 // Interlocked access to a volatile field is still atomic.
Action? a = Interlocked.Exchange(ref _pendingGameThreadAction, null);
#pragma warning restore CS0420
if (a != null)
{
try { a(); }
@ -706,6 +780,16 @@ internal static unsafe class Win32Backend
return IntPtr.Zero;
}
if (msg == WM_RYNTH_POST_ACTION)
{
while (_postedActions.TryDequeue(out Action? posted))
{
try { posted(); }
catch (Exception ex) { RynthLog.Info($"Win32Backend: posted action threw {ex.GetType().Name}: {ex.Message}"); }
}
return IntPtr.Zero;
}
if (msg == WM_RYNTH_DESTROY_HWND)
{
IntPtr target = wParam;
@ -714,6 +798,11 @@ internal static unsafe class Win32Backend
bool destroyed = DestroyWindow(target);
int err = destroyed ? 0 : Marshal.GetLastWin32Error();
RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND DestroyWindow(0x{target.ToInt64():X}) = {destroyed} err={err}.");
// 5 = ACCESS_DENIED: the window belongs to another thread. At least
// take it off the screen so a closed panel can't linger beside a
// reopened one (ShowWindow works across threads).
if (!destroyed && err == 5)
ShowWindow(target, 0 /* SW_HIDE */);
}
catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND threw {ex.GetType().Name}: {ex.Message}"); }
return IntPtr.Zero;
@ -883,7 +972,10 @@ internal static unsafe class Win32Backend
// RynthChatOwnsChat: only while RynthChat is open AND hiding the retail chatbox —
// whichever chat is visible gets Enter. Otherwise Enter belongs to AC's own chat,
// which used to be unusable whenever RynthChat was installed, even closed.
// !ImGuiTextInputActive: the same rule for an ImGui text box.
ExpireStaleCaptureFlags();
if (msg == WM_KEYDOWN && (int)wParam == VK_RETURN && !IsExtendedKey(lParam) && !ChatCaptureActive && !AvaloniaTextInputActive
&& !ImGuiTextInputActive
&& RynthCore.Engine.Compatibility.ChatHooks.RynthChatOwnsChat)
{
if (OnChatCaptureActivated != null)
@ -916,8 +1008,13 @@ internal static unsafe class Win32Backend
// the ImGui EnqueueInput/capture-eat below so ImGui never tracks the
// HUD drag (keeps our SetCapture from fighting NewFrame's). No-op
// unless the HUD is drawn.
if (IsMouseMessage(msg) && VitalHud.TryHandleMouse(hWnd, msg, wParam, lParam))
return IntPtr.Zero;
if (IsMouseMessage(msg))
TrackMouseButtons(msg, wParam);
else if (msg == WM_KILLFOCUS)
{
_heldMouseButtons = 0;
_heldButtonsBelongToGame = false;
}
// ── Avalonia panel hit-test & input forwarding ────────────────
// Only in the world: between characters the overlay isn't drawn, so its
@ -959,17 +1056,33 @@ internal static unsafe class Win32Backend
}
// ─────────────────────────────────────────────────────────────
// A popped-out ImGui panel is typing (its window never has focus, so its keys
// arrive here), or the wheel turned over one: the pop-out gets it. A click
// on the game ends a pop-out's text edit (ImGuiPopOuts.RouteInput).
if (ImGuiPopOuts.RouteInput(msg, wParam, lParam))
{
// Key-ups still reach the game: a key held before the text edit
// began must be released there (the "keeps moving" rule below).
if (msg == WM_KEYUP || msg == WM_SYSKEYUP)
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
return IntPtr.Zero;
}
// Only enqueue if we did NOT already forward to Avalonia above.
// (When AvaloniaTextInputActive is true and a key fires, we returned early.)
if (IsMouseMessage(msg) || IsKeyMessage(msg) || IsFocusMessage(msg))
EnqueueInput(msg, wParam, lParam);
// If ImGui wants mouse input, eat mouse messages so the game doesn't get them
if (_wantCaptureMouse && IsMouseMessage(msg))
// ImGui wants the mouse (io.WantCaptureMouse): eat it, unless the held
// buttons were pressed for the game (see _heldButtonsBelongToGame).
if (_wantCaptureMouse && IsMouseMessage(msg) && !_heldButtonsBelongToGame)
return IntPtr.Zero;
// If ImGui wants keyboard input, eat keyboard messages
if (_wantCaptureKeyboard && IsKeyMessage(msg))
// An ImGui text box is being typed in (io.WantTextInput): keep keys from
// the game, except key-ups. A key held before the click must still get
// its release, or AC's edge-triggered input stays latched (the "character
// keeps moving" bug); a stray key-up reaching AC is harmless.
if (_wantCaptureKeyboard && IsKeyMessage(msg) && msg != WM_KEYUP && msg != WM_SYSKEYUP)
return IntPtr.Zero;
// ── Background FPS unlock: lie to AC so it never idle-throttles ──
@ -1069,7 +1182,7 @@ internal static unsafe class Win32Backend
AvaloniaOverlay.TryGetBarButtonTitleAt(releasePoint.X, releasePoint.Y, out string? releasedButtonTitle) &&
string.Equals(_pendingBarButtonTitle, releasedButtonTitle, StringComparison.OrdinalIgnoreCase))
{
AvaloniaOverlay.ActivateBarButton(releasedButtonTitle!);
PanelRouter.Toggle(releasedButtonTitle!);
}
// Persist bar position on drag-end. All the live moves were
@ -1204,7 +1317,7 @@ internal static unsafe class Win32Backend
if (!string.IsNullOrEmpty(_pendingBarButtonTitle) &&
string.Equals(_pendingBarButtonTitle, barButtonTitle, StringComparison.OrdinalIgnoreCase))
{
AvaloniaOverlay.ActivateBarButton(barButtonTitle!);
PanelRouter.Toggle(barButtonTitle!);
}
_avIsButtonCapture = false;
@ -1307,7 +1420,7 @@ internal static unsafe class Win32Backend
return false;
}
private static ImGuiKey VkToImGuiKey(int vk)
internal static ImGuiKey VkToImGuiKey(int vk)
{
return vk switch
{
@ -1382,16 +1495,7 @@ internal static unsafe class Win32Backend
{
short x = (short)((long)lParam & 0xFFFF);
short y = (short)(((long)lParam >> 16) & 0xFFFF);
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
POINT p = new POINT { X = x, Y = y };
ClientToScreen(_gameHwnd, ref p);
io.AddMousePosEvent(p.X, p.Y);
}
else
{
io.AddMousePosEvent(x, y);
}
io.AddMousePosEvent(x, y);
}
private static void UpdateMouseButton(ImGuiIOPtr io, int buttonIndex, int virtualKey)
@ -1400,13 +1504,102 @@ internal static unsafe class Win32Backend
SetMouseButtonState(io, buttonIndex, isDown);
}
public static void UpdateCaptureFlags(bool wantMouse, bool wantKeyboard)
/// <summary>
/// Publishes what the ImGui frame just built wants: <paramref name="wantMouse"/>
/// is io.WantCaptureMouse, <paramref name="wantTextInput"/> io.WantTextInput.
/// Keyboard capture follows text input only (not IsAnyItemActive), so holding
/// a slider never swallows game keys. The Insert toggle (_uiCaptureEnabled)
/// and game focus gate both.
/// </summary>
public static void UpdateCaptureFlags(bool wantMouse, bool wantTextInput)
{
// ImGui.NET's WantCaptureMouse/WantCaptureKeyboard read from wrong native
// offsets (struct layout mismatch, same class of bug as ImDrawCmd stride).
// Use _uiCaptureEnabled directly — Insert key gives user explicit control.
_wantCaptureMouse = _uiCaptureEnabled && _hasFocus && wantMouse;
_wantCaptureKeyboard = _uiCaptureEnabled && _hasFocus && wantKeyboard;
bool live = _uiCaptureEnabled && _hasFocus;
_wantCaptureMouse = live && wantMouse;
_wantCaptureKeyboard = live && wantTextInput;
ImGuiTextInputActive = live && wantTextInput;
Volatile.Write(ref _captureFlagsTicks, Stopwatch.GetTimestamp());
}
public static string DescribeCapture() =>
$"wantMouse={_wantCaptureMouse} wantText={_wantCaptureKeyboard} insertToggle={_uiCaptureEnabled} focus={_hasFocus} heldButtons=0x{_heldMouseButtons:X} heldForGame={_heldButtonsBelongToGame}";
/// <summary>No ImGui frame this tick: ImGui wants nothing.</summary>
public static void ClearCaptureFlags()
{
_wantCaptureMouse = false;
_wantCaptureKeyboard = false;
ImGuiTextInputActive = false;
}
/// <summary>Clears capture flags that no ImGui frame has refreshed recently.</summary>
private static void ExpireStaleCaptureFlags()
{
if (!_wantCaptureMouse && !_wantCaptureKeyboard && !ImGuiTextInputActive)
return;
long age = Stopwatch.GetTimestamp() - Volatile.Read(ref _captureFlagsTicks);
if (age > Stopwatch.Frequency * CaptureStaleMs / 1000)
ClearCaptureFlags();
}
/// <summary>
/// Drops queued input while no ImGui frame runs (nothing would drain it) and
/// resets ImGui's key/button state so a key or button released while idle
/// doesn't read as held when frames resume. AC thread, ImGui context current.
/// </summary>
public static void DiscardQueuedInput()
{
lock (_inputLock)
_pendingInput.Clear();
}
public static void ResetImGuiInputState(ImGuiIOPtr io)
{
for (int i = 0; i < _mouseButtons.Length; i++)
SetMouseButtonState(io, i, false);
io.ClearInputKeys();
}
/// <summary>MK_* bit for a button message's button (0 for non-button messages).</summary>
private static int MouseButtonBit(uint msg, IntPtr wParam) => msg switch
{
WM_LBUTTONDOWN or WM_LBUTTONUP or WM_LBUTTONDBLCLK => MK_LBUTTON,
WM_RBUTTONDOWN or WM_RBUTTONUP or WM_RBUTTONDBLCLK => MK_RBUTTON,
WM_MBUTTONDOWN or WM_MBUTTONUP or WM_MBUTTONDBLCLK => MK_MBUTTON,
WM_XBUTTONDOWN or WM_XBUTTONUP => (((long)wParam >> 16) & 0xFFFF) == 1 ? MK_XBUTTON1 : MK_XBUTTON2,
_ => 0,
};
/// <summary>
/// Tracks held buttons and who owns the current press (see
/// _heldButtonsBelongToGame). Runs for every mouse message before anyone
/// handles it, so the bookkeeping never depends on which layer took it.
/// </summary>
private static void TrackMouseButtons(uint msg, IntPtr wParam)
{
if (msg == WM_MOUSEMOVE)
{
// MOUSEMOVE carries the real button state; resync so a release we
// never saw (outside the window, focus change) can't leave a button stuck.
_heldMouseButtons = (int)((long)wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON | MK_XBUTTON1 | MK_XBUTTON2));
if (_heldMouseButtons == 0) _heldButtonsBelongToGame = false;
return;
}
int bit = MouseButtonBit(msg, wParam);
if (bit == 0) return;
bool down = msg is WM_LBUTTONDOWN or WM_RBUTTONDOWN or WM_MBUTTONDOWN or WM_XBUTTONDOWN
or WM_LBUTTONDBLCLK or WM_RBUTTONDBLCLK or WM_MBUTTONDBLCLK;
if (down)
{
if (_heldMouseButtons == 0)
_heldButtonsBelongToGame = !_wantCaptureMouse;
_heldMouseButtons |= bit;
}
else
{
_heldMouseButtons &= ~bit;
}
}
public static bool IsUiCaptureEnabled()