Snapshot for release 2026.10.21.3 (internal 04b831a)

This commit is contained in:
Tom Bohar 2026-10-21 21:03:43 -04:00
commit c4efe5821d
46 changed files with 2657 additions and 213 deletions

View file

@ -5,13 +5,17 @@
//
// Order matters. Each phase is wrapped so a failure does not abort the rest:
//
// 0. TickPump.StopAndJoin — the plugin pump stops (and its frame in flight
// finishes) before any plugin is shut down: no Tick alongside a Shutdown.
// 1. EndSceneHook.Uninstall — chains into EngineFrameController.Shutdown which
// tears down PluginManager (RynthPluginShutdown + FreeLibrary plugins),
// OverlayTextureRenderer, DX9Backend, and destroys the ImGui context.
// 2. Drain — sleep so any in-flight EndScene call has returned through the
// trampoline before we tear down anything else.
// 3. AvaloniaOverlay.Stop — Dispatcher shutdown, join STA thread.
// 4. PluginManager.ShutdownAll — defensive (no-op if step 1 already ran).
// 4. PluginManager.ShutdownAll — defensive (no-op if step 1 already ran; it
// tries again if step 1 left the plugins alone because the pump was
// still inside a frame).
// 5. MH_DisableHook(ALL) + MH_Uninitialize — safety net for Compatibility/*
// hooks that aren't in the ImGui chain.
//
@ -140,6 +144,17 @@ internal static class EngineLifecycle
// plugin-mutating UI command while the plugins are shutting down.
Step("UiDataHub.Disarm", () => UI.Data.UiDataHub.Disarm());
// Stop the plugin pump (and wait for a frame in flight) BEFORE anything below can
// shut a plugin down: EndSceneHook.Uninstall runs PluginManager.ShutdownAll (through
// EngineFrameController.Shutdown), and a pump still running would call a plugin's Tick
// and events on its own thread while that plugin's Shutdown frees what they use on
// this one (audit 2026-10-21, 01 #1). It used to stop further down, after the plugins
// were already gone; only the WM_CLOSE path (Win32Backend) stopped it first. Every
// shutdown comes through here: the loader's hot reload, ExitProcess and
// RtlExitUserProcess, WM_CLOSE, the bar's Sd button. If a frame is still running when
// the wait ends, ShutdownAll leaves the plugins alone (PluginShutdownGate).
Step("TickPump.StopAndJoin", () => EntryPoint.StopTickPumpAndJoin());
// AC's UI-pass hook draws the world overlays mid-frame from the same render-side
// state EndSceneHook.Uninstall tears down: stop it first (its 80 ms drain covers both).
Step("AcUiPassHook.Uninstall", () => AcUiPassHook.Uninstall());
@ -166,17 +181,14 @@ internal static class EngineLifecycle
Step("Win32Backend.Shutdown (input subclass)", () => ImGuiBackend.Win32Backend.Shutdown());
Step("HotkeyService.Shutdown", () => Hotkeys.HotkeyService.Shutdown());
// Stop the dispatch-file watcher and the auto-ID drain timer before the
// tick pump and plugins go away — both otherwise keep firing in the old
// generation's (intentionally still-mapped) module across hot-reloads.
// Stop the dispatch-file watcher and the auto-ID drain timer — both
// otherwise keep firing in the old generation's (intentionally
// still-mapped) module across hot-reloads.
Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop());
Step("LogSettings.StopWatcher", () => LogSettings.StopWatcher());
Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop());
// Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary.
// Otherwise the pump's TickAll/ProcessPendingActions can be mid-call
// into a plugin whose code pages we're about to unmap → AV.
Step("TickPump.StopAndJoin", () => EntryPoint.StopTickPumpAndJoin());
// (The plugin pump stopped at the top, before the plugins were shut down.)
// spike/decal-bridge: after the pump (its only reader) has stopped.
Step("DecalBridgeHost.Shutdown", () => Compatibility.DecalBridgeHost.Shutdown());

View file

