Snapshot for release 2026.10.31.4 (internal 34cea02)
This commit is contained in:
parent
057bb66426
commit
b1c182b05d
114 changed files with 8691 additions and 452 deletions
|
|
@ -39,6 +39,37 @@ internal static unsafe class DX9Backend
|
|||
return _vtxScratch;
|
||||
}
|
||||
|
||||
// Rebased-index scratch (DrawSubmitPlan): one command's indices less its smallest one, reused for
|
||||
// every command (DrawIndexedPrimitiveUP copies them before it returns). Freed in Shutdown.
|
||||
private static ushort* _idxScratch;
|
||||
private static int _idxScratchCapacity;
|
||||
|
||||
private static ushort* EnsureIndexScratch(int needed)
|
||||
{
|
||||
if (needed > _idxScratchCapacity)
|
||||
{
|
||||
int cap = _idxScratchCapacity == 0 ? 16384 : _idxScratchCapacity;
|
||||
while (cap < needed) cap *= 2;
|
||||
if (_idxScratch != null) NativeMemory.Free(_idxScratch);
|
||||
_idxScratch = (ushort*)NativeMemory.Alloc((nuint)cap, sizeof(ushort));
|
||||
_idxScratchCapacity = cap;
|
||||
}
|
||||
return _idxScratch;
|
||||
}
|
||||
|
||||
// ── UiCost counters ──
|
||||
private static SubmitStats _lastSubmit;
|
||||
/// <summary>The last RenderDrawData / RenderDrawList call's counters (read right after the call). Render thread.</summary>
|
||||
public static SubmitStats LastSubmit => _lastSubmit;
|
||||
|
||||
private static int _fontUploads, _texUploads;
|
||||
/// <summary>Textures made since the last call: the font atlas, and the others (icons, map tiles, pictures). Render thread.</summary>
|
||||
public static void TakeUploads(out int font, out int tex)
|
||||
{
|
||||
font = _fontUploads; tex = _texUploads;
|
||||
_fontUploads = _texUploads = 0;
|
||||
}
|
||||
|
||||
// ── Diagnostics (/rc imgui diag): what the last RenderDrawData did ──
|
||||
private static int _diagLists, _diagVtx, _diagCmds, _diagDraws, _diagSkipped, _diagFailed, _diagLastHr;
|
||||
private static long _diagFrames;
|
||||
|
|
@ -413,6 +444,12 @@ internal static unsafe class DX9Backend
|
|||
_vtxScratch = null;
|
||||
_vtxScratchCapacity = 0;
|
||||
}
|
||||
if (_idxScratch != null)
|
||||
{
|
||||
NativeMemory.Free(_idxScratch);
|
||||
_idxScratch = null;
|
||||
_idxScratchCapacity = 0;
|
||||
}
|
||||
_initialized = false;
|
||||
_coreInitialized = false;
|
||||
}
|
||||
|
|
@ -524,6 +561,7 @@ internal static unsafe class DX9Backend
|
|||
private static void RenderLists(ImDrawList** cmdLists, int cmdListsCount, int totalVtx, Vector2 displayPos, Vector2 displaySize,
|
||||
IntPtr pDevice, bool midFrame)
|
||||
{
|
||||
_lastSubmit.Clear();
|
||||
if (cmdListsCount == 0) return;
|
||||
if (displaySize.X <= 0 || displaySize.Y <= 0) return;
|
||||
if (cmdLists == null) return;
|
||||
|
|
@ -629,6 +667,12 @@ internal static unsafe class DX9Backend
|
|||
SetupRenderStateNative(pDevice, displayPos, displaySize);
|
||||
|
||||
const int ResetRenderStateSentinel = -8; // ImDrawCallback_ResetRenderState
|
||||
// The texture and scissor rect last set here: an unchanged one isn't set again.
|
||||
IntPtr boundTex = IntPtr.Zero;
|
||||
bool texBound = false;
|
||||
RECT boundScissor = default;
|
||||
bool scissorBound = false;
|
||||
ref SubmitStats st = ref _lastSubmit;
|
||||
|
||||
for (int n = 0; n < cmdListsCount; n++)
|
||||
{
|
||||
|
|
@ -638,6 +682,7 @@ internal static unsafe class DX9Backend
|
|||
int vtxCount = list->VtxBuffer.Size;
|
||||
int cmdCount = list->CmdBuffer.Size;
|
||||
if (vtxCount == 0 || cmdCount == 0) continue;
|
||||
st.Lists++;
|
||||
|
||||
ImDrawVert* srcVtx = (ImDrawVert*)list->VtxBuffer.Data;
|
||||
ushort* idxBase = (ushort*)list->IdxBuffer.Data;
|
||||
|
|
@ -696,20 +741,52 @@ internal static unsafe class DX9Backend
|
|||
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, cmd->TextureId);
|
||||
if (sr.Right <= sr.Left || sr.Bottom <= sr.Top) { _diagSkipped++; st.Skipped++; continue; }
|
||||
|
||||
// DrawIndexedPrimitiveUP has no base-vertex argument, so the
|
||||
// command's VtxOffset is applied by offsetting the vertex pointer.
|
||||
// DrawIndexedPrimitiveUP copies NumVertices vertices on every call, so a
|
||||
// command gets only the vertices its indices reach (DrawSubmitPlan), not the
|
||||
// whole list (that was V x C vertices a frame: the Loot Editor's 200-330 ms
|
||||
// submit). It has no base-vertex argument: the command's VtxOffset and its
|
||||
// smallest index move the vertex pointer, and the indices are rebased to it.
|
||||
uint vtxOffset = cmd->VtxOffset;
|
||||
if (vtxOffset >= (uint)vtxCount) { _diagSkipped++; continue; }
|
||||
ushort* cmdIdx = idxBase + cmd->IdxOffset;
|
||||
if (vtxOffset >= (uint)vtxCount
|
||||
|| cmd->IdxOffset + elemCount > (uint)list->IdxBuffer.Size
|
||||
|| !DrawSubmitPlan.Plan(cmdIdx, (int)elemCount, vtxCount, (int)vtxOffset, out int first, out int numVerts))
|
||||
{
|
||||
_diagSkipped++; st.Skipped++; continue;
|
||||
}
|
||||
ushort* drawIdx = cmdIdx;
|
||||
if (first > 0)
|
||||
{
|
||||
drawIdx = EnsureIndexScratch((int)elemCount);
|
||||
DrawSubmitPlan.Rebase(cmdIdx, drawIdx, (int)elemCount, first);
|
||||
}
|
||||
|
||||
if (!scissorBound || sr.Left != boundScissor.Left || sr.Top != boundScissor.Top
|
||||
|| sr.Right != boundScissor.Right || sr.Bottom != boundScissor.Bottom)
|
||||
{
|
||||
_setScissorRect!(pDevice, &sr);
|
||||
boundScissor = sr;
|
||||
scissorBound = true;
|
||||
}
|
||||
if (!texBound || cmd->TextureId != boundTex)
|
||||
{
|
||||
_setTexture!(pDevice, 0, cmd->TextureId);
|
||||
if (texBound) st.TexSwitches++;
|
||||
boundTex = cmd->TextureId;
|
||||
texBound = true;
|
||||
}
|
||||
|
||||
int hr = _drawIndexedPrimUP!(pDevice,
|
||||
D3DPT_TRIANGLELIST, 0, (uint)vtxCount - vtxOffset,
|
||||
D3DPT_TRIANGLELIST, 0, (uint)numVerts,
|
||||
elemCount / 3,
|
||||
(IntPtr)(idxBase + cmd->IdxOffset), D3DFMT_INDEX16,
|
||||
(IntPtr)(vtxBuf + vtxOffset), (uint)sizeof(CustomVertex));
|
||||
(IntPtr)drawIdx, D3DFMT_INDEX16,
|
||||
(IntPtr)(vtxBuf + vtxOffset + first), (uint)sizeof(CustomVertex));
|
||||
_diagDraws++;
|
||||
st.Draws++;
|
||||
st.VtxCopied += numVerts;
|
||||
st.VtxWholeList += vtxCount - vtxOffset;
|
||||
if (hr < 0) { _diagFailed++; _diagLastHr = hr; }
|
||||
}
|
||||
}
|
||||
|
|
@ -927,27 +1004,42 @@ internal static unsafe class DX9Backend
|
|||
return false;
|
||||
}
|
||||
|
||||
// Copy with RGBA → BGRA swizzle (ImGui gives RGBA, D3D9 A8R8G8B8 is BGRA in memory)
|
||||
byte* src = (byte*)pixels;
|
||||
byte* dst = (byte*)locked.pBits;
|
||||
|
||||
for (int y = 0; y < height; y++)
|
||||
if (ImGuiFonts.TakeBgraPixels(width, height, out IntPtr bgra))
|
||||
{
|
||||
byte* srcRow = src + y * width * 4;
|
||||
byte* dstRow = dst + y * locked.Pitch;
|
||||
|
||||
for (int x = 0; x < width; x++)
|
||||
// The bake worker made the BGRA rows (ImGuiFonts.BakeWorker): only a row copy here.
|
||||
try
|
||||
{
|
||||
int si = x * 4;
|
||||
int di = x * 4;
|
||||
dstRow[di + 0] = srcRow[si + 2]; // B ← R
|
||||
dstRow[di + 1] = srcRow[si + 1]; // G ← G
|
||||
dstRow[di + 2] = srcRow[si + 0]; // R ← B
|
||||
dstRow[di + 3] = srcRow[si + 3]; // A ← A
|
||||
long row = (long)width * 4;
|
||||
for (int y = 0; y < height; y++)
|
||||
Buffer.MemoryCopy((byte*)bgra + y * row, dst + (long)y * locked.Pitch, row, row);
|
||||
}
|
||||
finally { ImGuiFonts.FreeBgraPixels(bgra); }
|
||||
}
|
||||
else
|
||||
{
|
||||
// Copy with RGBA → BGRA swizzle (ImGui gives RGBA, D3D9 A8R8G8B8 is BGRA in memory)
|
||||
byte* src = (byte*)pixels;
|
||||
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
byte* srcRow = src + y * width * 4;
|
||||
byte* dstRow = dst + y * locked.Pitch;
|
||||
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
int si = x * 4;
|
||||
int di = x * 4;
|
||||
dstRow[di + 0] = srcRow[si + 2]; // B ← R
|
||||
dstRow[di + 1] = srcRow[si + 1]; // G ← G
|
||||
dstRow[di + 2] = srcRow[si + 0]; // R ← B
|
||||
dstRow[di + 3] = srcRow[si + 3]; // A ← A
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unlockRect(_fontTexture, 0);
|
||||
_fontUploads++; // UiCost: a font atlas upload this frame
|
||||
|
||||
// Store texture ID for ImGui
|
||||
io.Fonts.SetTexID(_fontTexture);
|
||||
|
|
@ -1001,6 +1093,7 @@ internal static unsafe class DX9Backend
|
|||
}
|
||||
}
|
||||
unlockRect(tex, 0);
|
||||
_texUploads++; // UiCost
|
||||
return tex;
|
||||
}
|
||||
|
||||
|
|
@ -1033,6 +1126,7 @@ internal static unsafe class DX9Backend
|
|||
for (int y = 0; y < rows; y++) // the pitch of a compressed surface is the bytes of one row of blocks
|
||||
blocks.Slice(y * rowBytes, rowBytes).CopyTo(new Span<byte>(dst + y * locked.Pitch, rowBytes));
|
||||
unlockRect(tex, 0);
|
||||
_texUploads++; // UiCost
|
||||
return tex;
|
||||
}
|
||||
|
||||
|
|
|
|||
70
src/RynthCore.Engine/ImGui/DrawSubmitPlan.cs
Normal file
70
src/RynthCore.Engine/ImGui/DrawSubmitPlan.cs
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/DrawSubmitPlan.cs
|
||||
// How DX9Backend hands one ImDrawCmd to DrawIndexedPrimitiveUP. Pure logic,
|
||||
// no engine or D3D types (tools/UiCostTests compiles it). The submit's
|
||||
// counters (SubmitStats) live in UiCostModel.cs, which stays self-contained.
|
||||
//
|
||||
// DrawIndexedPrimitiveUP copies NumVertices vertices out of the caller's
|
||||
// memory into the runtime's own vertex buffer on EVERY call. The renderer used
|
||||
// to pass the whole draw list's vertex count for each command, so a window
|
||||
// with V vertices and C draw commands copied V x C vertices a frame. Every
|
||||
// PushClipRect starts a new command; the Loot Editor's rule list pushes two
|
||||
// clip rects per row (name, conditions), so with the editor open the frame's
|
||||
// vertices went from ~13k to ~30k in one child list split into a command or
|
||||
// more per row, and the submit copied the list once per command: on the order
|
||||
// of a million vertices (tens of MB) a frame through the runtime's ring
|
||||
// buffer. Logged live: submit 200-330 ms for <1 ms of building (and the GPU/
|
||||
// driver stalls slowed another client on the PC too).
|
||||
//
|
||||
// Now each command gets only the vertices its indices reach: the min..max of
|
||||
// its indices. When min > 0 the indices are rebased into a scratch copy and
|
||||
// the vertex pointer moved by min, so MinVertexIndex is always 0 (some D3D9
|
||||
// implementations copy from vertex 0 up to MinVertexIndex + NumVertices,
|
||||
// whatever MinVertexIndex says). A frame now copies about its vertex count.
|
||||
// ============================================================================
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static unsafe class DrawSubmitPlan
|
||||
{
|
||||
/// <summary>
|
||||
/// The vertices one command uses: the smallest and largest of its <paramref name="count"/>
|
||||
/// indices (count > 0). Linear in count; over a frame that is the frame's index count.
|
||||
/// </summary>
|
||||
public static void IndexRange(ushort* idx, int count, out int min, out int max)
|
||||
{
|
||||
int lo = ushort.MaxValue, hi = 0;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
int v = idx[i];
|
||||
if (v < lo) lo = v;
|
||||
if (v > hi) hi = v;
|
||||
}
|
||||
min = lo;
|
||||
max = hi;
|
||||
}
|
||||
|
||||
/// <summary>dst[i] = src[i] - by, for the <paramref name="count"/> indices of a command whose smallest index is <paramref name="by"/>.</summary>
|
||||
public static void Rebase(ushort* src, ushort* dst, int count, int by)
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
dst[i] = (ushort)(src[i] - by);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What to draw for one command: its first vertex (from the command's VtxOffset) and how many
|
||||
/// vertices to hand over. False when an index reaches past the list (a broken list: skipped,
|
||||
/// nothing read out of bounds). <paramref name="listVtx"/> is the list's vertex count.
|
||||
/// </summary>
|
||||
public static bool Plan(ushort* idx, int count, int listVtx, int vtxOffset, out int first, out int numVerts)
|
||||
{
|
||||
first = 0;
|
||||
numVerts = 0;
|
||||
if (count <= 0 || vtxOffset < 0 || vtxOffset >= listVtx) return false;
|
||||
IndexRange(idx, count, out int min, out int max);
|
||||
if (vtxOffset + max >= listVtx) return false;
|
||||
first = min;
|
||||
numVerts = max - min + 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -121,107 +121,174 @@ internal static class EngineFrameController
|
|||
return true;
|
||||
}
|
||||
|
||||
public static bool Init(IntPtr pDevice)
|
||||
// ImGui init runs in two parts since 2026-11-01: the first makes the context (handed to the
|
||||
// plugins at once, as before) and starts the font atlas bake on a worker (ImGuiFonts.
|
||||
// StartInitialBake); frames build nothing until the bake is done, and the frame that finds it
|
||||
// done swaps it in, sets up the Win32 backend and uploads the texture. The bake used to run
|
||||
// here, on AC's thread, for 2.5-5 s of every hot reload (the main-thread hangs of 10-31/11-01).
|
||||
private enum InitStep { Done, Baking, Failed }
|
||||
|
||||
private static long _initStartedTicks;
|
||||
|
||||
private static InitStep Init(IntPtr pDevice)
|
||||
{
|
||||
if (_imguiInitialized)
|
||||
return true;
|
||||
return InitStep.Done;
|
||||
bool begin = _context == IntPtr.Zero;
|
||||
|
||||
if (!EnsureCore(pDevice))
|
||||
if (begin)
|
||||
{
|
||||
_initFailStep = "EnsureCore (game window not found)";
|
||||
return false;
|
||||
if (!EnsureCore(pDevice))
|
||||
{
|
||||
_initFailStep = "EnsureCore (game window not found)";
|
||||
return InitStep.Failed;
|
||||
}
|
||||
|
||||
// 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.
|
||||
MainThreadHangWatchdog.Step = "ImGui init: self-test";
|
||||
_initStartedTicks = Stopwatch.GetTimestamp();
|
||||
Compatibility.MemoryUse.Mark("ImGui init: before the self-test");
|
||||
if (!ImGuiSelfTest.Run(EntryPoint.ImGuiNativeHandle))
|
||||
return InitStep.Failed;
|
||||
Compatibility.MemoryUse.Mark("ImGui self-test done");
|
||||
}
|
||||
|
||||
// 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.
|
||||
Compatibility.MemoryUse.Mark("ImGui init: before the self-test");
|
||||
if (!ImGuiSelfTest.Run(EntryPoint.ImGuiNativeHandle))
|
||||
return false;
|
||||
Compatibility.MemoryUse.Mark("ImGui self-test done");
|
||||
|
||||
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
|
||||
if (previousContext != IntPtr.Zero)
|
||||
RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context.");
|
||||
|
||||
_context = ImGuiNET.ImGui.CreateContext();
|
||||
Compatibility.MemoryUse.Mark("ImGui context created");
|
||||
bool initSucceeded = false;
|
||||
if (begin)
|
||||
{
|
||||
if (previousContext != IntPtr.Zero)
|
||||
RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context.");
|
||||
MainThreadHangWatchdog.Step = "ImGui init: context";
|
||||
_context = ImGuiNET.ImGui.CreateContext();
|
||||
Compatibility.MemoryUse.Mark("ImGui context created");
|
||||
}
|
||||
InitStep result = InitStep.Failed;
|
||||
try
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(_context);
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
|
||||
// Pin imgui.ini to a stable absolute path so window positions/sizes
|
||||
// persist across plugin reloads (RL) and AC restarts. The default
|
||||
// ImGui behavior writes to the working directory which can differ
|
||||
// between launches. Allocated once, kept alive for the process lifetime.
|
||||
try
|
||||
if (begin)
|
||||
{
|
||||
string iniPath = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "imgui.ini");
|
||||
System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir);
|
||||
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
|
||||
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
|
||||
RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}");
|
||||
SetUpContext(io);
|
||||
MainThreadHangWatchdog.Step = "ImGui init: starting the font bake";
|
||||
if (ImGuiFonts.StartInitialBake(_uiScale))
|
||||
{
|
||||
RynthLog.UI("EngineFrameController: the font atlas bakes on a worker; ImGui frames start once it is done.");
|
||||
result = InitStep.Baking;
|
||||
return result;
|
||||
}
|
||||
// No worker to be had: the old way, on this thread.
|
||||
MainThreadHangWatchdog.Step = "ImGui init: fonts on the render thread";
|
||||
ImGuiFonts.Build(io, _uiScale);
|
||||
}
|
||||
catch (Exception ex)
|
||||
else
|
||||
{
|
||||
RynthLog.Render($"EngineFrameController: failed to pin imgui.ini path - {ex.Message}");
|
||||
MainThreadHangWatchdog.Step = "ImGui init: swapping in the baked atlas";
|
||||
if (!ImGuiFonts.SwapFinished(io, _uiScale, out string baked))
|
||||
{
|
||||
result = InitStep.Baking; // still baking: no ImGui frame yet
|
||||
return result;
|
||||
}
|
||||
double sinceMs = (Stopwatch.GetTimestamp() - _initStartedTicks) * 1000.0 / Stopwatch.Frequency;
|
||||
RynthLog.UI($"ImGuiFonts: first atlas {baked} ({sinceMs:0} ms after ImGui init began).");
|
||||
Compatibility.MemoryUse.Mark("ImGui fonts swapped in");
|
||||
}
|
||||
|
||||
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
|
||||
// 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).
|
||||
|
||||
// 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);
|
||||
Compatibility.MemoryUse.Mark("ImGui theme applied");
|
||||
ImGuiFonts.Build(io, _uiScale);
|
||||
|
||||
MainThreadHangWatchdog.Step = "ImGui init: Win32 backend";
|
||||
if (!Win32Backend.Init(_gameHwnd))
|
||||
{
|
||||
_initFailStep = "Win32Backend.Init";
|
||||
return false;
|
||||
return result;
|
||||
}
|
||||
|
||||
Compatibility.MemoryUse.Mark("Win32 backend ready");
|
||||
MainThreadHangWatchdog.Step = "ImGui init: font texture upload";
|
||||
if (!DX9Backend.InitImGui(pDevice))
|
||||
{
|
||||
_initFailStep = "DX9Backend.InitImGui";
|
||||
return false;
|
||||
return result;
|
||||
}
|
||||
Compatibility.MemoryUse.Mark("DX9 backend ready (font texture)");
|
||||
|
||||
_lastFrameTicks = Stopwatch.GetTimestamp();
|
||||
_imguiInitialized = true;
|
||||
initSucceeded = true;
|
||||
result = InitStep.Done;
|
||||
|
||||
RynthLog.UI("EngineFrameController: ImGui initialized.");
|
||||
return true;
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!initSucceeded && _context != IntPtr.Zero)
|
||||
if (result == InitStep.Failed && _context != IntPtr.Zero)
|
||||
{
|
||||
// A bake may still be running: no context may be destroyed while it allocates.
|
||||
ImGuiFonts.WaitForWorkers();
|
||||
ImGuiNET.ImGui.DestroyContext(_context);
|
||||
_context = IntPtr.Zero;
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCurrentContext(previousContext);
|
||||
MainThreadHangWatchdog.Step = "EndScene: ImGui frame";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The new context's ini handling, flags, DPI scale and theme (Init's first part). Context current.</summary>
|
||||
private static void SetUpContext(ImGuiIOPtr io)
|
||||
{
|
||||
// Panel layout per character (UI/PanelLayout): the engine loads and saves the
|
||||
// imgui.ini of the layout in use itself (the character's, or the PC-wide
|
||||
// default), so Dear ImGui gets no file name: it would load only the one it
|
||||
// started with and write it from the render thread, not atomically. The
|
||||
// context starts with the layout already applied, if there is one.
|
||||
if (UI.PanelLayout.Initialized)
|
||||
{
|
||||
unsafe { io.NativePtr->IniFilename = null; }
|
||||
UI.PanelLayout.OnContextCreated(LoadIniFn);
|
||||
RynthLog.Info("EngineFrameController: imgui.ini is loaded and saved by the panel layout (UI/PanelLayout).");
|
||||
}
|
||||
// Without it (an engine that didn't get that far), as before: pin imgui.ini to
|
||||
// a stable absolute path so window positions/sizes persist across plugin
|
||||
// reloads (RL) and AC restarts. The default ImGui behavior writes to the
|
||||
// working directory which can differ between launches. Allocated once,
|
||||
// kept alive for the process lifetime.
|
||||
else try
|
||||
{
|
||||
string iniPath = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "imgui.ini");
|
||||
System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir);
|
||||
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
|
||||
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
|
||||
RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Render($"EngineFrameController: failed to pin imgui.ini path - {ex.Message}");
|
||||
}
|
||||
|
||||
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
|
||||
// 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).
|
||||
|
||||
// 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);
|
||||
Compatibility.MemoryUse.Mark("ImGui theme applied");
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
if (!_imguiInitialized)
|
||||
// A context whose first font atlas is still baking (Init's two parts) goes too.
|
||||
if (!_imguiInitialized && _context == IntPtr.Zero)
|
||||
return;
|
||||
bool framesRan = _imguiInitialized;
|
||||
|
||||
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
|
||||
IntPtr contextToDestroy = _context;
|
||||
|
|
@ -250,6 +317,15 @@ internal static class EngineFrameController
|
|||
// unhooks), so restoring AC's original WndProc this early sends
|
||||
// those destroys to AC's proc, which ignores them, and the orphaned
|
||||
// panel HWND outlives the engine load.
|
||||
// The windows' places go to the layout's imgui.ini now (with no IniFilename
|
||||
// DestroyContext doesn't save them; UI/PanelLayout).
|
||||
try
|
||||
{
|
||||
// Not before the first frame (the atlas still baking): nothing moved, nothing to save.
|
||||
if (UI.PanelLayout.Initialized && framesRan)
|
||||
UI.PanelLayout.SaveIniOnShutdown(ImGuiNET.ImGui.SaveIniSettingsToMemory());
|
||||
}
|
||||
catch (Exception ex) { RynthLog.UI($"EngineFrameController: imgui.ini save at shutdown threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
ImGuiNET.ImGui.DestroyContext(contextToDestroy);
|
||||
ImGuiFonts.Free(); // the atlas referenced these buffers; the context is gone now
|
||||
|
||||
|
|
@ -276,6 +352,7 @@ internal static class EngineFrameController
|
|||
{
|
||||
// Resolve game HWND and seed EntryPoint.GameHwnd. Required even
|
||||
// in ImGui-off mode so Avalonia owner-window binding works.
|
||||
MainThreadHangWatchdog.Step = "EndScene: engine pipeline (layout, prefetches, queues)";
|
||||
EnsureCore(pDevice);
|
||||
|
||||
// Settings > Display: borderless windowed + AC window placement. Throttled; reads only
|
||||
|
|
@ -283,6 +360,12 @@ internal static class EngineFrameController
|
|||
try { UI.AcWindowChrome.Tick(_gameHwnd); }
|
||||
catch (Exception ex) { RynthLog.UI($"AcWindowChrome.Tick threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
|
||||
// Panel layout per character: switches to the character's layout (or back to the
|
||||
// PC-wide default) and applies a loaded one, before anything below draws a panel.
|
||||
// A layout waits for the ImGui context while the ImGui layer is in use.
|
||||
UI.PanelLayout.Tick(imguiInUse: Plugins.EngineSettings.EnableImGuiBackend && !_imguiInitFailed,
|
||||
imguiReady: _imguiInitialized, SnapshotIniFn, LoadIniFn);
|
||||
|
||||
// Cache the D3D9 device function pointers used by Nav3DRenderInjector,
|
||||
// RenderNav3D, and the always-on render path. This is a strict subset
|
||||
// of what InitImGui needs and is safe to run without ImGui state.
|
||||
|
|
@ -400,8 +483,12 @@ internal static class EngineFrameController
|
|||
bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend;
|
||||
bool imguiBuilt = false;
|
||||
long uiTicks = 0;
|
||||
MainThreadHangWatchdog.Step = "EndScene: ImGui frame";
|
||||
if (!imguiEnabled)
|
||||
{
|
||||
_imguiIdle = true; // switched off in game: input state resets when it comes back
|
||||
UiCost.DiscardFrame(); // no UI frame: what the 3D pass timed isn't kept for one
|
||||
}
|
||||
else
|
||||
{
|
||||
long t0 = Stopwatch.GetTimestamp();
|
||||
|
|
@ -421,7 +508,13 @@ internal static class EngineFrameController
|
|||
long t0 = Stopwatch.GetTimestamp();
|
||||
// Popped-out panels: their own contexts, windows and render targets.
|
||||
if (_imguiInitialized)
|
||||
{
|
||||
MainThreadHangWatchdog.Step = "EndScene: pop-out panels";
|
||||
// UiCost: what RenderAll spends outside the pop-out windows it times itself.
|
||||
long c0 = UiCost.Start(), mark = UiCost.Mark;
|
||||
ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive);
|
||||
UiCost.StopExclusive(UiCost.PopOuts, c0, mark);
|
||||
}
|
||||
long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0);
|
||||
if (imguiBuilt)
|
||||
{
|
||||
|
|
@ -431,6 +524,7 @@ internal static class EngineFrameController
|
|||
else
|
||||
{
|
||||
UiFrameStats.Record(ticks);
|
||||
UiCost.EndFrame(ticks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -599,11 +693,38 @@ internal static class EngineFrameController
|
|||
/// Panel faces show only in the world, like the Avalonia overlay (hidden
|
||||
/// between characters, not closed). Also off as soon as AC leaves the world screen
|
||||
/// (UiFlowHooks, before the logout dispatch catches up) and for good once
|
||||
/// Client::Cleanup starts.
|
||||
/// Client::Cleanup starts. And after a login (or a hot reload) not before that
|
||||
/// character's panel layout is in place (UI/PanelLayout), so nothing draws at the
|
||||
/// default places first.
|
||||
/// </summary>
|
||||
private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete
|
||||
&& Compatibility.UiFlowHooks.InWorldOrUnknown
|
||||
&& !Compatibility.UiFlowHooks.ClientCleanupStarted;
|
||||
&& !Compatibility.UiFlowHooks.ClientCleanupStarted
|
||||
&& UI.PanelLayout.ReadyToDraw;
|
||||
|
||||
// The ImGui windows' saved text, read from and loaded into the main context for UI/PanelLayout
|
||||
// (render thread, between frames). Cached so the per-frame Tick allocates nothing.
|
||||
private static readonly Func<string?> SnapshotIniFn = SnapshotIni;
|
||||
private static readonly Action<string> LoadIniFn = LoadIni;
|
||||
|
||||
private static string? SnapshotIni()
|
||||
{
|
||||
if (!_imguiInitialized || _context == IntPtr.Zero) return null;
|
||||
IntPtr previous = ImGuiNET.ImGui.GetCurrentContext();
|
||||
ImGuiNET.ImGui.SetCurrentContext(_context);
|
||||
try { return ImGuiNET.ImGui.SaveIniSettingsToMemory(); }
|
||||
finally { ImGuiNET.ImGui.SetCurrentContext(previous); }
|
||||
}
|
||||
|
||||
/// <summary>Loads ini text into the main context: Dear ImGui applies it to windows that already exist too.</summary>
|
||||
private static void LoadIni(string text)
|
||||
{
|
||||
if (_context == IntPtr.Zero) return;
|
||||
IntPtr previous = ImGuiNET.ImGui.GetCurrentContext();
|
||||
ImGuiNET.ImGui.SetCurrentContext(_context);
|
||||
try { ImGuiNET.ImGui.LoadIniSettingsFromMemory(text); }
|
||||
finally { ImGuiNET.ImGui.SetCurrentContext(previous); }
|
||||
}
|
||||
|
||||
/// <summary>DPI scale the fonts and style were built for (see Init).</summary>
|
||||
private static float _uiScale = 1f;
|
||||
|
|
@ -663,19 +784,24 @@ internal static class EngineFrameController
|
|||
{
|
||||
// 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))
|
||||
InitStep step = Init(pDevice);
|
||||
if (step == InitStep.Failed)
|
||||
{
|
||||
_imguiInitFailed = true;
|
||||
RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session.");
|
||||
return false;
|
||||
}
|
||||
if (step == InitStep.Baking)
|
||||
return false; // the first font atlas is still baking on its worker: no ImGui frame yet
|
||||
}
|
||||
|
||||
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.
|
||||
long cHud = UiCost.Start();
|
||||
Hud.MonsterHud.Update(PanelsLive);
|
||||
UiCost.Stop(UiCost.HudUpdate, cHud);
|
||||
|
||||
if (!HasImGuiContent())
|
||||
{
|
||||
|
|
@ -704,6 +830,8 @@ internal static class EngineFrameController
|
|||
}
|
||||
|
||||
_frameCount++;
|
||||
// UiCost (ImGui/UiCost.cs): each part of the frame below is timed, by name.
|
||||
long cSetup = UiCost.Start();
|
||||
// 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
|
||||
|
|
@ -737,7 +865,10 @@ internal static class EngineFrameController
|
|||
io.DeltaTime = dt > 0f ? dt : 1f / 60f;
|
||||
|
||||
RynthTheme.RefreshStyle(ref _themeApplied); // a theme change re-colours the base style
|
||||
UiCost.Stop(UiCost.FrameSetup, cSetup);
|
||||
long cNew = UiCost.Start();
|
||||
ImGuiNET.ImGui.NewFrame();
|
||||
UiCost.Stop(UiCost.ImGuiNewFrame, cNew);
|
||||
frameStarted = true;
|
||||
// Before any window: a drag from a popped-out Inventory or AC's inventory becomes
|
||||
// a payload the client's drop targets (Mini Remote slots) see this frame.
|
||||
|
|
@ -755,15 +886,17 @@ internal static class EngineFrameController
|
|||
if (Plugins.EngineSettings.EnableImGuiShell)
|
||||
{
|
||||
branch = 1;
|
||||
long cShell = UiCost.Start();
|
||||
RynthCoreShell.Render(_frameCount);
|
||||
PluginManager.RenderAll();
|
||||
UiCost.Stop(UiCost.Shell, cShell);
|
||||
PluginManager.RenderAll(); // times each plugin's Render (UiCost)
|
||||
}
|
||||
else if (PluginOverlayWindowsLive)
|
||||
{
|
||||
branch = 2;
|
||||
// Only the opt-in extra windows (RynthPluginRenderOverlay), never the
|
||||
// plugins' full ImGui UIs.
|
||||
PluginManager.RenderOverlayAll();
|
||||
PluginManager.RenderOverlayAll(); // times each plugin's RenderOverlay (UiCost)
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
@ -779,29 +912,53 @@ internal static class EngineFrameController
|
|||
// 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.
|
||||
// Video patch: with no 3D scene only the screen-fixed player plate draws.
|
||||
// Timed from here, as one part (plates, the player plate, combat text): the HUD's own
|
||||
// code isn't instrumented.
|
||||
long cPlates = UiCost.Start();
|
||||
Hud.MonsterHud.Draw(_uiScale, worldVisible: !D3D9.VideoPatch.SkipWorldThisFrame);
|
||||
UiCost.Stop(UiCost.MonsterHud, cPlates, cPlates != 0 ? Hud.MonsterHud.PlateCount : -1);
|
||||
// Video patch "all": the "rendering paused" banner (background list, under the panels).
|
||||
long cPart = UiCost.Start();
|
||||
VideoPatchBanner.Draw();
|
||||
UiCost.Stop(UiCost.VideoBanner, cPart);
|
||||
// Server verdicts, the plugins' section manifests and the servermenu push. Every
|
||||
// frame, bar or not: with the bar hidden (the rail instead) nothing else ticks them,
|
||||
// so Options > Diagnostics listed no servers and no server plugin was told it is active.
|
||||
cPart = UiCost.Start();
|
||||
RynthCore.Engine.UI.ServerMenus.Tick();
|
||||
UiCost.Stop(UiCost.ServerMenus, cPart);
|
||||
cPart = UiCost.Start();
|
||||
if (ImGuiBar.Visible)
|
||||
ImGuiBar.Draw(_uiScale);
|
||||
ImGuiPanelHost.DrawAll(_uiScale);
|
||||
UiCost.Stop(UiCost.Bar, cPart);
|
||||
ImGuiPanelHost.DrawAll(_uiScale); // times each panel by title, and its own upkeep (UiCost)
|
||||
// Settings drawer bodies RynthAi's window didn't draw this frame let their sources go.
|
||||
cPart = UiCost.Start();
|
||||
Panels.SettingsDrawerBodies.EndFrame();
|
||||
UiCost.Stop(UiCost.DrawerBodies, cPart);
|
||||
cPart = UiCost.Start();
|
||||
ImGuiBar.SyncPopOut(_uiScale);
|
||||
UiCost.Stop(UiCost.Bar, cPart);
|
||||
}
|
||||
if (ImGuiFontTest.Enabled)
|
||||
ImGuiFontTest.Draw(_uiScale);
|
||||
|
||||
long cRender = UiCost.Start();
|
||||
ImGuiNET.ImGui.EndFrame();
|
||||
frameEnded = true;
|
||||
ImGuiNET.ImGui.Render();
|
||||
UiCost.Stop(UiCost.ImGuiRender, cRender);
|
||||
long cFinish = UiCost.Start();
|
||||
ImGuiAssertLog.Poll();
|
||||
_framesBuilt++;
|
||||
_lastDisplaySize = io.DisplaySize;
|
||||
// Windows moved a while ago (Dear ImGui's dirty timer; no IniFilename, so it asks):
|
||||
// saved to the panel layout's imgui.ini in the background (UI/PanelLayout).
|
||||
if (io.WantSaveIniSettings)
|
||||
{
|
||||
io.WantSaveIniSettings = false;
|
||||
UI.PanelLayout.QueueIniSave(ImGuiNET.ImGui.SaveIniSettingsToMemory(), explicitSave: false);
|
||||
}
|
||||
|
||||
// io.WantCaptureMouse already applies ImGui's own button-ownership
|
||||
// rule; io.WantTextInput is true only while a text field is edited.
|
||||
|
|
@ -826,6 +983,7 @@ internal static class EngineFrameController
|
|||
if (typing && !Win32Backend.UiCaptureEnabled)
|
||||
_dropImGuiTextFocus = true;
|
||||
ArbitrateTextFocus(io.WantTextInput);
|
||||
UiCost.Stop(UiCost.FrameFinish, cFinish);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
|
@ -884,7 +1042,9 @@ internal static class EngineFrameController
|
|||
|
||||
long t0 = Stopwatch.GetTimestamp();
|
||||
SubmitImGuiFrame(device);
|
||||
UiFrameStats.Record(_deferredUiTicks + (Stopwatch.GetTimestamp() - t0));
|
||||
long ticks = _deferredUiTicks + (Stopwatch.GetTimestamp() - t0);
|
||||
UiFrameStats.Record(ticks);
|
||||
UiCost.EndFrame(ticks);
|
||||
}
|
||||
|
||||
/// <summary>Draws the frame <see cref="BuildImGuiFrame"/> produced.</summary>
|
||||
|
|
@ -895,7 +1055,16 @@ internal static class EngineFrameController
|
|||
try
|
||||
{
|
||||
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
|
||||
long c0 = UiCost.Start();
|
||||
DX9Backend.RenderDrawData(drawData, pDevice);
|
||||
if (c0 != 0)
|
||||
{
|
||||
int vertices = 0;
|
||||
// ImDrawData +12 TotalVtxCount (as LogHeartbeatIfDue).
|
||||
unsafe { byte* p = (byte*)drawData.NativePtr; if (p != null) vertices = *(int*)(p + 12); }
|
||||
UiCost.Stop(UiCost.Submit, c0, vertices);
|
||||
UiCost.SetSubmit(DX9Backend.LastSubmit); // draws, texture switches, vertices copied
|
||||
}
|
||||
_drawSubmits++;
|
||||
if (!_loggedFirstSubmit)
|
||||
{
|
||||
|
|
|
|||
24
src/RynthCore.Engine/ImGui/FontPixels.cs
Normal file
24
src/RynthCore.Engine/ImGui/FontPixels.cs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/FontPixels.cs
|
||||
// ImGui's font atlas pixels (RGBA32) as D3D9 A8R8G8B8 rows (BGRA in memory). The bake
|
||||
// worker converts them (ImGuiFonts.BakeWorker), so AC's thread only copies rows into the
|
||||
// texture (DX9Backend.CreateFontTexture). Pure: tools\EngineRobustnessTests checks it.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static class FontPixels
|
||||
{
|
||||
/// <summary>R and B swap in each 32-bit pixel (little-endian RGBA: R in the low byte).</summary>
|
||||
public static void RgbaToBgra(ReadOnlySpan<uint> rgba, Span<uint> bgra)
|
||||
{
|
||||
if (bgra.Length < rgba.Length) throw new ArgumentException("destination too small", nameof(bgra));
|
||||
for (int i = 0; i < rgba.Length; i++)
|
||||
{
|
||||
uint p = rgba[i];
|
||||
bgra[i] = (p & 0xFF00FF00u) | ((p & 0x000000FFu) << 16) | ((p >> 16) & 0x000000FFu);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -241,6 +241,20 @@ internal static class ImGuiBar
|
|||
/// <summary>True when the ImGui bar should draw (the ImGui layer on, not popped out).</summary>
|
||||
public static bool Visible => ResolveFace() != PanelFace.Avalonia && !Floating;
|
||||
|
||||
/// <summary>
|
||||
/// The panel store now holds another layout (UI/PanelLayout: another character's, the default, or a
|
||||
/// reset): the bar's place, rows and popped-out state are read from it again; a popped-out bar's
|
||||
/// window closes and SyncPopOut opens it at the new layout's spot. AC thread, between frames.
|
||||
/// </summary>
|
||||
public static void OnLayoutSwitched()
|
||||
{
|
||||
Volatile.Write(ref _rowSettings, null);
|
||||
_floating = null;
|
||||
_placed = false;
|
||||
_userMoved = false;
|
||||
if (ImGuiPopOuts.IsPopped(PopOutTitle)) ImGuiPopOuts.Close(PopOutTitle);
|
||||
}
|
||||
|
||||
/// <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).
|
||||
|
|
|
|||
|
|
@ -32,6 +32,13 @@
|
|||
// 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).
|
||||
//
|
||||
// The first atlas is baked off AC's thread too (2026-11-01, StartInitialBake): on a
|
||||
// hot reload with every client reloading at once, queueing the fonts, rasterizing
|
||||
// the atlas, the RGBA->BGRA copy and freeing the ~150 MB of TTF copies took 2.5-5 s
|
||||
// of AC's main thread in the first ImGui frame (the "[UiCost] frame 3611 ms" lines,
|
||||
// the main-thread hangs of every reload). The worker now does all of it; AC's thread
|
||||
// swaps the finished atlas in and copies ready BGRA rows into the texture.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -105,6 +112,8 @@ internal static unsafe class ImGuiFonts
|
|||
// 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.
|
||||
// The sizes self-drawn windows are drawn at (UI.PanelDrawScale) are baked too:
|
||||
// a window at 160% draws its text from the 160% set (StepsToBake).
|
||||
private static readonly Dictionary<int, ImFontPtr[]> ScaledFonts = new();
|
||||
|
||||
/// <summary>Text size step of the panel being drawn (0 = normal). Render thread.</summary>
|
||||
|
|
@ -167,6 +176,15 @@ internal static unsafe class ImGuiFonts
|
|||
_preloaded = true;
|
||||
}
|
||||
|
||||
/// <summary>The text size steps any panel uses, and those the self-drawn windows' sizes need.</summary>
|
||||
private static List<int> StepsToBake(float scale)
|
||||
{
|
||||
List<int> steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse();
|
||||
foreach (int step in RynthCore.Engine.UI.PanelDrawScale.FontStepsInUse(scale))
|
||||
if (!steps.Contains(step)) steps.Add(step);
|
||||
return steps;
|
||||
}
|
||||
|
||||
/// <summary>A baked font. Before Build (or if it failed) this is ImGui's default font.</summary>
|
||||
public static ImFontPtr Get(UiFont font)
|
||||
{
|
||||
|
|
@ -219,7 +237,7 @@ internal static unsafe class ImGuiFonts
|
|||
Compatibility.MemoryUse.Mark("font files read");
|
||||
|
||||
ScaledFonts.Clear();
|
||||
AddAll(io.Fonts, scale, RynthCore.Engine.UI.PanelTextScale.StepsInUse(), Fonts, ScaledFonts);
|
||||
AddAll(io.Fonts, scale, StepsToBake(scale), Fonts, ScaledFonts);
|
||||
|
||||
if (Fonts[(int)UiFont.Ui11].NativePtr != null)
|
||||
io.NativePtr->FontDefault = Fonts[(int)UiFont.Ui11].NativePtr;
|
||||
|
|
@ -403,8 +421,16 @@ internal static unsafe class ImGuiFonts
|
|||
public int Steps;
|
||||
public double Ms;
|
||||
public string? Error;
|
||||
// The atlas pixels as D3D9 A8R8G8B8 rows (BGRA in memory), made by the worker
|
||||
// (NativeMemory); handed on by SwapIn. 0 when the bake failed.
|
||||
public IntPtr Bgra;
|
||||
public int Width, Height;
|
||||
}
|
||||
|
||||
// The swapped-in atlas's BGRA copy, until DX9Backend uploads it (TakeBgraPixels). Render thread.
|
||||
private static IntPtr _bgra;
|
||||
private static int _bgraWidth, _bgraHeight;
|
||||
|
||||
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();
|
||||
|
|
@ -418,32 +444,15 @@ internal static unsafe class ImGuiFonts
|
|||
{
|
||||
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;
|
||||
}
|
||||
return SwapFinished(io, scale, out what); // false while baking: frames go on with the old atlas
|
||||
|
||||
if (!TakeRebuildRequest()) return false;
|
||||
PrepareNativeData();
|
||||
List<int> steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse();
|
||||
List<int> steps = StepsToBake(scale);
|
||||
try
|
||||
{
|
||||
_bakeDone = null;
|
||||
_bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps));
|
||||
_bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps, prepare: false));
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
|
@ -456,27 +465,125 @@ internal static unsafe class ImGuiFonts
|
|||
}
|
||||
}
|
||||
|
||||
private static void BakeWorker(float scale, List<int> steps)
|
||||
/// <summary>
|
||||
/// The first atlas of a context, baked on a worker (see the header): reading the font files if
|
||||
/// the init worker hasn't, making their native copies, queueing every font, rasterizing, the
|
||||
/// BGRA copy and freeing the TTF copies all happen there. AC thread, once the scale is known.
|
||||
/// False when no worker could be started (the caller then calls <see cref="Build"/>).
|
||||
/// </summary>
|
||||
public static bool StartInitialBake(float scale)
|
||||
{
|
||||
if (_bakeThread != null) return true;
|
||||
List<int> steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse();
|
||||
try
|
||||
{
|
||||
_bakeDone = null;
|
||||
_bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps, prepare: true));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_bakeThread = null;
|
||||
RynthLog.UI($"ImGuiFonts: no bake thread for the first atlas ({ex.GetType().Name}: {ex.Message}); baking it on the render thread.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Render thread, with <paramref name="io"/>'s context current: swaps a finished bake (the
|
||||
/// first atlas, or a re-bake) into it. True when the atlas changed (the caller makes its
|
||||
/// texture); false while none is running or it is still baking.
|
||||
/// </summary>
|
||||
public static bool SwapFinished(ImGuiIOPtr io, float scale, out string what)
|
||||
{
|
||||
what = "";
|
||||
if (_bakeThread == null) return false;
|
||||
Bake? done = System.Threading.Volatile.Read(ref _bakeDone);
|
||||
if (done == null) return false;
|
||||
_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}); baked on the render thread";
|
||||
return true;
|
||||
}
|
||||
SwapIn(io, done);
|
||||
what = $"baked off-thread in {done.Ms:0.0} ms: {CountBaked()} fonts at scale {scale:0.##}, {done.Steps} enlarged size(s) in use, "
|
||||
+ $"icons {(_phosphor != null ? $"{IconCount()} merged" : "missing")}"
|
||||
+ (_symbolMerges > 0 ? $", Segoe UI Symbol merged into {_symbolMerges}" : "");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The swapped-in atlas's pixels as A8R8G8B8 rows, made by the bake worker, when they match
|
||||
/// <paramref name="width"/> x <paramref name="height"/>: the caller copies them into the texture
|
||||
/// and frees them with <see cref="FreeBgraPixels"/>. False (nothing to free) otherwise: the
|
||||
/// caller converts ImGui's RGBA itself. Either way the copy is no longer held here. Render thread.
|
||||
/// </summary>
|
||||
public static bool TakeBgraPixels(int width, int height, out IntPtr bgra)
|
||||
{
|
||||
bgra = _bgra;
|
||||
bool match = bgra != IntPtr.Zero && _bgraWidth == width && _bgraHeight == height;
|
||||
if (bgra != IntPtr.Zero && !match) FreeBgraPixels(bgra);
|
||||
_bgra = IntPtr.Zero;
|
||||
_bgraWidth = _bgraHeight = 0;
|
||||
if (!match) bgra = IntPtr.Zero;
|
||||
return match;
|
||||
}
|
||||
|
||||
public static void FreeBgraPixels(IntPtr bgra)
|
||||
{
|
||||
if (bgra != IntPtr.Zero) NativeMemory.Free((void*)bgra);
|
||||
}
|
||||
|
||||
private static void BakeWorker(float scale, List<int> steps, bool prepare)
|
||||
{
|
||||
var bake = new Bake { Steps = steps.Count };
|
||||
long t0 = Stopwatch.GetTimestamp();
|
||||
ImFontAtlas* atlas = null;
|
||||
try
|
||||
{
|
||||
// The first bake makes the native copies of the font files here; a re-bake finds
|
||||
// them made (PumpRebuild prepares them first). One bake runs at a time, and nothing
|
||||
// else touches them until it is joined (SwapFinished, WaitForWorkers).
|
||||
if (prepare)
|
||||
{
|
||||
PrepareNativeData();
|
||||
Compatibility.MemoryUse.Mark("font files read (bake worker)");
|
||||
}
|
||||
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 _);
|
||||
// The RGBA copy the texture is made from, and its BGRA rows for D3D9, here too:
|
||||
// the swap then only copies rows into the texture.
|
||||
ptr.GetTexDataAsRGBA32(out IntPtr rgba, out int w, out int h);
|
||||
if (rgba != IntPtr.Zero && w > 0 && h > 0)
|
||||
{
|
||||
bake.Bgra = (IntPtr)NativeMemory.Alloc((nuint)w * (nuint)h, 4);
|
||||
FontPixels.RgbaToBgra(new ReadOnlySpan<uint>((void*)rgba, w * h), new Span<uint>((void*)bake.Bgra, w * h));
|
||||
bake.Width = w;
|
||||
bake.Height = h;
|
||||
}
|
||||
// The glyphs are rasterized: the atlas's copies of the font files (~150 MB with
|
||||
// every size) are never read again (DX9Backend's note), so they go here, not on
|
||||
// AC's thread. The pixels and TexReady stay.
|
||||
ptr.ClearInputData();
|
||||
if (prepare) Compatibility.MemoryUse.Mark("font atlas baked (bake worker)");
|
||||
bake.Atlas = (IntPtr)atlas;
|
||||
atlas = null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
bake.Error = $"{ex.GetType().Name}: {ex.Message}";
|
||||
FreeBgraPixels(bake.Bgra);
|
||||
bake.Bgra = IntPtr.Zero;
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -496,6 +603,10 @@ internal static unsafe class ImGuiFonts
|
|||
Array.Copy(bake.Base, Fonts, Fonts.Length);
|
||||
ScaledFonts.Clear();
|
||||
foreach (KeyValuePair<int, ImFontPtr[]> kv in bake.Scaled) ScaledFonts[kv.Key] = kv.Value;
|
||||
FreeBgraPixels(_bgra); // a copy never uploaded (each swap is uploaded straight after)
|
||||
_bgra = bake.Bgra;
|
||||
_bgraWidth = bake.Width;
|
||||
_bgraHeight = bake.Height;
|
||||
ImGuiPopOuts.ReplaceFontAtlas((IntPtr)old, (IntPtr)fresh);
|
||||
if (old == null || old == fresh) return;
|
||||
IntPtr oldPtr = (IntPtr)old;
|
||||
|
|
@ -538,7 +649,11 @@ internal static unsafe class ImGuiFonts
|
|||
_bakeDone = null;
|
||||
if (pending != null && pending.Atlas != IntPtr.Zero)
|
||||
ImGuiNative.ImFontAtlas_destroy((ImFontAtlas*)pending.Atlas); // baked, never swapped in
|
||||
if (pending != null) FreeBgraPixels(pending.Bgra);
|
||||
}
|
||||
FreeBgraPixels(_bgra);
|
||||
_bgra = IntPtr.Zero;
|
||||
_bgraWidth = _bgraHeight = 0;
|
||||
foreach (IntPtr p in NativeBuffers)
|
||||
NativeMemory.Free((void*)p);
|
||||
NativeBuffers.Clear();
|
||||
|
|
|
|||
|
|
@ -118,6 +118,15 @@ internal interface IImGuiPanel
|
|||
/// </summary>
|
||||
bool ClickThroughWantsWheel => false;
|
||||
|
||||
/// <summary>
|
||||
/// True while the face shows a bare look (the Sense panel's compact view, 2026-10-31): docked,
|
||||
/// the host draws no header, frame, border, background or resize grip, so only what the face
|
||||
/// paints shows; with <see cref="ClickThrough"/> the rest passes clicks to the game. The window
|
||||
/// keeps its place and size for when the face is framed again. Popped out (an OS window of its
|
||||
/// own) and embedded copies are framed as usual. Answered by the face's last Draw; keep it cheap.
|
||||
/// </summary>
|
||||
bool Bare => false;
|
||||
|
||||
/// <summary>
|
||||
/// Popped out and not hovered or in use: how often the face is redrawn (Hz).
|
||||
/// Its pictures are only pushed when they change; this bounds the cost of
|
||||
|
|
@ -594,10 +603,14 @@ internal static class ImGuiPanelHost
|
|||
/// </summary>
|
||||
public static void DrawAll(float uiScale)
|
||||
{
|
||||
// UiCost: each panel by its title; the rest of DrawAll as the host's upkeep.
|
||||
long cHost = UiCost.Start(), costMark = UiCost.Mark;
|
||||
int drawn = 0;
|
||||
_frameScale = uiScale;
|
||||
WheelWanted = false;
|
||||
float placeScale = PlacementScale();
|
||||
ApplyFaceChanges(placeScale); // plugin windows taking over (or giving back) engine panels
|
||||
ApplyLayoutSwitch(placeScale); // another character's panel layout (UI/PanelLayout)
|
||||
while (Requests.TryDequeue(out var req))
|
||||
Apply(req.Title, req.Kind, placeScale);
|
||||
RemoveUnregistered();
|
||||
|
|
@ -614,9 +627,13 @@ internal static class ImGuiPanelHost
|
|||
if (_resizeTitle == entry.Title) _resizeTitle = null; // hid mid-resize: free the grip
|
||||
continue;
|
||||
}
|
||||
long cPanel = UiCost.Start();
|
||||
DrawPanel(entry, uiScale, placeScale, null);
|
||||
UiCost.StopPanel(entry.Title, cPanel);
|
||||
drawn++;
|
||||
}
|
||||
DrawSizeNote();
|
||||
UiCost.StopExclusive(UiCost.PanelHost, cHost, costMark, cHost != 0 ? drawn : -1);
|
||||
}
|
||||
|
||||
// ── One way to resize every panel (Tom 2026-10-23) ───────────────────
|
||||
|
|
@ -680,7 +697,9 @@ internal static class ImGuiPanelHost
|
|||
lock (Sync) Entries.TryGetValue(title, out entry);
|
||||
if (entry == null || !entry.Shown || !entry.Popped) return;
|
||||
_frameScale = uiScale;
|
||||
long cPanel = UiCost.Start();
|
||||
DrawPanel(entry, uiScale, PlacementScale(), display);
|
||||
UiCost.StopPopped(entry.Title, cPanel);
|
||||
}
|
||||
|
||||
/// <summary>A pop-out window was moved or resized by the user: save it. Game thread.</summary>
|
||||
|
|
@ -703,6 +722,12 @@ internal static class ImGuiPanelHost
|
|||
_restored = true;
|
||||
// Settings > Display "Remember Open Windows and Positions" (default on).
|
||||
if (!Plugins.EngineSettings.RememberWindowLayout) return;
|
||||
OpenSavedOpen();
|
||||
}
|
||||
|
||||
/// <summary>Opens the engine panels the panel store has saved open (ImGui or Both docked face). AC thread.</summary>
|
||||
private static void OpenSavedOpen()
|
||||
{
|
||||
List<string> titles = new();
|
||||
// Script windows (dynamic) open when their owner says so, not from the saved state.
|
||||
lock (Sync)
|
||||
|
|
@ -719,6 +744,77 @@ internal static class ImGuiPanelHost
|
|||
}
|
||||
}
|
||||
|
||||
// ── Panel layout per character (UI/PanelLayout) ───────────────────────
|
||||
|
||||
private static volatile bool _layoutSwitched;
|
||||
|
||||
/// <summary>
|
||||
/// The panel store now holds another layout (another character's, the default, or a reset): the
|
||||
/// open panels take their places from it at the next DrawAll. Any thread.
|
||||
/// </summary>
|
||||
public static void OnLayoutSwitched() => _layoutSwitched = true;
|
||||
|
||||
/// <summary>
|
||||
/// After a layout switch: each shown panel is placed from the new layout (docked spot and size, popped
|
||||
/// out or not, and where); an engine panel the layout has saved closed closes, without saving over
|
||||
/// it; engine panels it has saved open open. Plugin and script windows stay open (their owners
|
||||
/// decide that) and move. Nothing shown (a hot reload, the first login): only the opening. AC thread.
|
||||
/// </summary>
|
||||
private static void ApplyLayoutSwitch(float placeScale)
|
||||
{
|
||||
if (!_layoutSwitched) return;
|
||||
_layoutSwitched = false;
|
||||
bool remember = Plugins.EngineSettings.RememberWindowLayout;
|
||||
List<Entry> order;
|
||||
lock (Sync) order = DrawOrder;
|
||||
foreach (Entry e in order)
|
||||
{
|
||||
if (!e.Shown) continue;
|
||||
bool has = PanelStateStore.TryGetPanel(e.Title, out PanelStateStore.PanelEntry saved);
|
||||
if (!e.Dynamic && remember && has && !saved.Open)
|
||||
{
|
||||
CloseQuietly(e);
|
||||
continue;
|
||||
}
|
||||
if (e.Popped)
|
||||
{
|
||||
ImGuiPopOuts.Close(e.Title);
|
||||
e.Popped = false;
|
||||
}
|
||||
PlaceFromSavedState(e, placeScale);
|
||||
if (PanelRouter.CanPopOut && !e.Spec.NoPopOut && has && saved.Floating)
|
||||
StartPopOut(e, placeScale, fromSaved: true);
|
||||
else if (!has)
|
||||
Persist(e, open: true, placeScale); // new to this layout: saved here, so it reopens here
|
||||
}
|
||||
if (remember) OpenSavedOpen(); // queued; applied by this DrawAll (an open one is skipped)
|
||||
RynthLog.UI("ImGuiPanelHost: the open panels took their places from the panel layout now in use.");
|
||||
}
|
||||
|
||||
/// <summary>Closes a shown face without saving its placement (the layout it came from isn't in use any more). AC thread.</summary>
|
||||
private static void CloseQuietly(Entry entry)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
if (_open.Contains(entry.Title))
|
||||
{
|
||||
var next = new HashSet<string>(_open, StringComparer.OrdinalIgnoreCase);
|
||||
next.Remove(entry.Title);
|
||||
System.Threading.Volatile.Write(ref _open, next);
|
||||
}
|
||||
}
|
||||
if (entry.Popped)
|
||||
{
|
||||
ImGuiPopOuts.Close(entry.Title);
|
||||
entry.Popped = false;
|
||||
}
|
||||
try { entry.Instance?.OnHidden(); }
|
||||
catch (Exception ex) { RynthLog.UI($"ImGuiPanelHost: {entry.Title}.OnHidden threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
entry.Instance = null;
|
||||
entry.Shown = false;
|
||||
System.Threading.Interlocked.Decrement(ref _shownCount);
|
||||
}
|
||||
|
||||
/// <summary>Client pixels per logical unit (the unit PanelSpec sizes, MinSize and RequestSize use).</summary>
|
||||
internal static float PlacementScale()
|
||||
{
|
||||
|
|
@ -1006,7 +1102,10 @@ internal static class ImGuiPanelHost
|
|||
{
|
||||
PanelSpec spec = entry.Spec;
|
||||
bool popped = popDisplay.HasValue;
|
||||
bool standard = spec.Chrome == PanelChrome.Standard;
|
||||
// A bare face (IImGuiPanel.Bare): docked, no frame of any kind, only what it paints.
|
||||
bool bare = false;
|
||||
if (!popped) try { bare = entry.Instance?.Bare ?? false; } catch { }
|
||||
bool standard = spec.Chrome == PanelChrome.Standard && !bare;
|
||||
bool both = PanelRouter.ResolveDockedFace(entry.Title) == PanelFace.Both;
|
||||
|
||||
Vector2 minSize = (entry.Instance?.MinSize ?? spec.MinSize) * placeScale;
|
||||
|
|
@ -1071,10 +1170,10 @@ internal static class ImGuiPanelHost
|
|||
ImGuiNET.ImGui.SetNextWindowSizeConstraints(minSize, new Vector2(float.MaxValue, float.MaxValue));
|
||||
}
|
||||
|
||||
uint background = spec.Background ?? RynthTheme.PanelGlass;
|
||||
uint background = bare ? 0u : spec.Background ?? RynthTheme.PanelGlass;
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, spec.Rounding);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, spec.Chrome == PanelChrome.None ? 0f : 1f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, spec.Chrome == PanelChrome.None || bare ? 0f : 1f);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, background);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, spec.BorderColor ?? RynthTheme.PanelBorder);
|
||||
|
||||
|
|
@ -1113,7 +1212,7 @@ internal static class ImGuiPanelHost
|
|||
// the same way, over the corner the face leaves free.
|
||||
bool inlineGrip = standard && spec.GripInBody;
|
||||
bool manualGrip = (!standard || inlineGrip) && !clickThrough && !popped // popped: the window resizes itself
|
||||
&& !spec.NoResize;
|
||||
&& !spec.NoResize && !bare; // bare: sized while framed
|
||||
Vector2 outerPos = ImGuiNET.ImGui.GetWindowPos(), outerSize = ImGuiNET.ImGui.GetWindowSize();
|
||||
float gSize = GripSize(entry, uiScale);
|
||||
Vector2 gMin = GripMin(entry, uiScale, outerPos + outerSize);
|
||||
|
|
@ -1271,6 +1370,9 @@ internal static class ImGuiPanelHost
|
|||
/// <summary>True while an embedded copy draws: its window moves and size requests are ignored.</summary>
|
||||
[ThreadStatic] private static bool _inEmbed;
|
||||
|
||||
/// <summary>True while an embedded copy of a face draws (inside another panel's section). AC thread.</summary>
|
||||
internal static bool DrawingEmbedded => _inEmbed;
|
||||
|
||||
/// <summary>True when <paramref name="title"/> is registered and may be drawn inside another panel. Any thread.</summary>
|
||||
public static bool CanEmbed(string title) => !NotEmbeddable.Contains(title) && HasFace(title);
|
||||
|
||||
|
|
|
|||
|
|
@ -432,7 +432,10 @@ internal static unsafe class ImGuiPopOuts
|
|||
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;
|
||||
// UiCost: the window's own frame, render and present; its panel is timed by the host.
|
||||
long cPop = UiCost.Start(), costMark = UiCost.Mark;
|
||||
RenderOne(device, pop, uiScale, now);
|
||||
UiCost.StopPopOutWindow(pop.Title, cPop, costMark);
|
||||
}
|
||||
}
|
||||
finally
|
||||
|
|
|
|||
194
src/RynthCore.Engine/ImGui/MonsterHud/HealthProbe.cs
Normal file
194
src/RynthCore.Engine/ImGui/MonsterHud/HealthProbe.cs
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/MonsterHud/HealthProbe.cs
|
||||
// Fresh health for the monster plates that are NOT the selected / queried
|
||||
// target (2026-10-31: "only the selected monster's plate keeps updating; the
|
||||
// others show a number that stops changing while they take damage").
|
||||
//
|
||||
// Why they froze: ACE sends a creature's health (0x01C0 UpdateHealth) only
|
||||
// to players whose current health-query target it is (Player.HandleAction-
|
||||
// QueryHealth -> UpdateSelectedTarget; Creature.OnHealthUpdate walks that
|
||||
// creature's selectedTargets). One target per player: every QueryHealth
|
||||
// moves the stream. So a plate got one value when it was selected / queried /
|
||||
// appraised and then nothing, and CleaveHealth estimates only cover the
|
||||
// player's own weapon hits (no other players, pets, procs or DoTs).
|
||||
//
|
||||
// The fix: the HUD asks for them, slowly. At most one probe per interval
|
||||
// (setting, default 1 s), and each probe is immediately followed by a query
|
||||
// for the stream's owner (the last target a plugin or the selection asked
|
||||
// for), so the selected / fight target keeps its live stream. Cost per probe:
|
||||
// two 0x01BF game actions up, two 0x01C0 replies down (well under 100 bytes).
|
||||
//
|
||||
// Who is probed (Pick): plates on screen, not the stream owner, not dead.
|
||||
// 1. "active" plates (hurt, hit by you, or hitting you) whose last server
|
||||
// reading is ActiveRefreshSec old or more, the stalest first;
|
||||
// 2. plates never read by the server, nearest first (one probe each);
|
||||
// 3. quiet plates whose reading is IdleRefreshSec old or more.
|
||||
// Nothing due: no traffic.
|
||||
//
|
||||
// A probe's reply is the HUD's: PluginManager records it for the plates but
|
||||
// does not hand it to plugins (IsProbeReply), so a bot never reads another
|
||||
// player's damage on a monster it isn't fighting as its own hit.
|
||||
//
|
||||
// Pick and the ledger are pure (time is passed in); compiled into
|
||||
// tools/CleaveGhostTests. Engine-owned statics only.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Hud;
|
||||
|
||||
internal static class HealthProbe
|
||||
{
|
||||
/// <summary>A plate in the fight is re-read when its last server reading is this old (s).</summary>
|
||||
public const double ActiveRefreshSec = 2.0;
|
||||
/// <summary>A quiet plate (full health, nobody fighting it) is re-read this rarely (s).</summary>
|
||||
public const double IdleRefreshSec = 12.0;
|
||||
/// <summary>A 0x01C0 for a probed id this soon after the probe (ms) is the probe's reply.</summary>
|
||||
public const long ReplyWindowMs = 2000;
|
||||
|
||||
/// <summary>The setting's range and default: seconds between two probes.</summary>
|
||||
public const float DefaultIntervalSec = 1.0f, MinIntervalSec = 0.5f, MaxIntervalSec = 5.0f;
|
||||
|
||||
/// <summary>
|
||||
/// One plate. <paramref name="Seen"/>: the server has sent its health at least once;
|
||||
/// <paramref name="ServerAgeSec"/>: seconds since that last server reading (estimates don't count).
|
||||
/// <paramref name="Active"/>: hurt, hit by the player or hitting the player recently.
|
||||
/// <paramref name="Dead"/>: its last reading was 0.
|
||||
/// </summary>
|
||||
public readonly record struct Candidate(uint Id, float Distance, bool Seen, double ServerAgeSec, bool Active, bool Dead = false);
|
||||
|
||||
/// <summary>The plate to probe now, or 0 when none is due. <paramref name="owner"/> is never picked (it is streamed).</summary>
|
||||
public static uint Pick(ReadOnlySpan<Candidate> candidates, uint owner)
|
||||
{
|
||||
uint best = 0;
|
||||
int bestTier = -1;
|
||||
double bestScore = double.NegativeInfinity;
|
||||
float bestD = float.MaxValue;
|
||||
foreach (Candidate c in candidates)
|
||||
{
|
||||
if (c.Id == 0 || c.Id == owner || c.Dead) continue;
|
||||
int tier;
|
||||
double score;
|
||||
if (c.Active)
|
||||
{
|
||||
if (c.Seen && !(c.ServerAgeSec >= ActiveRefreshSec)) continue;
|
||||
tier = 2;
|
||||
score = c.Seen ? c.ServerAgeSec / ActiveRefreshSec : double.MaxValue;
|
||||
}
|
||||
else if (!c.Seen)
|
||||
{
|
||||
tier = 1;
|
||||
score = 0; // all equal: the nearest wins
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!(c.ServerAgeSec >= IdleRefreshSec)) continue;
|
||||
tier = 0;
|
||||
score = c.ServerAgeSec / IdleRefreshSec;
|
||||
}
|
||||
bool better = tier > bestTier ||
|
||||
(tier == bestTier && (score > bestScore || (score == bestScore && c.Distance < bestD)));
|
||||
if (!better) continue;
|
||||
best = c.Id; bestTier = tier; bestScore = score; bestD = c.Distance;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// ── The server's health stream: whose it is, and which replies are the HUD's ──
|
||||
|
||||
private static readonly object Sync = new();
|
||||
private static uint _owner;
|
||||
private static bool _ownerKnown;
|
||||
private const int MaxPending = 8;
|
||||
private static readonly uint[] PendingId = new uint[MaxPending];
|
||||
private static readonly long[] PendingAt = new long[MaxPending];
|
||||
private static readonly bool[] PendingSticky = new bool[MaxPending];
|
||||
private static int _pendingNext;
|
||||
private static long _probes;
|
||||
|
||||
/// <summary>Probes sent since the engine started (status line).</summary>
|
||||
public static long ProbeCount => Interlocked.Read(ref _probes);
|
||||
|
||||
/// <summary>
|
||||
/// A health query that is not the HUD's went out for <paramref name="id"/> (a plugin's QueryHealth,
|
||||
/// or the client's own on a selection change): the server streams that id now, and its replies
|
||||
/// belong to whoever asked. Any thread.
|
||||
/// </summary>
|
||||
public static void NoteQuery(uint id)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
_owner = id;
|
||||
_ownerKnown = true;
|
||||
// The stream moved: a sticky probe (sent with no owner to hand back to) no longer streams,
|
||||
// and the newly queried id's replies are the asker's.
|
||||
for (int i = 0; i < MaxPending; i++)
|
||||
if (PendingId[i] == id || PendingSticky[i]) { PendingId[i] = 0; PendingSticky[i] = false; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The id the server streams health for (see NoteQuery); false before anything was noted.</summary>
|
||||
public static bool TryGetOwner(out uint owner)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
owner = _owner;
|
||||
return _ownerKnown;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The HUD probed <paramref name="id"/> at <paramref name="nowMs"/>. <paramref name="sticky"/>: no owner was
|
||||
/// queried after it, so the server keeps streaming this id to us: every reply for it is the HUD's until
|
||||
/// the next NoteQuery (no ReplyWindowMs).
|
||||
/// </summary>
|
||||
public static void NoteProbe(uint id, long nowMs, bool sticky = false)
|
||||
{
|
||||
if (id == 0) return;
|
||||
lock (Sync)
|
||||
{
|
||||
int slot = -1;
|
||||
for (int i = 0; i < MaxPending; i++)
|
||||
if (PendingId[i] == id) { slot = i; break; }
|
||||
if (slot < 0) { slot = _pendingNext; _pendingNext = (_pendingNext + 1) % MaxPending; }
|
||||
PendingId[slot] = id;
|
||||
PendingAt[slot] = nowMs;
|
||||
PendingSticky[slot] = sticky;
|
||||
_probes++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when a health reply for <paramref name="id"/> answers a HUD probe (sent within ReplyWindowMs).</summary>
|
||||
public static bool IsProbeReply(uint id, long nowMs)
|
||||
{
|
||||
if (id == 0) return false;
|
||||
lock (Sync)
|
||||
{
|
||||
if (_ownerKnown && id == _owner) return false; // someone else asked for it too
|
||||
for (int i = 0; i < MaxPending; i++)
|
||||
if (PendingId[i] == id)
|
||||
{
|
||||
if (PendingSticky[i]) return true;
|
||||
long age = nowMs - PendingAt[i];
|
||||
if (age >= 0 && age <= ReplyWindowMs) return true;
|
||||
PendingId[i] = 0; // expired
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Logout / character switch: nothing carries over.</summary>
|
||||
public static void Reset()
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
_owner = 0;
|
||||
_ownerKnown = false;
|
||||
Array.Clear(PendingId);
|
||||
Array.Clear(PendingSticky);
|
||||
_pendingNext = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -288,6 +288,7 @@ internal static class MonsterHud
|
|||
if (track) Snapshot(now, trackMonsters);
|
||||
}
|
||||
if (monsters) ApplyDealtHits(now);
|
||||
if (monsters && MonsterHudSettings.RefreshOthersHealth) ProbeHealth(now);
|
||||
|
||||
_hasContent = Plates.Count > 0 || MonsterHudSettings.SelfPlate || CombatText.HasContent;
|
||||
}
|
||||
|
|
@ -316,6 +317,8 @@ internal static class MonsterHud
|
|||
{
|
||||
ClearPlates();
|
||||
MonsterHudData.Clear();
|
||||
HealthProbe.Reset();
|
||||
_nextProbeTicks = 0;
|
||||
PlateDebuffs.Clear();
|
||||
CombatText.Clear();
|
||||
PlayerPlate.Reset();
|
||||
|
|
@ -1590,6 +1593,45 @@ internal static class MonsterHud
|
|||
}
|
||||
}
|
||||
|
||||
// ── Health for the plates the server isn't streaming (HealthProbe) ──
|
||||
private static readonly List<HealthProbe.Candidate> ProbeCandidates = new();
|
||||
private static long _nextProbeTicks;
|
||||
/// <summary>"Hit by you" keeps a plate in the fight this long (s) for the probe's refresh.</summary>
|
||||
private const double ProbeHitMemorySec = 30;
|
||||
|
||||
/// <summary>
|
||||
/// At most one health query per "Refresh others' health" interval for an on-screen plate the server
|
||||
/// isn't streaming, then one for the stream's owner so the selected / fight target keeps its feed.
|
||||
/// AC's main thread only (both sends go out back to back, in order); skipped otherwise and in a
|
||||
/// death / portal / login window.
|
||||
/// </summary>
|
||||
private static void ProbeHealth(long now)
|
||||
{
|
||||
if (now < _nextProbeTicks || Plates.Count == 0) return;
|
||||
float interval = Math.Clamp(MonsterHudSettings.HealthRefreshSec, HealthProbe.MinIntervalSec, HealthProbe.MaxIntervalSec);
|
||||
_nextProbeTicks = now + (long)(interval * Stopwatch.Frequency);
|
||||
if (!CombatActionHooks.HasQueryHealth || AcMainThreadQueue.MustQueue(teardown: false)) return;
|
||||
|
||||
if (!HealthProbe.TryGetOwner(out uint owner)) owner = ClientHelperHooks.GetSelectedItemId();
|
||||
double freq = Stopwatch.Frequency;
|
||||
long hitWindow = (long)(ProbeHitMemorySec * freq);
|
||||
ProbeCandidates.Clear();
|
||||
foreach (Plate p in Plates.Values)
|
||||
{
|
||||
if (p.IsLabel || p.Gone || !p.OnScreen || p.Alpha < 0.01f || p.Id == _playerId) continue;
|
||||
bool has = MonsterHudData.TryGetHealth(p.Id, out HealthObservation h);
|
||||
bool seen = has && h.ServerTicks != 0;
|
||||
long lastHit = CombatText.LastHitTicks(p.Id);
|
||||
bool active = p.IsAttacker || (has && (h.Ratio < 0.999f || h.Estimated)) ||
|
||||
(lastHit != long.MinValue && now - lastHit < hitWindow);
|
||||
ProbeCandidates.Add(new HealthProbe.Candidate(p.Id, p.Distance, seen, seen ? (now - h.ServerTicks) / freq : 0,
|
||||
active, Dead: seen && h.Ratio <= 0.001f));
|
||||
}
|
||||
uint id = HealthProbe.Pick(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(ProbeCandidates), owner);
|
||||
if (id == 0) return;
|
||||
CombatActionHooks.SendHudHealthProbe(id, owner, Environment.TickCount64);
|
||||
}
|
||||
|
||||
internal static uint FindPlateByName(string name)
|
||||
{
|
||||
uint target = ClientHelperHooks.GetSelectedItemId();
|
||||
|
|
@ -1696,7 +1738,9 @@ internal static class MonsterHud
|
|||
$"name labels {labels} ({labelsOnScreen} on screen, {portals} portals), {Classes.Count} objects classified; " +
|
||||
$"camera {(GameMatrixCapture.HasCapturedFrame ? "captured" : "not captured")} " +
|
||||
$"(frame lb 0x{GameMatrixCapture.FrameLandblock:X4}, viewport {GameMatrixCapture.ViewportWidth}x{GameMatrixCapture.ViewportHeight}); " +
|
||||
$"weakness data {(_weakByWcid.Count + _weakByName.Count > 0 ? "loaded" : "none")}.",
|
||||
$"weakness data {(_weakByWcid.Count + _weakByName.Count > 0 ? "loaded" : "none")}; " +
|
||||
$"others' health refresh {(MonsterHudSettings.RefreshOthersHealth ? $"on, every {MonsterHudSettings.HealthRefreshSec:0.0#} s" : "off")} " +
|
||||
$"({HealthProbe.ProbeCount} quer{(HealthProbe.ProbeCount == 1 ? "y" : "ies")} sent).",
|
||||
PlateDebuffs.Describe(),
|
||||
PlayerPlate.Describe() + " " + CombatText.Describe(),
|
||||
AcMouseOver.Describe(),
|
||||
|
|
|
|||
|
|
@ -23,8 +23,10 @@ using System.Diagnostics;
|
|||
namespace RynthCore.Engine.ImGuiBackend.Hud;
|
||||
|
||||
/// <summary>Last health observation for one object. <paramref name="Prev"/>: the ratio before it
|
||||
/// (-1 = first). <paramref name="Estimated"/>: worked out from a hit (CleaveHealth), not sent by the server.</summary>
|
||||
internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks, float Prev = -1f, bool Estimated = false);
|
||||
/// (-1 = first). <paramref name="Estimated"/>: worked out from a hit (CleaveHealth), not sent by the server.
|
||||
/// <paramref name="ServerTicks"/>: when the server last sent this object's health (0 = never; estimates keep it).</summary>
|
||||
internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks, float Prev = -1f, bool Estimated = false,
|
||||
long ServerTicks = 0);
|
||||
|
||||
internal static class MonsterHudData
|
||||
{
|
||||
|
|
@ -58,7 +60,8 @@ internal static class MonsterHudData
|
|||
}
|
||||
if (Health.Count >= MaxHealthEntries && !Health.ContainsKey(id))
|
||||
Health.Clear();
|
||||
Health[id] = new HealthObservation(ratio, current, max, now, before, estimated);
|
||||
long serverTicks = estimated ? (had ? prev.ServerTicks : 0) : now;
|
||||
Health[id] = new HealthObservation(ratio, current, max, now, before, estimated, serverTicks);
|
||||
}
|
||||
// An estimate never kills (CleaveHealth keeps it above 0) and the server correcting one
|
||||
// isn't a heal: the combat text sees an estimate's successor as a first observation.
|
||||
|
|
|
|||
|
|
@ -49,6 +49,14 @@ internal static class MonsterHudSettings
|
|||
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;
|
||||
/// <summary>
|
||||
/// "Refresh others' health" (2026-10-31): the server streams health only for the selected / queried
|
||||
/// monster, so the HUD asks for the other plates' health itself, one monster per HealthRefreshSec
|
||||
/// (HealthProbe). Off: only the selected / queried monster's plate is live.
|
||||
/// </summary>
|
||||
public static bool RefreshOthersHealth = true;
|
||||
/// <summary>Seconds between two of those health queries (HealthProbe's range).</summary>
|
||||
public static float HealthRefreshSec = HealthProbe.DefaultIntervalSec;
|
||||
|
||||
// Name-only labels over NPCs (vendors in gold) and, optionally, other players.
|
||||
// Counted apart from MaxPlates so they never push a monster plate out.
|
||||
|
|
@ -220,6 +228,10 @@ internal static class MonsterHudSettings
|
|||
case "scale": if (TryF(val, out float s)) Scale = Math.Clamp(s, MinScale, MaxScale); break;
|
||||
case "opacity": if (TryF(val, out float o)) Opacity = Math.Clamp(o, MinOpacity, MaxOpacity); break;
|
||||
case "clickSelect": ClickToSelect = val == "1"; break;
|
||||
case "refreshOthersHealth": RefreshOthersHealth = val == "1"; break;
|
||||
case "healthRefreshSec":
|
||||
if (TryF(val, out float hr)) HealthRefreshSec = Math.Clamp(hr, HealthProbe.MinIntervalSec, HealthProbe.MaxIntervalSec);
|
||||
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;
|
||||
|
|
@ -339,6 +351,8 @@ internal static class MonsterHudSettings
|
|||
sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}"));
|
||||
sw.WriteLine($"clickSelect={B(ClickToSelect)}");
|
||||
sw.WriteLine($"refreshOthersHealth={B(RefreshOthersHealth)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"healthRefreshSec={HealthRefreshSec:0.##}"));
|
||||
sw.WriteLine($"npcNames={B(NpcNames)}");
|
||||
sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}"));
|
||||
sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}"));
|
||||
|
|
@ -397,6 +411,7 @@ internal static class MonsterHudSettings
|
|||
Enabled = true; MaxDistance = 35f; MaxPlates = 20; Filter = PlateFilter.All;
|
||||
ShowNames = true; ShowHpNumbers = true; ShowDistance = false; ShowLevel = true; ShowWeakness = true;
|
||||
FadeWithDistance = true; Scale = 1.0f; Opacity = 0.9f; HeightLift = 0f; ClickToSelect = true;
|
||||
RefreshOthersHealth = true; HealthRefreshSec = HealthProbe.DefaultIntervalSec;
|
||||
ShowDebuffs = true; ShowOthersDebuff = true;
|
||||
NpcNames = true; NpcMaxDistance = 30f; MaxNpcLabels = 15; PlayerNames = false; PlayerBars = false;
|
||||
PortalNames = true; PortalMaxDistance = DefaultPortalDistance;
|
||||
|
|
@ -462,7 +477,8 @@ internal static class MonsterHudSettings
|
|||
$"RynthVision nameplates: monsters {(Enabled ? "ON" : "OFF")} ({(Filter == PlateFilter.Engaged ? "engaged only" : "all monsters")}, " +
|
||||
$"{MaxDistance:0}yd, max {MaxPlates}, scale {Scale:0.##}, opacity {Opacity:0.##}, lift {HeightLift:0.#}m; " +
|
||||
$"names {OnOff(ShowNames)}, hp {OnOff(ShowHpNumbers)}, level {OnOff(ShowLevel)}, weak {OnOff(ShowWeakness)}, " +
|
||||
$"distance {OnOff(ShowDistance)}, fade {OnOff(FadeWithDistance)}, click to select {OnOff(ClickToSelect)}), debuffs {OnOff(ShowDebuffs)} (others {OnOff(ShowOthersDebuff)}); " +
|
||||
$"distance {OnOff(ShowDistance)}, fade {OnOff(FadeWithDistance)}, click to select {OnOff(ClickToSelect)}, " +
|
||||
$"refresh others' health {(RefreshOthersHealth ? $"every {HealthRefreshSec:0.0#} s" : "off")}), debuffs {OnOff(ShowDebuffs)} (others {OnOff(ShowOthersDebuff)}); " +
|
||||
$"NPC names {OnOff(NpcNames)} ({NpcMaxDistance:0}yd, max {MaxNpcLabels}), player names {OnOff(PlayerNames)} (bars {OnOff(PlayerBars)}), " +
|
||||
$"portal names {OnOff(PortalNames)} ({PortalMaxDistance:0}yd); " +
|
||||
$"self {OnOff(SelfPlate)} ({(SelfPlacement == SelfPlacement.Fixed ? "fixed on screen, " + (SelfLocked ? "locked" : "unlocked") : "follows you, " + SelfPosition.ToString().ToLowerInvariant())}, " +
|
||||
|
|
|
|||
|
|
@ -67,6 +67,14 @@ internal static class MonsterHudSettingsUi
|
|||
MonsterHudSettings.MinDistance, MonsterHudSettings.MaxDistanceLimit, "%.0f", w);
|
||||
changed |= SliderI("Max plates", ref MonsterHudSettings.MaxPlates,
|
||||
MonsterHudSettings.MinPlates, MonsterHudSettings.MaxPlatesLimit, w);
|
||||
changed |= Toggle("Refresh others' health", ref MonsterHudSettings.RefreshOthersHealth,
|
||||
"The server only keeps the selected (or fought) monster's health up to date. On: the HUD also asks for " +
|
||||
"the other plates' health, one monster at a time - first the ones in the fight, then any it hasn't seen - " +
|
||||
"and hands the live feed straight back to your target. Two small queries per refresh. " +
|
||||
"Off: only your target's plate is live. Chat: /rv plates refresh [on|off], /rv plates refresh <seconds>.");
|
||||
if (MonsterHudSettings.RefreshOthersHealth)
|
||||
changed |= SliderF("Refresh every (s)", ref MonsterHudSettings.HealthRefreshSec,
|
||||
HealthProbe.MinIntervalSec, HealthProbe.MaxIntervalSec, "%.1f s", w);
|
||||
|
||||
Section("On the plate", w);
|
||||
changed |= Toggle("Name", ref MonsterHudSettings.ShowNames, null);
|
||||
|
|
|
|||
|
|
@ -14,7 +14,8 @@
|
|||
// 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
|
||||
// from it: move / copy lines like it to a tab, hide them, colour or highlight
|
||||
// them (a "Highlight line" rule: a band behind the whole line). A line
|
||||
// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go
|
||||
// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them). The
|
||||
// coordinates are also drawn as underlined links: click points RynthNav's
|
||||
|
|
@ -638,6 +639,10 @@ internal sealed class ChatFace : IImGuiPanel
|
|||
Vector2 p = basePos + new Vector2(0, _tops[i]);
|
||||
ChatLine line = _vis[i];
|
||||
ChatRoute route = line.Route;
|
||||
// A "Highlight line" rule: a band behind all of the line's rows, under the mention
|
||||
// tint and the selection. One rect, no allocation; _h[i] already spans every row.
|
||||
if (route.HighlightArgb is uint band)
|
||||
dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), RynthTheme.Argb(ChatColorModes.BandArgb(band)));
|
||||
if (route.Mention)
|
||||
dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), MentionBg);
|
||||
if (lo >= 0 && i >= lo && i <= hi)
|
||||
|
|
@ -1065,15 +1070,17 @@ internal sealed class ChatFace : IImGuiPanel
|
|||
|
||||
// ── Rules from a line ────────────────────────────────────────────────
|
||||
|
||||
private void RuleFromLine(ChatRuleAction action, string? tab)
|
||||
private void RuleFromLine(ChatRuleAction action, string? tab, ChatColorMode colour = ChatColorMode.Line)
|
||||
{
|
||||
var rule = new ChatFilterRule { Pattern = _ctxPattern, Action = action, Tab = tab ?? "" };
|
||||
if (action == ChatRuleAction.Color)
|
||||
{
|
||||
rule.ColorMode = ChatColorMode.Line;
|
||||
rule.ColorMode = colour;
|
||||
ChatModel.AddRule(rule);
|
||||
if (!ImGuiPanelHost.IsOpen("ChatFilters")) PanelRouter.Toggle("ChatFilters");
|
||||
Flash("Rule added - pick its colour in Filters");
|
||||
Flash(colour == ChatColorMode.Highlight
|
||||
? "Rule added: lines like this are highlighted - pick its colour in Filters"
|
||||
: "Rule added - pick its colour in Filters");
|
||||
return;
|
||||
}
|
||||
ChatModel.AddRule(rule);
|
||||
|
|
@ -1486,6 +1493,7 @@ internal sealed class ChatFace : IImGuiPanel
|
|||
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);
|
||||
if (ImGuiNET.ImGui.MenuItem("Highlight them…")) RuleFromLine(ChatRuleAction.Color, null, ChatColorMode.Highlight);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters"))
|
||||
PanelRouter.Toggle("ChatFilters");
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
//
|
||||
// [#] [on] [Contains v] [pattern ...................] [up] [down] [delete]
|
||||
// When [Any line v] [Move to v] [Junk v] [Colour line v] [swatch]
|
||||
// (colour: No colour / Colour line / Colour match / Highlight line)
|
||||
// (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
|
||||
|
|
@ -84,7 +85,15 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
"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" };
|
||||
// Indexed by ChatColorMode.
|
||||
private static readonly string[] ColorLabels = { "No colour", "Colour line", "Colour match", "Highlight line" };
|
||||
private static readonly string[] ColorHelp =
|
||||
{
|
||||
"No colour: the rule doesn't colour the line.",
|
||||
"Colour line: the whole line's text in this colour.",
|
||||
"Colour match: just the text the rule matched, in this colour.",
|
||||
"Highlight line: a band in this colour behind the whole line; the text keeps its colour.",
|
||||
};
|
||||
private static readonly string[] ModeHelp =
|
||||
{
|
||||
"Regex: a case-insensitive regular expression (^ start, $ end, \\d+ a number...).",
|
||||
|
|
@ -116,7 +125,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
Label("Rules run top to bottom (" + PhosphorIcons.ArrowUp + PhosphorIcons.ArrowDown + " to reorder) on each line's text: plain text (any case) or a 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);
|
||||
Label("Colour: the first \"Colour line\" wins, and the first \"Highlight line\"; \"Colour match\" colours every match (a higher rule wins an overlap).", Mute);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
|
||||
|
||||
|
|
@ -346,7 +355,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
|
||||
if (r.Action != ChatRuleAction.Hide)
|
||||
{
|
||||
int mode = (int)r.ColorMode;
|
||||
int mode = Math.Clamp((int)r.ColorMode, 0, ColorLabels.Length - 1);
|
||||
string colText = ColorLabels[mode] + Caret;
|
||||
Vector2 cPos = flow.Place(ButtonWidth(colText));
|
||||
if (Button("##colmode", colText, cPos, new Vector2(ButtonWidth(colText), rowH), Text, BtnFill))
|
||||
|
|
@ -354,8 +363,8 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
{
|
||||
rule.ColorMode = (ChatColorMode)k;
|
||||
ChatModel.FiltersChanged();
|
||||
}, 130);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Colour line: the whole line. Colour match: just the text the rule matched.");
|
||||
}, 140);
|
||||
SafeImGui.SetItemTooltip(ColorHelp[mode]);
|
||||
if (r.ColorMode != ChatColorMode.None)
|
||||
{
|
||||
Vector2 sPos = flow.Place(rowH);
|
||||
|
|
@ -629,6 +638,9 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
}
|
||||
uint color = RynthTheme.Argb(ChatLineColors.Resolve(route.LineArgb, ChatLineColors.KindOf(type, channel, text), channel, type));
|
||||
_testResult.Add((where + (route.LineArgb != null ? " (this is its colour)" : ""), route.Hidden ? Faded(Mute) : color));
|
||||
if (!route.Hidden && route.HighlightArgb is uint band)
|
||||
_testResult.Add(($"Highlighted: a {ChatModel.FormatColor(band | 0xFF000000)} band behind the line (this colour).",
|
||||
RynthTheme.Argb(band | 0xFF000000)));
|
||||
|
||||
// Not hidden: name a standard filter that would hide it (one not in the rules yet).
|
||||
if (!route.Hidden)
|
||||
|
|
|
|||
|
|
@ -7,7 +7,9 @@
|
|||
// UiSources.LootEdit, shared with the Loot Editor): each rule
|
||||
// with its on/off gem, its action (Keep, Keep #, Salvage,
|
||||
// Sell, Read) and summary; move up / down, duplicate, delete,
|
||||
// add; Save and Reload; RynthAi's last message.
|
||||
// add; Why? (RynthAi's "Why this loot rule?" window for the
|
||||
// item selected in the game); Save and Reload; RynthAi's last
|
||||
// message.
|
||||
// A rule's conditions are written in the Loot Editor (the Editor plate opens it
|
||||
// on this file). Opening another file waits for unsaved changes to be saved or
|
||||
// reloaded (the Loot Editor asks about discarding them; this tab doesn't).
|
||||
|
|
@ -170,6 +172,11 @@ internal sealed class ClassicLootTab : IClassicTab
|
|||
if (Plate("##cl_add", "Add", new Vector2(x, y)) && editable)
|
||||
LootEditCommands.Simple("add", -1);
|
||||
SafeImGui.SetItemTooltip("Add a new rule at the end (write it in the Loot Editor)");
|
||||
x += Px(50);
|
||||
// The selected item, not the selected rule: RynthAi's "Why this loot rule?" window.
|
||||
if (x + Px(46) <= o.X + w && Plate("##cl_why", "Why?", new Vector2(x, y)))
|
||||
LootEditorFace.AskLootWhy();
|
||||
SafeImGui.SetItemTooltip(LootEditorFace.LootWhyLabel + "\n" + LootEditorFace.LootWhyTip);
|
||||
y += Px(21);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,6 +16,9 @@
|
|||
// Monster Detail panel (weaknesses, accuracy, damage, summons, damage taken,
|
||||
// its rule). x removes the monster (confirmed). Gold = set by you, dim =
|
||||
// automatic.
|
||||
// Under a monster's row, when the plugin sends them (the row's "mstats",
|
||||
// UI/Data/DamageRowStats.cs, 2026-10-30): how often it evades and resists you
|
||||
// and you it since login, the full numbers on hover.
|
||||
// Where the server plugin reports difficulty tiers: a tier chip after Reset stats
|
||||
// (DamageView.Tier) - which tier the numbers are for, and a picker; "~" marks an
|
||||
// HP estimated from tier 0's. Hidden elsewhere.
|
||||
|
|
@ -97,6 +100,8 @@ internal sealed class DamageFace : IImGuiPanel
|
|||
public string NameShown = "", NameTip = "";
|
||||
public string Weapon = "", Offhand = "", Pet = "", WeakTop = "", Sec = "", SecTip = "";
|
||||
public string Prefer = "Auto";
|
||||
/// <summary>The line under the row (the plugin's evades and resists since login) and its tooltip; "" for none.</summary>
|
||||
public string Stats = "", StatsTip = "";
|
||||
public bool CritSet, NonCritSet, WeaponGold, OffhandGold, PetGold, PreferGold;
|
||||
public string[] TierLines = Array.Empty<string>();
|
||||
/// <summary>Priority shown (int.MinValue = rules not loaded), whether it's the monster's own
|
||||
|
|
@ -361,6 +366,11 @@ internal sealed class DamageFace : IImGuiPanel
|
|||
t.Sec = r.SecKill > 0 ? r.SecKill.ToString("0.0", inv) : "—";
|
||||
t.SecTip = (r.SecKill > 0 ? $"{r.SecKill:0.0} s from engaging to the kill (average of timed kills)." : "No timed kills yet.")
|
||||
+ (r.HitRate >= 0 ? $"\nHits: {r.HitRate * 100:0}% of attacks and casts landed." : "");
|
||||
if (r.Stats != null)
|
||||
{
|
||||
t.Stats = r.Stats.Line();
|
||||
t.StatsTip = r.Stats.Tip();
|
||||
}
|
||||
t.TierLines = new string[r.Tiers.Count];
|
||||
for (int i = 0; i < r.Tiers.Count; i++)
|
||||
{
|
||||
|
|
@ -756,29 +766,33 @@ internal sealed class DamageFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
// The line under a monster's row: the plugin's evades and resists since login (DamageRowStats).
|
||||
private const float StatsH = 16;
|
||||
|
||||
private void DrawRow(DamageRow r, Vector2 clipMin, Vector2 clipMax)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (p.Y + RowH < clipMin.Y || p.Y > clipMax.Y)
|
||||
RowText t = _text[r];
|
||||
float h = RowH + (t.Stats.Length > 0 ? StatsH : 0);
|
||||
if (p.Y + h < clipMin.Y || p.Y > clipMax.Y)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(TableW, RowH)); // off screen: keep the layout, skip the drawing
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(TableW, h)); // off screen: keep the layout, skip the drawing
|
||||
return;
|
||||
}
|
||||
RowText t = _text[r];
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.AddRectFilled(p, p + new Vector2(TableW, RowH), r.IsDefault ? HeaderBg : RowBg);
|
||||
dl.AddRectFilled(p, p + new Vector2(TableW, h), r.IsDefault ? HeaderBg : RowBg);
|
||||
if (r.Targeted)
|
||||
{
|
||||
// The monster being fought (or selected): teal wash, a bar on the left, an outline.
|
||||
dl.AddRectFilled(p, p + new Vector2(TableW, RowH), TargetBg);
|
||||
dl.AddRectFilled(p, p + new Vector2(3, RowH), Teal);
|
||||
dl.AddRect(p, p + new Vector2(TableW, RowH), Teal);
|
||||
dl.AddRectFilled(p, p + new Vector2(TableW, h), TargetBg);
|
||||
dl.AddRectFilled(p, p + new Vector2(3, h), Teal);
|
||||
dl.AddRect(p, p + new Vector2(TableW, h), Teal);
|
||||
}
|
||||
else if (r.Nearby)
|
||||
{
|
||||
// On the player's landblock: a green wash and bar.
|
||||
dl.AddRectFilled(p, p + new Vector2(TableW, RowH), NearbyBg);
|
||||
dl.AddRectFilled(p, p + new Vector2(3, RowH), NearbyBar);
|
||||
dl.AddRectFilled(p, p + new Vector2(TableW, h), NearbyBg);
|
||||
dl.AddRectFilled(p, p + new Vector2(3, h), NearbyBar);
|
||||
}
|
||||
ImGuiNET.ImGui.PushID(r.IsDefault ? "default" : r.Key);
|
||||
float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
|
|
@ -892,8 +906,21 @@ internal sealed class DamageFace : IImGuiPanel
|
|||
}
|
||||
SafeImGui.SetItemTooltip("Remove " + r.Name + " from this list (asks first).");
|
||||
|
||||
if (t.Stats.Length > 0)
|
||||
{
|
||||
// Under the monster: its evades and resists both ways since login, the full numbers on hover.
|
||||
ImFontPtr small = ImGuiFonts.Get(UiFont.Ui10);
|
||||
var at = new Vector2(p.X + ColX[ColMonster] + 22, p.Y + RowH + (StatsH - small.FontSize) * 0.5f - 2);
|
||||
dl.PushClipRect(new Vector2(p.X, p.Y + RowH), new Vector2(p.X + TableW, p.Y + h), true);
|
||||
dl.AddText(small, small.FontSize, at, Dim, t.Stats);
|
||||
dl.PopClipRect();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + ColX[ColMonster] + 22, p.Y + RowH));
|
||||
ImGuiNET.ImGui.InvisibleButton("##stats", new Vector2(Math.Max(1, TableW - ColX[ColMonster] - 26), StatsH));
|
||||
SafeImGui.SetItemTooltip(t.StatsTip);
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.PopID();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + RowH));
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(TableW, 0));
|
||||
}
|
||||
|
||||
|
|
@ -1442,7 +1469,7 @@ internal sealed class DamageFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Reset ALL learned damage statistics?");
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text),
|
||||
"Monster names and your settings (manual HP, weapon/offhand picks, debuffs) are KEPT — only the learned damage, crit, casts-to-kill, kills and HP are cleared. This cannot be undone.");
|
||||
"Monster names and your settings (manual HP, weapon/offhand picks, debuffs) are KEPT — only the learned damage, crit, casts-to-kill, kills and HP are cleared, and the evades and resists under each monster start over. This cannot be undone.");
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
|
||||
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
|
|
|
|||
|
|
@ -60,6 +60,10 @@ internal sealed class ItemsFace : IImGuiPanel
|
|||
"An entry whose item is gone but with an unlisted item of the same name in your pack\n" +
|
||||
"(a new stack of kits, a replacement weapon) is pointed at that item instead.\n" +
|
||||
"Does nothing while your inventory is still loading. Also: /ra items clean.");
|
||||
// The other way: everything in the pack that belongs here and isn't listed yet (answers in chat).
|
||||
AddSelected("##fill_from_pack", PhosphorIcons.Plus + " Add From Pack", "(weapons, healing kits, lockpicks, pet essences not listed yet)",
|
||||
() => RynthAiCommands.ApplyRemoteCommand("sendchat", "/ra items fill"),
|
||||
"Adds every weapon, healing kit, lockpick and pet essence in your pack that isn't listed yet.\nRynthAi says in chat what it added. Also: /ra items fill.");
|
||||
|
||||
// Weapons
|
||||
Section("Weapons", bw);
|
||||
|
|
|
|||
|
|
@ -158,6 +158,11 @@ internal sealed class LootEditorFace : IImGuiPanel
|
|||
public readonly byte[] Bytes = new byte[512];
|
||||
public string? Shown;
|
||||
public bool Active;
|
||||
// A text condition (TextPattern): the mode shown, the words in the box, and the pattern they were
|
||||
// read from (re-read only when the pattern changes, so a mode the player picked stays).
|
||||
public LootTextMode? Mode;
|
||||
public string Words = "";
|
||||
public string? ParsedFrom;
|
||||
}
|
||||
private readonly Dictionary<(int Cond, int Line), FieldBuffer> _fields = new();
|
||||
private readonly FieldBuffer _nameField = new(), _keepField = new();
|
||||
|
|
@ -758,10 +763,26 @@ internal sealed class LootEditorFace : IImGuiPanel
|
|||
? "A rule for the item selected in the game (click it first): preview, then add it here"
|
||||
: s.Dirty ? "Save or discard your edits first" : "This profile is read-only here");
|
||||
addW += itemW + 6;
|
||||
// RynthAi answers in its own "Why this loot rule?" window (an older RynthAi ignores it).
|
||||
string whyLabel = PhosphorIcons.Info + " " + LootWhyLabel;
|
||||
float whyW = ButtonWidth(whyLabel) + 6;
|
||||
if (Button("##loot_why", whyLabel, new Vector2(p.X + addW + 6, p.Y), new Vector2(whyW, h), Text, BtnFill))
|
||||
AskLootWhy();
|
||||
SafeImGui.SetItemTooltip(LootWhyTip);
|
||||
addW += whyW + 6;
|
||||
MessageText(new Vector2(p.X + addW + 8, p.Y), p.X + w - grip - 4, h);
|
||||
NextLine(p, h);
|
||||
}
|
||||
|
||||
/// <summary>The "Why this loot rule?" buttons (here and the Classic Loot tab).</summary>
|
||||
internal const string LootWhyLabel = "Why this loot rule?";
|
||||
internal const string LootWhyTip =
|
||||
"Which rule of the loot profile in use takes the item selected in the game, and why the rules above it\n" +
|
||||
"didn't (the first condition each failed, and the value it read). RynthAi shows it in a small window.\nAlso: /ra loot why";
|
||||
|
||||
/// <summary>RynthAi's "lootwhy" remote command: /ra loot why window, for the selected item. Any thread.</summary>
|
||||
internal static void AskLootWhy() => RynthAiCommands.ApplyRemoteCommand("lootwhy", "show");
|
||||
|
||||
private void MessageText(Vector2 at, float right, float h)
|
||||
{
|
||||
if (_msg.Length == 0 || (_msgOk && (DateTime.Now - _msgAt).TotalSeconds > 10)) return;
|
||||
|
|
@ -1110,14 +1131,13 @@ internal sealed class LootEditorFace : IImGuiPanel
|
|||
}
|
||||
case "keypattern":
|
||||
{
|
||||
float kw = w * 0.34f;
|
||||
float kw = w * 0.30f;
|
||||
IdPicker("##key", c, 1, KeyTable(node.KeyTable), "key", p, kw - 2, h, ro);
|
||||
if (Field("##pat", FieldFor(i, 0), c.Lines[0], new Vector2(p.X + kw + 2, p.Y), w - kw - 2, "pattern (regex)", ro, out string v, h))
|
||||
c.Lines[0] = v;
|
||||
TextPattern("##pat", c, i, new Vector2(p.X + kw + 2, p.Y), w - kw - 2, h, ro);
|
||||
break;
|
||||
}
|
||||
case "text":
|
||||
if (Field("##text", FieldFor(i, 0), c.Lines[0], p, w, "pattern (regex)", ro, out string t, h)) c.Lines[0] = t;
|
||||
TextPattern("##text", c, i, p, w, h, ro);
|
||||
break;
|
||||
default: // "value"
|
||||
if (Field("##value", FieldFor(i, 0), c.Lines[0], p, w, node.Labels.Count > 0 ? node.Labels[0].ToLowerInvariant() : "value", ro, out string n, h))
|
||||
|
|
@ -1188,6 +1208,62 @@ internal sealed class LootEditorFace : IImGuiPanel
|
|||
SafeImGui.SetItemTooltip(tip);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A text condition's pattern as a mode and plain words (2026-11-01: "people hate regex"): [contains v]
|
||||
/// [words]. The editor writes the regex (UI.LootPatternText) into the condition, so the profile stays a
|
||||
/// plain VTank .utl; "regex" shows the pattern itself. A mode the player picks stays while the pattern
|
||||
/// still reads back as it.
|
||||
/// </summary>
|
||||
private void TextPattern(string id, LootEditConditionDto c, int cond, Vector2 p, float w, float h, bool ro)
|
||||
{
|
||||
FieldBuffer buf = FieldFor(cond, 0);
|
||||
string pattern = c.Lines[0];
|
||||
if (!ReferenceEquals(buf.ParsedFrom, pattern))
|
||||
{
|
||||
var (mode, words) = LootPatternText.Parse(pattern);
|
||||
LootTextMode keep = buf.Mode ?? mode;
|
||||
if (keep == LootTextMode.Regex) { buf.Mode = LootTextMode.Regex; buf.Words = pattern; }
|
||||
else if (pattern.Length == 0) { buf.Mode = keep; buf.Words = ""; }
|
||||
else { buf.Mode = mode; buf.Words = mode == LootTextMode.Regex ? pattern : words; }
|
||||
buf.ParsedFrom = pattern;
|
||||
}
|
||||
LootTextMode shown = buf.Mode ?? LootTextMode.Contains;
|
||||
|
||||
float mw = Math.Min(120, Math.Max(80, w * 0.36f));
|
||||
if (PickerButton(id + "_mode", LootPatternText.Label(shown), p, mw - 2, h, ro))
|
||||
{
|
||||
FieldBuffer target = buf;
|
||||
LootEditConditionDto dto = c;
|
||||
_picker.Open(new Vector2(p.X, p.Y + h), LootPatternText.Labels, (int)shown, k =>
|
||||
{
|
||||
LootTextMode next = LootPatternText.Modes[k];
|
||||
LootTextMode was = target.Mode ?? LootTextMode.Contains;
|
||||
if (next == was || dto.Lines.Count == 0) return;
|
||||
// Into regex: the pattern as it is. Out of regex: its words when it has a plain shape.
|
||||
string words = next == LootTextMode.Regex ? dto.Lines[0]
|
||||
: was == LootTextMode.Regex ? (LootPatternText.Parse(dto.Lines[0]) is var (m2, w2) && m2 != LootTextMode.Regex ? w2 : "")
|
||||
: target.Words;
|
||||
dto.Lines[0] = LootPatternText.Build(next, words);
|
||||
target.Mode = next;
|
||||
target.Words = words;
|
||||
target.ParsedFrom = dto.Lines[0];
|
||||
target.Shown = null; // the box shows the new words
|
||||
}, Math.Max(150, mw));
|
||||
}
|
||||
SafeImGui.SetItemTooltip("How the text is matched (case doesn't matter). Pick \"regex\" to type a pattern yourself.");
|
||||
|
||||
if (Field(id, buf, buf.Words, new Vector2(p.X + mw, p.Y), w - mw, LootPatternText.Hint(shown), ro, out string typed, h))
|
||||
{
|
||||
buf.Words = typed;
|
||||
c.Lines[0] = LootPatternText.Build(shown, typed);
|
||||
buf.ParsedFrom = c.Lines[0];
|
||||
}
|
||||
if (shown != LootTextMode.Regex)
|
||||
SafeImGui.SetItemTooltip(c.Lines[0].Length > 0
|
||||
? "Written to the profile as: " + c.Lines[0] + (shown is LootTextMode.Contains or LootTextMode.NotContains ? "\nSeveral words: separate them with commas (either of them)." : "")
|
||||
: (shown is LootTextMode.Contains or LootTextMode.NotContains ? "Type a word. Several: separate them with commas (either of them)." : "Type the text."));
|
||||
}
|
||||
|
||||
/// <summary>A whole number: "45", "45.0" (a buffed-long value written as a double).</summary>
|
||||
private static bool TryWhole(string? raw, out int value)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -2,8 +2,9 @@
|
|||
// 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":
|
||||
// RynthLua v2 (ScriptInfos present), tabs "Scripts" | "Editor", "Live reload:
|
||||
// on/off" (a RynthLua with live reload; /lua livereload), 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
|
||||
|
|
@ -161,13 +162,37 @@ internal sealed class LuaFace : IImGuiPanel
|
|||
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;
|
||||
|
||||
// RynthLua's live reload (a RynthLua that has it says so in the payload): /lua livereload on|off.
|
||||
float lrW = 0;
|
||||
if (LuaLiveReload.Label(d.LiveReload) is { } lrLabel)
|
||||
{
|
||||
bool on = d.LiveReload == true;
|
||||
string caption = PhosphorIcons.ArrowsClockwise + " " + lrLabel;
|
||||
lrW = ButtonWidth(caption) + 4;
|
||||
if (Button("##lua_live", caption, new Vector2(p.X + sw + ew + 8, p.Y), new Vector2(lrW, h), on ? Teal : Mute, on ? Selected : BtnFill))
|
||||
LuaCommands.Chat(LuaLiveReload.ClickArgs(on));
|
||||
SafeImGui.SetItemTooltip(LuaLiveReload.Tip(on));
|
||||
lrW += 6;
|
||||
}
|
||||
// Stop every running script (/lua stop all), while two or more run.
|
||||
if (d.RunningCount > 1 && d.ScriptInfos is { } running)
|
||||
{
|
||||
const string StopAll = PhosphorIcons.Stop + " Stop all";
|
||||
float saW = ButtonWidth(StopAll) + 4;
|
||||
if (Button("##lua_stopall", StopAll, new Vector2(p.X + sw + ew + 8 + lrW, p.Y), new Vector2(saW, h), Text, StopBg))
|
||||
foreach (LuaScriptInfo si in running)
|
||||
if (si.Running) LuaCommands.Send("stopScript", si.Name);
|
||||
SafeImGui.SetItemTooltip("Stop every running script. Also: /lua stop all");
|
||||
lrW += saW + 6;
|
||||
}
|
||||
|
||||
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 left = p.X + sw + ew + 10 + lrW, 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);
|
||||
|
|
|
|||
|
|
@ -691,6 +691,20 @@ internal sealed partial class MetaFace
|
|||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
bool canRevert = _editOriginal != null && !MetaRuleEdit.SameContent(_editRule, _editOriginal);
|
||||
string problem = SaveProblem();
|
||||
float problemX = p.X;
|
||||
if (canRevert) problemX += BtnW(PhosphorIcons.ArrowCounterClockwise + " Revert", 60) + 6;
|
||||
if (problem.Length > 0 && !_editConfirmDelete)
|
||||
{
|
||||
// The editor's status line: why the last change isn't saved (the full text on hover).
|
||||
string del = PhosphorIcons.Trash + (_editIndex < 0 ? " Discard" : " Delete rule");
|
||||
float room = p.X + w - BtnW(del, 70) - 6 - problemX;
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
dl.AddText(new Vector2(problemX, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Red, Fit(problem, Math.Max(20, room)));
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
if (ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(problemX, p.Y), new Vector2(problemX + Math.Max(20, room), p.Y + h)))
|
||||
ImGuiNET.ImGui.SetTooltip(problem);
|
||||
}
|
||||
if (canRevert)
|
||||
{
|
||||
string label = PhosphorIcons.ArrowCounterClockwise + " Revert";
|
||||
|
|
@ -702,7 +716,7 @@ internal sealed partial class MetaFace
|
|||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Undo every change since you opened this rule (and save that)");
|
||||
}
|
||||
else
|
||||
else if (problem.Length == 0)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
dl.AddText(new Vector2(p.X, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute),
|
||||
|
|
|
|||
|
|
@ -207,15 +207,18 @@ internal sealed partial class MetaFace
|
|||
FilterRow(w);
|
||||
|
||||
// A note over the list: the editor closed under a meta switch, or the meta can't do anything.
|
||||
string note = string.Empty;
|
||||
if (_listNote.Length > 0 && NowMs - _listNoteAt < 8000) note = _listNote;
|
||||
// A change that wasn't saved comes first, in red, and stays until the next result (2026-11-01).
|
||||
string note = SaveProblem();
|
||||
bool unsaved = note.Length > 0;
|
||||
if (unsaved) { }
|
||||
else if (_listNote.Length > 0 && NowMs - _listNoteAt < 8000) note = _listNote;
|
||||
else if (_data.Rules.Count > 0 && !HasRulesIn(_data.CurrentState))
|
||||
note = $"The current state, {_data.CurrentState}, has no rules: the meta does nothing until something changes the state.";
|
||||
if (note.Length > 0)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, unsaved ? Red : Amber);
|
||||
ImGuiNET.ImGui.TextUnformatted(note);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
|
|
|
|||
|
|
@ -102,8 +102,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
// ── Saving ───────────────────────────────────────────────────────────
|
||||
private readonly MetaAutosave _autosave = new();
|
||||
private readonly MetaBackupPlan _backup = new();
|
||||
private long _saveSentAt = -1; // ms (TickCount64) of the last rule command, for "Saving..."
|
||||
private long _saveSentVersion; // the snapshot version then
|
||||
private readonly MetaSaveWatch _saveWatch = new(); // waits for RynthAi's answer to each change
|
||||
private static long NowMs => Environment.TickCount64;
|
||||
|
||||
// ── Rule editor ──────────────────────────────────────────────────────
|
||||
|
|
@ -145,6 +144,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
UiSources.Meta.RequestRefresh();
|
||||
CodeEditor.SetMetaVocabulary(MetaVocabulary.StructKeywords, MetaVocabulary.ConditionKeywords, MetaVocabulary.ActionKeywords);
|
||||
_backup.NewSession(); // a new editing session: the first save backs the file up again
|
||||
_saveWatch.Reset();
|
||||
}
|
||||
|
||||
public void OnHidden()
|
||||
|
|
@ -271,8 +271,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
// Saving over another meta keeps that one's old copy as <file>.bak.
|
||||
MetaCommands.Backup(target, MetaBackupPlan.BackupOf(target));
|
||||
MetaCommands.Simple("save_file", path: target);
|
||||
_saveSentAt = NowMs;
|
||||
_saveSentVersion = _seenVersion;
|
||||
_saveWatch.Sent(NowMs, SeenSaveSeq, MetaCommands.Undelivered);
|
||||
}
|
||||
_saveAs = false;
|
||||
}
|
||||
|
|
@ -324,6 +323,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
{
|
||||
float m = Math.Max(ImGuiNET.ImGui.CalcTextSize(SavedText).X, ImGuiNET.ImGui.CalcTextSize(SavingText).X);
|
||||
m = Math.Max(m, Math.Max(ImGuiNET.ImGui.CalcTextSize(EditingText).X, ImGuiNET.ImGui.CalcTextSize(NoFileText).X));
|
||||
m = Math.Max(m, ImGuiNET.ImGui.CalcTextSize(UnconfirmedText).X);
|
||||
if (editor) m = Math.Max(m, ImGuiNET.ImGui.CalcTextSize(DraftText).X);
|
||||
return m + 6;
|
||||
}
|
||||
|
|
@ -339,10 +339,37 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
return _editTyping
|
||||
? (EditingText, Amber, "Saves when you leave the box (Enter, Tab or click elsewhere).")
|
||||
: (SavingText, Amber, "Saving in a moment...");
|
||||
if (_saveSentAt >= 0 && _seenVersion == _saveSentVersion && NowMs - _saveSentAt < 2500)
|
||||
return (SavingText, Amber, "Saving " + file + "...");
|
||||
switch (_saveWatch.State(NowMs, _data.SaveResult, MetaCommands.Undelivered))
|
||||
{
|
||||
case MetaSaveState.Saving:
|
||||
return (SavingText, Amber, "Saving " + file + "...");
|
||||
case MetaSaveState.Failed:
|
||||
case MetaSaveState.NotSent:
|
||||
return (NoFileText, Red, SaveProblem());
|
||||
case MetaSaveState.Unconfirmed:
|
||||
return (UnconfirmedText, Amber, SaveProblem());
|
||||
}
|
||||
string bak = System.IO.Path.GetFileName(MetaBackupPlan.BackupOf(MetaBackupPlan.WrittenFile(_data.CurrentMetaPath!)));
|
||||
return (SavedText, Green, $"Every change saves to {file} on its own. The first change after opening this panel keeps the file as it was in {bak}.");
|
||||
string last = _data.SaveResult is { Seq: > 0, Text.Length: > 0 } r ? $"\nLast: {r.Text}" : "";
|
||||
return (SavedText, Green, $"Every change saves to {file} on its own. The first change after opening this panel keeps the file as it was in {bak}.{last}");
|
||||
}
|
||||
|
||||
private const string UnconfirmedText = PhosphorIcons.Warning + " Not confirmed";
|
||||
|
||||
/// <summary>The result seq the panel has seen (0: none, or a RynthAi without results).</summary>
|
||||
private long SeenSaveSeq => _data.SaveResult?.Seq ?? 0;
|
||||
|
||||
/// <summary>Why the last change isn't saved, for the status line and the indicator's tooltip; empty when it is.</summary>
|
||||
private string SaveProblem()
|
||||
{
|
||||
if (string.IsNullOrEmpty(_data.CurrentMetaPath)) return string.Empty; // "Not saved" + its own hint
|
||||
return _saveWatch.State(NowMs, _data.SaveResult, MetaCommands.Undelivered) switch
|
||||
{
|
||||
MetaSaveState.Failed => _data.SaveResult!.Text,
|
||||
MetaSaveState.NotSent => "Not saved: the change never reached RynthAi (it isn't loaded, or is too old for this panel). Reload RynthAi and make the change again.",
|
||||
MetaSaveState.Unconfirmed => "RynthAi hasn't confirmed the last change. If this stays, it may not have been saved: check the rule after reopening the meta.",
|
||||
_ => string.Empty,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The save status, right-aligned in (pos, width); hover for details.</summary>
|
||||
|
|
@ -360,15 +387,14 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
|
||||
/// <summary>
|
||||
/// Every command that changes the meta's rules goes through here: before the first one of this
|
||||
/// session the file is backed up, and the indicator shows "Saving..." until the next snapshot.
|
||||
/// (RynthAi writes the file after each such command.)
|
||||
/// session the file is backed up, and the indicator shows "Saving..." until RynthAi answers
|
||||
/// (MetaSaveWatch; RynthAi writes the file after each such command and reports the result).
|
||||
/// </summary>
|
||||
private void SendEdit(MetaCmd cmd)
|
||||
{
|
||||
if (_backup.Before(_data.CurrentMetaPath) is { } b) MetaCommands.Backup(b.File, b.Backup);
|
||||
MetaCommands.Send(cmd);
|
||||
_saveSentAt = NowMs;
|
||||
_saveSentVersion = _seenVersion;
|
||||
_saveWatch.Sent(NowMs, SeenSaveSeq, MetaCommands.Undelivered);
|
||||
}
|
||||
|
||||
private void BeginSaveAs()
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
// Recall / Clear / Save / Dungeon Patrol, the route editor (move / duplicate /
|
||||
// delete / set active / move here on the selection; nearest, reverse, snap to
|
||||
// path, point at selection, pause, simplify; recording and trail -> route),
|
||||
// a chat waypoint, Save As, the nav file picker, the nav point reach
|
||||
// a chat waypoint, Save As, the nav file picker (at the top), the nav point reach
|
||||
// (RynthAi's FollowNavMin, the same row as Settings > Navigation), and the
|
||||
// waypoint list (click selects, Ctrl/Shift-click multi-selects, double-click
|
||||
// sets active, right-click edits, X or Delete deletes, => marks the active one).
|
||||
|
|
@ -56,6 +56,7 @@ internal sealed class NavFace : IImGuiPanel
|
|||
{
|
||||
PhosphorIcons.NavigationArrow + " Nearest", PhosphorIcons.ArrowsClockwise + " Reverse", PhosphorIcons.Path + " Snap to Path",
|
||||
PhosphorIcons.MapPin + " Point at Selected", PhosphorIcons.Hourglass + " Add Pause", PhosphorIcons.Scissors + " Simplify",
|
||||
PhosphorIcons.ArrowCounterClockwise + " Restart",
|
||||
};
|
||||
private static readonly string[] RowMenu =
|
||||
{ "Set Active", "Move Here", "Move Up", "Move Down", "Duplicate", "Delete" };
|
||||
|
|
@ -110,6 +111,19 @@ internal sealed class NavFace : IImGuiPanel
|
|||
bool typing = false;
|
||||
NavPayload d = _data;
|
||||
bool navActive = d.MacroRunning && d.NavigationEnabled;
|
||||
Vector2 p;
|
||||
|
||||
// Nav file picker, first (2026-11-01, the owner: "move the nav file selection to the top")
|
||||
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);
|
||||
}
|
||||
|
||||
// Active nav + status
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
|
|
@ -118,7 +132,7 @@ internal sealed class NavFace : IImGuiPanel
|
|||
if (d.NavStatusLine.Length > 0) Label(d.NavStatusLine, d.NavIsStuck ? Amber : Green);
|
||||
|
||||
// Start / Stop
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (Button("##startstop", navActive ? StopNav : StartNav, p, new Vector2(w, 28), Text, navActive ? StopBg : StartBg))
|
||||
{
|
||||
if (navActive)
|
||||
|
|
@ -258,18 +272,6 @@ internal sealed class NavFace : IImGuiPanel
|
|||
}
|
||||
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);
|
||||
|
|
@ -441,6 +443,10 @@ internal sealed class NavFace : IImGuiPanel
|
|||
_picker.Open(at, NavCommands.SimplifyLabels, -1, i =>
|
||||
NavCommands.Send(new NavCmd { Cmd = "simplifyRoute", Yards = NavCommands.SimplifyYards[i] }), width: 300);
|
||||
break;
|
||||
case 6:
|
||||
// Run the route again from its first point (a finished Once route too); answers in chat.
|
||||
RynthAiCommands.ApplyRemoteCommand("sendchat", "/ra nav restart");
|
||||
break;
|
||||
}
|
||||
|
||||
// Record | Route from Trail...
|
||||
|
|
@ -456,7 +462,11 @@ internal sealed class NavFace : IImGuiPanel
|
|||
Vector2 tp = new(p.X + half + 4, p.Y);
|
||||
if (Button("##fromtrail", FromTrail, tp, new Vector2(half, 22), Text, BtnFill, enabled: _data.TrailPoints >= 2))
|
||||
_picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i =>
|
||||
NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300);
|
||||
{
|
||||
// The last choice wipes the trail (/ra navtrail clear); the others make a route of it.
|
||||
if (i == NavCommands.TrailClearChoice) RynthAiCommands.ApplyRemoteCommand("sendchat", "/ra navtrail clear");
|
||||
else NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 });
|
||||
}, width: 300);
|
||||
if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
|
||||
SafeImGui.SetTooltip(_data.TrailPoints >= 2
|
||||
? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed."
|
||||
|
|
|
|||
|
|
@ -210,15 +210,31 @@ internal sealed unsafe class LogFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Tracker: the session-stat rows (TrackerSource) over an adjustable-opacity background.</summary>
|
||||
/// <summary>
|
||||
/// Tracker: the session-stat rows (TrackerSource) over an adjustable-opacity background, or text only
|
||||
/// (TrackerSettings.TextOnly: bare, the rows shadowed, clicks pass through except over them).
|
||||
/// </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 uint ResetBorder => RynthTheme.AccentFill;
|
||||
// Text only: no background behind it, so brighter than the framed look, each with a shadow.
|
||||
private static readonly uint BareLabel = RynthTheme.Argb(0xFFCFCFCF);
|
||||
private static readonly uint BareValue = RynthTheme.Argb(0xFFFFFFFF);
|
||||
private static readonly uint BareShadow = RynthTheme.Argb(0xD0000000);
|
||||
private int _opacity;
|
||||
|
||||
// Text only: the mouse is over what the last frame drew, so the window takes input (to drag it, or
|
||||
// for the frame button); elsewhere clicks reach the game. A press that began there keeps it.
|
||||
private bool _hot, _pressHot;
|
||||
|
||||
/// <summary>Text only is bare: docked, no frame, title, background or grip (popped out it is framed as usual).</summary>
|
||||
public bool Bare => TrackerSettings.TextOnly;
|
||||
|
||||
public bool ClickThrough => Bare && !_hot && !_pressHot;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.Tracker.Subscribe();
|
||||
|
|
@ -229,6 +245,90 @@ internal sealed class TrackerFace : IImGuiPanel
|
|||
public void OnHidden() => UiSources.Tracker.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
if (TrackerSettings.TextOnly && !ImGuiPanelHost.DrawingEmbedded && !ImGuiPopOuts.InPopOutFrame)
|
||||
{
|
||||
DrawTextOnly();
|
||||
return;
|
||||
}
|
||||
_hot = _pressHot = false;
|
||||
DrawFramed();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Text only: each row's label and value with a 1 px shadow, nothing behind them. The rows are a
|
||||
/// drag handle; the button at the end of the first row (faint until the mouse is on the rows)
|
||||
/// brings the frame back.
|
||||
/// </summary>
|
||||
private void DrawTextOnly()
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float width = Math.Max(60, ImGuiNET.ImGui.GetContentRegionAvail().X);
|
||||
Vector2 mouse = ImGuiNET.ImGui.GetIO().MousePos;
|
||||
bool wasHot = _hot;
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
float rowH = ImGuiNET.ImGui.GetTextLineHeight() + 1;
|
||||
float buttonW = rowH + 4;
|
||||
TrackerSnapshot? snap = UiSources.Tracker.Current?.Value;
|
||||
string[]? values = snap?.Values;
|
||||
string[] labels = snap?.Labels ?? TrackerSnapshot.DefaultLabels;
|
||||
ImFontPtr labelFont = ImGuiNET.ImGui.GetFont();
|
||||
float labelSize = ImGuiNET.ImGui.GetFontSize();
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono9));
|
||||
ImFontPtr valueFont = ImGuiNET.ImGui.GetFont();
|
||||
float valueSize = ImGuiNET.ImGui.GetFontSize();
|
||||
float y = origin.Y;
|
||||
for (int i = 0; i < labels.Length; i++)
|
||||
{
|
||||
// The first row stops short of the frame button.
|
||||
float right = origin.X + width - (i == 0 ? buttonW + 2 : 0);
|
||||
Shadowed(dl, labelFont, labelSize, new Vector2(origin.X, y), BareLabel, labels[i]);
|
||||
string value = values != null && i < values.Length ? values[i] : "—";
|
||||
float w = ImGuiNET.ImGui.CalcTextSize(value).X;
|
||||
Shadowed(dl, valueFont, valueSize, new Vector2(Math.Max(origin.X, right - w), y), BareValue, value);
|
||||
y += rowH;
|
||||
}
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
float height = Math.Max(rowH, y - origin.Y);
|
||||
|
||||
// The rows: a drag handle (the window has no title bar to hold).
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(origin);
|
||||
ImGuiNET.ImGui.InvisibleButton("##tracker_textonly_drag", new Vector2(Math.Max(1, width - buttonW - 2), height));
|
||||
ImGuiPanelHost.DragWindowWithLastItem();
|
||||
if (ImGuiNET.ImGui.IsItemHovered() && !ImGuiNET.ImGui.IsItemActive())
|
||||
ImGuiNET.ImGui.SetTooltip("Drag to move the Tracker.");
|
||||
|
||||
// Frame button: faint until the mouse is on the rows.
|
||||
Vector2 bp = new(origin.X + width - buttonW, origin.Y);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(bp);
|
||||
float alpha = wasHot ? 1f : 0.35f;
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.Alpha, alpha);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(1, 0));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, ResetBg);
|
||||
if (ImGuiNET.ImGui.Button(PhosphorIcons.SquaresFour + "##tracker_frame", new Vector2(buttonW, rowH)))
|
||||
TrackerSettings.SetTextOnly(false);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Show the Tracker's frame and background again.");
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.PopStyleVar(2);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
|
||||
// Hot for the next frame: the mouse over the rows or the button.
|
||||
bool over = mouse.X >= origin.X && mouse.X <= origin.X + width && mouse.Y >= origin.Y && mouse.Y <= origin.Y + height;
|
||||
_hot = over;
|
||||
bool down = ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left);
|
||||
if (!down) _pressHot = false;
|
||||
else if (over && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) _pressHot = true;
|
||||
}
|
||||
|
||||
private static void Shadowed(ImDrawListPtr dl, ImFontPtr font, float size, Vector2 p, uint color, string text)
|
||||
{
|
||||
dl.AddText(font, size, p + new Vector2(1, 1), BareShadow, text);
|
||||
dl.AddText(font, size, p, color, text);
|
||||
}
|
||||
|
||||
private void DrawFramed()
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
// Background behind the content only (like the Avalonia StackPanel), so
|
||||
|
|
@ -240,11 +340,12 @@ internal sealed class TrackerFace : IImGuiPanel
|
|||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
|
||||
// Title row: [Tracker] [===slider===] [reset]
|
||||
// Title row: [Tracker] [===slider===] [text only] [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));
|
||||
float textOnlyW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.TextAa).X + 8;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(10, ImGuiNET.ImGui.GetContentRegionAvail().X - resetW - textOnlyW - 8));
|
||||
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);
|
||||
|
|
@ -256,6 +357,15 @@ internal sealed class TrackerFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, ResetBorder);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 1));
|
||||
bool canBare = !ImGuiPanelHost.DrawingEmbedded && !ImGuiPopOuts.InPopOutFrame;
|
||||
ImGuiNET.ImGui.BeginDisabled(!canBare);
|
||||
if (ImGuiNET.ImGui.Button(PhosphorIcons.TextAa + "##textonly"))
|
||||
TrackerSettings.SetTextOnly(true);
|
||||
ImGuiNET.ImGui.EndDisabled();
|
||||
ImGuiNET.ImGui.SetItemTooltip(canBare
|
||||
? "Text only: hide the frame and background, just the numbers (clicks pass through to the game).\nThe button at the end of its first row brings the frame back."
|
||||
: "Text only works while the Tracker is docked (not popped out).");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + "##reset"))
|
||||
UiSources.Tracker.RequestReset();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Reset the session stats");
|
||||
|
|
|
|||
|
|
@ -15,6 +15,10 @@
|
|||
// (wantHeight) as its minimum and is fitted to it whenever it changes and the
|
||||
// mouse is up (a frameless window's empty rows would still catch clicks meant
|
||||
// for the game); a text size change scales its width along with its fonts.
|
||||
// A "scale": "draw" window set bigger than normal (PanelDrawScale) gets the
|
||||
// fonts baked nearest above its size while the plugin draws (2026-11-01: from
|
||||
// the normal bake, stretched, its text blurred); the font pushed for its menus
|
||||
// and tooltips stays at the panel's text size.
|
||||
// docs/PLUGIN_WINDOWS.md. AC's render thread.
|
||||
// ============================================================================
|
||||
|
||||
|
|
@ -39,11 +43,12 @@ internal sealed class PluginWindowFace : IImGuiPanel
|
|||
|
||||
// "fitHeight" (v90): the content height the plugin asked for (logical units; 0 = not known
|
||||
// yet), and the text size factor and width (logical) the window was last fitted at.
|
||||
private readonly bool _fitHeight;
|
||||
private readonly bool _fitHeight, _drawScale;
|
||||
private readonly float _minWidth;
|
||||
private float _contentHeight, _fitK, _fitWidth;
|
||||
|
||||
public PluginWindowFace(string plugin, string surface, string title, bool fitHeight = false, float minWidth = 0f)
|
||||
public PluginWindowFace(string plugin, string surface, string title, bool fitHeight = false, float minWidth = 0f,
|
||||
bool drawScale = false)
|
||||
{
|
||||
_plugin = plugin;
|
||||
_title = title;
|
||||
|
|
@ -51,6 +56,15 @@ internal sealed class PluginWindowFace : IImGuiPanel
|
|||
_idScope = "##pw_" + surface;
|
||||
_fitHeight = fitHeight;
|
||||
_minWidth = minWidth;
|
||||
_drawScale = drawScale;
|
||||
}
|
||||
|
||||
/// <summary>The font step the plugin draws with: a draw-scale window's own size's (baked), else the text size's.</summary>
|
||||
private int DrawFontStep(int textStep)
|
||||
{
|
||||
if (!_drawScale) return textStep;
|
||||
int pct = PanelDrawScale.Get(_title);
|
||||
return pct > 0 ? ImGuiFonts.BakedStepNear(PanelDrawScale.FontStep(pct, EngineFrameController.FontScale)) : textStep;
|
||||
}
|
||||
|
||||
/// <summary>A fitHeight window's minimum: its minimum width at its text size, and the content's height.</summary>
|
||||
|
|
@ -78,10 +92,13 @@ internal sealed class PluginWindowFace : IImGuiPanel
|
|||
guarded = guarded && ImGuiStackGuard.AtWindowBase(bodyBase); // drawn anywhere else: as before
|
||||
ImGuiNET.ImGui.PushID(_idScope);
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
int textStep = ImGuiFonts.CurrentStep;
|
||||
ImGuiFonts.CurrentStep = DrawFontStep(textStep);
|
||||
ImGuiStackGuard.Mark given = guarded ? ImGuiStackGuard.Take() : default;
|
||||
try { result = PluginManager.RenderEmbed(_plugin, _surface, avail, out want); }
|
||||
finally
|
||||
{
|
||||
ImGuiFonts.CurrentStep = textStep;
|
||||
ImGuiStackGuard.Mark after = default;
|
||||
StackCheck check = guarded ? ImGuiStackGuard.Check(given, out after) : StackCheck.Balanced;
|
||||
if (check == StackCheck.Balanced)
|
||||
|
|
|
|||
|
|
@ -14,6 +14,9 @@
|
|||
// legend. Your own arrow, the compass letters and the coordinates have sizes too.
|
||||
// Outdoors the World Map's picture can be drawn behind it (RadarSettingsStore.ShowWorldMap; the
|
||||
// tiles come from WorldMapTiles through WorldMapTileDrawer, the same code as the World Map).
|
||||
// The object selected in game is highlighted (RadarSettingsStore.HighlightSelected, RadarSelection):
|
||||
// a ring in its own colour round its marker and the hover label beside it, or an arrow on the
|
||||
// edge when it is off the picture.
|
||||
//
|
||||
// Data: UiSources.Radar (RadarView, lookups precomputed). World geometry is
|
||||
// drawn without anti-aliasing (crisp tiling like the Avalonia face's aliased
|
||||
|
|
@ -72,6 +75,8 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
// The round radar (RadarSettingsStore.RoundRadar): this frame's circle, read by the drawing helpers.
|
||||
private static bool _round;
|
||||
private static RoundMask _mask;
|
||||
// The selected object's marker this frame (RadarSelection.Highlighted), or null; drawn over everything.
|
||||
private static RadarMarker? _sel;
|
||||
|
||||
/// <summary>Markers move: popped out, redraw smoothly even when idle.</summary>
|
||||
public int PopOutIdleHz => 20;
|
||||
|
|
@ -167,6 +172,11 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
dl.AddLine(new Vector2(worldMin.X, centre.Y), new Vector2(worldMax.X, centre.Y), Crosshair);
|
||||
}
|
||||
|
||||
// The game's current selection (the global AC's SetSelectedObject writes; one read a frame).
|
||||
uint selectedId = view != null && RadarSettingsStore.HighlightSelected && Compatibility.SelectedTargetHooks.IsInstalled
|
||||
? Compatibility.SelectedTargetHooks.ReadCurrentSelectedId() : 0;
|
||||
_sel = view != null ? RadarSelection.Highlighted(RadarSettingsStore.HighlightSelected, view.Live.Markers, selectedId) : null;
|
||||
|
||||
if (view != null)
|
||||
{
|
||||
ImDrawListFlags saved = dl.Flags;
|
||||
|
|
@ -175,6 +185,7 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
DrawWorld(dl, view, centre, worldMin, worldMax);
|
||||
dl.PopClipRect();
|
||||
dl.Flags = saved;
|
||||
DrawSelected(dl, view, centre, worldMin, worldMax, origin, panelMax);
|
||||
|
||||
DrawOutlinedText(dl, ImGuiFonts.Get(UiFont.UiBold11), view.CoordText,
|
||||
new Vector2((origin.X + panelMax.X) * 0.5f, panelMax.Y), CoordText, alignBottom: true,
|
||||
|
|
@ -306,7 +317,7 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
{
|
||||
foreach (RadarMarker m in live.Markers)
|
||||
{
|
||||
if (!RadarSettingsStore.ShowKind(m.Kind)) continue;
|
||||
if (m == _sel || !RadarSettingsStore.ShowKind(m.Kind)) continue; // the selected one: DrawSelected
|
||||
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 (_round ? !_mask.Contains(pp) : (pp.X < clipMin.X || pp.X > clipMax.X || pp.Y < clipMin.Y || pp.Y > clipMax.Y)) continue;
|
||||
|
|
@ -323,6 +334,7 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
foreach (RadarMarker m in live.Markers)
|
||||
{
|
||||
if (!markers.NameShown(m.Kind) || !RadarSettingsStore.ShowKind(m.Kind)) continue;
|
||||
if (m == _sel && RadarSettingsStore.ShowSelectedLabel) continue; // its label has the name
|
||||
Vector2 pp = proj.P(m.X, m.Y);
|
||||
if (pp.X < clipMin.X - 8 || pp.X > clipMax.X || pp.Y < clipMin.Y - 8 || pp.Y > clipMax.Y + 8) continue;
|
||||
if (_round && !_mask.Contains(pp)) continue;
|
||||
|
|
@ -338,6 +350,57 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
dl.AddLine(centre, tip, PlayerCol, 2);
|
||||
}
|
||||
|
||||
// ── The selected object ────────────────────────────────────────────────
|
||||
// A ring in the selection colour round its marker (the marker drawn over everything, even when its
|
||||
// kind's box is off), and the hover label beside it; off the picture, an arrow on the edge pointing
|
||||
// to it with the label next to the arrow. Drawn anti-aliased, after the world.
|
||||
|
||||
private const float ArrowInset = 3f, ArrowLength = 9f, ArrowHalfWidth = 5f;
|
||||
private readonly TipCache _selTip = new();
|
||||
|
||||
private void DrawSelected(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax,
|
||||
Vector2 panelMin, Vector2 panelMax)
|
||||
{
|
||||
RadarMarker? sel = _sel;
|
||||
if (sel == null) return;
|
||||
var proj = new Projection(centre, view.Live.Player, RadarSettingsStore.RotateWithPlayer, MathF.Max(0.5f, RadarSettingsStore.Zoom));
|
||||
Vector2 pp = proj.P(sel.X, sel.Y);
|
||||
uint col = RynthTheme.Argb(RadarSettingsStore.SelectedColor);
|
||||
Vector2 anchor;
|
||||
float gap;
|
||||
dl.PushClipRect(clipMin, clipMax, true);
|
||||
if (RadarSelection.EdgeArrow(centre, pp, clipMin, clipMax, _round ? _mask : null, ArrowInset, out Vector2 tip, out Vector2 dir))
|
||||
{
|
||||
RadarSelection.ArrowCorners(tip, dir, ArrowLength, ArrowHalfWidth, out Vector2 a, out Vector2 b, out Vector2 c);
|
||||
dl.AddTriangleFilled(a, b, c, col);
|
||||
dl.AddTriangle(a, b, c, Outline, 1.5f);
|
||||
anchor = tip - dir * (ArrowLength * 0.5f);
|
||||
gap = ArrowLength;
|
||||
}
|
||||
else
|
||||
{
|
||||
float size = RadarSettingsStore.Markers.SizeOf(sel.Kind);
|
||||
float r = MathF.Max(6.5f, RadarMarkerStyle.Radius(sel.Kind) * size + 3f);
|
||||
dl.AddCircle(pp, r, Outline, 20, 3.5f);
|
||||
RadarMarkerStyle.Draw(dl, sel.Kind, pp, KindCols[sel.Kind], size);
|
||||
dl.AddCircle(pp, r, col, 20, 2f);
|
||||
anchor = pp;
|
||||
gap = r + 4f;
|
||||
}
|
||||
dl.PopClipRect();
|
||||
if (!RadarSettingsStore.ShowSelectedLabel) return;
|
||||
|
||||
// The hover label, as a tooltip-styled box kept inside the panel.
|
||||
string text = _selTip.Get(view, sel);
|
||||
var style = ImGuiNET.ImGui.GetStyle();
|
||||
Vector2 pad = new Vector2(6f, 4f);
|
||||
Vector2 box = ImGuiNET.ImGui.CalcTextSize(text) + pad * 2f;
|
||||
Vector2 at = RadarSelection.LabelPos(anchor, gap, box, panelMin, panelMax);
|
||||
dl.AddRectFilled(at, at + box, ImGuiNET.ImGui.GetColorU32(ImGuiCol.PopupBg), style.PopupRounding);
|
||||
dl.AddRect(at, at + box, col, style.PopupRounding, ImDrawFlags.None, 1f);
|
||||
dl.AddText(at + pad, ImGuiNET.ImGui.GetColorU32(ImGuiCol.Text), text);
|
||||
}
|
||||
|
||||
// ── World map backdrop ─────────────────────────────────────────────────
|
||||
// The radar's world coordinates are yards from the world's south-west corner; the World Map's cells
|
||||
// are 24 yards, so cell = yards / 24 on both axes, and the radar's zoom (px per yard) is 24x that
|
||||
|
|
@ -475,11 +538,7 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
|
||||
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 readonly TipCache _hoverTip = new();
|
||||
|
||||
private void MarkerInput(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax, bool clicked)
|
||||
{
|
||||
|
|
@ -517,8 +576,9 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
dl.PushClipRect(clipMin, clipMax, true);
|
||||
dl.AddCircle(hitPos, 6.5f, CoordText, 16, 1.5f);
|
||||
dl.PopClipRect();
|
||||
if (hit == _sel && RadarSettingsStore.ShowSelectedLabel) return; // its label is already showing
|
||||
ImGuiNET.ImGui.BeginTooltip();
|
||||
ImGuiNET.ImGui.TextUnformatted(TipText(view, hit));
|
||||
ImGuiNET.ImGui.TextUnformatted(_hoverTip.Get(view, hit));
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
|
||||
|
|
@ -621,34 +681,44 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
}
|
||||
|
||||
/// <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.
|
||||
/// "Name\n12 yd" for the hovered (or selected) marker, plus " 75%" when the marker has an id and
|
||||
/// the engine has a health reading for it (MonsterHudData: one locked lookup, hover and the
|
||||
/// selected marker only). Rebuilt only when the marker, whole yards or whole percent change; one
|
||||
/// cache for the hover tooltip, one for the selected object's label, so neither rebuilds the other's.
|
||||
/// </summary>
|
||||
private string TipText(RadarView view, RadarMarker m)
|
||||
private sealed class TipCache
|
||||
{
|
||||
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))
|
||||
private byte _tipKind = byte.MaxValue;
|
||||
private string? _tipLabel;
|
||||
private int _tipDistance = int.MinValue;
|
||||
private int _tipPct = -1;
|
||||
private string _tipText = "";
|
||||
|
||||
public string Get(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 kind always follows it, so a dot says which show box
|
||||
// in the settings hides it (a fellow is not a "Player", your kill's corpse not a "Corpse").
|
||||
string name = string.IsNullOrEmpty(m.Label) ? RadarKind.Name(m.Kind)
|
||||
: m.Label + " (" + RadarKind.Name(m.Kind) + ")";
|
||||
var inv = System.Globalization.CultureInfo.InvariantCulture;
|
||||
_tipText = name + "\n" + d.ToString(inv) + " yd"
|
||||
+ (pct >= 0 ? " " + pct.ToString(inv) + "%" : "");
|
||||
return _tipText;
|
||||
_tipKind = m.Kind;
|
||||
_tipLabel = m.Label;
|
||||
_tipDistance = d;
|
||||
_tipPct = pct;
|
||||
// A label is the object's name; the kind always follows it, so a dot says which show box
|
||||
// in the settings hides it (a fellow is not a "Player", your kill's corpse not a "Corpse").
|
||||
string name = string.IsNullOrEmpty(m.Label) ? RadarKind.Name(m.Kind)
|
||||
: m.Label + " (" + RadarKind.Name(m.Kind) + ")";
|
||||
var inv = System.Globalization.CultureInfo.InvariantCulture;
|
||||
_tipText = name + "\n" + d.ToString(inv) + " yd"
|
||||
+ (pct >= 0 ? " " + pct.ToString(inv) + "%" : "");
|
||||
return _tipText;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Compass and text ───────────────────────────────────────────────────
|
||||
|
|
@ -763,6 +833,26 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
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 |= Check("Highlight the selected object", ref RadarSettingsStore.HighlightSelected);
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
ImGuiNET.ImGui.SetTooltip("Whatever you have selected in game (a monster, NPC, player, portal, door, corpse or item on the ground)\ngets a ring in this colour round its dot, even when its kind's box is off.\nOff the radar's picture, an arrow on the edge points the way to it.");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
Vector4 selCol = RynthTheme.Vec(RadarSettingsStore.SelectedColor);
|
||||
if (ImGuiNET.ImGui.ColorEdit4("##selcol", ref selCol, PickFlags))
|
||||
{
|
||||
RadarSettingsStore.SelectedColor = ToArgb(selCol);
|
||||
_colorDirty = true;
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsItemHovered() && !ImGuiNET.ImGui.IsItemActive())
|
||||
ImGuiNET.ImGui.SetTooltip("The selection ring's colour (click to change it).");
|
||||
if (RadarSettingsStore.HighlightSelected)
|
||||
{
|
||||
ImGuiNET.ImGui.Indent();
|
||||
changed |= Check("Show its label", ref RadarSettingsStore.ShowSelectedLabel);
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
ImGuiNET.ImGui.SetTooltip("The hover label (name, distance, health) stays beside the selected object while it is selected.");
|
||||
ImGuiNET.ImGui.Unindent();
|
||||
}
|
||||
changed |= Slider("Opacity", ref RadarSettingsStore.Opacity, 0.05f, 1.0f, "%.2f");
|
||||
changed |= Slider("Zoom", ref RadarSettingsStore.Zoom, 0.5f, 6.0f, "%.1f");
|
||||
changed |= Check("World map behind the radar (outdoors)", ref RadarSettingsStore.ShowWorldMap);
|
||||
|
|
@ -865,8 +955,6 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
float xName = 232 * scale, xSize = 268 * scale, xText = 350 * scale;
|
||||
MarkerStyleSettings markers = RadarSettingsStore.Markers;
|
||||
MarkerStyleEditor.HeaderRow(xName, xSize, xText);
|
||||
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)
|
||||
{
|
||||
|
|
@ -893,7 +981,7 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(KindTips[kind]);
|
||||
ImGuiNET.ImGui.SameLine(190 * scale);
|
||||
Vector4 v = RynthTheme.Vec(RadarSettingsStore.KindColors[kind]);
|
||||
if (ImGuiNET.ImGui.ColorEdit4("##col", ref v, pickFlags))
|
||||
if (ImGuiNET.ImGui.ColorEdit4("##col", ref v, PickFlags))
|
||||
{
|
||||
RadarSettingsStore.KindColors[kind] = ToArgb(v);
|
||||
_colorDirty = true;
|
||||
|
|
@ -922,7 +1010,7 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
RadarSettingsStore.ResetKindColors();
|
||||
changed = true;
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Every kind back to its default colour (show boxes stay as they are).");
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Every kind, and the selection ring, back to its default colour (show boxes stay as they are).");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.SmallButton("Reset sizes and names"))
|
||||
{
|
||||
|
|
@ -935,6 +1023,10 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
|
||||
private static bool _colorDirty;
|
||||
|
||||
// The colour swatches: click to pick, alpha included.
|
||||
private const ImGuiColorEditFlags PickFlags = ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel
|
||||
| ImGuiColorEditFlags.AlphaBar | ImGuiColorEditFlags.AlphaPreviewHalf;
|
||||
|
||||
private static uint ToArgb(Vector4 v)
|
||||
{
|
||||
static uint B(float f) => (uint)Math.Clamp((int)MathF.Round(f * 255f), 0, 255);
|
||||
|
|
|
|||
116
src/RynthCore.Engine/ImGui/Panels/RadarSelection.cs
Normal file
116
src/RynthCore.Engine/ImGui/Panels/RadarSelection.cs
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/RadarSelection.cs
|
||||
// The object selected in game, highlighted on the radar (2026-10-31, a player's
|
||||
// request: "Can the hover icon stay over whichever mob/door/etc. you have
|
||||
// selected?"). RadarFace reads AC's current selection each frame (the global the
|
||||
// SetSelectedObject hook reads, SelectedTargetHooks.ReadCurrentSelectedId: no new
|
||||
// hook) and draws a ring in its own colour round that object's marker, with the
|
||||
// hover label (name, distance, health) beside it. Off the radar's picture, a small
|
||||
// arrow on the edge points the way to it.
|
||||
//
|
||||
// The rules, pure (no ImGui, no AC), so tools\RadarSettingsTests links this file:
|
||||
// - which marker is the selected one: the marker with the selected object's id;
|
||||
// none when nothing is selected or the marker has no id (RynthAi builds before
|
||||
// 2026-10-01 send none);
|
||||
// - it clears when the selection clears, or the object is no longer one of the
|
||||
// radar's markers (gone, out of the client's view, an item in a pack);
|
||||
// - the selected object is shown even when its kind's show box is off (items on
|
||||
// the ground start hidden, and the player picked this one);
|
||||
// - where the edge arrow goes, and where the label sits.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal static class RadarSelection
|
||||
{
|
||||
/// <summary>
|
||||
/// The marker of the selected object, or null: nothing selected (id 0), the object isn't one of
|
||||
/// the markers, or the markers carry no ids. A kind this engine doesn't know (a newer RynthAi's) is
|
||||
/// never highlighted: it has no shape or colour here. A List, not an interface, so the loop allocates nothing.
|
||||
/// </summary>
|
||||
public static RadarMarker? Find(List<RadarMarker>? markers, uint selectedId)
|
||||
{
|
||||
if (selectedId == 0 || markers == null) return null;
|
||||
foreach (RadarMarker m in markers)
|
||||
if (m.Id == selectedId)
|
||||
return m.Kind < RadarKind.Count ? m : null;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Whether a marker is highlighted this frame: the setting is on and it is the selected object's.</summary>
|
||||
public static RadarMarker? Highlighted(bool settingOn, List<RadarMarker>? markers, uint selectedId) =>
|
||||
settingOn ? Find(markers, selectedId) : null;
|
||||
|
||||
/// <summary>
|
||||
/// The edge arrow toward a marker that is off the radar's picture. <paramref name="target"/> is the
|
||||
/// marker's screen point; the picture is the box <paramref name="min"/>..<paramref name="max"/>, or the
|
||||
/// circle <paramref name="round"/> on the round radar. False when the marker is on the picture (it is
|
||||
/// drawn where it is) or is at the centre. Otherwise <paramref name="tip"/> is the arrow's point,
|
||||
/// <paramref name="inset"/> px inside the edge on the line from <paramref name="centre"/> to the marker,
|
||||
/// and <paramref name="dir"/> the unit direction it points.
|
||||
/// </summary>
|
||||
public static bool EdgeArrow(Vector2 centre, Vector2 target, Vector2 min, Vector2 max, RoundMask? round, float inset,
|
||||
out Vector2 tip, out Vector2 dir)
|
||||
{
|
||||
tip = default;
|
||||
dir = default;
|
||||
if (round is RoundMask circle)
|
||||
{
|
||||
if (circle.Contains(target)) return false;
|
||||
}
|
||||
else if (target.X >= min.X && target.X <= max.X && target.Y >= min.Y && target.Y <= max.Y) return false;
|
||||
|
||||
Vector2 d = target - centre;
|
||||
float len = d.Length();
|
||||
if (!(len > 1e-4f) || !float.IsFinite(len)) return false;
|
||||
dir = d / len;
|
||||
float t;
|
||||
if (round is RoundMask c)
|
||||
t = MathF.Max(0f, c.Radius - inset);
|
||||
else
|
||||
{
|
||||
// Onto the box: the nearer of the two sides the ray meets.
|
||||
float hx = MathF.Max(0f, MathF.Min(centre.X - min.X, max.X - centre.X) - inset);
|
||||
float hy = MathF.Max(0f, MathF.Min(centre.Y - min.Y, max.Y - centre.Y) - inset);
|
||||
float tx = MathF.Abs(dir.X) > 1e-6f ? hx / MathF.Abs(dir.X) : float.MaxValue;
|
||||
float ty = MathF.Abs(dir.Y) > 1e-6f ? hy / MathF.Abs(dir.Y) : float.MaxValue;
|
||||
t = MathF.Min(tx, ty);
|
||||
}
|
||||
tip = centre + dir * t;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The edge arrow's three corners: the point at <paramref name="tip"/>, the base
|
||||
/// <paramref name="length"/> px back toward the centre and <paramref name="halfWidth"/> px to each side.
|
||||
/// </summary>
|
||||
public static void ArrowCorners(Vector2 tip, Vector2 dir, float length, float halfWidth,
|
||||
out Vector2 a, out Vector2 b, out Vector2 c)
|
||||
{
|
||||
var side = new Vector2(-dir.Y, dir.X);
|
||||
Vector2 back = tip - dir * length;
|
||||
a = tip;
|
||||
b = back + side * halfWidth;
|
||||
c = back - side * halfWidth;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where the label's box (<paramref name="size"/>) goes: to the right of a marker at
|
||||
/// <paramref name="anchor"/>, <paramref name="gap"/> px clear of it, vertically centred; on the left when
|
||||
/// it would run past <paramref name="boundsMax"/>; then kept inside the bounds as far as it fits.
|
||||
/// </summary>
|
||||
public static Vector2 LabelPos(Vector2 anchor, float gap, Vector2 size, Vector2 boundsMin, Vector2 boundsMax)
|
||||
{
|
||||
float x = anchor.X + gap;
|
||||
if (x + size.X > boundsMax.X) x = anchor.X - gap - size.X;
|
||||
float y = anchor.Y - size.Y * 0.5f;
|
||||
x = MathF.Max(boundsMin.X, MathF.Min(x, boundsMax.X - size.X));
|
||||
y = MathF.Max(boundsMin.Y, MathF.Min(y, boundsMax.Y - size.Y));
|
||||
return new Vector2(x, y);
|
||||
}
|
||||
}
|
||||
|
|
@ -562,6 +562,15 @@ internal sealed class RynthNavFace : IImGuiPanel
|
|||
SectionLabel("WHERE YOUR RECALLS LAND");
|
||||
foreach (string line in st.MineLines) Wrapped(line, Text, iw);
|
||||
}
|
||||
// Lifestone Recall's landing, learned from the lifestone selected or stood at (/rnav tie lifestone).
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const string LsLabel = PhosphorIcons.MapPin + " My lifestone is the one selected";
|
||||
if (Button("##rc_tiels", LsLabel, p, new Vector2(Math.Min(iw, ButtonWidth(LsLabel) + 8), 22), Text, BtnFill))
|
||||
RynthNavCommands.Command("tie lifestone");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Select the lifestone you are tied to (or stand at it), then click: routes can use\nLifestone Recall from then on, without casting it once first. Also: /rnav tie lifestone");
|
||||
NextLine(p, 26);
|
||||
}
|
||||
}
|
||||
else Wrapped("Update RynthNav (0.6.1) to see your portal ties here and answer \"which tie was it?\" with a button.", Mute, iw);
|
||||
|
||||
|
|
@ -858,6 +867,19 @@ internal sealed class RynthNavFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
Label(view.Summary.Length > 0 ? view.Summary : RynthNavAtlas.Status.Length > 0 ? RynthNavAtlas.Status : "Loading…", Mute);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
// Recent: forget them (/rnav recent clear).
|
||||
if (_mode == AtlasMode.Recent && view.Rows.Length > 0)
|
||||
{
|
||||
Vector2 cp = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const string ClearLabel = PhosphorIcons.Eraser + " Forget recent places";
|
||||
if (Button("##atl_recent_clear", ClearLabel, cp, new Vector2(ButtonWidth(ClearLabel) + 8, 22), Text, BtnFill))
|
||||
{
|
||||
RynthNavCommands.Command("recent clear");
|
||||
PushQuery();
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Empty the Recent list (favorites stay). Also: /rnav recent clear");
|
||||
NextLine(cp, 26);
|
||||
}
|
||||
|
||||
// List
|
||||
float listH = Math.Max(60, origin.Y + size.Y - 6 - ImGuiNET.ImGui.GetCursorScreenPos().Y - DetailH - 4);
|
||||
|
|
|
|||
|
|
@ -13,6 +13,21 @@
|
|||
// gear a chat line and/or the system beep when a new match appears
|
||||
// (both off by default; they work with the panel closed).
|
||||
//
|
||||
// Compact (2026-10-31, the owner: "we should make a small version of it"; in
|
||||
// item-counter.lua's spirit): only the match rows, tighter, and docked no
|
||||
// frame or background (IImGuiPanel.Bare); clicks go through to the game except
|
||||
// over the rows (ClickThrough, worked out from the last frame's rows, as the
|
||||
// radar's dots). Each row: arrow, name, distance; the coordinates, then the
|
||||
// kind, when the window is wide enough (SenseLayout.Compact). After the first
|
||||
// row, two small buttons are always there (faint until the mouse is on the
|
||||
// panel; SenseLayout.OtherViews): collapse, and back to the full panel.
|
||||
// Collapsed: one line, "Sense: N"; a click on it (or the caret beside it)
|
||||
// opens it to compact. The full panel's add row has the compact and collapse
|
||||
// buttons. The look is kept in sense.txt
|
||||
// (view=...) and set by /rc sense compact on|off, collapse on|off. Moving and
|
||||
// resizing are the full panel's (the window keeps its place and size). Popped
|
||||
// out, or embedded in the Mini Remote, the frame stays; embedded is always full.
|
||||
//
|
||||
// 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)
|
||||
|
|
@ -62,6 +77,7 @@ internal sealed class SenseFace : IImGuiPanel
|
|||
"The distance shows when you and the object are both outdoors (or in surface buildings), or in the same dungeon. " +
|
||||
"Otherwise the row says elsewhere and gives the landblock.\n\n" +
|
||||
"Click a row to select it in game. Gear: a chat line or a beep when a new match appears.\n" +
|
||||
"The arrows-in button (or /rc sense compact on) shows just the matches, without the frame.\n" +
|
||||
"/rc sense opens and closes this panel.";
|
||||
|
||||
// ── State ───────────────────────────────────────────────────────────
|
||||
|
|
@ -72,6 +88,16 @@ internal sealed class SenseFace : IImGuiPanel
|
|||
private bool _openSettings;
|
||||
private bool _flashing;
|
||||
|
||||
// Compact / collapsed: the mouse is over what the last frame drew (rows, the line, the
|
||||
// buttons), so the window takes input; elsewhere it lets clicks through. A press that began
|
||||
// there keeps it until the button is released.
|
||||
private bool _hot, _pressHot;
|
||||
|
||||
/// <summary>Compact and collapsed are bare: docked, no frame or background.</summary>
|
||||
public bool Bare => SenseStore.Layout != SenseLayoutMode.Full;
|
||||
|
||||
public bool ClickThrough => Bare && !_hot && !_pressHot;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
SenseStore.EnsureLoadQueued();
|
||||
|
|
@ -82,6 +108,18 @@ internal sealed class SenseFace : IImGuiPanel
|
|||
public void OnHidden() => UiSources.Sense.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
SenseLayoutMode layout = SenseStore.Layout;
|
||||
if (layout != SenseLayoutMode.Full && !ImGuiPanelHost.DrawingEmbedded)
|
||||
{
|
||||
DrawSmall(layout);
|
||||
return;
|
||||
}
|
||||
_hot = _pressHot = false;
|
||||
DrawFull();
|
||||
}
|
||||
|
||||
private void DrawFull()
|
||||
{
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
DrawAddRow(w);
|
||||
|
|
@ -113,7 +151,7 @@ internal sealed class SenseFace : IImGuiPanel
|
|||
const float h = 22, iconW = 22;
|
||||
string addLabel = PhosphorIcons.Plus + " Add";
|
||||
float addW = ButtonWidth(addLabel);
|
||||
float boxW = Math.Max(60, w - addW - iconW * 2 - 12);
|
||||
float boxW = Math.Max(60, w - addW - iconW * 4 - 20);
|
||||
|
||||
bool enter = TextBox("##sense_input", _input, start, boxW,
|
||||
PhosphorIcons.MagnifyingGlass + " Name to watch for (* and ? wildcards)", out _,
|
||||
|
|
@ -124,6 +162,17 @@ internal sealed class SenseFace : IImGuiPanel
|
|||
if (enter || add) AddTerm();
|
||||
|
||||
float gx = start.X + boxW + 4 + addW + 4;
|
||||
// The view switch: compact, then collapsed (one line).
|
||||
if (IconButton("##sense_compact", PhosphorIcons.ArrowsInLineVertical, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill,
|
||||
enabled: SenseStore.Loaded))
|
||||
SenseStore.SetLayout(SenseLayoutMode.Compact);
|
||||
SafeImGui.SetItemTooltip(SenseLayout.SwitchTip(SenseLayoutMode.Compact));
|
||||
gx += iconW + 4;
|
||||
if (IconButton("##sense_collapse", PhosphorIcons.CaretUp, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill,
|
||||
enabled: SenseStore.Loaded))
|
||||
SenseStore.SetLayout(SenseLayoutMode.Collapsed);
|
||||
SafeImGui.SetItemTooltip(SenseLayout.SwitchTip(SenseLayoutMode.Collapsed));
|
||||
gx += iconW + 4;
|
||||
if (IconButton("##sense_gear", PhosphorIcons.Gear, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill))
|
||||
_openSettings = true;
|
||||
ImGuiNET.ImGui.SetItemTooltip("Alerts");
|
||||
|
|
@ -344,6 +393,218 @@ internal sealed class SenseFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
// ── Compact and collapsed (bare) ────────────────────────────────────
|
||||
|
||||
private static readonly uint Shadow = 0xB0000000;
|
||||
|
||||
/// <summary>
|
||||
/// The bare looks: compact (the match rows only) or collapsed ("Sense: N"). Works out
|
||||
/// <see cref="_hot"/> for the next frame's <see cref="ClickThrough"/> from what it draws.
|
||||
/// </summary>
|
||||
private void DrawSmall(SenseLayoutMode layout)
|
||||
{
|
||||
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
|
||||
bool popped = ImGuiPopOuts.InPopOutFrame;
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, Vector2.Zero);
|
||||
try
|
||||
{
|
||||
SenseView view = UiSources.Sense.Current?.Value ?? SenseView.Empty;
|
||||
Vector2 mouse = ImGuiNET.ImGui.GetIO().MousePos;
|
||||
bool wasHot = _hot;
|
||||
float k = MathF.Max(0.5f, ImGuiNET.ImGui.GetFontSize() / 10f);
|
||||
_flashing = false;
|
||||
|
||||
Vector2 drawnMax = layout == SenseLayoutMode.Collapsed || view.Rows.Length == 0
|
||||
? DrawCollapsedLine(origin, view, collapsed: layout == SenseLayoutMode.Collapsed, k)
|
||||
: DrawCompactRows(origin, size, view, k);
|
||||
|
||||
// The view switch after the first line, always there (2026-10-31: a control you can
|
||||
// see, not one that shows on hover): faint until the mouse is on the panel.
|
||||
float bh = MathF.Round(SenseLayout.CompactRowHeight * k), bw = bh + 2;
|
||||
Vector2 bp = new(drawnMax.X + 4, origin.Y);
|
||||
Vector2 buttonsMax = bp + new Vector2(bw * 2 + 2, bh);
|
||||
if (SenseStore.Loaded)
|
||||
{
|
||||
bool lit = wasHot || popped;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.AddRectFilled(bp - new Vector2(2, 0), buttonsMax + new Vector2(2, 0), WithAlpha(ShellBg, lit ? 0.85f : 0.45f), 3);
|
||||
(SenseLayoutMode first, SenseLayoutMode second) = SenseLayout.OtherViews(layout);
|
||||
ViewButton("##sense_v1", first, bp, new Vector2(bw, bh), lit);
|
||||
ViewButton("##sense_v2", second, bp + new Vector2(bw + 2, 0), new Vector2(bw, bh), lit);
|
||||
}
|
||||
|
||||
// Hot for the next frame: the mouse over what was drawn or the view switch, or (once hot)
|
||||
// the strip out to the buttons.
|
||||
bool over = SenseStore.Loaded
|
||||
? SenseLayout.TakesMouse(mouse.X, mouse.Y, origin.X, origin.Y, drawnMax.X, drawnMax.Y, bp.X - 2, buttonsMax.X + 2, buttonsMax.Y, wasHot)
|
||||
: SenseLayout.IsHot(mouse.X, mouse.Y, origin.X, origin.Y, drawnMax.X, drawnMax.Y, buttonsMax.X, buttonsMax.Y, wasHot);
|
||||
_hot = over;
|
||||
bool down = ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left);
|
||||
if (!down) _pressHot = false;
|
||||
else if (over && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) _pressHot = true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(origin);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(1, 1));
|
||||
}
|
||||
|
||||
/// <summary>One button of the view switch: to <paramref name="to"/> (its own glyph). <paramref name="lit"/>: full strength.</summary>
|
||||
private static void ViewButton(string id, SenseLayoutMode to, Vector2 pos, Vector2 size, bool lit)
|
||||
{
|
||||
string glyph = to switch
|
||||
{
|
||||
SenseLayoutMode.Compact => PhosphorIcons.CaretDown,
|
||||
SenseLayoutMode.Collapsed => PhosphorIcons.CaretUp,
|
||||
_ => PhosphorIcons.ArrowsOutLineVertical,
|
||||
};
|
||||
if (IconButton(id, glyph, pos, size, lit ? Text : Faded(Text), lit ? BtnFill : WithAlpha(BtnFill, 0.5f), font: UiFont.Ui11))
|
||||
SenseStore.SetLayout(to);
|
||||
SafeImGui.SetItemTooltip(SenseLayout.SwitchTip(to));
|
||||
}
|
||||
|
||||
/// <summary>"Sense: N" (collapsed, or compact with nothing to show). Click opens a collapsed one. Returns its far corner.</summary>
|
||||
private Vector2 DrawCollapsedLine(Vector2 origin, SenseView view, bool collapsed, float k)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float rowH = MathF.Round(SenseLayout.CompactRowHeight * k);
|
||||
string text = SenseLayout.CollapsedText(view.Rows.Length);
|
||||
float tw = ImGuiNET.ImGui.CalcTextSize(text).X;
|
||||
float iconW = rowH;
|
||||
Vector2 size = new(iconW + tw + 4, rowH);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(origin);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton("##sense_line", size);
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
if (hot)
|
||||
{
|
||||
dl.AddRectFilled(origin, origin + size, WithAlpha(ShellBg, 0.7f), 3);
|
||||
ImGuiNET.ImGui.BeginTooltip();
|
||||
ImGuiNET.ImGui.TextUnformatted(view.Status.Length > 0 ? view.Status : "Scanning...");
|
||||
ImGuiNET.ImGui.TextUnformatted(collapsed ? "Click to show the matches." : "Nothing matching to show.");
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
if (clicked && collapsed) SenseStore.SetLayout(SenseLayoutMode.Compact);
|
||||
|
||||
uint col = view.Rows.Length > 0 ? Amber : Faded(Text);
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Binoculars, origin + new Vector2(1, 1), new Vector2(iconW, rowH), Shadow);
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Binoculars, origin, new Vector2(iconW, rowH), col);
|
||||
ShadowText(dl, new Vector2(origin.X + iconW + 2, origin.Y + (rowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), view.Rows.Length > 0 ? Text : Faded(Text), text);
|
||||
return origin + size;
|
||||
}
|
||||
|
||||
/// <summary>The compact rows: arrow, name, distance, then the coordinates and the kind when they fit. Returns the far corner.</summary>
|
||||
private Vector2 DrawCompactRows(Vector2 origin, Vector2 size, SenseView view, float k)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
SenseRow[] rows = view.Rows;
|
||||
float rowH = MathF.Max(MathF.Round(SenseLayout.CompactRowHeight * k), MathF.Ceiling(ImGuiNET.ImGui.GetFontSize() + 3));
|
||||
(int shown, bool more) = SenseLayout.CompactFit(size.Y, rowH, rows.Length);
|
||||
SenseCompactColumns cols = SenseLayout.Compact(size.X, k);
|
||||
float arrowW = SenseLayout.CompactArrowWidth * k, distW = SenseLayout.CompactDistWidth * k,
|
||||
locW = SenseLayout.CompactLocWidth * k, kindW = SenseLayout.CompactKindWidth * k;
|
||||
|
||||
// The name column is as wide as the longest name shown (up to what the layout allows),
|
||||
// so the rows end where their text does: past that, clicks reach the game.
|
||||
float nameW = 0;
|
||||
for (int i = 0; i < shown; i++) nameW = MathF.Max(nameW, ImGuiNET.ImGui.CalcTextSize(rows[i].Name).X);
|
||||
nameW = MathF.Min(nameW + 8, cols.NameWidth);
|
||||
float used = arrowW + nameW + distW + (cols.Location ? locW : 0) + (cols.Kind ? kindW : 0);
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
uint selected = ClientHelperHooks.GetSelectedItemId();
|
||||
float heading = PlayerHeading(out bool haveHeading);
|
||||
float fontH = ImGuiNET.ImGui.GetFontSize();
|
||||
int clicked = -1, hovered = -1;
|
||||
for (int i = 0; i < shown; i++)
|
||||
{
|
||||
SenseRow r = rows[i];
|
||||
var p = new Vector2(origin.X, origin.Y + i * rowH);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##crow", new Vector2(used, rowH))) clicked = i;
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
if (hot) hovered = i;
|
||||
|
||||
bool isSel = r.Id == selected;
|
||||
if (hot) dl.AddRectFilled(p, p + new Vector2(used, rowH), WithAlpha(ShellBg, 0.7f), 2);
|
||||
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(used, rowH), WithAlpha(Amber, a), 2);
|
||||
}
|
||||
}
|
||||
if (isSel) dl.AddRect(p, p + new Vector2(used, rowH), Teal, 2);
|
||||
|
||||
Vector2 mid = p + new Vector2(arrowW * 0.5f, rowH * 0.5f);
|
||||
uint kc = KindColor(r.Kind);
|
||||
if (r.Measured && haveHeading && !float.IsNaN(r.Bearing))
|
||||
{
|
||||
DrawArrow(dl, mid + new Vector2(1, 1), r.Bearing - heading, Shadow);
|
||||
DrawArrow(dl, mid, r.Bearing - heading, kc);
|
||||
}
|
||||
else if (r.Measured)
|
||||
dl.AddCircleFilled(mid, 2.5f, kc);
|
||||
else
|
||||
dl.AddCircle(mid, 3.5f, Faded(Mute), 12, 1.2f);
|
||||
|
||||
float ty = p.Y + (rowH - fontH) * 0.5f;
|
||||
float x = p.X + arrowW;
|
||||
ShadowCell(dl, r.Name, x, ty, nameW - 4, r.Measured ? Text : Mute);
|
||||
x += nameW;
|
||||
ShadowCell(dl, r.DistanceText, x, ty, distW - 4, r.Measured ? Text : Faded(Text));
|
||||
x += distW;
|
||||
if (cols.Location) { ShadowCell(dl, r.LocationText, x, ty, locW - 4, Mute); x += locW; }
|
||||
if (cols.Kind) ShadowCell(dl, SenseSource.KindName(r.Kind), x, ty, kindW - 4, kc);
|
||||
}
|
||||
int slots = shown;
|
||||
if (more)
|
||||
{
|
||||
// Rows that don't fit (the window keeps the full panel's size): how many, in the last slot.
|
||||
var p = new Vector2(origin.X, origin.Y + shown * rowH);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.InvisibleButton("##cmore", new Vector2(used, rowH));
|
||||
ImGuiNET.ImGui.SetItemTooltip("More matches than fit: make the panel taller in its full view (/rc sense compact off).");
|
||||
ShadowText(dl, new Vector2(p.X + arrowW, p.Y + (rowH - fontH) * 0.5f), Mute, SenseLayout.MoreText(rows.Length - shown));
|
||||
slots++;
|
||||
}
|
||||
|
||||
if (clicked >= 0)
|
||||
AcMainThreadQueue.EnqueueOverlaySelect(rows[clicked].Id);
|
||||
if (hovered >= 0)
|
||||
{
|
||||
ImGuiNET.ImGui.BeginTooltip();
|
||||
ImGuiNET.ImGui.TextUnformatted(rows[hovered].Tooltip);
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
return origin + new Vector2(used, slots * rowH);
|
||||
}
|
||||
|
||||
private static void ShadowText(ImDrawListPtr dl, Vector2 at, uint color, string text)
|
||||
{
|
||||
if (text.Length == 0) return;
|
||||
dl.AddText(at + new Vector2(1, 1), Shadow, text);
|
||||
dl.AddText(at, color, text);
|
||||
}
|
||||
|
||||
private static void ShadowCell(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);
|
||||
ShadowText(dl, new Vector2(x, y), color, text);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
|
||||
private static void Cell(ImDrawListPtr dl, string text, float x, float y, float width, uint color)
|
||||
{
|
||||
if (text.Length == 0 || width <= 0) return;
|
||||
|
|
|
|||
|
|
@ -251,7 +251,19 @@ internal sealed class SettingsRows
|
|||
ImGuiNET.ImGui.TextUnformatted(row.Label);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f));
|
||||
if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label))
|
||||
bool clicked = ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label);
|
||||
Tooltip(row);
|
||||
if (row.Confirm != null)
|
||||
{
|
||||
// Asks first: the question, then the button's own caption to go ahead, or Cancel.
|
||||
if (clicked)
|
||||
{
|
||||
_confirmText = row.Confirm();
|
||||
ImGuiNET.ImGui.OpenPopup("##confirm");
|
||||
}
|
||||
clicked = ConfirmPopup(row.ButtonText ?? row.Label);
|
||||
}
|
||||
if (clicked)
|
||||
{
|
||||
// A settings edit is applied to this copy and saved like a typed value (the number
|
||||
// boxes re-sync from the copy next frame); Click, when also set, runs after.
|
||||
|
|
@ -262,7 +274,33 @@ internal sealed class SettingsRows
|
|||
}
|
||||
row.Click?.Invoke();
|
||||
}
|
||||
Tooltip(row);
|
||||
}
|
||||
|
||||
private string _confirmText = string.Empty;
|
||||
|
||||
/// <summary>The open confirmation (the row's ID scope): true when the player went ahead.</summary>
|
||||
private bool ConfirmPopup(string caption)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(12, 10));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##confirm");
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
if (!open) return false;
|
||||
bool go = false;
|
||||
try
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
|
||||
ImGuiNET.ImGui.TextUnformatted(_confirmText);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
if (ImGuiNET.ImGui.Button(caption.TrimEnd('.') + "##confirm_go")) { go = true; ImGuiNET.ImGui.CloseCurrentPopup(); }
|
||||
ImGuiNET.ImGui.SameLine(0, 8);
|
||||
if (ImGuiNET.ImGui.Button("Cancel##confirm_no")) ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
finally { ImGuiNET.ImGui.EndPopup(); }
|
||||
return go;
|
||||
}
|
||||
|
||||
private void Changed(SettingRow row, double value)
|
||||
|
|
|
|||
216
src/RynthCore.Engine/ImGui/UiCost.cs
Normal file
216
src/RynthCore.Engine/ImGui/UiCost.cs
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/UiCost.cs
|
||||
// Which part of the UI frame is slow: the breakdown behind the heartbeat's
|
||||
// ui= (UiFrameStats). The logic is in UiCostModel (tested offline); this is
|
||||
// the engine side - the slots by name, the settings, the log line, the
|
||||
// heartbeat field and /rc uicost.
|
||||
//
|
||||
// Timed (each one Start/Stop pair around a call, on AC's render thread):
|
||||
// frame setup (fonts, icon textures, backends' NewFrame), the monster HUD
|
||||
// update and draw (plates, combat text; from EngineFrameController, the
|
||||
// HUD's own code is not touched), ImGui NewFrame and EndFrame+Render, the
|
||||
// shell, each plugin's Render / RenderOverlay callback (by plugin), the bar,
|
||||
// the server menus, the panel host's upkeep, each docked panel and plugin
|
||||
// window (by title), each popped-out panel (by title) and its pop-out window
|
||||
// (its own frame, render and present), the ImGui submit (with its vertex
|
||||
// count), and outside ui= the Nav3D markers and the world overlays' present
|
||||
// at AC's 3D->UI pass.
|
||||
// Counted (no timing): the main submit's draw lists, draw calls, texture
|
||||
// switches and vertices copied, against what copying each command's whole list
|
||||
// would have been (DrawSubmitPlan), and the textures uploaded that frame (the
|
||||
// font atlas, the others). The line ends "| submit: ...; uploads: ...", the
|
||||
// heartbeat field adds " uisub=draws:N,texsw:N,vtx:copied/whole-list,up:font/tex".
|
||||
//
|
||||
// engine.json UiCostLog (default on) and UiCostThresholdMs (default 50):
|
||||
// Settings > Diagnostics, /rc uicost [on|off|<ms>|now]. Off = no timing at
|
||||
// all (each site is one flag check). On, a frame at or over the threshold
|
||||
// writes ONE "[UiCost] frame ..." line, at most once every 5 s; the
|
||||
// heartbeat gets " uitop=..." only while its ui p95 is over the threshold.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static class UiCost
|
||||
{
|
||||
private static readonly UiCostModel Model = new(Stopwatch.Frequency);
|
||||
private static readonly object Sync = new();
|
||||
|
||||
// Fixed parts of the frame.
|
||||
internal static readonly int FrameSetup = Model.Register("Frame setup");
|
||||
internal static readonly int HudUpdate = Model.Register("Monster HUD update");
|
||||
internal static readonly int ImGuiNewFrame = Model.Register("ImGui NewFrame");
|
||||
internal static readonly int Shell = Model.Register("Shell");
|
||||
internal static readonly int MonsterHud = Model.Register("Monster HUD (plates, combat text)", unit: "plates");
|
||||
internal static readonly int VideoBanner = Model.Register("Video patch banner");
|
||||
internal static readonly int ServerMenus = Model.Register("Server menus");
|
||||
internal static readonly int Bar = Model.Register("Bar");
|
||||
internal static readonly int PanelHost = Model.Register("Panel host upkeep", unit: "panels");
|
||||
internal static readonly int DrawerBodies = Model.Register("Settings drawer bodies");
|
||||
internal static readonly int ImGuiRender = Model.Register("ImGui EndFrame+Render");
|
||||
internal static readonly int FrameFinish = Model.Register("Frame finish (ini, input)");
|
||||
internal static readonly int PopOuts = Model.Register("Pop-outs upkeep");
|
||||
internal static readonly int Submit = Model.Register("ImGui submit", unit: "vtx");
|
||||
internal static readonly int Nav3D = Model.Register("Nav3D markers", outside: true);
|
||||
internal static readonly int WorldPresent = Model.Register("World overlays present", outside: true);
|
||||
|
||||
// Named parts, a slot each the first time the name is seen (render thread only).
|
||||
private static readonly Dictionary<string, int> PanelSlots = new(StringComparer.Ordinal);
|
||||
private static readonly Dictionary<string, int> Popped = new(StringComparer.Ordinal);
|
||||
private static readonly Dictionary<string, int> PopOutWindows = new(StringComparer.Ordinal);
|
||||
private static readonly Dictionary<string, int> PluginRender = new(StringComparer.Ordinal);
|
||||
private static readonly Dictionary<string, int> PluginOverlay = new(StringComparer.Ordinal);
|
||||
|
||||
private static bool _settingsRead;
|
||||
|
||||
/// <summary>Timing on (engine.json UiCostLog). Read once per frame from the settings.</summary>
|
||||
public static bool Enabled => Model.Enabled;
|
||||
|
||||
/// <summary>A timestamp for a Stop, or 0 while timing is off.</summary>
|
||||
public static long Start()
|
||||
{
|
||||
if (!_settingsRead) RefreshSettings();
|
||||
return Model.Start();
|
||||
}
|
||||
|
||||
public static void Stop(int slot, long start, int count = -1) => Model.Stop(slot, start, count);
|
||||
|
||||
/// <summary>What the slots got this frame so far, for <see cref="StopExclusive"/>.</summary>
|
||||
public static long Mark => Model.Mark;
|
||||
|
||||
public static void StopExclusive(int slot, long start, long mark, int count = -1) => Model.StopExclusive(slot, start, mark, count);
|
||||
|
||||
/// <summary>The main ImGui submit's counters (DX9Backend.LastSubmit right after it), for the line and the heartbeat.</summary>
|
||||
public static void SetSubmit(in SubmitStats stats)
|
||||
{
|
||||
if (Model.Enabled) Model.SetSubmit(stats);
|
||||
}
|
||||
|
||||
/// <summary>A docked panel or plugin window, by its title.</summary>
|
||||
public static void StopPanel(string title, long start)
|
||||
{
|
||||
if (start == 0) return;
|
||||
Model.Stop(SlotFor(PanelSlots, title, ""), start);
|
||||
}
|
||||
|
||||
/// <summary>A popped-out panel's drawing, by its title.</summary>
|
||||
public static void StopPopped(string title, long start)
|
||||
{
|
||||
if (start == 0) return;
|
||||
Model.Stop(SlotFor(Popped, title, " (popped out)"), start);
|
||||
}
|
||||
|
||||
/// <summary>A pop-out window's own frame, render and present (its panel's drawing not included).</summary>
|
||||
public static void StopPopOutWindow(string title, long start, long mark)
|
||||
{
|
||||
if (start == 0) return;
|
||||
Model.StopExclusive(SlotFor(PopOutWindows, title, " pop-out window"), start, mark);
|
||||
}
|
||||
|
||||
/// <summary>A plugin's Render callback (the shell branch).</summary>
|
||||
public static void StopPluginRender(string plugin, long start)
|
||||
{
|
||||
if (start == 0) return;
|
||||
Model.Stop(SlotFor(PluginRender, plugin, " (plugin render)"), start);
|
||||
}
|
||||
|
||||
/// <summary>A plugin's RenderOverlay callback (its overlay windows).</summary>
|
||||
public static void StopPluginOverlay(string plugin, long start)
|
||||
{
|
||||
if (start == 0) return;
|
||||
Model.Stop(SlotFor(PluginOverlay, plugin, " (plugin overlay)"), start);
|
||||
}
|
||||
|
||||
private static int SlotFor(Dictionary<string, int> map, string name, string suffix)
|
||||
{
|
||||
if (map.TryGetValue(name, out int slot)) return slot;
|
||||
slot = Model.Register(string.IsNullOrEmpty(name) ? "(no name)" + suffix : name + suffix);
|
||||
map[name] = slot;
|
||||
return slot;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The end of a UI frame, where UiFrameStats records it (<paramref name="uiTicks"/> is the same
|
||||
/// number). Writes the slow-frame line when one is due. Render thread.
|
||||
/// </summary>
|
||||
public static void EndFrame(long uiTicks)
|
||||
{
|
||||
RefreshSettings();
|
||||
DX9Backend.TakeUploads(out int fontUploads, out int texUploads); // this frame's (also cleared while off)
|
||||
if (!Model.Enabled && Model.Mark == 0) return; // off, and nothing left from a frame that was on
|
||||
Model.AddUploads(fontUploads, texUploads);
|
||||
string? line;
|
||||
lock (Sync) line = Model.EndFrame(uiTicks, Stopwatch.GetTimestamp(), logSlow: Model.Enabled);
|
||||
if (line != null) RynthLog.Info(line);
|
||||
}
|
||||
|
||||
/// <summary>No UI frame this EndScene (the ImGui layer is off): what was timed is dropped. Render thread.</summary>
|
||||
public static void DiscardFrame()
|
||||
{
|
||||
if (Model.Mark != 0) Model.DiscardFrame();
|
||||
}
|
||||
|
||||
private static void RefreshSettings()
|
||||
{
|
||||
_settingsRead = true;
|
||||
Model.Enabled = Plugins.EngineSettings.UiCostLog;
|
||||
int ms = Plugins.EngineSettings.UiCostThresholdMs;
|
||||
if (ms != Model.ThresholdMs) lock (Sync) Model.ThresholdMs = ms;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The heartbeat's " uitop=a:avg/max,b:avg/max,c:avg/max" (the window's top 3 by average), only
|
||||
/// while timing is on and <paramref name="uiP95Ms"/> is at or over the threshold; otherwise "".
|
||||
/// Heartbeat thread.
|
||||
/// </summary>
|
||||
public static string HeartbeatField(float uiP95Ms)
|
||||
{
|
||||
if (!Model.Enabled || uiP95Ms < Model.ThresholdMs) return "";
|
||||
lock (Sync) return Model.HeartbeatField(Stopwatch.GetTimestamp(), 3);
|
||||
}
|
||||
|
||||
/// <summary>/rc uicost [on|off|<ms>|now|status]: the reply lines (every form answers).</summary>
|
||||
public static List<string> HandleCommand(string args)
|
||||
{
|
||||
string a = (args ?? "").Trim().ToLowerInvariant();
|
||||
var lines = new List<string>();
|
||||
if (a is "on" or "off")
|
||||
{
|
||||
Plugins.EngineSettings.UiCostLog = a == "on";
|
||||
RefreshSettings();
|
||||
lines.Add(a == "on"
|
||||
? $"UI cost timing on: a UI frame of {Model.ThresholdMs} ms or more writes one [UiCost] line to the log (at most every 5 s)."
|
||||
: "UI cost timing off: nothing is timed or logged. /rc uicost on starts it again.");
|
||||
return lines;
|
||||
}
|
||||
if (a.EndsWith("ms", StringComparison.Ordinal)) a = a.Substring(0, a.Length - 2).Trim();
|
||||
if (int.TryParse(a, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int ms))
|
||||
{
|
||||
int v = UiCostModel.ClampThresholdMs(ms);
|
||||
Plugins.EngineSettings.UiCostThresholdMs = v;
|
||||
RefreshSettings();
|
||||
string clamped = v != ms ? $" (kept to {UiCostModel.MinThresholdMs}-{UiCostModel.MaxThresholdMs})" : "";
|
||||
lines.Add($"UI cost threshold {v} ms{clamped}; timing {(Model.Enabled ? "on" : "off - /rc uicost on to log")}.");
|
||||
return lines;
|
||||
}
|
||||
if (a is "now" or "")
|
||||
{
|
||||
lock (Sync) lines.AddRange(Model.Describe(Stopwatch.GetTimestamp()));
|
||||
if (!Model.Enabled) lines.Add("Timing is off, so this shows nothing new: /rc uicost on.");
|
||||
return lines;
|
||||
}
|
||||
if (a == "status")
|
||||
{
|
||||
lines.Add($"UI cost timing {(Model.Enabled ? "on" : "off")}, threshold {Model.ThresholdMs} ms, {Model.SlotCount} parts named, " +
|
||||
$"{Model.FramesSeen} frames timed, {Model.LinesWritten} slow-frame lines logged.");
|
||||
return lines;
|
||||
}
|
||||
lines.Add(Usage);
|
||||
return lines;
|
||||
}
|
||||
|
||||
public const string Usage = Compatibility.ChatCommandReplies.UiCostUsage;
|
||||
}
|
||||
649
src/RynthCore.Engine/ImGui/UiCostModel.cs
Normal file
649
src/RynthCore.Engine/ImGui/UiCostModel.cs
Normal file
|
|
@ -0,0 +1,649 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/UiCostModel.cs
|
||||
// The UI frame cost breakdown (ImGui/UiCost.cs): which part of the UI frame
|
||||
// takes the time. Pure logic, no engine types (tools/UiCostTests compiles it).
|
||||
//
|
||||
// Each timed part of a frame is a slot (a docked panel by title, a plugin's
|
||||
// render callback, the monster HUD, the ImGui submit, ...). Start/Stop add the
|
||||
// ticks of one call to the slot for this frame; EndFrame folds the frame into
|
||||
// a rolling window (Buckets x 1 s) and, when the frame's UI time is over the
|
||||
// threshold and no line was written in the last LogIntervalSeconds, returns
|
||||
// ONE line naming the frame's biggest parts. Nothing allocates per frame:
|
||||
// the arrays are fixed, a slot's name is made once, and strings are built only
|
||||
// for that line and for the summaries (/rc uicost now, the heartbeat field).
|
||||
//
|
||||
// "Outside" slots (the Nav3D markers and the world overlays' present at AC's
|
||||
// 3D->UI pass) cost render time but are not part of the heartbeat's ui=; they
|
||||
// are listed apart. Whatever the frame spent that no slot covers is "untimed"
|
||||
// (Dear ImGui's own work between the timed calls, input, ini saves...).
|
||||
//
|
||||
// Threads: Register, Start, Stop and EndFrame on AC's render thread; the
|
||||
// summaries from any thread, with the caller holding one lock around them and
|
||||
// EndFrame (UiCost does).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal sealed class UiCostModel
|
||||
{
|
||||
public const int DefaultThresholdMs = 50;
|
||||
public const int MinThresholdMs = 5;
|
||||
public const int MaxThresholdMs = 2000;
|
||||
public const int MaxSlots = 160;
|
||||
/// <summary>The rolling window: this many 1 s buckets (the summaries cover the last 4-5 s).</summary>
|
||||
public const int Buckets = 5;
|
||||
public const int LogIntervalSeconds = 5;
|
||||
/// <summary>Parts named in a slow-frame line; the rest are summed as "+N more".</summary>
|
||||
public const int LineTopItems = 8;
|
||||
|
||||
/// <summary>A threshold from a setting or a command, kept in range.</summary>
|
||||
public static int ClampThresholdMs(int ms) => Math.Clamp(ms, MinThresholdMs, MaxThresholdMs);
|
||||
|
||||
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
|
||||
|
||||
private readonly long _freq;
|
||||
private readonly long _bucketTicks;
|
||||
private readonly long _logIntervalTicks;
|
||||
|
||||
// Slots.
|
||||
private readonly string[] _names = new string[MaxSlots];
|
||||
private readonly string?[] _units = new string?[MaxSlots];
|
||||
private readonly bool[] _outside = new bool[MaxSlots];
|
||||
private int _slotCount;
|
||||
/// <summary>Slot 0: names past MaxSlots share it.</summary>
|
||||
public const int OverflowSlot = 0;
|
||||
|
||||
// This frame.
|
||||
private readonly long[] _fTicks = new long[MaxSlots];
|
||||
private readonly int[] _fCount = new int[MaxSlots];
|
||||
private readonly int[] _fCalls = new int[MaxSlots];
|
||||
private readonly int[] _touched = new int[MaxSlots];
|
||||
private int _touchedCount;
|
||||
private long _fAll, _fOutside;
|
||||
// This frame's ImGui submit counters (SubmitStats, end of this file) and texture uploads.
|
||||
private SubmitStats _fSubmit;
|
||||
private bool _fHasSubmit;
|
||||
private int _fFontUploads, _fTexUploads;
|
||||
|
||||
// The window, one row per bucket.
|
||||
private readonly long[] _bStart = new long[Buckets];
|
||||
private readonly long[] _bFrames = new long[Buckets];
|
||||
private readonly long[] _bUiSum = new long[Buckets];
|
||||
private readonly long[] _bUiMax = new long[Buckets];
|
||||
private readonly long[] _bSlow = new long[Buckets];
|
||||
private readonly long[] _bUntimedSum = new long[Buckets];
|
||||
private readonly long[] _bUntimedMax = new long[Buckets];
|
||||
private readonly long[,] _bSum = new long[Buckets, MaxSlots];
|
||||
private readonly long[,] _bMax = new long[Buckets, MaxSlots];
|
||||
private readonly int[,] _bMaxCount = new int[Buckets, MaxSlots];
|
||||
// The bucket's slowest frame, part by part.
|
||||
private readonly long[,] _bWorst = new long[Buckets, MaxSlots];
|
||||
private readonly int[,] _bWorstCount = new int[Buckets, MaxSlots];
|
||||
private readonly long[] _bWorstUntimed = new long[Buckets];
|
||||
// The bucket's submit counters (each one's largest frame) and uploads (summed).
|
||||
private readonly SubmitStats[] _bSubmitMax = new SubmitStats[Buckets];
|
||||
private readonly bool[] _bHasSubmit = new bool[Buckets];
|
||||
private readonly long[] _bFontUploads = new long[Buckets];
|
||||
private readonly long[] _bTexUploads = new long[Buckets];
|
||||
private int _cur = -1;
|
||||
|
||||
private long _lastLogAt;
|
||||
private bool _loggedOnce;
|
||||
private int _thresholdMs = DefaultThresholdMs;
|
||||
private long _thresholdTicks;
|
||||
|
||||
// Scratch for sorting (render thread for the frame line; under the caller's lock for summaries).
|
||||
private readonly int[] _order = new int[MaxSlots + 1];
|
||||
private readonly long[] _orderTicks = new long[MaxSlots + 1];
|
||||
private readonly long[] _winSum = new long[MaxSlots];
|
||||
private readonly long[] _winMax = new long[MaxSlots];
|
||||
private readonly int[] _winMaxCount = new int[MaxSlots];
|
||||
private SubmitStats _winSubmit;
|
||||
private bool _winHasSubmit;
|
||||
private long _winFontUploads, _winTexUploads;
|
||||
|
||||
/// <summary>Timing on: Start returns a timestamp; off: 0 and every Stop is a no-op.</summary>
|
||||
public bool Enabled;
|
||||
|
||||
/// <summary>Frames folded into the window since the start (diagnostics, tests).</summary>
|
||||
public long FramesSeen { get; private set; }
|
||||
|
||||
/// <summary>Slow-frame lines returned by EndFrame since the start.</summary>
|
||||
public long LinesWritten { get; private set; }
|
||||
|
||||
public UiCostModel(long ticksPerSecond)
|
||||
{
|
||||
_freq = Math.Max(1, ticksPerSecond);
|
||||
_bucketTicks = _freq;
|
||||
_logIntervalTicks = _freq * LogIntervalSeconds;
|
||||
ThresholdMs = DefaultThresholdMs;
|
||||
Register("(more names)");
|
||||
for (int i = 0; i < MaxSlots; i++) _fCount[i] = -1;
|
||||
}
|
||||
|
||||
/// <summary>A frame at or over this many ms is slow (logged, counted).</summary>
|
||||
public int ThresholdMs
|
||||
{
|
||||
get => _thresholdMs;
|
||||
set
|
||||
{
|
||||
_thresholdMs = ClampThresholdMs(value);
|
||||
_thresholdTicks = _thresholdMs * _freq / 1000;
|
||||
}
|
||||
}
|
||||
|
||||
public int SlotCount => Volatile.Read(ref _slotCount);
|
||||
|
||||
public string SlotName(int slot) => (uint)slot < (uint)SlotCount ? _names[slot] : "?";
|
||||
|
||||
/// <summary>
|
||||
/// A new slot. <paramref name="unit"/> names the count passed to Stop ("plates", "vtx"), null for
|
||||
/// none; <paramref name="outside"/>: not part of the frame's UI time (listed apart). Past
|
||||
/// MaxSlots the overflow slot. Render thread (the summaries read only slots already published).
|
||||
/// </summary>
|
||||
public int Register(string name, string? unit = null, bool outside = false)
|
||||
{
|
||||
int n = _slotCount;
|
||||
if (n >= MaxSlots) return OverflowSlot;
|
||||
_names[n] = name;
|
||||
_units[n] = unit;
|
||||
_outside[n] = outside;
|
||||
Volatile.Write(ref _slotCount, n + 1);
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>A timestamp to pass to Stop, or 0 while timing is off.</summary>
|
||||
public long Start() => Enabled ? Stopwatch.GetTimestamp() : 0;
|
||||
|
||||
/// <summary>Adds the time since <paramref name="start"/> (from Start) to <paramref name="slot"/>; a no-op for 0.</summary>
|
||||
public void Stop(int slot, long start, int count = -1)
|
||||
{
|
||||
if (start == 0) return;
|
||||
Add(slot, Stopwatch.GetTimestamp() - start, count);
|
||||
}
|
||||
|
||||
/// <summary>The ticks every slot got this frame so far: Mark before a part, StopExclusive after it.</summary>
|
||||
public long Mark => _fAll;
|
||||
|
||||
/// <summary>
|
||||
/// As Stop, less what the slots timed inside it got (since <paramref name="mark"/>): a part that
|
||||
/// draws other timed parts (the panel host around its panels, a pop-out window around its panel)
|
||||
/// keeps only its own time, so nothing is counted twice.
|
||||
/// </summary>
|
||||
public void StopExclusive(int slot, long start, long mark, int count = -1)
|
||||
{
|
||||
if (start == 0) return;
|
||||
long ticks = Stopwatch.GetTimestamp() - start - (_fAll - mark);
|
||||
Add(slot, ticks < 0 ? 0 : ticks, count);
|
||||
}
|
||||
|
||||
/// <summary>Adds <paramref name="ticks"/> (and a count, when not negative) to a slot for this frame.</summary>
|
||||
public void Add(int slot, long ticks, int count = -1)
|
||||
{
|
||||
if ((uint)slot >= (uint)_slotCount) return;
|
||||
if (_fCalls[slot]++ == 0) _touched[_touchedCount++] = slot;
|
||||
_fTicks[slot] += ticks;
|
||||
if (count >= 0) _fCount[slot] = (_fCount[slot] < 0 ? 0 : _fCount[slot]) + count;
|
||||
_fAll += ticks;
|
||||
if (_outside[slot]) _fOutside += ticks;
|
||||
}
|
||||
|
||||
/// <summary>This frame's ImGui submit counters (the main submit; a second call this frame replaces them).</summary>
|
||||
public void SetSubmit(in SubmitStats stats)
|
||||
{
|
||||
_fSubmit = stats;
|
||||
_fHasSubmit = true;
|
||||
}
|
||||
|
||||
/// <summary>Textures made or re-uploaded this frame: the font atlas, and any other (icons, map tiles, pictures).</summary>
|
||||
public void AddUploads(int font, int tex)
|
||||
{
|
||||
if (font > 0) _fFontUploads += font;
|
||||
if (tex > 0) _fTexUploads += tex;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ends the frame: <paramref name="uiTicks"/> is its UI time (what the heartbeat's ui= records).
|
||||
/// Folds it into the window and returns the slow-frame line when one is due (over the threshold,
|
||||
/// none in the last LogIntervalSeconds, logging on), else null.
|
||||
/// </summary>
|
||||
public string? EndFrame(long uiTicks, long now, bool logSlow)
|
||||
{
|
||||
Rotate(now);
|
||||
int b = _cur;
|
||||
long inside = _fAll - _fOutside;
|
||||
long untimed = uiTicks - inside;
|
||||
if (untimed < 0) untimed = 0;
|
||||
|
||||
FramesSeen++;
|
||||
_bFrames[b]++;
|
||||
_bUiSum[b] += uiTicks;
|
||||
bool worst = uiTicks > _bUiMax[b] || _bFrames[b] == 1;
|
||||
if (uiTicks > _bUiMax[b]) _bUiMax[b] = uiTicks;
|
||||
bool slow = uiTicks >= _thresholdTicks;
|
||||
if (slow) _bSlow[b]++;
|
||||
_bUntimedSum[b] += untimed;
|
||||
if (untimed > _bUntimedMax[b]) _bUntimedMax[b] = untimed;
|
||||
|
||||
if (worst)
|
||||
{
|
||||
for (int s = 0; s < MaxSlots; s++) { _bWorst[b, s] = 0; _bWorstCount[b, s] = -1; }
|
||||
_bWorstUntimed[b] = untimed;
|
||||
}
|
||||
for (int i = 0; i < _touchedCount; i++)
|
||||
{
|
||||
int s = _touched[i];
|
||||
long t = _fTicks[s];
|
||||
_bSum[b, s] += t;
|
||||
if (t > _bMax[b, s]) _bMax[b, s] = t;
|
||||
if (_fCount[s] > _bMaxCount[b, s]) _bMaxCount[b, s] = _fCount[s];
|
||||
if (worst) { _bWorst[b, s] = t; _bWorstCount[b, s] = _fCount[s]; }
|
||||
}
|
||||
if (_fHasSubmit) { _bSubmitMax[b].MaxWith(_fSubmit); _bHasSubmit[b] = true; }
|
||||
_bFontUploads[b] += _fFontUploads;
|
||||
_bTexUploads[b] += _fTexUploads;
|
||||
|
||||
string? line = null;
|
||||
if (logSlow && slow && (!_loggedOnce || now - _lastLogAt >= _logIntervalTicks))
|
||||
{
|
||||
_loggedOnce = true;
|
||||
_lastLogAt = now;
|
||||
LinesWritten++;
|
||||
line = FormatFrameLine(uiTicks, untimed);
|
||||
}
|
||||
|
||||
DiscardFrame(); // clears only what this frame touched
|
||||
return line;
|
||||
}
|
||||
|
||||
/// <summary>Drops what this frame timed without folding it in (no UI frame this EndScene).</summary>
|
||||
public void DiscardFrame()
|
||||
{
|
||||
for (int i = 0; i < _touchedCount; i++)
|
||||
{
|
||||
int s = _touched[i];
|
||||
_fTicks[s] = 0;
|
||||
_fCalls[s] = 0;
|
||||
_fCount[s] = -1;
|
||||
}
|
||||
_touchedCount = 0;
|
||||
_fAll = 0;
|
||||
_fOutside = 0;
|
||||
_fSubmit = default;
|
||||
_fHasSubmit = false;
|
||||
_fFontUploads = _fTexUploads = 0;
|
||||
}
|
||||
|
||||
private void Rotate(long now)
|
||||
{
|
||||
if (_cur < 0)
|
||||
{
|
||||
_cur = 0;
|
||||
ClearBucket(0, now);
|
||||
return;
|
||||
}
|
||||
long age = now - _bStart[_cur];
|
||||
if (age < _bucketTicks) return;
|
||||
long steps = age / _bucketTicks;
|
||||
if (steps >= Buckets)
|
||||
{
|
||||
for (int i = 0; i < Buckets; i++) ClearBucket(i, 0);
|
||||
_cur = 0;
|
||||
_bStart[0] = now;
|
||||
return;
|
||||
}
|
||||
long start = _bStart[_cur];
|
||||
for (long i = 0; i < steps; i++)
|
||||
{
|
||||
start += _bucketTicks;
|
||||
_cur = (_cur + 1) % Buckets;
|
||||
ClearBucket(_cur, start);
|
||||
}
|
||||
}
|
||||
|
||||
private void ClearBucket(int b, long start)
|
||||
{
|
||||
_bStart[b] = start;
|
||||
_bFrames[b] = _bUiSum[b] = _bUiMax[b] = _bSlow[b] = _bUntimedSum[b] = _bUntimedMax[b] = _bWorstUntimed[b] = 0;
|
||||
_bSubmitMax[b] = default;
|
||||
_bHasSubmit[b] = false;
|
||||
_bFontUploads[b] = _bTexUploads[b] = 0;
|
||||
for (int s = 0; s < MaxSlots; s++)
|
||||
{
|
||||
_bSum[b, s] = 0; _bMax[b, s] = 0; _bMaxCount[b, s] = -1;
|
||||
_bWorst[b, s] = 0; _bWorstCount[b, s] = -1;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Text ───────────────────────────────────────────────────────────────
|
||||
|
||||
private string Ms(long ticks) => (ticks * 1000.0 / _freq).ToString("0.0", Inv);
|
||||
|
||||
private string WithCount(int slot, int count) =>
|
||||
count >= 0 && _units[slot] is { } unit ? $" ({count.ToString(Inv)} {unit})" : "";
|
||||
|
||||
/// <summary>
|
||||
/// "[UiCost] frame 187.0 ms (over 50): Radar 120.3, Monster HUD 41.0 (38 plates), ..., untimed 3.2,
|
||||
/// +4 more 0.9 | 3D pass, not in ui=: Nav3D markers 1.2". Parts under 0.05 ms are left out.
|
||||
/// </summary>
|
||||
private string FormatFrameLine(long uiTicks, long untimed)
|
||||
{
|
||||
var sb = new StringBuilder(256);
|
||||
sb.Append("[UiCost] frame ").Append(Ms(uiTicks)).Append(" ms (over ").Append(_thresholdMs.ToString(Inv)).Append("): ");
|
||||
int n = 0;
|
||||
for (int i = 0; i < _touchedCount; i++)
|
||||
{
|
||||
int s = _touched[i];
|
||||
if (_outside[s]) continue;
|
||||
_order[n] = s; _orderTicks[n] = _fTicks[s]; n++;
|
||||
}
|
||||
_order[n] = -1; _orderTicks[n] = untimed; n++;
|
||||
SortDesc(n);
|
||||
AppendTop(sb, n, LineTopItems, s => _fCount[s]);
|
||||
AppendSubmit(sb, _fHasSubmit, _fSubmit, _fFontUploads, _fTexUploads);
|
||||
|
||||
int o = 0;
|
||||
for (int i = 0; i < _touchedCount; i++)
|
||||
{
|
||||
int s = _touched[i];
|
||||
if (!_outside[s]) continue;
|
||||
_order[o] = s; _orderTicks[o] = _fTicks[s]; o++;
|
||||
}
|
||||
if (o > 0)
|
||||
{
|
||||
SortDesc(o);
|
||||
sb.Append(" | 3D pass, not in ui=: ");
|
||||
AppendTop(sb, o, LineTopItems, s => _fCount[s]);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// " | submit: 21 lists, 412 draws, 3 tex switches, 31k vtx copied (whole-list 4.2M); uploads: 1 font, 0 tex".
|
||||
/// The submit part only when one was recorded, the uploads only when there were any.
|
||||
/// </summary>
|
||||
private static void AppendSubmit(StringBuilder sb, bool has, in SubmitStats s, long font, long tex)
|
||||
{
|
||||
if (has)
|
||||
{
|
||||
sb.Append(" | submit: ").Append(s.Lists.ToString(Inv)).Append(" lists, ")
|
||||
.Append(s.Draws.ToString(Inv)).Append(" draws, ")
|
||||
.Append(s.TexSwitches.ToString(Inv)).Append(" tex switches, ")
|
||||
.Append(Compact(s.VtxCopied)).Append(" vtx copied (whole-list ").Append(Compact(s.VtxWholeList)).Append(')');
|
||||
if (s.Skipped > 0) sb.Append(", ").Append(s.Skipped.ToString(Inv)).Append(" skipped");
|
||||
}
|
||||
if (font > 0 || tex > 0)
|
||||
sb.Append(has ? "; uploads: " : " | uploads: ").Append(font.ToString(Inv)).Append(" font, ").Append(tex.ToString(Inv)).Append(" tex");
|
||||
}
|
||||
|
||||
/// <summary>950, 31.2k, 4.2M.</summary>
|
||||
public static string Compact(long n)
|
||||
{
|
||||
if (n < 1000) return n.ToString(Inv);
|
||||
if (n < 1_000_000) return (n / 1000.0).ToString("0.#", Inv) + "k";
|
||||
return (n / 1_000_000.0).ToString("0.#", Inv) + "M";
|
||||
}
|
||||
|
||||
private void AppendTop(StringBuilder sb, int n, int top, Func<int, int> count)
|
||||
{
|
||||
long minTicks = _freq / 20000; // 0.05 ms
|
||||
int shown = 0, more = 0;
|
||||
long moreTicks = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int s = _order[i];
|
||||
long t = _orderTicks[i];
|
||||
if (shown >= top || t < minTicks || t <= 0)
|
||||
{
|
||||
if (t > 0) { more++; moreTicks += t; }
|
||||
continue;
|
||||
}
|
||||
if (shown > 0) sb.Append(", ");
|
||||
if (s < 0) sb.Append("untimed ").Append(Ms(t));
|
||||
else sb.Append(_names[s]).Append(' ').Append(Ms(t)).Append(WithCount(s, count(s)));
|
||||
shown++;
|
||||
}
|
||||
if (shown == 0) sb.Append("nothing timed");
|
||||
if (more > 0) sb.Append(", +").Append(more.ToString(Inv)).Append(" more ").Append(Ms(moreTicks));
|
||||
}
|
||||
|
||||
// Insertion sort of _order/_orderTicks [0, n) by ticks, largest first (n is small).
|
||||
private void SortDesc(int n)
|
||||
{
|
||||
for (int i = 1; i < n; i++)
|
||||
{
|
||||
int s = _order[i];
|
||||
long t = _orderTicks[i];
|
||||
int j = i - 1;
|
||||
while (j >= 0 && _orderTicks[j] < t)
|
||||
{
|
||||
_order[j + 1] = _order[j];
|
||||
_orderTicks[j + 1] = _orderTicks[j];
|
||||
j--;
|
||||
}
|
||||
_order[j + 1] = s;
|
||||
_orderTicks[j + 1] = t;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The live buckets at <paramref name="now"/> (the window), folded into the _win arrays.</summary>
|
||||
private (long frames, long uiSum, long uiMax, long slow, long untimedSum, long untimedMax, long spanTicks, int worstBucket) FoldWindow(long now)
|
||||
{
|
||||
Array.Clear(_winSum);
|
||||
Array.Clear(_winMax);
|
||||
for (int s = 0; s < MaxSlots; s++) _winMaxCount[s] = -1;
|
||||
_winSubmit = default;
|
||||
_winHasSubmit = false;
|
||||
_winFontUploads = _winTexUploads = 0;
|
||||
long frames = 0, uiSum = 0, uiMax = 0, slow = 0, untimedSum = 0, untimedMax = 0, oldest = now;
|
||||
int worstBucket = -1;
|
||||
if (_cur < 0) return (0, 0, 0, 0, 0, 0, 0, -1);
|
||||
long horizon = now - _bucketTicks * Buckets;
|
||||
int slots = SlotCount;
|
||||
for (int b = 0; b < Buckets; b++)
|
||||
{
|
||||
if (_bFrames[b] == 0 || _bStart[b] < horizon) continue;
|
||||
if (_bStart[b] < oldest) oldest = _bStart[b];
|
||||
frames += _bFrames[b];
|
||||
uiSum += _bUiSum[b];
|
||||
if (worstBucket < 0 || _bUiMax[b] > uiMax) { uiMax = _bUiMax[b]; worstBucket = b; }
|
||||
slow += _bSlow[b];
|
||||
untimedSum += _bUntimedSum[b];
|
||||
if (_bUntimedMax[b] > untimedMax) untimedMax = _bUntimedMax[b];
|
||||
if (_bHasSubmit[b]) { _winSubmit.MaxWith(_bSubmitMax[b]); _winHasSubmit = true; }
|
||||
_winFontUploads += _bFontUploads[b];
|
||||
_winTexUploads += _bTexUploads[b];
|
||||
for (int s = 0; s < slots; s++)
|
||||
{
|
||||
_winSum[s] += _bSum[b, s];
|
||||
if (_bMax[b, s] > _winMax[s]) _winMax[s] = _bMax[b, s];
|
||||
if (_bMaxCount[b, s] > _winMaxCount[s]) _winMaxCount[s] = _bMaxCount[b, s];
|
||||
}
|
||||
}
|
||||
return (frames, uiSum, uiMax, slow, untimedSum, untimedMax, now - oldest, worstBucket);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The window's biggest parts by average per frame, for the heartbeat: " uitop=Radar:2.1/120.3,..."
|
||||
/// (avg/max ms, spaces in names as '_'). Empty when the window has no frames.
|
||||
/// </summary>
|
||||
public string HeartbeatField(long now, int top = 3)
|
||||
{
|
||||
var w = FoldWindow(now);
|
||||
if (w.frames == 0) return "";
|
||||
int n = FillWindowOrder(w.untimedSum, includeOutside: false);
|
||||
var sb = new StringBuilder(" uitop=");
|
||||
int shown = 0;
|
||||
for (int i = 0; i < n && shown < top; i++)
|
||||
{
|
||||
if (_orderTicks[i] <= 0) break;
|
||||
int s = _order[i];
|
||||
if (shown > 0) sb.Append(',');
|
||||
string name = s < 0 ? "untimed" : _names[s];
|
||||
sb.Append(name.Replace(' ', '_').Replace(',', ';').Replace('=', '-'));
|
||||
sb.Append(':').Append(Ms(_orderTicks[i] / w.frames)).Append('/').Append(Ms(s < 0 ? w.untimedMax : _winMax[s]));
|
||||
shown++;
|
||||
}
|
||||
if (shown == 0) return "";
|
||||
// The window's largest submit: " uisub=draws:412,texsw:3,vtx:31k/4.2M,up:0/0"
|
||||
// (vtx copied / what whole-list copies would have been; uploads font/other, summed).
|
||||
if (_winHasSubmit || _winFontUploads > 0 || _winTexUploads > 0)
|
||||
{
|
||||
sb.Append(" uisub=draws:").Append(_winSubmit.Draws.ToString(Inv))
|
||||
.Append(",texsw:").Append(_winSubmit.TexSwitches.ToString(Inv))
|
||||
.Append(",vtx:").Append(Compact(_winSubmit.VtxCopied)).Append('/').Append(Compact(_winSubmit.VtxWholeList))
|
||||
.Append(",up:").Append(_winFontUploads.ToString(Inv)).Append('/').Append(_winTexUploads.ToString(Inv));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private int FillWindowOrder(long untimedSum, bool includeOutside)
|
||||
{
|
||||
int n = 0;
|
||||
int slots = SlotCount;
|
||||
for (int s = 0; s < slots; s++)
|
||||
{
|
||||
if (_winSum[s] <= 0 || _outside[s] != includeOutside) continue;
|
||||
_order[n] = s; _orderTicks[n] = _winSum[s]; n++;
|
||||
}
|
||||
if (!includeOutside && untimedSum > 0) { _order[n] = -1; _orderTicks[n] = untimedSum; n++; }
|
||||
SortDesc(n);
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The breakdown for /rc uicost now: the window's frames, the parts by average per frame (with
|
||||
/// their worst), the slowest frame part by part, and the 3D pass parts.
|
||||
/// </summary>
|
||||
public List<string> Describe(long now, int top = 8)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
var w = FoldWindow(now);
|
||||
string state = Enabled ? $"timing on, slow frames logged at {_thresholdMs.ToString(Inv)} ms+" : "timing off";
|
||||
if (w.frames == 0)
|
||||
{
|
||||
lines.Add($"UI cost: no UI frames in the last {Buckets.ToString(Inv)} s ({state}).");
|
||||
return lines;
|
||||
}
|
||||
double span = w.spanTicks / (double)_freq;
|
||||
lines.Add($"UI cost, last {span.ToString("0.0", Inv)} s: {w.frames.ToString(Inv)} frames, avg {Ms(w.uiSum / w.frames)} ms, " +
|
||||
$"max {Ms(w.uiMax)} ms, {w.slow.ToString(Inv)} at {_thresholdMs.ToString(Inv)} ms+ ({state}).");
|
||||
|
||||
int n = FillWindowOrder(w.untimedSum, includeOutside: false);
|
||||
var sb = new StringBuilder("Per frame, avg (max): ");
|
||||
AppendWindowItems(sb, n, top, w.frames, w.untimedMax);
|
||||
lines.Add(sb.ToString());
|
||||
|
||||
if (w.worstBucket >= 0)
|
||||
{
|
||||
int b = w.worstBucket;
|
||||
int m = 0;
|
||||
int slots = SlotCount;
|
||||
for (int s = 0; s < slots; s++)
|
||||
{
|
||||
if (_outside[s] || _bWorst[b, s] <= 0) continue;
|
||||
_order[m] = s; _orderTicks[m] = _bWorst[b, s]; m++;
|
||||
}
|
||||
_order[m] = -1; _orderTicks[m] = _bWorstUntimed[b]; m++;
|
||||
SortDesc(m);
|
||||
var wsb = new StringBuilder("Slowest frame ").Append(Ms(w.uiMax)).Append(" ms: ");
|
||||
AppendTop(wsb, m, top, s => _bWorstCount[b, s]);
|
||||
lines.Add(wsb.ToString());
|
||||
}
|
||||
|
||||
if (_winHasSubmit || _winFontUploads > 0 || _winTexUploads > 0)
|
||||
{
|
||||
var ssb = new StringBuilder("ImGui submit, largest per frame");
|
||||
AppendSubmit(ssb, _winHasSubmit, _winSubmit, _winFontUploads, _winTexUploads);
|
||||
// "... | submit: ..." reads as "ImGui submit, largest per frame: ..." here; uploads are the window's sum.
|
||||
ssb.Replace(" | submit:", ":").Replace(" | uploads:", ": uploads (window total):").Replace("; uploads:", "; uploads (window total):");
|
||||
lines.Add(ssb.ToString());
|
||||
}
|
||||
|
||||
int o = FillWindowOrder(0, includeOutside: true);
|
||||
if (o > 0)
|
||||
{
|
||||
var osb = new StringBuilder("3D pass, not in ui=, avg (max): ");
|
||||
AppendWindowItems(osb, o, top, w.frames, 0);
|
||||
lines.Add(osb.ToString());
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private void AppendWindowItems(StringBuilder sb, int n, int top, long frames, long untimedMax)
|
||||
{
|
||||
int shown = 0;
|
||||
for (int i = 0; i < n && shown < top; i++)
|
||||
{
|
||||
int s = _order[i];
|
||||
long avg = _orderTicks[i] / frames;
|
||||
if (shown > 0) sb.Append(", ");
|
||||
if (s < 0) sb.Append("untimed ").Append(Ms(avg)).Append(" (").Append(Ms(untimedMax)).Append(')');
|
||||
else
|
||||
{
|
||||
sb.Append(_names[s]).Append(' ').Append(Ms(avg)).Append(" (").Append(Ms(_winMax[s]));
|
||||
if (_winMaxCount[s] >= 0 && _units[s] is { } unit) sb.Append(", ").Append(_winMaxCount[s].ToString(Inv)).Append(' ').Append(unit);
|
||||
sb.Append(')');
|
||||
}
|
||||
shown++;
|
||||
}
|
||||
if (shown == 0) sb.Append("nothing timed");
|
||||
else if (n > shown) sb.Append(", +").Append((n - shown).ToString(Inv)).Append(" more");
|
||||
}
|
||||
|
||||
/// <summary>The window's totals (tests): frames, average and max UI ms, slow frames.</summary>
|
||||
public (long Frames, double AvgMs, double MaxMs, long Slow) WindowTotals(long now)
|
||||
{
|
||||
var w = FoldWindow(now);
|
||||
if (w.frames == 0) return (0, 0, 0, 0);
|
||||
return (w.frames, w.uiSum * 1000.0 / _freq / w.frames, w.uiMax * 1000.0 / _freq, w.slow);
|
||||
}
|
||||
|
||||
/// <summary>One slot's window total, average per frame and max, in ms (tests).</summary>
|
||||
public (double AvgMs, double MaxMs) SlotWindow(long now, int slot)
|
||||
{
|
||||
var w = FoldWindow(now);
|
||||
if (w.frames == 0 || (uint)slot >= (uint)SlotCount) return (0, 0);
|
||||
return (_winSum[slot] * 1000.0 / _freq / w.frames, _winMax[slot] * 1000.0 / _freq);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One ImGui submit's counters (DX9Backend.RenderLists): what the [UiCost] line and the
|
||||
/// heartbeat print about the submit, so a slow one names its shape.
|
||||
/// </summary>
|
||||
internal struct SubmitStats
|
||||
{
|
||||
/// <summary>Draw lists drawn.</summary>
|
||||
public int Lists;
|
||||
/// <summary>Draw calls made (commands with geometry, not clipped away).</summary>
|
||||
public int Draws;
|
||||
/// <summary>Commands skipped: clipped away or broken.</summary>
|
||||
public int Skipped;
|
||||
/// <summary>SetTexture calls that changed the texture.</summary>
|
||||
public int TexSwitches;
|
||||
/// <summary>Vertices handed to the draw calls (what the runtime copies).</summary>
|
||||
public long VtxCopied;
|
||||
/// <summary>What the same submit would have copied handing each command its whole list (the old renderer).</summary>
|
||||
public long VtxWholeList;
|
||||
|
||||
public void Clear() => this = default;
|
||||
|
||||
/// <summary>Folds another submit in (the window keeps each counter's largest).</summary>
|
||||
public void MaxWith(in SubmitStats o)
|
||||
{
|
||||
if (o.Lists > Lists) Lists = o.Lists;
|
||||
if (o.Draws > Draws) Draws = o.Draws;
|
||||
if (o.Skipped > Skipped) Skipped = o.Skipped;
|
||||
if (o.TexSwitches > TexSwitches) TexSwitches = o.TexSwitches;
|
||||
if (o.VtxCopied > VtxCopied) VtxCopied = o.VtxCopied;
|
||||
if (o.VtxWholeList > VtxWholeList) VtxWholeList = o.VtxWholeList;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue