feat: port aelrynth 2026.9.27.2 snapshot onto GitHub history

Overlay upstream/main (9b5e276) onto BlankenshipG main without rewriting
history. Keep origin-only Decal/plugin/docs trees. Re-apply aelrynth.com
and sibling-fork URL fixes that aelrynth git still has as tombohar links.

Co-authored-by: BlankenshipG <BlankenshipG@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-10-04 15:43:50 +00:00
commit 4ddbb52eb2
No known key found for this signature in database
244 changed files with 59710 additions and 3067 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,201 @@
// AC window tracker for the DComp overlay path.
//
// Subclasses AC's WndProc to catch WM_MOVE / WM_SIZE / WM_SHOWWINDOW /
// WM_ACTIVATE and fires .NET events the overlay subscribes to. Lets the
// DcompOverlayWindow keep its position locked to AC's client area without
// constant polling.
//
// IMPORTANT: AC's WndProc is ALREADY subclassed by Win32Backend.cs for the
// production overlay's input forwarding path. We can't double-subclass;
// instead we install AFTER Win32Backend if it's present, or directly if not.
// To keep this self-contained for the parallel system, we use a polling
// fallback (every 100ms) — fast enough to feel smooth during drag and avoids
// any subclass-conflict risk with production code. Phase D can replace the
// poller with proper subclass-chaining when this path becomes canonical.
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.UI.Dcomp;
internal static class AcWindowTracker
{
[DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint lpdwProcessId);
[DllImport("kernel32.dll")] private static extern uint GetCurrentProcessId();
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetWindowTextW(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetClassNameW(IntPtr hWnd, System.Text.StringBuilder lpClassName, int nMaxCount);
/// <summary>
/// When true, the tracker actively restores AC as the foreground window
/// whenever it sees foreground!=AC — needed because AC's EndSceneHook FPS
/// governor checks GetForegroundWindow(). Set false for normal user
/// foreground swaps (Alt-Tab to a different app etc.) — but for now we
/// always-on this until we're confident the bar isn't stealing focus.
/// </summary>
public static bool RestoreForegroundOnDrift { get; set; } = false;
[StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; }
public readonly record struct ClientRect(int ScreenX, int ScreenY, int Width, int Height, bool Visible, bool Foreground);
/// <summary>Fires whenever AC's client-area screen rect changes (move, resize, show/hide).</summary>
public static event Action<ClientRect>? ClientRectChanged;
private static ClientRect _last;
private static IntPtr _trackedHwnd;
private static Thread? _thread;
private static bool _started;
public static void Start()
{
if (_started) return;
_started = true;
_thread = new Thread(PollLoop)
{
Name = "RynthCore.Dcomp.AcTracker",
IsBackground = true,
};
_thread.Start();
}
private static void PollLoop()
{
// Poll cadence: 16ms = ~60 Hz. The user reported visible drag lag at
// 50ms, which makes sense — that's enough latency to feel "draggy"
// when the cursor is moving fast. 16ms matches monitor refresh and
// is virtually free CPU-wise (just a couple of GetClientRect calls).
const int PollPeriodMs = 16;
const long DiagnosticPeriodMs = 5000;
long nextDiagnosticAt = Environment.TickCount64 + DiagnosticPeriodMs;
while (true)
{
try
{
IntPtr hwnd = ImGuiBackend.Win32Backend.GameHwnd;
if (hwnd == IntPtr.Zero)
{
Thread.Sleep(PollPeriodMs);
continue;
}
if (hwnd != _trackedHwnd)
{
_trackedHwnd = hwnd;
_last = default;
RynthLog.UI($"AcWindowTracker: now tracking HWND 0x{hwnd.ToInt64():X}.");
}
if (!GetClientRect(hwnd, out RECT rc))
{
Thread.Sleep(PollPeriodMs);
continue;
}
var pt = new POINT { X = rc.Left, Y = rc.Top };
if (!ClientToScreen(hwnd, ref pt))
{
Thread.Sleep(PollPeriodMs);
continue;
}
bool visible = IsWindowVisible(hwnd) && !IsIconic(hwnd);
int width = rc.Right - rc.Left;
int height = rc.Bottom - rc.Top;
// Foreground = AC itself, OR any window in our process (overlay
// bar / panels). With WS_EX_NOACTIVATE clicking the bar shouldn't
// move foreground, but cover the case anyway via PID match.
IntPtr fg = GetForegroundWindow();
bool foreground = false;
if (fg != IntPtr.Zero)
{
if (fg == hwnd) foreground = true;
else
{
GetWindowThreadProcessId(fg, out uint fgPid);
if (fgPid == GetCurrentProcessId()) foreground = true;
}
}
var current = new ClientRect(pt.X, pt.Y, width, height, visible, foreground);
if (current != _last)
{
_last = current;
try { ClientRectChanged?.Invoke(current); }
catch (Exception ex)
{
RynthLog.UI($"AcWindowTracker: ClientRectChanged subscriber threw {ex.GetType().Name}: {ex.Message}");
}
}
// Periodic foreground diagnostic. Logs what currently holds
// foreground vs. AC's HWND, so we can pin down whether AC is
// really being seen as background by Windows (which would trip
// EndSceneHook's FPS governor) or whether the governor logic
// has a different bug. Also optionally restores AC foreground.
long now = Environment.TickCount64;
if (now >= nextDiagnosticAt)
{
nextDiagnosticAt = now + DiagnosticPeriodMs;
LogForegroundStatus(hwnd);
if (RestoreForegroundOnDrift && visible)
{
IntPtr fgNow = GetForegroundWindow();
if (fgNow != hwnd && fgNow != IntPtr.Zero)
{
SetForegroundWindow(hwnd);
}
}
}
}
catch (Exception ex)
{
RynthLog.UI($"AcWindowTracker: PollLoop swallowed {ex.GetType().Name}: {ex.Message}");
}
Thread.Sleep(PollPeriodMs);
}
}
private static void LogForegroundStatus(IntPtr acHwnd)
{
try
{
IntPtr fg = GetForegroundWindow();
string fgInfo;
if (fg == IntPtr.Zero)
{
fgInfo = "<null>";
}
else if (fg == acHwnd)
{
fgInfo = "AC";
}
else
{
var title = new System.Text.StringBuilder(128);
var cls = new System.Text.StringBuilder(128);
GetWindowTextW(fg, title, title.Capacity);
GetClassNameW(fg, cls, cls.Capacity);
fgInfo = $"0x{fg.ToInt64():X} title='{title}' cls='{cls}'";
}
RynthLog.UI($"AcWindowTracker: foreground={fgInfo}, ac=0x{acHwnd.ToInt64():X}.");
}
catch { }
}
public static ClientRect Current => _last;
}

View file

@ -0,0 +1,249 @@
// Free-floating overlay panel window for the DComp path.
// Wraps any Avalonia Control in a dark-themed shell with a draggable
// header and a resize grip. Never destroyed on close — just hidden.
using System;
using System.Runtime.InteropServices;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
namespace RynthCore.Engine.UI.Dcomp;
internal sealed class DcompFloatingPanel : Window
{
[DllImport("user32.dll")] private static extern int SetWindowLongW(IntPtr h, int n, IntPtr v);
[DllImport("user32.dll")] private static extern int GetWindowLongW(IntPtr h, int n);
[DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT pt);
[DllImport("user32.dll")] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint flags);
private const int GWL_HWNDPARENT = -8;
private const int GWL_EXSTYLE = -20;
private const int WS_EX_NOACTIVATE = 0x08000000;
private const int WS_EX_TOOLWINDOW = 0x00000080;
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_NOZORDER = 0x0004;
private const uint SWP_NOACTIVATE = 0x0010;
[StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; }
// Set by DcompOverlayWindow to restore bar z-order on any panel click.
// Tunnel-phase so it fires even when a child control handles the event.
internal static Action? OnAnyPointerPressed;
private readonly Border _contentHost;
private readonly IntPtr _hostHwnd;
private bool _contentSet;
// Custom drag state — avoids BeginMoveDrag which calls BringWindowToTop
// and pushes the bar below this panel.
private bool _dragging;
private int _dragStartCursorX, _dragStartCursorY;
private PixelPoint _dragStartWindowPos;
public DcompFloatingPanel(string title, IntPtr hostHwnd, int initialX, int initialY, int initialWidth, int initialHeight)
{
_hostHwnd = hostHwnd;
SystemDecorations = SystemDecorations.None;
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
Background = Brushes.Transparent;
ShowInTaskbar = false;
CanResize = true;
ShowActivated = false;
Width = initialWidth;
Height = initialHeight;
MinWidth = 160;
MinHeight = 80;
SizeToContent = SizeToContent.Manual;
WindowStartupLocation = WindowStartupLocation.Manual;
Position = new PixelPoint(initialX, initialY);
Title = $"RC — {title}";
_contentHost = new Border
{
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch,
};
Content = BuildShell(title);
// Tunnel phase fires before any child can handle the event, so the
// bar is always brought to front on any click inside this panel.
this.AddHandler(PointerPressedEvent,
(_, _) => OnAnyPointerPressed?.Invoke(),
Avalonia.Interactivity.RoutingStrategies.Tunnel);
Opened += OnOpened;
Closing += (_, e) => { e.Cancel = true; Hide(); };
}
// Called on the Avalonia UI thread (posted by DcompOverlayWindow.MovePanels).
internal void MoveBy(int dx, int dy)
{
Position = new PixelPoint(Position.X + dx, Position.Y + dy);
}
public void ShowWithContent(Control content, bool wrapInScroll)
{
if (!_contentSet)
{
_contentSet = true;
if (wrapInScroll)
{
content = new ScrollViewer
{
Content = content,
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch,
};
}
_contentHost.Child = content;
}
Show();
}
private void OnOpened(object? sender, EventArgs e)
{
IntPtr hwnd = TryGetHwnd();
if (hwnd == IntPtr.Zero) return;
int ex = GetWindowLongW(hwnd, GWL_EXSTYLE);
SetWindowLongW(hwnd, GWL_EXSTYLE, new IntPtr(ex | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW));
if (_hostHwnd != IntPtr.Zero)
SetWindowLongW(hwnd, GWL_HWNDPARENT, _hostHwnd);
}
private Control BuildShell(string title)
{
var closeBtn = new Button
{
Content = "✕",
FontSize = 11,
Padding = new Thickness(6, 2),
Background = Brushes.Transparent,
Foreground = new SolidColorBrush(Color.FromArgb(0xAA, 0xCC, 0xCC, 0xCC)),
VerticalAlignment = VerticalAlignment.Center,
};
closeBtn.Click += (_, _) => Hide();
var titleLabel = new TextBlock
{
Text = title,
Foreground = Brushes.LightGray,
FontSize = 11,
FontFamily = new FontFamily("Consolas, Courier New, monospace"),
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(8, 0, 0, 0),
};
var header = new DockPanel
{
Height = 22,
Background = new SolidColorBrush(Color.FromArgb(0xFF, 0x0D, 0x0D, 0x22)),
};
DockPanel.SetDock(closeBtn, Dock.Right);
header.Children.Add(closeBtn);
header.Children.Add(titleLabel);
// Custom drag: don't use BeginMoveDrag because the Windows system move
// loop calls BringWindowToTop on the dragged window, pushing the bar
// below this panel. Instead, track cursor delta via GetCursorPos and
// apply it with SWP_NOZORDER so z-order is never touched.
header.PointerPressed += (_, e) =>
{
if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
if (GetCursorPos(out POINT pt))
{
_dragging = true;
_dragStartCursorX = pt.X;
_dragStartCursorY = pt.Y;
_dragStartWindowPos = Position;
e.Pointer.Capture(header);
}
e.Handled = true;
};
header.PointerMoved += (_, e) =>
{
if (!_dragging) return;
if (!GetCursorPos(out POINT pt)) return;
int dx = pt.X - _dragStartCursorX;
int dy = pt.Y - _dragStartCursorY;
IntPtr hwnd = TryGetHwnd();
if (hwnd != IntPtr.Zero)
{
// Move via Win32 with SWP_NOZORDER — no z-order change.
SetWindowPos(hwnd, IntPtr.Zero,
_dragStartWindowPos.X + dx, _dragStartWindowPos.Y + dy,
0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
};
header.PointerReleased += (_, e) =>
{
if (!_dragging) return;
_dragging = false;
e.Pointer.Capture(null);
// Sync Avalonia's Position property with the Win32 position so
// subsequent Position reads are correct (e.g. MoveBy).
if (GetCursorPos(out POINT pt))
{
int dx = pt.X - _dragStartCursorX;
int dy = pt.Y - _dragStartCursorY;
Position = new PixelPoint(_dragStartWindowPos.X + dx, _dragStartWindowPos.Y + dy);
}
};
header.PointerCaptureLost += (_, _) => _dragging = false;
var grip = new Border
{
Width = 14,
Height = 14,
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Bottom,
Background = Brushes.Transparent,
Child = new TextBlock
{
Text = "⊿",
FontSize = 9,
Foreground = new SolidColorBrush(Color.FromArgb(0x60, 0xAA, 0xAA, 0xAA)),
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Bottom,
},
};
grip.PointerPressed += (_, e) =>
{
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
BeginResizeDrag(WindowEdge.SouthEast, e);
};
var dock = new DockPanel { LastChildFill = true };
DockPanel.SetDock(header, Dock.Top);
DockPanel.SetDock(grip, Dock.Bottom);
dock.Children.Add(header);
dock.Children.Add(grip);
dock.Children.Add(_contentHost);
return new Border
{
Background = new SolidColorBrush(Color.FromArgb(0xEC, 0x07, 0x07, 0x12)),
BorderBrush = new SolidColorBrush(Color.FromArgb(0xFF, 0x35, 0x65, 0xBB)),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(4),
ClipToBounds = true,
Child = dock,
};
}
private IntPtr TryGetHwnd()
{
try { return TryGetPlatformHandle()?.Handle ?? IntPtr.Zero; }
catch { return IntPtr.Zero; }
}
}

View file

@ -0,0 +1,38 @@
// Minimal Avalonia App for the DComp test harness. Single window, no theme
// content beyond what's needed for transparency to render correctly.
using System;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml.Styling;
using Avalonia.Themes.Simple;
namespace RynthCore.Engine.UI.Dcomp;
internal sealed class DcompOverlayApp : Application
{
public override void Initialize()
{
// Use Avalonia.Themes.Simple — already trim-rooted in the engine csproj
// (same as the production overlay path). Don't pull Themes.Fluent which
// would add another ~MB of resources we don't need for the test panel.
Styles.Add(new SimpleTheme());
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var window = new DcompOverlayWindow();
desktop.MainWindow = window;
window.Show();
// Once the HWND exists, parent it to AC's HWND for owner Z-order.
// This must happen after Show() because Avalonia creates the native
// HWND lazily on first show.
window.AttachToGameWindow();
}
base.OnFrameworkInitializationCompleted();
}
}

View file

@ -0,0 +1,181 @@
// Entry point for the DComp parallel overlay system. Activated by:
// 1. Setting "EnableDcompOverlay": true in %APPDATA%\RynthCore\engine.json
// 2. OR setting env var RYNTHCORE_DCOMP_OVERLAY=1 in the launcher's env
// Either trips the gate; engine.json is the recommended path because it
// doesn't depend on env-var propagation through the injector chain.
//
// Production AvaloniaOverlay.Start() is skipped when active (see EntryPoint.cs).
//
// Spawns a dedicated STA thread, brings up Avalonia configured for
// CompositionMode = [WinUIComposition, LowLatencyDxgiSwapChain, RedirectionSurface]
// and default rendering (Avalonia's own ANGLE — no custom Skia bridge, no
// software path). Creates the test window. Spawns a GameHwnd poller so the
// overlay can attach to AC even when ImGui and the production AvaloniaOverlay
// are both skipped.
using System;
using System.IO;
using System.Text.Json;
using System.Threading;
using Avalonia;
namespace RynthCore.Engine.UI.Dcomp;
internal static class DcompOverlayBootstrap
{
private const string EnvVarName = "RYNTHCORE_DCOMP_OVERLAY";
private const string EngineJsonField = "EnableDcompOverlay";
private static Thread? _thread;
private static bool _started;
public static bool IsEnabled
{
get
{
// Env var path — keeps a fast escape hatch for power users.
if (string.Equals(Environment.GetEnvironmentVariable(EnvVarName), "1", StringComparison.Ordinal))
return true;
// engine.json path — recommended. Survives env-var-propagation
// through the launcher → injector → acclient.exe chain.
try
{
string path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore", "engine.json");
if (!File.Exists(path)) return false;
using var doc = JsonDocument.Parse(File.ReadAllText(path));
if (doc.RootElement.TryGetProperty(EngineJsonField, out var el) &&
el.ValueKind == JsonValueKind.True)
return true;
}
catch
{
// Best-effort; default to false on parse error.
}
return false;
}
}
public static void Start()
{
if (_started) return;
_started = true;
RynthLog.UI("DcompOverlay: starting — IsEnabled=true (env=" +
(Environment.GetEnvironmentVariable(EnvVarName) ?? "<unset>") + ").");
// Spawn the GameHwnd poller before the Avalonia thread so the window
// can attach as soon as it's shown. Production AvaloniaOverlay's poller
// doesn't run in this path (we skipped Start()), and ImGui's path may
// also be skipped. Pattern mirrors AvaloniaOverlay.Start lines 410-440.
new Thread(GameHwndPollerLoop)
{
Name = "RynthCore.Dcomp.GameHwndPoller",
IsBackground = true,
}.Start();
// Spawn the AC client-rect tracker. It fires ClientRectChanged whenever
// AC moves, resizes, hides, or shows. The overlay window subscribes
// to keep its position+size locked to AC's client area.
AcWindowTracker.Start();
_thread = new Thread(ThreadMain)
{
Name = "RynthCore.Avalonia.Dcomp",
IsBackground = true,
};
_thread.SetApartmentState(ApartmentState.STA);
_thread.Start();
}
private static void GameHwndPollerLoop()
{
// Polls every 100ms for up to 60s. Once AC's window is found, populates
// ImGuiBackend.Win32Backend.GameHwnd which DcompOverlayWindow reads.
long deadline = Environment.TickCount64 + 60_000;
while (Environment.TickCount64 < deadline)
{
try
{
if (ImGuiBackend.Win32Backend.GameHwnd != IntPtr.Zero)
{
IntPtr existingHwnd = ImGuiBackend.Win32Backend.GameHwnd;
RynthLog.UI($"DcompOverlay: GameHwnd already populated externally = 0x{existingHwnd.ToInt64():X}.");
if (ImGuiBackend.Win32Backend.Init(existingHwnd))
RynthLog.UI("DcompOverlay: WndProc subclassed (externally-set HWND).");
else
RynthLog.UI("DcompOverlay: WndProc subclass FAILED (externally-set HWND).");
return;
}
IntPtr hwnd = ImGuiBackend.EngineFrameController.FindGameWindow();
if (hwnd != IntPtr.Zero)
{
ImGuiBackend.Win32Backend.SetGameHwndExternal(hwnd);
EntryPoint.GameHwnd = hwnd;
// Subclass AC's WndProc so Win32Backend.WndProcHook intercepts
// WM_ACTIVATE(WA_INACTIVE) when our DComp overlay takes focus.
// Without this the subclass is never installed in the DComp path
// (EngineFrameController.Init, which normally calls Win32Backend.Init,
// is skipped when EnableImGuiBackend=false), so AC receives
// WA_INACTIVE on every click in the panel and throttles to ~8fps.
if (ImGuiBackend.Win32Backend.Init(hwnd))
RynthLog.UI("DcompOverlay: WndProc subclassed for WM_ACTIVATE interception.");
else
RynthLog.UI("DcompOverlay: WndProc subclass FAILED — AC may throttle on overlay interaction.");
RynthLog.UI($"DcompOverlay: GameHwnd populated via EnumWindows = 0x{hwnd.ToInt64():X}.");
return;
}
}
catch (Exception ex)
{
RynthLog.UI($"DcompOverlay: GameHwnd poller swallowed {ex.GetType().Name}: {ex.Message}");
}
Thread.Sleep(100);
}
RynthLog.UI("DcompOverlay: GameHwnd poller timed out without finding AC's window.");
}
private static void ThreadMain()
{
try
{
// Software rendering + RedirectionSurface: same pipeline as the
// production overlay. WinUIComposition and LowLatencyDxgiSwapChain
// both use DirectComposition and contend with AC's D3D9 Present on
// DWM's VSync budget — the result is AC dropping to ~8fps whenever
// Avalonia's DComp visual tree is dirty (any interaction). The unique
// value of this path (separate per-client HWND, multi-client
// visibility when cascaded) doesn't depend on GPU compositing.
// RedirectionSurface is also the only mode that works reliably in
// RDP sessions, where WinUIComposition support is limited.
var platformOptions = new Avalonia.Win32PlatformOptions
{
CompositionMode = new[]
{
Avalonia.Win32CompositionMode.RedirectionSurface,
},
RenderingMode = new[]
{
Avalonia.Win32RenderingMode.Software,
},
ShouldRenderOnUIThread = true,
};
AppBuilder.Configure<DcompOverlayApp>()
.UsePlatformDetect()
.With(platformOptions)
.StartWithClassicDesktopLifetime(Array.Empty<string>());
}
catch (Exception ex)
{
RynthLog.UI($"DcompOverlay: ThreadMain crashed — {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
}
}

View file

@ -0,0 +1,480 @@
// DComp overlay — bar + free-floating panel windows.
//
// Bar: ⠿ RC | AI | Status | Log | Radar | RL
// Each panel is an independent DcompFloatingPanel (movable + resizable).
// RynthAi footer buttons (Settings, Items, Monsters, Nav, Meta) call
// AvaloniaOverlay.ActivateBarButton() which is redirected here via
// AvaloniaOverlay.DcompActivateBarButton.
// Login gate — bar stays hidden until LoginLifecycleHooks.LoginComplete.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.ImGuiBackend;
using RynthCore.Engine.UI.Panels;
namespace RynthCore.Engine.UI.Dcomp;
internal sealed class DcompOverlayWindow : Window
{
[DllImport("user32.dll", SetLastError = true)]
private static extern int SetWindowLongW(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLongW(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
int x, int y, int cx, int cy, uint flags);
[DllImport("user32.dll")]
private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);
[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 GetCursorPos(out POINT pt);
[StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; }
// Custom bar-drag state (avoids BeginMoveDrag → Windows modal move loop →
// BringWindowToTop which pushes the bar below panels).
private bool _barDragging;
private int _barDragStartCursorX, _barDragStartCursorY;
private PixelPoint _barDragStartWindowPos;
private const int GWL_HWNDPARENT = -8;
private const int GWL_EXSTYLE = -20;
private const int WS_EX_NOACTIVATE = 0x08000000;
private const int WS_EX_TOOLWINDOW = 0x00000080;
private const uint SWP_NOACTIVATE = 0x0010;
private const uint SWP_NOZORDER = 0x0004;
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_NOMOVE = 0x0002;
// HWND_TOP = IntPtr.Zero: puts window above all non-topmost siblings.
private IntPtr _hostHwnd;
private volatile bool _attached;
private volatile bool _loginComplete;
private IntPtr _cachedOurHwnd;
// Bar offset from AC client top-left. Updated on user drag; preserved when AC moves.
private int _barOffsetX = 8;
private int _barOffsetY = 8;
// Volatile: written on tracker thread, read on UI thread in PositionChanged.
private volatile int _acScreenX;
private volatile int _acScreenY;
// ── Panel registry ────────────────────────────────────────────────────────
private readonly Dictionary<string, DcompFloatingPanel> _panels = new();
private readonly record struct PanelDef(Func<Control> Creator, bool WrapInScroll, int W, int H);
private Dictionary<string, PanelDef>? _panelDefs;
// Bar toggle buttons — keyed by panel name so TogglePanel can sync color.
private readonly Dictionary<string, Button> _barButtons = new();
public DcompOverlayWindow()
{
SystemDecorations = SystemDecorations.None;
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
Background = Brushes.Transparent;
ShowInTaskbar = false;
CanResize = false;
ShowActivated = false;
// Topmost is intentionally false: with multi-client setups, each
// process's overlay must hide when its AC isn't foreground (handled
// by foreground tracking in OnAcClientRectChanged). A topmost bar
// would show across all clients simultaneously.
Title = "RynthCore Overlay";
SizeToContent = SizeToContent.WidthAndHeight;
WindowStartupLocation = WindowStartupLocation.Manual;
Position = new PixelPoint(40, 40);
Content = BuildBar();
AcWindowTracker.ClientRectChanged += OnAcClientRectChanged;
Opened += (_, _) =>
{
IntPtr hwnd = TryGetHwnd();
if (hwnd != IntPtr.Zero)
{
int ex = GetWindowLongW(hwnd, GWL_EXSTYLE);
int next = ex | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW;
if (next != ex) SetWindowLongW(hwnd, GWL_EXSTYLE, new IntPtr(next));
}
};
Closed += (_, _) =>
{
AcWindowTracker.ClientRectChanged -= OnAcClientRectChanged;
LoginLifecycleHooks.LoginComplete -= OnLoginComplete;
AvaloniaOverlay.DcompActivateBarButton = null;
DcompFloatingPanel.OnAnyPointerPressed = null;
};
}
// ── Bar ───────────────────────────────────────────────────────────────────
private Control BuildBar()
{
var aiBtn = RegisterBarButton("AI");
var statusBtn = RegisterBarButton("Status");
var logBtn = RegisterBarButton("Log");
var radarBtn = RegisterBarButton("Radar");
var reloadBtn = MakeButton("RL");
reloadBtn.Foreground = Brushes.Khaki;
reloadBtn.Click += (_, _) => EngineLifecycle.SignalReload();
var barStack = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 4,
Margin = new Thickness(8, 4),
VerticalAlignment = VerticalAlignment.Center,
Children =
{
new TextBlock
{
Text = "⠿",
Foreground = new SolidColorBrush(Color.FromArgb(0x80, 0xAA, 0xAA, 0xAA)),
FontSize = 12,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 4, 0),
},
new TextBlock
{
Text = "RC",
Foreground = Brushes.LightGreen,
FontSize = 12,
FontWeight = FontWeight.Bold,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 8, 0),
},
aiBtn,
statusBtn,
logBtn,
radarBtn,
reloadBtn,
},
};
var barBorder = new Border
{
Background = new SolidColorBrush(Color.Parse("#E60A0A14")),
CornerRadius = new CornerRadius(4),
Child = barStack,
};
// Custom drag — avoids BeginMoveDrag which uses the Windows system move
// loop (BringWindowToTop side-effect that buries the bar under panels).
barBorder.PointerPressed += (_, e) =>
{
if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
if (!GetCursorPos(out POINT pt)) return;
_barDragging = true;
_barDragStartCursorX = pt.X;
_barDragStartCursorY = pt.Y;
_barDragStartWindowPos = Position;
e.Pointer.Capture(barBorder);
e.Handled = true;
};
barBorder.PointerMoved += (_, e) =>
{
if (!_barDragging || !GetCursorPos(out POINT pt)) return;
int dx = pt.X - _barDragStartCursorX;
int dy = pt.Y - _barDragStartCursorY;
if (_cachedOurHwnd != IntPtr.Zero)
SetWindowPos(_cachedOurHwnd, IntPtr.Zero,
_barDragStartWindowPos.X + dx, _barDragStartWindowPos.Y + dy,
0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
};
barBorder.PointerReleased += (_, e) =>
{
if (!_barDragging) return;
_barDragging = false;
e.Pointer.Capture(null);
// Sync Avalonia Position so PositionChanged-based offset update sees
// the final dragged position (button is up, guard will skip it).
if (GetCursorPos(out POINT pt))
{
int dx = pt.X - _barDragStartCursorX;
int dy = pt.Y - _barDragStartCursorY;
Position = new PixelPoint(_barDragStartWindowPos.X + dx, _barDragStartWindowPos.Y + dy);
_barOffsetX = Position.X - _acScreenX;
_barOffsetY = Position.Y - _acScreenY;
}
};
barBorder.PointerCaptureLost += (_, _) => _barDragging = false;
return barBorder;
}
private Button RegisterBarButton(string panelName)
{
var btn = MakeButton(panelName);
_barButtons[panelName] = btn;
btn.Click += (_, _) => TogglePanel(panelName);
return btn;
}
private static Button MakeButton(string label) => new Button
{
Content = label,
FontSize = 11,
Padding = new Thickness(6, 2),
Background = new SolidColorBrush(Color.FromArgb(0x50, 0x30, 0x60, 0xA0)),
Foreground = Brushes.LightGray,
VerticalAlignment = VerticalAlignment.Center,
};
// ── Panel toggle ──────────────────────────────────────────────────────────
// Called by bar buttons and by AvaloniaOverlay.DcompActivateBarButton
// (which routes RynthAiPanel's launcher button clicks here).
private void TogglePanel(string name)
{
if (_panels.TryGetValue(name, out var existing))
{
bool nowVisible = !existing.IsVisible;
if (nowVisible) { existing.Show(); BringBarToFront(); }
else existing.Hide();
UpdateBarButtonColor(name, nowVisible);
return;
}
EnsurePanelDefs();
if (!_panelDefs!.TryGetValue(name, out var def)) return;
// Stagger new panels so they don't all open at the exact same position.
int stagger = _panels.Count * 24;
var panel = new DcompFloatingPanel(
name, _hostHwnd,
_acScreenX + 60 + stagger, _acScreenY + 80 + stagger,
def.W, def.H);
_panels[name] = panel;
Control content;
try { content = def.Creator(); }
catch (Exception ex)
{
RynthLog.UI($"DcompOverlay: {name} panel Create() threw {ex.GetType().Name}: {ex.Message}");
content = new TextBlock
{
Text = $"Panel error: {ex.Message}",
Foreground = Brushes.Tomato,
FontSize = 10,
TextWrapping = TextWrapping.Wrap,
};
}
panel.ShowWithContent(content, def.WrapInScroll);
UpdateBarButtonColor(name, true);
BringBarToFront();
}
private void UpdateBarButtonColor(string name, bool open)
{
if (_barButtons.TryGetValue(name, out var btn))
btn.Foreground = open ? Brushes.LightGreen : Brushes.LightGray;
}
private void EnsurePanelDefs()
{
if (_panelDefs != null) return;
_panelDefs = new Dictionary<string, PanelDef>
{
["AI"] = new(CreateAiContent, false, 400, 520),
["Status"] = new(StatusPanel.Create, true, 360, 480),
["Log"] = new(LogPanel.Create, false, 500, 280),
["Radar"] = new(RadarPanel.Create, true, 420, 480),
["Settings"] = new(SettingsPanel.Create, false, 560, 480),
["Items"] = new(ItemsPanel.Create, true, 460, 480),
["Monsters"] = new(MonstersPanel.Create, true, 460, 480),
["Nav"] = new(NavPanel.Create, true, 420, 480),
["Meta"] = new(MetaPanel.Create, true, 460, 480),
};
}
private static Control CreateAiContent()
{
RynthAiPanel.AttachDragHandle = null;
RynthAiPanel.RequestPopOut = null;
RynthAiPanel.RequestRedock = null;
RynthAiPanel.IsFloatingNow = () => false;
return RynthAiPanel.Create();
}
// ── AC window tracking ────────────────────────────────────────────────────
private void OnAcClientRectChanged(AcWindowTracker.ClientRect rect)
{
if (!_attached || !_loginComplete) return;
int prevX = _acScreenX;
int prevY = _acScreenY;
_acScreenX = rect.ScreenX;
_acScreenY = rect.ScreenY;
int dx = rect.ScreenX - prevX;
int dy = rect.ScreenY - prevY;
int newX = rect.ScreenX + _barOffsetX;
int newY = rect.ScreenY + _barOffsetY;
// We never hide the bar based on rect.Visible — Win32's owner-window
// relationship (GWL_HWNDPARENT) already auto-minimizes / auto-restores
// owned windows when the owner does.
if (_cachedOurHwnd != IntPtr.Zero)
{
SetWindowPos(_cachedOurHwnd, IntPtr.Zero, newX, newY, 0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
// Panels move on the UI thread (Avalonia Position is UI-thread-only).
if (dx != 0 || dy != 0)
{
int capturedDx = dx, capturedDy = dy;
Dispatcher.UIThread.Post(() => MovePanels(capturedDx, capturedDy), DispatcherPriority.Send);
}
}
}
// Restores bar above all panels without making it globally topmost.
// Called from the diagnostic timer so even if a panel's drag briefly
// brings it above the bar, the bar recovers within ~500 ms.
private void BringBarToFront()
{
if (_cachedOurHwnd != IntPtr.Zero)
SetWindowPos(_cachedOurHwnd, IntPtr.Zero, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
private void MovePanels(int dx, int dy)
{
foreach (var panel in _panels.Values)
{
if (panel.IsVisible)
panel.MoveBy(dx, dy);
}
}
// ── Attach + login gate ───────────────────────────────────────────────────
private int _attachRetryCount;
public void AttachToGameWindow()
{
if (_attached) return;
IntPtr ourHwnd = TryGetHwnd();
if (ourHwnd == IntPtr.Zero)
{
if (_attachRetryCount < 3)
RynthLog.UI($"DcompOverlay: HWND not yet realized (retry {_attachRetryCount}).");
_attachRetryCount++;
DispatcherTimer.RunOnce(AttachToGameWindow, TimeSpan.FromMilliseconds(100));
return;
}
IntPtr acHwnd = Win32Backend.GameHwnd;
if (acHwnd == IntPtr.Zero)
{
if (_attachRetryCount % 30 == 0)
RynthLog.UI($"DcompOverlay: waiting for GameHwnd (retry {_attachRetryCount}).");
_attachRetryCount++;
DispatcherTimer.RunOnce(AttachToGameWindow, TimeSpan.FromMilliseconds(100));
return;
}
_hostHwnd = acHwnd;
int ex = GetWindowLongW(ourHwnd, GWL_EXSTYLE);
SetWindowLongW(ourHwnd, GWL_EXSTYLE, new IntPtr(ex | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW));
SetWindowLongW(ourHwnd, GWL_HWNDPARENT, acHwnd);
_cachedOurHwnd = ourHwnd;
_attached = true;
// Route RynthAiPanel launcher button clicks to our panel toggle.
AvaloniaOverlay.DcompActivateBarButton = name =>
Dispatcher.UIThread.Post(() => TogglePanel(name), DispatcherPriority.Input);
// Any click inside any panel restores bar z-order immediately.
DcompFloatingPanel.OnAnyPointerPressed = BringBarToFront;
RynthLog.UI($"DcompOverlay: attached to host 0x{acHwnd.ToInt64():X}, our HWND 0x{ourHwnd.ToInt64():X}.");
if (LoginLifecycleHooks.HasObservedLoginComplete)
ShowAfterLogin(ourHwnd, acHwnd);
else
{
Hide();
LoginLifecycleHooks.LoginComplete += OnLoginComplete;
RynthLog.UI("DcompOverlay: waiting for LoginComplete before showing.");
}
}
private void OnLoginComplete()
{
LoginLifecycleHooks.LoginComplete -= OnLoginComplete;
Dispatcher.UIThread.Post(() =>
{
IntPtr ourHwnd = TryGetHwnd();
if (ourHwnd != IntPtr.Zero && _hostHwnd != IntPtr.Zero)
ShowAfterLogin(ourHwnd, _hostHwnd);
});
}
private void ShowAfterLogin(IntPtr ourHwnd, IntPtr acHwnd)
{
_loginComplete = true;
// Seed AC position directly — GetClientRect is reliable regardless of
// whether AcWindowTracker has fired yet (which it may not have).
if (GetClientRect(acHwnd, out RECT rc))
{
var pt = new POINT { X = rc.Left, Y = rc.Top };
if (ClientToScreen(acHwnd, ref pt))
{
_acScreenX = pt.X;
_acScreenY = pt.Y;
}
}
if (_acScreenX == 0 && _acScreenY == 0)
{
var cur = AcWindowTracker.Current;
_acScreenX = cur.ScreenX;
_acScreenY = cur.ScreenY;
}
SetWindowPos(ourHwnd, IntPtr.Zero,
_acScreenX + _barOffsetX, _acScreenY + _barOffsetY,
0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
if (!IsVisible) Show();
if (GetForegroundWindow() != acHwnd)
{
SetForegroundWindow(acHwnd);
RynthLog.UI("DcompOverlay: returned foreground to AC after login show.");
}
RynthLog.UI("DcompOverlay: visible after LoginComplete.");
}
private IntPtr TryGetHwnd()
{
try { return TryGetPlatformHandle()?.Handle ?? IntPtr.Zero; }
catch { return IntPtr.Zero; }
}
}

View file

@ -0,0 +1,38 @@
# DComp parallel overlay system (TEST HARNESS)
Opt-in alternative to the production AvaloniaOverlay. Lives entirely in this folder; activated by env var:
```powershell
$env:RYNTHCORE_DCOMP_OVERLAY = "1"
```
When set, [EntryPoint.cs](../../EntryPoint.cs) skips `AvaloniaOverlay.Start()` and calls `DcompOverlayBootstrap.Start()` instead. **Production code paths are unaffected when the env var is unset.**
## Why this exists
Phase A of the WGL_NV_DX_interop2 spike (see `spikes/WglDxInterop/findings.md`) ruled out GPU-into-AC's-D3D9 rendering on NVIDIA. The remaining viable GPU path is "render the Avalonia overlay into its own ANGLE swap chain on a separate top-level layered window, composited by DWM over AC's window."
This folder is the side-by-side test bed for that approach. **Goal: prove the rendering, positioning, Z-order, transparency, and DWM compositing work correctly before committing to a full migration.**
## Architecture (per AC client)
```
acclient.exe (one process per client)
└─ AC's main HWND (D3D9 backbuffer, AC renders here)
└─ DcompOverlayWindow (Avalonia Window, owned-Z-order child of AC's HWND)
└─ DComp / ANGLE swap chain composited by DWM
└─ Avalonia content tree (test panel for now)
```
- `DcompOverlayBootstrap.cs` — entry point, spawns the STA thread, runs Avalonia.
- `DcompOverlayApp.cs` — Avalonia App configured with `Win32CompositionMode.LowLatencyDComp` and default rendering (no custom platform graphics, no software fallback). Avalonia uses its own ANGLE.
- `DcompOverlayWindow.cs` — borderless, transparent, no chrome. Sized and positioned to AC's client area. Set as owned by AC HWND via SetWindowLong(GWL_HWNDPARENT). Initially hosts a simple visual indicator.
- `AcWindowTracker.cs` — subclasses AC's WndProc to catch WM_MOVE/WM_SIZE/WM_SHOWWINDOW and propagate to the overlay window.
## Phases
**Phase A (this commit):** scaffold the bootstrap, get an Avalonia window appearing over AC with a test panel. Verify GPU rendering, transparency, owner-Z-order. Don't worry about input forwarding or content yet.
**Phase B:** AC HWND tracking — overlay follows AC's moves, resizes, hide/show on minimize. Verify against multi-client scenarios (cascaded windows, foreground vs background).
**Phase C (deferred):** port the actual bar + docked panels into this system, replacing the EndScene composite path.

File diff suppressed because it is too large Load diff

View file

@ -24,9 +24,18 @@ internal sealed class OverlaySkiaPlatformGraphics : IPlatformGraphicsWithFeature
internal sealed class OverlaySkiaGpuContext : ISkiaGpu
{
private static readonly IDisposable NoopLease = new NoopDisposable();
private static int _detachedTargetCount;
private readonly object _sync = new();
private OverlaySkiaRenderTarget? _renderTarget;
/// <summary>
/// How many TopLevels other than the overlay window asked for a render
/// target this session. Expected to stay 0: popups are embedded in the
/// overlay window (Win32PlatformOptions.OverlayPopups). Logged with every
/// popup open/close so a regression is visible in the per-pid log.
/// </summary>
internal static int DetachedTargetCount => Volatile.Read(ref _detachedTargetCount);
public bool IsLost => false;
public IDisposable EnsureCurrent() => NoopLease;
@ -37,11 +46,53 @@ internal sealed class OverlaySkiaGpuContext : ISkiaGpu
{
lock (_sync)
{
_renderTarget ??= new OverlaySkiaRenderTarget();
// Only the overlay window may own the render target whose frames go
// to the game. Every Avalonia TopLevel calls this - before the
// OverlayPopups fix each ToolTip/Flyout/ContextMenu/ComboBox opened
// a PopupRoot TopLevel that got this same target: its render cleared
// the shared surface and submitted a popup-only frame (every docked
// panel vanished), and closing it disposed the surface under the
// overlay window (rebuilt on its next frame). Any other TopLevel now
// gets a detached target that renders nowhere.
IntPtr hwnd = TryGetHwnd(surfaces);
IntPtr overlayHwnd = AvaloniaOverlay.AvaloniaHwnd;
bool isOverlayWindow = overlayHwnd != IntPtr.Zero && hwnd != IntPtr.Zero
? hwnd == overlayHwnd
: _renderTarget == null || _renderTarget.IsDisposed;
if (!isOverlayWindow)
{
int n = Interlocked.Increment(ref _detachedTargetCount);
RynthLog.UI($"OverlaySkiaGpuContext: TopLevel hwnd=0x{hwnd.ToInt64():X} is not the overlay window (0x{overlayHwnd.ToInt64():X}); gave it detached render target #{n} so it can't blank the docked panels.");
return new DetachedOverlayRenderTarget();
}
if (_renderTarget == null || _renderTarget.IsDisposed)
_renderTarget = new OverlaySkiaRenderTarget();
return _renderTarget;
}
}
private static IntPtr TryGetHwnd(IEnumerable<object> surfaces)
{
try
{
foreach (object surface in surfaces)
{
if (surface is IPlatformHandle handle &&
string.Equals(handle.HandleDescriptor, "HWND", StringComparison.OrdinalIgnoreCase))
{
return handle.Handle;
}
}
}
catch
{
}
return IntPtr.Zero;
}
public ISkiaSurface? TryCreateSurface(PixelSize size, ISkiaGpuRenderSession? session)
{
if (size.Width <= 0 || size.Height <= 0)
@ -70,12 +121,35 @@ internal sealed class OverlaySkiaGpuContext : ISkiaGpu
internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget
{
private readonly object _sync = new();
/// <summary>
/// Exposed so OverlaySkiaRenderSession.Dispose can hold the same lock
/// while it touches _surface (via ReadPixels). Without this, a parallel
/// BeginRenderingSession that triggers EnsureSurface size-change can
/// dispose the SKSurface that a still-running session is reading from
/// → native UAF into Skia's heap → LFH freelist corruption surfaces
/// minutes later as the AV at ntdll!RtlpHeap RVA 0x5B10C.
/// </summary>
internal object SyncRoot => _sync;
private OverlayD3D9SharedTexturePublisher? _sharedTexturePublisher;
private SKSurface? _surface;
private byte[]? _softwareBuffer;
private int _width;
private int _height;
private int _loggedSharedTextureDisabled;
private bool _disposed;
private static int _surfaceCreateCount;
/// <summary>
/// Full-size raster surfaces created this session (startup + resizes, and
/// the old popup-flash rebuilds). Popup open/close logging compares it
/// before and after each popup: anything other than +0 is the flash.
/// </summary>
internal static int SurfaceCreateCount => Volatile.Read(ref _surfaceCreateCount);
internal bool IsDisposed
{
get { lock (_sync) return _disposed; }
}
public bool IsCorrupted => false;
@ -96,10 +170,12 @@ internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget
{
lock (_sync)
{
_disposed = true;
_surface?.Dispose();
_surface = null;
_softwareBuffer = null;
_sharedTexturePublisher?.Dispose();
_sharedTexturePublisher = null;
_width = 0;
_height = 0;
}
@ -109,7 +185,10 @@ internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget
{
lock (_sync)
{
if (_softwareBuffer == null || _softwareBuffer.Length != byteCount)
// Only grow. Reallocating on every pixel-difference (Length != byteCount)
// produces ~MB-sized LOH allocations that churn the LFH and triggered
// the heap-corruption AV at ntdll!RtlpHeap RVA 0x5B10C.
if (_softwareBuffer == null || _softwareBuffer.Length < byteCount)
_softwareBuffer = new byte[byteCount];
return _softwareBuffer;
@ -162,13 +241,22 @@ internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget
if (_surface != null && width == _width && height == _height)
return;
// Why the surface is being (re)built. "recreate-after-dispose" at an
// unchanged size is the old popup-flash signature: a TopLevel disposed
// this target and the overlay window had to rebuild it.
string reason = _surface != null
? $"resize {_width}x{_height}->{width}x{height}"
: _disposed ? "recreate-after-dispose" : "initial";
_disposed = false;
_surface?.Dispose();
_width = width;
_height = height;
var info = new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul);
_surface = SKSurface.Create(info);
RynthLog.UI($"OverlaySkiaRenderTarget: Created raster render surface {_width}x{_height}.");
int total = Interlocked.Increment(ref _surfaceCreateCount);
RynthLog.UI($"OverlaySkiaRenderTarget: Created raster render surface {_width}x{_height} (reason={reason}, total={total}).");
}
}
@ -214,26 +302,82 @@ internal sealed class OverlaySkiaRenderSession : ISkiaGpuRenderSession
if (!AvaloniaOverlay.ShouldUseCustomSkiaProducer)
return;
var info = new SKImageInfo(_width, _height, SKColorType.Bgra8888, SKAlphaType.Premul);
byte[] pixels = _owner.RentSoftwareBuffer(info.BytesSize);
fixed (byte* pixelPtr = pixels)
// Hold the owner's lock for the duration of the surface read. Without
// this, a parallel BeginRenderingSession on a different thread can
// size-change → dispose the SKSurface we still hold a ref to → ReadPixels
// writes into freed Skia native memory → LFH heap corruption. lock is
// reentrant so the inner RentSoftwareBuffer / TrySubmitSharedTexture
// calls (which also take _sync) are safe.
lock (_owner.SyncRoot)
{
if (!_surface.ReadPixels(info, (IntPtr)pixelPtr, info.RowBytes, 0, 0))
{
RynthLog.UI("OverlaySkiaRenderSession: Failed to read pixels from custom render target.");
return;
}
var info = new SKImageInfo(_width, _height, SKColorType.Bgra8888, SKAlphaType.Premul);
byte[] pixels = _owner.RentSoftwareBuffer(info.BytesSize);
AvaloniaOverlay.SurfacePixelWidth = _width;
AvaloniaOverlay.SurfacePixelHeight = _height;
if (_owner.TrySubmitSharedTexture((IntPtr)pixelPtr, pixels.Length, _width, _height, info.RowBytes, out OverlaySharedTextureDescriptor sharedDescriptor))
fixed (byte* pixelPtr = pixels)
{
OverlaySurfaceBridge.SubmitSharedTexture(OverlaySurfaceKind.D3D9SharedTexture, sharedDescriptor);
}
if (!_surface.ReadPixels(info, (IntPtr)pixelPtr, info.RowBytes, 0, 0))
{
RynthLog.UI("OverlaySkiaRenderSession: Failed to read pixels from custom render target.");
return;
}
OverlaySurfaceBridge.SubmitSoftwareFrame((IntPtr)pixelPtr, pixels.Length, _width, _height);
AvaloniaOverlay.NotifyCustomFrameSubmitted(_width, _height);
AvaloniaOverlay.SurfacePixelWidth = _width;
AvaloniaOverlay.SurfacePixelHeight = _height;
if (_owner.TrySubmitSharedTexture((IntPtr)pixelPtr, pixels.Length, _width, _height, info.RowBytes, out OverlaySharedTextureDescriptor sharedDescriptor))
{
OverlaySurfaceBridge.SubmitSharedTexture(OverlaySurfaceKind.D3D9SharedTexture, sharedDescriptor);
}
OverlaySurfaceBridge.SubmitSoftwareFrame((IntPtr)pixelPtr, pixels.Length, _width, _height);
AvaloniaOverlay.NotifyCustomFrameSubmitted(_width, _height);
}
}
}
}
/// <summary>
/// Render target for any Avalonia TopLevel that is not the overlay window.
/// Avalonia needs somewhere to draw, but only the overlay window's frames may
/// reach the game: this target draws into a private 1x1 raster surface and
/// never submits, reads back or clears anything shared.
/// </summary>
internal sealed class DetachedOverlayRenderTarget : ISkiaGpuRenderTarget
{
private readonly object _sync = new();
private SKSurface? _surface;
public bool IsCorrupted => false;
public ISkiaGpuRenderSession BeginRenderingSession()
{
lock (_sync)
{
_surface ??= SKSurface.Create(new SKImageInfo(1, 1, SKColorType.Bgra8888, SKAlphaType.Premul))
?? throw new InvalidOperationException("Detached overlay render surface could not be created.");
return new Session(_surface);
}
}
public void Dispose()
{
lock (_sync)
{
_surface?.Dispose();
_surface = null;
}
}
private sealed class Session : ISkiaGpuRenderSession
{
public Session(SKSurface surface) => SkSurface = surface;
public GRContext GrContext => null!;
public double ScaleFactor => 1.0d;
public SKSurface SkSurface { get; }
public GRSurfaceOrigin SurfaceOrigin => GRSurfaceOrigin.TopLeft;
public void Dispose()
{
}
}
}

View file

@ -37,9 +37,24 @@ internal sealed class OverlaySurfaceFrame
Height = sharedTexture.Height;
}
public OverlaySurfaceKind Kind { get; }
public byte[]? SoftwarePixels { get; }
public OverlaySharedTextureDescriptor? SharedTexture { get; }
public int Width { get; }
public int Height { get; }
public OverlaySurfaceKind Kind { get; private set; }
public byte[]? SoftwarePixels { get; private set; }
public OverlaySharedTextureDescriptor? SharedTexture { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
/// <summary>
/// Reuses this instance for a new software frame. Lets the bridge avoid
/// allocating a new <see cref="OverlaySurfaceFrame"/> on every consumed
/// frame at 36-60 Hz — the small-bucket LFH churn from that allocation
/// was bisected as residual heap-corruption pressure.
/// </summary>
internal void ResetSoftware(byte[] pixels, int width, int height)
{
Kind = OverlaySurfaceKind.SoftwareBgra32;
SoftwarePixels = pixels;
SharedTexture = null;
Width = width;
Height = height;
}
}

View file

@ -0,0 +1,281 @@
// ============================================================================
// RynthCore.Engine - UI/PanelStateStore.cs
// Tiny disk-backed store for Avalonia panel positions/sizes/open-state so a
// hot reload doesn't snap every panel back to the cascade-default. Plain
// text key=value to avoid pulling System.Text.Json into the AOT trim graph
// for the sake of ~30 lines of state.
//
// File format:
// bar=<left>,<top>[,<docked|floating>,<floatingLeft>,<floatingTop>]
// panel.<title>=<open|closed>,<left>,<top>,<width>,<height>
// [,<docked|floating>,<screenLeft>,<screenTop>]
//
// The trailing three columns on each row were added when panels (and later
// the bar itself) gained the ability to detach into their own top-level
// layered windows. Files that pre-date the feature still parse — the floating
// mode just defaults to docked and the screen coords default to 0.
//
// Stored under %LocalAppData%\RynthCore\panel_state.txt — survives reloads
// and out-of-game (the Runtime dir might be wiped during deploy).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace RynthCore.Engine.UI;
internal static class PanelStateStore
{
public readonly record struct PanelEntry(
bool Open,
double Left,
double Top,
double Width,
double Height,
bool Floating = false,
double FloatingLeft = 0,
double FloatingTop = 0);
private static readonly object Sync = new();
private static readonly Dictionary<string, PanelEntry> Panels = new(StringComparer.OrdinalIgnoreCase);
private static (double Left, double Top)? _barPosition;
private static bool _barFloating;
private static (double Left, double Top)? _barFloatingPosition;
private static bool _loaded;
private static string FilePath
{
get
{
string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(root, "RynthCore", "panel_state.txt");
}
}
public static (double Left, double Top)? BarPosition
{
get { lock (Sync) { Load(); return _barPosition; } }
}
/// <summary>
/// True if the bar should restore in its own top-level floating layered
/// window (instead of inside the in-AC overlay canvas).
/// </summary>
public static bool BarFloating
{
get { lock (Sync) { Load(); return _barFloating; } }
}
/// <summary>
/// Last-known screen coords of the floating bar. Null if the bar has never
/// been popped out yet (the popout path falls back to a sensible default).
/// </summary>
public static (double Left, double Top)? BarFloatingPosition
{
get { lock (Sync) { Load(); return _barFloatingPosition; } }
}
public static bool TryGetPanel(string title, out PanelEntry entry)
{
lock (Sync)
{
Load();
return Panels.TryGetValue(title, out entry);
}
}
public static IEnumerable<KeyValuePair<string, PanelEntry>> AllOpenPanels()
{
lock (Sync)
{
Load();
foreach (var kv in Panels)
if (kv.Value.Open)
yield return kv;
}
}
public static void SetBarPosition(double left, double top)
{
lock (Sync)
{
Load();
_barPosition = (left, top);
Save();
}
}
/// <summary>
/// Persist the floating-mode flag and last-known screen coords. Called
/// from PopOutBar / RedockBar and from the FloatingPanelHost move callback
/// while the bar is floating. Leaves the docked <c>BarPosition</c>
/// untouched so a redock returns to the user's last docked location.
/// </summary>
public static void SetBarFloatingState(bool floating, double floatingLeft, double floatingTop)
{
lock (Sync)
{
Load();
_barFloating = floating;
_barFloatingPosition = (floatingLeft, floatingTop);
Save();
}
}
public static void SetPanel(string title, PanelEntry entry)
{
lock (Sync)
{
Load();
Panels[title] = entry;
Save();
}
}
public static void MarkPanelClosed(string title)
{
lock (Sync)
{
Load();
if (Panels.TryGetValue(title, out PanelEntry existing))
{
Panels[title] = existing with { Open = false };
Save();
}
}
}
private static void Load()
{
if (_loaded) return;
_loaded = true;
try
{
string path = FilePath;
if (!File.Exists(path)) return;
foreach (string raw in File.ReadAllLines(path))
{
string line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#'))
continue;
int eq = line.IndexOf('=');
if (eq <= 0) continue;
string key = line[..eq].Trim();
string value = line[(eq + 1)..].Trim();
if (string.Equals(key, "bar", StringComparison.OrdinalIgnoreCase))
{
// 2 = legacy (left, top)
// 5 = current (left, top, docked|floating, floatingLeft, floatingTop)
string[] barParts = value.Split(',');
if (barParts.Length == 2 && TryParseDoubles(value, 2, out double[] legacyVals))
{
_barPosition = (legacyVals[0], legacyVals[1]);
}
else if (barParts.Length == 5 &&
TryParseDoubles(string.Join(',', barParts, 0, 2), 2, out double[] dockedVals) &&
TryParseDoubles(string.Join(',', barParts, 3, 2), 2, out double[] floatingVals))
{
_barPosition = (dockedVals[0], dockedVals[1]);
_barFloating = string.Equals(barParts[2].Trim(), "floating", StringComparison.OrdinalIgnoreCase);
_barFloatingPosition = (floatingVals[0], floatingVals[1]);
}
}
else if (key.StartsWith("panel.", StringComparison.OrdinalIgnoreCase))
{
string title = key["panel.".Length..];
string[] parts = value.Split(',');
// 5 = legacy (open, left, top, width, height)
// 8 = current (legacy + floating-mode, screenLeft, screenTop)
if (parts.Length != 5 && parts.Length != 8) continue;
bool open = string.Equals(parts[0].Trim(), "open", StringComparison.OrdinalIgnoreCase);
if (!TryParseDoubles(string.Join(',', parts, 1, 4), 4, out double[] dims))
continue;
bool floating = false;
double floatingLeft = 0;
double floatingTop = 0;
if (parts.Length == 8)
{
floating = string.Equals(parts[5].Trim(), "floating", StringComparison.OrdinalIgnoreCase);
if (TryParseDoubles(string.Join(',', parts, 6, 2), 2, out double[] screen))
{
floatingLeft = screen[0];
floatingTop = screen[1];
}
}
Panels[title] = new PanelEntry(open, dims[0], dims[1], dims[2], dims[3], floating, floatingLeft, floatingTop);
}
}
}
catch (Exception ex)
{
try { RynthLog.UI($"PanelStateStore: load failed - {ex.Message}"); } catch { }
}
}
private static void Save()
{
try
{
string path = FilePath;
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir))
Directory.CreateDirectory(dir);
using var sw = new StreamWriter(path, append: false);
sw.WriteLine("# RynthCore Avalonia panel state — auto-generated, hand-edits OK.");
if (_barPosition is { } bar)
{
// Always emit the extended form if we have any floating state to
// remember; legacy 2-column form only when no popout has happened.
if (_barFloating || _barFloatingPosition is not null)
{
(double fl, double ft) = _barFloatingPosition ?? (0, 0);
sw.WriteLine(FormattableString.Invariant(
$"bar={bar.Left:0.##},{bar.Top:0.##},{(_barFloating ? "floating" : "docked")},{fl:0.##},{ft:0.##}"));
}
else
{
sw.WriteLine(FormattableString.Invariant($"bar={bar.Left:0.##},{bar.Top:0.##}"));
}
}
foreach (var kv in Panels)
{
PanelEntry e = kv.Value;
sw.WriteLine(FormattableString.Invariant(
$"panel.{kv.Key}={(e.Open ? "open" : "closed")},{e.Left:0.##},{e.Top:0.##},{e.Width:0.##},{e.Height:0.##},{(e.Floating ? "floating" : "docked")},{e.FloatingLeft:0.##},{e.FloatingTop:0.##}"));
}
}
catch (Exception ex)
{
try { RynthLog.UI($"PanelStateStore: save failed - {ex.Message}"); } catch { }
}
}
private static bool TryParseDoubles(string csv, int expected, out double[] values)
{
string[] parts = csv.Split(',');
if (parts.Length != expected)
{
values = Array.Empty<double>();
return false;
}
values = new double[expected];
for (int i = 0; i < expected; i++)
{
if (!double.TryParse(parts[i].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out values[i]))
return false;
}
return true;
}
}

View file

@ -0,0 +1,824 @@
// ============================================================================
// RynthCore.Engine — UI/Panels/ItemsPanel.cs
// Avalonia replica of the ImGui Items tab (LegacyWeaponsUi.cs).
//
// Three sections:
// Weapons — Name, Element picker, Delete
// Consumables — Name, Type picker, Delete
// Mana Stones — Enable tapping toggle, keep count, min mana threshold
//
// Plugin exports used:
// RynthPluginGetItemsJson → polled every 1s for external edits
// RynthPluginSetItemsJson → write-back on edit
// RynthPluginAddSelectedWeapon → add currently selected inventory item as weapon
// RynthPluginAddSelectedConsumable → add currently selected inventory item as consumable
// ============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Panels;
[JsonSerializable(typeof(ItemsPanel.Payload))]
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = true)]
internal partial class ItemsPanelJsonContext : JsonSerializerContext { }
internal static class ItemsPanel
{
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr GetItemsJsonFn();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void SetItemsJsonFn(IntPtr ansiJson);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void VoidFn();
private static GetItemsJsonFn? _getItemsJson;
private static SetItemsJsonFn? _setItemsJson;
private static VoidFn? _addSelectedWeapon;
private static VoidFn? _addSelectedConsumable;
private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33));
private static readonly IBrush ColRed = new SolidColorBrush(Color.FromRgb(0xFF, 0x55, 0x55));
private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6));
private static readonly IBrush ColTextDim = new SolidColorBrush(Color.FromRgb(0xD9, 0xE6, 0xF2));
private static readonly IBrush ColMute = new SolidColorBrush(Color.FromRgb(0x8C, 0xA6, 0xBF));
private static readonly IBrush ColShellBg = new SolidColorBrush(Color.FromRgb(0x0A, 0x0F, 0x14));
private static readonly IBrush ColPanelBg = new SolidColorBrush(Color.FromRgb(0x14, 0x1F, 0x29));
private static readonly IBrush ColRowAlt = new SolidColorBrush(Color.FromRgb(0x10, 0x18, 0x22));
private static readonly IBrush ColBtnFill = new SolidColorBrush(Color.FromRgb(0x0F, 0x1F, 0x2E));
private static readonly IBrush ColBtnBord = new SolidColorBrush(Color.FromRgb(0x26, 0x40, 0x59));
private static readonly IBrush ColHdrBg = new SolidColorBrush(Color.FromRgb(0x1A, 0x2E, 0x42));
private static readonly string[] Elements =
{ "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
private static readonly string[] ConsumableTypes =
{ "General", "Lockpick", "HealthKit", "ManaStone", "Stamina", "Pet" };
internal sealed class Payload
{
[JsonPropertyName("weapons")] public List<WeaponEntry> Weapons { get; set; } = new();
[JsonPropertyName("consumables")] public List<ConsumableEntry> Consumables { get; set; } = new();
[JsonPropertyName("enableManaTapping")] public bool EnableManaTapping { get; set; }
[JsonPropertyName("manaTapMinMana")] public int ManaTapMinMana { get; set; } = 2500;
[JsonPropertyName("manaStoneKeepCount")]public int ManaStoneKeepCount{ get; set; } = 5;
[JsonPropertyName("currentTargetName")] public string CurrentTargetName { get; set; } = string.Empty;
}
internal sealed class WeaponEntry
{
[JsonPropertyName("id")] public int Id { get; set; }
[JsonPropertyName("name")] public string Name { get; set; } = string.Empty;
[JsonPropertyName("element")] public string Element { get; set; } = "Slash";
}
internal sealed class ConsumableEntry
{
[JsonPropertyName("id")] public int Id { get; set; }
[JsonPropertyName("name")] public string Name { get; set; } = string.Empty;
[JsonPropertyName("type")] public string Type { get; set; } = "General";
}
private sealed class State
{
public Payload Data = new();
public bool Dirty;
}
public static Control Create()
{
TryBind();
var state = new State();
var root = new Border
{
Background = ColShellBg,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(4),
Padding = new Thickness(6),
};
// Root grid: content layer + picker overlay.
var rootGrid = new Grid();
root.Child = rootGrid;
var rootStack = new DockPanel { LastChildFill = true };
rootGrid.Children.Add(rootStack);
var pickerCanvas = new Canvas
{
IsHitTestVisible = false,
Background = Brushes.Transparent,
};
rootGrid.Children.Add(pickerCanvas);
Border? activePicker = null;
Button? activeAnchor = null;
void ClosePicker()
{
if (activePicker != null)
{
pickerCanvas.Children.Remove(activePicker);
activePicker = null;
}
activeAnchor = null;
pickerCanvas.IsHitTestVisible = false;
}
pickerCanvas.PointerPressed += (_, e) =>
{
if (activePicker == null || !ReferenceEquals(e.Source, pickerCanvas)) return;
e.Handled = true;
ClosePicker();
};
rootStack.PointerPressed += (_, _) => ClosePicker();
void ShowPicker(Button anchor, string[] items, int selected, Action<int> onPick)
{
if (ReferenceEquals(anchor, activeAnchor)) { ClosePicker(); return; }
ClosePicker();
activeAnchor = anchor;
var stack = new StackPanel { Spacing = 1 };
for (int i = 0; i < items.Length; i++)
{
int captured = i;
bool isSel = i == selected;
var entry = new Button
{
Content = items[i],
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Left,
Background = isSel ? ColHdrBg : ColBtnFill,
Foreground = isSel ? ColTeal : ColTextDim,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(6, 2),
FontSize = 10,
Height = 20,
};
entry.Click += (_, _) => { onPick(captured); ClosePicker(); };
stack.Children.Add(entry);
}
const double pickerWidth = 160;
Point ap = anchor.TranslatePoint(new Point(0, anchor.Bounds.Height), pickerCanvas) ?? new Point(8, 8);
double left = Math.Clamp(ap.X, 4, Math.Max(4, root.Bounds.Width - pickerWidth - 4));
double top = ap.Y;
double maxH = Math.Min(items.Length * 22 + 8, Math.Max(80, root.Bounds.Height - top - 4));
var picker = new Border
{
Width = pickerWidth,
MaxHeight = maxH,
Background = ColShellBg,
BorderBrush = ColTeal,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(4),
Padding = new Thickness(2),
Child = new ScrollViewer
{
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
Content = stack,
},
};
pickerCanvas.Children.Add(picker);
Canvas.SetLeft(picker, left);
Canvas.SetTop(picker, top);
activePicker = picker;
pickerCanvas.IsHitTestVisible = true;
}
// ── Scrollable body ──────────────────────────────────────────────────
var scroll = new ScrollViewer
{
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
Background = ColPanelBg,
};
var body = new StackPanel { Orientation = Orientation.Vertical, Spacing = 0 };
scroll.Content = body;
// ── Mana stone section at the bottom ─────────────────────────────────
var manaSection = BuildManaSectionContainer(state, () => { state.Dirty = true; PushChanges(state); });
void Refresh()
{
body.Children.Clear();
// ── Weapons ──────────────────────────────────────────────────────
body.Children.Add(BuildSectionHeader("Weapons"));
if (state.Data.Weapons.Count == 0)
{
body.Children.Add(BuildEmptyRow("No weapons configured"));
}
else
{
body.Children.Add(BuildTableHeader(new[] { "Item Name", "Element", "" }, new[] { true, false, false }, new double[] { 0, 100, 46 }));
for (int i = 0; i < state.Data.Weapons.Count; i++)
{
var w = state.Data.Weapons[i];
int wi = i;
body.Children.Add(BuildWeaponRow(w, wi % 2 == 0, ShowPicker,
onChanged: () => { state.Dirty = true; PushChanges(state); },
onDelete: () =>
{
state.Data.Weapons.RemoveAt(wi);
state.Dirty = true;
PushChanges(state);
Refresh();
}));
}
}
body.Children.Add(BuildAddButton("Add Selected Weapon", "(select a weapon in inventory first)",
() =>
{
if (_addSelectedWeapon == null) TryBind();
_addSelectedWeapon?.Invoke();
}));
body.Children.Add(BuildDivider());
// ── Consumables ──────────────────────────────────────────────────
body.Children.Add(BuildSectionHeader("Consumable Items"));
if (state.Data.Consumables.Count == 0)
{
body.Children.Add(BuildEmptyRow("No consumables configured"));
}
else
{
body.Children.Add(BuildTableHeader(new[] { "Item Name", "Type", "" }, new[] { true, false, false }, new double[] { 0, 100, 46 }));
for (int i = 0; i < state.Data.Consumables.Count; i++)
{
var c = state.Data.Consumables[i];
int ci = i;
body.Children.Add(BuildConsumableRow(c, ci % 2 == 0, ShowPicker,
onChanged: () => { state.Dirty = true; PushChanges(state); },
onDelete: () =>
{
state.Data.Consumables.RemoveAt(ci);
state.Dirty = true;
PushChanges(state);
Refresh();
}));
}
}
body.Children.Add(BuildAddButton("Add Selected Consumable", "(select an item in inventory first)",
() =>
{
if (_addSelectedConsumable == null) TryBind();
_addSelectedConsumable?.Invoke();
}));
body.Children.Add(BuildDivider());
// Mana stone section is rebuilt separately so spinners capture fresh state.
RebuildManaSection(manaSection, state, () => { state.Dirty = true; PushChanges(state); });
body.Children.Add(manaSection);
}
DockPanel.SetDock(scroll, Dock.Top);
rootStack.Children.Add(scroll);
// ── Initial load + polling ───────────────────────────────────────────
if (TryFetch(out var initial)) state.Data = initial;
Refresh();
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) };
timer.Tick += (_, _) =>
{
if (_getItemsJson == null) TryBind();
if (state.Dirty) return;
if (!TryFetch(out var fresh)) return;
bool weaponsChanged = WeaponsChanged(state.Data.Weapons, fresh.Weapons);
bool consumablesChanged = ConsumablesChanged(state.Data.Consumables, fresh.Consumables);
bool manaChanged = state.Data.EnableManaTapping != fresh.EnableManaTapping
|| state.Data.ManaTapMinMana != fresh.ManaTapMinMana
|| state.Data.ManaStoneKeepCount != fresh.ManaStoneKeepCount;
// UI deep-dive finding P0-4 (2026-07-02): state.Data = fresh used
// to run unconditionally, EVERY poll tick, even when the
// comparison above found nothing relevant different. Row edit
// handlers (the Element picker, etc.) mutate the SAME objects
// already living in state.Data.Weapons/Consumables in place —
// swapping in a brand-new (but content-equivalent) object graph
// on a "nothing changed" tick discarded that in-place edit
// anyway if it hadn't yet round-tripped through PushChanges'
// fire-and-forget Send + a later poll picking up the plugin's
// still-stale response. Only swap when something is ACTUALLY
// different — the same case that already triggers Refresh()
// (which rebuilds the rows and orphans their old closures
// regardless, so there's no additional cost to swapping there).
if (weaponsChanged || consumablesChanged || manaChanged)
{
state.Data = fresh;
Refresh();
}
};
timer.Start();
// Stop with the visual tree — a running DispatcherTimer roots the closed
// view forever (one immortal poller per open/close). RadarPanel idiom;
// must restart on attach: drag/resize fires Detached→Attached.
root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
root.DetachedFromVisualTree += (_, _) => timer.Stop();
return root;
}
// ── Section header ───────────────────────────────────────────────────────
private static Control BuildSectionHeader(string title)
{
return new Border
{
Background = ColHdrBg,
Padding = new Thickness(8, 4),
Margin = new Thickness(0, 4, 0, 0),
Child = new TextBlock
{
Text = title,
Foreground = ColAmber,
FontSize = 11,
FontWeight = Avalonia.Media.FontWeight.Bold,
},
};
}
// ── Table column header ──────────────────────────────────────────────────
private static Control BuildTableHeader(string[] labels, bool[] stretch, double[] fixedWidths)
{
var grid = new Grid { Background = ColHdrBg, Height = 22 };
var cols = new ColumnDefinitions();
for (int i = 0; i < labels.Length; i++)
cols.Add(stretch[i] ? new ColumnDefinition(1, GridUnitType.Star) : new ColumnDefinition(fixedWidths[i], GridUnitType.Pixel));
grid.ColumnDefinitions = cols;
for (int i = 0; i < labels.Length; i++)
{
var tb = new TextBlock
{
Text = labels[i],
Foreground = ColTextDim,
FontSize = 10,
FontWeight = Avalonia.Media.FontWeight.Bold,
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = string.IsNullOrEmpty(labels[i]) ? HorizontalAlignment.Center : HorizontalAlignment.Left,
Margin = new Thickness(6, 0),
};
Grid.SetColumn(tb, i);
grid.Children.Add(tb);
}
return grid;
}
// ── Empty placeholder row ────────────────────────────────────────────────
private static Control BuildEmptyRow(string msg)
{
return new Border
{
Background = ColRowAlt,
Padding = new Thickness(8, 4),
Child = new TextBlock
{
Text = msg,
Foreground = ColMute,
FontSize = 10,
FontStyle = Avalonia.Media.FontStyle.Italic,
},
};
}
// ── Divider ──────────────────────────────────────────────────────────────
private static Control BuildDivider()
{
return new Border
{
Height = 1,
Background = ColBtnBord,
Margin = new Thickness(0, 6, 0, 0),
};
}
// ── "Add Selected" button row ─────────────────────────────────────────────
private static Control BuildAddButton(string label, string hint, Action onClick)
{
var btn = new Button
{
Content = label,
Background = ColBtnFill,
Foreground = ColTeal,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(10, 4),
FontSize = 10,
Margin = new Thickness(0, 4, 0, 0),
};
btn.Click += (_, _) => onClick();
var hintTb = new TextBlock
{
Text = hint,
Foreground = ColMute,
FontSize = 9,
FontStyle = Avalonia.Media.FontStyle.Italic,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(8, 0, 0, 0),
};
var dp = new DockPanel { LastChildFill = true };
DockPanel.SetDock(btn, Dock.Left);
dp.Children.Add(btn);
dp.Children.Add(hintTb);
return new Border { Padding = new Thickness(4, 2), Child = dp };
}
// ── Weapon table row ──────────────────────────────────────────────────────
private static Control BuildWeaponRow(
WeaponEntry w, bool alt,
Action<Button, string[], int, Action<int>> showPicker,
Action onChanged, Action onDelete)
{
var grid = new Grid
{
Background = alt ? ColRowAlt : ColPanelBg,
Height = 24,
ColumnDefinitions = new ColumnDefinitions("*, 100, 46"),
};
// Name
var nameTb = new TextBlock
{
Text = w.Name,
Foreground = ColTextDim,
FontSize = 10,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(6, 0),
TextTrimming = TextTrimming.CharacterEllipsis,
};
Grid.SetColumn(nameTb, 0);
grid.Children.Add(nameTb);
// Element picker button
int elemIdx = Array.IndexOf(Elements, w.Element);
if (elemIdx < 0) elemIdx = 0;
var elemBtn = new Button
{
Content = w.Element,
Background = ColBtnFill,
Foreground = ColTextDim,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(4, 2),
FontSize = 10,
HorizontalContentAlignment = HorizontalAlignment.Center,
Margin = new Thickness(2, 2),
};
elemBtn.Click += (_, _) =>
{
showPicker(elemBtn, Elements, Array.IndexOf(Elements, w.Element), picked =>
{
w.Element = Elements[picked];
elemBtn.Content = w.Element;
onChanged();
});
};
Grid.SetColumn(elemBtn, 1);
grid.Children.Add(elemBtn);
// Delete button
var del = new Button
{
Content = "Del",
Background = ColBtnFill,
Foreground = ColRed,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(4, 2),
FontSize = 10,
Margin = new Thickness(2, 2),
};
del.Click += (_, _) => onDelete();
Grid.SetColumn(del, 2);
grid.Children.Add(del);
return grid;
}
// ── Consumable table row ──────────────────────────────────────────────────
private static Control BuildConsumableRow(
ConsumableEntry c, bool alt,
Action<Button, string[], int, Action<int>> showPicker,
Action onChanged, Action onDelete)
{
var grid = new Grid
{
Background = alt ? ColRowAlt : ColPanelBg,
Height = 24,
ColumnDefinitions = new ColumnDefinitions("*, 100, 46"),
};
var nameTb = new TextBlock
{
Text = c.Name,
Foreground = ColTextDim,
FontSize = 10,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(6, 0),
TextTrimming = TextTrimming.CharacterEllipsis,
};
Grid.SetColumn(nameTb, 0);
grid.Children.Add(nameTb);
int typeIdx = Array.IndexOf(ConsumableTypes, c.Type);
if (typeIdx < 0) typeIdx = 0;
var typeBtn = new Button
{
Content = c.Type,
Background = ColBtnFill,
Foreground = ColTextDim,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(4, 2),
FontSize = 10,
HorizontalContentAlignment = HorizontalAlignment.Center,
Margin = new Thickness(2, 2),
};
typeBtn.Click += (_, _) =>
{
showPicker(typeBtn, ConsumableTypes, Array.IndexOf(ConsumableTypes, c.Type), picked =>
{
c.Type = ConsumableTypes[picked];
typeBtn.Content = c.Type;
onChanged();
});
};
Grid.SetColumn(typeBtn, 1);
grid.Children.Add(typeBtn);
var del = new Button
{
Content = "Del",
Background = ColBtnFill,
Foreground = ColRed,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(4, 2),
FontSize = 10,
Margin = new Thickness(2, 2),
};
del.Click += (_, _) => onDelete();
Grid.SetColumn(del, 2);
grid.Children.Add(del);
return grid;
}
// ── Mana stone section ────────────────────────────────────────────────────
private static StackPanel BuildManaSectionContainer(State state, Action onChanged)
{
var sp = new StackPanel { Orientation = Orientation.Vertical };
RebuildManaSection(sp, state, onChanged);
return sp;
}
private static void RebuildManaSection(StackPanel sp, State state, Action onChanged)
{
sp.Children.Clear();
sp.Children.Add(BuildSectionHeader("Mana Stone Tapping"));
// Row 1: Enable toggle + Keep count
var row1 = new WrapPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(4, 4, 4, 2) };
var enableLbl = new TextBlock
{
Text = "Enable Tapping",
Foreground = ColTextDim,
FontSize = 10,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 6, 0),
};
row1.Children.Add(enableLbl);
var enableBtn = new Button
{
Content = state.Data.EnableManaTapping ? "ON" : "OFF",
Background = state.Data.EnableManaTapping
? new SolidColorBrush(Color.FromRgb(0x10, 0x40, 0x10))
: ColBtnFill,
Foreground = state.Data.EnableManaTapping
? new SolidColorBrush(Color.FromRgb(0x33, 0xFF, 0x33))
: ColMute,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(8, 2),
FontSize = 10,
Width = 50,
Margin = new Thickness(0, 0, 16, 0),
};
enableBtn.Click += (_, _) =>
{
state.Data.EnableManaTapping = !state.Data.EnableManaTapping;
onChanged();
RebuildManaSection(sp, state, onChanged);
};
row1.Children.Add(enableBtn);
row1.Children.Add(new TextBlock
{
Text = "Keep count:",
Foreground = ColTextDim,
FontSize = 10,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 6, 0),
});
row1.Children.Add(BuildIntSpinner(state.Data.ManaStoneKeepCount, 1, 999,
v => { state.Data.ManaStoneKeepCount = v; onChanged(); }));
sp.Children.Add(row1);
// Row 2: Min mana threshold (only when tapping is on)
if (state.Data.EnableManaTapping)
{
var row2 = new WrapPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(4, 2, 4, 4) };
row2.Children.Add(new TextBlock
{
Text = "Min MaxMana to tap:",
Foreground = ColTextDim,
FontSize = 10,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 6, 0),
});
row2.Children.Add(BuildIntSpinner(state.Data.ManaTapMinMana, 100, 99999,
v => { state.Data.ManaTapMinMana = v; onChanged(); }));
sp.Children.Add(row2);
}
}
// ── Integer spinner (−/value/+) ───────────────────────────────────────────
private static Control BuildIntSpinner(int value, int min, int max, Action<int> onChanged)
{
var lbl = new TextBlock
{
Text = value.ToString(),
Foreground = ColTextDim,
FontSize = 10,
Width = 60,
TextAlignment = Avalonia.Media.TextAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
};
int cur = value;
var decBtn = MakeSmallBtn("-", () =>
{
cur = Math.Max(min, cur - 1);
lbl.Text = cur.ToString();
onChanged(cur);
});
var incBtn = MakeSmallBtn("+", () =>
{
cur = Math.Min(max, cur + 1);
lbl.Text = cur.ToString();
onChanged(cur);
});
var sp = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2 };
sp.Children.Add(decBtn);
sp.Children.Add(lbl);
sp.Children.Add(incBtn);
return sp;
}
private static Button MakeSmallBtn(string label, Action onClick)
{
var b = new Button
{
Content = label,
Background = ColBtnFill,
Foreground = ColTeal,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(4, 1),
FontSize = 10,
Width = 22,
};
b.Click += (_, _) => onClick();
return b;
}
// ── Plugin binding ────────────────────────────────────────────────────────
// RL loads fresh plugin copies without unloading the old ones: drop the
// exports bound below so the next poll re-binds to the live copy.
static ItemsPanel() => PluginManager.PluginsUnloaded += () =>
{
_getItemsJson = null;
_setItemsJson = null;
_addSelectedWeapon = null;
_addSelectedConsumable = null;
};
private static void TryBind()
{
var plugin = PluginManager.Plugins.FirstOrDefault(
p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase));
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
if (_getItemsJson == null)
{
IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetItemsJson");
if (p != IntPtr.Zero) _getItemsJson = Marshal.GetDelegateForFunctionPointer<GetItemsJsonFn>(p);
}
if (_setItemsJson == null)
{
IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginSetItemsJson");
if (p != IntPtr.Zero) _setItemsJson = Marshal.GetDelegateForFunctionPointer<SetItemsJsonFn>(p);
}
if (_addSelectedWeapon == null)
{
IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginAddSelectedWeapon");
if (p != IntPtr.Zero) _addSelectedWeapon = Marshal.GetDelegateForFunctionPointer<VoidFn>(p);
}
if (_addSelectedConsumable == null)
{
IntPtr p = GetProcAddress(plugin.ModuleHandle, "RynthPluginAddSelectedConsumable");
if (p != IntPtr.Zero) _addSelectedConsumable = Marshal.GetDelegateForFunctionPointer<VoidFn>(p);
}
}
private static bool TryFetch(out Payload payload)
{
payload = new Payload();
if (_getItemsJson == null) return false;
try
{
IntPtr ptr = _getItemsJson();
if (ptr == IntPtr.Zero) return false;
string? json = Marshal.PtrToStringAnsi(ptr);
if (string.IsNullOrEmpty(json)) return false;
var parsed = JsonSerializer.Deserialize(json, ItemsPanelJsonContext.Default.Payload);
if (parsed == null) return false;
payload = parsed;
return true;
}
catch { return false; }
}
private static void PushChanges(State state)
{
if (_setItemsJson == null) TryBind();
if (_setItemsJson == null) return;
IntPtr ansi = IntPtr.Zero;
try
{
string json = JsonSerializer.Serialize(state.Data, ItemsPanelJsonContext.Default.Payload);
ansi = Marshal.StringToHGlobalAnsi(json);
_setItemsJson(ansi);
state.Dirty = false;
}
catch { }
finally
{
if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi);
}
}
// ── Change detection ──────────────────────────────────────────────────────
private static bool WeaponsChanged(List<WeaponEntry> a, List<WeaponEntry> b)
{
if (a.Count != b.Count) return true;
for (int i = 0; i < a.Count; i++)
if (a[i].Id != b[i].Id || a[i].Name != b[i].Name || a[i].Element != b[i].Element) return true;
return false;
}
private static bool ConsumablesChanged(List<ConsumableEntry> a, List<ConsumableEntry> b)
{
if (a.Count != b.Count) return true;
for (int i = 0; i < a.Count; i++)
if (a[i].Id != b[i].Id || a[i].Name != b[i].Name || a[i].Type != b[i].Type) return true;
return false;
}
}