@ -1312,7 +1312,11 @@ public static class EntryPoint
{
try
{
if (!EngineThreads.Sleep(DecalCoexistencePluginInitDelay))
// In short steps that watch the pump's stop flag: a teardown in these seconds
// (a reload right after login) then finds this thread gone at once rather than
// after the delay, and plugins are never initialised for a dying generation
// (StopTickPumpAndJoin, PluginShutdownGate).
if (!SleepUnlessPumpStopRequested(DecalCoexistencePluginInitDelay))
return;
// Reseed the qualities pointer from the live player object
@ -1601,10 +1605,13 @@ public static class EntryPoint
internal static bool StopTickPumpAndJoin(int timeoutMs = 2000)
{
Compatibility.GameTickHooks.HeadlessPrefetch = false; // no more prefetch work once teardown starts
// Before the null check: a pump that starts after this (a login bootstrap racing the
// teardown) leaves its loop at once instead of ticking a generation being torn down.
Interlocked.Exchange(ref _tickPumpStopRequested, 1);
if (_tickPumpThread == null)
return true;
Interlocked.Exchange(ref _tickPumpStopRequested, 1);
if (_tickPumpThread == Thread.CurrentThread)
return Volatile.Read(ref _tickPumpExited) != 0; // never wait for itself
long deadline = Environment.TickCount64 + timeoutMs;
while (Volatile.Read(ref _tickPumpExited) == 0 && Environment.TickCount64 < deadline)
@ -1612,10 +1619,31 @@ public static class EntryPoint
bool exited = Volatile.Read(ref _tickPumpExited) != 0;
if (!exited)
RynthLog.Plugin($"DecalCoexistence: tick pump did NOT exit within {timeoutMs}ms.");
RynthLog.Plugin($"Plugin tick pump did NOT exit within {timeoutMs}ms{DescribePumpInside()}.");
return exited;
}
private static string DescribePumpInside()
{
try { string? inside = Plugins.PluginManager.DescribePumpDispatch(); return inside != null ? " (" + inside + ")" : ""; }
catch { return ""; }
}
/// <summary>
/// For PluginManager.ShutdownAll: stops the plugin pump if it is still running, waits up
/// to <paramref name="timeoutMs"/> for its frame in flight, and says whether the plugins
/// may be shut down now (PluginShutdownGate). At once when the pump already stopped (every
/// EngineLifecycle.Shutdown stops it first) or never started.
/// </summary>
internal static Plugins.PluginShutdownGate.Verdict StopTickPumpForPluginShutdown(int timeoutMs)
{
Thread? pump = _tickPumpThread;
bool onPump = pump != null && pump == Thread.CurrentThread;
if (pump != null && !onPump && Volatile.Read(ref _tickPumpExited) == 0)
StopTickPumpAndJoin(timeoutMs);
return Plugins.PluginShutdownGate.Decide(pump != null, Volatile.Read(ref _tickPumpExited) != 0, onPump);
}
/// <summary>
/// Non-blocking request for the headless plugin pump (NormalPluginPump /
/// DecalCoexistence) to stop. Sets the same flag as <see cref="StopTickPumpAndJoin"/>
@ -1630,6 +1658,22 @@ public static class EntryPoint
Interlocked.Exchange(ref _tickPumpStopRequested, 1);
}
/// <summary>
/// Sleeps <paramref name="total"/> in steps of at most 100 ms. False (stop now) as soon as
/// the pump's stop is requested or the engine's threads are stopped.
/// </summary>
private static bool SleepUnlessPumpStopRequested(TimeSpan total)
{
long end = Environment.TickCount64 + (long)total.TotalMilliseconds;
while (Volatile.Read(ref _tickPumpStopRequested) == 0)
{
long left = end - Environment.TickCount64;
if (left <= 0) return true;
if (!EngineThreads.Sleep((int)Math.Min(left, 100))) return false;
}
return false;
}
private static Thread? _initThread;
private static int _initAbortLogged;

View file

@ -9,7 +9,11 @@
// asked for a button (WindowFlags.BarButton: RynthSort, Oracle, ...; tooltip =
// its title; the set is rebuilt as plugins come and go), one per window a plugin
// draws that asked for one (its manifest's "windows" with "bar", UI/Sections/
// PluginWindows.cs), reload (RL) and pop out.
// PluginWindows.cs; an engine panel such a window has taken over loses its own
// button), reload (RL) and pop out.
// A button whose window is open, docked or popped out, draws highlighted in the
// theme's accent (RynthTheme.BarButtonOpen*); the ILT and Scripts buttons while
// any window in their menu is (UI/BarOpenState.cs; one IsOpen lookup a key).
// Dragging the grip moves the bar; the position is the shared bar= row in
// panel_state.txt. Right-click the grip for the bar's menu: its size, its rows
// and "Report a problem" (panel buttons have no menu). Pop out moves the ImGui
@ -65,8 +69,12 @@ internal static class ImGuiBar
// Window: a plugin's script window with a bar button of its own (WindowFlags.BarButton);
// the button toggles it through ScriptWindowRegistry, like the Scripts menu does.
// OpenKey: the panel whose open state lights the button (BarOpenState.KeyFor).
private sealed record ButtonInfo(string Title, string Id, string Icon, bool Letter, string Tooltip,
ScriptWindow? Window = null);
string OpenKey, ScriptWindow? Window = null);
// The open check every highlight uses (one set lookup a key), as one delegate: no allocation a frame.
private static readonly Func<string, bool> IsOpenCheck = ImGuiPanelHost.IsOpen;
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
// Item Count has no icon of its own since 2026-10-18: Inventory's Count button, /rc itemcount, the Character menu.
@ -147,6 +155,9 @@ internal static class ImGuiBar
private static ScriptBarItem[]? _builtScriptButtons;
private static int _builtImGuiOnlyMask;
private static int _builtPluginWindows = -1;
// The Scripts menu's panel keys (its button lights while any is open), rebuilt with the snapshot.
private static ScriptBarItem[]? _scriptKeysFor;
private static string[] _scriptKeys = Array.Empty<string>();
private static string _tooltip = "";
private static bool _placed;
private static Vector2 _pos, _persistedPos;
@ -457,12 +468,15 @@ internal static class ImGuiBar
PushBarButtonStyle(s);
ImFontPtr letterFont = ImGuiFonts.Get(UiFont.UiBold11);
// A button whose window is open (docked or popped out) draws in the theme's accent
// (BarOpenState); a menu button (ILT, Scripts) while any window it lists is open.
foreach (ButtonInfo b in _buttons!)
{
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText))
bool open = BarOpenState.IsOpen(b.OpenKey, IsOpenCheck);
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText, open))
{
if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !ImGuiPanelHost.IsOpen(b.Window.PanelKey));
if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !open);
else PanelRouter.Toggle(b.Title);
}
SafeImGui.SetItemTooltip(b.Tooltip);
@ -474,7 +488,8 @@ internal static class ImGuiBar
{
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
string? only = iltCount == 1 ? FirstIltPanel() : null;
if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText))
bool open = BarOpenState.AnyOpen(IltPanels, IsOpenCheck);
if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText, open))
{
if (only != null) PanelRouter.Toggle(only);
else ImGuiNET.ImGui.OpenPopup("##ilt_menu");
@ -488,7 +503,8 @@ internal static class ImGuiBar
if (scripts.Length > 0)
{
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
if (IconButton("##scripts", iconFont, PhosphorIcons.AppWindow, square, RynthTheme.BarText))
bool open = BarOpenState.AnyOpen(ScriptKeys(scripts), IsOpenCheck);
if (IconButton("##scripts", iconFont, PhosphorIcons.AppWindow, square, RynthTheme.BarText, open))
ImGuiNET.ImGui.OpenPopup("##scripts_menu");
ImGuiNET.ImGui.SetItemTooltip("Script windows");
}
@ -610,11 +626,32 @@ internal static class ImGuiBar
}
}
/// <summary>A square bar button (the bar's button style) with an icon, or a letter, centred on it.</summary>
private static bool IconButton(string id, ImFontPtr font, string icon, Vector2 size, uint color)
/// <summary>The Scripts menu's panel keys, rebuilt only when its snapshot changes (a new array then). AC thread.</summary>
private static string[] ScriptKeys(ScriptBarItem[] items)
{
if (ReferenceEquals(items, _scriptKeysFor)) return _scriptKeys;
var keys = new string[items.Length];
for (int i = 0; i < items.Length; i++) keys[i] = items[i].PanelKey;
_scriptKeys = keys;
_scriptKeysFor = items;
return keys;
}
/// <summary>
/// A square bar button (the bar's button style) with an icon, or a letter, centred on it.
/// <paramref name="open"/>: its window is open, so it draws in the theme's accent.
/// </summary>
private static bool IconButton(string id, ImFontPtr font, string icon, Vector2 size, uint color, bool open = false)
{
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos();
if (open)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, RynthTheme.BarButtonOpen);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, RynthTheme.BarButtonOpenHover);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, RynthTheme.BarButtonOpenBorder);
}
bool clicked = ImGuiNET.ImGui.Button(id, size);
if (open) ImGuiNET.ImGui.PopStyleColor(3);
PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), font, icon, at, size, color);
return clicked;
}
@ -761,17 +798,19 @@ internal static class ImGuiBar
_builtImGuiOnlyMask = mask;
_builtPluginWindows = pluginWindows;
var list = new List<ButtonInfo>();
// An engine panel a plugin window has taken over ("takeOver") has no engine button: the
// window's own (below) stands in when it asks for one.
foreach (var (title, _) in OverlayHost.GetPanels())
if (!LauncherOnly.Contains(title))
if (!LauncherOnly.Contains(title) && !UI.Sections.PluginWindows.TakesOver(title))
{
string icon = IconFor(title, out bool letter);
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title));
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title, BarOpenState.KeyFor(title, null)));
}
foreach (string title in ImGuiOnlyBarPanels)
if (ImGuiOnlyWanted(title) && !LauncherOnly.Contains(title))
if (ImGuiOnlyWanted(title) && !LauncherOnly.Contains(title) && !UI.Sections.PluginWindows.TakesOver(title))
{
string icon = IconFor(title, out bool letter);
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title));
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title, BarOpenState.KeyFor(title, null)));
}
// Windows plugins draw (their manifests' "windows" with "bar", docs/PLUGIN_WINDOWS.md): the
// icon they name (a Phosphor glyph), else the title's letter; the button toggles the panel.
@ -779,7 +818,8 @@ internal static class ImGuiBar
{
bool letter = false;
string icon = w.Icon.Length > 0 ? w.Icon : IconFor(w.Title, out letter);
list.Add(new ButtonInfo(w.Title, "##bar_pw_" + w.Plugin + "_" + w.Id, icon, letter, w.Title));
list.Add(new ButtonInfo(w.Title, "##bar_pw_" + w.Plugin + "_" + w.Id, icon, letter, w.Title,
BarOpenState.KeyFor(w.Title, null)));
}
// Plugin script windows that asked for a button (RynthSort, Oracle, ...): after the
// engine's own. Only while the plugin is loaded and has submitted the window.
@ -789,7 +829,7 @@ internal static class ImGuiBar
string title = w.Title.Length > 0 ? w.Title : w.Key;
string icon = IconFor(title, out bool letter);
string id = "##bar_sw" + w.Hash.ToString("X8");
list.Add(new ButtonInfo(title, id, icon, letter, title, Window: w));
list.Add(new ButtonInfo(title, id, icon, letter, title, BarOpenState.KeyFor(title, w.PanelKey), Window: w));
}
_buttons = list.ToArray();
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar size and rows. Ctrl+wheel over the bar: size.";

