diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index f652df1..1acd7ab 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -241,6 +241,24 @@ internal static class ClientObjectHooks private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue; private static bool _loggedObjectIdentityServe; private const int ObjectIdentityPrefetchThrottleMs = 500; + + // Create-time identity seeds. ACCObjectMaint::CreateObject receives the server's + // PublicWeenieDesc, which already carries the object's name and ITEM_TYPE before + // qualities/appraisal exist. The main-thread snapshot above can't resolve names for + // ~10 s after login (qualities not populated yet), so off-thread readers fall back to + // these seeds when the snapshot has no entry (or reports type 0). Entries live from + // create until delete; the cap only guards against a missed delete hook. + private static readonly object _createSeedLock = new(); + private static readonly Dictionary _createSeedNames = new(1024); + private static readonly Dictionary _createSeedTypes = new(1024); + private const int CreateSeedCap = 16384; + // PublicWeenieDesc field offsets (Chorizite Weenie.cs; same layout the PWD-direct + // fallbacks in TryGetObjectName / TryGetItemType read from the embedded copy). + // PwdTypeOffset is declared with the other PublicWeenieDesc offsets further down. + private const int PwdNameOffset = 4; + private static int _createSeedCount; + private static bool _loggedCreateSeedServe; + // Every id the same walk visited, swapped whole (readers never see a half-built array). private static volatile uint[] _liveObjectIds = Array.Empty(); @@ -393,6 +411,7 @@ internal static class ClientObjectHooks private static readonly object _weeniePtrSwapLock = new(); private static Dictionary _weeniePtrFront = new(512); private static Dictionary _weeniePtrBack = new(512); + // Diagnostic (temporary): periodic snapshot-size log + live-read probe of // objects with a position but no cached name. Remove once the missing- // monsters cause is pinned. _diagSampleBuf preallocated to stay low-alloc. @@ -2019,8 +2038,9 @@ internal static class ClientObjectHooks value = 0; if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0) return false; + // Off-thread: served from the main-thread PWD byte snapshot, never from AC memory. if (!MainThreadGuard.IsOnMainThread()) - return false; + return TryGetPwdSnapshotRawInt32(objectId, pwdFieldOffset, out value); if (_getWeenieObject == null) { if (!Probe() || _getWeenieObject == null) @@ -2393,6 +2413,19 @@ internal static class ClientObjectHooks // Off-thread: serve from the main-thread snapshot populated by PrefetchObjectIdentity(). if (!MainThreadGuard.IsOnMainThread()) { + lock (_objectIdentityCacheLock) + { + // A zero snapshot value means qualities weren't populated when the walk + // ran; prefer the create-time descriptor type in that case. + if (_objectTypeCache.TryGetValue(objectId, out typeFlags) && typeFlags != 0) + return true; + } + if (TryGetCreateSeedType(objectId, out uint seeded)) + { + typeFlags = seeded; + return true; + } + // Snapshot hit with flags=0 is still an answer (static scenery often has no type). lock (_objectIdentityCacheLock) { if (_objectTypeCache.TryGetValue(objectId, out typeFlags)) @@ -3341,6 +3374,101 @@ internal static class ClientObjectHooks } } + /// + /// Records an object's name and ITEM_TYPE straight from the PublicWeenieDesc passed + /// to ACCObjectMaint::CreateObject. Called from the create hook on AC's main thread, + /// after the original returns. The descriptor is server data that exists before the + /// object's qualities do, so this makes names/types readable off-thread immediately + /// instead of after the first successful identity snapshot (~10 s at login). + /// Every read is pointer-validated; a bad descriptor simply records nothing. + /// + internal static void SeedIdentityFromCreate(uint objectId, IntPtr weenieDesc) + { + if (objectId == 0 || weenieDesc == IntPtr.Zero) + return; + + try + { + // PublicWeenieDesc derives from PackObj, so a real descriptor starts with an + // acclient.exe vtable; reject anything else before reading fields. + if (!LooksLikeAcHeapObject(weenieDesc)) + return; + + bool gotName = TryReadPwdString(weenieDesc, PwdNameOffset, out string name); + + uint typeFlags = 0; + IntPtr typeAddr = weenieDesc + PwdTypeOffset; + bool gotType = IsReadablePointer(typeAddr); + if (gotType) + typeFlags = unchecked((uint)Marshal.ReadInt32(typeAddr)); + + if (!gotName && (!gotType || typeFlags == 0)) + return; + + lock (_createSeedLock) + { + // Safety valve for a missed delete: drop everything rather than grow forever. + // The live snapshot covers anything still in the world. + if (_createSeedNames.Count >= CreateSeedCap || _createSeedTypes.Count >= CreateSeedCap) + { + _createSeedNames.Clear(); + _createSeedTypes.Clear(); + } + if (gotName) + _createSeedNames[objectId] = name; + if (gotType && typeFlags != 0) + _createSeedTypes[objectId] = typeFlags; + } + + int seedNo = System.Threading.Interlocked.Increment(ref _createSeedCount); + // First few samples let a log reader confirm the descriptor offsets resolve + // to sensible names/types on this client build. + if (seedNo <= 5) + RynthLog.Compat($"[CreateSeed] #{seedNo} 0x{objectId:X8} name='{(gotName ? name : "")}' type=0x{typeFlags:X8}"); + if (!_loggedCreateSeedServe && seedNo >= 50) + { + _loggedCreateSeedServe = true; + int names, types; + lock (_createSeedLock) { names = _createSeedNames.Count; types = _createSeedTypes.Count; } + RynthLog.Compat($"ClientObjectHooks: create-descriptor identity seeds active — {names} names, {types} types captured at CreateObject."); + } + } + catch + { + // Descriptor read failures are non-fatal; the periodic snapshot still runs. + } + } + + /// Drops create-time seeds for a deleted object (called from the delete hook). + internal static void ForgetCreateSeed(uint objectId) + { + lock (_createSeedLock) + { + _createSeedNames.Remove(objectId); + _createSeedTypes.Remove(objectId); + } + } + + private static bool TryGetCreateSeedName(uint objectId, out string name) + { + lock (_createSeedLock) + { + if (_createSeedNames.TryGetValue(objectId, out string? seeded) && seeded.Length > 0) + { + name = seeded; + return true; + } + } + name = string.Empty; + return false; + } + + private static bool TryGetCreateSeedType(uint objectId, out uint typeFlags) + { + lock (_createSeedLock) + return _createSeedTypes.TryGetValue(objectId, out typeFlags); + } + public static bool TryGetObjectName(uint objectId, out string name) { name = string.Empty; @@ -3356,6 +3484,10 @@ internal static class ClientObjectHooks return true; } } + // Snapshot miss (login burst / object newer than the last walk): serve the + // name captured from the create descriptor. + if (TryGetCreateSeedName(objectId, out name)) + return true; name = string.Empty; return false; } @@ -3809,6 +3941,21 @@ internal static class ClientObjectHooks && PwdLayout.TryGetInt(e.Bytes, stype, out value); } + /// + /// Off-thread read of one 4-byte PWD field by raw offset (the + /// contract) from the main-thread snapshot. False for objects the last walk didn't see. + /// + private static bool TryGetPwdSnapshotRawInt32(uint objectId, int pwdFieldOffset, out int value) + { + value = 0; + if (pwdFieldOffset < 0 || pwdFieldOffset + 4 > PwdLayout.Size) + return false; + if (!TryGetPwdSnapshot(objectId, out PwdEntry e)) + return false; + value = System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(((ReadOnlySpan)e.Bytes).Slice(pwdFieldOffset)); + return true; + } + private static bool TryGetPwdSnapshotFloat(uint objectId, uint stype, out double value) { value = 0; diff --git a/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs b/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs index 9377b39..558a192 100644 --- a/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs @@ -81,6 +81,9 @@ internal static class CreateObjectHooks if (count <= 0) RynthLog.Verbose($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}"); + // Capture name/type from the create descriptor BEFORE the plugin is told about the + // object, so its off-thread classifier can read them on the very first attempt. + ClientObjectHooks.SeedIdentityFromCreate(objectId, weenieDesc); PluginManager.QueueCreateObject(objectId); AutoIdService.Enqueue(objectId); return result; diff --git a/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs b/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs index 3f8df11..151dffd 100644 --- a/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs @@ -71,6 +71,7 @@ internal static class DeleteObjectHooks if (objectId != 0) { PaletteCache.Remove(objectId); + ClientObjectHooks.ForgetCreateSeed(objectId); PluginManager.QueueDeleteObject(objectId); AutoIdService.Evict(objectId); } diff --git a/src/RynthCore.Engine/D3D9/EndSceneHook.cs b/src/RynthCore.Engine/D3D9/EndSceneHook.cs index 1c0274d..e572bdf 100644 --- a/src/RynthCore.Engine/D3D9/EndSceneHook.cs +++ b/src/RynthCore.Engine/D3D9/EndSceneHook.cs @@ -456,6 +456,11 @@ internal static class EndSceneHook if (_uiFrameCount < 30) RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}"); } + + // ImGui draw data (in-client panels, plugin overlay windows such as the ILT Hub) + // is submitted LAST so it sits on top of the Avalonia layer. Built in OnEndScene; + // guarded internally, so an ImGui draw failure can't skip the original EndScene. + EngineFrameController.RenderDeferredImGui(); } catch (Exception ex) { diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs index 27bc9e2..1f619e2 100644 --- a/src/RynthCore.Engine/EngineLifecycle.cs +++ b/src/RynthCore.Engine/EngineLifecycle.cs @@ -160,6 +160,7 @@ internal static class EngineLifecycle // tick pump and plugins go away — both otherwise keep firing in the old // generation's (intentionally still-mapped) module across hot-reloads. Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop()); + Step("LogSettings.StopWatcher", () => LogSettings.StopWatcher()); Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop()); // Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary. diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 681d284..50cafa3 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -23,6 +23,7 @@ using System.Runtime.InteropServices; using ImGuiNET; using RynthCore.Engine.D3D9; using RynthCore.Engine.Plugins; +using RynthCore.Install; namespace RynthCore.Engine.ImGuiBackend; @@ -48,6 +49,9 @@ internal static class EngineFrameController private static bool _imguiInitFailed; private static bool _coreResolved; private static bool _pluginsInitialized; + // Pump frames plugin init has waited for the ImGui context (PumpPluginFrame; ~16 ms each). + private static int _pluginInitContextWaits; + private const int PluginInitContextMaxWaits = 300; private static IntPtr _context; private static IntPtr _gameHwnd; @@ -61,6 +65,25 @@ internal static class EngineFrameController /// internal static volatile IntPtr CachedDevice; private static int _pluginPumpInFrame; // re-entrancy guard for the pump + + // ImGui pipeline diagnostics (render thread only): one-time lines plus a 30 s heartbeat so a + // log shows whether frames start, which branch runs and whether draw data is submitted. + private const long HeartbeatIntervalMs = 30_000; + private static long _engineErrorCount; + private static long _nextEngineErrorLogAt; + private static bool _loggedFirstSubmit; + private static int _loggedBranch = -1; + private static string _initFailStep = "unknown"; + private static long _drawSubmits; + private static long _nextHeartbeatAt; + + // Device for this frame's built ImGui draw data, submitted by RenderDeferredImGui after the + // Avalonia blit. Render thread only; Zero = nothing pending. The draw data stays valid until + // the next NewFrame on the main context. + private static IntPtr _deferredSubmitDevice; + // Build + pop-out time of the frame waiting in _deferredSubmitDevice (UiFrameStats adds the submit). + private static long _deferredUiTicks; + private static long _lastFrameTicks; private static int _frameCount; @@ -103,7 +126,10 @@ internal static class EngineFrameController return true; if (!EnsureCore(pDevice)) + { + _initFailStep = "EnsureCore (game window not found)"; return false; + } // Before any context exists: the loaded cimgui.dll must be the exact // build ImGui.NET wraps, or every struct read below is at wrong offsets. @@ -127,11 +153,11 @@ internal static class EngineFrameController // between launches. Allocated once, kept alive for the process lifetime. try { - const string iniPath = @"C:\Games\RynthSuite\RynthAi\imgui.ini"; - System.IO.Directory.CreateDirectory(@"C:\Games\RynthSuite\RynthAi"); + string iniPath = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, "imgui.ini"); + System.IO.Directory.CreateDirectory(RynthInstallPaths.RynthAiDir); IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath); unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; } - RynthLog.Render($"EngineFrameController: imgui.ini pinned to {iniPath}"); + RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}"); } catch (Exception ex) { @@ -155,10 +181,16 @@ internal static class EngineFrameController ImGuiFonts.Build(io, _uiScale); if (!Win32Backend.Init(_gameHwnd)) + { + _initFailStep = "Win32Backend.Init"; return false; + } if (!DX9Backend.InitImGui(pDevice)) + { + _initFailStep = "DX9Backend.InitImGui"; return false; + } _lastFrameTicks = Stopwatch.GetTimestamp(); _imguiInitialized = true; @@ -229,6 +261,8 @@ internal static class EngineFrameController // EngineSettings.EnableImGuiBackend, so world→screen capture, nav- // marker rendering, and plugin lifecycle stay alive when the ImGui // surface is disabled. + // A frame that throws before its build must not resubmit last frame's draw data. + _deferredSubmitDevice = IntPtr.Zero; try { // Resolve game HWND and seed EntryPoint.GameHwnd. Required even @@ -344,10 +378,10 @@ internal static class EngineFrameController // calls it at all. // ── ImGui-gated work ───────────────────────────────────────── - // The frame is BUILT here and SUBMITTED after the Nav3D fallback and - // the vital HUD, so ImGui windows sit above both. The Avalonia quad - // (EndSceneHook, after this returns) stays topmost while both stacks - // run, matching input order: Avalonia gets the first hit test. + // The frame is BUILT here and SUBMITTED by RenderDeferredImGui, which + // EndSceneHook calls after the Avalonia quad, so ImGui windows sit above + // the Nav3D fallback, the vital HUD and the Avalonia panels. Input order + // matches: Win32Backend gives ImGui the mouse while it wants it. bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend; bool imguiBuilt = false; long uiTicks = 0; @@ -370,17 +404,33 @@ internal static class EngineFrameController if (imguiEnabled) { long t0 = Stopwatch.GetTimestamp(); - if (imguiBuilt) - SubmitImGuiFrame(pDevice); // Popped-out panels: their own contexts, windows and render targets. if (_imguiInitialized) ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive); - UiFrameStats.Record(uiTicks + (Stopwatch.GetTimestamp() - t0)); + long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0); + if (imguiBuilt) + { + _deferredUiTicks = ticks; + _deferredSubmitDevice = pDevice; + } + else + { + UiFrameStats.Record(ticks); + } } } catch (Exception ex) { - RynthLog.Info($"EngineFrameController: frame {_frameCount} engine error: {ex.GetType().Name}: {ex.Message}"); + // An exception here skips everything after it this frame (including RunImGuiFrame), so + // the first one gets a stack trace; repeats are summarised every 30 s instead of per frame. + _engineErrorCount++; + long errNow = Environment.TickCount64; + if (_engineErrorCount == 1) + RynthLog.Error($"EngineFrameController: engine frame error (rest of this frame skipped): {ex}"); + else if (errNow >= _nextEngineErrorLogAt) + RynthLog.Error($"EngineFrameController: engine frame errors so far={_engineErrorCount}, latest {ex.GetType().Name}: {ex.Message}"); + if (errNow >= _nextEngineErrorLogAt) + _nextEngineErrorLogAt = errNow + HeartbeatIntervalMs; } finally { @@ -442,14 +492,26 @@ internal static class EngineFrameController return; // never re-enter PluginManager from two stacks try { - // Plugins only get the ImGui context when they may draw with it - // (EnableImGuiShell, FORCE-gated). The engine's own ImGui panels - // don't need plugins to see it, and handing it over switched - // RynthAi into its legacy-ImGui setup (first ImGui-on test, - // 2026-09-28) - plugins must behave exactly as in Avalonia-only mode. - IntPtr pluginContext = Plugins.EngineSettings.EnableImGuiShell ? _context : IntPtr.Zero; + // Plugins only get the ImGui context when they may draw with it: the + // ImGui shell (EnableImGuiShell, FORCE-gated) or their own overlay + // windows (EnablePluginOverlayWindows: RynthAi's ILT Hub, HUDs, Item + // Info; RynthPluginRenderOverlay). RynthAi only reads the context for + // those windows, so this does not switch it into a legacy-ImGui setup. + bool pluginsDraw = Plugins.EngineSettings.EnableImGuiShell + || (Plugins.EngineSettings.EnablePluginOverlayWindows && Plugins.EngineSettings.EnableImGuiBackend); + // _context is written by the render thread (Init); this is the pump thread. + IntPtr pluginContext = pluginsDraw ? System.Threading.Volatile.Read(ref _context) : IntPtr.Zero; if (!_pluginsInitialized) { + // The plugin host copies the context once at init, so wait for the + // render path's ImGui init (first ImGui frame) rather than hand over + // zero for the whole session. Bounded: a failed or stalled ImGui init + // must not hold plugins (and the bot) back. + if (pluginsDraw && pluginContext == IntPtr.Zero && !_imguiInitFailed + && ++_pluginInitContextWaits <= PluginInitContextMaxWaits) + return; + if (pluginsDraw && pluginContext == IntPtr.Zero) + RynthLog.Warn($"EngineFrameController: plugins initialised without an ImGui context (imguiInitFailed={_imguiInitFailed}, waits={_pluginInitContextWaits}) - plugin overlay windows will not draw this session."); _pluginsInitialized = true; PluginManager.InitPlugins(pluginContext, device, _gameHwnd); } @@ -500,9 +562,17 @@ internal static class EngineFrameController if (Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled) return true; if (!PanelsLive) return false; ImGuiPanelHost.RestoreOnce(); - return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame; + return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame + || PluginOverlayWindowsLive; } + /// + /// In the world, with the shell off, and some loaded plugin exports + /// RynthPluginRenderOverlay: its windows need a frame every frame. + /// + private static bool PluginOverlayWindowsLive => + PanelsLive && Plugins.EngineSettings.EnablePluginOverlayWindows && PluginManager.HasOverlayPlugins; + /// /// 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 @@ -543,7 +613,8 @@ internal static class EngineFrameController } private static bool HasImGuiContentNoRestore() => - Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame)); + Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame)) + || PluginOverlayWindowsLive; // Keyboard owner between the stacks (plan §3.2 d): whichever side started // text entry most recently keeps the keyboard. @@ -572,6 +643,7 @@ internal static class EngineFrameController if (!Init(pDevice)) { _imguiInitFailed = true; + RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session."); return false; } } @@ -595,7 +667,6 @@ internal static class EngineFrameController ImGuiNET.ImGui.SetCurrentContext(_context); bool frameStarted = false; bool frameEnded = false; - try { ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); @@ -643,6 +714,9 @@ internal static class EngineFrameController ImGuiNET.ImGui.NewFrame(); 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. + ItemDragBridge.SubmitMainFrame(io); ImGuiTextFocus.BeginFrame(); if (_dropImGuiTextFocus) { @@ -652,11 +726,29 @@ internal static class EngineFrameController } // EnableImGuiShell gates the old diagnostic shell and plugin-drawn // ImGui windows (plugin code on AC's thread: FORCE-gated, stays off). + int branch; if (Plugins.EngineSettings.EnableImGuiShell) { + branch = 1; RynthCoreShell.Render(_frameCount); PluginManager.RenderAll(); } + else if (PluginOverlayWindowsLive) + { + branch = 2; + // Only the opt-in extra windows (RynthPluginRenderOverlay), never the + // plugins' full ImGui UIs. + PluginManager.RenderOverlayAll(); + } + else + { + branch = 0; + } + if (branch != _loggedBranch) + { + _loggedBranch = branch; + RynthLog.Info($"EngineFrameController: ImGui plugin branch = {(branch == 1 ? "shell (RenderAll)" : branch == 2 ? "overlay windows (RenderOverlayAll)" : "none")}."); + } if (PanelsLive) { // World overlays: built into UnderUiLayer's list, drawn next frame at @@ -736,6 +828,24 @@ internal static class EngineFrameController _prevAvaloniaText = avaloniaText; } + /// + /// Submits this frame's ImGui draw data. EndSceneHook calls it after + /// OverlayTextureRenderer.Render so ImGui windows draw on top of the Avalonia layer. + /// Runs whether or not the Avalonia blit ran (character select, Avalonia off), and is + /// a no-op when built nothing this frame. Never throws. + /// + public static void RenderDeferredImGui() + { + IntPtr device = _deferredSubmitDevice; + if (device == IntPtr.Zero) + return; + _deferredSubmitDevice = IntPtr.Zero; // one submission per frame, even if it throws + + long t0 = Stopwatch.GetTimestamp(); + SubmitImGuiFrame(device); + UiFrameStats.Record(_deferredUiTicks + (Stopwatch.GetTimestamp() - t0)); + } + /// Draws the frame produced. private static void SubmitImGuiFrame(IntPtr pDevice) { @@ -743,7 +853,15 @@ internal static class EngineFrameController ImGuiNET.ImGui.SetCurrentContext(_context); try { - DX9Backend.RenderDrawData(ImGuiNET.ImGui.GetDrawData(), pDevice); + ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData(); + DX9Backend.RenderDrawData(drawData, pDevice); + _drawSubmits++; + if (!_loggedFirstSubmit) + { + _loggedFirstSubmit = true; + RynthLog.Info("EngineFrameController: first ImGui draw submitted."); + } + LogHeartbeatIfDue(drawData); } catch (Exception ex) { @@ -755,6 +873,29 @@ internal static class EngineFrameController } } + /// + /// Every 30 s: built ImGui frames, submits, draw list / vertex counts of the + /// latest frame and the overlay-window stats from PluginManager. Zero draw lists means no + /// ImGui window was drawn that frame. One string per interval; no per-frame allocation. + /// + private static void LogHeartbeatIfDue(ImDrawDataPtr drawData) + { + long now = Environment.TickCount64; + if (now < _nextHeartbeatAt) return; + bool first = _nextHeartbeatAt == 0; + _nextHeartbeatAt = now + HeartbeatIntervalMs; + if (first) return; // first interval starts now; the first-frame line already covers t=0 + + int lists = 0, vertices = 0; + unsafe + { + // ImDrawData: +4 CmdListsCount, +8 TotalIdxCount, +12 TotalVtxCount (see CLAUDE.md offsets). + byte* p = (byte*)drawData.NativePtr; + if (p != null) { lists = *(int*)(p + 4); vertices = *(int*)(p + 12); } + } + RynthLog.Info($"EngineFrameController: ImGui heartbeat frames={_framesBuilt} submits={_drawSubmits} lastFrame drawLists={lists} vertices={vertices} {PluginManager.DescribeOverlayState()}."); + } + internal static IntPtr FindGameWindow() { uint pid = GetCurrentProcessId(); diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index f153763..f55b35d 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -66,7 +66,11 @@ internal sealed record PanelSpec( ImGuiWindowFlags BodyFlags = ImGuiWindowFlags.None, // Where the panel first opens (logical units) when nothing is saved for its // key; null = the cascade. (Script windows: a FirstUseEver position.) - Vector2? DefaultPos = null); + Vector2? DefaultPos = null, + // With nothing saved and no DefaultPos: open centred in the game view rather + // than in the top-left cascade, where popped-out panels (separate windows + // above the game frame) usually sit and would hide it. + bool OpenCentered = false); /// An ImGui panel face. One instance per open; dropped on close. internal interface IImGuiPanel @@ -648,6 +652,10 @@ internal static class ImGuiPanelHost { pos = defaultPos; // the face's own first spot (a script window's FirstUseEver position) } + else if (entry.Spec.OpenCentered && CenteredLogicalPos(size, placeScale) is Vector2 centered) + { + pos = centered; + } else { int shown = 0; @@ -667,6 +675,104 @@ internal static class ImGuiPanelHost entry.NeedsPlacement = true; entry.DesiredPos = entry.Pos != pos * placeScale ? pos * placeScale : null; entry.DesiredForDisplay = ImGuiNET.ImGui.GetIO().DisplaySize; + + // Popped-out windows sit above the game frame, so a docked panel opening under + // one would be invisible. The new spot is saved by the open's Persist, so the + // panel comes back where it could be seen. + if (ClearOfPopOuts(entry.Pos, entry.Size) is Vector2 clear) + { + RynthLog.UI($"ImGuiPanelHost: {entry.Title} would open under a popped-out window; " + + $"moved from ({entry.Pos.X:0},{entry.Pos.Y:0}) to ({clear.X:0},{clear.Y:0})."); + entry.Pos = clear; + entry.PersistedPos = clear; + entry.DesiredPos = null; // don't pull it back under the pop-out as the display grows + } + } + + /// Above this share of a docked panel hidden by popped-out windows, it opens elsewhere. + private const float MaxCoveredFraction = 0.5f; + /// Candidate spots per axis when looking for a clear place (a grid over the game view). + private const int ClearSpotSteps = 8; + + /// + /// A spot (client px) for a docked window of at + /// that popped-out windows hide less, nearest the original among the least-covered; null when + /// at most half of it is covered or no spot is better. + /// + private static Vector2? ClearOfPopOuts(Vector2 pos, Vector2 size) + { + float area = size.X * size.Y; + if (area <= 0) return null; + List<(Vector2 Min, Vector2 Max)> covers = PopOutRectsInClient(); + if (covers.Count == 0) return null; + float covered = CoveredArea(pos, size, covers); + if (covered <= area * MaxCoveredFraction) return null; + + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + if (display.X <= 1 || display.Y <= 1) return null; + Vector2 room = Vector2.Max(Vector2.Zero, display - size); + + // Pass 1: the least coverage any grid spot reaches. Pass 2: the nearest spot within + // 2% of the panel's area of that, so a nearly-as-clear nearby spot beats a far one. + float least = float.MaxValue; + for (int i = 0; i <= ClearSpotSteps; i++) + for (int j = 0; j <= ClearSpotSteps; j++) + least = Math.Min(least, CoveredArea(GridSpot(room, i, j), size, covers)); + if (least >= covered) return null; + + float tolerance = least + area * 0.02f; + Vector2? best = null; + float bestDist = float.MaxValue; + for (int i = 0; i <= ClearSpotSteps; i++) + for (int j = 0; j <= ClearSpotSteps; j++) + { + Vector2 spot = GridSpot(room, i, j); + if (CoveredArea(spot, size, covers) > tolerance) continue; + float dist = Vector2.DistanceSquared(spot, pos); + if (dist < bestDist) { bestDist = dist; best = spot; } + } + return best; + } + + private static Vector2 GridSpot(Vector2 room, int i, int j) => + new(MathF.Round(room.X * i / ClearSpotSteps), MathF.Round(room.Y * j / ClearSpotSteps)); + + /// Visible popped-out windows' rects in the game window's client px (ImGui coordinates). + private static List<(Vector2 Min, Vector2 Max)> PopOutRectsInClient() + { + Vector2 origin = ImGuiPopOuts.ClientOriginOnScreen(); + var rects = new List<(Vector2, Vector2)>(); + foreach (var (left, top, width, height) in UI.LayeredWindow.VisibleContentRects()) + { + var min = new Vector2(left, top) - origin; + rects.Add((min, min + new Vector2(width, height))); + } + return rects; + } + + /// Area of the window hidden by (overlaps between covers count twice). + private static float CoveredArea(Vector2 pos, Vector2 size, List<(Vector2 Min, Vector2 Max)> covers) + { + Vector2 max = pos + size; + float total = 0; + foreach (var (cMin, cMax) in covers) + { + float w = MathF.Min(max.X, cMax.X) - MathF.Max(pos.X, cMin.X); + float h = MathF.Min(max.Y, cMax.Y) - MathF.Max(pos.Y, cMin.Y); + if (w > 0 && h > 0) total += w * h; + } + return total; + } + + /// + /// Top-left (logical units) that centres a window of logical in the + /// game view; null while the display size isn't known yet. + /// + private static Vector2? CenteredLogicalPos(Vector2 size, float placeScale) + { + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + if (display.X <= 1 || display.Y <= 1 || placeScale <= 0) return null; + return Vector2.Max(Vector2.Zero, (display / placeScale - size) * 0.5f); } private static Vector2 ClampToDisplay(Vector2 pos, Vector2 size) diff --git a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs index 8d572a3..b2ce607 100644 --- a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs +++ b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs @@ -54,6 +54,11 @@ internal sealed class LoadedPlugin public PluginOnEnchantmentRemovedDelegate? OnEnchantmentRemoved { get; set; } public PluginTickDelegate? Tick { get; set; } public PluginRenderDelegate? Render { get; set; } + /// Optional RynthPluginRenderOverlay: ImGui windows drawn while the ImGui shell is off. + public PluginRenderDelegate? RenderOverlay { get; set; } + + /// Set after the first RenderOverlay call has been logged (render thread only). + public bool RenderOverlayLogged { get; set; } // ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ─── public bool UiExportsResolved { get; set; } @@ -85,4 +90,44 @@ internal sealed class LoadedPlugin public RynthCore.PluginSdk.Manifest.RynthPluginManifest? Manifest { get; set; } /// Why the plugin was not started (a required plugin missing or failed); empty otherwise. public string NotStartedReason { get; set; } = ""; + + /// + /// Drops managed delegates wrapping exports so the native module can fully unload after + /// the host calls FreeLibrary (hot-reload / rescan). + /// + internal void ClearResolvedDelegates() + { + Init = null; + Shutdown = null; + GetName = null; + GetVersion = null; + OnLoginComplete = null; + OnUIInitialized = null; + OnBusyCountIncremented = null; + OnBusyCountDecremented = null; + OnSelectedTargetChange = null; + OnCombatModeChange = null; + OnSmartBoxEventPtr = IntPtr.Zero; + OnSmartBoxEvent = null; + OnDeleteObject = null; + OnCreateObject = null; + OnUpdateObjectPtr = IntPtr.Zero; + OnUpdateObject = null; + OnUpdateObjectInventory = null; + OnViewObjectContents = null; + OnStopViewingObjectContents = null; + OnVendorOpen = null; + OnVendorClose = null; + OnUpdateHealthPtr = IntPtr.Zero; + OnUpdateHealth = null; + OnChatWindowTextPtr = IntPtr.Zero; + OnChatWindowText = null; + OnChatBarEnter = null; + OnBarAction = null; + OnEnchantmentAdded = null; + OnEnchantmentRemoved = null; + Tick = null; + Render = null; + RenderOverlay = null; + } } diff --git a/src/RynthCore.Engine/Plugins/PluginLoader.cs b/src/RynthCore.Engine/Plugins/PluginLoader.cs index 1b45302..8e73b3a 100644 --- a/src/RynthCore.Engine/Plugins/PluginLoader.cs +++ b/src/RynthCore.Engine/Plugins/PluginLoader.cs @@ -89,6 +89,9 @@ internal static class PluginLoader /// public static void Unload(LoadedPlugin plugin) { + // Release managed thunks first so the module ref-count can drop to zero on FreeLibrary. + plugin.ClearResolvedDelegates(); + if (ManagedPlugins.IsManagedHandle(plugin.ModuleHandle)) { ManagedPlugins.Unload(plugin.ModuleHandle); // a managed plugin really goes away @@ -506,6 +509,10 @@ internal static class PluginLoader if (renderPtr != IntPtr.Zero) plugin.Render = Marshal.GetDelegateForFunctionPointer(renderPtr); + IntPtr renderOverlayPtr = GetProcAddress(handle, "RynthPluginRenderOverlay"); + if (renderOverlayPtr != IntPtr.Zero) + plugin.RenderOverlay = Marshal.GetDelegateForFunctionPointer(renderOverlayPtr); + // Read name/version from the plugin if available if (plugin.GetName != null) { diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 95775ba..410f2ed 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -1138,6 +1138,109 @@ internal static partial class PluginManager } } + /// + /// ImGui-shell-off counterpart of : calls the optional + /// RynthPluginRenderOverlay export, where a plugin draws only the extra windows that have + /// no Avalonia panel (e.g. RynthAi's ILT Hub). They float beside the Avalonia UI and add to it. + /// A throw switches off just that plugin's overlay windows; the plugin is NOT marked Failed, + /// so its tick/automation and Avalonia panels keep running. + /// + public static void RenderOverlayAll() + { + _overlayCalls++; + if (!_loginCompleteObserved) + { + if (!_loggedOverlayWaitingForLogin) + { + _loggedOverlayWaitingForLogin = true; + RynthLog.Info("PluginManager: RenderOverlayAll called - waiting for login before drawing overlay windows."); + } + return; // same not-in-world crash zone guard as RenderAll + } + + LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot); + + // Count plugins that will actually be called; log whenever that set changes. + int bound = 0; + for (int i = 0; i < plugins.Length; i++) + { + var p = plugins[i]; + if (p.Initialized && !p.Failed && p.RenderOverlay != null) bound++; + } + _overlayBound = bound; + if (bound != _loggedOverlayBound || plugins.Length != _loggedOverlayTotal) + { + _loggedOverlayBound = bound; + _loggedOverlayTotal = plugins.Length; + var sb = new System.Text.StringBuilder(); + for (int i = 0; i < plugins.Length; i++) + { + var p = plugins[i]; + if (sb.Length > 0) sb.Append(", "); + sb.Append(p.DisplayName).Append('(') + .Append(p.RenderOverlay != null ? "overlay" : "no-overlay") + .Append(p.Initialized ? "" : ",not-init") + .Append(p.Failed ? ",failed" : "") + .Append(')'); + } + RynthLog.Info($"PluginManager: RenderOverlayAll login seen, {bound} of {plugins.Length} plugin(s) will draw overlay windows: {sb}."); + } + + for (int i = 0; i < plugins.Length; i++) + { + var plugin = plugins[i]; + var overlay = plugin.RenderOverlay; + if (!plugin.Initialized || plugin.Failed || overlay == null) + continue; + + if (!plugin.RenderOverlayLogged) + { + // One line per plugin per session: proves the engine is actually driving the overlay export. + plugin.RenderOverlayLogged = true; + RynthLog.Plugin($"PluginManager: first RenderOverlay call for {plugin.DisplayName}."); + } + + try + { + overlay(); + } + catch (Exception ex) + { + plugin.RenderOverlay = null; + RynthLog.Error($"PluginManager: {plugin.DisplayName} RenderOverlay threw {ex.GetType().Name}: {ex.Message} - overlay windows off for this session (plugin keeps running)."); + } + } + } + + // RenderOverlayAll diagnostics (render thread only). + private static long _overlayCalls; + private static int _overlayBound; + private static bool _loggedOverlayWaitingForLogin; + private static int _loggedOverlayBound = -1; + private static int _loggedOverlayTotal = -1; + + /// + /// True when an initialized, healthy plugin exports RynthPluginRenderOverlay. Reads the + /// render snapshot only (no lock, no allocation): safe every frame on the render thread. + /// + internal static bool HasOverlayPlugins + { + get + { + LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot); + for (int i = 0; i < plugins.Length; i++) + { + var p = plugins[i]; + if (p.Initialized && !p.Failed && p.RenderOverlay != null) return true; + } + return false; + } + } + + /// Overlay stats for the ImGui heartbeat line. + internal static string DescribeOverlayState() + => $"overlayCalls={_overlayCalls} loginSeen={_loginCompleteObserved} overlayPlugins={_overlayBound}"; + public static void ShutdownAll() { RynthLog.Plugin($"PluginManager: Shutting down {_plugins.Count} plugin(s)..."); diff --git a/src/RynthCore.Engine/UI/LayeredWindow.cs b/src/RynthCore.Engine/UI/LayeredWindow.cs index 9ada298..5b8aa13 100644 --- a/src/RynthCore.Engine/UI/LayeredWindow.cs +++ b/src/RynthCore.Engine/UI/LayeredWindow.cs @@ -367,6 +367,25 @@ internal sealed unsafe class LayeredWindow : IDisposable } } + /// + /// The content rects (screen px: left, top, width, height) of every visible panel window. + /// They sit above the game window, so nothing drawn in the game frame can show over them. + /// + internal static List<(int Left, int Top, int Width, int Height)> VisibleContentRects() + { + LayeredWindow[] windows; + lock (_instancesLock) + { + windows = new LayeredWindow[_instances.Count]; + _instances.Values.CopyTo(windows, 0); + } + var rects = new List<(int, int, int, int)>(windows.Length); + foreach (LayeredWindow w in windows) + if (w.IsVisible && w.Width > 0 && w.Height > 0) + rects.Add((w.ScreenLeft, w.ScreenTop, w.Width, w.Height)); + return rects; + } + private static readonly HashSet _sweptLogged = new(); [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]