View file

@ -85,6 +85,11 @@ internal static class LogPanel
scroll.ScrollToEnd();
};
timer.Start();
// Stop with the visual tree — a running DispatcherTimer roots the closed
// view forever (one immortal poller per open/close). RadarPanel idiom;
// must restart on attach: drag/resize fires Detached→Attached.
root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
root.DetachedFromVisualTree += (_, _) => timer.Stop();
return root;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,396 @@
// =============================================================================
// RynthCore.Engine — UI/Panels/MetaSourceEditor.cs
// AvaloniaEdit-based source editor for the Meta panel's Source view.
// Provides syntax highlighting (programmatic, NativeAOT-friendly — no XSHD)
// and context-aware Ctrl+Space completion driven by the live MetaPanel
// payload (states / nav files / embedded nav keys).
// =============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using AvaloniaEdit;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using RynthCore.Engine.ImGuiBackend;
namespace RynthCore.Engine.UI.Panels;
internal static class MetaSourceEditor
{
// ── .af vocabulary (mirrors MetaSchema in RynthSuite plugin) ──────────────
// Top-level structural keywords.
private static readonly HashSet<string> StructKeywords = new(StringComparer.OrdinalIgnoreCase)
{
"STATE", "IF", "DO", "NAV",
};
// Condition keywords as they appear in .af source (keyword form, not labels).
internal static readonly string[] ConditionKeywords =
{
"Never", "Always", "All", "Any", "ChatMatch", "MainSlotsLE",
"SecsInStateGE", "Death", "VendorOpen", "VendorClosed",
"ItemCountLE", "ItemCountGE",
"MobsInDist_Name", "MobsInDist_Priority",
"NeedToBuff", "NoMobsInDist", "BlockE", "CellE",
"IntoPortal", "ExitPortal", "Not",
"PSecsInStateGE", "SecsOnSpellGE", "SecsOnSpellLE",
"BuPercentGE", "DistToRteGE", "Expr",
"ChatCapture", "NavEmpty",
"MainHealthLE", "MainHealthPHE", "MainManaLE", "MainManaPHE",
"MainStamLE", "VitaePHE",
};
internal static readonly string[] ActionKeywords =
{
"None", "Chat", "SetState", "EmbedNav", "DoAll",
"CallState", "Return", "DoExpr", "ChatExpr",
"SetWatchdog", "ClearWatchdog", "GetOpt", "SetOpt",
"CreateView", "DestroyView", "DestroyAllViews",
};
private static readonly HashSet<string> CondSet = new(ConditionKeywords, StringComparer.OrdinalIgnoreCase);
private static readonly HashSet<string> ActSet = new(ActionKeywords, StringComparer.OrdinalIgnoreCase);
// ── Colorblind-aware palette ─────────────────────────────────────────────
// Differentiation by both hue AND weight/style so it reads without colour.
private static readonly IBrush BrStruct = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6)); // teal, bold
private static readonly IBrush BrCond = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33)); // amber, bold
private static readonly IBrush BrAction = new SolidColorBrush(Color.FromRgb(0x7B, 0xB8, 0xFF)); // light blue
private static readonly IBrush BrComment = new SolidColorBrush(Color.FromRgb(0x6A, 0x7A, 0x8A)); // grey, italic
private static readonly IBrush BrBrace = new SolidColorBrush(Color.FromRgb(0xCC, 0x88, 0xCC)); // pink/violet
private static readonly IBrush BrNumber = new SolidColorBrush(Color.FromRgb(0x99, 0xE6, 0x99)); // green
private static readonly IBrush BrText = new SolidColorBrush(Color.FromRgb(0xD9, 0xE6, 0xF2)); // default
private static readonly IBrush BrBg = new SolidColorBrush(Color.FromRgb(0x14, 0x1F, 0x29));
private static readonly IBrush BrBorder = new SolidColorBrush(Color.FromRgb(0x26, 0x40, 0x59));
// ── Public factory ───────────────────────────────────────────────────────
/// <summary>
/// Returns a TextEditor wired to the meta source view. <paramref name="getText"/>
/// is read once at construction; <paramref name="onTextChanged"/> fires on every
/// edit. <paramref name="getStates"/> / <paramref name="getNavs"/> are queried
/// lazily when the completion popup opens so suggestions track live payload.
/// </summary>
public static TextEditor Create(
Func<string> getText,
Action<string> onTextChanged,
Func<IReadOnlyList<string>> getStates,
Func<IReadOnlyList<string>> getNavs)
{
var editor = new TextEditor
{
ShowLineNumbers = true,
Background = BrBg,
Foreground = BrText,
BorderBrush = BrBorder,
BorderThickness = new Thickness(1),
FontFamily = new FontFamily("Cascadia Mono,Consolas,monospace"),
FontSize = 12,
MinHeight = 320,
Padding = new Thickness(4),
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
Options =
{
ConvertTabsToSpaces = false,
IndentationSize = 4,
HighlightCurrentLine = true,
ShowSpaces = false,
ShowTabs = false,
EnableHyperlinks = false,
EnableEmailHyperlinks = false,
AllowScrollBelowDocument = true,
},
};
// Initial text.
editor.Document = new TextDocument(getText() ?? string.Empty);
// Open the keyboard gate while the editor has focus so forwarded
// WM_KEYDOWNs reach it instead of the game, and the WM_SETFOCUS hijack
// doesn't yank focus back ~50 ms after the click. Without this the
// Source field is untypable (most visibly when the panel is floating).
editor.TextArea.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
editor.TextArea.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false;
// Syntax highlighter.
editor.TextArea.TextView.LineTransformers.Add(new MetaColorizer());
// Text-changed fan-out — keep ps.SourceText in sync.
editor.Document.TextChanged += (_, _) => onTextChanged(editor.Document.Text);
// Completion (Ctrl+Space, also after ':' or '.').
CompletionWindow? completionWindow = null;
void OpenCompletion(bool autoTriggered)
{
if (completionWindow != null) return;
var items = BuildSuggestionsForContext(editor, getStates, getNavs);
if (items.Count == 0) return;
completionWindow = new CompletionWindow(editor.TextArea);
foreach (var s in items)
completionWindow.CompletionList.CompletionData.Add(new MetaCompletionItem(s.Text, s.Kind));
// For auto-trigger don't force-select; user might just want to type freely.
completionWindow.CompletionList.IsFiltering = true;
if (!autoTriggered) completionWindow.CompletionList.SelectedItem ??= completionWindow.CompletionList.CompletionData.FirstOrDefault();
completionWindow.Closed += (_, _) => completionWindow = null;
completionWindow.Show();
}
editor.TextArea.KeyDown += (_, e) =>
{
if (e.Key == Key.Space && (e.KeyModifiers & KeyModifiers.Control) != 0)
{
e.Handled = true;
OpenCompletion(autoTriggered: false);
}
};
// Auto-trigger after typing ':' followed by a space-or-letter, so
// "IF:<space>" pops the conditions list without Ctrl+Space.
editor.TextArea.TextEntered += (_, e) =>
{
if (e.Text == " ")
{
var caret = editor.TextArea.Caret.Offset;
if (caret >= 2 && editor.Document.GetCharAt(caret - 2) == ':')
OpenCompletion(autoTriggered: true);
}
};
return editor;
}
// ── Context-aware suggestion builder ─────────────────────────────────────
private enum SuggestionKind { Struct, Cond, Action, State, Nav, Generic }
private readonly record struct Suggestion(string Text, SuggestionKind Kind);
private static List<Suggestion> BuildSuggestionsForContext(
TextEditor editor,
Func<IReadOnlyList<string>> getStates,
Func<IReadOnlyList<string>> getNavs)
{
var caret = editor.TextArea.Caret.Offset;
var doc = editor.Document;
// Read the current line up to the caret.
var line = doc.GetLineByOffset(caret);
string prefix = doc.GetText(line.Offset, Math.Max(0, caret - line.Offset));
string trimmed = prefix.TrimStart();
string trimmedNoTrailing = trimmed.TrimEnd();
var states = SafeList(getStates);
var navs = SafeList(getNavs);
// After IF: → conditions
if (StartsWithKeyword(trimmedNoTrailing, "IF:", out var rest))
{
// If the user already typed a known cond keyword followed by a space,
// start suggesting state/nav names where meaningful (SetState/CallState
// appear as action data, not condition; keep conditions list here).
return ConditionKeywords.Select(s => new Suggestion(s, SuggestionKind.Cond)).ToList();
}
// After DO: → actions
if (StartsWithKeyword(trimmedNoTrailing, "DO:", out rest))
{
// If user typed "DO: SetState " or "DO: CallState " → states
if (StartsWithKeyword(rest.TrimStart(), "SetState", out _) ||
StartsWithKeyword(rest.TrimStart(), "CallState", out _))
return states.Select(s => new Suggestion(s, SuggestionKind.State)).ToList();
if (StartsWithKeyword(rest.TrimStart(), "EmbedNav", out _))
return navs.Select(s => new Suggestion(s, SuggestionKind.Nav)).ToList();
return ActionKeywords.Select(s => new Suggestion(s, SuggestionKind.Action)).ToList();
}
// After STATE: → existing state names + free-form (user types new)
if (StartsWithKeyword(trimmedNoTrailing, "STATE:", out _))
return states.Select(s => new Suggestion(s, SuggestionKind.State)).ToList();
// After NAV: → nav names
if (StartsWithKeyword(trimmedNoTrailing, "NAV:", out _))
return navs.Select(s => new Suggestion(s, SuggestionKind.Nav)).ToList();
// Beginning of line → structural keywords
return new List<Suggestion>
{
new("STATE:", SuggestionKind.Struct),
new("IF:", SuggestionKind.Struct),
new("DO:", SuggestionKind.Struct),
new("NAV:", SuggestionKind.Struct),
};
}
private static bool StartsWithKeyword(string text, string keyword, out string rest)
{
if (text.StartsWith(keyword, StringComparison.OrdinalIgnoreCase))
{
rest = text.Substring(keyword.Length);
return true;
}
rest = string.Empty;
return false;
}
private static IReadOnlyList<string> SafeList(Func<IReadOnlyList<string>> fn)
{
try { return fn() ?? Array.Empty<string>(); }
catch { return Array.Empty<string>(); }
}
// ── Colorizer ─────────────────────────────────────────────────────────────
private sealed class MetaColorizer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
var doc = CurrentContext.Document;
int start = line.Offset;
int end = line.EndOffset;
if (end <= start) return;
string text = doc.GetText(start, end - start);
// ── Comments: ~~ … to EOL (handles both "~~ }" and "~~ @disabled") ──
int commentIdx = text.IndexOf("~~", StringComparison.Ordinal);
int contentEnd = commentIdx >= 0 ? commentIdx : text.Length;
if (commentIdx >= 0)
{
ChangeLinePart(start + commentIdx, end, el =>
{
el.TextRunProperties.SetForegroundBrush(BrComment);
el.TextRunProperties.SetTypeface(new Typeface(
el.TextRunProperties.Typeface.FontFamily,
FontStyle.Italic));
});
}
// ── Token sweep over the non-comment portion ──────────────────────
int i = 0;
while (i < contentEnd)
{
char c = text[i];
// Whitespace
if (c == ' ' || c == '\t') { i++; continue; }
// Braces { }
if (c == '{' || c == '}')
{
ChangeLinePart(start + i, start + i + 1, el =>
el.TextRunProperties.SetForegroundBrush(BrBrace));
i++;
continue;
}
// Numbers (decimal, hex like A9B40000, signed)
if (char.IsDigit(c) || (c == '-' && i + 1 < contentEnd && char.IsDigit(text[i + 1])))
{
int j = i + 1;
while (j < contentEnd && (char.IsLetterOrDigit(text[j]) || text[j] == '.' || text[j] == '_'))
j++;
ChangeLinePart(start + i, start + j, el =>
el.TextRunProperties.SetForegroundBrush(BrNumber));
i = j;
continue;
}
// Identifier / keyword
if (char.IsLetter(c) || c == '_')
{
int j = i + 1;
while (j < contentEnd && (char.IsLetterOrDigit(text[j]) || text[j] == '_'))
j++;
string tok = text.Substring(i, j - i);
// STATE / IF / DO / NAV followed by ':' = struct keyword
bool isStruct = StructKeywords.Contains(tok)
&& j < contentEnd && text[j] == ':';
IBrush? brush = null;
bool bold = false;
if (isStruct) { brush = BrStruct; bold = true; }
else if (CondSet.Contains(tok)) { brush = BrCond; bold = true; }
else if (ActSet.Contains(tok)) { brush = BrAction; }
if (brush != null)
{
int tokStart = start + i;
int tokEnd = start + j;
bool boldCopy = bold;
IBrush brushCopy = brush;
ChangeLinePart(tokStart, tokEnd, el =>
{
el.TextRunProperties.SetForegroundBrush(brushCopy);
if (boldCopy)
el.TextRunProperties.SetTypeface(new Typeface(
el.TextRunProperties.Typeface.FontFamily,
FontStyle.Normal, FontWeight.Bold));
});
if (isStruct && j < contentEnd && text[j] == ':')
{
// colour the trailing ':' too
ChangeLinePart(start + j, start + j + 1, el =>
el.TextRunProperties.SetForegroundBrush(BrStruct));
j++;
}
}
i = j;
continue;
}
i++;
}
}
}
// ── Completion item ───────────────────────────────────────────────────────
private sealed class MetaCompletionItem : ICompletionData
{
private readonly string _text;
private readonly SuggestionKind _kind;
public MetaCompletionItem(string text, SuggestionKind kind)
{
_text = text;
_kind = kind;
}
public Avalonia.Media.IImage? Image => null;
public string Text => _text;
public object Content => _text;
public object Description => _kind switch
{
SuggestionKind.Struct => "structural keyword",
SuggestionKind.Cond => "condition",
SuggestionKind.Action => "action",
SuggestionKind.State => "meta state",
SuggestionKind.Nav => "nav route",
_ => string.Empty,
};
public double Priority => _kind switch
{
SuggestionKind.Struct => 100,
SuggestionKind.Cond => 90,
SuggestionKind.Action => 90,
SuggestionKind.State => 80,
SuggestionKind.Nav => 80,
_ => 0,
};
public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
=> textArea.Document.Replace(completionSegment, _text);
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,618 @@
// ============================================================================
// RynthCore.Engine — UI/Panels/NavPanel.cs
// Avalonia replica of LegacyNavigationUi.cs (RynthSuite plugin).
//
// Plugin exports used:
// RynthPluginGetNavJson → polled every 1s for live state
// RynthPluginSendNavCommand → dispatched on button actions
// ============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Panels;
[JsonSerializable(typeof(NavPanel.Payload))]
[JsonSerializable(typeof(NavPanel.NavCmd))]
[JsonSerializable(typeof(List<NavPanel.NavPoint>))]
[JsonSerializable(typeof(List<string>), TypeInfoPropertyName = "StringList")]
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, WriteIndented = false, IncludeFields = false)]
internal partial class NavPanelJsonContext : JsonSerializerContext { }
internal static class NavPanel
{
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr GetNavJsonFn();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void SendNavCommandFn(IntPtr ansiJson);
private static GetNavJsonFn? _getNavJson;
private static SendNavCommandFn? _sendNavCommand;
private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33));
private static readonly IBrush ColGreen = new SolidColorBrush(Color.FromRgb(0x33, 0xCC, 0x66));
private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6));
private static readonly IBrush ColMute = new SolidColorBrush(Color.FromRgb(0x8C, 0xA6, 0xBF));
private static readonly IBrush ColTextDim = new SolidColorBrush(Color.FromRgb(0xD9, 0xE6, 0xF2));
private static readonly IBrush ColShellBg = new SolidColorBrush(Color.FromRgb(0x0A, 0x0F, 0x14));
private static readonly IBrush ColPanelBg = new SolidColorBrush(Color.FromRgb(0x14, 0x1F, 0x29));
private static readonly IBrush ColRowAlt = new SolidColorBrush(Color.FromRgb(0x10, 0x18, 0x22));
private static readonly IBrush ColBtnFill = new SolidColorBrush(Color.FromRgb(0x0F, 0x1F, 0x2E));
private static readonly IBrush ColBtnBord = new SolidColorBrush(Color.FromRgb(0x26, 0x40, 0x59));
private static readonly IBrush ColStartBg = new SolidColorBrush(Color.FromRgb(0x19, 0x61, 0x19));
private static readonly IBrush ColStopBg = new SolidColorBrush(Color.FromRgb(0x80, 0x19, 0x19));
private static readonly string[] RouteTypes = { "Once", "Circular", "Linear", "Follow" };
private static readonly string[] AddModes = { "End", "Above", "Below" };
private static readonly int[] RecallIds =
{
48, 2645, 2647,
1635, 1636,
157, 158, 1637,
2648, 2649, 2650,
2931, 2023, 2041, 2358, 2813, 2941, 2943,
3865, 3929, 3930, 4084, 4198, 4213,
4907, 4908, 4909,
5175, 5330, 5541, 6150, 6321, 6322,
};
// ── Data types (mirror NavBridgePayload / NavCommand on plugin side) ──────
internal sealed class NavPoint
{
public int Idx { get; set; }
public string Type { get; set; } = string.Empty;
public string Desc { get; set; } = string.Empty;
public double NS { get; set; }
public double EW { get; set; }
public double Z { get; set; }
}
internal sealed class Payload
{
public string ActiveNavName { get; set; } = string.Empty;
public string NavStatusLine { get; set; } = string.Empty;
public bool NavIsStuck { get; set; }
public bool MacroRunning { get; set; }
public bool NavigationEnabled { get; set; }
public int RouteType { get; set; }
public int ActiveNavIndex { get; set; }
public List<string> NavFiles { get; set; } = new();
public List<NavPoint> Points { get; set; } = new();
}
internal sealed class NavCmd
{
public string Cmd { get; set; } = string.Empty;
public int SpellId { get; set; }
public int Index { get; set; }
public int RouteType { get; set; }
public int AddMode { get; set; }
public int InsertAt { get; set; } = -1;
public string NavName { get; set; } = string.Empty;
}
private sealed class State
{
public Payload Data = new();
public int SelectedIdx = -1;
public int AddModeIdx = 0;
}
// ── Picker overlay (identical pattern to SettingsPanel) ──────────────────
private sealed class PickerState
{
public Canvas Canvas = null!;
public Border? ActivePicker;
public Button? ActiveAnchor;
public Control? Root;
public void Close()
{
if (ActivePicker != null) { Canvas.Children.Remove(ActivePicker); ActivePicker = null; }
ActiveAnchor = null;
Canvas.IsHitTestVisible = false;
}
public void Show(Button anchor, string[] items, int selected, Action<int> onPick)
{
if (ReferenceEquals(anchor, ActiveAnchor)) { Close(); return; }
Close();
ActiveAnchor = anchor;
var stack = new StackPanel { Spacing = 1 };
for (int i = 0; i < items.Length; i++)
{
int ci = i;
var entry = new Button
{
Content = items[i],
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Left,
Background = i == selected ? new SolidColorBrush(Color.FromRgb(0x1A, 0x2E, 0x42)) : ColBtnFill,
Foreground = i == selected ? ColTeal : ColTextDim,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(6, 2),
FontSize = 10,
Height = 20,
};
entry.Click += (_, _) => { onPick(ci); Close(); };
stack.Children.Add(entry);
}
const double pickerWidth = 220;
Point ap = anchor.TranslatePoint(new Point(0, anchor.Bounds.Height), Canvas) ?? new Point(8, 8);
double rootWidth = Root?.Bounds.Width ?? 400;
double rootHeight = Root?.Bounds.Height ?? 300;
double left = Math.Clamp(ap.X, 4, Math.Max(4, rootWidth - pickerWidth - 4));
double top = ap.Y;
double maxH = Math.Min(items.Length * 22 + 8, Math.Max(80, rootHeight - top - 4));
var pb = new Border
{
Width = pickerWidth,
MaxHeight = maxH,
Background = ColShellBg,
BorderBrush = ColTeal,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(4),
Padding = new Thickness(2),
Child = new ScrollViewer
{
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
Content = stack,
},
};
Canvas.Children.Add(pb);
Avalonia.Controls.Canvas.SetLeft(pb, left);
Avalonia.Controls.Canvas.SetTop(pb, top);
ActivePicker = pb;
Canvas.IsHitTestVisible = true;
}
}
// =========================================================================
// Create
// =========================================================================
public static Control Create()
{
TryBind();
var state = new State();
var root = new Border
{
Background = ColShellBg,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(4),
MinWidth = 360,
};
var rootGrid = new Grid();
root.Child = rootGrid;
var pickerCanvas = new Canvas { IsHitTestVisible = false, Background = Brushes.Transparent };
var picker = new PickerState { Canvas = pickerCanvas, Root = root };
var content = new StackPanel { Margin = new Thickness(6), Spacing = 4 };
rootGrid.Children.Add(new ScrollViewer
{
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
Content = content,
});
rootGrid.Children.Add(pickerCanvas);
pickerCanvas.PointerPressed += (_, e) =>
{
if (picker.ActivePicker != null && ReferenceEquals(e.Source, pickerCanvas))
{ e.Handled = true; picker.Close(); }
};
void Rebuild()
{
content.Children.Clear();
var d = state.Data;
bool navActive = d.MacroRunning && d.NavigationEnabled;
// ── Active nav name ───────────────────────────────────────────────
content.Children.Add(new TextBlock
{
Text = $"Active Nav: {(string.IsNullOrEmpty(d.ActiveNavName) ? "None (Unsaved)" : d.ActiveNavName)}",
Foreground = ColAmber,
FontSize = 11,
FontWeight = FontWeight.Bold,
TextTrimming = TextTrimming.CharacterEllipsis,
});
// ── Status line ───────────────────────────────────────────────────
if (!string.IsNullOrEmpty(d.NavStatusLine))
{
content.Children.Add(new TextBlock
{
Text = d.NavStatusLine,
Foreground = d.NavIsStuck ? ColAmber : ColGreen,
FontSize = 10,
TextTrimming = TextTrimming.CharacterEllipsis,
});
}
// ── Start / Stop button ───────────────────────────────────────────
var startStopBtn = new Button
{
Content = navActive ? "Stop Navigation" : "Start Navigation",
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Center,
Height = 28,
Background = navActive ? ColStopBg : ColStartBg,
Foreground = ColTextDim,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(3),
FontSize = 11,
};
startStopBtn.Click += (_, _) =>
{
bool active = state.Data.MacroRunning && state.Data.NavigationEnabled;
if (active)
{
Send(new NavCmd { Cmd = "stopNav" });
state.Data.NavigationEnabled = false;
}
else
{
Send(new NavCmd { Cmd = "startNav" });
state.Data.MacroRunning = true;
state.Data.NavigationEnabled = true;
}
Rebuild();
};
content.Children.Add(startStopBtn);
content.Children.Add(new Border { Height = 1, Background = ColBtnBord });
// ── Route type + Insert mode ──────────────────────────────────────
var controlRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,4,*") };
int rIdx = d.RouteType switch { 1 => 1, 2 => 2, 3 => 3, _ => 0 };
var routeBtn = MakePickerBtn($"Route: {RouteTypes[rIdx]}");
routeBtn.Click += (_, _) =>
{
int cur = state.Data.RouteType switch { 1 => 1, 2 => 2, 3 => 3, _ => 0 };
picker.Show(routeBtn, RouteTypes, cur, idx =>
{
int enumVal = idx switch { 1 => 1, 2 => 2, 3 => 3, _ => 4 };
Send(new NavCmd { Cmd = "setRouteType", RouteType = enumVal });
state.Data.RouteType = enumVal;
Rebuild();
});
};
Grid.SetColumn(routeBtn, 0);
controlRow.Children.Add(routeBtn);
var insertBtn = MakePickerBtn($"Insert: {AddModes[state.AddModeIdx]}");
insertBtn.Click += (_, _) =>
{
int cur = state.AddModeIdx;
picker.Show(insertBtn, AddModes, cur, idx =>
{
state.AddModeIdx = idx;
Rebuild();
});
};
Grid.SetColumn(insertBtn, 2);
controlRow.Children.Add(insertBtn);
content.Children.Add(controlRow);
// ── Action buttons ────────────────────────────────────────────────
var actionWrap = new WrapPanel { Orientation = Orientation.Horizontal };
var addWpBtn = MakeActionBtn("Add Waypoint");
addWpBtn.Click += (_, _) =>
Send(new NavCmd { Cmd = "addWaypoint", AddMode = state.AddModeIdx, InsertAt = state.SelectedIdx });
actionWrap.Children.Add(addWpBtn);
var addPortalBtn = MakeActionBtn("Add Portal");
addPortalBtn.IsEnabled = false;
ToolTip.SetTip(addPortalBtn, "Add Portal is not yet implemented.");
actionWrap.Children.Add(addPortalBtn);
var addRecallBtn = MakeActionBtn("Add Recall");
var recallLabels = new string[RecallIds.Length];
for (int ri = 0; ri < RecallIds.Length; ri++)
recallLabels[ri] = $"Spell {RecallIds[ri]} ({RecallIds[ri]})";
addRecallBtn.Click += (_, _) =>
picker.Show(addRecallBtn, recallLabels, -1, idx =>
Send(new NavCmd { Cmd = "addRecall", SpellId = RecallIds[idx], AddMode = state.AddModeIdx, InsertAt = state.SelectedIdx }));
actionWrap.Children.Add(addRecallBtn);
var clearBtn = MakeActionBtn("Clear Route");
clearBtn.Click += (_, _) =>
{
Send(new NavCmd { Cmd = "clearRoute" });
state.Data.Points.Clear();
state.SelectedIdx = -1;
Rebuild();
};
actionWrap.Children.Add(clearBtn);
var saveBtn = MakeActionBtn("Save Route");
saveBtn.Click += (_, _) => Send(new NavCmd { Cmd = "saveRoute" });
actionWrap.Children.Add(saveBtn);
var dunPatrolBtn = MakeActionBtn("Dungeon Patrol");
dunPatrolBtn.Click += (_, _) => Send(new NavCmd { Cmd = "dunPatrol" });
actionWrap.Children.Add(dunPatrolBtn);
content.Children.Add(actionWrap);
// ── Nav file selector ─────────────────────────────────────────────
if (d.NavFiles.Count > 0)
{
var fileRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };
fileRow.Children.Add(new TextBlock
{
Text = "Nav:",
Foreground = ColMute,
FontSize = 10,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 6, 0),
});
int activeFileIdx = string.IsNullOrEmpty(d.ActiveNavName) ? -1 : d.NavFiles.IndexOf(d.ActiveNavName);
string fileBtnText = activeFileIdx >= 0 ? d.NavFiles[activeFileIdx] : "Select nav file...";
var fileBtn = MakePickerBtn(fileBtnText);
Grid.SetColumn(fileBtn, 1);
fileBtn.Click += (_, _) =>
{
int cur = string.IsNullOrEmpty(state.Data.ActiveNavName) ? -1 : state.Data.NavFiles.IndexOf(state.Data.ActiveNavName);
picker.Show(fileBtn, state.Data.NavFiles.ToArray(), cur, idx =>
Send(new NavCmd { Cmd = "loadNav", NavName = state.Data.NavFiles[idx] }));
};
fileRow.Children.Add(fileBtn);
content.Children.Add(fileRow);
}
// ── Waypoint list ─────────────────────────────────────────────────
content.Children.Add(new Border { Height = 1, Background = ColBtnBord });
content.Children.Add(new TextBlock
{
Text = $"Waypoints ({d.Points.Count})",
Foreground = ColMute,
FontSize = 10,
});
var waypointStack = new StackPanel { Spacing = 1 };
for (int i = 0; i < d.Points.Count; i++)
{
int ci = i;
var pt = d.Points[i];
bool isActive = i == d.ActiveNavIndex;
bool isSelected = i == state.SelectedIdx;
var row = new Grid
{
ColumnDefinitions = new ColumnDefinitions("22,18,*"),
Background = isSelected
? new SolidColorBrush(Color.FromRgb(0x1A, 0x2E, 0x42))
: (i % 2 == 0 ? ColPanelBg : ColRowAlt),
};
var delBtn = new Button
{
Content = "X",
Width = 18,
Height = 18,
Padding = new Thickness(0),
Margin = new Thickness(2),
Background = new SolidColorBrush(Color.FromRgb(0x80, 0x1A, 0x1A)),
Foreground = ColTextDim,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(2),
FontSize = 9,
HorizontalContentAlignment = HorizontalAlignment.Center,
};
delBtn.Click += (_, e) =>
{
e.Handled = true;
Send(new NavCmd { Cmd = "deletePoint", Index = ci });
if (state.SelectedIdx == ci) state.SelectedIdx = -1;
else if (state.SelectedIdx > ci) state.SelectedIdx--;
if (ci < state.Data.Points.Count) state.Data.Points.RemoveAt(ci);
Rebuild();
};
Grid.SetColumn(delBtn, 0);
row.Children.Add(delBtn);
var indicator = new TextBlock
{
Text = isActive ? "=>" : " ",
Foreground = isActive ? ColTeal : ColMute,
FontSize = 9,
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
};
Grid.SetColumn(indicator, 1);
row.Children.Add(indicator);
string disp = !string.IsNullOrEmpty(pt.Desc)
? $"[{i}] {pt.Desc}"
: $"[{i}] {pt.Type} ({pt.NS:F2}N, {pt.EW:F2}E, {pt.Z:F1})";
var desc = new TextBlock
{
Text = disp,
Foreground = isActive ? ColTeal : ColTextDim,
FontSize = 10,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(4, 0, 2, 0),
TextTrimming = TextTrimming.CharacterEllipsis,
};
Grid.SetColumn(desc, 2);
row.Children.Add(desc);
row.PointerPressed += (_, e) =>
{
if (e.Handled) return;
state.SelectedIdx = ci;
Rebuild();
};
waypointStack.Children.Add(row);
}
content.Children.Add(new Border
{
Height = 200,
Child = new ScrollViewer
{
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
Content = waypointStack,
},
});
}
// ── Poll timer ────────────────────────────────────────────────────────
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
timer.Tick += (_, _) =>
{
if (_getNavJson == null) TryBind();
if (picker.ActivePicker != null) return;
if (!TryFetch(out var fresh)) return;
state.Data = fresh;
Rebuild();
};
timer.Start();
// Stop with the visual tree — a running DispatcherTimer roots the closed
// view forever (one immortal poller per open/close). RadarPanel idiom;
// must restart on attach: drag/resize fires Detached→Attached.
root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
root.DetachedFromVisualTree += (_, _) => timer.Stop();
Rebuild();
return root;
}
// =========================================================================
// Helpers
// =========================================================================
private static Button MakePickerBtn(string text) => new Button
{
Content = text,
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Left,
Background = ColBtnFill,
Foreground = ColTextDim,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(3),
Padding = new Thickness(6, 2),
FontSize = 10,
Height = 22,
};
private static Button MakeActionBtn(string text) => new Button
{
Content = text,
Background = ColBtnFill,
Foreground = ColTextDim,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(3),
Padding = new Thickness(8, 3),
FontSize = 10,
Height = 24,
Margin = new Thickness(0, 0, 4, 4),
};
// =========================================================================
// Plugin bridge
// =========================================================================
// RL loads fresh plugin copies without unloading the old ones: drop the
// exports bound below so the next poll re-binds to the live copy.
static NavPanel() => PluginManager.PluginsUnloaded += () =>
{
_getNavJson = null;
_sendNavCommand = null;
};
private static void TryBind()
{
var plugin = PluginManager.Plugins.FirstOrDefault(
p => p.DisplayName.Contains("RynthAi", StringComparison.OrdinalIgnoreCase));
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
if (_getNavJson == null)
{
IntPtr p1 = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetNavJson");
if (p1 != IntPtr.Zero)
_getNavJson = Marshal.GetDelegateForFunctionPointer<GetNavJsonFn>(p1);
}
if (_sendNavCommand == null)
{
IntPtr p2 = GetProcAddress(plugin.ModuleHandle, "RynthPluginSendNavCommand");
if (p2 != IntPtr.Zero)
_sendNavCommand = Marshal.GetDelegateForFunctionPointer<SendNavCommandFn>(p2);
}
}
private static bool TryFetch(out Payload payload)
{
payload = new Payload();
if (_getNavJson == null) return false;
try
{
IntPtr ptr = _getNavJson();
if (ptr == IntPtr.Zero) return false;
string? json = Marshal.PtrToStringAnsi(ptr);
if (string.IsNullOrEmpty(json)) return false;
var parsed = JsonSerializer.Deserialize(json, NavPanelJsonContext.Default.Payload);
if (parsed == null) return false;
payload = parsed;
return true;
}
catch { return false; }
}
private static void Send(NavCmd cmd)
{
if (_sendNavCommand == null) TryBind();
if (_sendNavCommand == null) return;
IntPtr ansi = IntPtr.Zero;
try
{
string json = JsonSerializer.Serialize(cmd, NavPanelJsonContext.Default.NavCmd);
ansi = Marshal.StringToHGlobalAnsi(json);
_sendNavCommand(ansi);
}
catch { }
finally
{
if (ansi != IntPtr.Zero) Marshal.FreeHGlobal(ansi);
}
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,214 @@
// ============================================================================
// RynthCore.Engine — UI/Panels/RynthChatFiltersPanel.cs
// Standalone editor for RynthChat regex filter rules. Registered as its own
// "ChatFilters" panel (dockable/floatable) — rules get complex enough that
// a small overlay inside the chat panel doesn't cut it.
//
// Rule semantics (shared state lives in RynthChatPanel):
// • Regex, case-insensitive, matched against the formatted line.
// • FIRST matching rule wins — order matters, hence the ▲▼ buttons.
// • Tab name set → matching lines MOVE to that tab (still shown in All).
// • Tab name empty → matching lines are hidden everywhere.
// ============================================================================
using System;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using RynthCore.Engine.ImGuiBackend;
namespace RynthCore.Engine.UI.Panels;
internal static class RynthChatFiltersPanel
{
private static readonly IBrush PanelBg = new SolidColorBrush(Color.FromArgb(0xF2, 0x0A, 0x12, 0x1A));
private static readonly IBrush FieldBg = new SolidColorBrush(Color.FromArgb(0xFF, 0x0A, 0x12, 0x1A));
private static readonly IBrush FieldBorder = new SolidColorBrush(Color.FromArgb(0xFF, 0x26, 0x40, 0x59));
private static readonly IBrush AccentBg = new SolidColorBrush(Color.FromArgb(0xFF, 0x26, 0x4C, 0x59));
private static readonly IBrush ButtonBg = new SolidColorBrush(Color.FromArgb(0xFF, 0x0F, 0x1F, 0x2E));
internal static Control Create()
{
RynthChatPanel.EnsureSettingsLoaded();
var hint = new TextBlock
{
Text = "Regex rules, case-insensitive — FIRST match wins (reorder with ▲▼).\n" +
"Tab set: matching lines move to that tab (still visible in All).\n" +
"Tab empty: matching lines are hidden everywhere.",
FontSize = 9,
Foreground = Brushes.Gray,
Margin = new Thickness(4, 4, 4, 2),
};
var rows = new StackPanel { Orientation = Orientation.Vertical, Spacing = 4, Margin = new Thickness(4) };
var addBtn = new Button
{
Content = "+ Add filter",
FontSize = 10,
Padding = new Thickness(8, 3),
Margin = new Thickness(4, 2, 4, 6),
Background = AccentBg,
Foreground = Brushes.White,
BorderThickness = new Thickness(0),
};
var layout = new DockPanel { Background = PanelBg };
DockPanel.SetDock(hint, Dock.Top);
DockPanel.SetDock(addBtn, Dock.Bottom);
layout.Children.Add(hint);
layout.Children.Add(addBtn);
layout.Children.Add(new ScrollViewer
{
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
Content = rows,
});
void RebuildRows()
{
var filters = RynthChatPanel.Filters;
rows.Children.Clear();
for (int i = 0; i < filters.Count; i++)
{
var r = filters[i];
int index = i;
var enabledCheck = new CheckBox
{
IsChecked = r.Enabled,
Margin = new Thickness(0, 0, 2, 0),
VerticalAlignment = VerticalAlignment.Center,
};
enabledCheck.IsCheckedChanged += (_, _) =>
{
r.Enabled = enabledCheck.IsChecked == true;
RynthChatPanel.NotifyFiltersChanged();
};
var patternBox = new TextBox
{
Text = r.Pattern,
Watermark = "regex (e.g. AutoRun)",
FontSize = 10,
MinWidth = 220,
Height = 24,
Background = FieldBg,
Foreground = Brushes.White,
BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder,
BorderThickness = new Thickness(1),
};
ScrollViewer.SetHorizontalScrollBarVisibility(patternBox, ScrollBarVisibility.Disabled);
ScrollViewer.SetVerticalScrollBarVisibility(patternBox, ScrollBarVisibility.Disabled);
patternBox.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
patternBox.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false;
patternBox.TextChanged += (_, _) =>
{
r.Pattern = patternBox.Text ?? "";
r.Recompile();
patternBox.BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder;
RynthChatPanel.NotifyFiltersChanged();
};
var tabBox = new TextBox
{
Text = r.Tab,
Watermark = "tab (empty = hide)",
FontSize = 10,
Width = 120,
Height = 24,
Background = FieldBg,
Foreground = Brushes.White,
BorderBrush = FieldBorder,
BorderThickness = new Thickness(1),
};
ScrollViewer.SetHorizontalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled);
ScrollViewer.SetVerticalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled);
tabBox.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
tabBox.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false;
tabBox.TextChanged += (_, _) =>
{
r.Tab = (tabBox.Text ?? "").Trim();
RynthChatPanel.NotifyFiltersChanged();
};
Button SmallBtn(string label, IBrush fg) => new()
{
Content = label,
FontSize = 10,
Padding = new Thickness(5, 2),
Background = ButtonBg,
Foreground = fg,
BorderThickness = new Thickness(0),
VerticalAlignment = VerticalAlignment.Center,
};
var upBtn = SmallBtn("▲", Brushes.White);
upBtn.IsEnabled = index > 0;
upBtn.Click += (_, _) =>
{
if (index <= 0) return;
filters.RemoveAt(index);
filters.Insert(index - 1, r);
RebuildRows();
RynthChatPanel.NotifyFiltersChanged();
};
var downBtn = SmallBtn("▼", Brushes.White);
downBtn.IsEnabled = index < filters.Count - 1;
downBtn.Click += (_, _) =>
{
if (index >= filters.Count - 1) return;
filters.RemoveAt(index);
filters.Insert(index + 1, r);
RebuildRows();
RynthChatPanel.NotifyFiltersChanged();
};
var delBtn = SmallBtn("Delete", Brushes.IndianRed);
delBtn.Click += (_, _) =>
{
filters.Remove(r);
RebuildRows();
RynthChatPanel.NotifyFiltersChanged();
};
rows.Children.Add(new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 4,
Children = { enabledCheck, patternBox, tabBox, upBtn, downBtn, delBtn },
});
}
if (filters.Count == 0)
{
rows.Children.Add(new TextBlock
{
Text = "No filters yet — click \"+ Add filter\".",
FontSize = 10,
Foreground = Brushes.Gray,
Margin = new Thickness(2, 6),
});
}
}
addBtn.Click += (_, _) =>
{
var rule = new RynthChatPanel.ChatFilterRule();
rule.Recompile();
RynthChatPanel.Filters.Add(rule);
RebuildRows();
// Empty pattern is inert until typed — no display change yet, but
// persist the row so it survives a relaunch mid-edit.
RynthChatPanel.NotifyFiltersChanged();
};
RebuildRows();
return layout;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,330 @@
// ============================================================================
// RynthCore.Engine — UI/Panels/RynthNavPanel.cs
// Avalonia bar panel for the RynthNav plugin (mesh navigation). Bridges to the
// plugin DLL via GetProcAddress: polls a status JSON and drives load/test/preview.
// This is the only visible RynthNav surface in Decal-coexistence mode (ImGui and
// the Nav3D world overlay are both unavailable there).
//
// Bridge exports (resolved from the RynthNav plugin DLL):
// RynthNavGetStatusJson() → ANSI JSON status
// RynthNavLoadTile() → load current landblock's baked tile
// RynthNavTestQuery() → FindNearestPoly at the player
// RynthNavPreviewPath(char* loc) → preview a route to a /loc coordinate
// ============================================================================
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Shapes;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using RynthCore.Engine.ImGuiBackend;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Panels;
internal static class RynthNavPanel
{
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetStatusJsonFn();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void VoidFn();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void PreviewFn(IntPtr ansiCoord);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void MoveFn(int cmd);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void GotoFn(IntPtr ansiCoord);
private static GetStatusJsonFn? _getStatus;
private static VoidFn? _loadTile;
private static VoidFn? _testQuery;
private static PreviewFn? _preview;
private static MoveFn? _move;
private static GotoFn? _goto;
private static bool _bindingLogged;
// ── Palette (matches RynthAiPanel) ──────────────────────────────────────────
private static readonly IBrush ColTeal = new SolidColorBrush(Color.FromRgb(0x26, 0xD9, 0xE6));
private static readonly IBrush ColGreen = new SolidColorBrush(Color.FromRgb(0x40, 0xD9, 0x73));
private static readonly IBrush ColAmber = new SolidColorBrush(Color.FromRgb(0xE8, 0xB3, 0x33));
private static readonly IBrush ColRed = new SolidColorBrush(Color.FromRgb(0xD9, 0x55, 0x55));
private static readonly IBrush ColMute = new SolidColorBrush(Color.FromRgb(0x8C, 0xA6, 0xBF));
private static readonly IBrush ColText = Brushes.White;
private static readonly IBrush ColShellBg = new SolidColorBrush(Color.FromRgb(0x0A, 0x0F, 0x14));
private static readonly IBrush ColPanelBg = new SolidColorBrush(Color.FromRgb(0x0A, 0x12, 0x1A));
private static readonly IBrush ColBtnFill = new SolidColorBrush(Color.FromRgb(0x0F, 0x1F, 0x2E));
private static readonly IBrush ColBtnBord = new SolidColorBrush(Color.FromRgb(0x26, 0x40, 0x59));
private static readonly IBrush ColSep = new SolidColorBrush(Color.FromRgb(0x1A, 0x2A, 0x39));
// ── Controls (UI thread only) ───────────────────────────────────────────────
private static Ellipse? _dot;
private static TextBlock? _playerVal, _meshVal, _statusVal, _pathVal;
private static TextBox? _coordBox;
private static Button? _fwdBtn, _backBtn, _leftBtn, _rightBtn;
internal static Control Create()
{
TryBind();
var root = new StackPanel { Orientation = Orientation.Vertical, Margin = new Thickness(10), Spacing = 5, MinWidth = 300 };
// Title
var title = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };
_dot = new Ellipse { Width = 9, Height = 9, Fill = ColMute, VerticalAlignment = VerticalAlignment.Center };
title.Children.Add(_dot);
title.Children.Add(new TextBlock { Text = "RynthNav", FontSize = 15, FontWeight = FontWeight.Bold, Foreground = ColTeal });
title.Children.Add(new TextBlock { Text = "mesh nav · v0.2", FontSize = 10, Foreground = ColMute, VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(2, 0, 0, 2) });
root.Children.Add(title);
root.Children.Add(Sep());
// Status block
_playerVal = ValueRow(root, "Player");
_meshVal = ValueRow(root, "Navmesh");
_statusVal = new TextBlock { Text = "—", FontSize = 11, Foreground = ColMute, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 1, 0, 0) };
root.Children.Add(_statusVal);
root.Children.Add(Sep());
// Movement d-pad (each tap is marshaled to the plugin tick thread)
root.Children.Add(new TextBlock { Text = "MOVE", FontSize = 9, FontWeight = FontWeight.Bold, Foreground = ColTeal, Margin = new Thickness(0, 2, 0, 1) });
root.Children.Add(BuildDpad());
root.Children.Add(new TextBlock { Text = "tap ▲▼ run · tap ◄► turn (tap again to stop) · ■ stop", FontSize = 9, Foreground = ColMute, HorizontalAlignment = HorizontalAlignment.Center });
root.Children.Add(Sep());
// Actions
var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 0 };
actions.Children.Add(Btn("Load tile", () => { TryBind(); _loadTile?.Invoke(); }));
actions.Children.Add(Btn("Test @ me", () => { TryBind(); _testQuery?.Invoke(); }));
root.Children.Add(actions);
root.Children.Add(Sep());
// Goto preview
root.Children.Add(new TextBlock { Text = "PREVIEW ROUTE", FontSize = 9, FontWeight = FontWeight.Bold, Foreground = ColTeal, Margin = new Thickness(0, 2, 0, 1) });
var gotoRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
_coordBox = new TextBox
{
Watermark = "42.5N, 33.6E",
FontSize = 12,
Width = 150,
FontFamily = new FontFamily("Consolas,monospace"),
VerticalAlignment = VerticalAlignment.Center,
};
_coordBox.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
_coordBox.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false;
gotoRow.Children.Add(_coordBox);
gotoRow.Children.Add(Btn("Preview", Preview));
gotoRow.Children.Add(Btn("Go ▶", Go));
root.Children.Add(gotoRow);
_pathVal = new TextBlock { Text = "", FontSize = 12, Foreground = ColText, FontWeight = FontWeight.SemiBold, Margin = new Thickness(0, 1, 0, 0) };
root.Children.Add(_pathVal);
root.Children.Add(new TextBlock { Text = "Go ▶ walks the navmesh path · ■ (or any d-pad tap) stops", FontSize = 9, Foreground = ColMute, Margin = new Thickness(0, 6, 0, 0) });
// Poll the plugin for status (UI thread).
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
timer.Tick += (_, _) =>
{
if (_getStatus == null) TryBind();
Refresh();
};
var outer = new Border { Background = ColShellBg, CornerRadius = new CornerRadius(5), Child = new ScrollViewer { Content = root } };
outer.AttachedToVisualTree += (_, _) => timer.Start();
outer.DetachedFromVisualTree += (_, _) => timer.Stop();
return outer;
}
private static void Refresh()
{
if (_getStatus == null) { if (_dot != null) _dot.Fill = ColMute; return; }
IntPtr ptr;
try { ptr = _getStatus(); } catch { return; }
if (ptr == IntPtr.Zero) return;
string? json = Marshal.PtrToStringAnsi(ptr);
if (string.IsNullOrEmpty(json)) return;
try
{
using var doc = JsonDocument.Parse(json);
var r = doc.RootElement;
bool hasPose = r.TryGetProperty("hasPose", out var v) && v.GetInt32() != 0;
string lb = r.TryGetProperty("landblock", out v) ? v.GetString() ?? "----" : "----";
double ns = r.TryGetProperty("ns", out v) ? v.GetDouble() : 0;
double ew = r.TryGetProperty("ew", out v) ? v.GetDouble() : 0;
bool loaded = r.TryGetProperty("tileLoaded", out v) && v.GetInt32() != 0;
string loadLb = r.TryGetProperty("loadedLb", out v) ? v.GetString() ?? "----" : "----";
int polys = r.TryGetProperty("polyCount", out v) ? v.GetInt32() : 0;
string status = r.TryGetProperty("status", out v) ? v.GetString() ?? "" : "";
string path = r.TryGetProperty("lastPath", out v) ? v.GetString() ?? "" : "";
// Change-detection: only touch a control when its value actually changed,
// so an idle panel issues zero invalidations (no GDI-overlay flicker).
SetText(_playerVal, hasPose ? $"0x{lb} {Loc(ns, 'N', 'S')} {Loc(ew, 'E', 'W')}" : "— no pose —");
SetText(_meshVal, loaded ? $"LOADED 0x{loadLb} · {polys} polys" : "not loaded");
SetFg(_meshVal, loaded ? ColGreen : ColAmber);
SetFill(_dot, loaded ? ColGreen : (hasPose ? ColAmber : ColMute));
SetText(_statusVal, status);
SetText(_pathVal, string.IsNullOrEmpty(path) ? "" : "↳ " + path);
int run = r.TryGetProperty("runState", out v) ? v.GetInt32() : 0;
int turn = r.TryGetProperty("turnState", out v) ? v.GetInt32() : 0;
SetBg(_fwdBtn, run == 1 ? ColGreen : ColBtnFill);
SetBg(_backBtn, run == 2 ? ColGreen : ColBtnFill);
SetBg(_leftBtn, turn == -1 ? ColGreen : ColBtnFill);
SetBg(_rightBtn, turn == 1 ? ColGreen : ColBtnFill);
}
catch { /* transient partial JSON — ignore */ }
}
private static void Preview()
{
TryBind();
if (_preview == null) return;
string txt = _coordBox?.Text ?? "";
IntPtr p = Marshal.StringToHGlobalAnsi(txt);
try { _preview(p); }
finally { Marshal.FreeHGlobal(p); }
}
private static void Go()
{
TryBind();
if (_goto == null) return;
string txt = _coordBox?.Text ?? "";
IntPtr p = Marshal.StringToHGlobalAnsi(txt);
try { _goto(p); }
finally { Marshal.FreeHGlobal(p); }
}
// ── Plugin binding ──────────────────────────────────────────────────────────
// RL loads fresh plugin copies without unloading the old ones: drop the
// exports bound below so the next poll re-binds to the live copy.
static RynthNavPanel() => PluginManager.PluginsUnloaded += () =>
{
_getStatus = null;
_loadTile = null;
_testQuery = null;
_preview = null;
_move = null;
_goto = null;
};
private static void TryBind()
{
LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault(
p => p.DisplayName.Contains("RynthNav", StringComparison.OrdinalIgnoreCase));
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
_getStatus ??= Bind<GetStatusJsonFn>(plugin, "RynthNavGetStatusJson");
_loadTile ??= Bind<VoidFn>(plugin, "RynthNavLoadTile");
_testQuery ??= Bind<VoidFn>(plugin, "RynthNavTestQuery");
_preview ??= Bind<PreviewFn>(plugin, "RynthNavPreviewPath");
_move ??= Bind<MoveFn>(plugin, "RynthNavMove");
_goto ??= Bind<GotoFn>(plugin, "RynthNavGoto");
if (!_bindingLogged && _getStatus != null)
{
_bindingLogged = true;
RynthLog.UI("RynthNavPanel: bound RynthNav plugin exports.");
}
}
private static T? Bind<T>(LoadedPlugin plugin, string export) where T : Delegate
{
IntPtr addr = GetProcAddress(plugin.ModuleHandle, export);
return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr);
}
// ── UI helpers ──────────────────────────────────────────────────────────────
private static TextBlock ValueRow(StackPanel parent, string label)
{
var lbl = new TextBlock { Text = label, FontSize = 10, Foreground = ColMute, Width = 58, VerticalAlignment = VerticalAlignment.Center };
var val = new TextBlock { Text = "—", FontSize = 12, Foreground = ColText, FontWeight = FontWeight.SemiBold, FontFamily = new FontFamily("Consolas,monospace"), VerticalAlignment = VerticalAlignment.Center };
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
row.Children.Add(lbl);
row.Children.Add(val);
parent.Children.Add(row);
return val;
}
private static Button Btn(string text, Action onClick)
{
var b = new Button
{
Content = text,
FontSize = 11,
Foreground = ColText,
Background = ColBtnFill,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(3),
Padding = new Thickness(9, 3, 9, 3),
Margin = new Thickness(0, 0, 6, 0),
};
b.Click += (_, _) => onClick();
return b;
}
private static Border Sep() => new() { Height = 1, Background = ColSep, Margin = new Thickness(0, 3, 0, 3) };
private static Control BuildDpad()
{
var pad = new Grid
{
HorizontalAlignment = HorizontalAlignment.Center,
ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto"),
RowDefinitions = new RowDefinitions("Auto,Auto,Auto"),
};
_fwdBtn = MoveBtn("▲", "Forward (tap to run / stop)", 1);
_leftBtn = MoveBtn("◄", "Turn left (tap to start / stop)", 3);
var stop = MoveBtn("■", "Stop everything", 5);
_rightBtn = MoveBtn("►", "Turn right (tap to start / stop)", 4);
_backBtn = MoveBtn("▼", "Backward (tap to walk back / stop)", 2);
Place(pad, _fwdBtn, 0, 1);
Place(pad, _leftBtn, 1, 0);
Place(pad, stop, 1, 1);
Place(pad, _rightBtn, 1, 2);
Place(pad, _backBtn, 2, 1);
return pad;
}
private static void Place(Grid g, Control c, int row, int col)
{
Grid.SetRow(c, row);
Grid.SetColumn(c, col);
g.Children.Add(c);
}
private static Button MoveBtn(string glyph, string tip, int cmd)
{
var b = new Button
{
Content = glyph,
FontSize = 18,
Width = 58,
Height = 42,
Foreground = ColText,
Background = ColBtnFill,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(5),
Margin = new Thickness(3),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
};
ToolTip.SetTip(b, tip);
b.Click += (_, _) => { TryBind(); _move?.Invoke(cmd); };
return b;
}
private static void SetText(TextBlock? tb, string s) { if (tb != null && !string.Equals(tb.Text, s, StringComparison.Ordinal)) tb.Text = s; }
private static void SetFg(TextBlock? tb, IBrush br) { if (tb != null && !ReferenceEquals(tb.Foreground, br)) tb.Foreground = br; }
private static void SetBg(Button? b, IBrush br) { if (b != null && !ReferenceEquals(b.Background, br)) b.Background = br; }
private static void SetFill(Ellipse? e, IBrush br) { if (e != null && !ReferenceEquals(e.Fill, br)) e.Fill = br; }
private static string Loc(double v, char pos, char neg)
=> v.ToString("F1", CultureInfo.InvariantCulture).TrimStart('-') + (v >= 0 ? pos : neg);
}