View file

@ -9,12 +9,16 @@
// and close; 16 px resize grip, all Phosphor icons), placement restore/persistence shared
// with the Avalonia face through PanelStateStore, and per-panel error isolation.
//
// A plugin window can take an engine panel's place (TakeOver, the manifest's
// "takeOver"): same key, so the saved place, open state and commands carry
// over; the engine's face is kept and comes back on ReleaseTakeOver.
//
// Threads:
// Register engine init.
// RegisterDynamic / Unregister / RequestSize / RequestPos
// RegisterDynamic / Unregister / RequestSize / RequestPos / TakeOver / ReleaseTakeOver
// any thread (script windows, from the plugin pump thread);
// DrawOrder is copy-on-write, removal finishes in DrawAll;
// requests are applied in DrawPanel.
// requests are applied in DrawPanel, face swaps in DrawAll.
// Open / Close any thread (router: game thread / Avalonia UI thread).
// Applied on AC's render thread at the next DrawAll.
// DrawAll AC's render thread, inside the ImGui frame.
@ -146,8 +150,17 @@ internal static class ImGuiPanelHost
public volatile bool HasRequest; // RequestedSize or RequestedPos is set
public int Failures;
public string? Error;
/// <summary>True while a plugin window has this engine panel's place (TakeOver).</summary>
public bool TakenOver;
/// <summary>The engine's own face, kept from the first TakeOver for ReleaseTakeOver.</summary>
public FaceSet? EngineOwn;
/// <summary>A face change waiting for the render thread (ApplyFaceChanges).</summary>
public FaceSet? NextFace;
}
/// <summary>What draws a panel: its spec, its face's factory and its header text.</summary>
private sealed record FaceSet(PanelSpec Spec, Func<IImGuiPanel> Factory, string DisplayTitle);
private static readonly object Sync = new();
private static readonly Dictionary<string, Entry> Entries = new(StringComparer.OrdinalIgnoreCase);
// Copy-on-write under Sync: DrawAll iterates the list it read without holding the lock,
@ -264,6 +277,109 @@ internal static class ImGuiPanelHost
lock (Sync) return Entries.ContainsKey(title);
}
// ── Plugin windows taking over an engine panel (docs/PLUGIN_WINDOWS.md, "takeOver") ──
/// <summary>True when <paramref name="key"/> is an engine panel (Register), taken over or not. Any thread.</summary>
public static bool IsEnginePanel(string key)
{
lock (Sync) return Entries.TryGetValue(key, out Entry? e) && !e.Dynamic;
}
/// <summary>True while a plugin window draws in the engine panel <paramref name="key"/>'s place. Any thread.</summary>
public static bool IsTakenOver(string key)
{
lock (Sync) return Entries.TryGetValue(key, out Entry? e) && e.TakenOver;
}
/// <summary>
/// A plugin window takes the engine panel <paramref name="key"/>'s place: the panel keeps its
/// key (its saved place and size, open state, hotkeys, /rc command and router entry) and is
/// drawn with <paramref name="spec"/> and <paramref name="factory"/>'s face from the next
/// frame; one open now closes and opens again as the new face, where it was (popped out
/// stays popped out). The engine's own face is kept for <see cref="ReleaseTakeOver"/>. Also
/// updates a window already in place. False when <paramref name="key"/> isn't an engine
/// panel. Any thread; applied on AC's render thread.
/// </summary>
public static bool TakeOver(string key, string displayTitle, PanelSpec spec, Func<IImGuiPanel> factory)
{
lock (Sync)
{
if (!Entries.TryGetValue(key, out Entry? e) || e.Dynamic) return false;
// The first takeover finds the engine's face in place; later ones may find a plugin's.
e.EngineOwn ??= new FaceSet(e.Spec, e.Factory, e.DisplayTitle);
e.TakenOver = true;
e.NextFace = new FaceSet(spec, factory, displayTitle);
}
_faceChangePending = true;
return true;
}
/// <summary>
/// The plugin window that took over <paramref name="key"/> went (plugin unloaded, window
/// dropped): the engine's own face comes back in its place, open if the window was open.
/// Any thread; applied on AC's render thread.
/// </summary>
public static void ReleaseTakeOver(string key)
{
lock (Sync)
{
if (!Entries.TryGetValue(key, out Entry? e) || !e.TakenOver || e.EngineOwn == null) return;
e.TakenOver = false;
e.NextFace = e.EngineOwn;
}
_faceChangePending = true;
}
private static volatile bool _faceChangePending;
/// <summary>
/// Swaps in the faces TakeOver / ReleaseTakeOver asked for. A panel shown now closes as its
/// old face and opens as the new one (placement saved and read back as usual), and embedded
/// copies of it are dropped so their hosts draw the new face. AC thread, before the requests.
/// </summary>
private static void ApplyFaceChanges(float placeScale)
{
if (!_faceChangePending) return;
_faceChangePending = false;
List<Entry>? changed = null;
lock (Sync)
foreach (Entry e in DrawOrder)
{
if (e.NextFace is not FaceSet next) continue;
e.NextFace = null;
bool sameFace = e.Factory == next.Factory;
e.Spec = next.Spec;
e.Factory = next.Factory;
e.DisplayTitle = next.DisplayTitle;
if (!sameFace) (changed ??= new List<Entry>()).Add(e);
}
if (changed == null) return;
foreach (Entry e in changed)
{
RynthLog.UI($"ImGuiPanelHost: {e.Title} is drawn by {(e.TakenOver ? "a plugin's window" : "the engine's face again")}.");
DropEmbeddedCopies(e.Title);
if (!e.Shown) continue; // the next open uses the new face
Apply(e.Title, RequestKind.Close, placeScale);
Apply(e.Title, RequestKind.Open, placeScale);
}
}
/// <summary>Hides and drops the embedded copies of <paramref name="title"/> (another face takes its place). AC thread.</summary>
private static void DropEmbeddedCopies(string title)
{
List<string>? gone = null;
foreach (var kv in EmbeddedFaces)
if (kv.Value.Title.Equals(title, StringComparison.OrdinalIgnoreCase)) (gone ??= new List<string>()).Add(kv.Key);
if (gone == null) return;
foreach (string key in gone)
{
EmbeddedFace face = EmbeddedFaces[key];
EmbeddedFaces.Remove(key);
try { face.Instance.OnHidden(); }
catch (Exception ex) { RynthLog.UI($"ImGuiPanelHost: embedded {face.Title}.OnHidden threw {ex.GetType().Name}: {ex.Message}"); }
}
}
public static PanelFace CodeDefault(string title)
{
lock (Sync) return Entries.TryGetValue(title, out Entry? e) ? e.Spec.CodeDefault : PanelFace.Avalonia;
@ -455,6 +571,7 @@ internal static class ImGuiPanelHost
{
_frameScale = uiScale;
float placeScale = PlacementScale();
ApplyFaceChanges(placeScale); // plugin windows taking over (or giving back) engine panels
while (Requests.TryDequeue(out var req))
Apply(req.Title, req.Kind, placeScale);
RemoveUnregistered();

View file

@ -0,0 +1,149 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiStackGuard.cs
// Puts ImGui's stacks back after plugin drawing code (audit 2026-10-21, 02 F4).
// A plugin window's body (PluginWindowFace) is the plugin's own ImGui code; one
// unbalanced PushStyleColor, a BeginChild left open, or an exception between a
// Begin and its End used to carry over into every panel drawn after it that
// frame (soft asserts, so it showed as garbage or a later native fault).
//
// Take() records the stack depths with ImGui's own ErrorRecoveryStoreState
// (exported by our cimgui build); Check() compares a fresh record with it;
// RecoverTo() hands a record back to ErrorRecoveryTryToRecoverState, which ends
// what was left open (windows and child windows, tables, tab bars, tree nodes,
// groups, IDs, disabled blocks, colours, item flags, style vars, fonts, focus
// scopes) down to that record. ImGui's own error report (assert, tooltip, debug
// log) is switched off around that call: the caller logs once instead, and a
// broken plugin can't put an error tooltip on the screen every frame.
//
// Rule from ImGui: a record to recover to must be taken where the current
// window's ID stack is at its base (the start of a window or child body), since
// the recovery pops that window's IDs down to its first.
//
// The record is opaque here (ImGuiStackState reads it for the log). Its size is
// checked on first use; on a mismatch, or with a cimgui.dll without the exports,
// Available is false and callers do as before. AC's render thread, inside an
// ImGui frame and window (StoreState reads the current window).
// ============================================================================
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ImGuiStackGuard
{
/// <summary>Room for one record (ImGui 1.91.6 writes 22 bytes).</summary>
private const int RecordCapacity = 64;
/// <summary>One stack record. Zeroed before ImGui writes it, so two records compare byte for byte.</summary>
[StructLayout(LayoutKind.Sequential, Size = RecordCapacity)]
internal struct Mark
{
private fixed byte _bytes[RecordCapacity];
}
/// <summary>A record's fields (ImGuiStackState.Names), read in place: no allocation.</summary>
private static ReadOnlySpan<short> FieldsOf(in Mark m) =>
MemoryMarshal.Cast<byte, short>(MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in m), 1)))
[..ImGuiStackState.Fields];
private static delegate* unmanaged[Cdecl]<void*, void> _store;
private static delegate* unmanaged[Cdecl]<void*, void> _recover;
private static int _state; // 0 = not resolved, 1 = available, -1 = off
/// <summary>True when the exports exist and the record size checked out. Render thread, inside a window.</summary>
public static bool Available
{
get
{
if (_state == 0) Resolve();
return _state > 0;
}
}
private static void Resolve()
{
_state = -1;
IntPtr module = EntryPoint.ImGuiNativeHandle;
if (module == IntPtr.Zero
|| !NativeLibrary.TryGetExport(module, "igErrorRecoveryStoreState", out IntPtr store)
|| !NativeLibrary.TryGetExport(module, "igErrorRecoveryTryToRecoverState", out IntPtr recover))
{
RynthLog.UI("ImGuiStackGuard: this cimgui.dll has no igErrorRecovery* exports; plugin drawing isn't checked for unbalanced stacks.");
return;
}
_store = (delegate* unmanaged[Cdecl]<void*, void>)store;
_recover = (delegate* unmanaged[Cdecl]<void*, void>)recover;
const byte fill = 0xCC;
byte* probe = stackalloc byte[RecordCapacity];
new Span<byte>(probe, RecordCapacity).Fill(fill);
_store(probe);
if (!ImGuiStackState.WroteExpectedSize(new ReadOnlySpan<byte>(probe, RecordCapacity), fill))
{
RynthLog.UI($"ImGuiStackGuard: ImGui's stack record isn't the {ImGuiStackState.RecordBytes} bytes this engine expects; plugin drawing isn't checked.");
return;
}
_state = 1;
}
/// <summary>The stack depths now. Only when <see cref="Available"/>.</summary>
public static Mark Take()
{
Mark m = default;
_store(&m);
return m;
}
/// <summary>The stack depths now against <paramref name="before"/>; <paramref name="now"/> for the log.</summary>
public static StackCheck Check(in Mark before, out Mark now)
{
now = Take();
return ImGuiStackState.Compare(FieldsOf(before), FieldsOf(now));
}
/// <summary>True when the record was taken with the window's ID stack at its base: one a recovery may go back to.</summary>
public static bool AtWindowBase(in Mark mark) => ImGuiStackState.IdsAtBase(FieldsOf(mark));
/// <summary>What changed between two records, for the log ("colours +2, windows +1").</summary>
public static string Describe(in Mark before, in Mark after) => ImGuiStackState.Describe(FieldsOf(before), FieldsOf(after));
/// <summary>
/// Ends and pops everything above <paramref name="mark"/> (taken where the window's ID stack
/// was at its base). Windows or pops below the mark can't be put back. When windows below it
/// were ended (ImGui's recovery then does nothing), only the colours, style vars and fonts
/// above it are popped, which are the context's and safe from any window.
/// </summary>
public static void RecoverTo(in Mark mark)
{
Mark now = Take();
if (!ImGuiStackState.CanRecover(FieldsOf(mark), FieldsOf(now)))
{
(int colours, int vars, int fonts) = ImGuiStackState.GlobalPops(FieldsOf(mark), FieldsOf(now));
if (colours > 0) ImGuiNET.ImGui.PopStyleColor(colours);
if (vars > 0) ImGuiNET.ImGui.PopStyleVar(vars);
for (int i = 0; i < fonts; i++) ImGuiNET.ImGui.PopFont();
return;
}
ImGuiNET.ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
bool assert = io.ConfigErrorRecoveryEnableAssert, tooltip = io.ConfigErrorRecoveryEnableTooltip;
bool debugLog = io.ConfigErrorRecoveryEnableDebugLog, recovery = io.ConfigErrorRecovery;
io.ConfigErrorRecoveryEnableAssert = false;
io.ConfigErrorRecoveryEnableTooltip = false;
io.ConfigErrorRecoveryEnableDebugLog = false;
io.ConfigErrorRecovery = true;
try
{
fixed (Mark* m = &Unsafe.AsRef(in mark)) _recover(m);
}
finally
{
io.ConfigErrorRecoveryEnableAssert = assert;
io.ConfigErrorRecoveryEnableTooltip = tooltip;
io.ConfigErrorRecoveryEnableDebugLog = debugLog;
io.ConfigErrorRecovery = recovery;
}
}
}

