RynthCore as of 2026-09-05 (internal f9abab9)
A snapshot of the working tree for aelrynth.com/git/: the code, build files and public docs. Internal review notes and agent instructions are left out. MIT licensed; see LICENSE. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
68c301dac8
277 changed files with 86286 additions and 0 deletions
1360
src/RynthCore.Engine/ImGui/DX9Backend.cs
Normal file
1360
src/RynthCore.Engine/ImGui/DX9Backend.cs
Normal file
File diff suppressed because it is too large
Load diff
582
src/RynthCore.Engine/ImGui/EngineFrameController.cs
Normal file
582
src/RynthCore.Engine/ImGui/EngineFrameController.cs
Normal file
|
|
@ -0,0 +1,582 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/EngineFrameController.cs
|
||||
// Top-level orchestrator: drives the per-frame engine pipeline from EndScene.
|
||||
//
|
||||
// Per-frame work splits into two layers:
|
||||
// * Always-on (when EndScene fires): GameMatrixCapture, Nav3DRenderInjector
|
||||
// install/reset, PluginManager init/pending/delete/tick, DX9Backend.RenderNav3D
|
||||
// fallback. These run regardless of EngineSettings.EnableImGuiBackend so
|
||||
// world→screen, nav markers, and plugin lifecycle stay alive even when
|
||||
// the ImGui surface is disabled.
|
||||
// * ImGui-gated (only when EngineSettings.EnableImGuiBackend is true):
|
||||
// Win32Backend.NewFrame / DX9Backend.NewFrame, ImGui.NewFrame/EndFrame/
|
||||
// Render, RynthCoreShell + plugin RenderAll, DX9Backend.RenderDrawData,
|
||||
// mouse/keyboard capture flag updates, multi-viewport platform pump.
|
||||
//
|
||||
// Renamed 2026-05-10 from ImGuiController — the type now owns more than
|
||||
// ImGui's frame; the ImGui block is just one branch of its work.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.D3D9;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static class EngineFrameController
|
||||
{
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern uint GetCurrentProcessId();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool GetClientRect(IntPtr hWnd, out ClientRect lpRect);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ClientToScreen(IntPtr hWnd, ref ClientPoint lpPoint);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct ClientRect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct ClientPoint { public int X, Y; }
|
||||
|
||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||
|
||||
private static bool _imguiInitialized;
|
||||
private static bool _imguiInitFailed;
|
||||
private static bool _coreResolved;
|
||||
private static bool _pluginsInitialized;
|
||||
private static IntPtr _context;
|
||||
private static IntPtr _gameHwnd;
|
||||
|
||||
/// <summary>
|
||||
/// Live D3D9 device pointer, published by <see cref="OnEndScene"/> on AC's
|
||||
/// render thread and consumed by <see cref="PumpPluginFrame"/> on the
|
||||
/// dedicated plugin pump thread. Zero until the first real backbuffer
|
||||
/// frame — the pump no-ops until then (we need the HWND/core resolved and
|
||||
/// a device to hand plugins). Volatile: written by render thread, read by
|
||||
/// pump thread; IntPtr writes are atomic on this platform.
|
||||
/// </summary>
|
||||
internal static volatile IntPtr CachedDevice;
|
||||
private static int _pluginPumpInFrame; // re-entrancy guard for the pump
|
||||
private static long _lastFrameTicks;
|
||||
private static int _frameCount;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the AC game HWND (via the D3D9 device, falling back to
|
||||
/// EnumWindows) and seeds <see cref="EntryPoint.GameHwnd"/>. Required by
|
||||
/// the always-on path (Nav3DRenderInjector + DX9Backend core delegates)
|
||||
/// and by the ImGui init path. Idempotent — safe to call every frame.
|
||||
/// </summary>
|
||||
public static bool EnsureCore(IntPtr pDevice)
|
||||
{
|
||||
if (_coreResolved && _gameHwnd != IntPtr.Zero)
|
||||
return true;
|
||||
|
||||
// Prefer the actual D3D device window so startup does not latch onto a splash/loading HWND.
|
||||
_gameHwnd = DX9Backend.GetDeviceWindow(pDevice);
|
||||
if (_gameHwnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Render("EngineFrameController: D3D device window unavailable, falling back to EnumWindows.");
|
||||
_gameHwnd = FindGameWindow();
|
||||
}
|
||||
|
||||
if (_gameHwnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Render("EngineFrameController: Could not find game window.");
|
||||
return false;
|
||||
}
|
||||
|
||||
RynthLog.Render($"EngineFrameController: Game HWND = 0x{_gameHwnd:X8}");
|
||||
EntryPoint.GameHwnd = _gameHwnd;
|
||||
_coreResolved = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool Init(IntPtr pDevice)
|
||||
{
|
||||
if (_imguiInitialized)
|
||||
return true;
|
||||
|
||||
if (!EnsureCore(pDevice))
|
||||
return false;
|
||||
|
||||
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();
|
||||
bool initSucceeded = false;
|
||||
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
|
||||
{
|
||||
const string iniPath = @"C:\Games\RynthSuite\RynthAi\imgui.ini";
|
||||
System.IO.Directory.CreateDirectory(@"C:\Games\RynthSuite\RynthAi");
|
||||
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
|
||||
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
|
||||
RynthLog.Render($"EngineFrameController: imgui.ini pinned to {iniPath}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Render($"EngineFrameController: failed to pin imgui.ini path - {ex.Message}");
|
||||
}
|
||||
|
||||
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
|
||||
// ViewportsEnable was enabling ImGui multi-viewport platform/renderer
|
||||
// callbacks against a cimgui.dll that is NOT built with
|
||||
// IMGUI_ENABLE_VIEWPORTS. The platform/renderer callback chain then
|
||||
// recursed (Platform → Renderer → Platform → ...) on AC's render
|
||||
// thread, eating the 1MB stack in ~17s and AV'ing in ntdll mid-push.
|
||||
// CLAUDE.md flags this: Multi-viewport "requires cimgui built with
|
||||
// IMGUI_ENABLE_VIEWPORTS" — flag re-introduced this in the engine
|
||||
// and triggered the silent stack-overflow on every login.
|
||||
// io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;
|
||||
// Popped-out plugin windows use WS_EX_TOOLWINDOW so they don't show
|
||||
// up as extra "Asheron's Call" entries in the taskbar — critical for
|
||||
// users running many clients side by side.
|
||||
io.ConfigViewportsNoTaskBarIcon = true;
|
||||
ImGuiNET.ImGui.StyleColorsDark();
|
||||
|
||||
// One-shot offset probe for diagnostics — safe to keep installed.
|
||||
ViewportProbe.Run();
|
||||
|
||||
if (!Win32Backend.Init(_gameHwnd))
|
||||
return false;
|
||||
|
||||
if (!DX9Backend.InitImGui(pDevice))
|
||||
return false;
|
||||
|
||||
// Viewport backends only run when ViewportsEnable is on. Installing
|
||||
// their callbacks on PlatformIO without the flag has no upside and
|
||||
// just expands the crash surface.
|
||||
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
|
||||
{
|
||||
bool platformOk = ViewportPlatformBackend.Init(_gameHwnd);
|
||||
bool rendererOk = platformOk && ViewportRendererBackend.Init(pDevice);
|
||||
if (!platformOk || !rendererOk)
|
||||
{
|
||||
RynthLog.Render($"EngineFrameController: viewport init failed (platform={platformOk}, renderer={rendererOk}) — disabling ViewportsEnable.");
|
||||
io.ConfigFlags &= ~ImGuiConfigFlags.ViewportsEnable;
|
||||
}
|
||||
ViewportPlatformBackend.ImGuiContext = _context;
|
||||
}
|
||||
|
||||
_lastFrameTicks = Stopwatch.GetTimestamp();
|
||||
_imguiInitialized = true;
|
||||
initSucceeded = true;
|
||||
|
||||
RynthLog.Render("EngineFrameController: Fully initialized - RynthCore shell active.");
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!initSucceeded && _context != IntPtr.Zero)
|
||||
{
|
||||
ImGuiNET.ImGui.DestroyContext(_context);
|
||||
_context = IntPtr.Zero;
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCurrentContext(previousContext);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
if (!_imguiInitialized)
|
||||
return;
|
||||
|
||||
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
|
||||
IntPtr contextToDestroy = _context;
|
||||
|
||||
try
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(contextToDestroy);
|
||||
|
||||
// Zero the WndProc context guard BEFORE DestroyContext so any
|
||||
// deferred OS messages that arrive at viewport HWNDs during or
|
||||
// after teardown don't try to call into freed ImGui memory.
|
||||
ViewportPlatformBackend.ImGuiContext = IntPtr.Zero;
|
||||
PluginManager.ShutdownAll();
|
||||
OverlayTextureRenderer.Shutdown();
|
||||
ViewportRendererBackend.Shutdown();
|
||||
ViewportPlatformBackend.Shutdown();
|
||||
DX9Backend.Shutdown();
|
||||
// Do NOT call Win32Backend.Shutdown() here. EngineLifecycle.Shutdown
|
||||
// owns that step explicitly, AFTER AvaloniaOverlay.Stop — floating
|
||||
// panels are destroyed via RunOnGameThread (a SendMessage handled by
|
||||
// our subclass WndProc), so restoring AC's original WndProc this
|
||||
// early makes that SendMessage land on AC's proc, get ignored, and
|
||||
// "succeed" — DestroyWindow never runs and the orphaned panel HWND
|
||||
// outlives the engine module with its WndProc pointing at freed code.
|
||||
ImGuiNET.ImGui.DestroyContext(contextToDestroy);
|
||||
|
||||
_imguiInitialized = false;
|
||||
_coreResolved = false;
|
||||
_context = IntPtr.Zero;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(previousContext == contextToDestroy ? IntPtr.Zero : previousContext);
|
||||
}
|
||||
}
|
||||
|
||||
public static void OnEndScene(IntPtr pDevice)
|
||||
{
|
||||
// ── Always-on engine pipeline ────────────────────────────────────
|
||||
// These run on every EndScene tick, regardless of
|
||||
// EngineSettings.EnableImGuiBackend, so world→screen capture, nav-
|
||||
// marker rendering, and plugin lifecycle stay alive when the ImGui
|
||||
// surface is disabled.
|
||||
try
|
||||
{
|
||||
// Resolve game HWND and seed EntryPoint.GameHwnd. Required even
|
||||
// in ImGui-off mode so Avalonia owner-window binding works.
|
||||
EnsureCore(pDevice);
|
||||
|
||||
// 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.
|
||||
DX9Backend.InitCore(pDevice);
|
||||
|
||||
// Install the DrawIndexedPrimitive hook that injects Nav3D markers at
|
||||
// the 3D→UI ZENABLE transition so they render BEHIND AC's UI. Idempotent
|
||||
// (installs once); placed here because its Detour reads the device
|
||||
// delegates InitCore (above) just cached. WITHOUT THIS the injector never
|
||||
// accumulates, RenderedThisFrame stays false on every frame, and the
|
||||
// end-of-frame fallback below paints markers OVER the UI. This call was
|
||||
// dropped in the v0.19 Nav3D double-buffer refactor — restored here.
|
||||
D3D9.Nav3DRenderInjector.Install(pDevice);
|
||||
|
||||
// Capture the game's View/Projection matrices before ImGui touches them
|
||||
GameMatrixCapture.CaptureFrame(pDevice);
|
||||
|
||||
// Refresh the player-skill snapshot on AC's main thread (this
|
||||
// EndScene runs on it). The plugin tick is pumped off-thread and
|
||||
// can't read skills live (TryGetObjectQualitiesPtr fail-closes);
|
||||
// without this it gets (0,0) → tier-1 casts and never buffs.
|
||||
// Throttled internally.
|
||||
Compatibility.ClientObjectHooks.PrefetchPlayerSkills();
|
||||
// Same rationale + same main-thread guard: snapshot the spellbook
|
||||
// so the off-thread pump can resolve tiers against spells the char
|
||||
// actually knows (throttled internally).
|
||||
Compatibility.ClientObjectHooks.PrefetchKnownSpells();
|
||||
// Same main-thread guard + rationale: snapshot AC's real
|
||||
// ObjectIsAttackable for every live object so the off-thread pump
|
||||
// can tell NPC/vendor (attackable=false) from monster. Without it
|
||||
// the pump got hardcoded true and the classifier promoted NPCs to
|
||||
// attackable creatures → war magic cast at NPCs (throttled
|
||||
// internally).
|
||||
Compatibility.ClientObjectHooks.PrefetchAttackable();
|
||||
// Same main-thread guard + rationale: snapshot object names and
|
||||
// item types for every live object so the off-thread plugin pump
|
||||
// can classify objects without walking AC's live CObjectMaint
|
||||
// table (0x0067E779 READ-AV class; throttled internally at 3 s).
|
||||
Compatibility.ClientObjectHooks.PrefetchObjectIdentity();
|
||||
// Same main-thread guard: snapshot every live object's POSITION so the
|
||||
// off-thread plugin pump reads position from cache instead of resolving
|
||||
// _getWeenieObject live — that resolution is AC's CObjectMaint walk and
|
||||
// is the dump-verified 0x0067E779 READ-AV when done on the pump thread.
|
||||
// Sampled every frame (positions are volatile), zero-alloc.
|
||||
Compatibility.ClientObjectHooks.PrefetchPositions();
|
||||
// Same main-thread guard: snapshot XP/luminance/deaths/vitae (main-thread-only
|
||||
// Inq* reads) so the GetEngineStatusJson host bridge can serve them off-thread (throttled).
|
||||
Compatibility.ClientObjectHooks.PrefetchPlayerStats();
|
||||
|
||||
// Cold-login object backfill on the SAME AC main thread as the
|
||||
// skill prefetch above: deliver objects already present at login
|
||||
// (the incremental CreateObject hook only catches NEW spawns, so
|
||||
// login-present mobs were never reaching the plugin — proven via
|
||||
// per-id ClassifyTrace). One-shot per login, IsOnMainThread-gated
|
||||
// and attempt-bounded internally; reuses the guarded
|
||||
// QueueCreateObject delivery path. EndScene is a build-independent
|
||||
// anchor (D3D9 hook, not string-resolved like SmartBox).
|
||||
try { Plugins.PluginManager.TrySeedLiveObjectsFromCObjectMaintOnce(); }
|
||||
catch (Exception ex) { RynthLog.Plugin($"CObjectMaint seed threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
|
||||
// P1: drain off-thread bot actions (UseObject / ChangeCombatMode / melee /
|
||||
// missile / movement / jump) here on AC's MAIN thread. The pump enqueues
|
||||
// them instead of calling AC directly, so AC mutates its single-threaded
|
||||
// object/animation (CSequence) state on the same thread that updates it —
|
||||
// closing the off-thread-mutation corruption class (the CSequence::
|
||||
// update_internal AV captured 2026-06-03, the 0x0055FA24 range-list AV, etc).
|
||||
// CastSpell is deliberately NOT routed here (stays off-thread + SEH).
|
||||
try { Compatibility.AcMainThreadQueue.Drain(); }
|
||||
catch (Exception ex) { RynthLog.Plugin($"AcMainThreadQueue.Drain threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
|
||||
// Nav3DRenderInjector fires mid-frame at the 3D→UI ZENABLE
|
||||
// transition — that's the only pipeline position where markers
|
||||
// can render BEHIND AC's UI (the UI pass draws after ZENABLE
|
||||
// turns off, and the end-of-frame fallback is past it entirely).
|
||||
//
|
||||
// The injector accumulates state per-frame via DrawIndexedPrimitive
|
||||
// callbacks during AC's draws (which fire before this EndScene),
|
||||
// so by the time we check RenderedThisFrame here, its decision
|
||||
// for the current frame is final. ResetFrame at the END of
|
||||
// OnEndScene primes it for the next frame's accumulation.
|
||||
//
|
||||
// Historically the engine forced the end-of-frame fallback ONLY
|
||||
// because the injector's hit-rate varied across motion, producing
|
||||
// flicker when some frames painted at the 3D→UI boundary and
|
||||
// others at end-of-frame. We accept that risk here: the user
|
||||
// wants markers behind the UI, and a frame the injector misses
|
||||
// simply doesn't render markers (less jarring than a Z-order flip).
|
||||
bool nav3DAlreadyRendered = D3D9.Nav3DRenderInjector.RenderedThisFrame;
|
||||
|
||||
// Publish the live device pointer for the off-render-thread plugin
|
||||
// pump (see PumpPluginFrame). The D3D9 device is a stable COM
|
||||
// pointer for the session, so caching it is safe; the pump only
|
||||
// passes it opaquely to plugins (RynthAi in Avalonia-only mode
|
||||
// never dereferences it). Atomic IntPtr write; volatile read.
|
||||
CachedDevice = pDevice;
|
||||
|
||||
// NOTE (2026-05-16): PluginManager.InitPlugins / ProcessPendingActions
|
||||
// / FlushPendingDeletes / TickAll are NO LONGER called here. The
|
||||
// 2026-05-10 refactor put them on this EndScene reverse-P/Invoke
|
||||
// (AC's D3D9 render thread); a GC during the plugin tick on that
|
||||
// AC-owned thread fail-fasts in NativeAOT's
|
||||
// RhpReversePInvokeAttachOrTrapThread2 (proven from the
|
||||
// 2026-05-16 09:39 dump). They now run on the dedicated managed
|
||||
// plugin pump thread (EntryPoint.StartNormalPluginPump →
|
||||
// PumpPluginFrame), which mirrors the proven DecalCoexistence
|
||||
// pump. EXACTLY ONE TickAll driver: this render path no longer
|
||||
// calls it at all.
|
||||
|
||||
// ── ImGui-gated work ─────────────────────────────────────────
|
||||
if (Plugins.EngineSettings.EnableImGuiBackend)
|
||||
RunImGuiFrame(pDevice);
|
||||
|
||||
// Fallback render — only fires when the injector missed this
|
||||
// frame's 3D→UI transition. _coreInitialized is enough — this
|
||||
// does not touch font / vertex buffer state.
|
||||
if (!nav3DAlreadyRendered)
|
||||
DX9Backend.RenderNav3D(pDevice);
|
||||
|
||||
// Custom D3D9 vital HUD (Health/Stamina/Mana). Always-on (independent
|
||||
// of EnableImGuiBackend) so it shows even in Avalonia-only mode; drawn
|
||||
// last so it sits on top of the world + AC UI. Reads the vitals
|
||||
// snapshot maintained on this same (AC main) thread and does its own
|
||||
// device state save/restore. No-op until vitals are seeded.
|
||||
if (Plugins.EngineSettings.DrawCustomVitalBars)
|
||||
D3D9.VitalHud.Draw(pDevice);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"EngineFrameController: frame {_frameCount} engine error: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Prime the injector for the next frame's DIP accumulation.
|
||||
// Without this, _markersRenderedThisFrame latches true after
|
||||
// the first 3D→UI transition in the session and the injector
|
||||
// never fires again — every subsequent frame falls back to the
|
||||
// end-of-frame draw (which paints over the UI).
|
||||
D3D9.Nav3DRenderInjector.ResetFrame();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plugin lifecycle/tick work that used to run inline in
|
||||
/// <see cref="OnEndScene"/>. Driven by the dedicated managed plugin pump
|
||||
/// thread (EntryPoint.StartNormalPluginPump) — NOT AC's render thread —
|
||||
/// so a GC during the plugin tick can't fail-fast NativeAOT's reverse-
|
||||
/// P/Invoke transition on an AC-owned thread (the 2026-05-16 root cause).
|
||||
///
|
||||
/// No-ops until the render path has resolved the game HWND and published
|
||||
/// a device (CachedDevice != 0). Single-threaded by contract: only the
|
||||
/// one pump thread calls this; the render path no longer touches
|
||||
/// PluginManager at all, so there is exactly one TickAll driver. The
|
||||
/// re-entrancy guard is belt-and-braces against an accidental second
|
||||
/// caller.
|
||||
/// </summary>
|
||||
public static void PumpPluginFrame()
|
||||
{
|
||||
IntPtr device = CachedDevice;
|
||||
if (device == IntPtr.Zero || _gameHwnd == IntPtr.Zero)
|
||||
return; // render path hasn't established core state yet
|
||||
|
||||
if (System.Threading.Interlocked.Exchange(ref _pluginPumpInFrame, 1) != 0)
|
||||
return; // never re-enter PluginManager from two stacks
|
||||
try
|
||||
{
|
||||
if (!_pluginsInitialized)
|
||||
{
|
||||
_pluginsInitialized = true;
|
||||
PluginManager.InitPlugins(_context, device, _gameHwnd);
|
||||
}
|
||||
|
||||
PluginManager.ProcessPendingActions(_context, device, _gameHwnd);
|
||||
PluginManager.FlushPendingDeletes(); // closes the create→delete race window
|
||||
PluginManager.TickAll();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
System.Threading.Interlocked.Exchange(ref _pluginPumpInFrame, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the ImGui-specific portion of the per-frame pipeline:
|
||||
/// backend NewFrame plumbing, ImGui frame open/close, RynthCore shell +
|
||||
/// plugin RenderAll, draw-data submission, capture flag update, and the
|
||||
/// multi-viewport platform pump. Bypassed entirely when
|
||||
/// EngineSettings.EnableImGuiBackend is false.
|
||||
/// </summary>
|
||||
private static void RunImGuiFrame(IntPtr pDevice)
|
||||
{
|
||||
if (_imguiInitFailed) return;
|
||||
|
||||
if (!_imguiInitialized)
|
||||
{
|
||||
if (!Init(pDevice))
|
||||
{
|
||||
_imguiInitFailed = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
|
||||
ImGuiNET.ImGui.SetCurrentContext(_context);
|
||||
bool frameStarted = false;
|
||||
bool frameEnded = false;
|
||||
|
||||
try
|
||||
{
|
||||
_frameCount++;
|
||||
DX9Backend.NewFrame();
|
||||
Win32Backend.NewFrame();
|
||||
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
|
||||
// Fallback: if Win32Backend could not determine display size, read from the D3D9 viewport.
|
||||
if (io.DisplaySize.X <= 1 || io.DisplaySize.Y <= 1)
|
||||
{
|
||||
DX9Backend.GetViewportSize(pDevice, out int vpW, out int vpH);
|
||||
if (vpW > 1 && vpH > 1)
|
||||
io.DisplaySize = new System.Numerics.Vector2(vpW, vpH);
|
||||
}
|
||||
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
float dt = (float)(now - _lastFrameTicks) / Stopwatch.Frequency;
|
||||
_lastFrameTicks = now;
|
||||
io.DeltaTime = dt > 0f ? dt : 1f / 60f;
|
||||
|
||||
// With ViewportsEnable on, ImGui routes mouse and window positions in
|
||||
// absolute screen coords. The main viewport's Pos must equal the game
|
||||
// client's screen origin so clicks over the main viewport map to the
|
||||
// correct windows, and popped-out viewports share a coord system with
|
||||
// the main one.
|
||||
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
|
||||
{
|
||||
int screenX = 0, screenY = 0;
|
||||
if (_gameHwnd != IntPtr.Zero)
|
||||
{
|
||||
ClientPoint p = new ClientPoint { X = 0, Y = 0 };
|
||||
if (ClientToScreen(_gameHwnd, ref p)) { screenX = p.X; screenY = p.Y; }
|
||||
}
|
||||
ImGuiViewportPtr mainVp = ImGuiNET.ImGui.GetMainViewport();
|
||||
mainVp.Pos = new System.Numerics.Vector2(screenX, screenY);
|
||||
mainVp.Size = io.DisplaySize;
|
||||
mainVp.WorkPos = new System.Numerics.Vector2(screenX, screenY);
|
||||
mainVp.WorkSize = io.DisplaySize;
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.NewFrame();
|
||||
frameStarted = true;
|
||||
// EnableImGuiShell gates the in-AC ImGui surface as a whole: both the
|
||||
// RynthCore overlay bar and any plugin-drawn ImGui windows. Plugins
|
||||
// still load, init, and tick when this is off — they just don't
|
||||
// draw, so Avalonia panels can drive them via the plugin's C exports.
|
||||
if (Plugins.EngineSettings.EnableImGuiShell)
|
||||
{
|
||||
RynthCoreShell.Render(_frameCount);
|
||||
PluginManager.RenderAll();
|
||||
}
|
||||
|
||||
bool captureMouse =
|
||||
ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow) ||
|
||||
ImGuiNET.ImGui.IsAnyItemActive();
|
||||
bool captureKeyboard = ImGuiNET.ImGui.IsAnyItemActive();
|
||||
|
||||
ImGuiNET.ImGui.EndFrame();
|
||||
frameEnded = true;
|
||||
ImGuiNET.ImGui.Render();
|
||||
Win32Backend.UpdateCaptureFlags(captureMouse, captureKeyboard);
|
||||
|
||||
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
|
||||
|
||||
DX9Backend.RenderDrawData(drawData, pDevice);
|
||||
// OverlayTextureRenderer.Render is now driven from EndSceneHook.EndSceneDetour
|
||||
// directly so the Avalonia compositor runs even when EnableImGuiBackend=false.
|
||||
// Leaving it out of this call site avoids double-blit when ImGui is also active.
|
||||
|
||||
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
|
||||
{
|
||||
ImGuiNET.ImGui.UpdatePlatformWindows();
|
||||
ImGuiNET.ImGui.RenderPlatformWindowsDefault();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Keep Dear ImGui's frame state balanced so the next frame does not assert.
|
||||
if (frameStarted && !frameEnded && ImGuiNET.ImGui.GetCurrentContext() == _context)
|
||||
ImGuiNET.ImGui.EndFrame();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
RynthLog.Info($"EngineFrameController: frame {_frameCount} ImGui error: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(previousContext);
|
||||
}
|
||||
}
|
||||
|
||||
internal static IntPtr FindGameWindow()
|
||||
{
|
||||
uint pid = GetCurrentProcessId();
|
||||
IntPtr found = IntPtr.Zero;
|
||||
|
||||
EnumWindows((hWnd, _) =>
|
||||
{
|
||||
GetWindowThreadProcessId(hWnd, out uint windowPid);
|
||||
if (windowPid == pid && IsWindowVisible(hWnd))
|
||||
{
|
||||
found = hWnd;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}, IntPtr.Zero);
|
||||
|
||||
return found;
|
||||
}
|
||||
}
|
||||
1204
src/RynthCore.Engine/ImGui/RynthCoreShell.cs
Normal file
1204
src/RynthCore.Engine/ImGui/RynthCoreShell.cs
Normal file
File diff suppressed because it is too large
Load diff
53
src/RynthCore.Engine/ImGui/ViewportOffsets.cs
Normal file
53
src/RynthCore.Engine/ImGui/ViewportOffsets.cs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — ImGui/ViewportOffsets.cs
|
||||
// Byte offsets of ImGuiPlatformIO callback fields in the cimgui.dll shipped
|
||||
// with ImGui.NET 1.91.6.1 (docking branch).
|
||||
//
|
||||
// WARNING: these do NOT match ImGui.NET's compiled struct layout. ImGui.NET
|
||||
// prepends 36 bytes of clipboard/IME/OpenInShell fields that this cimgui.dll
|
||||
// build does not have. Writing via ImGui.NET's ref properties lands 36 bytes
|
||||
// past the native field, so the native library sees NULL and asserts
|
||||
// "Platform init didn't install handlers".
|
||||
//
|
||||
// Source of truth (disassembled cimgui.dll 1.91.6.1, x86):
|
||||
// ImGuiPlatformIO_Set_Platform_GetWindowPos → mov [pio+0x10], shim
|
||||
// ImGuiPlatformIO_Set_Platform_GetWindowSize → mov [pio+0x18], shim
|
||||
// igUpdatePlatformWindows first callback dispatch → call [g+0x37B8]
|
||||
// with ImGuiContext PlatformIO offset → pio field 0 = Platform_CreateWindow
|
||||
//
|
||||
// Struct size (from constructor memset): 0x74 (116 bytes). Fields 0x00..0x5F
|
||||
// hold 24 callback pointers; 0x60..0x73 hold Monitors + Viewports ImVectors.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static class ViewportOffsets
|
||||
{
|
||||
// Platform_* (18 callbacks — this cimgui.dll build lacks GetWindowWorkAreaInsets)
|
||||
public const int PlatformCreateWindow = 0;
|
||||
public const int PlatformDestroyWindow = 4;
|
||||
public const int PlatformShowWindow = 8;
|
||||
public const int PlatformSetWindowPos = 12;
|
||||
public const int PlatformGetWindowPos = 16; // confirmed via _Set_ helper disasm
|
||||
public const int PlatformSetWindowSize = 20;
|
||||
public const int PlatformGetWindowSize = 24; // confirmed via _Set_ helper disasm
|
||||
public const int PlatformSetWindowFocus = 28;
|
||||
public const int PlatformGetWindowFocus = 32;
|
||||
public const int PlatformGetWindowMinimized = 36;
|
||||
public const int PlatformSetWindowTitle = 40;
|
||||
public const int PlatformSetWindowAlpha = 44;
|
||||
public const int PlatformUpdateWindow = 48;
|
||||
public const int PlatformRenderWindow = 52;
|
||||
public const int PlatformSwapBuffers = 56;
|
||||
public const int PlatformGetWindowDpiScale = 60;
|
||||
public const int PlatformOnChangedViewport = 64;
|
||||
public const int PlatformCreateVkSurface = 68;
|
||||
|
||||
// Renderer_* (5 callbacks) — RendererCreateWindow at +72 confirmed by
|
||||
// igUpdatePlatformWindows disasm: [ebx+0x3800] = [pio + 0x48] = +72.
|
||||
public const int RendererCreateWindow = 72;
|
||||
public const int RendererDestroyWindow = 76;
|
||||
public const int RendererSetWindowSize = 80;
|
||||
public const int RendererRenderWindow = 84;
|
||||
public const int RendererSwapBuffers = 88;
|
||||
}
|
||||
829
src/RynthCore.Engine/ImGui/ViewportPlatformBackend.cs
Normal file
829
src/RynthCore.Engine/ImGui/ViewportPlatformBackend.cs
Normal file
|
|
@ -0,0 +1,829 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — ImGui/ViewportPlatformBackend.cs
|
||||
// Win32 platform backend for Dear ImGui multi-viewport (equivalent of
|
||||
// imgui_impl_win32's viewport-capable portion). Installs Platform_* callbacks
|
||||
// into the native ImGuiPlatformIO struct, registers a window class for
|
||||
// popped-out ImGui windows, and proxies the required Win32 calls.
|
||||
//
|
||||
// Input for viewport HWNDs is forwarded into the existing Dear ImGui IO
|
||||
// event queue via a dedicated WndProc.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using ImGuiNET;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static unsafe class ViewportPlatformBackend
|
||||
{
|
||||
// ── Delegate types (cdecl; ImGui callbacks on x86 use the default C ABI) ──
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void ViewportVoidDelegate(ImGuiViewport* vp);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void ViewportGetVec2Delegate(ImGuiViewport* vp, Vector2* outVec);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void ViewportSetVec2Delegate(ImGuiViewport* vp, Vector2 value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate byte ViewportGetBoolDelegate(ImGuiViewport* vp);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void ViewportSetStringDelegate(ImGuiViewport* vp, IntPtr str);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void ViewportSetFloatDelegate(ImGuiViewport* vp, float value);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern ushort RegisterClassExW(ref WNDCLASSEXW lpwcx);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr CreateWindowExW(
|
||||
uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle,
|
||||
int X, int Y, int nWidth, int nHeight,
|
||||
IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool DestroyWindow(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
|
||||
int X, int Y, int cx, int cy, uint uFlags);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern int SetWindowTextW(IntPtr hWnd, string lpString);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool SetForegroundWindow(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool IsIconic(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr SetWindowLongW(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetWindowLongW(IntPtr hWnd, int nIndex);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool SetLayeredWindowAttributes(IntPtr hWnd, uint crKey, byte bAlpha, uint dwFlags);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr DefWindowProcW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool AdjustWindowRectEx(ref RECT lpRect, uint dwStyle, bool bMenu, uint dwExStyle);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool PostMessageW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr SetCapture(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ReleaseCapture();
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct POINT { public int X, Y; }
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr LoadCursorW(IntPtr hInstance, IntPtr lpCursorName);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int GetSystemMetrics(int nIndex);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProc lpfnEnum, IntPtr dwData);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern bool GetMonitorInfoW(IntPtr hMonitor, ref MONITORINFO lpmi);
|
||||
|
||||
private delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct MONITORINFO
|
||||
{
|
||||
public uint cbSize;
|
||||
public RECT rcMonitor;
|
||||
public RECT rcWork;
|
||||
public uint dwFlags;
|
||||
}
|
||||
|
||||
private const int SM_CXSCREEN = 0;
|
||||
private const int SM_CYSCREEN = 1;
|
||||
private const uint MONITORINFOF_PRIMARY = 0x00000001;
|
||||
|
||||
// ImGuiPlatformIO Monitors ImVector (native cimgui.dll layout).
|
||||
// Native has 18 Platform_* + 5 Renderer_* = 23 callback pointers = 92 bytes,
|
||||
// then Monitors ImVector{ int Size; int Capacity; void* Data; } at +92..+103,
|
||||
// then Viewports ImVector at +104..+115. (ImGui.NET's compiled layout adds
|
||||
// GetWindowWorkAreaInsets and so puts Monitors at +96 — do NOT use that.)
|
||||
// Confirmed by probe dump showing Viewports.Size=1, Cap=8, Data=ptr at
|
||||
// +104..+115 when native had just seeded the main viewport.
|
||||
private const int MonitorsSize = 92;
|
||||
private const int MonitorsCapacity = 96;
|
||||
private const int MonitorsData = 100;
|
||||
|
||||
// ImGuiPlatformMonitor is 40 bytes (confirmed by cimgui.dll ctor "push 28h"):
|
||||
// +0 MainPos (ImVec2, 8)
|
||||
// +8 MainSize (ImVec2, 8)
|
||||
// +16 WorkPos (ImVec2, 8)
|
||||
// +24 WorkSize (ImVec2, 8)
|
||||
// +32 DpiScale (float, 4)
|
||||
// +36 PlatformHandle (void*, 4)
|
||||
private const int MonitorStructSize = 40;
|
||||
|
||||
private static IntPtr _monitorArrayPtr;
|
||||
private static int _monitorCount;
|
||||
|
||||
private delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct WNDCLASSEXW
|
||||
{
|
||||
public uint cbSize;
|
||||
public uint style;
|
||||
public IntPtr lpfnWndProc;
|
||||
public int cbClsExtra;
|
||||
public int cbWndExtra;
|
||||
public IntPtr hInstance;
|
||||
public IntPtr hIcon;
|
||||
public IntPtr hCursor;
|
||||
public IntPtr hbrBackground;
|
||||
[MarshalAs(UnmanagedType.LPWStr)] public string? lpszMenuName;
|
||||
[MarshalAs(UnmanagedType.LPWStr)] public string? lpszClassName;
|
||||
public IntPtr hIconSm;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct RECT { public int Left, Top, Right, Bottom; }
|
||||
|
||||
// Win32 constants
|
||||
private const int GWL_STYLE = -16;
|
||||
private const int GWL_EXSTYLE = -20;
|
||||
private const int SW_SHOWNA = 8;
|
||||
private const int SW_HIDE = 0;
|
||||
private const uint SWP_NOMOVE = 0x0002;
|
||||
private const uint SWP_NOSIZE = 0x0001;
|
||||
private const uint SWP_NOZORDER = 0x0004;
|
||||
private const uint SWP_NOACTIVATE = 0x0010;
|
||||
private const uint WS_POPUP = 0x80000000;
|
||||
private const uint WS_OVERLAPPEDWINDOW = 0x00CF0000;
|
||||
private const uint WS_CLIPCHILDREN = 0x02000000;
|
||||
private const uint WS_CLIPSIBLINGS = 0x04000000;
|
||||
private const uint WS_EX_TOOLWINDOW = 0x00000080;
|
||||
private const uint WS_EX_LAYERED = 0x00080000;
|
||||
private const uint WS_EX_APPWINDOW = 0x00040000;
|
||||
private const uint WS_EX_TOPMOST = 0x00000008;
|
||||
private const uint WS_EX_NOACTIVATE = 0x08000000;
|
||||
private const uint LWA_ALPHA = 0x00000002;
|
||||
private const uint WM_CLOSE = 0x0010;
|
||||
private const uint WM_MOVE = 0x0003;
|
||||
private const uint WM_SIZE = 0x0005;
|
||||
private const uint WM_MOUSEACTIVATE = 0x0021;
|
||||
private const uint WM_NCHITTEST = 0x0084;
|
||||
private const uint WM_MOUSEMOVE = 0x0200;
|
||||
private const uint WM_LBUTTONDOWN = 0x0201;
|
||||
private const uint WM_LBUTTONUP = 0x0202;
|
||||
private const uint WM_LBUTTONDBLCLK = 0x0203;
|
||||
private const uint WM_RBUTTONDOWN = 0x0204;
|
||||
private const uint WM_RBUTTONUP = 0x0205;
|
||||
private const uint WM_RBUTTONDBLCLK = 0x0206;
|
||||
private const uint WM_MBUTTONDOWN = 0x0207;
|
||||
private const uint WM_MBUTTONUP = 0x0208;
|
||||
private const uint WM_MBUTTONDBLCLK = 0x0209;
|
||||
private const uint WM_MOUSEWHEEL = 0x020A;
|
||||
private const uint WM_XBUTTONDOWN = 0x020B;
|
||||
private const uint WM_XBUTTONUP = 0x020C;
|
||||
private const uint WM_MOUSEHWHEEL = 0x020E;
|
||||
private const uint WM_KEYDOWN = 0x0100;
|
||||
private const uint WM_KEYUP = 0x0101;
|
||||
private const uint WM_CHAR = 0x0102;
|
||||
private const uint WM_SYSKEYDOWN = 0x0104;
|
||||
private const uint WM_SYSKEYUP = 0x0105;
|
||||
private const int MA_NOACTIVATE = 3;
|
||||
private const int HTCLIENT = 1;
|
||||
private const IntPtr IDC_ARROW = 0x7F00; // MAKEINTRESOURCE(32512)
|
||||
|
||||
private const string WindowClassName = "RynthCoreImGuiViewport";
|
||||
|
||||
// Pinned delegate instances — prevent GC while ImGui holds function pointers.
|
||||
private static readonly List<Delegate> _delegateRoots = new();
|
||||
private static WndProcDelegate? _viewportWndProc;
|
||||
private static IntPtr _viewportWndProcPtr;
|
||||
private static bool _initialized;
|
||||
private static bool _classRegistered;
|
||||
private static IntPtr _hInstance;
|
||||
private static IntPtr _mainHwnd;
|
||||
|
||||
// Per-viewport state kept on the managed side.
|
||||
// Keyed by the native ImGuiViewport* pointer.
|
||||
private static readonly Dictionary<IntPtr, ViewportState> _viewports = new();
|
||||
|
||||
private class ViewportState
|
||||
{
|
||||
public IntPtr Hwnd;
|
||||
public bool HwndOwned;
|
||||
public uint DwStyle;
|
||||
public uint DwExStyle;
|
||||
}
|
||||
|
||||
public static bool Init(IntPtr mainHwnd)
|
||||
{
|
||||
if (_initialized) return true;
|
||||
|
||||
_mainHwnd = mainHwnd;
|
||||
_hInstance = GetModuleHandleW(null);
|
||||
|
||||
if (!EnsureWindowClassRegistered())
|
||||
{
|
||||
RynthLog.Info($"ViewportPlatform: RegisterClassEx failed (err {Marshal.GetLastWin32Error()})");
|
||||
return false;
|
||||
}
|
||||
|
||||
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
|
||||
InstallCallbacks(pio);
|
||||
PopulateMonitors(pio);
|
||||
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
io.BackendFlags |= ImGuiBackendFlags.PlatformHasViewports;
|
||||
// Do NOT set HasMouseHoveredViewport: that flag tells ImGui the backend
|
||||
// will route hovered-viewport info via AddMouseViewportEvent each frame.
|
||||
// We don't call that, so setting the flag causes mouse input to drop on
|
||||
// the floor (IsWindowHovered returns false for every window).
|
||||
|
||||
// The main viewport's PlatformHandle points to the game window; store it
|
||||
// so the very first frame doesn't try to create a new HWND for viewport 0.
|
||||
ImGuiViewportPtr mainViewport = ImGuiNET.ImGui.GetMainViewport();
|
||||
mainViewport.PlatformHandle = _mainHwnd;
|
||||
mainViewport.PlatformHandleRaw = _mainHwnd;
|
||||
_viewports[(IntPtr)mainViewport.NativePtr] = new ViewportState
|
||||
{
|
||||
Hwnd = _mainHwnd,
|
||||
HwndOwned = false,
|
||||
DwStyle = unchecked((uint)(long)GetWindowLongW(_mainHwnd, GWL_STYLE)),
|
||||
DwExStyle = unchecked((uint)(long)GetWindowLongW(_mainHwnd, GWL_EXSTYLE)),
|
||||
};
|
||||
|
||||
_initialized = true;
|
||||
RynthLog.Info("ViewportPlatform: initialized.");
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
if (!_initialized) return;
|
||||
|
||||
// Destroy any viewport windows we created.
|
||||
foreach (var kv in _viewports)
|
||||
{
|
||||
if (kv.Value.HwndOwned && kv.Value.Hwnd != IntPtr.Zero)
|
||||
DestroyWindow(kv.Value.Hwnd);
|
||||
}
|
||||
_viewports.Clear();
|
||||
|
||||
// Clear the Monitors ImVector pointer in PlatformIO before freeing our
|
||||
// backing buffer — native ImGui otherwise keeps a stale Data pointer.
|
||||
if (_monitorArrayPtr != IntPtr.Zero)
|
||||
{
|
||||
try
|
||||
{
|
||||
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
|
||||
IntPtr pioNative = (IntPtr)pio.NativePtr;
|
||||
Marshal.WriteInt32(pioNative, MonitorsSize, 0);
|
||||
Marshal.WriteInt32(pioNative, MonitorsCapacity, 0);
|
||||
Marshal.WriteIntPtr(pioNative, MonitorsData, IntPtr.Zero);
|
||||
}
|
||||
catch { /* context may already be torn down */ }
|
||||
|
||||
Marshal.FreeHGlobal(_monitorArrayPtr);
|
||||
_monitorArrayPtr = IntPtr.Zero;
|
||||
_monitorCount = 0;
|
||||
}
|
||||
|
||||
_initialized = false;
|
||||
}
|
||||
|
||||
// Dear ImGui asserts Monitor.Size > 0 before the first UpdatePlatformWindows
|
||||
// call when ViewportsEnable is on. Populate the Monitors ImVector with the
|
||||
// primary (and any secondary) displays so windows can pop out correctly.
|
||||
private static void PopulateMonitors(ImGuiPlatformIOPtr pio)
|
||||
{
|
||||
var rects = new List<(RECT mon, RECT work, bool primary)>();
|
||||
MonitorEnumProc cb = (IntPtr hMon, IntPtr hdc, ref RECT r, IntPtr _) =>
|
||||
{
|
||||
MONITORINFO mi = default;
|
||||
mi.cbSize = (uint)Marshal.SizeOf<MONITORINFO>();
|
||||
if (GetMonitorInfoW(hMon, ref mi))
|
||||
rects.Add((mi.rcMonitor, mi.rcWork, (mi.dwFlags & MONITORINFOF_PRIMARY) != 0));
|
||||
return true;
|
||||
};
|
||||
|
||||
if (!EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, cb, IntPtr.Zero) || rects.Count == 0)
|
||||
{
|
||||
// Fallback: single primary display via GetSystemMetrics.
|
||||
int w = GetSystemMetrics(SM_CXSCREEN);
|
||||
int h = GetSystemMetrics(SM_CYSCREEN);
|
||||
RECT r = new RECT { Left = 0, Top = 0, Right = w > 0 ? w : 1920, Bottom = h > 0 ? h : 1080 };
|
||||
rects.Add((r, r, true));
|
||||
}
|
||||
|
||||
GC.KeepAlive(cb);
|
||||
|
||||
_monitorCount = rects.Count;
|
||||
_monitorArrayPtr = Marshal.AllocHGlobal(_monitorCount * MonitorStructSize);
|
||||
|
||||
// Primary monitor must be at index 0 for Dear ImGui's viewport code.
|
||||
rects.Sort((a, b) => (b.primary ? 1 : 0) - (a.primary ? 1 : 0));
|
||||
|
||||
for (int i = 0; i < _monitorCount; i++)
|
||||
{
|
||||
var (mon, work, _) = rects[i];
|
||||
IntPtr mp = _monitorArrayPtr + i * MonitorStructSize;
|
||||
|
||||
WriteFloat(mp, 0, mon.Left);
|
||||
WriteFloat(mp, 4, mon.Top);
|
||||
WriteFloat(mp, 8, mon.Right - mon.Left);
|
||||
WriteFloat(mp, 12, mon.Bottom - mon.Top);
|
||||
WriteFloat(mp, 16, work.Left);
|
||||
WriteFloat(mp, 20, work.Top);
|
||||
WriteFloat(mp, 24, work.Right - work.Left);
|
||||
WriteFloat(mp, 28, work.Bottom - work.Top);
|
||||
WriteFloat(mp, 32, 1.0f);
|
||||
Marshal.WriteIntPtr(mp, 36, IntPtr.Zero);
|
||||
}
|
||||
|
||||
IntPtr pioNative = (IntPtr)pio.NativePtr;
|
||||
Marshal.WriteInt32(pioNative, MonitorsSize, _monitorCount);
|
||||
Marshal.WriteInt32(pioNative, MonitorsCapacity, _monitorCount);
|
||||
Marshal.WriteIntPtr(pioNative, MonitorsData, _monitorArrayPtr);
|
||||
|
||||
RynthLog.Info($"ViewportPlatform: populated {_monitorCount} monitor(s) at 0x{_monitorArrayPtr.ToInt64():X8}");
|
||||
}
|
||||
|
||||
private static bool EnsureWindowClassRegistered()
|
||||
{
|
||||
if (_classRegistered) return true;
|
||||
|
||||
_viewportWndProc = ViewportWndProc;
|
||||
_viewportWndProcPtr = Marshal.GetFunctionPointerForDelegate(_viewportWndProc);
|
||||
|
||||
WNDCLASSEXW wc = default;
|
||||
wc.cbSize = (uint)Marshal.SizeOf<WNDCLASSEXW>();
|
||||
wc.style = 0x0020 /*CS_OWNDC*/ | 0x0002 /*CS_HREDRAW*/ | 0x0001 /*CS_VREDRAW*/;
|
||||
wc.lpfnWndProc = _viewportWndProcPtr;
|
||||
wc.hInstance = _hInstance;
|
||||
wc.hCursor = LoadCursorW(IntPtr.Zero, IDC_ARROW);
|
||||
wc.hbrBackground = IntPtr.Zero;
|
||||
wc.lpszClassName = WindowClassName;
|
||||
|
||||
ushort atom = RegisterClassExW(ref wc);
|
||||
if (atom == 0)
|
||||
{
|
||||
int err = Marshal.GetLastWin32Error();
|
||||
// 1410 = ERROR_CLASS_ALREADY_EXISTS; fine if we were re-initialized.
|
||||
if (err != 1410) return false;
|
||||
}
|
||||
|
||||
_classRegistered = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ─── Callback installation ────────────────────────────────────────────
|
||||
private static void InstallCallbacks(ImGuiPlatformIOPtr pio)
|
||||
{
|
||||
IntPtr pioNative = (IntPtr)pio.NativePtr;
|
||||
|
||||
IntPtr createPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportCreate);
|
||||
IntPtr destroyPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportDestroy);
|
||||
IntPtr showPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportShow);
|
||||
IntPtr setPosPtr = RootAndGetPointer<ViewportSetVec2Delegate>(ViewportSetPos);
|
||||
IntPtr setSizePtr = RootAndGetPointer<ViewportSetVec2Delegate>(ViewportSetSize);
|
||||
IntPtr setFocusPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportSetFocus);
|
||||
IntPtr getFocusPtr = RootAndGetPointer<ViewportGetBoolDelegate>(ViewportGetFocus);
|
||||
IntPtr getMinPtr = RootAndGetPointer<ViewportGetBoolDelegate>(ViewportGetMinimized);
|
||||
IntPtr setTitlePtr = RootAndGetPointer<ViewportSetStringDelegate>(ViewportSetTitle);
|
||||
IntPtr setAlphaPtr = RootAndGetPointer<ViewportSetFloatDelegate>(ViewportSetAlpha);
|
||||
IntPtr updatePtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportUpdate);
|
||||
|
||||
// Direct writes at native cimgui.dll offsets (NOT ImGui.NET's compiled
|
||||
// layout offsets — those are off by 36 bytes). Void-return and
|
||||
// small-return callbacks match the cdecl ABI naturally.
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformCreateWindow, createPtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformDestroyWindow, destroyPtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformShowWindow, showPtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowPos, setPosPtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowSize, setSizePtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowFocus, setFocusPtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformGetWindowFocus, getFocusPtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformGetWindowMinimized, getMinPtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowTitle, setTitlePtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowAlpha, setAlphaPtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformUpdateWindow, updatePtr);
|
||||
|
||||
// GetWindowPos / GetWindowSize return ImVec2 by value (x86 cdecl struct
|
||||
// return — hidden first arg on stack). Our C# delegates take an out-ptr
|
||||
// instead; cimgui ships a wrapper helper that adapts the ABI and writes
|
||||
// the wrapper at the right offset for us. Must install via helper, not
|
||||
// Marshal.WriteIntPtr, or native crashes on the first call.
|
||||
IntPtr getPosPtr = RootAndGetPointer<ViewportGetVec2Delegate>(ViewportGetPos);
|
||||
IntPtr getSizePtr = RootAndGetPointer<ViewportGetVec2Delegate>(ViewportGetSize);
|
||||
ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowPos(pio.NativePtr, getPosPtr);
|
||||
ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowSize(pio.NativePtr, getSizePtr);
|
||||
|
||||
// Read back and log so a silent mismatch surfaces as a log line, not an IM_ASSERT.
|
||||
IntPtr verifyCreate = Marshal.ReadIntPtr(pioNative, ViewportOffsets.PlatformCreateWindow);
|
||||
IntPtr verifyGetPos = Marshal.ReadIntPtr(pioNative, ViewportOffsets.PlatformGetWindowPos);
|
||||
RynthLog.Info($"ViewportPlatform: installed handlers (CreateWindow readback=0x{verifyCreate.ToInt64():X8}, expected=0x{createPtr.ToInt64():X8}, GetWindowPos shim=0x{verifyGetPos.ToInt64():X8})");
|
||||
}
|
||||
|
||||
private static IntPtr RootAndGetPointer<TDelegate>(TDelegate del) where TDelegate : Delegate
|
||||
{
|
||||
_delegateRoots.Add(del);
|
||||
return Marshal.GetFunctionPointerForDelegate<TDelegate>(del);
|
||||
}
|
||||
|
||||
private static void WriteFloat(IntPtr basePtr, int offset, float value)
|
||||
{
|
||||
Marshal.WriteInt32(basePtr, offset, BitConverter.SingleToInt32Bits(value));
|
||||
}
|
||||
|
||||
// ─── Callback implementations ─────────────────────────────────────────
|
||||
private static void ViewportCreate(ImGuiViewport* vp)
|
||||
{
|
||||
uint flags = unchecked((uint)vp->Flags);
|
||||
bool noDecoration = (flags & (uint)ImGuiViewportFlags.NoDecoration) != 0;
|
||||
bool topMost = (flags & (uint)ImGuiViewportFlags.TopMost) != 0;
|
||||
|
||||
uint dwStyle = noDecoration
|
||||
? WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS
|
||||
: WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
|
||||
|
||||
// Always use WS_EX_TOOLWINDOW so tear-off viewports don't clutter the taskbar / Alt-Tab
|
||||
// list when users run many clients. Owned by _mainHwnd so it still closes with the game.
|
||||
uint dwExStyle = WS_EX_TOOLWINDOW;
|
||||
if (topMost) dwExStyle |= WS_EX_TOPMOST;
|
||||
dwExStyle |= WS_EX_NOACTIVATE;
|
||||
|
||||
// Compute outer window rect that yields the requested client size.
|
||||
RECT rect;
|
||||
rect.Left = (int)vp->Pos.X;
|
||||
rect.Top = (int)vp->Pos.Y;
|
||||
rect.Right = rect.Left + (int)vp->Size.X;
|
||||
rect.Bottom = rect.Top + (int)vp->Size.Y;
|
||||
AdjustWindowRectEx(ref rect, dwStyle, false, dwExStyle);
|
||||
|
||||
IntPtr hwnd = CreateWindowExW(
|
||||
dwExStyle, WindowClassName, "RynthCore Viewport", dwStyle,
|
||||
rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top,
|
||||
_mainHwnd, IntPtr.Zero, _hInstance, IntPtr.Zero);
|
||||
|
||||
if (hwnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Info($"ViewportPlatform: CreateWindowEx failed (err {Marshal.GetLastWin32Error()})");
|
||||
return;
|
||||
}
|
||||
|
||||
var state = new ViewportState { Hwnd = hwnd, HwndOwned = true, DwStyle = dwStyle, DwExStyle = dwExStyle };
|
||||
_viewports[(IntPtr)vp] = state;
|
||||
|
||||
vp->PlatformHandle = (void*)hwnd;
|
||||
vp->PlatformHandleRaw = (void*)hwnd;
|
||||
}
|
||||
|
||||
private static void ViewportDestroy(ImGuiViewport* vp)
|
||||
{
|
||||
IntPtr key = (IntPtr)vp;
|
||||
if (_viewports.TryGetValue(key, out var state))
|
||||
{
|
||||
if (state.HwndOwned && state.Hwnd != IntPtr.Zero)
|
||||
DestroyWindow(state.Hwnd);
|
||||
_viewports.Remove(key);
|
||||
}
|
||||
|
||||
vp->PlatformHandle = (void*)IntPtr.Zero;
|
||||
vp->PlatformHandleRaw = (void*)IntPtr.Zero;
|
||||
}
|
||||
|
||||
private static void ViewportShow(ImGuiViewport* vp)
|
||||
{
|
||||
if (!TryGetState(vp, out var state)) return;
|
||||
|
||||
ShowWindow(state.Hwnd, SW_SHOWNA);
|
||||
}
|
||||
|
||||
private static void ViewportSetPos(ImGuiViewport* vp, Vector2 pos)
|
||||
{
|
||||
if (!TryGetState(vp, out var state)) return;
|
||||
|
||||
RECT rect;
|
||||
rect.Left = (int)pos.X;
|
||||
rect.Top = (int)pos.Y;
|
||||
rect.Right = rect.Left;
|
||||
rect.Bottom = rect.Top;
|
||||
AdjustWindowRectEx(ref rect, state.DwStyle, false, state.DwExStyle);
|
||||
SetWindowPos(state.Hwnd, IntPtr.Zero, rect.Left, rect.Top, 0, 0,
|
||||
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
}
|
||||
|
||||
private static void ViewportSetSize(ImGuiViewport* vp, Vector2 size)
|
||||
{
|
||||
if (!TryGetState(vp, out var state)) return;
|
||||
|
||||
RECT rect;
|
||||
rect.Left = 0; rect.Top = 0;
|
||||
rect.Right = (int)size.X;
|
||||
rect.Bottom = (int)size.Y;
|
||||
AdjustWindowRectEx(ref rect, state.DwStyle, false, state.DwExStyle);
|
||||
SetWindowPos(state.Hwnd, IntPtr.Zero, 0, 0,
|
||||
rect.Right - rect.Left, rect.Bottom - rect.Top,
|
||||
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
}
|
||||
|
||||
private static void ViewportGetPos(ImGuiViewport* vp, Vector2* outPos)
|
||||
{
|
||||
*outPos = new Vector2(0, 0);
|
||||
if (!TryGetState(vp, out var state)) return;
|
||||
// Return the CLIENT-area origin in screen coords, not the outer window
|
||||
// rect. ImGui's hit-testing uses this as the viewport origin; if we
|
||||
// include the title-bar height, every click misses by that offset.
|
||||
POINT p = new POINT { X = 0, Y = 0 };
|
||||
if (!ClientToScreen(state.Hwnd, ref p)) return;
|
||||
*outPos = new Vector2(p.X, p.Y);
|
||||
}
|
||||
|
||||
private static void ViewportGetSize(ImGuiViewport* vp, Vector2* outSize)
|
||||
{
|
||||
*outSize = new Vector2(0, 0);
|
||||
if (!TryGetState(vp, out var state)) return;
|
||||
if (!GetClientRect(state.Hwnd, out RECT r)) return;
|
||||
*outSize = new Vector2(r.Right - r.Left, r.Bottom - r.Top);
|
||||
}
|
||||
|
||||
private static void ViewportSetFocus(ImGuiViewport* vp)
|
||||
{
|
||||
if (!TryGetState(vp, out var state)) return;
|
||||
SetForegroundWindow(state.Hwnd);
|
||||
}
|
||||
|
||||
private static byte ViewportGetFocus(ImGuiViewport* vp)
|
||||
{
|
||||
if (!TryGetState(vp, out var state)) return 0;
|
||||
return GetForegroundWindow() == state.Hwnd ? (byte)1 : (byte)0;
|
||||
}
|
||||
|
||||
private static byte ViewportGetMinimized(ImGuiViewport* vp)
|
||||
{
|
||||
if (!TryGetState(vp, out var state)) return 0;
|
||||
return IsIconic(state.Hwnd) ? (byte)1 : (byte)0;
|
||||
}
|
||||
|
||||
private static void ViewportSetTitle(ImGuiViewport* vp, IntPtr strPtr)
|
||||
{
|
||||
if (!TryGetState(vp, out var state)) return;
|
||||
string title = Marshal.PtrToStringUTF8(strPtr) ?? "RynthCore Viewport";
|
||||
SetWindowTextW(state.Hwnd, title);
|
||||
}
|
||||
|
||||
private static void ViewportSetAlpha(ImGuiViewport* vp, float alpha)
|
||||
{
|
||||
if (!TryGetState(vp, out var state)) return;
|
||||
IntPtr exStyle = GetWindowLongW(state.Hwnd, GWL_EXSTYLE);
|
||||
long exs = (long)exStyle;
|
||||
if (alpha < 1.0f)
|
||||
SetWindowLongW(state.Hwnd, GWL_EXSTYLE, (IntPtr)(exs | WS_EX_LAYERED));
|
||||
byte a = (byte)Math.Clamp((int)(alpha * 255f + 0.5f), 0, 255);
|
||||
SetLayeredWindowAttributes(state.Hwnd, 0, a, LWA_ALPHA);
|
||||
}
|
||||
|
||||
private static void ViewportUpdate(ImGuiViewport* vp)
|
||||
{
|
||||
// No-op on Win32 — imgui_impl_win32 handles monitor updates and other
|
||||
// housekeeping elsewhere. We refresh monitors from EngineFrameController.
|
||||
}
|
||||
|
||||
private static bool TryGetState(ImGuiViewport* vp, out ViewportState state)
|
||||
{
|
||||
return _viewports.TryGetValue((IntPtr)vp, out state!);
|
||||
}
|
||||
|
||||
// ─── WndProc for viewport HWNDs ───────────────────────────────────────
|
||||
internal static IntPtr ImGuiContext;
|
||||
|
||||
private static IntPtr ViewportWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
// If the ImGui context has been torn down (Shutdown already ran), don't
|
||||
// touch any ImGui API — the context memory is freed and any call into it
|
||||
// is a use-after-free. Just forward to the default handler.
|
||||
if (ImGuiContext == IntPtr.Zero)
|
||||
return DefWindowProcW(hWnd, msg, wParam, lParam);
|
||||
|
||||
// OS delivers messages (WM_GETICON, WM_PAINT, etc.) asynchronously outside
|
||||
// of EndScene. By then our saved context has been restored → GImGui is null,
|
||||
// and any ImGui call here AVs. Temporarily set our context for the message.
|
||||
IntPtr saved = ImGuiNET.ImGui.GetCurrentContext();
|
||||
if (saved != ImGuiContext)
|
||||
ImGuiNET.ImGui.SetCurrentContext(ImGuiContext);
|
||||
|
||||
try
|
||||
{
|
||||
ImGuiViewportPtr vp = ImGuiNET.ImGui.FindViewportByPlatformHandle(hWnd);
|
||||
if (vp.NativePtr == null)
|
||||
return DefWindowProcW(hWnd, msg, wParam, lParam);
|
||||
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
|
||||
// ── Mouse position: forward in screen coords (multi-viewport) ────
|
||||
if (msg == WM_MOUSEMOVE || msg == WM_LBUTTONDOWN || msg == WM_LBUTTONUP
|
||||
|| msg == WM_LBUTTONDBLCLK || msg == WM_RBUTTONDOWN || msg == WM_RBUTTONUP
|
||||
|| msg == WM_RBUTTONDBLCLK || msg == WM_MBUTTONDOWN || msg == WM_MBUTTONUP
|
||||
|| msg == WM_MBUTTONDBLCLK || msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP)
|
||||
{
|
||||
short cx = (short)((long)lParam & 0xFFFF);
|
||||
short cy = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
POINT pt = new POINT { X = cx, Y = cy };
|
||||
ClientToScreen(hWnd, ref pt);
|
||||
io.AddMouseSourceEvent(ImGuiMouseSource.Mouse);
|
||||
io.AddMousePosEvent(pt.X, pt.Y);
|
||||
}
|
||||
|
||||
switch (msg)
|
||||
{
|
||||
case WM_LBUTTONDOWN:
|
||||
case WM_LBUTTONDBLCLK:
|
||||
if (SetCapture(hWnd) == IntPtr.Zero) { /* ignore */ }
|
||||
io.AddMouseButtonEvent(0, true);
|
||||
return IntPtr.Zero;
|
||||
case WM_LBUTTONUP:
|
||||
io.AddMouseButtonEvent(0, false);
|
||||
ReleaseCapture();
|
||||
return IntPtr.Zero;
|
||||
|
||||
case WM_RBUTTONDOWN:
|
||||
case WM_RBUTTONDBLCLK:
|
||||
SetCapture(hWnd);
|
||||
io.AddMouseButtonEvent(1, true);
|
||||
return IntPtr.Zero;
|
||||
case WM_RBUTTONUP:
|
||||
io.AddMouseButtonEvent(1, false);
|
||||
ReleaseCapture();
|
||||
return IntPtr.Zero;
|
||||
|
||||
case WM_MBUTTONDOWN:
|
||||
case WM_MBUTTONDBLCLK:
|
||||
SetCapture(hWnd);
|
||||
io.AddMouseButtonEvent(2, true);
|
||||
return IntPtr.Zero;
|
||||
case WM_MBUTTONUP:
|
||||
io.AddMouseButtonEvent(2, false);
|
||||
ReleaseCapture();
|
||||
return IntPtr.Zero;
|
||||
|
||||
case WM_XBUTTONDOWN:
|
||||
{
|
||||
int btn = (((int)(long)wParam >> 16) & 0xFFFF) == 1 ? 3 : 4;
|
||||
SetCapture(hWnd);
|
||||
io.AddMouseButtonEvent(btn, true);
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
case WM_XBUTTONUP:
|
||||
{
|
||||
int btn = (((int)(long)wParam >> 16) & 0xFFFF) == 1 ? 3 : 4;
|
||||
io.AddMouseButtonEvent(btn, false);
|
||||
ReleaseCapture();
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
case WM_MOUSEWHEEL:
|
||||
io.AddMouseWheelEvent(0f, (short)(((long)wParam >> 16) & 0xFFFF) / 120f);
|
||||
return IntPtr.Zero;
|
||||
case WM_MOUSEHWHEEL:
|
||||
io.AddMouseWheelEvent((short)(((long)wParam >> 16) & 0xFFFF) / 120f, 0f);
|
||||
return IntPtr.Zero;
|
||||
|
||||
case WM_KEYDOWN:
|
||||
case WM_SYSKEYDOWN:
|
||||
{
|
||||
ImGuiKey key = VkToImGuiKey((int)(long)wParam);
|
||||
if (key != ImGuiKey.None) io.AddKeyEvent(key, true);
|
||||
// Let DefWindowProc run so system keys still function (Alt+F4 etc.).
|
||||
break;
|
||||
}
|
||||
case WM_KEYUP:
|
||||
case WM_SYSKEYUP:
|
||||
{
|
||||
ImGuiKey key = VkToImGuiKey((int)(long)wParam);
|
||||
if (key != ImGuiKey.None) io.AddKeyEvent(key, false);
|
||||
break;
|
||||
}
|
||||
case WM_CHAR:
|
||||
{
|
||||
uint ch = (uint)(long)wParam;
|
||||
if (ch > 0 && ch < 0x10000) io.AddInputCharacter(ch);
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
case WM_CLOSE:
|
||||
vp.PlatformRequestClose = true;
|
||||
return IntPtr.Zero;
|
||||
|
||||
case WM_MOVE:
|
||||
vp.PlatformRequestMove = true;
|
||||
break;
|
||||
|
||||
case WM_SIZE:
|
||||
vp.PlatformRequestResize = true;
|
||||
break;
|
||||
|
||||
case WM_MOUSEACTIVATE:
|
||||
{
|
||||
// If AC is the foreground app, don't steal its focus — just process the click.
|
||||
// If the user is tabbed out (some other app is foreground), allow Windows to
|
||||
// activate this viewport so the click actually brings it to the front.
|
||||
IntPtr fg = GetForegroundWindow();
|
||||
IntPtr game = Win32Backend.GameHwnd;
|
||||
if (game != IntPtr.Zero && fg == game)
|
||||
return new IntPtr(MA_NOACTIVATE);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_NCHITTEST:
|
||||
{
|
||||
uint flags = unchecked((uint)vp.Flags);
|
||||
if ((flags & (uint)ImGuiViewportFlags.NoInputs) != 0)
|
||||
return new IntPtr(-1 /*HTTRANSPARENT*/);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"ViewportPlatform.WndProc: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (ImGuiContext != IntPtr.Zero && saved != ImGuiContext)
|
||||
ImGuiNET.ImGui.SetCurrentContext(saved);
|
||||
}
|
||||
|
||||
return DefWindowProcW(hWnd, msg, wParam, lParam);
|
||||
}
|
||||
|
||||
private static ImGuiKey VkToImGuiKey(int vk)
|
||||
{
|
||||
return vk switch
|
||||
{
|
||||
0x09 => ImGuiKey.Tab,
|
||||
0x25 => ImGuiKey.LeftArrow,
|
||||
0x27 => ImGuiKey.RightArrow,
|
||||
0x26 => ImGuiKey.UpArrow,
|
||||
0x28 => ImGuiKey.DownArrow,
|
||||
0x21 => ImGuiKey.PageUp,
|
||||
0x22 => ImGuiKey.PageDown,
|
||||
0x24 => ImGuiKey.Home,
|
||||
0x23 => ImGuiKey.End,
|
||||
0x2D => ImGuiKey.Insert,
|
||||
0x2E => ImGuiKey.Delete,
|
||||
0x08 => ImGuiKey.Backspace,
|
||||
0x20 => ImGuiKey.Space,
|
||||
0x0D => ImGuiKey.Enter,
|
||||
0x1B => ImGuiKey.Escape,
|
||||
0xBE => ImGuiKey.Period,
|
||||
0xBC => ImGuiKey.Comma,
|
||||
0xBD => ImGuiKey.Minus,
|
||||
0xBB => ImGuiKey.Equal,
|
||||
0xBA => ImGuiKey.Semicolon,
|
||||
0xBF => ImGuiKey.Slash,
|
||||
0xC0 => ImGuiKey.GraveAccent,
|
||||
0xDB => ImGuiKey.LeftBracket,
|
||||
0xDC => ImGuiKey.Backslash,
|
||||
0xDD => ImGuiKey.RightBracket,
|
||||
0xDE => ImGuiKey.Apostrophe,
|
||||
>= 0x30 and <= 0x39 => ImGuiKey._0 + (vk - 0x30),
|
||||
>= 0x41 and <= 0x5A => ImGuiKey.A + (vk - 0x41),
|
||||
>= 0x60 and <= 0x69 => ImGuiKey.Keypad0 + (vk - 0x60),
|
||||
>= 0x70 and <= 0x7B => ImGuiKey.F1 + (vk - 0x70),
|
||||
0x10 => ImGuiKey.LeftShift,
|
||||
0x11 => ImGuiKey.LeftCtrl,
|
||||
0x12 => ImGuiKey.LeftAlt,
|
||||
_ => ImGuiKey.None,
|
||||
};
|
||||
}
|
||||
}
|
||||
200
src/RynthCore.Engine/ImGui/ViewportProbe.cs
Normal file
200
src/RynthCore.Engine/ImGui/ViewportProbe.cs
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — ImGui/ViewportProbe.cs
|
||||
// One-shot diagnostic run at startup. Determines the byte offsets of each
|
||||
// ImGuiPlatformIO callback field in the running cimgui.dll, so that we can
|
||||
// install Win32/DX9 platform callbacks by writing IntPtrs directly into
|
||||
// the native struct (ImGui.NET exposes callback fields as get-only).
|
||||
//
|
||||
// Remove/gate this once offsets are documented and wired into a static table.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using ImGuiNET;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static class ViewportProbe
|
||||
{
|
||||
// Every Platform_* and Renderer_* callback field ImGui.NET exposes.
|
||||
// Probing strategy: write a unique sentinel at each 4-byte slot, read
|
||||
// every getter, record which getter sees the sentinel, restore the slot.
|
||||
private static readonly string[] FieldsToProbe =
|
||||
{
|
||||
"Platform_CreateWindow",
|
||||
"Platform_DestroyWindow",
|
||||
"Platform_ShowWindow",
|
||||
"Platform_SetWindowPos",
|
||||
"Platform_GetWindowPos",
|
||||
"Platform_SetWindowSize",
|
||||
"Platform_GetWindowSize",
|
||||
"Platform_SetWindowFocus",
|
||||
"Platform_GetWindowFocus",
|
||||
"Platform_GetWindowMinimized",
|
||||
"Platform_SetWindowTitle",
|
||||
"Platform_SetWindowAlpha",
|
||||
"Platform_UpdateWindow",
|
||||
"Platform_RenderWindow",
|
||||
"Platform_SwapBuffers",
|
||||
"Platform_GetWindowDpiScale",
|
||||
"Platform_OnChangedViewport",
|
||||
"Platform_GetWindowWorkAreaInsets",
|
||||
"Platform_CreateVkSurface",
|
||||
"Renderer_CreateWindow",
|
||||
"Renderer_DestroyWindow",
|
||||
"Renderer_SetWindowSize",
|
||||
"Renderer_RenderWindow",
|
||||
"Renderer_SwapBuffers",
|
||||
};
|
||||
|
||||
// ImGuiViewport fields worth locating so we know where ImGui.NET reads from
|
||||
// vs the authoritative bytes. These are read-back tests — no writes.
|
||||
private static readonly string[] ViewportFieldsToLog =
|
||||
{
|
||||
"ID",
|
||||
"Flags",
|
||||
"Pos",
|
||||
"Size",
|
||||
"WorkPos",
|
||||
"WorkSize",
|
||||
"DpiScale",
|
||||
"ParentViewportId",
|
||||
"DrawData",
|
||||
"RendererUserData",
|
||||
"PlatformUserData",
|
||||
"PlatformHandle",
|
||||
"PlatformHandleRaw",
|
||||
"PlatformWindowCreated",
|
||||
"PlatformRequestMove",
|
||||
"PlatformRequestResize",
|
||||
"PlatformRequestClose",
|
||||
};
|
||||
|
||||
private const int ScanBytes = 768;
|
||||
|
||||
public static void Run()
|
||||
{
|
||||
try
|
||||
{
|
||||
RynthLog.Info("ViewportProbe: ---- begin ----");
|
||||
RunPlatformIOProbe();
|
||||
RunMainViewportDump();
|
||||
RynthLog.Info("ViewportProbe: ---- end ----");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"ViewportProbe: FAILED {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static unsafe void RunPlatformIOProbe()
|
||||
{
|
||||
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
|
||||
IntPtr pioNative = (IntPtr)pio.NativePtr;
|
||||
RynthLog.Info($"ViewportProbe: PlatformIO native = 0x{pioNative.ToInt64():X8}");
|
||||
|
||||
// Log what each getter returns BEFORE probing, so we can see the stock zero state.
|
||||
var propertyCache = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
|
||||
Type ptrType = typeof(ImGuiPlatformIOPtr);
|
||||
foreach (string name in FieldsToProbe)
|
||||
{
|
||||
PropertyInfo? prop = ptrType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
|
||||
bool intptrLike = prop != null && (
|
||||
prop.PropertyType == typeof(IntPtr) ||
|
||||
(prop.PropertyType.IsByRef && prop.PropertyType.GetElementType() == typeof(IntPtr)));
|
||||
if (intptrLike)
|
||||
{
|
||||
propertyCache[name] = prop!;
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Info($"ViewportProbe: {name}: NOT FOUND on ImGuiPlatformIOPtr (type={prop?.PropertyType.Name ?? "null"})");
|
||||
}
|
||||
}
|
||||
|
||||
var discovered = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
|
||||
for (int off = 0; off < ScanBytes; off += 4)
|
||||
{
|
||||
IntPtr orig = Marshal.ReadIntPtr(pioNative, off);
|
||||
IntPtr sentinel = new IntPtr(unchecked((int)0xAB000000) | off);
|
||||
Marshal.WriteIntPtr(pioNative, off, sentinel);
|
||||
|
||||
foreach (var kv in propertyCache)
|
||||
{
|
||||
IntPtr read;
|
||||
try
|
||||
{
|
||||
read = (IntPtr)kv.Value.GetValue(pio)!;
|
||||
}
|
||||
catch
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (read == sentinel && !discovered.ContainsKey(kv.Key))
|
||||
{
|
||||
discovered[kv.Key] = off;
|
||||
}
|
||||
}
|
||||
|
||||
Marshal.WriteIntPtr(pioNative, off, orig);
|
||||
}
|
||||
|
||||
// Emit in ascending offset order so the mapping is obvious in the log.
|
||||
var sorted = new List<KeyValuePair<string, int>>(discovered);
|
||||
sorted.Sort((a, b) => a.Value.CompareTo(b.Value));
|
||||
RynthLog.Info($"ViewportProbe: discovered {sorted.Count}/{propertyCache.Count} offsets:");
|
||||
foreach (var kv in sorted)
|
||||
RynthLog.Info($"ViewportProbe: +{kv.Value,4} {kv.Key}");
|
||||
|
||||
foreach (string name in FieldsToProbe)
|
||||
{
|
||||
if (propertyCache.ContainsKey(name) && !discovered.ContainsKey(name))
|
||||
RynthLog.Info($"ViewportProbe: MISSING {name} (getter exists but sentinel never matched)");
|
||||
}
|
||||
|
||||
// Hex dump of the first chunk so we can visually scan for anomalies.
|
||||
DumpRange(pioNative, 0, 256, "PlatformIO");
|
||||
}
|
||||
|
||||
private static unsafe void RunMainViewportDump()
|
||||
{
|
||||
ImGuiViewportPtr main = ImGuiNET.ImGui.GetMainViewport();
|
||||
IntPtr vp = (IntPtr)main.NativePtr;
|
||||
RynthLog.Info($"ViewportProbe: MainViewport native = 0x{vp.ToInt64():X8}");
|
||||
|
||||
Type vptrType = typeof(ImGuiViewportPtr);
|
||||
foreach (string name in ViewportFieldsToLog)
|
||||
{
|
||||
PropertyInfo? prop = vptrType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
|
||||
if (prop == null)
|
||||
{
|
||||
RynthLog.Info($"ViewportProbe: MainViewport.{name}: (no such property)");
|
||||
continue;
|
||||
}
|
||||
|
||||
object? val;
|
||||
try { val = prop.GetValue(main); }
|
||||
catch (Exception ex) { val = $"<throw {ex.GetType().Name}>"; continue; }
|
||||
|
||||
RynthLog.Info($"ViewportProbe: MainViewport.{name} ({prop.PropertyType.Name}) = {val}");
|
||||
}
|
||||
|
||||
DumpRange(vp, 0, 160, "MainViewport");
|
||||
}
|
||||
|
||||
private static void DumpRange(IntPtr basePtr, int startOffset, int length, string label)
|
||||
{
|
||||
for (int off = startOffset; off < startOffset + length; off += 16)
|
||||
{
|
||||
uint w0 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 0));
|
||||
uint w1 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 4));
|
||||
uint w2 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 8));
|
||||
uint w3 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 12));
|
||||
RynthLog.Info($"ViewportProbe: {label} +{off,4} {w0:X8} {w1:X8} {w2:X8} {w3:X8}");
|
||||
}
|
||||
}
|
||||
}
|
||||
367
src/RynthCore.Engine/ImGui/ViewportRendererBackend.cs
Normal file
367
src/RynthCore.Engine/ImGui/ViewportRendererBackend.cs
Normal file
|
|
@ -0,0 +1,367 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — ImGui/ViewportRendererBackend.cs
|
||||
// Per-viewport D3D9 renderer backend for ImGui multi-viewport.
|
||||
// Installs Renderer_* callbacks on ImGuiPlatformIO: for each viewport we
|
||||
// create an additional swap chain on the game's device, render the viewport's
|
||||
// ImDrawData into that swap chain's back buffer, and Present it so the
|
||||
// viewport's OS window displays the ImGui content.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.D3D9;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static unsafe class ViewportRendererBackend
|
||||
{
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────
|
||||
private const uint D3DFMT_UNKNOWN = 0;
|
||||
private const uint D3DFMT_A8R8G8B8 = 21;
|
||||
private const uint D3DFMT_X8R8G8B8 = 22;
|
||||
private const uint D3DSWAPEFFECT_DISCARD = 1;
|
||||
private const uint D3DBACKBUFFER_TYPE_MONO = 0;
|
||||
private const uint D3DCLEAR_TARGET = 0x00000001;
|
||||
private const uint D3DPRESENT_INTERVAL_IMMEDIATE = 0x80000000;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DPRESENT_PARAMETERS
|
||||
{
|
||||
public uint BackBufferWidth;
|
||||
public uint BackBufferHeight;
|
||||
public uint BackBufferFormat;
|
||||
public uint BackBufferCount;
|
||||
public uint MultiSampleType;
|
||||
public uint MultiSampleQuality;
|
||||
public uint SwapEffect;
|
||||
public IntPtr hDeviceWindow;
|
||||
public int Windowed; // BOOL
|
||||
public int EnableAutoDepthStencil; // BOOL
|
||||
public uint AutoDepthStencilFormat;
|
||||
public uint Flags;
|
||||
public uint FullScreen_RefreshRateInHz;
|
||||
public uint PresentationInterval;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct RECT { public int L, T, R, B; }
|
||||
|
||||
// ─── Device method delegates ──────────────────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateAdditionalSwapChainD(IntPtr pDevice, D3DPRESENT_PARAMETERS* pp, out IntPtr ppSwapChain);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetRenderTargetD(IntPtr pDevice, uint rtIndex, IntPtr pSurface);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetRenderTargetD(IntPtr pDevice, uint rtIndex, out IntPtr ppSurface);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int ClearD(IntPtr pDevice, uint count, RECT* pRects, uint flags, uint color, float z, uint stencil);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseD(IntPtr pObj);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SwapChainGetBackBufferD(IntPtr pSwapChain, uint backBufIdx, uint type, out IntPtr ppBackBuffer);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SwapChainPresentD(IntPtr pSwapChain, RECT* src, RECT* dest, IntPtr hDestWnd, IntPtr dirtyRgn, uint flags);
|
||||
|
||||
// ─── Callback delegates (must match imgui types) ──────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void ViewportCallbackD(ImGuiViewport* vp);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void ViewportSizeCallbackD(ImGuiViewport* vp, System.Numerics.Vector2 size);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void ViewportRenderD(ImGuiViewport* vp, IntPtr renderArg);
|
||||
|
||||
// ─── State ────────────────────────────────────────────────────────
|
||||
private sealed class ViewportGpuState
|
||||
{
|
||||
public IntPtr SwapChain;
|
||||
public int Width;
|
||||
public int Height;
|
||||
}
|
||||
|
||||
private static IntPtr _device;
|
||||
private static CreateAdditionalSwapChainD? _createAdditionalSwapChain;
|
||||
private static SetRenderTargetD? _setRenderTarget;
|
||||
private static GetRenderTargetD? _getRenderTarget;
|
||||
private static ClearD? _clear;
|
||||
private static readonly Dictionary<IntPtr, ViewportGpuState> _viewports = new();
|
||||
private static readonly List<Delegate> _delegateRoots = new();
|
||||
private static bool _initialized;
|
||||
|
||||
// Diagnostic one-shot logging counters — limited to a few calls so log doesn't explode.
|
||||
private static int _logCreate;
|
||||
private static int _logRender;
|
||||
private static int _logSwap;
|
||||
private const int MaxLog = 3;
|
||||
|
||||
public static bool Init(IntPtr pDevice)
|
||||
{
|
||||
if (_initialized) return true;
|
||||
if (pDevice == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Info("ViewportRenderer: Init called with null device.");
|
||||
return false;
|
||||
}
|
||||
|
||||
_device = pDevice;
|
||||
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
_createAdditionalSwapChain = GetMethod<CreateAdditionalSwapChainD>(vtable, DeviceVTableIndex.CreateAdditionalSwapChain);
|
||||
_setRenderTarget = GetMethod<SetRenderTargetD>(vtable, DeviceVTableIndex.SetRenderTarget);
|
||||
_getRenderTarget = GetMethod<GetRenderTargetD>(vtable, DeviceVTableIndex.GetRenderTarget);
|
||||
_clear = GetMethod<ClearD>(vtable, DeviceVTableIndex.Clear);
|
||||
|
||||
InstallCallbacks();
|
||||
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports;
|
||||
|
||||
_initialized = true;
|
||||
RynthLog.Info("ViewportRenderer: initialized.");
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
foreach (var kv in _viewports)
|
||||
{
|
||||
if (kv.Value.SwapChain != IntPtr.Zero)
|
||||
ReleaseCom(kv.Value.SwapChain);
|
||||
}
|
||||
_viewports.Clear();
|
||||
_delegateRoots.Clear();
|
||||
_initialized = false;
|
||||
}
|
||||
|
||||
private static void InstallCallbacks()
|
||||
{
|
||||
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
|
||||
IntPtr pioNative = (IntPtr)pio.NativePtr;
|
||||
|
||||
ViewportCallbackD createFn = RendererCreateWindow;
|
||||
ViewportCallbackD destroyFn = RendererDestroyWindow;
|
||||
ViewportSizeCallbackD setSizeFn = RendererSetWindowSize;
|
||||
ViewportRenderD renderFn = RendererRenderWindow;
|
||||
ViewportRenderD swapFn = RendererSwapBuffers;
|
||||
|
||||
_delegateRoots.Add(createFn);
|
||||
_delegateRoots.Add(destroyFn);
|
||||
_delegateRoots.Add(setSizeFn);
|
||||
_delegateRoots.Add(renderFn);
|
||||
_delegateRoots.Add(swapFn);
|
||||
|
||||
IntPtr createPtr = Marshal.GetFunctionPointerForDelegate(createFn);
|
||||
IntPtr destroyPtr = Marshal.GetFunctionPointerForDelegate(destroyFn);
|
||||
IntPtr setSizePtr = Marshal.GetFunctionPointerForDelegate(setSizeFn);
|
||||
IntPtr renderPtr = Marshal.GetFunctionPointerForDelegate(renderFn);
|
||||
IntPtr swapPtr = Marshal.GetFunctionPointerForDelegate(swapFn);
|
||||
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererCreateWindow, createPtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererDestroyWindow, destroyPtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererSetWindowSize, setSizePtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererRenderWindow, renderPtr);
|
||||
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererSwapBuffers, swapPtr);
|
||||
|
||||
IntPtr verify = Marshal.ReadIntPtr(pioNative, ViewportOffsets.RendererRenderWindow);
|
||||
RynthLog.Info($"ViewportRenderer: installed handlers (RenderWindow readback=0x{verify.ToInt64():X8}, expected=0x{renderPtr.ToInt64():X8})");
|
||||
}
|
||||
|
||||
// ─── Callback implementations ─────────────────────────────────────
|
||||
private static void RendererCreateWindow(ImGuiViewport* vp)
|
||||
{
|
||||
IntPtr key = (IntPtr)vp;
|
||||
if (_viewports.ContainsKey(key)) return;
|
||||
|
||||
var state = new ViewportGpuState();
|
||||
_viewports[key] = state;
|
||||
|
||||
int w = Math.Max(1, (int)vp->Size.X);
|
||||
int h = Math.Max(1, (int)vp->Size.Y);
|
||||
CreateSwapChainForViewport(vp, state, w, h);
|
||||
|
||||
if (_logCreate++ < MaxLog)
|
||||
{
|
||||
IntPtr hwnd = (IntPtr)vp->PlatformHandleRaw;
|
||||
if (hwnd == IntPtr.Zero) hwnd = (IntPtr)vp->PlatformHandle;
|
||||
RynthLog.Info($"ViewportRenderer: CreateWindow vp=0x{key.ToInt64():X8} hwnd=0x{hwnd.ToInt64():X8} size={w}x{h} swapChain=0x{state.SwapChain.ToInt64():X8}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void RendererDestroyWindow(ImGuiViewport* vp)
|
||||
{
|
||||
IntPtr key = (IntPtr)vp;
|
||||
if (!_viewports.TryGetValue(key, out var state)) return;
|
||||
if (state.SwapChain != IntPtr.Zero)
|
||||
{
|
||||
ReleaseCom(state.SwapChain);
|
||||
state.SwapChain = IntPtr.Zero;
|
||||
}
|
||||
_viewports.Remove(key);
|
||||
}
|
||||
|
||||
private static void RendererSetWindowSize(ImGuiViewport* vp, System.Numerics.Vector2 size)
|
||||
{
|
||||
IntPtr key = (IntPtr)vp;
|
||||
if (!_viewports.TryGetValue(key, out var state)) return;
|
||||
|
||||
int w = Math.Max(1, (int)size.X);
|
||||
int h = Math.Max(1, (int)size.Y);
|
||||
if (w == state.Width && h == state.Height) return;
|
||||
|
||||
if (state.SwapChain != IntPtr.Zero)
|
||||
{
|
||||
ReleaseCom(state.SwapChain);
|
||||
state.SwapChain = IntPtr.Zero;
|
||||
}
|
||||
CreateSwapChainForViewport(vp, state, w, h);
|
||||
}
|
||||
|
||||
private static void RendererRenderWindow(ImGuiViewport* vp, IntPtr renderArg)
|
||||
{
|
||||
IntPtr key = (IntPtr)vp;
|
||||
bool diag = _logRender < MaxLog;
|
||||
if (!_viewports.TryGetValue(key, out var state))
|
||||
{
|
||||
if (diag) { RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} NO STATE"); _logRender++; }
|
||||
return;
|
||||
}
|
||||
if (state.SwapChain == IntPtr.Zero)
|
||||
{
|
||||
if (diag) { RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} NO SWAPCHAIN"); _logRender++; }
|
||||
return;
|
||||
}
|
||||
if (_setRenderTarget == null || _getRenderTarget == null || _clear == null)
|
||||
{
|
||||
if (diag) { RynthLog.Info("ViewportRenderer: RenderWindow device methods null"); _logRender++; }
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the swap chain's back-buffer surface
|
||||
var getBB = GetMethodFromObj<SwapChainGetBackBufferD>(state.SwapChain, SwapChain9VTableIndex.GetBackBuffer);
|
||||
int hrBB = getBB(state.SwapChain, 0, D3DBACKBUFFER_TYPE_MONO, out IntPtr backBuffer);
|
||||
if (hrBB < 0 || backBuffer == IntPtr.Zero)
|
||||
{
|
||||
if (diag) { RynthLog.Info($"ViewportRenderer: GetBackBuffer failed hr=0x{hrBB:X8}"); _logRender++; }
|
||||
return;
|
||||
}
|
||||
|
||||
IntPtr oldRenderTarget = IntPtr.Zero;
|
||||
int cmdCount = 0;
|
||||
float ddW = 0, ddH = 0, ddX = 0, ddY = 0;
|
||||
try
|
||||
{
|
||||
_getRenderTarget(_device, 0, out oldRenderTarget);
|
||||
int hrSRT = _setRenderTarget(_device, 0, backBuffer);
|
||||
|
||||
// Clear unless the ImGui viewport asked us not to.
|
||||
uint flags = unchecked((uint)vp->Flags);
|
||||
if ((flags & (uint)ImGuiViewportFlags.NoRendererClear) == 0)
|
||||
{
|
||||
_clear(_device, 0, null, D3DCLEAR_TARGET, 0x00000000u, 1.0f, 0);
|
||||
}
|
||||
|
||||
// Render the viewport's own draw data through the main DX9 backend,
|
||||
// which already handles full state save/restore.
|
||||
ImDrawDataPtr draw = new ImDrawDataPtr((ImDrawData*)vp->DrawData);
|
||||
if ((IntPtr)draw.NativePtr != IntPtr.Zero)
|
||||
{
|
||||
IntPtr dd = (IntPtr)draw.NativePtr;
|
||||
cmdCount = Marshal.ReadInt32(dd, 4);
|
||||
ddX = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 20));
|
||||
ddY = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 24));
|
||||
ddW = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 28));
|
||||
ddH = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 32));
|
||||
DX9Backend.RenderDrawData(draw, _device);
|
||||
}
|
||||
|
||||
if (diag)
|
||||
{
|
||||
RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} setRT=0x{hrSRT:X8} bb=0x{backBuffer.ToInt64():X8} cmds={cmdCount} ddPos=({ddX},{ddY}) ddSize=({ddW},{ddH})");
|
||||
_logRender++;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (oldRenderTarget != IntPtr.Zero)
|
||||
{
|
||||
_setRenderTarget(_device, 0, oldRenderTarget);
|
||||
ReleaseCom(oldRenderTarget);
|
||||
}
|
||||
ReleaseCom(backBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RendererSwapBuffers(ImGuiViewport* vp, IntPtr renderArg)
|
||||
{
|
||||
IntPtr key = (IntPtr)vp;
|
||||
if (!_viewports.TryGetValue(key, out var state)) return;
|
||||
if (state.SwapChain == IntPtr.Zero) return;
|
||||
|
||||
var present = GetMethodFromObj<SwapChainPresentD>(state.SwapChain, SwapChain9VTableIndex.Present);
|
||||
int hr = present(state.SwapChain, null, null, IntPtr.Zero, IntPtr.Zero, 0);
|
||||
if (_logSwap++ < MaxLog)
|
||||
RynthLog.Info($"ViewportRenderer: SwapBuffers vp=0x{key.ToInt64():X8} Present hr=0x{hr:X8}");
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────
|
||||
private static void CreateSwapChainForViewport(ImGuiViewport* vp, ViewportGpuState state, int w, int h)
|
||||
{
|
||||
if (_createAdditionalSwapChain == null) return;
|
||||
|
||||
IntPtr hwnd = (IntPtr)vp->PlatformHandleRaw;
|
||||
if (hwnd == IntPtr.Zero) hwnd = (IntPtr)vp->PlatformHandle;
|
||||
if (hwnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Info("ViewportRenderer: viewport has no HWND — cannot create swap chain.");
|
||||
return;
|
||||
}
|
||||
|
||||
var pp = new D3DPRESENT_PARAMETERS
|
||||
{
|
||||
BackBufferWidth = (uint)w,
|
||||
BackBufferHeight = (uint)h,
|
||||
BackBufferFormat = D3DFMT_UNKNOWN, // match device default
|
||||
BackBufferCount = 1,
|
||||
SwapEffect = D3DSWAPEFFECT_DISCARD,
|
||||
hDeviceWindow = hwnd,
|
||||
Windowed = 1,
|
||||
// Don't wait for vblank — each popped viewport adds another Present
|
||||
// per frame, and stacking vsyncs cuts the effective frame rate.
|
||||
PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE,
|
||||
};
|
||||
|
||||
int hr = _createAdditionalSwapChain(_device, &pp, out IntPtr swapChain);
|
||||
if (hr < 0 || swapChain == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Info($"ViewportRenderer: CreateAdditionalSwapChain failed (hr=0x{hr:X8}) for {w}x{h} hwnd=0x{hwnd:X}");
|
||||
return;
|
||||
}
|
||||
|
||||
state.SwapChain = swapChain;
|
||||
state.Width = w;
|
||||
state.Height = h;
|
||||
}
|
||||
|
||||
private static T GetMethod<T>(IntPtr vtable, int index) where T : Delegate
|
||||
{
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
|
||||
private static T GetMethodFromObj<T>(IntPtr pObj, int index) where T : Delegate
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pObj);
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
|
||||
private static void ReleaseCom(IntPtr pObj)
|
||||
{
|
||||
if (pObj == IntPtr.Zero) return;
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pObj);
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, 2 * IntPtr.Size); // Release is index 2
|
||||
var release = Marshal.GetDelegateForFunctionPointer<ReleaseD>(addr);
|
||||
release(pObj);
|
||||
}
|
||||
}
|
||||
1587
src/RynthCore.Engine/ImGui/Win32Backend.cs
Normal file
1587
src/RynthCore.Engine/ImGui/Win32Backend.cs
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Reference in a new issue