View file

@ -0,0 +1,302 @@
// ============================================================================
// RynthCore.Engine — UI/Panels/RynthTrackerPanel.cs
// Session-stats panel backed by the RynthTracker plugin (RynthSuite).
//
// Bridge exports (resolved from the RynthTracker plugin DLL via GetProcAddress):
// RynthTrackerGetSnapshotJson() → ANSI JSON object, polled every 500ms
// RynthTrackerReset() → resets session counters + timer
// ============================================================================
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Panels;
internal static class RynthTrackerPanel
{
// ── P/Invoke ──────────────────────────────────────────────────────────────
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr GetSnapshotJsonFn();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ResetFn();
// ── Bridge state ──────────────────────────────────────────────────────────
private static GetSnapshotJsonFn? _getSnapshotJson;
private static ResetFn? _reset;
private static bool _bindingLogged;
// ── Persisted settings ────────────────────────────────────────────────────
private static byte _bgAlpha = 0xCC; // ~80% default
// ── Panel construction ────────────────────────────────────────────────────
internal static Control Create()
{
LoadSettings();
TryBind();
// ── Value TextBlocks (updated by poll timer) ───────────────────
// Rates first — most important at the top when panel is tiny.
var sessionVal = Val();
var xpHrVal = Val();
var lumHrVal = Val();
var killHrVal = Val();
var xpVal = Val();
var lumVal = Val();
var killVal = Val();
var xpkVal = Val();
var deathVal = Val();
// ── Background brush — only this changes with the slider ───────
SolidColorBrush MakeBg() => new(Color.FromArgb(_bgAlpha, 0x0A, 0x12, 0x1A));
var stack = new StackPanel
{
Orientation = Orientation.Vertical,
Background = MakeBg(),
};
// ── Opacity slider ─────────────────────────────────────────────
var opacitySlider = new Slider
{
Minimum = 0,
Maximum = 100,
Value = Math.Round(_bgAlpha / 2.55),
Padding = new Thickness(0),
Margin = new Thickness(4, 0, 4, 0),
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Stretch,
};
opacitySlider.ValueChanged += (_, e) =>
{
_bgAlpha = (byte)Math.Round(e.NewValue * 2.55);
stack.Background = MakeBg();
SaveSettings();
};
// ── Reset button ───────────────────────────────────────────────
var resetBtn = new Button
{
Content = "R",
FontSize = 8,
Padding = new Thickness(4, 1),
Background = new SolidColorBrush(Color.FromArgb(0xFF, 0x1A, 0x2E, 0x40)),
Foreground = Brushes.White,
BorderBrush = new SolidColorBrush(Color.FromArgb(0xFF, 0x26, 0x4C, 0x59)),
BorderThickness = new Thickness(1),
VerticalAlignment = VerticalAlignment.Center,
};
resetBtn.Click += (_, _) => _reset?.Invoke();
// ── Title row: [Tracker] [===slider===] [R] ────────────────────
var titleText = new TextBlock
{
Text = "Tracker",
FontSize = 9,
FontWeight = FontWeight.SemiBold,
Foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0xE6, 0xB4, 0x50)),
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 4, 0),
};
var titleRow = new DockPanel { Margin = new Thickness(4, 2, 4, 2) };
DockPanel.SetDock(resetBtn, Dock.Right);
DockPanel.SetDock(titleText, Dock.Left);
titleRow.Children.Add(resetBtn);
titleRow.Children.Add(titleText);
titleRow.Children.Add(opacitySlider); // LastChildFill = slider
// ── Stat rows ──────────────────────────────────────────────────
stack.Children.Add(titleRow);
stack.Children.Add(Row("Session", sessionVal));
stack.Children.Add(Row("XP/hr", xpHrVal));
stack.Children.Add(Row("Lum/hr", lumHrVal));
stack.Children.Add(Row("Kls/hr", killHrVal));
stack.Children.Add(Row("XP", xpVal));
stack.Children.Add(Row("Lum", lumVal));
stack.Children.Add(Row("Kills", killVal));
stack.Children.Add(Row("XP/kl", xpkVal));
stack.Children.Add(Row("Deaths", deathVal));
// ── Root: clip content when panel is shrunk below content height
var root = new Grid { ClipToBounds = true };
root.Children.Add(stack);
// ── Poll timer (500ms) ─────────────────────────────────────────
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
timer.Tick += (_, _) =>
{
if (_getSnapshotJson == null) { TryBind(); return; }
IntPtr ptr = _getSnapshotJson();
if (ptr == IntPtr.Zero) return;
string? json = Marshal.PtrToStringAnsi(ptr);
if (string.IsNullOrEmpty(json)) return;
try
{
using var doc = JsonDocument.Parse(json);
var r = doc.RootElement;
double ss = r.TryGetProperty("ss", out var v) ? v.GetDouble() : 0;
long xt = r.TryGetProperty("xt", out v) ? v.GetInt64() : 0;
long xh = r.TryGetProperty("xh", out v) ? v.GetInt64() : 0;
long lt = r.TryGetProperty("lt", out v) ? v.GetInt64() : 0;
long lh = r.TryGetProperty("lh", out v) ? v.GetInt64() : 0;
int kt = r.TryGetProperty("kt", out v) ? v.GetInt32() : 0;
double kh = r.TryGetProperty("kh", out v) ? v.GetDouble() : 0;
long xk = r.TryGetProperty("xk", out v) ? v.GetInt64() : 0;
int dt = r.TryGetProperty("dt", out v) ? v.GetInt32() : 0;
var ic = System.Globalization.CultureInfo.InvariantCulture;
sessionVal.Text = FormatTime(ss);
xpHrVal.Text = FormatNum(xh);
lumHrVal.Text = FormatNum(lh);
killHrVal.Text = kh.ToString("F1", ic);
xpVal.Text = FormatNum(xt);
lumVal.Text = FormatNum(lt);
killVal.Text = kt.ToString();
xpkVal.Text = FormatNum(xk);
deathVal.Text = dt.ToString();
}
catch { }
};
timer.Start();
// Stop with the visual tree — a running DispatcherTimer roots the closed
// view forever (one immortal poller per open/close). RadarPanel idiom;
// must restart on attach: drag/resize fires Detached→Attached.
root.AttachedToVisualTree += (_, _) => { if (!timer.IsEnabled) timer.Start(); };
root.DetachedFromVisualTree += (_, _) => timer.Stop();
return root;
}
// ── Helpers ───────────────────────────────────────────────────────────────
// One stat row: label (left, auto-width) + value (right-aligned, fills rest).
private static Control Row(string labelText, TextBlock value)
{
var grid = new Grid { Margin = new Thickness(4, 1, 4, 1) };
grid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Auto));
grid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
var label = new TextBlock
{
Text = labelText,
FontSize = 9,
Foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0x99, 0x99, 0x99)),
Margin = new Thickness(0, 0, 6, 0),
};
Grid.SetColumn(label, 0);
Grid.SetColumn(value, 1);
grid.Children.Add(label);
grid.Children.Add(value);
return grid;
}
private static TextBlock Val() => new()
{
Text = "—",
FontSize = 9,
FontFamily = new FontFamily("Consolas,Courier New,monospace"),
Foreground = Brushes.White,
HorizontalAlignment = HorizontalAlignment.Right,
};
private static string FormatTime(double totalSeconds)
{
var ts = TimeSpan.FromSeconds(totalSeconds);
return ts.TotalHours >= 1
? $"{(int)ts.TotalHours}:{ts.Minutes:D2}:{ts.Seconds:D2}"
: $"{ts.Minutes}:{ts.Seconds:D2}";
}
private static string FormatNum(long value)
{
if (value == 0) return "0";
bool neg = value < 0;
string s = (neg ? -value : value).ToString();
var sb = new System.Text.StringBuilder(s.Length + s.Length / 3);
int offset = s.Length % 3;
for (int i = 0; i < s.Length; i++)
{
if (i > 0 && (i - offset) % 3 == 0) sb.Append(',');
sb.Append(s[i]);
}
return neg ? "-" + sb : sb.ToString();
}
// RL loads fresh plugin copies without unloading the old ones: drop the
// exports bound below so the next poll re-binds to the live copy.
static RynthTrackerPanel() => PluginManager.PluginsUnloaded += () =>
{
_getSnapshotJson = null;
_reset = null;
};
private static void TryBind()
{
LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault(
p => p.DisplayName.Contains("RynthTracker", StringComparison.OrdinalIgnoreCase));
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
_getSnapshotJson ??= Bind<GetSnapshotJsonFn>(plugin, "RynthTrackerGetSnapshotJson");
_reset ??= Bind<ResetFn>(plugin, "RynthTrackerReset");
if (!_bindingLogged && _getSnapshotJson != null)
{
_bindingLogged = true;
RynthLog.UI("RynthTrackerPanel: bound RynthTracker plugin exports.");
}
}
private static T? Bind<T>(LoadedPlugin plugin, string exportName) where T : Delegate
{
IntPtr addr = GetProcAddress(plugin.ModuleHandle, exportName);
return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr);
}
// ── Settings persistence ──────────────────────────────────────────────────
private static string SettingsPath =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore", "rynthtracker_settings.json");
private static void LoadSettings()
{
try
{
string path = SettingsPath;
if (!File.Exists(path)) return;
using var doc = JsonDocument.Parse(File.ReadAllText(path));
if (doc.RootElement.TryGetProperty("bgAlpha", out var v))
_bgAlpha = (byte)Math.Clamp(v.GetInt32(), 0, 255);
}
catch { }
}
private static void SaveSettings()
{
try
{
string path = SettingsPath;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, $"{{\"bgAlpha\":{_bgAlpha}}}");
}
catch { }
}
}