View file

@ -0,0 +1,121 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiStackState.cs
// What a plugin's draw left on ImGui's stacks, from two of Dear ImGui's own
// stack records (ImGuiErrorRecoveryState, taken by ImGuiStackGuard before and
// after the call). Pure: no ImGui calls, so tools/SectionsTests compiles it.
//
// The record is ImGui 1.91.6's ImGuiErrorRecoveryState: 11 shorts in the order
// of Names below (imgui_internal.h; ImGuiSelfTest pins the version). Checked
// against our cimgui.dll in a 32-bit probe on 2026-10-21: 22 bytes written,
// and ImGuiStackGuard re-checks the size before its first use.
// ============================================================================
using System;
using System.Text;
namespace RynthCore.Engine.ImGuiBackend;
/// <summary>How a plugin's draw left ImGui's stacks.</summary>
internal enum StackCheck
{
/// <summary>As it found them.</summary>
Balanced,
/// <summary>It left things open (pushes, a child window, a group...): ImGui can unwind them.</summary>
LeftOpen,
/// <summary>It ended or popped something it didn't begin (the host's window, colours): can't be put back.</summary>
ClosedTooMuch,
}
internal static class ImGuiStackState
{
/// <summary>Shorts in ImGuiErrorRecoveryState (1.91.6).</summary>
public const int Fields = 11;
/// <summary>Bytes ImGui writes for one record.</summary>
public const int RecordBytes = Fields * sizeof(short);
/// <summary>Index of the window stack's depth (Begin / BeginChild).</summary>
public const int WindowStack = 0;
/// <summary>What each field counts, in the record's order.</summary>
public static readonly string[] Names =
{
"windows", "IDs", "tree nodes", "colours", "style vars", "fonts",
"focus scopes", "groups", "item flags", "popups", "disabled",
};
/// <summary>
/// Fields that count the current window's own stacks (its IDs, its tree depth): they compare
/// only at the same window depth. The rest belong to the context.
/// </summary>
public static bool PerWindow(int field) => field is 1 or 2;
/// <summary>The draw's effect: <paramref name="after"/> against <paramref name="before"/>.</summary>
public static StackCheck Compare(ReadOnlySpan<short> before, ReadOnlySpan<short> after)
{
if (after[WindowStack] < before[WindowStack]) return StackCheck.ClosedTooMuch;
bool sameWindow = after[WindowStack] == before[WindowStack];
bool changed = !sameWindow;
for (int i = 0; i < Fields; i++)
{
if (i == WindowStack || (!sameWindow && PerWindow(i))) continue;
if (after[i] < before[i]) return StackCheck.ClosedTooMuch;
if (after[i] != before[i]) changed = true;
}
return changed ? StackCheck.LeftOpen : StackCheck.Balanced;
}
/// <summary>
/// The window's ID stack holds only the window's own ID: a record taken here is one ImGui's
/// recovery can go back to (it pops a window's IDs down to that one).
/// </summary>
public static bool IdsAtBase(ReadOnlySpan<short> record) => record[1] == 1;
/// <summary>Indexes of the context-wide stacks a pop works on from any window.</summary>
public const int Colours = 3, StyleVars = 4, Fonts = 5;
/// <summary>
/// ImGui's recovery can unwind to <paramref name="mark"/> only from the same window depth or
/// deeper; when the draw ended windows below the mark (the host's own), it does nothing.
/// </summary>
public static bool CanRecover(ReadOnlySpan<short> mark, ReadOnlySpan<short> now) => now[WindowStack] >= mark[WindowStack];
/// <summary>
/// When <see cref="CanRecover"/> is false: the colours, style vars and fonts to pop to get back
/// to <paramref name="mark"/> (those stacks belong to the context, not a window). 0 where none.
/// </summary>
public static (int Colours, int StyleVars, int Fonts) GlobalPops(ReadOnlySpan<short> mark, ReadOnlySpan<short> now) =>
(Math.Max(0, now[Colours] - mark[Colours]), Math.Max(0, now[StyleVars] - mark[StyleVars]), Math.Max(0, now[Fonts] - mark[Fonts]));
/// <summary>
/// "windows +1, colours +2, style vars +1": the fields that changed, with the change (a
/// window's own IDs and tree depth only when the window depth is the same).
/// </summary>
public static string Describe(ReadOnlySpan<short> before, ReadOnlySpan<short> after)
{
var sb = new StringBuilder();
bool sameWindow = after[WindowStack] == before[WindowStack];
for (int i = 0; i < Fields; i++)
{
int d = after[i] - before[i];
if (d == 0 || (!sameWindow && PerWindow(i))) continue;
if (sb.Length > 0) sb.Append(", ");
sb.Append(Names[i]).Append(' ').Append(d > 0 ? "+" : "").Append(d);
}
return sb.Length > 0 ? sb.ToString() : "nothing";
}
/// <summary>
/// The size check on first use: <paramref name="record"/> was filled with
/// <paramref name="fill"/> and then written by ImGui. True when exactly the first
/// <see cref="RecordBytes"/> bytes were written (the layout this file expects).
/// </summary>
public static bool WroteExpectedSize(ReadOnlySpan<byte> record, byte fill)
{
int written = 0;
for (int i = 0; i < record.Length; i++)
if (record[i] != fill) written = i + 1;
// A short that happens to equal fill|fill is a value no stack reaches (0xCCCC = -13108).
return written == RecordBytes;
}
}