View file

@ -0,0 +1,422 @@
// ============================================================================
// RynthCore.Engine — UI/Panels/RynthVisionPanel.cs
// Avalonia settings panel for the RynthVision plugin (RynthSuite). Bridges to
// the plugin via GetProcAddress on its DLL: reads settings JSON to populate
// controls and pushes changes back. Replaces the abandoned in-plugin ImGui UI.
//
// Bridge exports (resolved from the RynthVision plugin DLL):
// RynthVisionGetSettingsJson() → ANSI JSON of current settings
// RynthVisionSetSettings(char* json) → apply + persist settings
// RynthVisionInspectTerrain() → log terrain types under the player
// ============================================================================
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using RynthCore.Engine.ImGuiBackend;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Panels;
internal static class RynthVisionPanel
{
// ── P/Invoke ──────────────────────────────────────────────────────────────
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr GetSettingsJsonFn();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void SetSettingsFn(IntPtr ansiJson);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void InspectFn();
// ── Bridge state ──────────────────────────────────────────────────────────
private static GetSettingsJsonFn? _getSettings;
private static SetSettingsFn? _setSettings;
private static InspectFn? _inspect;
private static bool _bindingLogged;
// ── Controls (Avalonia UI thread only) ─────────────────────────────────────
private static CheckBox? _cbRadar, _cbSlopes, _cbWater, _cbWaterAnyCorner, _cbWaterImpassableOnly;
private static Slider? _slRange, _slThick, _slHeight, _slSlopeR, _slWaterR, _slSlopeFloor, _slSlopeBias;
private static TextBox? _tbSlope, _tbWater, _tbRadar, _tbWaterTypes;
private static Border? _swSlope, _swWater, _swRadar;
private static uint _slopeColor = 0x60FF2020;
private static uint _waterColor = 0x600060FF;
private static uint _radarColor = 0x80FFD000;
private static bool _suppressPush;
private static bool _populated;
private static int _createCounter;
// ── Panel construction ──────────────────────────────────────────────────────
internal static Control Create()
{
// The static `_populated` flag survives between panel closes/reopens, so
// without resetting we'd skip Populate() on every reopen — the newly
// constructed controls would sit at their Avalonia defaults (slider=min,
// checkbox=null, textbox=empty), and the next user edit would Push()
// those defaults to disk, blanking the saved settings.
//
// Suppress push until the first successful Populate. Without this, any
// change-event fired during/before Populate (Avalonia raises
// IsCheckedChanged when IsChecked transitions null→true/false, even when
// we set it programmatically) writes Avalonia defaults over the JSON.
// Populate flips _suppressPush back to false in its finally block.
_populated = false;
_suppressPush = true;
int createN = System.Threading.Interlocked.Increment(ref _createCounter);
RynthLog.UI($"RynthVisionPanel.Create #{createN}: starting (_populated reset, _suppressPush=true)");
var root = new StackPanel { Orientation = Orientation.Vertical, Margin = new Thickness(8), Spacing = 3 };
root.Children.Add(Header("Overlays"));
_cbRadar = AddCheck(root, "Radar range ring");
_cbSlopes = AddCheck(root, "Unclimbable slopes");
_cbWater = AddCheck(root, "Impassable water");
var dungeon = AddCheck(root, "Dungeon lighting (planned)");
dungeon.IsEnabled = false;
_cbRadar.IsCheckedChanged += (_, _) => Push();
_cbSlopes.IsCheckedChanged += (_, _) => Push();
_cbWater.IsCheckedChanged += (_, _) => Push();
root.Children.Add(Header("Colors (hex AARRGGBB)"));
(_tbSlope, _swSlope) = AddColorRow(root, "Slope", () => _slopeColor, c => _slopeColor = c);
(_tbWater, _swWater) = AddColorRow(root, "Water", () => _waterColor, c => _waterColor = c);
(_tbRadar, _swRadar) = AddColorRow(root, "Radar", () => _radarColor, c => _radarColor = c);
root.Children.Add(Header("Tuning"));
(_slRange, _) = AddSlider(root, "Radar range", 24, 300, 0, false);
(_slThick, _) = AddSlider(root, "Ring thickness", 0.5, 6, 1, false);
(_slHeight, _) = AddSlider(root, "Ring height (m)",0.5, 30, 1, false);
(_slSlopeR, _) = AddSlider(root, "Slope radius (cells)", 1, 24, 0, true);
(_slSlopeFloor, _)= AddSlider(root, "Slope floor Z", 0.30, 0.95, 3, false);
(_slSlopeBias, _) = AddSlider(root, "Slope height bias (m)",0.00, 1.00, 2, false);
(_slWaterR, _) = AddSlider(root, "Water radius (cells)", 1, 24, 0, true);
root.Children.Add(Header("Water terrain types"));
_cbWaterAnyCorner = AddCheck(root, "Highlight cell if ANY corner is water (else all four)");
_cbWaterAnyCorner.IsCheckedChanged += (_, _) => Push();
_cbWaterImpassableOnly = AddCheck(root, "Only paint water cells with an unwalkable triangle (real impassable)");
_cbWaterImpassableOnly.IsCheckedChanged += (_, _) => Push();
_tbWaterTypes = new TextBox { Watermark = "18,19,20", FontSize = 11, MinWidth = 120 };
_tbWaterTypes.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
_tbWaterTypes.LostFocus += (_, _) => { Win32Backend.AvaloniaTextInputActive = false; Push(); };
var applyBtn = new Button { Content = "Apply", FontSize = 11, Margin = new Thickness(4, 0, 0, 0) };
applyBtn.Click += (_, _) => Push();
var wtRow = new StackPanel { Orientation = Orientation.Horizontal };
wtRow.Children.Add(_tbWaterTypes);
wtRow.Children.Add(applyBtn);
root.Children.Add(wtRow);
var inspectBtn = new Button { Content = "Log terrain types here", FontSize = 11, Margin = new Thickness(0, 4, 0, 0) };
inspectBtn.Click += (_, _) => { TryBind(); _inspect?.Invoke(); };
root.Children.Add(inspectBtn);
// Bind + populate once the plugin DLL is loaded AND the plugin has
// finished initializing its settings (Runtime.Plugin is non-null on
// the plugin side). Until then, GetSettingsJson() returns "{}" and
// populating from that would blank every control — and the first
// user edit would Push() those blanks over the real saved JSON.
// Retries every 500 ms until Populate succeeds (returns true) or the
// panel is closed. Caps at 60 retries (~30 s) so we don't spin forever
// if the plugin never initializes.
int retries = 0;
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
timer.Tick += (_, _) =>
{
if (_populated) { timer.Stop(); return; }
if (++retries > 60) { timer.Stop(); RynthLog.UI("RynthVisionPanel: gave up populating after 30s"); return; }
TryBind();
if (_getSettings != null && Populate())
{
_populated = true;
timer.Stop();
}
};
timer.Start();
return new ScrollViewer { Content = root };
}
// ── Control factories ───────────────────────────────────────────────────────
private static TextBlock Header(string text) => new()
{
Text = text,
FontSize = 10,
FontWeight = FontWeight.Bold,
Foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0x7A, 0xB8, 0xF5)),
Margin = new Thickness(0, 6, 0, 1),
};
private static CheckBox AddCheck(StackPanel parent, string label)
{
var cb = new CheckBox { Content = label, FontSize = 11, Foreground = Brushes.White };
parent.Children.Add(cb);
return cb;
}
private static (Slider, TextBlock) AddSlider(StackPanel parent, string name, double min, double max, int decimals, bool snap)
{
var label = new TextBlock { FontSize = 11, Foreground = Brushes.White, Text = name + ":" };
var slider = new Slider { Minimum = min, Maximum = max, Width = 170, VerticalAlignment = VerticalAlignment.Center };
if (snap) { slider.TickFrequency = 1; slider.IsSnapToTickEnabled = true; }
// Companion textbox: lets the user type exact values (matters for the
// narrow-range tunables like Slope floor Z 0.30–0.95 where a single
// pixel of slider travel is meaningful). Kept two-way synced via the
// `syncing` flag so updating one side doesn't loop back through the
// other side's change handler.
string fmt = "F" + decimals;
var box = new TextBox
{
FontSize = 11,
Width = 64,
Margin = new Thickness(6, 0, 0, 0),
FontFamily = new FontFamily("Consolas,monospace"),
VerticalAlignment = VerticalAlignment.Center,
};
var row = new StackPanel { Orientation = Orientation.Horizontal };
row.Children.Add(slider);
row.Children.Add(box);
var stack = new StackPanel { Orientation = Orientation.Vertical };
stack.Children.Add(label);
stack.Children.Add(row);
parent.Children.Add(stack);
bool syncing = false;
slider.ValueChanged += (_, e) =>
{
string s = e.NewValue.ToString(fmt, CultureInfo.InvariantCulture);
label.Text = $"{name}: {s}";
if (syncing) { RynthLog.UI($"RynthVisionPanel.Slider[{name}].ValueChanged → {s} (syncing, no push)"); return; }
RynthLog.UI($"RynthVisionPanel.Slider[{name}].ValueChanged → {s}");
syncing = true;
box.Text = s;
syncing = false;
Push();
};
box.GotFocus += (_, _) =>
{
// Block AvaloniaSubclassWndProc from yanking focus back to the
// game HWND while the user is typing into this textbox.
Win32Backend.AvaloniaTextInputActive = true;
RynthLog.UI($"RynthVisionPanel.TextBox[{name}].GotFocus (text='{box.Text}')");
};
box.LostFocus += (_, _) =>
{
Win32Backend.AvaloniaTextInputActive = false;
RynthLog.UI($"RynthVisionPanel.TextBox[{name}].LostFocus (text='{box.Text}', syncing={syncing})");
if (syncing) return;
// Don't clobber the user's typed value on bad input — leave it
// visible so they can fix the typo without re-typing from scratch.
if (double.TryParse(box.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out double v))
{
v = Math.Clamp(v, min, max);
syncing = true;
slider.Value = v;
string s = v.ToString(fmt, CultureInfo.InvariantCulture);
box.Text = s;
label.Text = $"{name}: {s}";
syncing = false;
Push();
}
};
return (slider, label);
}
private static (TextBox, Border) AddColorRow(StackPanel parent, string name, Func<uint> get, Action<uint> set)
{
var lbl = new TextBlock { Text = name, FontSize = 11, Foreground = Brushes.White, Width = 44, VerticalAlignment = VerticalAlignment.Center };
var tb = new TextBox { FontSize = 11, Width = 92, FontFamily = new FontFamily("Consolas,monospace") };
var sw = new Border { Width = 22, Height = 16, BorderThickness = new Thickness(1), BorderBrush = Brushes.Gray, VerticalAlignment = VerticalAlignment.Center };
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
row.Children.Add(lbl);
row.Children.Add(tb);
row.Children.Add(sw);
parent.Children.Add(row);
tb.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
tb.LostFocus += (_, _) =>
{
Win32Backend.AvaloniaTextInputActive = false;
if (TryParseHex(tb.Text, out uint c)) { set(c); sw.Background = ToBrush(c); Push(); }
else tb.Text = get().ToString("X8"); // revert on bad input
};
return (tb, sw);
}
// ── Plugin binding ────────────────────────────────────────────────────────
// RL loads fresh plugin copies without unloading the old ones: drop the
// exports bound below so the next poll re-binds to the live copy.
static RynthVisionPanel() => PluginManager.PluginsUnloaded += () =>
{
_getSettings = null;
_setSettings = null;
_inspect = null;
};
private static void TryBind()
{
LoadedPlugin? plugin = PluginManager.Plugins.FirstOrDefault(
p => p.DisplayName.Contains("RynthVision", StringComparison.OrdinalIgnoreCase));
if (plugin == null || plugin.ModuleHandle == IntPtr.Zero) return;
_getSettings ??= Bind<GetSettingsJsonFn>(plugin, "RynthVisionGetSettingsJson");
_setSettings ??= Bind<SetSettingsFn>(plugin, "RynthVisionSetSettings");
_inspect ??= Bind<InspectFn>(plugin, "RynthVisionInspectTerrain");
if (!_bindingLogged && _getSettings != null)
{
_bindingLogged = true;
RynthLog.UI("RynthVisionPanel: bound RynthVision plugin exports.");
}
}
private static T? Bind<T>(LoadedPlugin plugin, string export) where T : Delegate
{
IntPtr addr = GetProcAddress(plugin.ModuleHandle, export);
return addr == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer<T>(addr);
}
// ── Sync ──────────────────────────────────────────────────────────────────
/// <summary>
/// Reads the plugin's current settings JSON and applies it to the panel
/// controls. Returns true only when the JSON contained at least one
/// recognised field — an empty "{}" from a still-initializing plugin
/// returns false so the caller can retry rather than treating control
/// defaults as the authoritative state.
/// </summary>
private static bool Populate()
{
if (_getSettings == null) return false;
IntPtr ptr = _getSettings();
if (ptr == IntPtr.Zero) return false;
string? json = Marshal.PtrToStringAnsi(ptr);
if (string.IsNullOrEmpty(json) || json == "{}") return false;
RynthLog.UI($"RynthVisionPanel.Populate: applying JSON ({json.Length} chars): {json}");
try
{
using var doc = JsonDocument.Parse(json);
var r = doc.RootElement;
_suppressPush = true;
if (_cbRadar != null && r.TryGetProperty("radar", out var v)) _cbRadar.IsChecked = v.GetInt32() != 0;
if (_cbSlopes != null && r.TryGetProperty("slopes", out v)) _cbSlopes.IsChecked = v.GetInt32() != 0;
if (_cbWater != null && r.TryGetProperty("water", out v)) _cbWater.IsChecked = v.GetInt32() != 0;
if (_cbWaterAnyCorner != null && r.TryGetProperty("waterAnyCorner", out v))
_cbWaterAnyCorner.IsChecked = v.GetInt32() != 0;
if (_cbWaterImpassableOnly != null && r.TryGetProperty("waterImpassableOnly", out v))
_cbWaterImpassableOnly.IsChecked = v.GetInt32() != 0;
if (r.TryGetProperty("slopeColor", out v)) { _slopeColor = v.GetUInt32(); SetColor(_tbSlope, _swSlope, _slopeColor); }
if (r.TryGetProperty("waterColor", out v)) { _waterColor = v.GetUInt32(); SetColor(_tbWater, _swWater, _waterColor); }
if (r.TryGetProperty("radarColor", out v)) { _radarColor = v.GetUInt32(); SetColor(_tbRadar, _swRadar, _radarColor); }
if (_slRange != null && r.TryGetProperty("radarRange", out v)) _slRange.Value = v.GetDouble();
if (_slThick != null && r.TryGetProperty("ringThick", out v)) _slThick.Value = v.GetDouble();
if (_slHeight != null && r.TryGetProperty("ringHeight", out v)) _slHeight.Value = v.GetDouble();
if (_slSlopeR != null && r.TryGetProperty("slopeRadius", out v)) _slSlopeR.Value = v.GetInt32();
if (_slSlopeFloor!= null && r.TryGetProperty("slopeFloorZ",out v)) _slSlopeFloor.Value = v.GetDouble();
if (_slSlopeBias != null && r.TryGetProperty("slopeBias", out v)) _slSlopeBias.Value = v.GetDouble();
if (_slWaterR != null && r.TryGetProperty("waterRadius", out v)) _slWaterR.Value = v.GetInt32();
if (_tbWaterTypes != null && r.TryGetProperty("waterTypes", out v) && v.ValueKind == JsonValueKind.Array)
_tbWaterTypes.Text = string.Join(",", v.EnumerateArray().Select(e => e.GetInt32()));
}
catch (Exception ex) { RynthLog.UI($"RynthVisionPanel.Populate: parse failed: {ex.GetType().Name}: {ex.Message}"); return false; }
finally { _suppressPush = false; }
return true;
}
private static void Push()
{
if (_suppressPush)
{
RynthLog.UI("RynthVisionPanel.Push: SUPPRESSED (Populate in flight or panel not yet ready)");
return;
}
if (_setSettings == null)
{
RynthLog.UI("RynthVisionPanel.Push: SKIPPED (plugin not yet bound)");
return;
}
var ci = CultureInfo.InvariantCulture;
var sb = new StringBuilder(256);
sb.Append('{');
sb.Append("\"radar\":").Append(_cbRadar?.IsChecked == true ? 1 : 0).Append(',');
sb.Append("\"slopes\":").Append(_cbSlopes?.IsChecked == true ? 1 : 0).Append(',');
sb.Append("\"water\":").Append(_cbWater?.IsChecked == true ? 1 : 0).Append(',');
sb.Append("\"slopeColor\":").Append(_slopeColor).Append(',');
sb.Append("\"waterColor\":").Append(_waterColor).Append(',');
sb.Append("\"radarColor\":").Append(_radarColor).Append(',');
sb.Append("\"radarRange\":").Append((_slRange?.Value ?? 192).ToString("R", ci)).Append(',');
sb.Append("\"ringThick\":").Append((_slThick?.Value ?? 2).ToString("R", ci)).Append(',');
sb.Append("\"ringHeight\":").Append((_slHeight?.Value ?? 3).ToString("R", ci)).Append(',');
sb.Append("\"slopeRadius\":").Append((int)(_slSlopeR?.Value ?? 12)).Append(',');
sb.Append("\"slopeFloorZ\":").Append((_slSlopeFloor?.Value ?? 0.664).ToString("R", ci)).Append(',');
sb.Append("\"slopeBias\":").Append((_slSlopeBias?.Value ?? 0.15).ToString("R", ci)).Append(',');
sb.Append("\"waterRadius\":").Append((int)(_slWaterR?.Value ?? 12)).Append(',');
sb.Append("\"waterAnyCorner\":").Append(_cbWaterAnyCorner?.IsChecked == true ? 1 : 0).Append(',');
sb.Append("\"waterImpassableOnly\":").Append(_cbWaterImpassableOnly?.IsChecked == true ? 1 : 0).Append(',');
sb.Append("\"waterTypes\":[").Append(CleanCsv(_tbWaterTypes?.Text)).Append(']');
sb.Append('}');
string outJson = sb.ToString();
RynthLog.UI($"RynthVisionPanel.Push: writing JSON ({outJson.Length} chars): {outJson}");
IntPtr p = Marshal.StringToHGlobalAnsi(outJson);
try { _setSettings(p); }
finally { Marshal.FreeHGlobal(p); }
}
// ── Helpers ───────────────────────────────────────────────────────────────
private static void SetColor(TextBox? tb, Border? sw, uint argb)
{
if (tb != null) tb.Text = argb.ToString("X8");
if (sw != null) sw.Background = ToBrush(argb);
}
private static string CleanCsv(string? csv)
{
if (string.IsNullOrWhiteSpace(csv)) return "";
return string.Join(",", csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Where(s => int.TryParse(s, out _)));
}
private static bool TryParseHex(string? s, out uint argb)
{
argb = 0;
if (string.IsNullOrWhiteSpace(s)) return false;
s = s.Trim().TrimStart('#');
if (s.Length == 6) s = "FF" + s; // assume opaque
if (s.Length != 8) return false;
return uint.TryParse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out argb);
}
private static IBrush ToBrush(uint argb) => new SolidColorBrush(Color.FromArgb(
(byte)(argb >> 24), (byte)(argb >> 16), (byte)(argb >> 8), (byte)argb));
}

File diff suppressed because it is too large Load diff

View file

@ -41,7 +41,7 @@ internal static class StatusPanel
panel.Children.Clear();
AddHeader(panel, "Engine");
AddRow(panel, "Build", EntryPoint.BuildStamp);
AddRow(panel, "Version", EntryPoint.BuildStamp);
AddRow(panel, "Game HWND", $"0x{EntryPoint.GameHwnd:X8}");
AddRow(panel, "Plugin dir", PluginManager.PluginDirectory);
@ -64,7 +64,7 @@ internal static class StatusPanel
foreach (var p in plugins)
{
string state = p.Failed ? "FAILED" : p.Initialized ? "OK" : "pending";
string version = p.VersionString.Length > 0 ? $" v{p.VersionString}" : "";
string version = p.VersionString.Length > 0 ? $" {p.VersionString}" : "";
AddRow(panel, p.DisplayName + version, state, p.Failed);
}
}

View file

@ -6,17 +6,20 @@ namespace RynthCore.Engine.UI;
internal sealed class SoftwareOverlaySurfaceBridge : IOverlaySurfaceBridge
{
private sealed class PendingFrame
{
public PendingFrame(byte[] pixels, int width, int height)
{
Frame = new OverlaySurfaceFrame(pixels, width, height);
}
public OverlaySurfaceFrame Frame { get; }
}
private PendingFrame? _pending;
// Reuses a single byte[] across frames. Eliminates ~350 MB/sec LOH churn at 1600x900@60fps,
// which was hammering the GC and (suspected) exposing/triggering an LFH heap corruption AV
// in ntdll. The producer's Marshal.Copy and the consumer's MemoryCopy can run concurrently
// on the same buffer at worst (visual tearing during fast frames), which is harmless: byte[]
// is GC-tracked so the buffer can't be freed underneath the consumer.
private byte[]? _buffer;
private int _pendingByteCount;
private int _pendingWidth;
private int _pendingHeight;
private int _hasPending;
private readonly object _sync = new();
// Single reusable frame instance — TryConsume mutates it via ResetSoftware.
// Avoids ~45,000 small-heap allocs over a 20-min session that fed LFH churn.
private readonly OverlaySurfaceFrame _frame = new(Array.Empty<byte>(), 0, 0);
public string Name => "software-bgra32";
public bool SupportsGpuInterop => false;
@ -24,9 +27,16 @@ internal sealed class SoftwareOverlaySurfaceBridge : IOverlaySurfaceBridge
public void SubmitSoftwareFrame(IntPtr pixelData, int byteCount, int width, int height)
{
var buffer = new byte[byteCount];
Marshal.Copy(pixelData, buffer, 0, byteCount);
Interlocked.Exchange(ref _pending, new PendingFrame(buffer, width, height));
lock (_sync)
{
if (_buffer == null || _buffer.Length < byteCount)
_buffer = new byte[byteCount];
Marshal.Copy(pixelData, _buffer, 0, byteCount);
_pendingByteCount = byteCount;
_pendingWidth = width;
_pendingHeight = height;
}
Interlocked.Exchange(ref _hasPending, 1);
}
public void SubmitSharedTexture(OverlaySurfaceKind kind, OverlaySharedTextureDescriptor descriptor)
@ -44,14 +54,29 @@ internal sealed class SoftwareOverlaySurfaceBridge : IOverlaySurfaceBridge
public bool TryConsume(out OverlaySurfaceFrame? frame)
{
PendingFrame? pending = Interlocked.Exchange(ref _pending, null);
if (pending == null)
if (Interlocked.Exchange(ref _hasPending, 0) == 0)
{
frame = null;
return false;
}
frame = pending.Frame;
byte[]? buffer;
int width, height;
lock (_sync)
{
buffer = _buffer;
width = _pendingWidth;
height = _pendingHeight;
}
if (buffer == null)
{
frame = null;
return false;
}
_frame.ResetSoftware(buffer, width, height);
frame = _frame;
return true;
}
}