View file

@ -4,9 +4,13 @@
// the panel host draws the window, this face hands the body to the plugin's
// RynthPluginRenderEmbed(surface, width, height) in the default UI font, under
// an ID scope of its own. Popped out, PluginManager.RenderEmbed adds ":popout"
// to the surface name. An export that throws is switched off (PluginManager
// logs it); the body then says so and asks again every 5 s, so a reloaded
// plugin draws again without the window being reopened.
// to the surface name. An export that throws (or returns -2, "failed") is
// switched off (PluginManager logs it); the body then says so and asks again
// every 5 s, so a reloaded plugin draws again without the window being reopened.
// After every call ImGui's stacks are checked against what they were before it
// (ImGuiStackGuard): whatever the plugin left open (colours, style vars, fonts,
// IDs, groups, child windows, tables...) is ended and popped there, so the
// panels drawn after it start clean; logged once per window, then counted.
// docs/PLUGIN_WINDOWS.md. AC's render thread.
// ============================================================================
@ -44,13 +48,31 @@ internal sealed class PluginWindowFace : IImGuiPanel
int result = PluginManager.EmbedFailed;
if (_failedAtMs < 0 || now - _failedAtMs >= RetryMs)
{
// Two stack records: the body's base (where a recovery goes back to: the panel host
// calls Draw right after its BeginChild, the ID stack at its base) and the depth the
// plugin gets, which it must leave as it found.
bool guarded = ImGuiStackGuard.Available;
ImGuiStackGuard.Mark bodyBase = guarded ? ImGuiStackGuard.Take() : default;
guarded = guarded && ImGuiStackGuard.AtWindowBase(bodyBase); // drawn anywhere else: as before
ImGuiNET.ImGui.PushID(_idScope);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
ImGuiStackGuard.Mark given = guarded ? ImGuiStackGuard.Take() : default;
try { result = PluginManager.RenderEmbed(_plugin, _surface, avail, out _); }
finally
{
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.PopID();
ImGuiStackGuard.Mark after = default;
StackCheck check = guarded ? ImGuiStackGuard.Check(given, out after) : StackCheck.Balanced;
if (check == StackCheck.Balanced)
{
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.PopID();
}
else
{
// Ends and pops what the plugin left, with this face's ID scope and font.
ImGuiStackGuard.RecoverTo(bodyBase);
NoteUnbalanced(check, ImGuiStackGuard.Describe(given, after));
}
}
if (result == PluginManager.EmbedFailed) _failedAtMs = now;
else if (result == PluginManager.EmbedDrawn) _failedAtMs = -1;
@ -66,4 +88,22 @@ internal sealed class PluginWindowFace : IImGuiPanel
_ => $"Waiting for {_plugin}…",
}, Mute);
}
// Unbalanced draws by plugin + surface: logged the first time, then every RepeatEvery-th.
private static readonly System.Collections.Generic.Dictionary<string, int> Unbalanced = new(StringComparer.Ordinal);
private const int RepeatEvery = 1000;
private void NoteUnbalanced(StackCheck check, string what)
{
string key = _plugin + "/" + _title;
Unbalanced.TryGetValue(key, out int n);
Unbalanced[key] = ++n;
if (n != 1 && n % RepeatEvery != 0) return;
string again = n == 1 ? "" : $" ({n} times so far)";
RynthLog.Warn(check == StackCheck.ClosedTooMuch
? $"PluginWindows: {_plugin} drawing '{_title}' ended or popped what it didn't open ({what}){again}. " +
"What it left open was put back; what it took can't be, so the window may draw wrongly."
: $"PluginWindows: {_plugin} drawing '{_title}' left ImGui's stacks unbalanced ({what}){again}. " +
"Put back after its draw; the panels after it draw as normal.");
}
}

View file

@ -211,6 +211,11 @@ internal static class RynthTheme
public static uint BarBackground => WithAlpha(_t.BarBg, 0xE6);
public const float BarRounding = 4f;
public static uint BarButton => _t.FrameBg;
// A button whose window is open (docked or popped out, BarOpenState): the accent fill
// (Chat's active tab), halfway to the accent under the mouse, and an accent border.
public static uint BarButtonOpen => _t.AccentFill;
public static uint BarButtonOpenHover => _t.WindowBorder;
public static uint BarButtonOpenBorder => _t.Accent;
public static readonly uint BarText = Argb(0xFFFFFFFF);
public static readonly uint RcLabel = Argb(0xFF90EE90); // LightGreen
public static readonly uint ReloadLabel = Argb(0xFFF0E68C); // Khaki

View file

@ -21,7 +21,12 @@
// "miniremote") into the engine's current ImGui
// window on AC's render thread, inside a
// width x height child; reports the size it wants.
// 1 = drawn, 0 = not ready / unknown surface.
// 1 = drawn, 0 = not ready / unknown surface,
// -2 = failed (it caught its own exception): its
// surfaces go off for the session, as for a throw
// (engines before 2026-10-21 read -2 as 0). Leave
// ImGui's stacks as found; the engine puts back
// what a plugin window leaves open, and logs it.
// void RynthPluginOnServerMessage(uint opcode, byte* data, int length)
// — v78, reassembled server messages the plugin
// asked for with SetServerMessageInterestFn

View file

@ -1336,8 +1336,8 @@ internal static partial class PluginManager
/// Render thread only. Returns <see cref="EmbedDrawn"/>, <see cref="EmbedNotReady"/> (the
/// plugin isn't ready: before login, no ImGui context, or too old to draw in a pop-out),
/// <see cref="EmbedNoPlugin"/> (not loaded, or too old to have the export) or
/// <see cref="EmbedFailed"/> (it threw: the export is switched off for this session; the
/// plugin keeps running).
/// <see cref="EmbedFailed"/> (it threw, or returned -2 to say it caught its own exception:
/// the export is switched off for this session; the plugin keeps running).
/// </summary>
internal static unsafe int RenderEmbed(string pluginName, ReadOnlySpan<byte> surfaceUtf8, System.Numerics.Vector2 size, out System.Numerics.Vector2 want)
{
@ -1380,6 +1380,15 @@ internal static partial class PluginManager
fixed (byte* s = surfaceUtf8)
r = ((delegate* unmanaged[Cdecl]<byte*, float, float, float*, float*, int>)fn)(s, size.X, size.Y, &w, &h);
want = new System.Numerics.Vector2(float.IsFinite(w) ? MathF.Max(0, w) : 0, float.IsFinite(h) ? MathF.Max(0, h) : 0);
if (r == EmbedFailed)
{
// The plugin caught its own exception and says so (an exception can't leave a
// managed plugin's [UnmanagedCallersOnly] export, so plugins catch everything; with
// 0 the window would say "Waiting..." for ever): the same as a throw.
p.RenderEmbedPtr = IntPtr.Zero;
RynthLog.Error($"PluginManager: {p.DisplayName} RenderEmbed reported a failure (-2) - embedded surfaces off for this session (plugin keeps running).");
return EmbedFailed;
}
return r == 1 ? EmbedDrawn : EmbedNotReady;
}
catch (Exception ex)
@ -1436,6 +1445,17 @@ internal static partial class PluginManager
public static void ShutdownAll()
{
// A plugin's Shutdown never runs alongside its Tick on the pump thread (audit
// 2026-10-21, 01 #1). EngineLifecycle.Shutdown stops the pump before anything reaches
// here, so this returns at once; a frame still running gets ShutdownWaitMs more, and
// if it outlasts that the plugins are left alone. Nothing below changes then: the
// teardown's defensive ShutdownAll asks again after its other steps.
PluginShutdownGate.Verdict gate = EntryPoint.StopTickPumpForPluginShutdown(PluginShutdownGate.ShutdownWaitMs);
if (!PluginShutdownGate.MayShutDownPlugins(gate))
{
RynthLog.Error(PluginShutdownGate.DescribeRefusal(_plugins.Count, DescribePumpDispatch()));
return;
}
RynthLog.Plugin($"PluginManager: Shutting down {_plugins.Count} plugin(s)...");
UiLifecycleHooks.UiInitialized -= OnUIInitializedObserved;
LoginLifecycleHooks.LoginComplete -= OnLoginCompleteObserved;

View file

@ -1,7 +1,7 @@
// ============================================================================
// RynthCore.Engine - Plugins/PumpGuards.cs
//
// Two small pieces for PluginManager.TickAll and the plugin pump thread.
// Small pieces for PluginManager.TickAll, the plugin pump thread and plugin shutdown.
//
// StepFaultLog: TickAll's own steps (the main-thread freeze check, the delayed
// self-identify, the Nav3D frame clear/commit, dropping failed plugins' script
@ -17,6 +17,9 @@
// the dump, the hang watchdog reports, and this line names the plugin
// (2026-10-13 06:00: RynthAi's tick jumped to address 0).
//
// PluginShutdownGate: plugins are shut down only once the pump has stopped (or
// never ran), so no plugin's Shutdown runs alongside its Tick (audit 2026-10-21).
//
// Pure: no engine state. Compiled into tools\EngineRobustnessTests.
// ============================================================================
@ -82,3 +85,47 @@ internal static class PumpDispatchInfo
return $"inside {plugin} {export ?? "call"} for {ms} ms";
}
}
/// <summary>
/// Whether PluginManager.ShutdownAll may call the plugins' Shutdown now: never while the
/// plugin pump may still be inside a frame on its own thread, or a plugin's Tick and events
/// would run alongside its Shutdown, which frees their threads, textures and handles (a
/// native fault there can't be caught: audit 2026-10-21, 01 #1). EngineLifecycle.Shutdown
/// stops the pump before anything shuts a plugin down; this checks that the stop finished.
/// </summary>
internal static class PluginShutdownGate
{
/// <summary>How long ShutdownAll waits for the pump on top of EngineLifecycle's own join.</summary>
public const int ShutdownWaitMs = 5000;
internal enum Verdict
{
/// <summary>No pump was started in this generation (plugins off, or before login).</summary>
NoPump,
/// <summary>The pump has left its loop: nothing ticks the plugins any more.</summary>
PumpStopped,
/// <summary>Called on the pump thread itself: no frame of it can run alongside.</summary>
OnPumpThread,
/// <summary>The pump is still running (a frame outlasted the wait): leave the plugins alone.</summary>
PumpStillRunning,
}
/// <summary>
/// <paramref name="pumpStarted"/>: a pump thread was started; <paramref name="pumpExited"/>:
/// it has left its loop (after the stop and the wait); <paramref name="onPumpThread"/>: the
/// caller is that thread.
/// </summary>
public static Verdict Decide(bool pumpStarted, bool pumpExited, bool onPumpThread) =>
!pumpStarted ? Verdict.NoPump
: pumpExited ? Verdict.PumpStopped
: onPumpThread ? Verdict.OnPumpThread
: Verdict.PumpStillRunning;
public static bool MayShutDownPlugins(Verdict verdict) => verdict != Verdict.PumpStillRunning;
/// <summary>The log line when ShutdownAll leaves the plugins alone.</summary>
public static string DescribeRefusal(int plugins, string? pumpInside) =>
$"PluginManager: the plugin pump is still running ({pumpInside ?? "no plugin call named"}) - " +
$"{plugins} plugin(s) NOT shut down now, so no Shutdown runs alongside a Tick. " +
"The engine's teardown tries once more after its other steps.";
}

View file

@ -0,0 +1,42 @@
// ============================================================================
// RynthCore.Engine - UI/BarOpenState.cs
// Which toolbar buttons (ImGuiBar) draw as open: a button is highlighted in
// the theme's accent while a window it stands for is open, docked or popped
// out (a popped-out panel stays open in ImGuiPanelHost).
//
// What a button stands for: an engine panel's or a plugin window's button its
// title (a plugin window that took over an engine panel has that panel's
// title), a plugin script window's button that window's panel key ("script:
// ...", not its title); a button that opens a menu of several (ILT, Scripts)
// every window it lists, open while any of them is.
//
// Pure (no ImGui, no engine state): the caller passes the open check
// (ImGuiPanelHost.IsOpen, one set lookup a key). Tests: tools/BarLayoutTests.
// Any thread.
// ============================================================================
using System;
namespace RynthCore.Engine.UI;
internal static class BarOpenState
{
/// <summary>
/// The window a one-window button stands for: a script window's panel key when it is one,
/// else the title (engine panels, ImGui-only panels, plugin windows).
/// </summary>
public static string KeyFor(string title, string? scriptPanelKey) =>
string.IsNullOrEmpty(scriptPanelKey) ? title : scriptPanelKey;
/// <summary>A one-window button is open while its window is (an empty key never is).</summary>
public static bool IsOpen(string key, Func<string, bool> isOpen) =>
!string.IsNullOrEmpty(key) && isOpen(key);
/// <summary>A button for several windows (ILT, Scripts) is open while any of them is; none listed = closed.</summary>
public static bool AnyOpen(ReadOnlySpan<string> keys, Func<string, bool> isOpen)
{
foreach (string key in keys)
if (IsOpen(key, isOpen)) return true;
return false;
}
}

View file

@ -9,12 +9,20 @@
// registers a dynamic panel for each window the manifests ask for (a window
// with "server" only while that server is active) and unregisters the rest.
// The panel key is the window's title, so its saved place, hotkeys and /rc
// commands use the name players see; a title an engine panel has is refused.
// commands use the name players see. A title an engine panel has is refused,
// unless the window declares "takeOver": then it takes that panel's place
// (ImGuiPanelHost.TakeOver: same key, so the saved place and size, open state,
// hotkeys and commands carry over) and the engine's face steps aside, not drawn
// and without its bar button (TakesOver), until the window goes (the plugin
// unloads or stops declaring it): then the engine's face comes back where the
// window was, open if it was open. So a screen can move out of the engine with
// the plugin shipping first and the engine face deleted a release later.
// A window seen for the first time this session opens if it was open when the
// game last closed (Remember Open Windows); one that went with a plugin reload
// opens again when the plugin comes back.
//
// WindowPlan.cs is the pure part (which windows, which are refused and why).
// WindowPlan.cs is the pure part (which windows, which are refused and why,
// which take over an engine panel).
// ============================================================================
using System;
@ -27,13 +35,14 @@ namespace RynthCore.Engine.UI.Sections;
internal static class PluginWindows
{
private sealed record Hosted(SectionWindowDecl Decl, string Signature);
private sealed record Hosted(SectionWindowDecl Decl, string Signature, bool TakesOver);
private static readonly Dictionary<string, Hosted> Live = new(StringComparer.OrdinalIgnoreCase); // render thread
private static readonly HashSet<string> SeenThisSession = new(StringComparer.OrdinalIgnoreCase); // render thread
private static readonly HashSet<string> ReopenWhenBack = new(StringComparer.OrdinalIgnoreCase); // render thread
private static readonly HashSet<string> RefusalsLogged = new(StringComparer.Ordinal); // render thread
private static volatile SectionWindowDecl[] _barWindows = Array.Empty<SectionWindowDecl>();
private static volatile string[] _takenOver = Array.Empty<string>();
private static int _version;
/// <summary>Hosted windows that asked for a bar button, in manifest order. Any thread.</summary>
@ -45,12 +54,23 @@ internal static class PluginWindows
/// <summary>True when <paramref name="title"/> is a plugin window hosted now. Render thread.</summary>
public static bool IsHosted(string title) => Live.ContainsKey(title);
/// <summary>
/// True while a plugin window has taken the place of the engine panel <paramref name="title"/>:
/// the engine's own bar button for it is left out (the window has its own when it asks). Any thread.
/// </summary>
public static bool TakesOver(string title)
{
foreach (string t in _takenOver)
if (t.Equals(title, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>After a SectionRegistry rebuild: register, update and drop the windows' panels. Render thread.</summary>
public static void Sync(IReadOnlyList<SectionManifest> manifests, IReadOnlyList<ServerState> servers)
{
var refused = new List<string>();
Dictionary<string, SectionWindowDecl> want = WindowPlan.Build(manifests, servers,
title => ImGuiPanelHost.HasFace(title) && !Live.ContainsKey(title), refused);
var takeOvers = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, SectionWindowDecl> want = WindowPlan.Build(manifests, servers, Use, refused, takeOvers);
foreach (string r in refused)
if (RefusalsLogged.Add(r)) RynthLog.UI("PluginWindows: " + r + " - not shown.");
@ -60,8 +80,18 @@ internal static class PluginWindows
if (!want.ContainsKey(title)) gone.Add(title);
foreach (string title in gone)
{
if (ImGuiPanelHost.IsOpen(title)) ReopenWhenBack.Add(title);
ImGuiPanelHost.Unregister(title);
Hosted was = Live[title];
if (was.TakesOver)
{
// The engine's face comes back in the window's place (open if it was open).
ImGuiPanelHost.ReleaseTakeOver(title);
RynthLog.UI($"PluginWindows: {was.Decl.Plugin}'s window '{title}' went - the engine's panel is back.");
}
else
{
if (ImGuiPanelHost.IsOpen(title)) ReopenWhenBack.Add(title);
ImGuiPanelHost.Unregister(title);
}
Live.Remove(title);
changed = true;
}
@ -71,9 +101,19 @@ internal static class PluginWindows
string sig = WindowPlan.Signature(w);
if (Live.TryGetValue(title, out Hosted? h) && h.Signature == sig) continue;
SectionWindowDecl decl = w;
ImGuiPanelHost.RegisterDynamic(title, title, Spec(decl), () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title));
Func<IImGuiPanel> face = () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title);
if (takeOvers.Contains(title))
{
// An engine panel's place: its key, saved place and open state stay; nothing to reopen.
if (!ImGuiPanelHost.TakeOver(title, title, Spec(decl), face)) continue;
if (h == null) RynthLog.UI($"PluginWindows: {decl.Plugin}'s window '{title}' takes the engine panel's place.");
Live[title] = new Hosted(decl, sig, TakesOver: true);
changed = true;
continue;
}
ImGuiPanelHost.RegisterDynamic(title, title, Spec(decl), face);
bool first = h == null;
Live[title] = new Hosted(decl, sig);
Live[title] = new Hosted(decl, sig, TakesOver: false);
changed = true;
if (!first) continue;
bool reopen = ReopenWhenBack.Remove(title);
@ -86,12 +126,26 @@ internal static class PluginWindows
if (!changed) return;
var bar = new List<SectionWindowDecl>();
var taken = new List<string>();
foreach (Hosted h in Live.Values)
{
if (h.Decl.Bar) bar.Add(h.Decl);
if (h.TakesOver) taken.Add(h.Decl.Title);
}
_barWindows = bar.ToArray();
_takenOver = taken.ToArray();
System.Threading.Interlocked.Increment(ref _version);
}
/// <summary>
/// What already uses <paramref name="title"/>: an engine panel (taken over by a window here or
/// not), this sync's own hosted window (free), or another panel such as a script window.
/// </summary>
private static TitleUse Use(string title) =>
ImGuiPanelHost.IsEnginePanel(title) ? TitleUse.EnginePanel
: ImGuiPanelHost.HasFace(title) && !Live.ContainsKey(title) ? TitleUse.Other
: TitleUse.Free;
private static PanelSpec Spec(SectionWindowDecl w) => new(
new Vector2(w.Width, w.Height), new Vector2(w.MinWidth, w.MinHeight),
EdgeToEdge: w.EdgeToEdge, GripInBody: w.EdgeToEdge);

View file

@ -20,7 +20,7 @@
// "windows": [
// { "id": "characters", "title": "Characters", "surface": "window:characters",
// "icon": "\uE68E", "width": 420, "height": 260, "minWidth": 280, "minHeight": 140,
// "bar": true, "edgeToEdge": true, "server": "" } ]
// "bar": true, "edgeToEdge": true, "server": "", "takeOver": false } ]
// }
// servers servers the plugin knows. A built-in id (ilt, aelrynth) keeps the
// engine's own detection; a new id is detected from its lists.
@ -34,7 +34,11 @@
// hosts as panels: header, pop-out, resize, remembered place, a bar
// button when "bar" (the icon: a Phosphor glyph, else the title's
// letter); the body is "surface" through RynthPluginRenderEmbed.
// "title" is the panel key (unique; an engine panel's is refused).
// "title" is the panel key (unique). An engine panel's title is refused,
// unless "takeOver": true (2026-10-21): the window then draws in that
// panel's place (same key: its saved place, open state and commands)
// and the engine's face comes back when the plugin goes. Engines
// before that ignore the key and keep their face (the title refused).
// "server" set: only while that server is active. docs/PLUGIN_WINDOWS.md.
//
// Everything from a plugin is checked here: ids are short lower-case words,
@ -93,7 +97,9 @@ internal sealed record SectionWindowDecl(
float MinHeight,
bool Bar,
bool EdgeToEdge,
string Server)
string Server,
// Takes the place of the engine panel with this title while hosted ("takeOver": true).
bool TakeOver = false)
{
/// <summary>For every world, not one server.</summary>
public bool IsUniversal => Server.Length == 0;
@ -210,7 +216,8 @@ internal static class SectionManifestParser
float minWidth = Math.Min(WindowSize(Size(e, "minWidth"), MinWindowSize), width);
float minHeight = Math.Min(WindowSize(Size(e, "minHeight"), MinWindowSize), height);
windows.Add(new SectionWindowDecl(plugin, id, title, surface, Icon(Str(e, "icon")),
width, height, minWidth, minHeight, Bool(e, "bar", false), Bool(e, "edgeToEdge", false), server));
width, height, minWidth, minHeight, Bool(e, "bar", false), Bool(e, "edgeToEdge", false), server,
Bool(e, "takeOver", false)));
}
return new SectionManifest(plugin, servers.ToArray(), sections.ToArray(), contributions.ToArray())

View file

@ -9,29 +9,49 @@ using System.Collections.Generic;
namespace RynthCore.Engine.UI.Sections;
/// <summary>What already uses a window's title (its panel key).</summary>
internal enum TitleUse
{
/// <summary>Nothing, or this window's own panel (hosted already).</summary>
Free,
/// <summary>An engine panel: a window that declares "takeOver" draws in its place; any other is refused.</summary>
EnginePanel,
/// <summary>Another panel that isn't the engine's (a script window): refused.</summary>
Other,
}
/// <summary>Which plugin windows to host, from the manifests and the servers. Pure.</summary>
internal static class WindowPlan
{
/// <summary>
/// The windows to host, keyed by title, and the ones left out with the reason. A server
/// window counts only while its server is active; the first plugin to claim a title keeps it;
/// <paramref name="isEnginePanel"/> titles are refused.
/// window counts only while its server is active; the first plugin to claim a title keeps it.
/// A title an engine panel has (<paramref name="titleUse"/>) is hosted only when the window
/// declares "takeOver": it then goes in <paramref name="takeOvers"/>, and the engine's face
/// for that title steps aside while the window is hosted. Other used titles are refused.
/// </summary>
public static Dictionary<string, SectionWindowDecl> Build(IReadOnlyList<SectionManifest> manifests,
IReadOnlyList<ServerState> servers, Func<string, bool> isEnginePanel, List<string> refused)
IReadOnlyList<ServerState> servers, Func<string, TitleUse> titleUse, List<string> refused, ISet<string> takeOvers)
{
var want = new Dictionary<string, SectionWindowDecl>(StringComparer.OrdinalIgnoreCase);
foreach (SectionManifest m in manifests)
foreach (SectionWindowDecl w in m.Windows)
{
if (!w.IsUniversal && !ServerActive(servers, w.Server)) continue;
if (isEnginePanel(w.Title)) { refused.Add($"{w.Plugin}'s window '{w.Title}': an engine panel has that title"); continue; }
TitleUse use = titleUse(w.Title);
if (use == TitleUse.Other) { refused.Add($"{w.Plugin}'s window '{w.Title}': another panel has that title"); continue; }
if (use == TitleUse.EnginePanel && !w.TakeOver)
{
refused.Add($"{w.Plugin}'s window '{w.Title}': an engine panel has that title (\"takeOver\": true takes its place)");
continue;
}
if (want.TryGetValue(w.Title, out SectionWindowDecl? first))
{
refused.Add($"{w.Plugin}'s window '{w.Title}': {first.Plugin} has a window with that title");
continue;
}
want[w.Title] = w;
if (use == TitleUse.EnginePanel) takeOvers.Add(w.Title);
}
return want;
}
@ -45,5 +65,5 @@ internal static class WindowPlan
/// <summary>What a hosted window's panel depends on: a change re-registers it.</summary>
public static string Signature(SectionWindowDecl w) =>
string.Join("|", w.Plugin, w.Surface, w.Icon, w.Width, w.Height, w.MinWidth, w.MinHeight, w.Bar, w.EdgeToEdge);
string.Join("|", w.Plugin, w.Surface, w.Icon, w.Width, w.Height, w.MinWidth, w.MinHeight, w.Bar, w.EdgeToEdge, w.TakeOver);
}